btrfs-progs: btrfs_list_find_updated_files: Fix memory leak.
[platform/upstream/btrfs-progs.git] / btrfs-list.c
1 /*
2  * Copyright (C) 2010 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #define _GNU_SOURCE
20 #include <sys/ioctl.h>
21 #include <sys/mount.h>
22 #include "ioctl.h"
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <dirent.h>
30 #include <libgen.h>
31 #include "ctree.h"
32 #include "transaction.h"
33 #include "utils.h"
34 #include <uuid/uuid.h>
35 #include "btrfs-list.h"
36
37 #define BTRFS_LIST_NFILTERS_INCREASE    (2 * BTRFS_LIST_FILTER_MAX)
38 #define BTRFS_LIST_NCOMPS_INCREASE      (2 * BTRFS_LIST_COMP_MAX)
39
40 /* we store all the roots we find in an rbtree so that we can
41  * search for them later.
42  */
43 struct root_lookup {
44         struct rb_root root;
45 };
46
47 static struct {
48         char    *name;
49         char    *column_name;
50         int     need_print;
51 } btrfs_list_columns[] = {
52         {
53                 .name           = "ID",
54                 .column_name    = "ID",
55                 .need_print     = 0,
56         },
57         {
58                 .name           = "gen",
59                 .column_name    = "Gen",
60                 .need_print     = 0,
61         },
62         {
63                 .name           = "cgen",
64                 .column_name    = "CGen",
65                 .need_print     = 0,
66         },
67         {
68                 .name           = "parent",
69                 .column_name    = "Parent",
70                 .need_print     = 0,
71         },
72         {
73                 .name           = "top level",
74                 .column_name    = "Top Level",
75                 .need_print     = 0,
76         },
77         {
78                 .name           = "otime",
79                 .column_name    = "OTime",
80                 .need_print     = 0,
81         },
82         {
83                 .name           = "parent_uuid",
84                 .column_name    = "Parent UUID",
85                 .need_print     = 0,
86         },
87         {
88                 .name           = "uuid",
89                 .column_name    = "UUID",
90                 .need_print     = 0,
91         },
92         {
93                 .name           = "path",
94                 .column_name    = "Path",
95                 .need_print     = 0,
96         },
97         {
98                 .name           = NULL,
99                 .column_name    = NULL,
100                 .need_print     = 0,
101         },
102 };
103
104 static btrfs_list_filter_func all_filter_funcs[];
105 static btrfs_list_comp_func all_comp_funcs[];
106
107 void btrfs_list_setup_print_column(enum btrfs_list_column_enum column)
108 {
109         int i;
110
111         BUG_ON(column < 0 || column > BTRFS_LIST_ALL);
112
113         if (column < BTRFS_LIST_ALL) {
114                 btrfs_list_columns[column].need_print = 1;
115                 return;
116         }
117
118         for (i = 0; i < BTRFS_LIST_ALL; i++)
119                 btrfs_list_columns[i].need_print = 1;
120 }
121
122 static void root_lookup_init(struct root_lookup *tree)
123 {
124         tree->root.rb_node = NULL;
125 }
126
127 static int comp_entry_with_rootid(struct root_info *entry1,
128                                   struct root_info *entry2,
129                                   int is_descending)
130 {
131         int ret;
132
133         if (entry1->root_id > entry2->root_id)
134                 ret = 1;
135         else if (entry1->root_id < entry2->root_id)
136                 ret = -1;
137         else
138                 ret = 0;
139
140         return is_descending ? -ret : ret;
141 }
142
143 static int comp_entry_with_gen(struct root_info *entry1,
144                                struct root_info *entry2,
145                                int is_descending)
146 {
147         int ret;
148
149         if (entry1->gen > entry2->gen)
150                 ret = 1;
151         else if (entry1->gen < entry2->gen)
152                 ret = -1;
153         else
154                 ret = 0;
155
156         return is_descending ? -ret : ret;
157 }
158
159 static int comp_entry_with_ogen(struct root_info *entry1,
160                                 struct root_info *entry2,
161                                 int is_descending)
162 {
163         int ret;
164
165         if (entry1->ogen > entry2->ogen)
166                 ret = 1;
167         else if (entry1->ogen < entry2->ogen)
168                 ret = -1;
169         else
170                 ret = 0;
171
172         return is_descending ? -ret : ret;
173 }
174
175 static int comp_entry_with_path(struct root_info *entry1,
176                                 struct root_info *entry2,
177                                 int is_descending)
178 {
179         int ret;
180
181         if (strcmp(entry1->full_path, entry2->full_path) > 0)
182                 ret = 1;
183         else if (strcmp(entry1->full_path, entry2->full_path) < 0)
184                 ret = -1;
185         else
186                 ret = 0;
187
188         return is_descending ? -ret : ret;
189 }
190
191 static btrfs_list_comp_func all_comp_funcs[] = {
192         [BTRFS_LIST_COMP_ROOTID]        = comp_entry_with_rootid,
193         [BTRFS_LIST_COMP_OGEN]          = comp_entry_with_ogen,
194         [BTRFS_LIST_COMP_GEN]           = comp_entry_with_gen,
195         [BTRFS_LIST_COMP_PATH]          = comp_entry_with_path,
196 };
197
198 static char *all_sort_items[] = {
199         [BTRFS_LIST_COMP_ROOTID]        = "rootid",
200         [BTRFS_LIST_COMP_OGEN]          = "ogen",
201         [BTRFS_LIST_COMP_GEN]           = "gen",
202         [BTRFS_LIST_COMP_PATH]          = "path",
203         [BTRFS_LIST_COMP_MAX]           = NULL,
204 };
205
206 static int  btrfs_list_get_sort_item(char *sort_name)
207 {
208         int i;
209
210         for (i = 0; i < BTRFS_LIST_COMP_MAX; i++) {
211                 if (strcmp(sort_name, all_sort_items[i]) == 0)
212                         return i;
213         }
214         return -1;
215 }
216
217 struct btrfs_list_comparer_set *btrfs_list_alloc_comparer_set(void)
218 {
219         struct btrfs_list_comparer_set *set;
220         int size;
221
222         size = sizeof(struct btrfs_list_comparer_set) +
223                BTRFS_LIST_NCOMPS_INCREASE * sizeof(struct btrfs_list_comparer);
224         set = malloc(size);
225         if (!set) {
226                 fprintf(stderr, "memory allocation failed\n");
227                 exit(1);
228         }
229
230         memset(set, 0, size);
231         set->total = BTRFS_LIST_NCOMPS_INCREASE;
232
233         return set;
234 }
235
236 void btrfs_list_free_comparer_set(struct btrfs_list_comparer_set *comp_set)
237 {
238         free(comp_set);
239 }
240
241 static int btrfs_list_setup_comparer(struct btrfs_list_comparer_set **comp_set,
242                 enum btrfs_list_comp_enum comparer, int is_descending)
243 {
244         struct btrfs_list_comparer_set *set = *comp_set;
245         int size;
246
247         BUG_ON(!set);
248         BUG_ON(comparer >= BTRFS_LIST_COMP_MAX);
249         BUG_ON(set->ncomps > set->total);
250
251         if (set->ncomps == set->total) {
252                 size = set->total + BTRFS_LIST_NCOMPS_INCREASE;
253                 size = sizeof(*set) + size * sizeof(struct btrfs_list_comparer);
254                 set = realloc(set, size);
255                 if (!set) {
256                         fprintf(stderr, "memory allocation failed\n");
257                         exit(1);
258                 }
259
260                 memset(&set->comps[set->total], 0,
261                        BTRFS_LIST_NCOMPS_INCREASE *
262                        sizeof(struct btrfs_list_comparer));
263                 set->total += BTRFS_LIST_NCOMPS_INCREASE;
264                 *comp_set = set;
265         }
266
267         BUG_ON(set->comps[set->ncomps].comp_func);
268
269         set->comps[set->ncomps].comp_func = all_comp_funcs[comparer];
270         set->comps[set->ncomps].is_descending = is_descending;
271         set->ncomps++;
272         return 0;
273 }
274
275 static int sort_comp(struct root_info *entry1, struct root_info *entry2,
276                      struct btrfs_list_comparer_set *set)
277 {
278         int rootid_compared = 0;
279         int i, ret = 0;
280
281         if (!set || !set->ncomps)
282                 goto comp_rootid;
283
284         for (i = 0; i < set->ncomps; i++) {
285                 if (!set->comps[i].comp_func)
286                         break;
287
288                 ret = set->comps[i].comp_func(entry1, entry2,
289                                               set->comps[i].is_descending);
290                 if (ret)
291                         return ret;
292
293                 if (set->comps[i].comp_func == comp_entry_with_rootid)
294                         rootid_compared = 1;
295         }
296
297         if (!rootid_compared) {
298 comp_rootid:
299                 ret = comp_entry_with_rootid(entry1, entry2, 0);
300         }
301
302         return ret;
303 }
304
305 static int sort_tree_insert(struct root_lookup *sort_tree,
306                             struct root_info *ins,
307                             struct btrfs_list_comparer_set *comp_set)
308 {
309         struct rb_node **p = &sort_tree->root.rb_node;
310         struct rb_node *parent = NULL;
311         struct root_info *curr;
312         int ret;
313
314         while (*p) {
315                 parent = *p;
316                 curr = rb_entry(parent, struct root_info, sort_node);
317
318                 ret = sort_comp(ins, curr, comp_set);
319                 if (ret < 0)
320                         p = &(*p)->rb_left;
321                 else if (ret > 0)
322                         p = &(*p)->rb_right;
323                 else
324                         return -EEXIST;
325         }
326
327         rb_link_node(&ins->sort_node, parent, p);
328         rb_insert_color(&ins->sort_node, &sort_tree->root);
329         return 0;
330 }
331
332 /*
333  * insert a new root into the tree.  returns the existing root entry
334  * if one is already there.  Both root_id and ref_tree are used
335  * as the key
336  */
337 static int root_tree_insert(struct root_lookup *root_tree,
338                             struct root_info *ins)
339 {
340         struct rb_node **p = &root_tree->root.rb_node;
341         struct rb_node * parent = NULL;
342         struct root_info *curr;
343         int ret;
344
345         while(*p) {
346                 parent = *p;
347                 curr = rb_entry(parent, struct root_info, rb_node);
348
349                 ret = comp_entry_with_rootid(ins, curr, 0);
350                 if (ret < 0)
351                         p = &(*p)->rb_left;
352                 else if (ret > 0)
353                         p = &(*p)->rb_right;
354                 else
355                         return -EEXIST;
356         }
357
358         rb_link_node(&ins->rb_node, parent, p);
359         rb_insert_color(&ins->rb_node, &root_tree->root);
360         return 0;
361 }
362
363 /*
364  * find a given root id in the tree.  We return the smallest one,
365  * rb_next can be used to move forward looking for more if required
366  */
367 static struct root_info *root_tree_search(struct root_lookup *root_tree,
368                                           u64 root_id)
369 {
370         struct rb_node *n = root_tree->root.rb_node;
371         struct root_info *entry;
372         struct root_info tmp;
373         int ret;
374
375         tmp.root_id = root_id;
376
377         while(n) {
378                 entry = rb_entry(n, struct root_info, rb_node);
379
380                 ret = comp_entry_with_rootid(&tmp, entry, 0);
381                 if (ret < 0)
382                         n = n->rb_left;
383                 else if (ret > 0)
384                         n = n->rb_right;
385                 else
386                         return entry;
387         }
388         return NULL;
389 }
390
391 static int update_root(struct root_lookup *root_lookup,
392                        u64 root_id, u64 ref_tree, u64 root_offset, u64 flags,
393                        u64 dir_id, char *name, int name_len, u64 ogen, u64 gen,
394                        time_t ot, void *uuid, void *puuid)
395 {
396         struct root_info *ri;
397
398         ri = root_tree_search(root_lookup, root_id);
399         if (!ri || ri->root_id != root_id)
400                 return -ENOENT;
401         if (name && name_len > 0) {
402                 if (ri->name)
403                         free(ri->name);
404
405                 ri->name = malloc(name_len + 1);
406                 if (!ri->name) {
407                         fprintf(stderr, "memory allocation failed\n");
408                         exit(1);
409                 }
410                 strncpy(ri->name, name, name_len);
411                 ri->name[name_len] = 0;
412         }
413         if (ref_tree)
414                 ri->ref_tree = ref_tree;
415         if (root_offset)
416                 ri->root_offset = root_offset;
417         if (flags)
418                 ri->flags = flags;
419         if (dir_id)
420                 ri->dir_id = dir_id;
421         if (gen)
422                 ri->gen = gen;
423         if (ogen)
424                 ri->ogen = ogen;
425         if (!ri->ogen && root_offset)
426                 ri->ogen = root_offset;
427         if (ot)
428                 ri->otime = ot;
429         if (uuid)
430                 memcpy(&ri->uuid, uuid, BTRFS_UUID_SIZE);
431         if (puuid)
432                 memcpy(&ri->puuid, puuid, BTRFS_UUID_SIZE);
433
434         return 0;
435 }
436
437 /*
438  * add_root - update the existed root, or allocate a new root and insert it
439  *            into the lookup tree.
440  * root_id: object id of the root
441  * ref_tree: object id of the referring root.
442  * root_offset: offset value of the root'key
443  * dir_id: inode id of the directory in ref_tree where this root can be found.
444  * name: the name of root_id in that directory
445  * name_len: the length of name
446  * ogen: the original generation of the root
447  * gen: the current generation of the root
448  * ot: the original time(create time) of the root
449  * uuid: uuid of the root
450  * puuid: uuid of the root parent if any
451  */
452 static int add_root(struct root_lookup *root_lookup,
453                     u64 root_id, u64 ref_tree, u64 root_offset, u64 flags,
454                     u64 dir_id, char *name, int name_len, u64 ogen, u64 gen,
455                     time_t ot, void *uuid, void *puuid)
456 {
457         struct root_info *ri;
458         int ret;
459
460         ret = update_root(root_lookup, root_id, ref_tree, root_offset, flags,
461                           dir_id, name, name_len, ogen, gen, ot, uuid, puuid);
462         if (!ret)
463                 return 0;
464
465         ri = malloc(sizeof(*ri));
466         if (!ri) {
467                 printf("memory allocation failed\n");
468                 exit(1);
469         }
470         memset(ri, 0, sizeof(*ri));
471         ri->root_id = root_id;
472
473         if (name && name_len > 0) {
474                 ri->name = malloc(name_len + 1);
475                 if (!ri->name) {
476                         fprintf(stderr, "memory allocation failed\n");
477                         exit(1);
478                 }
479                 strncpy(ri->name, name, name_len);
480                 ri->name[name_len] = 0;
481         }
482         if (ref_tree)
483                 ri->ref_tree = ref_tree;
484         if (dir_id)
485                 ri->dir_id = dir_id;
486         if (root_offset)
487                 ri->root_offset = root_offset;
488         if (flags)
489                 ri->flags = flags;
490         if (gen)
491                 ri->gen = gen;
492         if (ogen)
493                 ri->ogen = ogen;
494         if (!ri->ogen && root_offset)
495                 ri->ogen = root_offset;
496         if (ot)
497                 ri->otime = ot;
498
499         if (uuid)
500                 memcpy(&ri->uuid, uuid, BTRFS_UUID_SIZE);
501
502         if (puuid)
503                 memcpy(&ri->puuid, puuid, BTRFS_UUID_SIZE);
504
505         ret = root_tree_insert(root_lookup, ri);
506         if (ret) {
507                 printf("failed to insert tree %llu\n", (unsigned long long)root_id);
508                 exit(1);
509         }
510         return 0;
511 }
512
513 static void __free_root_info(struct rb_node *node)
514 {
515         struct root_info *ri;
516
517         ri = rb_entry(node, struct root_info, rb_node);
518         if (ri->name)
519                 free(ri->name);
520
521         if (ri->path)
522                 free(ri->path);
523
524         if (ri->full_path)
525                 free(ri->full_path);
526
527         free(ri);
528 }
529
530 static inline void __free_all_subvolumn(struct root_lookup *root_tree)
531 {
532         rb_free_nodes(&root_tree->root, __free_root_info);
533 }
534
535 /*
536  * for a given root_info, search through the root_lookup tree to construct
537  * the full path name to it.
538  *
539  * This can't be called until all the root_info->path fields are filled
540  * in by lookup_ino_path
541  */
542 static int resolve_root(struct root_lookup *rl, struct root_info *ri,
543                        u64 top_id)
544 {
545         char *full_path = NULL;
546         int len = 0;
547         struct root_info *found;
548
549         /*
550          * we go backwards from the root_info object and add pathnames
551          * from parent directories as we go.
552          */
553         found = ri;
554         while (1) {
555                 char *tmp;
556                 u64 next;
557                 int add_len;
558
559                 /*
560                  * ref_tree = 0 indicates the subvolumes
561                  * has been deleted.
562                  */
563                 if (!found->ref_tree) {
564                         free(full_path);
565                         return -ENOENT;
566                 }
567
568                 add_len = strlen(found->path);
569
570                 if (full_path) {
571                         /* room for / and for null */
572                         tmp = malloc(add_len + 2 + len);
573                         if (!tmp) {
574                                 perror("malloc failed");
575                                 exit(1);
576                         }
577                         memcpy(tmp + add_len + 1, full_path, len);
578                         tmp[add_len] = '/';
579                         memcpy(tmp, found->path, add_len);
580                         tmp [add_len + len + 1] = '\0';
581                         free(full_path);
582                         full_path = tmp;
583                         len += add_len + 1;
584                 } else {
585                         full_path = strdup(found->path);
586                         len = add_len;
587                 }
588
589                 next = found->ref_tree;
590
591                 if (next == top_id) {
592                         ri->top_id = top_id;
593                         break;
594                 }
595
596                 /*
597                 * if the ref_tree = BTRFS_FS_TREE_OBJECTID,
598                 * we are at the top
599                 */
600                 if (next == BTRFS_FS_TREE_OBJECTID) {
601                         ri->top_id = next;
602                         break;
603                 }
604
605                 /*
606                 * if the ref_tree wasn't in our tree of roots, the
607                 * subvolume was deleted.
608                 */
609                 found = root_tree_search(rl, next);
610                 if (!found) {
611                         free(full_path);
612                         return -ENOENT;
613                 }
614         }
615
616         ri->full_path = full_path;
617
618         return 0;
619 }
620
621 /*
622  * for a single root_info, ask the kernel to give us a path name
623  * inside it's ref_root for the dir_id where it lives.
624  *
625  * This fills in root_info->path with the path to the directory and and
626  * appends this root's name.
627  */
628 static int lookup_ino_path(int fd, struct root_info *ri)
629 {
630         struct btrfs_ioctl_ino_lookup_args args;
631         int ret, e;
632
633         if (ri->path)
634                 return 0;
635
636         if (!ri->ref_tree)
637                 return -ENOENT;
638
639         memset(&args, 0, sizeof(args));
640         args.treeid = ri->ref_tree;
641         args.objectid = ri->dir_id;
642
643         ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
644         e = errno;
645         if (ret) {
646                 if (e == ENOENT) {
647                         ri->ref_tree = 0;
648                         return -ENOENT;
649                 }
650                 fprintf(stderr, "ERROR: Failed to lookup path for root %llu - %s\n",
651                         (unsigned long long)ri->ref_tree,
652                         strerror(e));
653                 return ret;
654         }
655
656         if (args.name[0]) {
657                 /*
658                  * we're in a subdirectory of ref_tree, the kernel ioctl
659                  * puts a / in there for us
660                  */
661                 ri->path = malloc(strlen(ri->name) + strlen(args.name) + 1);
662                 if (!ri->path) {
663                         perror("malloc failed");
664                         exit(1);
665                 }
666                 strcpy(ri->path, args.name);
667                 strcat(ri->path, ri->name);
668         } else {
669                 /* we're at the root of ref_tree */
670                 ri->path = strdup(ri->name);
671                 if (!ri->path) {
672                         perror("strdup failed");
673                         exit(1);
674                 }
675         }
676         return 0;
677 }
678
679 /* finding the generation for a given path is a two step process.
680  * First we use the inode loookup routine to find out the root id
681  *
682  * Then we use the tree search ioctl to scan all the root items for a
683  * given root id and spit out the latest generation we can find
684  */
685 static u64 find_root_gen(int fd)
686 {
687         struct btrfs_ioctl_ino_lookup_args ino_args;
688         int ret;
689         struct btrfs_ioctl_search_args args;
690         struct btrfs_ioctl_search_key *sk = &args.key;
691         struct btrfs_ioctl_search_header sh;
692         unsigned long off = 0;
693         u64 max_found = 0;
694         int i;
695         int e;
696
697         memset(&ino_args, 0, sizeof(ino_args));
698         ino_args.objectid = BTRFS_FIRST_FREE_OBJECTID;
699
700         /* this ioctl fills in ino_args->treeid */
701         ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &ino_args);
702         e = errno;
703         if (ret) {
704                 fprintf(stderr, "ERROR: Failed to lookup path for dirid %llu - %s\n",
705                         (unsigned long long)BTRFS_FIRST_FREE_OBJECTID,
706                         strerror(e));
707                 return 0;
708         }
709
710         memset(&args, 0, sizeof(args));
711
712         sk->tree_id = 1;
713
714         /*
715          * there may be more than one ROOT_ITEM key if there are
716          * snapshots pending deletion, we have to loop through
717          * them.
718          */
719         sk->min_objectid = ino_args.treeid;
720         sk->max_objectid = ino_args.treeid;
721         sk->max_type = BTRFS_ROOT_ITEM_KEY;
722         sk->min_type = BTRFS_ROOT_ITEM_KEY;
723         sk->max_offset = (u64)-1;
724         sk->max_transid = (u64)-1;
725         sk->nr_items = 4096;
726
727         while (1) {
728                 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args);
729                 e = errno;
730                 if (ret < 0) {
731                         fprintf(stderr, "ERROR: can't perform the search - %s\n",
732                                 strerror(e));
733                         return 0;
734                 }
735                 /* the ioctl returns the number of item it found in nr_items */
736                 if (sk->nr_items == 0)
737                         break;
738
739                 off = 0;
740                 for (i = 0; i < sk->nr_items; i++) {
741                         struct btrfs_root_item *item;
742
743                         memcpy(&sh, args.buf + off, sizeof(sh));
744                         off += sizeof(sh);
745                         item = (struct btrfs_root_item *)(args.buf + off);
746                         off += sh.len;
747
748                         sk->min_objectid = sh.objectid;
749                         sk->min_type = sh.type;
750                         sk->min_offset = sh.offset;
751
752                         if (sh.objectid > ino_args.treeid)
753                                 break;
754
755                         if (sh.objectid == ino_args.treeid &&
756                             sh.type == BTRFS_ROOT_ITEM_KEY) {
757                                 max_found = max(max_found,
758                                                 btrfs_root_generation(item));
759                         }
760                 }
761                 if (sk->min_offset < (u64)-1)
762                         sk->min_offset++;
763                 else
764                         break;
765
766                 if (sk->min_type != BTRFS_ROOT_ITEM_KEY)
767                         break;
768                 if (sk->min_objectid != ino_args.treeid)
769                         break;
770         }
771         return max_found;
772 }
773
774 /* pass in a directory id and this will return
775  * the full path of the parent directory inside its
776  * subvolume root.
777  *
778  * It may return NULL if it is in the root, or an ERR_PTR if things
779  * go badly.
780  */
781 static char *__ino_resolve(int fd, u64 dirid)
782 {
783         struct btrfs_ioctl_ino_lookup_args args;
784         int ret;
785         char *full;
786         int e;
787
788         memset(&args, 0, sizeof(args));
789         args.objectid = dirid;
790
791         ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
792         e = errno;
793         if (ret) {
794                 fprintf(stderr, "ERROR: Failed to lookup path for dirid %llu - %s\n",
795                         (unsigned long long)dirid, strerror(e) );
796                 return ERR_PTR(ret);
797         }
798
799         if (args.name[0]) {
800                 /*
801                  * we're in a subdirectory of ref_tree, the kernel ioctl
802                  * puts a / in there for us
803                  */
804                 full = strdup(args.name);
805                 if (!full) {
806                         perror("malloc failed");
807                         return ERR_PTR(-ENOMEM);
808                 }
809         } else {
810                 /* we're at the root of ref_tree */
811                 full = NULL;
812         }
813         return full;
814 }
815
816 /*
817  * simple string builder, returning a new string with both
818  * dirid and name
819  */
820 static char *build_name(char *dirid, char *name)
821 {
822         char *full;
823         if (!dirid)
824                 return strdup(name);
825
826         full = malloc(strlen(dirid) + strlen(name) + 1);
827         if (!full)
828                 return NULL;
829         strcpy(full, dirid);
830         strcat(full, name);
831         return full;
832 }
833
834 /*
835  * given an inode number, this returns the full path name inside the subvolume
836  * to that file/directory.  cache_dirid and cache_name are used to
837  * cache the results so we can avoid tree searches if a later call goes
838  * to the same directory or file name
839  */
840 static char *ino_resolve(int fd, u64 ino, u64 *cache_dirid, char **cache_name)
841
842 {
843         u64 dirid;
844         char *dirname;
845         char *name;
846         char *full;
847         int ret;
848         struct btrfs_ioctl_search_args args;
849         struct btrfs_ioctl_search_key *sk = &args.key;
850         struct btrfs_ioctl_search_header *sh;
851         unsigned long off = 0;
852         int namelen;
853         int e;
854
855         memset(&args, 0, sizeof(args));
856
857         sk->tree_id = 0;
858
859         /*
860          * step one, we search for the inode back ref.  We just use the first
861          * one
862          */
863         sk->min_objectid = ino;
864         sk->max_objectid = ino;
865         sk->max_type = BTRFS_INODE_REF_KEY;
866         sk->max_offset = (u64)-1;
867         sk->min_type = BTRFS_INODE_REF_KEY;
868         sk->max_transid = (u64)-1;
869         sk->nr_items = 1;
870
871         ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args);
872         e = errno;
873         if (ret < 0) {
874                 fprintf(stderr, "ERROR: can't perform the search - %s\n",
875                         strerror(e));
876                 return NULL;
877         }
878         /* the ioctl returns the number of item it found in nr_items */
879         if (sk->nr_items == 0)
880                 return NULL;
881
882         off = 0;
883         sh = (struct btrfs_ioctl_search_header *)(args.buf + off);
884
885         if (sh->type == BTRFS_INODE_REF_KEY) {
886                 struct btrfs_inode_ref *ref;
887                 dirid = sh->offset;
888
889                 ref = (struct btrfs_inode_ref *)(sh + 1);
890                 namelen = btrfs_stack_inode_ref_name_len(ref);
891
892                 name = (char *)(ref + 1);
893                 name = strndup(name, namelen);
894
895                 /* use our cached value */
896                 if (dirid == *cache_dirid && *cache_name) {
897                         dirname = *cache_name;
898                         goto build;
899                 }
900         } else {
901                 return NULL;
902         }
903         /*
904          * the inode backref gives us the file name and the parent directory id.
905          * From here we use __ino_resolve to get the path to the parent
906          */
907         dirname = __ino_resolve(fd, dirid);
908 build:
909         full = build_name(dirname, name);
910         if (*cache_name && dirname != *cache_name)
911                 free(*cache_name);
912
913         *cache_name = dirname;
914         *cache_dirid = dirid;
915         free(name);
916
917         return full;
918 }
919
920 int btrfs_list_get_default_subvolume(int fd, u64 *default_id)
921 {
922         struct btrfs_ioctl_search_args args;
923         struct btrfs_ioctl_search_key *sk = &args.key;
924         struct btrfs_ioctl_search_header *sh;
925         u64 found = 0;
926         int ret;
927
928         memset(&args, 0, sizeof(args));
929
930         /*
931          * search for a dir item with a name 'default' in the tree of
932          * tree roots, it should point us to a default root
933          */
934         sk->tree_id = 1;
935
936         /* don't worry about ancient format and request only one item */
937         sk->nr_items = 1;
938
939         sk->max_objectid = BTRFS_ROOT_TREE_DIR_OBJECTID;
940         sk->min_objectid = BTRFS_ROOT_TREE_DIR_OBJECTID;
941         sk->max_type = BTRFS_DIR_ITEM_KEY;
942         sk->min_type = BTRFS_DIR_ITEM_KEY;
943         sk->max_offset = (u64)-1;
944         sk->max_transid = (u64)-1;
945
946         ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args);
947         if (ret < 0)
948                 return ret;
949
950         /* the ioctl returns the number of items it found in nr_items */
951         if (sk->nr_items == 0)
952                 goto out;
953
954         sh = (struct btrfs_ioctl_search_header *)args.buf;
955
956         if (sh->type == BTRFS_DIR_ITEM_KEY) {
957                 struct btrfs_dir_item *di;
958                 int name_len;
959                 char *name;
960
961                 di = (struct btrfs_dir_item *)(sh + 1);
962                 name_len = btrfs_stack_dir_name_len(di);
963                 name = (char *)(di + 1);
964
965                 if (!strncmp("default", name, name_len))
966                         found = btrfs_disk_key_objectid(&di->location);
967         }
968
969 out:
970         *default_id = found;
971         return 0;
972 }
973
974 static int __list_subvol_search(int fd, struct root_lookup *root_lookup)
975 {
976         int ret;
977         struct btrfs_ioctl_search_args args;
978         struct btrfs_ioctl_search_key *sk = &args.key;
979         struct btrfs_ioctl_search_header sh;
980         struct btrfs_root_ref *ref;
981         struct btrfs_root_item *ri;
982         unsigned long off = 0;
983         int name_len;
984         char *name;
985         u64 dir_id;
986         u64 gen = 0;
987         u64 ogen;
988         u64 flags;
989         int i;
990         time_t t;
991         u8 uuid[BTRFS_UUID_SIZE];
992         u8 puuid[BTRFS_UUID_SIZE];
993
994         root_lookup_init(root_lookup);
995         memset(&args, 0, sizeof(args));
996
997         /* search in the tree of tree roots */
998         sk->tree_id = 1;
999
1000         /*
1001          * set the min and max to backref keys.  The search will
1002          * only send back this type of key now.
1003          */
1004         sk->max_type = BTRFS_ROOT_BACKREF_KEY;
1005         sk->min_type = BTRFS_ROOT_ITEM_KEY;
1006
1007         sk->min_objectid = BTRFS_FIRST_FREE_OBJECTID;
1008
1009         /*
1010          * set all the other params to the max, we'll take any objectid
1011          * and any trans
1012          */
1013         sk->max_objectid = BTRFS_LAST_FREE_OBJECTID;
1014         sk->max_offset = (u64)-1;
1015         sk->max_transid = (u64)-1;
1016
1017         /* just a big number, doesn't matter much */
1018         sk->nr_items = 4096;
1019
1020         while(1) {
1021                 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args);
1022                 if (ret < 0)
1023                         return ret;
1024                 /* the ioctl returns the number of item it found in nr_items */
1025                 if (sk->nr_items == 0)
1026                         break;
1027
1028                 off = 0;
1029
1030                 /*
1031                  * for each item, pull the key out of the header and then
1032                  * read the root_ref item it contains
1033                  */
1034                 for (i = 0; i < sk->nr_items; i++) {
1035                         memcpy(&sh, args.buf + off, sizeof(sh));
1036                         off += sizeof(sh);
1037                         if (sh.type == BTRFS_ROOT_BACKREF_KEY) {
1038                                 ref = (struct btrfs_root_ref *)(args.buf + off);
1039                                 name_len = btrfs_stack_root_ref_name_len(ref);
1040                                 name = (char *)(ref + 1);
1041                                 dir_id = btrfs_stack_root_ref_dirid(ref);
1042
1043                                 add_root(root_lookup, sh.objectid, sh.offset,
1044                                          0, 0, dir_id, name, name_len, 0, 0, 0,
1045                                          NULL, NULL);
1046                         } else if (sh.type == BTRFS_ROOT_ITEM_KEY) {
1047                                 ri = (struct btrfs_root_item *)(args.buf + off);
1048                                 gen = btrfs_root_generation(ri);
1049                                 flags = btrfs_root_flags(ri);
1050                                 if(sh.len >
1051                                    sizeof(struct btrfs_root_item_v0)) {
1052                                         t = btrfs_stack_timespec_sec(&ri->otime);
1053                                         ogen = btrfs_root_otransid(ri);
1054                                         memcpy(uuid, ri->uuid, BTRFS_UUID_SIZE);
1055                                         memcpy(puuid, ri->parent_uuid, BTRFS_UUID_SIZE);
1056                                 } else {
1057                                         t = 0;
1058                                         ogen = 0;
1059                                         memset(uuid, 0, BTRFS_UUID_SIZE);
1060                                         memset(puuid, 0, BTRFS_UUID_SIZE);
1061                                 }
1062
1063                                 add_root(root_lookup, sh.objectid, 0,
1064                                          sh.offset, flags, 0, NULL, 0, ogen,
1065                                          gen, t, uuid, puuid);
1066                         }
1067
1068                         off += sh.len;
1069
1070                         /*
1071                          * record the mins in sk so we can make sure the
1072                          * next search doesn't repeat this root
1073                          */
1074                         sk->min_objectid = sh.objectid;
1075                         sk->min_type = sh.type;
1076                         sk->min_offset = sh.offset;
1077                 }
1078                 sk->nr_items = 4096;
1079                 sk->min_offset++;
1080                 if (!sk->min_offset)    /* overflow */
1081                         sk->min_type++;
1082                 else
1083                         continue;
1084
1085                 if (sk->min_type > BTRFS_ROOT_BACKREF_KEY) {
1086                         sk->min_type = BTRFS_ROOT_ITEM_KEY;
1087                         sk->min_objectid++;
1088                 } else
1089                         continue;
1090
1091                 if (sk->min_objectid > sk->max_objectid)
1092                         break;
1093         }
1094
1095         return 0;
1096 }
1097
1098 static int filter_by_rootid(struct root_info *ri, u64 data)
1099 {
1100         return ri->root_id == data;
1101 }
1102
1103 static int filter_snapshot(struct root_info *ri, u64 data)
1104 {
1105         return !!ri->root_offset;
1106 }
1107
1108 static int filter_flags(struct root_info *ri, u64 flags)
1109 {
1110         return ri->flags & flags;
1111 }
1112
1113 static int filter_gen_more(struct root_info *ri, u64 data)
1114 {
1115         return ri->gen >= data;
1116 }
1117
1118 static int filter_gen_less(struct root_info *ri, u64 data)
1119 {
1120         return ri->gen <= data;
1121 }
1122
1123 static int filter_gen_equal(struct root_info  *ri, u64 data)
1124 {
1125         return ri->gen == data;
1126 }
1127
1128 static int filter_cgen_more(struct root_info *ri, u64 data)
1129 {
1130         return ri->ogen >= data;
1131 }
1132
1133 static int filter_cgen_less(struct root_info *ri, u64 data)
1134 {
1135         return ri->ogen <= data;
1136 }
1137
1138 static int filter_cgen_equal(struct root_info *ri, u64 data)
1139 {
1140         return ri->ogen == data;
1141 }
1142
1143 static int filter_topid_equal(struct root_info *ri, u64 data)
1144 {
1145         return ri->top_id == data;
1146 }
1147
1148 static int filter_full_path(struct root_info *ri, u64 data)
1149 {
1150         if (ri->full_path && ri->top_id != data) {
1151                 char *tmp;
1152                 char p[] = "<FS_TREE>";
1153                 int add_len = strlen(p);
1154                 int len = strlen(ri->full_path);
1155
1156                 tmp = malloc(len + add_len + 2);
1157                 if (!tmp) {
1158                         fprintf(stderr, "memory allocation failed\n");
1159                         exit(1);
1160                 }
1161                 memcpy(tmp + add_len + 1, ri->full_path, len);
1162                 tmp[len + add_len + 1] = '\0';
1163                 tmp[add_len] = '/';
1164                 memcpy(tmp, p, add_len);
1165                 free(ri->full_path);
1166                 ri->full_path = tmp;
1167         }
1168         return 1;
1169 }
1170
1171 static int filter_by_parent(struct root_info *ri, u64 data)
1172 {
1173         return !uuid_compare(ri->puuid, (u8 *)(unsigned long)data);
1174 }
1175
1176 static btrfs_list_filter_func all_filter_funcs[] = {
1177         [BTRFS_LIST_FILTER_ROOTID]              = filter_by_rootid,
1178         [BTRFS_LIST_FILTER_SNAPSHOT_ONLY]       = filter_snapshot,
1179         [BTRFS_LIST_FILTER_FLAGS]               = filter_flags,
1180         [BTRFS_LIST_FILTER_GEN_MORE]            = filter_gen_more,
1181         [BTRFS_LIST_FILTER_GEN_LESS]            = filter_gen_less,
1182         [BTRFS_LIST_FILTER_GEN_EQUAL]           = filter_gen_equal,
1183         [BTRFS_LIST_FILTER_CGEN_MORE]           = filter_cgen_more,
1184         [BTRFS_LIST_FILTER_CGEN_LESS]           = filter_cgen_less,
1185         [BTRFS_LIST_FILTER_CGEN_EQUAL]          = filter_cgen_equal,
1186         [BTRFS_LIST_FILTER_TOPID_EQUAL]         = filter_topid_equal,
1187         [BTRFS_LIST_FILTER_FULL_PATH]           = filter_full_path,
1188         [BTRFS_LIST_FILTER_BY_PARENT]           = filter_by_parent,
1189 };
1190
1191 struct btrfs_list_filter_set *btrfs_list_alloc_filter_set(void)
1192 {
1193         struct btrfs_list_filter_set *set;
1194         int size;
1195
1196         size = sizeof(struct btrfs_list_filter_set) +
1197                BTRFS_LIST_NFILTERS_INCREASE * sizeof(struct btrfs_list_filter);
1198         set = malloc(size);
1199         if (!set) {
1200                 fprintf(stderr, "memory allocation failed\n");
1201                 exit(1);
1202         }
1203
1204         memset(set, 0, size);
1205         set->total = BTRFS_LIST_NFILTERS_INCREASE;
1206
1207         return set;
1208 }
1209
1210 void btrfs_list_free_filter_set(struct btrfs_list_filter_set *filter_set)
1211 {
1212         free(filter_set);
1213 }
1214
1215 int btrfs_list_setup_filter(struct btrfs_list_filter_set **filter_set,
1216                             enum btrfs_list_filter_enum filter, u64 data)
1217 {
1218         struct btrfs_list_filter_set *set = *filter_set;
1219         int size;
1220
1221         BUG_ON(!set);
1222         BUG_ON(filter >= BTRFS_LIST_FILTER_MAX);
1223         BUG_ON(set->nfilters > set->total);
1224
1225         if (set->nfilters == set->total) {
1226                 size = set->total + BTRFS_LIST_NFILTERS_INCREASE;
1227                 size = sizeof(*set) + size * sizeof(struct btrfs_list_filter);
1228                 set = realloc(set, size);
1229                 if (!set) {
1230                         fprintf(stderr, "memory allocation failed\n");
1231                         exit(1);
1232                 }
1233
1234                 memset(&set->filters[set->total], 0,
1235                        BTRFS_LIST_NFILTERS_INCREASE *
1236                        sizeof(struct btrfs_list_filter));
1237                 set->total += BTRFS_LIST_NFILTERS_INCREASE;
1238                 *filter_set = set;
1239         }
1240
1241         BUG_ON(set->filters[set->nfilters].filter_func);
1242
1243         set->filters[set->nfilters].filter_func = all_filter_funcs[filter];
1244         set->filters[set->nfilters].data = data;
1245         set->nfilters++;
1246         return 0;
1247 }
1248
1249 static int filter_root(struct root_info *ri,
1250                        struct btrfs_list_filter_set *set)
1251 {
1252         int i, ret;
1253
1254         if (!set || !set->nfilters)
1255                 return 1;
1256
1257         for (i = 0; i < set->nfilters; i++) {
1258                 if (!set->filters[i].filter_func)
1259                         break;
1260                 ret = set->filters[i].filter_func(ri, set->filters[i].data);
1261                 if (!ret)
1262                         return 0;
1263         }
1264         return 1;
1265 }
1266
1267 static void __filter_and_sort_subvol(struct root_lookup *all_subvols,
1268                                     struct root_lookup *sort_tree,
1269                                     struct btrfs_list_filter_set *filter_set,
1270                                     struct btrfs_list_comparer_set *comp_set,
1271                                     u64 top_id)
1272 {
1273         struct rb_node *n;
1274         struct root_info *entry;
1275         int ret;
1276
1277         root_lookup_init(sort_tree);
1278
1279         n = rb_last(&all_subvols->root);
1280         while (n) {
1281                 entry = rb_entry(n, struct root_info, rb_node);
1282
1283                 ret = resolve_root(all_subvols, entry, top_id);
1284                 if (ret == -ENOENT)
1285                         goto skip;
1286                 ret = filter_root(entry, filter_set);
1287                 if (ret)
1288                         sort_tree_insert(sort_tree, entry, comp_set);
1289 skip:
1290                 n = rb_prev(n);
1291         }
1292 }
1293
1294 static int __list_subvol_fill_paths(int fd, struct root_lookup *root_lookup)
1295 {
1296         struct rb_node *n;
1297
1298         n = rb_first(&root_lookup->root);
1299         while (n) {
1300                 struct root_info *entry;
1301                 int ret;
1302                 entry = rb_entry(n, struct root_info, rb_node);
1303                 ret = lookup_ino_path(fd, entry);
1304                 if (ret && ret != -ENOENT)
1305                         return ret;
1306                 n = rb_next(n);
1307         }
1308
1309         return 0;
1310 }
1311
1312 static void print_subvolume_column(struct root_info *subv,
1313                                    enum btrfs_list_column_enum column)
1314 {
1315         char tstr[256];
1316         char uuidparse[37];
1317
1318         BUG_ON(column >= BTRFS_LIST_ALL || column < 0);
1319
1320         switch (column) {
1321         case BTRFS_LIST_OBJECTID:
1322                 printf("%llu", subv->root_id);
1323                 break;
1324         case BTRFS_LIST_GENERATION:
1325                 printf("%llu", subv->gen);
1326                 break;
1327         case BTRFS_LIST_OGENERATION:
1328                 printf("%llu", subv->ogen);
1329                 break;
1330         case BTRFS_LIST_PARENT:
1331                 printf("%llu", subv->ref_tree);
1332                 break;
1333         case BTRFS_LIST_TOP_LEVEL:
1334                 printf("%llu", subv->top_id);
1335                 break;
1336         case BTRFS_LIST_OTIME:
1337                 if (subv->otime) {
1338                         struct tm tm;
1339
1340                         localtime_r(&subv->otime, &tm);
1341                         strftime(tstr, 256, "%Y-%m-%d %X", &tm);
1342                 } else
1343                         strcpy(tstr, "-");
1344                 printf("%s", tstr);
1345                 break;
1346         case BTRFS_LIST_UUID:
1347                 if (uuid_is_null(subv->uuid))
1348                         strcpy(uuidparse, "-");
1349                 else
1350                         uuid_unparse(subv->uuid, uuidparse);
1351                 printf("%s", uuidparse);
1352                 break;
1353         case BTRFS_LIST_PUUID:
1354                 if (uuid_is_null(subv->puuid))
1355                         strcpy(uuidparse, "-");
1356                 else
1357                         uuid_unparse(subv->puuid, uuidparse);
1358                 printf("%s", uuidparse);
1359                 break;
1360         case BTRFS_LIST_PATH:
1361                 BUG_ON(!subv->full_path);
1362                 printf("%s", subv->full_path);
1363                 break;
1364         default:
1365                 break;
1366         }
1367 }
1368
1369 static void print_single_volume_info_raw(struct root_info *subv, char *raw_prefix)
1370 {
1371         int i;
1372
1373         for (i = 0; i < BTRFS_LIST_ALL; i++) {
1374                 if (!btrfs_list_columns[i].need_print)
1375                         continue;
1376
1377                 if (raw_prefix)
1378                         printf("%s",raw_prefix);
1379
1380                 print_subvolume_column(subv, i);
1381         }
1382         printf("\n");
1383 }
1384
1385 static void print_single_volume_info_table(struct root_info *subv)
1386 {
1387         int i;
1388
1389         for (i = 0; i < BTRFS_LIST_ALL; i++) {
1390                 if (!btrfs_list_columns[i].need_print)
1391                         continue;
1392
1393                 print_subvolume_column(subv, i);
1394
1395                 if (i != BTRFS_LIST_PATH)
1396                         printf("\t");
1397
1398                 if (i == BTRFS_LIST_TOP_LEVEL)
1399                         printf("\t");
1400         }
1401         printf("\n");
1402 }
1403
1404 static void print_single_volume_info_default(struct root_info *subv)
1405 {
1406         int i;
1407
1408         for (i = 0; i < BTRFS_LIST_ALL; i++) {
1409                 if (!btrfs_list_columns[i].need_print)
1410                         continue;
1411
1412                 printf("%s ", btrfs_list_columns[i].name);
1413                 print_subvolume_column(subv, i);
1414
1415                 if (i != BTRFS_LIST_PATH)
1416                         printf(" ");
1417         }
1418         printf("\n");
1419 }
1420
1421 static void print_all_volume_info_tab_head(void)
1422 {
1423         int i;
1424         int len;
1425         char barrier[20];
1426
1427         for (i = 0; i < BTRFS_LIST_ALL; i++) {
1428                 if (btrfs_list_columns[i].need_print)
1429                         printf("%s\t", btrfs_list_columns[i].name);
1430
1431                 if (i == BTRFS_LIST_ALL-1)
1432                         printf("\n");
1433         }
1434
1435         for (i = 0; i < BTRFS_LIST_ALL; i++) {
1436                 memset(barrier, 0, sizeof(barrier));
1437
1438                 if (btrfs_list_columns[i].need_print) {
1439                         len = strlen(btrfs_list_columns[i].name);
1440                         while (len--)
1441                                 strcat(barrier, "-");
1442
1443                         printf("%s\t", barrier);
1444                 }
1445                 if (i == BTRFS_LIST_ALL-1)
1446                         printf("\n");
1447         }
1448 }
1449
1450 static void print_all_volume_info(struct root_lookup *sorted_tree,
1451                                   int layout, char *raw_prefix)
1452 {
1453         struct rb_node *n;
1454         struct root_info *entry;
1455
1456         if (layout == BTRFS_LIST_LAYOUT_TABLE)
1457                 print_all_volume_info_tab_head();
1458
1459         n = rb_first(&sorted_tree->root);
1460         while (n) {
1461                 entry = rb_entry(n, struct root_info, sort_node);
1462                 switch (layout) {
1463                 case BTRFS_LIST_LAYOUT_DEFAULT:
1464                         print_single_volume_info_default(entry);
1465                         break;
1466                 case BTRFS_LIST_LAYOUT_TABLE:
1467                         print_single_volume_info_table(entry);
1468                         break;
1469                 case BTRFS_LIST_LAYOUT_RAW:
1470                         print_single_volume_info_raw(entry, raw_prefix);
1471                         break;
1472                 }
1473                 n = rb_next(n);
1474         }
1475 }
1476
1477 static int btrfs_list_subvols(int fd, struct root_lookup *root_lookup)
1478 {
1479         int ret;
1480
1481         ret = __list_subvol_search(fd, root_lookup);
1482         if (ret) {
1483                 fprintf(stderr, "ERROR: can't perform the search - %s\n",
1484                                 strerror(errno));
1485                 return ret;
1486         }
1487
1488         /*
1489          * now we have an rbtree full of root_info objects, but we need to fill
1490          * in their path names within the subvol that is referencing each one.
1491          */
1492         ret = __list_subvol_fill_paths(fd, root_lookup);
1493         return ret;
1494 }
1495
1496 int btrfs_list_subvols_print(int fd, struct btrfs_list_filter_set *filter_set,
1497                        struct btrfs_list_comparer_set *comp_set,
1498                        int layout, int full_path, char *raw_prefix)
1499 {
1500         struct root_lookup root_lookup;
1501         struct root_lookup root_sort;
1502         int ret = 0;
1503         u64 top_id = 0;
1504
1505         if (full_path)
1506                 ret = btrfs_list_get_path_rootid(fd, &top_id);
1507         if (ret)
1508                 return ret;
1509
1510         ret = btrfs_list_subvols(fd, &root_lookup);
1511         if (ret)
1512                 return ret;
1513         __filter_and_sort_subvol(&root_lookup, &root_sort, filter_set,
1514                                  comp_set, top_id);
1515
1516         print_all_volume_info(&root_sort, layout, raw_prefix);
1517         __free_all_subvolumn(&root_lookup);
1518
1519         return 0;
1520 }
1521
1522 static char *strdup_or_null(const char *s)
1523 {
1524         if (!s)
1525                 return NULL;
1526         return strdup(s);
1527 }
1528
1529 int btrfs_get_subvol(int fd, struct root_info *the_ri)
1530 {
1531         int ret, rr;
1532         struct root_lookup rl;
1533         struct rb_node *rbn;
1534         struct root_info *ri;
1535         u64 root_id;
1536
1537         ret = btrfs_list_get_path_rootid(fd, &root_id);
1538         if (ret)
1539                 return ret;
1540
1541         ret = btrfs_list_subvols(fd, &rl);
1542         if (ret)
1543                 return ret;
1544
1545         rbn = rb_first(&rl.root);
1546         while(rbn) {
1547                 ri = rb_entry(rbn, struct root_info, rb_node);
1548                 rr = resolve_root(&rl, ri, root_id);
1549                 if (rr == -ENOENT) {
1550                         ret = -ENOENT;
1551                         rbn = rb_next(rbn);
1552                         continue;
1553                 }
1554                 if (!comp_entry_with_rootid(the_ri, ri, 0)) {
1555                         memcpy(the_ri, ri, offsetof(struct root_info, path));
1556                         the_ri->path = strdup_or_null(ri->path);
1557                         the_ri->name = strdup_or_null(ri->name);
1558                         the_ri->full_path = strdup_or_null(ri->full_path);
1559                         ret = 0;
1560                         break;
1561                 }
1562                 rbn = rb_next(rbn);
1563         }
1564         __free_all_subvolumn(&rl);
1565         return ret;
1566 }
1567
1568 static int print_one_extent(int fd, struct btrfs_ioctl_search_header *sh,
1569                             struct btrfs_file_extent_item *item,
1570                             u64 found_gen, u64 *cache_dirid,
1571                             char **cache_dir_name, u64 *cache_ino,
1572                             char **cache_full_name)
1573 {
1574         u64 len = 0;
1575         u64 disk_start = 0;
1576         u64 disk_offset = 0;
1577         u8 type;
1578         int compressed = 0;
1579         int flags = 0;
1580         char *name = NULL;
1581
1582         if (sh->objectid == *cache_ino) {
1583                 name = *cache_full_name;
1584         } else if (*cache_full_name) {
1585                 free(*cache_full_name);
1586                 *cache_full_name = NULL;
1587         }
1588         if (!name) {
1589                 name = ino_resolve(fd, sh->objectid, cache_dirid,
1590                                    cache_dir_name);
1591                 *cache_full_name = name;
1592                 *cache_ino = sh->objectid;
1593         }
1594         if (!name)
1595                 return -EIO;
1596
1597         type = btrfs_stack_file_extent_type(item);
1598         compressed = btrfs_stack_file_extent_compression(item);
1599
1600         if (type == BTRFS_FILE_EXTENT_REG ||
1601             type == BTRFS_FILE_EXTENT_PREALLOC) {
1602                 disk_start = btrfs_stack_file_extent_disk_bytenr(item);
1603                 disk_offset = btrfs_stack_file_extent_offset(item);
1604                 len = btrfs_stack_file_extent_num_bytes(item);
1605         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
1606                 disk_start = 0;
1607                 disk_offset = 0;
1608                 len = btrfs_stack_file_extent_ram_bytes(item);
1609         } else {
1610                 printf("unhandled extent type %d for inode %llu "
1611                        "file offset %llu gen %llu\n",
1612                         type,
1613                         (unsigned long long)sh->objectid,
1614                         (unsigned long long)sh->offset,
1615                         (unsigned long long)found_gen);
1616
1617                 return -EIO;
1618         }
1619         printf("inode %llu file offset %llu len %llu disk start %llu "
1620                "offset %llu gen %llu flags ",
1621                (unsigned long long)sh->objectid,
1622                (unsigned long long)sh->offset,
1623                (unsigned long long)len,
1624                (unsigned long long)disk_start,
1625                (unsigned long long)disk_offset,
1626                (unsigned long long)found_gen);
1627
1628         if (compressed) {
1629                 printf("COMPRESS");
1630                 flags++;
1631         }
1632         if (type == BTRFS_FILE_EXTENT_PREALLOC) {
1633                 printf("%sPREALLOC", flags ? "|" : "");
1634                 flags++;
1635         }
1636         if (type == BTRFS_FILE_EXTENT_INLINE) {
1637                 printf("%sINLINE", flags ? "|" : "");
1638                 flags++;
1639         }
1640         if (!flags)
1641                 printf("NONE");
1642
1643         printf(" %s\n", name);
1644         return 0;
1645 }
1646
1647 int btrfs_list_find_updated_files(int fd, u64 root_id, u64 oldest_gen)
1648 {
1649         int ret;
1650         struct btrfs_ioctl_search_args args;
1651         struct btrfs_ioctl_search_key *sk = &args.key;
1652         struct btrfs_ioctl_search_header sh;
1653         struct btrfs_file_extent_item *item;
1654         unsigned long off = 0;
1655         u64 found_gen;
1656         u64 max_found = 0;
1657         int i;
1658         int e;
1659         u64 cache_dirid = 0;
1660         u64 cache_ino = 0;
1661         char *cache_dir_name = NULL;
1662         char *cache_full_name = NULL;
1663         struct btrfs_file_extent_item backup;
1664
1665         memset(&backup, 0, sizeof(backup));
1666         memset(&args, 0, sizeof(args));
1667
1668         sk->tree_id = root_id;
1669
1670         /*
1671          * set all the other params to the max, we'll take any objectid
1672          * and any trans
1673          */
1674         sk->max_objectid = (u64)-1;
1675         sk->max_offset = (u64)-1;
1676         sk->max_transid = (u64)-1;
1677         sk->max_type = BTRFS_EXTENT_DATA_KEY;
1678         sk->min_transid = oldest_gen;
1679         /* just a big number, doesn't matter much */
1680         sk->nr_items = 4096;
1681
1682         max_found = find_root_gen(fd);
1683         while(1) {
1684                 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args);
1685                 e = errno;
1686                 if (ret < 0) {
1687                         fprintf(stderr, "ERROR: can't perform the search- %s\n",
1688                                 strerror(e));
1689                         break;
1690                 }
1691                 /* the ioctl returns the number of item it found in nr_items */
1692                 if (sk->nr_items == 0)
1693                         break;
1694
1695                 off = 0;
1696
1697                 /*
1698                  * for each item, pull the key out of the header and then
1699                  * read the root_ref item it contains
1700                  */
1701                 for (i = 0; i < sk->nr_items; i++) {
1702                         memcpy(&sh, args.buf + off, sizeof(sh));
1703                         off += sizeof(sh);
1704
1705                         /*
1706                          * just in case the item was too big, pass something other
1707                          * than garbage
1708                          */
1709                         if (sh.len == 0)
1710                                 item = &backup;
1711                         else
1712                                 item = (struct btrfs_file_extent_item *)(args.buf +
1713                                                                  off);
1714                         found_gen = btrfs_stack_file_extent_generation(item);
1715                         if (sh.type == BTRFS_EXTENT_DATA_KEY &&
1716                             found_gen >= oldest_gen) {
1717                                 print_one_extent(fd, &sh, item, found_gen,
1718                                                  &cache_dirid, &cache_dir_name,
1719                                                  &cache_ino, &cache_full_name);
1720                         }
1721                         off += sh.len;
1722
1723                         /*
1724                          * record the mins in sk so we can make sure the
1725                          * next search doesn't repeat this root
1726                          */
1727                         sk->min_objectid = sh.objectid;
1728                         sk->min_offset = sh.offset;
1729                         sk->min_type = sh.type;
1730                 }
1731                 sk->nr_items = 4096;
1732                 if (sk->min_offset < (u64)-1)
1733                         sk->min_offset++;
1734                 else if (sk->min_objectid < (u64)-1) {
1735                         sk->min_objectid++;
1736                         sk->min_offset = 0;
1737                         sk->min_type = 0;
1738                 } else
1739                         break;
1740         }
1741         free(cache_dir_name);
1742         free(cache_full_name);
1743         printf("transid marker was %llu\n", (unsigned long long)max_found);
1744         return ret;
1745 }
1746
1747 char *btrfs_list_path_for_root(int fd, u64 root)
1748 {
1749         struct root_lookup root_lookup;
1750         struct rb_node *n;
1751         char *ret_path = NULL;
1752         int ret;
1753         u64 top_id;
1754
1755         ret = btrfs_list_get_path_rootid(fd, &top_id);
1756         if (ret)
1757                 return ERR_PTR(ret);
1758
1759         ret = __list_subvol_search(fd, &root_lookup);
1760         if (ret < 0)
1761                 return ERR_PTR(ret);
1762
1763         ret = __list_subvol_fill_paths(fd, &root_lookup);
1764         if (ret < 0)
1765                 return ERR_PTR(ret);
1766
1767         n = rb_last(&root_lookup.root);
1768         while (n) {
1769                 struct root_info *entry;
1770
1771                 entry = rb_entry(n, struct root_info, rb_node);
1772                 ret = resolve_root(&root_lookup, entry, top_id);
1773                 if (ret == -ENOENT && entry->root_id == root) {
1774                         ret_path = NULL;
1775                         break;
1776                 }
1777                 if (entry->root_id == root) {
1778                         ret_path = entry->full_path;
1779                         entry->full_path = NULL;
1780                 }
1781
1782                 n = rb_prev(n);
1783         }
1784         __free_all_subvolumn(&root_lookup);
1785
1786         return ret_path;
1787 }
1788
1789 int btrfs_list_parse_sort_string(char *opt_arg,
1790                                  struct btrfs_list_comparer_set **comps)
1791 {
1792         int order;
1793         int flag;
1794         char *p;
1795         char **ptr_argv;
1796         int what_to_sort;
1797
1798         while ((p = strtok(opt_arg, ",")) != NULL) {
1799                 flag = 0;
1800                 ptr_argv = all_sort_items;
1801
1802                 while (*ptr_argv) {
1803                         if (strcmp(*ptr_argv, p) == 0) {
1804                                 flag = 1;
1805                                 break;
1806                         } else {
1807                                 p++;
1808                                 if (strcmp(*ptr_argv, p) == 0) {
1809                                         flag = 1;
1810                                         p--;
1811                                         break;
1812                                 }
1813                                 p--;
1814                         }
1815                         ptr_argv++;
1816                 }
1817
1818                 if (flag == 0)
1819                         return -1;
1820
1821                 else {
1822                         if (*p == '+') {
1823                                 order = 0;
1824                                 p++;
1825                         } else if (*p == '-') {
1826                                 order = 1;
1827                                 p++;
1828                         } else
1829                                 order = 0;
1830
1831                         what_to_sort = btrfs_list_get_sort_item(p);
1832                         btrfs_list_setup_comparer(comps, what_to_sort, order);
1833                 }
1834                 opt_arg = NULL;
1835         }
1836
1837         return 0;
1838 }
1839
1840 /*
1841  * This function is used to parse the argument of filter condition.
1842  *
1843  * type is the filter object.
1844  */
1845 int btrfs_list_parse_filter_string(char *opt_arg,
1846                                    struct btrfs_list_filter_set **filters,
1847                                    enum btrfs_list_filter_enum type)
1848 {
1849
1850         u64 arg;
1851         char *ptr_parse_end = NULL;
1852         char *ptr_opt_arg_end = opt_arg + strlen(opt_arg);
1853
1854         switch (*(opt_arg++)) {
1855         case '+':
1856                 arg = (u64)strtol(opt_arg, &ptr_parse_end, 10);
1857                 type += 2;
1858                 if (ptr_parse_end != ptr_opt_arg_end)
1859                         return -1;
1860
1861                 btrfs_list_setup_filter(filters, type, arg);
1862                 break;
1863         case '-':
1864                 arg = (u64)strtoll(opt_arg, &ptr_parse_end, 10);
1865                 type += 1;
1866                 if (ptr_parse_end != ptr_opt_arg_end)
1867                         return -1;
1868
1869                 btrfs_list_setup_filter(filters, type, arg);
1870                 break;
1871         default:
1872                 opt_arg--;
1873                 arg = (u64)strtoll(opt_arg, &ptr_parse_end, 10);
1874
1875                 if (ptr_parse_end != ptr_opt_arg_end)
1876                         return -1;
1877                 btrfs_list_setup_filter(filters, type, arg);
1878                 break;
1879         }
1880
1881         return 0;
1882 }
1883
1884 int btrfs_list_get_path_rootid(int fd, u64 *treeid)
1885 {
1886         int  ret;
1887         struct btrfs_ioctl_ino_lookup_args args;
1888
1889         memset(&args, 0, sizeof(args));
1890         args.objectid = BTRFS_FIRST_FREE_OBJECTID;
1891
1892         ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
1893         if (ret < 0) {
1894                 fprintf(stderr,
1895                         "ERROR: can't perform the search -%s\n",
1896                         strerror(errno));
1897                 return ret;
1898         }
1899         *treeid = args.treeid;
1900         return 0;
1901 }