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