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