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