Btrfs-progs: we need to have the string null terminated
[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[len + add_len + 1] = '\0';
637                         tmp[add_len] = '/';
638                         memcpy(tmp, p, add_len);
639                         free(full_path);
640                         full_path = tmp;
641                         ri->top_id = next;
642                         break;
643                 }
644
645                 /*
646                  * if the ref_tree wasn't in our tree of roots, we're
647                  * at the top
648                  */
649                 found = root_tree_search(rl, next);
650                 if (!found) {
651                         ri->top_id = next;
652                         break;
653                 }
654         }
655
656         ri->full_path = full_path;
657
658         return 0;
659 }
660
661 /*
662  * for a single root_info, ask the kernel to give us a path name
663  * inside it's ref_root for the dir_id where it lives.
664  *
665  * This fills in root_info->path with the path to the directory and and
666  * appends this root's name.
667  */
668 static int lookup_ino_path(int fd, struct root_info *ri)
669 {
670         struct btrfs_ioctl_ino_lookup_args args;
671         int ret, e;
672
673         if (ri->path)
674                 return 0;
675
676         memset(&args, 0, sizeof(args));
677         args.treeid = ri->ref_tree;
678         args.objectid = ri->dir_id;
679
680         ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
681         e = errno;
682         if (ret) {
683                 fprintf(stderr, "ERROR: Failed to lookup path for root %llu - %s\n",
684                         (unsigned long long)ri->ref_tree,
685                         strerror(e));
686                 return ret;
687         }
688
689         if (args.name[0]) {
690                 /*
691                  * we're in a subdirectory of ref_tree, the kernel ioctl
692                  * puts a / in there for us
693                  */
694                 ri->path = malloc(strlen(ri->name) + strlen(args.name) + 1);
695                 if (!ri->path) {
696                         perror("malloc failed");
697                         exit(1);
698                 }
699                 strcpy(ri->path, args.name);
700                 strcat(ri->path, ri->name);
701         } else {
702                 /* we're at the root of ref_tree */
703                 ri->path = strdup(ri->name);
704                 if (!ri->path) {
705                         perror("strdup failed");
706                         exit(1);
707                 }
708         }
709         return 0;
710 }
711
712 /* finding the generation for a given path is a two step process.
713  * First we use the inode loookup routine to find out the root id
714  *
715  * Then we use the tree search ioctl to scan all the root items for a
716  * given root id and spit out the latest generation we can find
717  */
718 static u64 find_root_gen(int fd)
719 {
720         struct btrfs_ioctl_ino_lookup_args ino_args;
721         int ret;
722         struct btrfs_ioctl_search_args args;
723         struct btrfs_ioctl_search_key *sk = &args.key;
724         struct btrfs_ioctl_search_header sh;
725         unsigned long off = 0;
726         u64 max_found = 0;
727         int i;
728         int e;
729
730         memset(&ino_args, 0, sizeof(ino_args));
731         ino_args.objectid = BTRFS_FIRST_FREE_OBJECTID;
732
733         /* this ioctl fills in ino_args->treeid */
734         ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &ino_args);
735         e = errno;
736         if (ret) {
737                 fprintf(stderr, "ERROR: Failed to lookup path for dirid %llu - %s\n",
738                         (unsigned long long)BTRFS_FIRST_FREE_OBJECTID,
739                         strerror(e));
740                 return 0;
741         }
742
743         memset(&args, 0, sizeof(args));
744
745         sk->tree_id = 1;
746
747         /*
748          * there may be more than one ROOT_ITEM key if there are
749          * snapshots pending deletion, we have to loop through
750          * them.
751          */
752         sk->min_objectid = ino_args.treeid;
753         sk->max_objectid = ino_args.treeid;
754         sk->max_type = BTRFS_ROOT_ITEM_KEY;
755         sk->min_type = BTRFS_ROOT_ITEM_KEY;
756         sk->max_offset = (u64)-1;
757         sk->max_transid = (u64)-1;
758         sk->nr_items = 4096;
759
760         while (1) {
761                 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args);
762                 e = errno;
763                 if (ret < 0) {
764                         fprintf(stderr, "ERROR: can't perform the search - %s\n",
765                                 strerror(e));
766                         return 0;
767                 }
768                 /* the ioctl returns the number of item it found in nr_items */
769                 if (sk->nr_items == 0)
770                         break;
771
772                 off = 0;
773                 for (i = 0; i < sk->nr_items; i++) {
774                         struct btrfs_root_item *item;
775
776                         memcpy(&sh, args.buf + off, sizeof(sh));
777                         off += sizeof(sh);
778                         item = (struct btrfs_root_item *)(args.buf + off);
779                         off += sh.len;
780
781                         sk->min_objectid = sh.objectid;
782                         sk->min_type = sh.type;
783                         sk->min_offset = sh.offset;
784
785                         if (sh.objectid > ino_args.treeid)
786                                 break;
787
788                         if (sh.objectid == ino_args.treeid &&
789                             sh.type == BTRFS_ROOT_ITEM_KEY) {
790                                 max_found = max(max_found,
791                                                 btrfs_root_generation(item));
792                         }
793                 }
794                 if (sk->min_offset < (u64)-1)
795                         sk->min_offset++;
796                 else
797                         break;
798
799                 if (sk->min_type != BTRFS_ROOT_ITEM_KEY)
800                         break;
801                 if (sk->min_objectid != BTRFS_ROOT_ITEM_KEY)
802                         break;
803         }
804         return max_found;
805 }
806
807 /* pass in a directory id and this will return
808  * the full path of the parent directory inside its
809  * subvolume root.
810  *
811  * It may return NULL if it is in the root, or an ERR_PTR if things
812  * go badly.
813  */
814 static char *__ino_resolve(int fd, u64 dirid)
815 {
816         struct btrfs_ioctl_ino_lookup_args args;
817         int ret;
818         char *full;
819         int e;
820
821         memset(&args, 0, sizeof(args));
822         args.objectid = dirid;
823
824         ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
825         e = errno;
826         if (ret) {
827                 fprintf(stderr, "ERROR: Failed to lookup path for dirid %llu - %s\n",
828                         (unsigned long long)dirid, strerror(e) );
829                 return ERR_PTR(ret);
830         }
831
832         if (args.name[0]) {
833                 /*
834                  * we're in a subdirectory of ref_tree, the kernel ioctl
835                  * puts a / in there for us
836                  */
837                 full = strdup(args.name);
838                 if (!full) {
839                         perror("malloc failed");
840                         return ERR_PTR(-ENOMEM);
841                 }
842         } else {
843                 /* we're at the root of ref_tree */
844                 full = NULL;
845         }
846         return full;
847 }
848
849 /*
850  * simple string builder, returning a new string with both
851  * dirid and name
852  */
853 char *build_name(char *dirid, char *name)
854 {
855         char *full;
856         if (!dirid)
857                 return strdup(name);
858
859         full = malloc(strlen(dirid) + strlen(name) + 1);
860         if (!full)
861                 return NULL;
862         strcpy(full, dirid);
863         strcat(full, name);
864         return full;
865 }
866
867 /*
868  * given an inode number, this returns the full path name inside the subvolume
869  * to that file/directory.  cache_dirid and cache_name are used to
870  * cache the results so we can avoid tree searches if a later call goes
871  * to the same directory or file name
872  */
873 static char *ino_resolve(int fd, u64 ino, u64 *cache_dirid, char **cache_name)
874
875 {
876         u64 dirid;
877         char *dirname;
878         char *name;
879         char *full;
880         int ret;
881         struct btrfs_ioctl_search_args args;
882         struct btrfs_ioctl_search_key *sk = &args.key;
883         struct btrfs_ioctl_search_header *sh;
884         unsigned long off = 0;
885         int namelen;
886         int e;
887
888         memset(&args, 0, sizeof(args));
889
890         sk->tree_id = 0;
891
892         /*
893          * step one, we search for the inode back ref.  We just use the first
894          * one
895          */
896         sk->min_objectid = ino;
897         sk->max_objectid = ino;
898         sk->max_type = BTRFS_INODE_REF_KEY;
899         sk->max_offset = (u64)-1;
900         sk->min_type = BTRFS_INODE_REF_KEY;
901         sk->max_transid = (u64)-1;
902         sk->nr_items = 1;
903
904         ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args);
905         e = errno;
906         if (ret < 0) {
907                 fprintf(stderr, "ERROR: can't perform the search - %s\n",
908                         strerror(e));
909                 return NULL;
910         }
911         /* the ioctl returns the number of item it found in nr_items */
912         if (sk->nr_items == 0)
913                 return NULL;
914
915         off = 0;
916         sh = (struct btrfs_ioctl_search_header *)(args.buf + off);
917
918         if (sh->type == BTRFS_INODE_REF_KEY) {
919                 struct btrfs_inode_ref *ref;
920                 dirid = sh->offset;
921
922                 ref = (struct btrfs_inode_ref *)(sh + 1);
923                 namelen = btrfs_stack_inode_ref_name_len(ref);
924
925                 name = (char *)(ref + 1);
926                 name = strndup(name, namelen);
927
928                 /* use our cached value */
929                 if (dirid == *cache_dirid && *cache_name) {
930                         dirname = *cache_name;
931                         goto build;
932                 }
933         } else {
934                 return NULL;
935         }
936         /*
937          * the inode backref gives us the file name and the parent directory id.
938          * From here we use __ino_resolve to get the path to the parent
939          */
940         dirname = __ino_resolve(fd, dirid);
941 build:
942         full = build_name(dirname, name);
943         if (*cache_name && dirname != *cache_name)
944                 free(*cache_name);
945
946         *cache_name = dirname;
947         *cache_dirid = dirid;
948         free(name);
949
950         return full;
951 }
952
953 int btrfs_list_get_default_subvolume(int fd, u64 *default_id)
954 {
955         struct btrfs_ioctl_search_args args;
956         struct btrfs_ioctl_search_key *sk = &args.key;
957         struct btrfs_ioctl_search_header *sh;
958         u64 found = 0;
959         int ret;
960
961         memset(&args, 0, sizeof(args));
962
963         /*
964          * search for a dir item with a name 'default' in the tree of
965          * tree roots, it should point us to a default root
966          */
967         sk->tree_id = 1;
968
969         /* don't worry about ancient format and request only one item */
970         sk->nr_items = 1;
971
972         sk->max_objectid = BTRFS_ROOT_TREE_DIR_OBJECTID;
973         sk->min_objectid = BTRFS_ROOT_TREE_DIR_OBJECTID;
974         sk->max_type = BTRFS_DIR_ITEM_KEY;
975         sk->min_type = BTRFS_DIR_ITEM_KEY;
976         sk->max_offset = (u64)-1;
977         sk->max_transid = (u64)-1;
978
979         ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args);
980         if (ret < 0)
981                 return ret;
982
983         /* the ioctl returns the number of items it found in nr_items */
984         if (sk->nr_items == 0)
985                 goto out;
986
987         sh = (struct btrfs_ioctl_search_header *)args.buf;
988
989         if (sh->type == BTRFS_DIR_ITEM_KEY) {
990                 struct btrfs_dir_item *di;
991                 int name_len;
992                 char *name;
993
994                 di = (struct btrfs_dir_item *)(sh + 1);
995                 name_len = btrfs_stack_dir_name_len(di);
996                 name = (char *)(di + 1);
997
998                 if (!strncmp("default", name, name_len))
999                         found = btrfs_disk_key_objectid(&di->location);
1000         }
1001
1002 out:
1003         *default_id = found;
1004         return 0;
1005 }
1006
1007 static int __list_subvol_search(int fd, struct root_lookup *root_lookup)
1008 {
1009         int ret;
1010         struct btrfs_ioctl_search_args args;
1011         struct btrfs_ioctl_search_key *sk = &args.key;
1012         struct btrfs_ioctl_search_header sh;
1013         struct btrfs_root_ref *ref;
1014         struct btrfs_root_item *ri;
1015         unsigned long off = 0;
1016         int name_len;
1017         char *name;
1018         u64 dir_id;
1019         u64 gen = 0;
1020         u64 ogen;
1021         u64 flags;
1022         int i;
1023         time_t t;
1024         u8 uuid[BTRFS_UUID_SIZE];
1025
1026         root_lookup_init(root_lookup);
1027         memset(&args, 0, sizeof(args));
1028
1029         /* search in the tree of tree roots */
1030         sk->tree_id = 1;
1031
1032         /*
1033          * set the min and max to backref keys.  The search will
1034          * only send back this type of key now.
1035          */
1036         sk->max_type = BTRFS_ROOT_BACKREF_KEY;
1037         sk->min_type = BTRFS_ROOT_ITEM_KEY;
1038
1039         sk->min_objectid = BTRFS_FIRST_FREE_OBJECTID;
1040
1041         /*
1042          * set all the other params to the max, we'll take any objectid
1043          * and any trans
1044          */
1045         sk->max_objectid = BTRFS_LAST_FREE_OBJECTID;
1046         sk->max_offset = (u64)-1;
1047         sk->max_transid = (u64)-1;
1048
1049         /* just a big number, doesn't matter much */
1050         sk->nr_items = 4096;
1051
1052         while(1) {
1053                 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args);
1054                 if (ret < 0)
1055                         return ret;
1056                 /* the ioctl returns the number of item it found in nr_items */
1057                 if (sk->nr_items == 0)
1058                         break;
1059
1060                 off = 0;
1061
1062                 /*
1063                  * for each item, pull the key out of the header and then
1064                  * read the root_ref item it contains
1065                  */
1066                 for (i = 0; i < sk->nr_items; i++) {
1067                         memcpy(&sh, args.buf + off, sizeof(sh));
1068                         off += sizeof(sh);
1069                         if (sh.type == BTRFS_ROOT_BACKREF_KEY) {
1070                                 ref = (struct btrfs_root_ref *)(args.buf + off);
1071                                 name_len = btrfs_stack_root_ref_name_len(ref);
1072                                 name = (char *)(ref + 1);
1073                                 dir_id = btrfs_stack_root_ref_dirid(ref);
1074
1075                                 add_root(root_lookup, sh.objectid, sh.offset,
1076                                          0, 0, dir_id, name, name_len, 0, 0, 0,
1077                                          NULL);
1078                         } else if (sh.type == BTRFS_ROOT_ITEM_KEY) {
1079                                 ri = (struct btrfs_root_item *)(args.buf + off);
1080                                 gen = btrfs_root_generation(ri);
1081                                 flags = btrfs_root_flags(ri);
1082                                 if(sh.len >
1083                                    sizeof(struct btrfs_root_item_v0)) {
1084                                         t = ri->otime.sec;
1085                                         ogen = btrfs_root_otransid(ri);
1086                                         memcpy(uuid, ri->uuid, BTRFS_UUID_SIZE);
1087                                 } else {
1088                                         t = 0;
1089                                         ogen = 0;
1090                                         memset(uuid, 0, BTRFS_UUID_SIZE);
1091                                 }
1092
1093                                 add_root(root_lookup, sh.objectid, 0,
1094                                          sh.offset, flags, 0, NULL, 0, ogen,
1095                                          gen, t, uuid);
1096                         }
1097
1098                         off += sh.len;
1099
1100                         /*
1101                          * record the mins in sk so we can make sure the
1102                          * next search doesn't repeat this root
1103                          */
1104                         sk->min_objectid = sh.objectid;
1105                         sk->min_type = sh.type;
1106                         sk->min_offset = sh.offset;
1107                 }
1108                 sk->nr_items = 4096;
1109                 sk->min_offset++;
1110                 if (!sk->min_offset)    /* overflow */
1111                         sk->min_type++;
1112                 else
1113                         continue;
1114
1115                 if (sk->min_type > BTRFS_ROOT_BACKREF_KEY) {
1116                         sk->min_type = BTRFS_ROOT_ITEM_KEY;
1117                         sk->min_objectid++;
1118                 } else
1119                         continue;
1120
1121                 if (sk->min_objectid > sk->max_objectid)
1122                         break;
1123         }
1124
1125         return 0;
1126 }
1127
1128 static int filter_by_rootid(struct root_info *ri, u64 data)
1129 {
1130         return ri->root_id == data;
1131 }
1132
1133 static int filter_snapshot(struct root_info *ri, u64 data)
1134 {
1135         return !!ri->root_offset;
1136 }
1137
1138 static int filter_flags(struct root_info *ri, u64 flags)
1139 {
1140         return ri->flags & flags;
1141 }
1142
1143 static int filter_gen_more(struct root_info *ri, u64 data)
1144 {
1145         return ri->gen >= data;
1146 }
1147
1148 static int filter_gen_less(struct root_info *ri, u64 data)
1149 {
1150         return ri->gen <= data;
1151 }
1152
1153 static int filter_gen_equal(struct root_info  *ri, u64 data)
1154 {
1155         return ri->gen == data;
1156 }
1157
1158 static int filter_cgen_more(struct root_info *ri, u64 data)
1159 {
1160         return ri->ogen >= data;
1161 }
1162
1163 static int filter_cgen_less(struct root_info *ri, u64 data)
1164 {
1165         return ri->ogen <= data;
1166 }
1167
1168 static int filter_cgen_equal(struct root_info *ri, u64 data)
1169 {
1170         return ri->ogen == data;
1171 }
1172
1173 static int filter_topid_equal(struct root_info *ri, u64 data)
1174 {
1175         return ri->top_id == data;
1176 }
1177
1178 static btrfs_list_filter_func all_filter_funcs[] = {
1179         [BTRFS_LIST_FILTER_ROOTID]              = filter_by_rootid,
1180         [BTRFS_LIST_FILTER_SNAPSHOT_ONLY]       = filter_snapshot,
1181         [BTRFS_LIST_FILTER_FLAGS]               = filter_flags,
1182         [BTRFS_LIST_FILTER_GEN_MORE]            = filter_gen_more,
1183         [BTRFS_LIST_FILTER_GEN_LESS]            = filter_gen_less,
1184         [BTRFS_LIST_FILTER_GEN_EQUAL]           = filter_gen_equal,
1185         [BTRFS_LIST_FILTER_CGEN_MORE]           = filter_cgen_more,
1186         [BTRFS_LIST_FILTER_CGEN_LESS]           = filter_cgen_less,
1187         [BTRFS_LIST_FILTER_CGEN_EQUAL]          = filter_cgen_equal,
1188         [BTRFS_LIST_FILTER_TOPID_EQUAL]         = filter_topid_equal,
1189 };
1190
1191 struct btrfs_list_filter_set *btrfs_list_alloc_filter_set(void)
1192 {
1193         struct btrfs_list_filter_set *set;
1194         int size;
1195
1196         size = sizeof(struct btrfs_list_filter_set) +
1197                BTRFS_LIST_NFILTERS_INCREASE * sizeof(struct btrfs_list_filter);
1198         set = malloc(size);
1199         if (!set) {
1200                 fprintf(stderr, "memory allocation failed\n");
1201                 exit(1);
1202         }
1203
1204         memset(set, 0, size);
1205         set->total = BTRFS_LIST_NFILTERS_INCREASE;
1206
1207         return set;
1208 }
1209
1210 void btrfs_list_free_filter_set(struct btrfs_list_filter_set *filter_set)
1211 {
1212         free(filter_set);
1213 }
1214
1215 int btrfs_list_setup_filter(struct btrfs_list_filter_set **filter_set,
1216                             enum btrfs_list_filter_enum filter, u64 data)
1217 {
1218         struct btrfs_list_filter_set *set = *filter_set;
1219         int size;
1220
1221         BUG_ON(!set);
1222         BUG_ON(filter >= BTRFS_LIST_FILTER_MAX);
1223         BUG_ON(set->nfilters > set->total);
1224
1225         if (set->nfilters == set->total) {
1226                 size = set->total + BTRFS_LIST_NFILTERS_INCREASE;
1227                 size = sizeof(*set) + size * sizeof(struct btrfs_list_filter);
1228                 set = realloc(set, size);
1229                 if (!set) {
1230                         fprintf(stderr, "memory allocation failed\n");
1231                         exit(1);
1232                 }
1233
1234                 memset(&set->filters[set->total], 0,
1235                        BTRFS_LIST_NFILTERS_INCREASE *
1236                        sizeof(struct btrfs_list_filter));
1237                 set->total += BTRFS_LIST_NFILTERS_INCREASE;
1238                 *filter_set = set;
1239         }
1240
1241         BUG_ON(set->filters[set->nfilters].filter_func);
1242
1243         set->filters[set->nfilters].filter_func = all_filter_funcs[filter];
1244         set->filters[set->nfilters].data = data;
1245         set->nfilters++;
1246         return 0;
1247 }
1248
1249 static int filter_root(struct root_info *ri,
1250                        struct btrfs_list_filter_set *set)
1251 {
1252         int i, ret;
1253
1254         if (!set || !set->nfilters)
1255                 return 1;
1256
1257         for (i = 0; i < set->nfilters; i++) {
1258                 if (!set->filters[i].filter_func)
1259                         break;
1260                 ret = set->filters[i].filter_func(ri, set->filters[i].data);
1261                 if (!ret)
1262                         return 0;
1263         }
1264         return 1;
1265 }
1266
1267 static void __filter_and_sort_subvol(struct root_lookup *all_subvols,
1268                                     struct root_lookup *sort_tree,
1269                                     struct btrfs_list_filter_set *filter_set,
1270                                     struct btrfs_list_comparer_set *comp_set,
1271                                     int fd)
1272 {
1273         struct rb_node *n;
1274         struct root_info *entry;
1275         int ret;
1276         u64 top_id = btrfs_list_get_path_rootid(fd);
1277
1278         root_lookup_init(sort_tree);
1279
1280         n = rb_last(&all_subvols->root);
1281         while (n) {
1282                 entry = rb_entry(n, struct root_info, rb_node);
1283
1284                 resolve_root(all_subvols, entry, top_id);
1285                 ret = filter_root(entry, filter_set);
1286                 if (ret)
1287                         sort_tree_insert(sort_tree, entry, comp_set);
1288                 n = rb_prev(n);
1289         }
1290 }
1291
1292 static int __list_subvol_fill_paths(int fd, struct root_lookup *root_lookup)
1293 {
1294         struct rb_node *n;
1295
1296         n = rb_first(&root_lookup->root);
1297         while (n) {
1298                 struct root_info *entry;
1299                 int ret;
1300                 entry = rb_entry(n, struct root_info, rb_node);
1301                 ret = lookup_ino_path(fd, entry);
1302                 if(ret < 0)
1303                         return ret;
1304                 n = rb_next(n);
1305         }
1306
1307         return 0;
1308 }
1309
1310 static void print_subvolume_column(struct root_info *subv,
1311                                    enum btrfs_list_column_enum column)
1312 {
1313         char tstr[256];
1314         char uuidparse[37];
1315
1316         BUG_ON(column >= BTRFS_LIST_ALL || column < 0);
1317
1318         switch (column) {
1319         case BTRFS_LIST_OBJECTID:
1320                 printf("%llu", subv->root_id);
1321                 break;
1322         case BTRFS_LIST_GENERATION:
1323                 printf("%llu", subv->gen);
1324                 break;
1325         case BTRFS_LIST_OGENERATION:
1326                 printf("%llu", subv->ogen);
1327                 break;
1328         case BTRFS_LIST_PARENT:
1329                 printf("%llu", subv->ref_tree);
1330                 break;
1331         case BTRFS_LIST_TOP_LEVEL:
1332                 printf("%llu", subv->top_id);
1333                 break;
1334         case BTRFS_LIST_OTIME:
1335                 if (subv->otime)
1336                         strftime(tstr, 256, "%Y-%m-%d %X",
1337                                  localtime(&subv->otime));
1338                 else
1339                         strcpy(tstr, "-");
1340                 printf("%s", tstr);
1341                 break;
1342         case BTRFS_LIST_UUID:
1343                 if (uuid_is_null(subv->uuid))
1344                         strcpy(uuidparse, "-");
1345                 else
1346                         uuid_unparse(subv->uuid, uuidparse);
1347                 printf("%s", uuidparse);
1348                 break;
1349         case BTRFS_LIST_PATH:
1350                 BUG_ON(!subv->full_path);
1351                 printf("%s", subv->full_path);
1352                 break;
1353         default:
1354                 break;
1355         }
1356 }
1357
1358 static void print_single_volume_info_table(struct root_info *subv)
1359 {
1360         int i;
1361
1362         for (i = 0; i < BTRFS_LIST_ALL; i++) {
1363                 if (!btrfs_list_columns[i].need_print)
1364                         continue;
1365
1366                 print_subvolume_column(subv, i);
1367
1368                 if (i != BTRFS_LIST_PATH)
1369                         printf("\t");
1370
1371                 if (i == BTRFS_LIST_TOP_LEVEL)
1372                         printf("\t");
1373         }
1374         printf("\n");
1375 }
1376
1377 static void print_single_volume_info_default(struct root_info *subv)
1378 {
1379         int i;
1380
1381         for (i = 0; i < BTRFS_LIST_ALL; i++) {
1382                 if (!btrfs_list_columns[i].need_print)
1383                         continue;
1384
1385                 printf("%s ", btrfs_list_columns[i].name);
1386                 print_subvolume_column(subv, i);
1387
1388                 if (i != BTRFS_LIST_PATH)
1389                         printf(" ");
1390         }
1391         printf("\n");
1392 }
1393
1394 static void print_all_volume_info_tab_head()
1395 {
1396         int i;
1397         int len;
1398         char barrier[20];
1399
1400         for (i = 0; i < BTRFS_LIST_ALL; i++) {
1401                 if (btrfs_list_columns[i].need_print)
1402                         printf("%s\t", btrfs_list_columns[i].name);
1403
1404                 if (i == BTRFS_LIST_ALL-1)
1405                         printf("\n");
1406         }
1407
1408         for (i = 0; i < BTRFS_LIST_ALL; i++) {
1409                 memset(barrier, 0, sizeof(barrier));
1410
1411                 if (btrfs_list_columns[i].need_print) {
1412                         len = strlen(btrfs_list_columns[i].name);
1413                         while (len--)
1414                                 strcat(barrier, "-");
1415
1416                         printf("%s\t", barrier);
1417                 }
1418                 if (i == BTRFS_LIST_ALL-1)
1419                         printf("\n");
1420         }
1421 }
1422
1423 static void print_all_volume_info(struct root_lookup *sorted_tree,
1424                                   int is_tab_result)
1425 {
1426         struct rb_node *n;
1427         struct root_info *entry;
1428
1429         if (is_tab_result)
1430                 print_all_volume_info_tab_head();
1431
1432         n = rb_first(&sorted_tree->root);
1433         while (n) {
1434                 entry = rb_entry(n, struct root_info, sort_node);
1435                 if (is_tab_result)
1436                         print_single_volume_info_table(entry);
1437                 else
1438                         print_single_volume_info_default(entry);
1439                 n = rb_next(n);
1440         }
1441 }
1442
1443 int btrfs_list_subvols(int fd, struct btrfs_list_filter_set *filter_set,
1444                        struct btrfs_list_comparer_set *comp_set,
1445                        int is_tab_result)
1446 {
1447         struct root_lookup root_lookup;
1448         struct root_lookup root_sort;
1449         int ret;
1450
1451         ret = __list_subvol_search(fd, &root_lookup);
1452         if (ret) {
1453                 fprintf(stderr, "ERROR: can't perform the search - %s\n",
1454                                 strerror(errno));
1455                 return ret;
1456         }
1457
1458         /*
1459          * now we have an rbtree full of root_info objects, but we need to fill
1460          * in their path names within the subvol that is referencing each one.
1461          */
1462         ret = __list_subvol_fill_paths(fd, &root_lookup);
1463         if (ret < 0)
1464                 return ret;
1465
1466         __filter_and_sort_subvol(&root_lookup, &root_sort, filter_set,
1467                                  comp_set, fd);
1468
1469         print_all_volume_info(&root_sort, is_tab_result);
1470         __free_all_subvolumn(&root_lookup);
1471         return ret;
1472 }
1473
1474 static int print_one_extent(int fd, struct btrfs_ioctl_search_header *sh,
1475                             struct btrfs_file_extent_item *item,
1476                             u64 found_gen, u64 *cache_dirid,
1477                             char **cache_dir_name, u64 *cache_ino,
1478                             char **cache_full_name)
1479 {
1480         u64 len = 0;
1481         u64 disk_start = 0;
1482         u64 disk_offset = 0;
1483         u8 type;
1484         int compressed = 0;
1485         int flags = 0;
1486         char *name = NULL;
1487
1488         if (sh->objectid == *cache_ino) {
1489                 name = *cache_full_name;
1490         } else if (*cache_full_name) {
1491                 free(*cache_full_name);
1492                 *cache_full_name = NULL;
1493         }
1494         if (!name) {
1495                 name = ino_resolve(fd, sh->objectid, cache_dirid,
1496                                    cache_dir_name);
1497                 *cache_full_name = name;
1498                 *cache_ino = sh->objectid;
1499         }
1500         if (!name)
1501                 return -EIO;
1502
1503         type = btrfs_stack_file_extent_type(item);
1504         compressed = btrfs_stack_file_extent_compression(item);
1505
1506         if (type == BTRFS_FILE_EXTENT_REG ||
1507             type == BTRFS_FILE_EXTENT_PREALLOC) {
1508                 disk_start = btrfs_stack_file_extent_disk_bytenr(item);
1509                 disk_offset = btrfs_stack_file_extent_offset(item);
1510                 len = btrfs_stack_file_extent_num_bytes(item);
1511         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
1512                 disk_start = 0;
1513                 disk_offset = 0;
1514                 len = btrfs_stack_file_extent_ram_bytes(item);
1515         } else {
1516                 printf("unhandled extent type %d for inode %llu "
1517                        "file offset %llu gen %llu\n",
1518                         type,
1519                         (unsigned long long)sh->objectid,
1520                         (unsigned long long)sh->offset,
1521                         (unsigned long long)found_gen);
1522
1523                 return -EIO;
1524         }
1525         printf("inode %llu file offset %llu len %llu disk start %llu "
1526                "offset %llu gen %llu flags ",
1527                (unsigned long long)sh->objectid,
1528                (unsigned long long)sh->offset,
1529                (unsigned long long)len,
1530                (unsigned long long)disk_start,
1531                (unsigned long long)disk_offset,
1532                (unsigned long long)found_gen);
1533
1534         if (compressed) {
1535                 printf("COMPRESS");
1536                 flags++;
1537         }
1538         if (type == BTRFS_FILE_EXTENT_PREALLOC) {
1539                 printf("%sPREALLOC", flags ? "|" : "");
1540                 flags++;
1541         }
1542         if (type == BTRFS_FILE_EXTENT_INLINE) {
1543                 printf("%sINLINE", flags ? "|" : "");
1544                 flags++;
1545         }
1546         if (!flags)
1547                 printf("NONE");
1548
1549         printf(" %s\n", name);
1550         return 0;
1551 }
1552
1553 int btrfs_list_find_updated_files(int fd, u64 root_id, u64 oldest_gen)
1554 {
1555         int ret;
1556         struct btrfs_ioctl_search_args args;
1557         struct btrfs_ioctl_search_key *sk = &args.key;
1558         struct btrfs_ioctl_search_header sh;
1559         struct btrfs_file_extent_item *item;
1560         unsigned long off = 0;
1561         u64 found_gen;
1562         u64 max_found = 0;
1563         int i;
1564         int e;
1565         u64 cache_dirid = 0;
1566         u64 cache_ino = 0;
1567         char *cache_dir_name = NULL;
1568         char *cache_full_name = NULL;
1569         struct btrfs_file_extent_item backup;
1570
1571         memset(&backup, 0, sizeof(backup));
1572         memset(&args, 0, sizeof(args));
1573
1574         sk->tree_id = root_id;
1575
1576         /*
1577          * set all the other params to the max, we'll take any objectid
1578          * and any trans
1579          */
1580         sk->max_objectid = (u64)-1;
1581         sk->max_offset = (u64)-1;
1582         sk->max_transid = (u64)-1;
1583         sk->max_type = BTRFS_EXTENT_DATA_KEY;
1584         sk->min_transid = oldest_gen;
1585         /* just a big number, doesn't matter much */
1586         sk->nr_items = 4096;
1587
1588         max_found = find_root_gen(fd);
1589         while(1) {
1590                 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args);
1591                 e = errno;
1592                 if (ret < 0) {
1593                         fprintf(stderr, "ERROR: can't perform the search- %s\n",
1594                                 strerror(e));
1595                         return ret;
1596                 }
1597                 /* the ioctl returns the number of item it found in nr_items */
1598                 if (sk->nr_items == 0)
1599                         break;
1600
1601                 off = 0;
1602
1603                 /*
1604                  * for each item, pull the key out of the header and then
1605                  * read the root_ref item it contains
1606                  */
1607                 for (i = 0; i < sk->nr_items; i++) {
1608                         memcpy(&sh, args.buf + off, sizeof(sh));
1609                         off += sizeof(sh);
1610
1611                         /*
1612                          * just in case the item was too big, pass something other
1613                          * than garbage
1614                          */
1615                         if (sh.len == 0)
1616                                 item = &backup;
1617                         else
1618                                 item = (struct btrfs_file_extent_item *)(args.buf +
1619                                                                  off);
1620                         found_gen = btrfs_stack_file_extent_generation(item);
1621                         if (sh.type == BTRFS_EXTENT_DATA_KEY &&
1622                             found_gen >= oldest_gen) {
1623                                 print_one_extent(fd, &sh, item, found_gen,
1624                                                  &cache_dirid, &cache_dir_name,
1625                                                  &cache_ino, &cache_full_name);
1626                         }
1627                         off += sh.len;
1628
1629                         /*
1630                          * record the mins in sk so we can make sure the
1631                          * next search doesn't repeat this root
1632                          */
1633                         sk->min_objectid = sh.objectid;
1634                         sk->min_offset = sh.offset;
1635                         sk->min_type = sh.type;
1636                 }
1637                 sk->nr_items = 4096;
1638                 if (sk->min_offset < (u64)-1)
1639                         sk->min_offset++;
1640                 else if (sk->min_objectid < (u64)-1) {
1641                         sk->min_objectid++;
1642                         sk->min_offset = 0;
1643                         sk->min_type = 0;
1644                 } else
1645                         break;
1646         }
1647         free(cache_dir_name);
1648         free(cache_full_name);
1649         printf("transid marker was %llu\n", (unsigned long long)max_found);
1650         return ret;
1651 }
1652
1653 char *btrfs_list_path_for_root(int fd, u64 root)
1654 {
1655         struct root_lookup root_lookup;
1656         struct rb_node *n;
1657         char *ret_path = NULL;
1658         int ret;
1659         u64 top_id = btrfs_list_get_path_rootid(fd);
1660
1661         ret = __list_subvol_search(fd, &root_lookup);
1662         if (ret < 0)
1663                 return ERR_PTR(ret);
1664
1665         ret = __list_subvol_fill_paths(fd, &root_lookup);
1666         if (ret < 0)
1667                 return ERR_PTR(ret);
1668
1669         n = rb_last(&root_lookup.root);
1670         while (n) {
1671                 struct root_info *entry;
1672
1673                 entry = rb_entry(n, struct root_info, rb_node);
1674                 resolve_root(&root_lookup, entry, top_id);
1675                 if (entry->root_id == root) {
1676                         ret_path = entry->full_path;
1677                         entry->full_path = NULL;
1678                 }
1679
1680                 n = rb_prev(n);
1681         }
1682         __free_all_subvolumn(&root_lookup);
1683
1684         return ret_path;
1685 }
1686
1687 int btrfs_list_parse_sort_string(char *optarg,
1688                                  struct btrfs_list_comparer_set **comps)
1689 {
1690         int order;
1691         int flag;
1692         char *p;
1693         char **ptr_argv;
1694         int what_to_sort;
1695
1696         while ((p = strtok(optarg, ",")) != NULL) {
1697                 flag = 0;
1698                 ptr_argv = all_sort_items;
1699
1700                 while (*ptr_argv) {
1701                         if (strcmp(*ptr_argv, p) == 0) {
1702                                 flag = 1;
1703                                 break;
1704                         } else {
1705                                 p++;
1706                                 if (strcmp(*ptr_argv, p) == 0) {
1707                                         flag = 1;
1708                                         p--;
1709                                         break;
1710                                 }
1711                                 p--;
1712                         }
1713                         ptr_argv++;
1714                 }
1715
1716                 if (flag == 0)
1717                         return -1;
1718
1719                 else {
1720                         if (*p == '+') {
1721                                 order = 0;
1722                                 p++;
1723                         } else if (*p == '-') {
1724                                 order = 1;
1725                                 p++;
1726                         } else
1727                                 order = 0;
1728
1729                         what_to_sort = btrfs_list_get_sort_item(p);
1730                         btrfs_list_setup_comparer(comps, what_to_sort, order);
1731                 }
1732                 optarg = NULL;
1733         }
1734
1735         return 0;
1736 }
1737
1738 /*
1739  * This function is used to parse the argument of filter condition.
1740  *
1741  * type is the filter object.
1742  */
1743 int btrfs_list_parse_filter_string(char *optarg,
1744                                    struct btrfs_list_filter_set **filters,
1745                                    enum btrfs_list_filter_enum type)
1746 {
1747
1748         u64 arg;
1749         char *ptr_parse_end = NULL;
1750         char *ptr_optarg_end = optarg + strlen(optarg);
1751
1752         switch (*(optarg++)) {
1753         case '+':
1754                 arg = (u64)strtol(optarg, &ptr_parse_end, 10);
1755                 type += 2;
1756                 if (ptr_parse_end != ptr_optarg_end)
1757                         return -1;
1758
1759                 btrfs_list_setup_filter(filters, type, arg);
1760                 break;
1761         case '-':
1762                 arg = (u64)strtoll(optarg, &ptr_parse_end, 10);
1763                 type += 1;
1764                 if (ptr_parse_end != ptr_optarg_end)
1765                         return -1;
1766
1767                 btrfs_list_setup_filter(filters, type, arg);
1768                 break;
1769         default:
1770                 optarg--;
1771                 arg = (u64)strtoll(optarg, &ptr_parse_end, 10);
1772
1773                 if (ptr_parse_end != ptr_optarg_end)
1774                         return -1;
1775                 btrfs_list_setup_filter(filters, type, arg);
1776                 break;
1777         }
1778
1779         return 0;
1780 }
1781
1782 u64 btrfs_list_get_path_rootid(int fd)
1783 {
1784         int  ret;
1785         struct btrfs_ioctl_ino_lookup_args args;
1786
1787         memset(&args, 0, sizeof(args));
1788         args.objectid = BTRFS_FIRST_FREE_OBJECTID;
1789
1790         ret = ioctl(fd, BTRFS_IOC_INO_LOOKUP, &args);
1791         if (ret < 0) {
1792                 fprintf(stderr,
1793                         "ERROR: can't perform the search -%s\n",
1794                         strerror(errno));
1795                 return ret;
1796         }
1797         return args.treeid;
1798 }