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