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