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