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