f3618b9c5c5cb72a738976a12cbc43f0b5b99547
[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 int filter_deleted(struct root_info *ri, u64 data)
1177 {
1178         return ri->deleted;
1179 }
1180
1181 static btrfs_list_filter_func all_filter_funcs[] = {
1182         [BTRFS_LIST_FILTER_ROOTID]              = filter_by_rootid,
1183         [BTRFS_LIST_FILTER_SNAPSHOT_ONLY]       = filter_snapshot,
1184         [BTRFS_LIST_FILTER_FLAGS]               = filter_flags,
1185         [BTRFS_LIST_FILTER_GEN_MORE]            = filter_gen_more,
1186         [BTRFS_LIST_FILTER_GEN_LESS]            = filter_gen_less,
1187         [BTRFS_LIST_FILTER_GEN_EQUAL]           = filter_gen_equal,
1188         [BTRFS_LIST_FILTER_CGEN_MORE]           = filter_cgen_more,
1189         [BTRFS_LIST_FILTER_CGEN_LESS]           = filter_cgen_less,
1190         [BTRFS_LIST_FILTER_CGEN_EQUAL]          = filter_cgen_equal,
1191         [BTRFS_LIST_FILTER_TOPID_EQUAL]         = filter_topid_equal,
1192         [BTRFS_LIST_FILTER_FULL_PATH]           = filter_full_path,
1193         [BTRFS_LIST_FILTER_BY_PARENT]           = filter_by_parent,
1194         [BTRFS_LIST_FILTER_DELETED]             = filter_deleted,
1195 };
1196
1197 struct btrfs_list_filter_set *btrfs_list_alloc_filter_set(void)
1198 {
1199         struct btrfs_list_filter_set *set;
1200         int size;
1201
1202         size = sizeof(struct btrfs_list_filter_set) +
1203                BTRFS_LIST_NFILTERS_INCREASE * sizeof(struct btrfs_list_filter);
1204         set = malloc(size);
1205         if (!set) {
1206                 fprintf(stderr, "memory allocation failed\n");
1207                 exit(1);
1208         }
1209
1210         memset(set, 0, size);
1211         set->total = BTRFS_LIST_NFILTERS_INCREASE;
1212
1213         return set;
1214 }
1215
1216 void btrfs_list_free_filter_set(struct btrfs_list_filter_set *filter_set)
1217 {
1218         free(filter_set);
1219 }
1220
1221 int btrfs_list_setup_filter(struct btrfs_list_filter_set **filter_set,
1222                             enum btrfs_list_filter_enum filter, u64 data)
1223 {
1224         struct btrfs_list_filter_set *set = *filter_set;
1225         int size;
1226
1227         BUG_ON(!set);
1228         BUG_ON(filter >= BTRFS_LIST_FILTER_MAX);
1229         BUG_ON(set->nfilters > set->total);
1230
1231         if (filter == BTRFS_LIST_FILTER_DELETED) {
1232                 set->only_deleted = 1;
1233                 return 0;
1234         }
1235
1236         if (set->nfilters == set->total) {
1237                 size = set->total + BTRFS_LIST_NFILTERS_INCREASE;
1238                 size = sizeof(*set) + size * sizeof(struct btrfs_list_filter);
1239                 set = realloc(set, size);
1240                 if (!set) {
1241                         fprintf(stderr, "memory allocation failed\n");
1242                         exit(1);
1243                 }
1244
1245                 memset(&set->filters[set->total], 0,
1246                        BTRFS_LIST_NFILTERS_INCREASE *
1247                        sizeof(struct btrfs_list_filter));
1248                 set->total += BTRFS_LIST_NFILTERS_INCREASE;
1249                 *filter_set = set;
1250         }
1251
1252         BUG_ON(set->filters[set->nfilters].filter_func);
1253
1254         set->filters[set->nfilters].filter_func = all_filter_funcs[filter];
1255         set->filters[set->nfilters].data = data;
1256         set->nfilters++;
1257         return 0;
1258 }
1259
1260 static int filter_root(struct root_info *ri,
1261                        struct btrfs_list_filter_set *set)
1262 {
1263         int i, ret;
1264
1265         if (!set || !set->nfilters)
1266                 return 1;
1267
1268         if (set->only_deleted && !ri->deleted)
1269                 return 0;
1270
1271         if (!set->only_deleted && ri->deleted)
1272                 return 0;
1273
1274         for (i = 0; i < set->nfilters; i++) {
1275                 if (!set->filters[i].filter_func)
1276                         break;
1277                 ret = set->filters[i].filter_func(ri, set->filters[i].data);
1278                 if (!ret)
1279                         return 0;
1280         }
1281         return 1;
1282 }
1283
1284 static void __filter_and_sort_subvol(struct root_lookup *all_subvols,
1285                                     struct root_lookup *sort_tree,
1286                                     struct btrfs_list_filter_set *filter_set,
1287                                     struct btrfs_list_comparer_set *comp_set,
1288                                     u64 top_id)
1289 {
1290         struct rb_node *n;
1291         struct root_info *entry;
1292         int ret;
1293
1294         root_lookup_init(sort_tree);
1295
1296         n = rb_last(&all_subvols->root);
1297         while (n) {
1298                 entry = rb_entry(n, struct root_info, rb_node);
1299
1300                 ret = resolve_root(all_subvols, entry, top_id);
1301                 if (ret == -ENOENT) {
1302                         entry->full_path = strdup("DELETED");
1303                         entry->deleted = 1;
1304                 }
1305                 ret = filter_root(entry, filter_set);
1306                 if (ret)
1307                         sort_tree_insert(sort_tree, entry, comp_set);
1308                 n = rb_prev(n);
1309         }
1310 }
1311
1312 static int __list_subvol_fill_paths(int fd, struct root_lookup *root_lookup)
1313 {
1314         struct rb_node *n;
1315
1316         n = rb_first(&root_lookup->root);
1317         while (n) {
1318                 struct root_info *entry;
1319                 int ret;
1320                 entry = rb_entry(n, struct root_info, rb_node);
1321                 ret = lookup_ino_path(fd, entry);
1322                 if (ret && ret != -ENOENT)
1323                         return ret;
1324                 n = rb_next(n);
1325         }
1326
1327         return 0;
1328 }
1329
1330 static void print_subvolume_column(struct root_info *subv,
1331                                    enum btrfs_list_column_enum column)
1332 {
1333         char tstr[256];
1334         char uuidparse[37];
1335
1336         BUG_ON(column >= BTRFS_LIST_ALL || column < 0);
1337
1338         switch (column) {
1339         case BTRFS_LIST_OBJECTID:
1340                 printf("%llu", subv->root_id);
1341                 break;
1342         case BTRFS_LIST_GENERATION:
1343                 printf("%llu", subv->gen);
1344                 break;
1345         case BTRFS_LIST_OGENERATION:
1346                 printf("%llu", subv->ogen);
1347                 break;
1348         case BTRFS_LIST_PARENT:
1349                 printf("%llu", subv->ref_tree);
1350                 break;
1351         case BTRFS_LIST_TOP_LEVEL:
1352                 printf("%llu", subv->top_id);
1353                 break;
1354         case BTRFS_LIST_OTIME:
1355                 if (subv->otime) {
1356                         struct tm tm;
1357
1358                         localtime_r(&subv->otime, &tm);
1359                         strftime(tstr, 256, "%Y-%m-%d %X", &tm);
1360                 } else
1361                         strcpy(tstr, "-");
1362                 printf("%s", tstr);
1363                 break;
1364         case BTRFS_LIST_UUID:
1365                 if (uuid_is_null(subv->uuid))
1366                         strcpy(uuidparse, "-");
1367                 else
1368                         uuid_unparse(subv->uuid, uuidparse);
1369                 printf("%s", uuidparse);
1370                 break;
1371         case BTRFS_LIST_PUUID:
1372                 if (uuid_is_null(subv->puuid))
1373                         strcpy(uuidparse, "-");
1374                 else
1375                         uuid_unparse(subv->puuid, uuidparse);
1376                 printf("%s", uuidparse);
1377                 break;
1378         case BTRFS_LIST_PATH:
1379                 BUG_ON(!subv->full_path);
1380                 printf("%s", subv->full_path);
1381                 break;
1382         default:
1383                 break;
1384         }
1385 }
1386
1387 static void print_single_volume_info_raw(struct root_info *subv, char *raw_prefix)
1388 {
1389         int i;
1390
1391         for (i = 0; i < BTRFS_LIST_ALL; i++) {
1392                 if (!btrfs_list_columns[i].need_print)
1393                         continue;
1394
1395                 if (raw_prefix)
1396                         printf("%s",raw_prefix);
1397
1398                 print_subvolume_column(subv, i);
1399         }
1400         printf("\n");
1401 }
1402
1403 static void print_single_volume_info_table(struct root_info *subv)
1404 {
1405         int i;
1406
1407         for (i = 0; i < BTRFS_LIST_ALL; i++) {
1408                 if (!btrfs_list_columns[i].need_print)
1409                         continue;
1410
1411                 print_subvolume_column(subv, i);
1412
1413                 if (i != BTRFS_LIST_PATH)
1414                         printf("\t");
1415
1416                 if (i == BTRFS_LIST_TOP_LEVEL)
1417                         printf("\t");
1418         }
1419         printf("\n");
1420 }
1421
1422 static void print_single_volume_info_default(struct root_info *subv)
1423 {
1424         int i;
1425
1426         for (i = 0; i < BTRFS_LIST_ALL; i++) {
1427                 if (!btrfs_list_columns[i].need_print)
1428                         continue;
1429
1430                 printf("%s ", btrfs_list_columns[i].name);
1431                 print_subvolume_column(subv, i);
1432
1433                 if (i != BTRFS_LIST_PATH)
1434                         printf(" ");
1435         }
1436         printf("\n");
1437 }
1438
1439 static void print_all_volume_info_tab_head(void)
1440 {
1441         int i;
1442         int len;
1443         char barrier[20];
1444
1445         for (i = 0; i < BTRFS_LIST_ALL; i++) {
1446                 if (btrfs_list_columns[i].need_print)
1447                         printf("%s\t", btrfs_list_columns[i].name);
1448
1449                 if (i == BTRFS_LIST_ALL-1)
1450                         printf("\n");
1451         }
1452
1453         for (i = 0; i < BTRFS_LIST_ALL; i++) {
1454                 memset(barrier, 0, sizeof(barrier));
1455
1456                 if (btrfs_list_columns[i].need_print) {
1457                         len = strlen(btrfs_list_columns[i].name);
1458                         while (len--)
1459                                 strcat(barrier, "-");
1460
1461                         printf("%s\t", barrier);
1462                 }
1463                 if (i == BTRFS_LIST_ALL-1)
1464                         printf("\n");
1465         }
1466 }
1467
1468 static void print_all_volume_info(struct root_lookup *sorted_tree,
1469                                   int layout, char *raw_prefix)
1470 {
1471         struct rb_node *n;
1472         struct root_info *entry;
1473
1474         if (layout == BTRFS_LIST_LAYOUT_TABLE)
1475                 print_all_volume_info_tab_head();
1476
1477         n = rb_first(&sorted_tree->root);
1478         while (n) {
1479                 entry = rb_entry(n, struct root_info, sort_node);
1480                 switch (layout) {
1481                 case BTRFS_LIST_LAYOUT_DEFAULT:
1482                         print_single_volume_info_default(entry);
1483                         break;
1484                 case BTRFS_LIST_LAYOUT_TABLE:
1485                         print_single_volume_info_table(entry);
1486                         break;
1487                 case BTRFS_LIST_LAYOUT_RAW:
1488                         print_single_volume_info_raw(entry, raw_prefix);
1489                         break;
1490                 }
1491                 n = rb_next(n);
1492         }
1493 }
1494
1495 static int btrfs_list_subvols(int fd, struct root_lookup *root_lookup)
1496 {
1497         int ret;
1498
1499         ret = __list_subvol_search(fd, root_lookup);
1500         if (ret) {
1501                 fprintf(stderr, "ERROR: can't perform the search - %s\n",
1502                                 strerror(errno));
1503                 return ret;
1504         }
1505
1506         /*
1507          * now we have an rbtree full of root_info objects, but we need to fill
1508          * in their path names within the subvol that is referencing each one.
1509          */
1510         ret = __list_subvol_fill_paths(fd, root_lookup);
1511         return ret;
1512 }
1513
1514 int btrfs_list_subvols_print(int fd, struct btrfs_list_filter_set *filter_set,
1515                        struct btrfs_list_comparer_set *comp_set,
1516                        int layout, int full_path, char *raw_prefix)
1517 {
1518         struct root_lookup root_lookup;
1519         struct root_lookup root_sort;
1520         int ret = 0;
1521         u64 top_id = 0;
1522
1523         if (full_path)
1524                 ret = btrfs_list_get_path_rootid(fd, &top_id);
1525         if (ret)
1526                 return ret;
1527
1528         ret = btrfs_list_subvols(fd, &root_lookup);
1529         if (ret)
1530                 return ret;
1531         __filter_and_sort_subvol(&root_lookup, &root_sort, filter_set,
1532                                  comp_set, top_id);
1533
1534         print_all_volume_info(&root_sort, layout, raw_prefix);
1535         __free_all_subvolumn(&root_lookup);
1536
1537         return 0;
1538 }
1539
1540 static char *strdup_or_null(const char *s)
1541 {
1542         if (!s)
1543                 return NULL;
1544         return strdup(s);
1545 }
1546
1547 int btrfs_get_subvol(int fd, struct root_info *the_ri)
1548 {
1549         int ret, rr;
1550         struct root_lookup rl;
1551         struct rb_node *rbn;
1552         struct root_info *ri;
1553         u64 root_id;
1554
1555         ret = btrfs_list_get_path_rootid(fd, &root_id);
1556         if (ret)
1557                 return ret;
1558
1559         ret = btrfs_list_subvols(fd, &rl);
1560         if (ret)
1561                 return ret;
1562
1563         rbn = rb_first(&rl.root);
1564         while(rbn) {
1565                 ri = rb_entry(rbn, struct root_info, rb_node);
1566                 rr = resolve_root(&rl, ri, root_id);
1567                 if (rr == -ENOENT) {
1568                         ret = -ENOENT;
1569                         rbn = rb_next(rbn);
1570                         continue;
1571                 }
1572                 if (!comp_entry_with_rootid(the_ri, ri, 0)) {
1573                         memcpy(the_ri, ri, offsetof(struct root_info, path));
1574                         the_ri->path = strdup_or_null(ri->path);
1575                         the_ri->name = strdup_or_null(ri->name);
1576                         the_ri->full_path = strdup_or_null(ri->full_path);
1577                         ret = 0;
1578                         break;
1579                 }
1580                 rbn = rb_next(rbn);
1581         }
1582         __free_all_subvolumn(&rl);
1583         return ret;
1584 }
1585
1586 static int print_one_extent(int fd, struct btrfs_ioctl_search_header *sh,
1587                             struct btrfs_file_extent_item *item,
1588                             u64 found_gen, u64 *cache_dirid,
1589                             char **cache_dir_name, u64 *cache_ino,
1590                             char **cache_full_name)
1591 {
1592         u64 len = 0;
1593         u64 disk_start = 0;
1594         u64 disk_offset = 0;
1595         u8 type;
1596         int compressed = 0;
1597         int flags = 0;
1598         char *name = NULL;
1599
1600         if (sh->objectid == *cache_ino) {
1601                 name = *cache_full_name;
1602         } else if (*cache_full_name) {
1603                 free(*cache_full_name);
1604                 *cache_full_name = NULL;
1605         }
1606         if (!name) {
1607                 name = ino_resolve(fd, sh->objectid, cache_dirid,
1608                                    cache_dir_name);
1609                 *cache_full_name = name;
1610                 *cache_ino = sh->objectid;
1611         }
1612         if (!name)
1613                 return -EIO;
1614
1615         type = btrfs_stack_file_extent_type(item);
1616         compressed = btrfs_stack_file_extent_compression(item);
1617
1618         if (type == BTRFS_FILE_EXTENT_REG ||
1619             type == BTRFS_FILE_EXTENT_PREALLOC) {
1620                 disk_start = btrfs_stack_file_extent_disk_bytenr(item);
1621                 disk_offset = btrfs_stack_file_extent_offset(item);
1622                 len = btrfs_stack_file_extent_num_bytes(item);
1623         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
1624                 disk_start = 0;
1625                 disk_offset = 0;
1626                 len = btrfs_stack_file_extent_ram_bytes(item);
1627         } else {
1628                 printf("unhandled extent type %d for inode %llu "
1629                        "file offset %llu gen %llu\n",
1630                         type,
1631                         (unsigned long long)sh->objectid,
1632                         (unsigned long long)sh->offset,
1633                         (unsigned long long)found_gen);
1634
1635                 return -EIO;
1636         }
1637         printf("inode %llu file offset %llu len %llu disk start %llu "
1638                "offset %llu gen %llu flags ",
1639                (unsigned long long)sh->objectid,
1640                (unsigned long long)sh->offset,
1641                (unsigned long long)len,
1642                (unsigned long long)disk_start,
1643                (unsigned long long)disk_offset,
1644                (unsigned long long)found_gen);
1645
1646         if (compressed) {
1647                 printf("COMPRESS");
1648                 flags++;
1649         }
1650         if (type == BTRFS_FILE_EXTENT_PREALLOC) {
1651                 printf("%sPREALLOC", flags ? "|" : "");
1652                 flags++;
1653         }
1654         if (type == BTRFS_FILE_EXTENT_INLINE) {
1655                 printf("%sINLINE", flags ? "|" : "");
1656                 flags++;
1657         }
1658         if (!flags)
1659                 printf("NONE");
1660
1661         printf(" %s\n", name);
1662         return 0;
1663 }
1664
1665 int btrfs_list_find_updated_files(int fd, u64 root_id, u64 oldest_gen)
1666 {
1667         int ret;
1668         struct btrfs_ioctl_search_args args;
1669         struct btrfs_ioctl_search_key *sk = &args.key;
1670         struct btrfs_ioctl_search_header sh;
1671         struct btrfs_file_extent_item *item;
1672         unsigned long off = 0;
1673         u64 found_gen;
1674         u64 max_found = 0;
1675         int i;
1676         int e;
1677         u64 cache_dirid = 0;
1678         u64 cache_ino = 0;
1679         char *cache_dir_name = NULL;
1680         char *cache_full_name = NULL;
1681         struct btrfs_file_extent_item backup;
1682
1683         memset(&backup, 0, sizeof(backup));
1684         memset(&args, 0, sizeof(args));
1685
1686         sk->tree_id = root_id;
1687
1688         /*
1689          * set all the other params to the max, we'll take any objectid
1690          * and any trans
1691          */
1692         sk->max_objectid = (u64)-1;
1693         sk->max_offset = (u64)-1;
1694         sk->max_transid = (u64)-1;
1695         sk->max_type = BTRFS_EXTENT_DATA_KEY;
1696         sk->min_transid = oldest_gen;
1697         /* just a big number, doesn't matter much */
1698         sk->nr_items = 4096;
1699
1700         max_found = find_root_gen(fd);
1701         while(1) {
1702                 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args);
1703                 e = errno;
1704                 if (ret < 0) {
1705                         fprintf(stderr, "ERROR: can't perform the search- %s\n",
1706                                 strerror(e));
1707                         break;
1708                 }
1709                 /* the ioctl returns the number of item it found in nr_items */
1710                 if (sk->nr_items == 0)
1711                         break;
1712
1713                 off = 0;
1714
1715                 /*
1716                  * for each item, pull the key out of the header and then
1717                  * read the root_ref item it contains
1718                  */
1719                 for (i = 0; i < sk->nr_items; i++) {
1720                         memcpy(&sh, args.buf + off, sizeof(sh));
1721                         off += sizeof(sh);
1722
1723                         /*
1724                          * just in case the item was too big, pass something other
1725                          * than garbage
1726                          */
1727                         if (sh.len == 0)
1728                                 item = &backup;
1729                         else
1730                                 item = (struct btrfs_file_extent_item *)(args.buf +
1731                                                                  off);
1732                         found_gen = btrfs_stack_file_extent_generation(item);
1733                         if (sh.type == BTRFS_EXTENT_DATA_KEY &&
1734                             found_gen >= oldest_gen) {
1735                                 print_one_extent(fd, &sh, item, found_gen,
1736                                                  &cache_dirid, &cache_dir_name,
1737                                                  &cache_ino, &cache_full_name);
1738                         }
1739                         off += sh.len;
1740
1741                         /*
1742                          * record the mins in sk so we can make sure the
1743                          * next search doesn't repeat this root
1744                          */
1745                         sk->min_objectid = sh.objectid;
1746                         sk->min_offset = sh.offset;
1747                         sk->min_type = sh.type;
1748                 }
1749                 sk->nr_items = 4096;
1750                 if (sk->min_offset < (u64)-1)
1751                         sk->min_offset++;
1752                 else if (sk->min_objectid < (u64)-1) {
1753                         sk->min_objectid++;
1754                         sk->min_offset = 0;
1755                         sk->min_type = 0;
1756                 } else
1757                         break;
1758         }
1759         free(cache_dir_name);
1760         free(cache_full_name);
1761         printf("transid marker was %llu\n", (unsigned long long)max_found);
1762         return ret;
1763 }
1764
1765 char *btrfs_list_path_for_root(int fd, u64 root)
1766 {
1767         struct root_lookup root_lookup;
1768         struct rb_node *n;
1769         char *ret_path = NULL;
1770         int ret;
1771         u64 top_id;
1772
1773         ret = btrfs_list_get_path_rootid(fd, &top_id);
1774         if (ret)
1775                 return ERR_PTR(ret);
1776
1777         ret = __list_subvol_search(fd, &root_lookup);
1778         if (ret < 0)
1779                 return ERR_PTR(ret);
1780
1781         ret = __list_subvol_fill_paths(fd, &root_lookup);
1782         if (ret < 0)
1783                 return ERR_PTR(ret);
1784
1785         n = rb_last(&root_lookup.root);
1786         while (n) {
1787                 struct root_info *entry;
1788
1789                 entry = rb_entry(n, struct root_info, rb_node);
1790                 ret = resolve_root(&root_lookup, entry, top_id);
1791                 if (ret == -ENOENT && entry->root_id == root) {
1792                         ret_path = NULL;
1793                         break;
1794                 }
1795                 if (entry->root_id == root) {
1796                         ret_path = entry->full_path;
1797                         entry->full_path = NULL;
1798                 }
1799
1800                 n = rb_prev(n);
1801         }
1802         __free_all_subvolumn(&root_lookup);
1803
1804         return ret_path;
1805 }
1806
1807 int btrfs_list_parse_sort_string(char *opt_arg,
1808                                  struct btrfs_list_comparer_set **comps)
1809 {
1810         int order;
1811         int flag;
1812         char *p;
1813         char **ptr_argv;
1814         int what_to_sort;
1815
1816         while ((p = strtok(opt_arg, ",")) != NULL) {
1817                 flag = 0;
1818                 ptr_argv = all_sort_items;
1819
1820                 while (*ptr_argv) {
1821                         if (strcmp(*ptr_argv, p) == 0) {
1822                                 flag = 1;
1823                                 break;
1824                         } else {
1825                                 p++;
1826                                 if (strcmp(*ptr_argv, p) == 0) {
1827                                         flag = 1;
1828                                         p--;
1829                                         break;
1830                                 }
1831                                 p--;
1832                         }
1833                         ptr_argv++;
1834                 }
1835
1836                 if (flag == 0)
1837                         return -1;
1838
1839                 else {
1840                         if (*p == '+') {
1841                                 order = 0;
1842                                 p++;
1843                         } else if (*p == '-') {
1844                                 order = 1;
1845                                 p++;
1846                         } else
1847                                 order = 0;
1848
1849                         what_to_sort = btrfs_list_get_sort_item(p);
1850                         btrfs_list_setup_comparer(comps, what_to_sort, order);
1851                 }
1852                 opt_arg = NULL;
1853         }
1854
1855         return 0;
1856 }
1857
1858 /*
1859  * This function is used to parse the argument of filter condition.
1860  *
1861  * type is the filter object.
1862  */
1863 int btrfs_list_parse_filter_string(char *opt_arg,
1864                                    struct btrfs_list_filter_set **filters,
1865                                    enum btrfs_list_filter_enum type)
1866 {
1867
1868         u64 arg;
1869         char *ptr_parse_end = NULL;
1870         char *ptr_opt_arg_end = opt_arg + strlen(opt_arg);
1871
1872         switch (*(opt_arg++)) {
1873         case '+':
1874                 arg = (u64)strtol(opt_arg, &ptr_parse_end, 10);
1875                 type += 2;
1876                 if (ptr_parse_end != ptr_opt_arg_end)
1877                         return -1;
1878
1879                 btrfs_list_setup_filter(filters, type, arg);
1880                 break;
1881         case '-':
1882                 arg = (u64)strtoll(opt_arg, &ptr_parse_end, 10);
1883                 type += 1;
1884                 if (ptr_parse_end != ptr_opt_arg_end)
1885                         return -1;
1886
1887                 btrfs_list_setup_filter(filters, type, arg);
1888                 break;
1889         default:
1890                 opt_arg--;
1891                 arg = (u64)strtoll(opt_arg, &ptr_parse_end, 10);
1892
1893                 if (ptr_parse_end != ptr_opt_arg_end)
1894                         return -1;
1895                 btrfs_list_setup_filter(filters, type, arg);
1896                 break;
1897         }
1898
1899         return 0;
1900 }
1901
1902 int btrfs_list_get_path_rootid(int fd, u64 *treeid)
1903 {
1904         int  ret;
1905         struct btrfs_ioctl_ino_lookup_args args;
1906
1907         memset(&args, 0, sizeof(args));
1908         args.objectid = BTRFS_FIRST_FREE_OBJECTID;
1909
1910         ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
1911         if (ret < 0) {
1912                 fprintf(stderr,
1913                         "ERROR: can't perform the search -%s\n",
1914                         strerror(errno));
1915                 return ret;
1916         }
1917         *treeid = args.treeid;
1918         return 0;
1919 }