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