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