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