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