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