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