btrfs-progs: restore: use on-stack path buffer in copy_metadata
[platform/upstream/btrfs-progs.git] / cmds-restore.c
1 /*
2  * Copyright (C) 2011 Red Hat.  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
20 #include "kerncompat.h"
21
22 #include <ctype.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <lzo/lzoconf.h>
30 #include <lzo/lzo1x.h>
31 #include <zlib.h>
32 #include <regex.h>
33 #include <getopt.h>
34 #include <sys/types.h>
35 #include <sys/xattr.h>
36
37 #include "ctree.h"
38 #include "disk-io.h"
39 #include "print-tree.h"
40 #include "transaction.h"
41 #include "list.h"
42 #include "volumes.h"
43 #include "utils.h"
44 #include "commands.h"
45
46 static char fs_name[PATH_MAX];
47 static char path_name[PATH_MAX];
48 static char symlink_target[PATH_MAX];
49 static int get_snaps = 0;
50 static int verbose = 0;
51 static int restore_metadata = 0;
52 static int restore_symlinks = 0;
53 static int ignore_errors = 0;
54 static int overwrite = 0;
55 static int get_xattrs = 0;
56 static int dry_run = 0;
57
58 #define LZO_LEN 4
59 #define lzo1x_worst_compress(x) ((x) + ((x) / 16) + 64 + 3)
60
61 static int decompress_zlib(char *inbuf, char *outbuf, u64 compress_len,
62                            u64 decompress_len)
63 {
64         z_stream strm;
65         int ret;
66
67         memset(&strm, 0, sizeof(strm));
68         ret = inflateInit(&strm);
69         if (ret != Z_OK) {
70                 error("zlib init returned %d", ret);
71                 return -1;
72         }
73
74         strm.avail_in = compress_len;
75         strm.next_in = (unsigned char *)inbuf;
76         strm.avail_out = decompress_len;
77         strm.next_out = (unsigned char *)outbuf;
78         ret = inflate(&strm, Z_NO_FLUSH);
79         if (ret != Z_STREAM_END) {
80                 (void)inflateEnd(&strm);
81                 error("zlib inflate failed: %d", ret);
82                 return -1;
83         }
84
85         (void)inflateEnd(&strm);
86         return 0;
87 }
88 static inline size_t read_compress_length(unsigned char *buf)
89 {
90         __le32 dlen;
91         memcpy(&dlen, buf, LZO_LEN);
92         return le32_to_cpu(dlen);
93 }
94
95 static int decompress_lzo(struct btrfs_root *root, unsigned char *inbuf,
96                         char *outbuf, u64 compress_len, u64 *decompress_len)
97 {
98         size_t new_len;
99         size_t in_len;
100         size_t out_len = 0;
101         size_t tot_len;
102         size_t tot_in;
103         int ret;
104
105         ret = lzo_init();
106         if (ret != LZO_E_OK) {
107                 error("lzo init returned %d", ret);
108                 return -1;
109         }
110
111         tot_len = read_compress_length(inbuf);
112         inbuf += LZO_LEN;
113         tot_in = LZO_LEN;
114
115         while (tot_in < tot_len) {
116                 size_t mod_page;
117                 size_t rem_page;
118                 in_len = read_compress_length(inbuf);
119
120                 if ((tot_in + LZO_LEN + in_len) > tot_len) {
121                         error("bad compress length %lu",
122                                 (unsigned long)in_len);
123                         return -1;
124                 }
125
126                 inbuf += LZO_LEN;
127                 tot_in += LZO_LEN;
128                 new_len = lzo1x_worst_compress(root->sectorsize);
129                 ret = lzo1x_decompress_safe((const unsigned char *)inbuf, in_len,
130                                             (unsigned char *)outbuf,
131                                             (void *)&new_len, NULL);
132                 if (ret != LZO_E_OK) {
133                         error("lzo decompress failed: %d", ret);
134                         return -1;
135                 }
136                 out_len += new_len;
137                 outbuf += new_len;
138                 inbuf += in_len;
139                 tot_in += in_len;
140
141                 /*
142                  * If the 4 byte header does not fit to the rest of the page we
143                  * have to move to the next one, unless we read some garbage
144                  */
145                 mod_page = tot_in % root->sectorsize;
146                 rem_page = root->sectorsize - mod_page;
147                 if (rem_page < LZO_LEN) {
148                         inbuf += rem_page;
149                         tot_in += rem_page;
150                 }
151         }
152
153         *decompress_len = out_len;
154
155         return 0;
156 }
157
158 static int decompress(struct btrfs_root *root, char *inbuf, char *outbuf,
159                         u64 compress_len, u64 *decompress_len, int compress)
160 {
161         switch (compress) {
162         case BTRFS_COMPRESS_ZLIB:
163                 return decompress_zlib(inbuf, outbuf, compress_len,
164                                        *decompress_len);
165         case BTRFS_COMPRESS_LZO:
166                 return decompress_lzo(root, (unsigned char *)inbuf, outbuf,
167                                         compress_len, decompress_len);
168         default:
169                 break;
170         }
171
172         error("invalid compression type: %d", compress);
173         return -1;
174 }
175
176 static int next_leaf(struct btrfs_root *root, struct btrfs_path *path)
177 {
178         int slot;
179         int level = 1;
180         int offset = 1;
181         struct extent_buffer *c;
182         struct extent_buffer *next = NULL;
183
184 again:
185         for (; level < BTRFS_MAX_LEVEL; level++) {
186                 if (path->nodes[level])
187                         break;
188         }
189
190         if (level >= BTRFS_MAX_LEVEL)
191                 return 1;
192
193         slot = path->slots[level] + 1;
194
195         while(level < BTRFS_MAX_LEVEL) {
196                 if (!path->nodes[level])
197                         return 1;
198
199                 slot = path->slots[level] + offset;
200                 c = path->nodes[level];
201                 if (slot >= btrfs_header_nritems(c)) {
202                         level++;
203                         if (level == BTRFS_MAX_LEVEL)
204                                 return 1;
205                         offset = 1;
206                         continue;
207                 }
208
209                 if (path->reada)
210                         reada_for_search(root, path, level, slot, 0);
211
212                 next = read_node_slot(root, c, slot);
213                 if (extent_buffer_uptodate(next))
214                         break;
215                 offset++;
216         }
217         path->slots[level] = slot;
218         while(1) {
219                 level--;
220                 c = path->nodes[level];
221                 free_extent_buffer(c);
222                 path->nodes[level] = next;
223                 path->slots[level] = 0;
224                 if (!level)
225                         break;
226                 if (path->reada)
227                         reada_for_search(root, path, level, 0, 0);
228                 next = read_node_slot(root, next, 0);
229                 if (!extent_buffer_uptodate(next))
230                         goto again;
231         }
232         return 0;
233 }
234
235 static int copy_one_inline(struct btrfs_root *root, int fd,
236                                 struct btrfs_path *path, u64 pos)
237 {
238         struct extent_buffer *leaf = path->nodes[0];
239         struct btrfs_file_extent_item *fi;
240         char buf[4096];
241         char *outbuf;
242         u64 ram_size;
243         ssize_t done;
244         unsigned long ptr;
245         int ret;
246         int len;
247         int inline_item_len;
248         int compress;
249
250         fi = btrfs_item_ptr(leaf, path->slots[0],
251                             struct btrfs_file_extent_item);
252         ptr = btrfs_file_extent_inline_start(fi);
253         len = btrfs_file_extent_inline_len(leaf, path->slots[0], fi);
254         inline_item_len = btrfs_file_extent_inline_item_len(leaf, btrfs_item_nr(path->slots[0]));
255         read_extent_buffer(leaf, buf, ptr, inline_item_len);
256
257         compress = btrfs_file_extent_compression(leaf, fi);
258         if (compress == BTRFS_COMPRESS_NONE) {
259                 done = pwrite(fd, buf, len, pos);
260                 if (done < len) {
261                         fprintf(stderr, "Short inline write, wanted %d, did "
262                                 "%zd: %d\n", len, done, errno);
263                         return -1;
264                 }
265                 return 0;
266         }
267
268         ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
269         outbuf = calloc(1, ram_size);
270         if (!outbuf) {
271                 error("not enough memory");
272                 return -ENOMEM;
273         }
274
275         ret = decompress(root, buf, outbuf, len, &ram_size, compress);
276         if (ret) {
277                 free(outbuf);
278                 return ret;
279         }
280
281         done = pwrite(fd, outbuf, ram_size, pos);
282         free(outbuf);
283         if (done < ram_size) {
284                 fprintf(stderr, "Short compressed inline write, wanted %Lu, "
285                         "did %zd: %d\n", ram_size, done, errno);
286                 return -1;
287         }
288
289         return 0;
290 }
291
292 static int copy_one_extent(struct btrfs_root *root, int fd,
293                            struct extent_buffer *leaf,
294                            struct btrfs_file_extent_item *fi, u64 pos)
295 {
296         struct btrfs_multi_bio *multi = NULL;
297         struct btrfs_device *device;
298         char *inbuf, *outbuf = NULL;
299         ssize_t done, total = 0;
300         u64 bytenr;
301         u64 ram_size;
302         u64 disk_size;
303         u64 num_bytes;
304         u64 length;
305         u64 size_left;
306         u64 dev_bytenr;
307         u64 offset;
308         u64 count = 0;
309         int compress;
310         int ret;
311         int dev_fd;
312         int mirror_num = 1;
313         int num_copies;
314
315         compress = btrfs_file_extent_compression(leaf, fi);
316         bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
317         disk_size = btrfs_file_extent_disk_num_bytes(leaf, fi);
318         ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
319         offset = btrfs_file_extent_offset(leaf, fi);
320         num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
321         size_left = disk_size;
322         if (compress == BTRFS_COMPRESS_NONE)
323                 bytenr += offset;
324
325         if (verbose && offset)
326                 printf("offset is %Lu\n", offset);
327         /* we found a hole */
328         if (disk_size == 0)
329                 return 0;
330
331         inbuf = malloc(size_left);
332         if (!inbuf) {
333                 error("not enough memory\n");
334                 return -ENOMEM;
335         }
336
337         if (compress != BTRFS_COMPRESS_NONE) {
338                 outbuf = calloc(1, ram_size);
339                 if (!outbuf) {
340                         error("not enough memory");
341                         free(inbuf);
342                         return -ENOMEM;
343                 }
344         }
345 again:
346         length = size_left;
347         ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
348                               bytenr, &length, &multi, mirror_num, NULL);
349         if (ret) {
350                 error("cannot map block logical %llu length %llu: %d",
351                                 (unsigned long long)bytenr,
352                                 (unsigned long long)length, ret);
353                 goto out;
354         }
355         device = multi->stripes[0].dev;
356         dev_fd = device->fd;
357         device->total_ios++;
358         dev_bytenr = multi->stripes[0].physical;
359         free(multi);
360
361         if (size_left < length)
362                 length = size_left;
363
364         done = pread(dev_fd, inbuf+count, length, dev_bytenr);
365         /* Need both checks, or we miss negative values due to u64 conversion */
366         if (done < 0 || done < length) {
367                 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
368                                               bytenr, length);
369                 mirror_num++;
370                 /* mirror_num is 1-indexed, so num_copies is a valid mirror. */
371                 if (mirror_num > num_copies) {
372                         ret = -1;
373                         error("exhausted mirrors trying to read (%d > %d)",
374                                         mirror_num, num_copies);
375                         goto out;
376                 }
377                 fprintf(stderr, "Trying another mirror\n");
378                 goto again;
379         }
380
381         mirror_num = 1;
382         size_left -= length;
383         count += length;
384         bytenr += length;
385         if (size_left)
386                 goto again;
387
388         if (compress == BTRFS_COMPRESS_NONE) {
389                 while (total < num_bytes) {
390                         done = pwrite(fd, inbuf+total, num_bytes-total,
391                                       pos+total);
392                         if (done < 0) {
393                                 ret = -1;
394                                 error("cannot write data: %d %s", errno, strerror(errno));
395                                 goto out;
396                         }
397                         total += done;
398                 }
399                 ret = 0;
400                 goto out;
401         }
402
403         ret = decompress(root, inbuf, outbuf, disk_size, &ram_size, compress);
404         if (ret) {
405                 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
406                                               bytenr, length);
407                 mirror_num++;
408                 if (mirror_num >= num_copies) {
409                         ret = -1;
410                         goto out;
411                 }
412                 fprintf(stderr, "Trying another mirror\n");
413                 goto again;
414         }
415
416         while (total < num_bytes) {
417                 done = pwrite(fd, outbuf + offset + total,
418                               num_bytes - total,
419                               pos + total);
420                 if (done < 0) {
421                         ret = -1;
422                         goto out;
423                 }
424                 total += done;
425         }
426 out:
427         free(inbuf);
428         free(outbuf);
429         return ret;
430 }
431
432 enum loop_response {
433         LOOP_STOP,
434         LOOP_CONTINUE,
435         LOOP_DONTASK
436 };
437
438 static enum loop_response ask_to_continue(const char *file)
439 {
440         char buf[2];
441         char *ret;
442
443         printf("We seem to be looping a lot on %s, do you want to keep going "
444                "on ? (y/N/a): ", file);
445 again:
446         ret = fgets(buf, 2, stdin);
447         if (*ret == '\n' || tolower(*ret) == 'n')
448                 return LOOP_STOP;
449         if (tolower(*ret) == 'a')
450                 return LOOP_DONTASK;
451         if (tolower(*ret) != 'y') {
452                 printf("Please enter one of 'y', 'n', or 'a': ");
453                 goto again;
454         }
455
456         return LOOP_CONTINUE;
457 }
458
459
460 static int set_file_xattrs(struct btrfs_root *root, u64 inode,
461                            int fd, const char *file_name)
462 {
463         struct btrfs_key key;
464         struct btrfs_path path;
465         struct extent_buffer *leaf;
466         struct btrfs_dir_item *di;
467         u32 name_len = 0;
468         u32 data_len = 0;
469         u32 len = 0;
470         u32 cur, total_len;
471         char *name = NULL;
472         char *data = NULL;
473         int ret = 0;
474
475         btrfs_init_path(&path);
476         key.objectid = inode;
477         key.type = BTRFS_XATTR_ITEM_KEY;
478         key.offset = 0;
479         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
480         if (ret < 0)
481                 goto out;
482
483         leaf = path.nodes[0];
484         while (1) {
485                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
486                         do {
487                                 ret = next_leaf(root, &path);
488                                 if (ret < 0) {
489                                         error("searching for extended attributes: %d\n",
490                                                 ret);
491                                         goto out;
492                                 } else if (ret) {
493                                         /* No more leaves to search */
494                                         ret = 0;
495                                         goto out;
496                                 }
497                                 leaf = path.nodes[0];
498                         } while (!leaf);
499                         continue;
500                 }
501
502                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
503                 if (key.type != BTRFS_XATTR_ITEM_KEY || key.objectid != inode)
504                         break;
505                 cur = 0;
506                 total_len = btrfs_item_size_nr(leaf, path.slots[0]);
507                 di = btrfs_item_ptr(leaf, path.slots[0],
508                                     struct btrfs_dir_item);
509
510                 while (cur < total_len) {
511                         len = btrfs_dir_name_len(leaf, di);
512                         if (len > name_len) {
513                                 free(name);
514                                 name = (char *) malloc(len + 1);
515                                 if (!name) {
516                                         ret = -ENOMEM;
517                                         goto out;
518                                 }
519                         }
520                         read_extent_buffer(leaf, name,
521                                            (unsigned long)(di + 1), len);
522                         name[len] = '\0';
523                         name_len = len;
524
525                         len = btrfs_dir_data_len(leaf, di);
526                         if (len > data_len) {
527                                 free(data);
528                                 data = (char *) malloc(len);
529                                 if (!data) {
530                                         ret = -ENOMEM;
531                                         goto out;
532                                 }
533                         }
534                         read_extent_buffer(leaf, data,
535                                            (unsigned long)(di + 1) + name_len,
536                                            len);
537                         data_len = len;
538
539                         if (fsetxattr(fd, name, data, data_len, 0))
540                                 error("setting extended attribute %s on file %s: %s",
541                                         name, file_name, strerror(errno));
542
543                         len = sizeof(*di) + name_len + data_len;
544                         cur += len;
545                         di = (struct btrfs_dir_item *)((char *)di + len);
546                 }
547                 path.slots[0]++;
548         }
549         ret = 0;
550 out:
551         btrfs_release_path(&path);
552         free(name);
553         free(data);
554
555         return ret;
556 }
557
558 static int copy_metadata(struct btrfs_root *root, int fd,
559                 struct btrfs_key *key)
560 {
561         struct btrfs_path path;
562         struct btrfs_inode_item *inode_item;
563         int ret;
564
565         btrfs_init_path(&path);
566         ret = btrfs_lookup_inode(NULL, root, &path, key, 0);
567         if (ret == 0) {
568                 struct btrfs_timespec *bts;
569                 struct timespec times[2];
570
571                 inode_item = btrfs_item_ptr(path.nodes[0], path.slots[0],
572                                 struct btrfs_inode_item);
573
574                 ret = fchown(fd, btrfs_inode_uid(path.nodes[0], inode_item),
575                                 btrfs_inode_gid(path.nodes[0], inode_item));
576                 if (ret) {
577                         error("failed to change owner: %s", strerror(errno));
578                         goto out;
579                 }
580
581                 ret = fchmod(fd, btrfs_inode_mode(path.nodes[0], inode_item));
582                 if (ret) {
583                         error("failed to change mode: %s", strerror(errno));
584                         goto out;
585                 }
586
587                 bts = btrfs_inode_atime(inode_item);
588                 times[0].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
589                 times[0].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
590
591                 bts = btrfs_inode_mtime(inode_item);
592                 times[1].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
593                 times[1].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
594
595                 ret = futimens(fd, times);
596                 if (ret) {
597                         error("failed to set times: %s", strerror(errno));
598                         goto out;
599                 }
600         }
601 out:
602         btrfs_release_path(&path);
603         return ret;
604 }
605
606 static int copy_file(struct btrfs_root *root, int fd, struct btrfs_key *key,
607                      const char *file)
608 {
609         struct extent_buffer *leaf;
610         struct btrfs_path *path;
611         struct btrfs_file_extent_item *fi;
612         struct btrfs_inode_item *inode_item;
613         struct btrfs_timespec *bts;
614         struct btrfs_key found_key;
615         int ret;
616         int extent_type;
617         int compression;
618         int loops = 0;
619         u64 found_size = 0;
620         struct timespec times[2];
621         int times_ok = 0;
622
623         path = btrfs_alloc_path();
624         if (!path) {
625                 error("not enough memory");
626                 return -ENOMEM;
627         }
628
629         ret = btrfs_lookup_inode(NULL, root, path, key, 0);
630         if (ret == 0) {
631                 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
632                                     struct btrfs_inode_item);
633                 found_size = btrfs_inode_size(path->nodes[0], inode_item);
634
635                 if (restore_metadata) {
636                         /*
637                          * Change the ownership and mode now, set times when
638                          * copyout is finished.
639                          */
640
641                         ret = fchown(fd, btrfs_inode_uid(path->nodes[0], inode_item),
642                                         btrfs_inode_gid(path->nodes[0], inode_item));
643                         if (ret && !ignore_errors)
644                                 goto out;
645
646                         ret = fchmod(fd, btrfs_inode_mode(path->nodes[0], inode_item));
647                         if (ret && !ignore_errors)
648                                 goto out;
649
650                         bts = btrfs_inode_atime(inode_item);
651                         times[0].tv_sec = btrfs_timespec_sec(path->nodes[0], bts);
652                         times[0].tv_nsec = btrfs_timespec_nsec(path->nodes[0], bts);
653
654                         bts = btrfs_inode_mtime(inode_item);
655                         times[1].tv_sec = btrfs_timespec_sec(path->nodes[0], bts);
656                         times[1].tv_nsec = btrfs_timespec_nsec(path->nodes[0], bts);
657                         times_ok = 1;
658                 }
659         }
660         btrfs_release_path(path);
661
662         key->offset = 0;
663         key->type = BTRFS_EXTENT_DATA_KEY;
664
665         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
666         if (ret < 0) {
667                 error("searching extent data returned %d", ret);
668                 goto out;
669         }
670
671         leaf = path->nodes[0];
672         while (!leaf) {
673                 ret = next_leaf(root, path);
674                 if (ret < 0) {
675                         error("cannot get next leaf: %d", ret);
676                         goto out;
677                 } else if (ret > 0) {
678                         /* No more leaves to search */
679                         ret = 0;
680                         goto out;
681                 }
682                 leaf = path->nodes[0];
683         }
684
685         while (1) {
686                 if (loops >= 0 && loops++ >= 1024) {
687                         enum loop_response resp;
688
689                         resp = ask_to_continue(file);
690                         if (resp == LOOP_STOP)
691                                 break;
692                         else if (resp == LOOP_CONTINUE)
693                                 loops = 0;
694                         else if (resp == LOOP_DONTASK)
695                                 loops = -1;
696                 }
697                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
698                         do {
699                                 ret = next_leaf(root, path);
700                                 if (ret < 0) {
701                                         fprintf(stderr, "Error searching %d\n", ret);
702                                         goto out;
703                                 } else if (ret) {
704                                         /* No more leaves to search */
705                                         btrfs_free_path(path);
706                                         goto set_size;
707                                 }
708                                 leaf = path->nodes[0];
709                         } while (!leaf);
710                         continue;
711                 }
712                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
713                 if (found_key.objectid != key->objectid)
714                         break;
715                 if (found_key.type != key->type)
716                         break;
717                 fi = btrfs_item_ptr(leaf, path->slots[0],
718                                     struct btrfs_file_extent_item);
719                 extent_type = btrfs_file_extent_type(leaf, fi);
720                 compression = btrfs_file_extent_compression(leaf, fi);
721                 if (compression >= BTRFS_COMPRESS_LAST) {
722                         warning("compression type %d not supported",
723                                 compression);
724                         ret = -1;
725                         goto out;
726                 }
727
728                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC)
729                         goto next;
730                 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
731                         ret = copy_one_inline(root, fd, path, found_key.offset);
732                         if (ret)
733                                 goto out;
734                 } else if (extent_type == BTRFS_FILE_EXTENT_REG) {
735                         ret = copy_one_extent(root, fd, leaf, fi,
736                                               found_key.offset);
737                         if (ret)
738                                 goto out;
739                 } else {
740                         warning("weird extent type %d", extent_type);
741                 }
742 next:
743                 path->slots[0]++;
744         }
745
746         btrfs_free_path(path);
747 set_size:
748         if (found_size) {
749                 ret = ftruncate(fd, (loff_t)found_size);
750                 if (ret)
751                         return ret;
752         }
753         if (get_xattrs) {
754                 ret = set_file_xattrs(root, key->objectid, fd, file);
755                 if (ret)
756                         return ret;
757         }
758         if (restore_metadata && times_ok) {
759                 ret = futimens(fd, times);
760                 if (ret)
761                         return ret;
762         }
763         return 0;
764
765 out:
766         btrfs_free_path(path);
767         return ret;
768 }
769
770 /*
771  * returns:
772  *  0 if the file exists and should be skipped.
773  *  1 if the file does NOT exist
774  *  2 if the file exists but is OK to overwrite
775  */
776 static int overwrite_ok(const char * path)
777 {
778         static int warn = 0;
779         struct stat st;
780         int ret;
781
782         /* don't be fooled by symlinks */
783         ret = fstatat(-1, path_name, &st, AT_SYMLINK_NOFOLLOW);
784
785         if (!ret) {
786                 if (overwrite)
787                         return 2;
788
789                 if (verbose || !warn)
790                         printf("Skipping existing file"
791                                    " %s\n", path);
792                 if (!warn)
793                         printf("If you wish to overwrite use -o\n");
794                 warn = 1;
795                 return 0;
796         }
797         return 1;
798 }
799
800 static int copy_symlink(struct btrfs_root *root, struct btrfs_key *key,
801                      const char *file)
802 {
803         struct btrfs_path *path;
804         struct extent_buffer *leaf;
805         struct btrfs_file_extent_item *extent_item;
806         struct btrfs_inode_item *inode_item;
807         u32 len;
808         u32 name_offset;
809         int ret;
810         struct btrfs_timespec *bts;
811         struct timespec times[2];
812
813         ret = overwrite_ok(path_name);
814         if (ret == 0)
815             return 0; /* skip this file */
816
817         /* symlink() can't overwrite, so unlink first */
818         if (ret == 2) {
819                 ret = unlink(path_name);
820                 if (ret) {
821                         fprintf(stderr, "failed to unlink '%s' for overwrite\n",
822                                         path_name);
823                         return ret;
824                 }
825         }
826
827         key->type = BTRFS_EXTENT_DATA_KEY;
828         key->offset = 0;
829
830         path = btrfs_alloc_path();
831         if (!path)
832                 return -ENOMEM;
833
834         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
835         if (ret < 0)
836                 goto out;
837
838         leaf = path->nodes[0];
839         if (!leaf) {
840                 fprintf(stderr, "Error getting leaf for symlink '%s'\n", file);
841                 ret = -1;
842                 goto out;
843         }
844
845         extent_item = btrfs_item_ptr(leaf, path->slots[0],
846                         struct btrfs_file_extent_item);
847
848         len = btrfs_file_extent_inline_item_len(leaf,
849                         btrfs_item_nr(path->slots[0]));
850         if (len >= PATH_MAX) {
851                 fprintf(stderr, "Symlink '%s' target length %d is longer than PATH_MAX\n",
852                                 fs_name, len);
853                 ret = -1;
854                 goto out;
855         }
856
857         name_offset = (unsigned long) extent_item
858                         + offsetof(struct btrfs_file_extent_item, disk_bytenr);
859         read_extent_buffer(leaf, symlink_target, name_offset, len);
860
861         symlink_target[len] = 0;
862
863         if (!dry_run) {
864                 ret = symlink(symlink_target, path_name);
865                 if (ret < 0) {
866                         fprintf(stderr, "Failed to restore symlink '%s': %s\n",
867                                         path_name, strerror(errno));
868                         goto out;
869                 }
870         }
871         printf("SYMLINK: '%s' => '%s'\n", path_name, symlink_target);
872
873         ret = 0;
874         if (!restore_metadata)
875                 goto out;
876
877         /*
878          * Symlink metadata operates differently than files/directories, so do
879          * our own work here.
880          */
881         key->type = BTRFS_INODE_ITEM_KEY;
882         key->offset = 0;
883
884         btrfs_release_path(path);
885
886         ret = btrfs_lookup_inode(NULL, root, path, key, 0);
887         if (ret) {
888                 fprintf(stderr, "Failed to lookup inode for '%s'\n", file);
889                 goto out;
890         }
891
892         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
893                         struct btrfs_inode_item);
894
895         ret = fchownat(-1, file, btrfs_inode_uid(path->nodes[0], inode_item),
896                                    btrfs_inode_gid(path->nodes[0], inode_item),
897                                    AT_SYMLINK_NOFOLLOW);
898         if (ret) {
899                 fprintf(stderr, "Failed to change owner: %s\n",
900                                 strerror(errno));
901                 goto out;
902         }
903
904         bts = btrfs_inode_atime(inode_item);
905         times[0].tv_sec  = btrfs_timespec_sec(path->nodes[0], bts);
906         times[0].tv_nsec = btrfs_timespec_nsec(path->nodes[0], bts);
907
908         bts = btrfs_inode_mtime(inode_item);
909         times[1].tv_sec  = btrfs_timespec_sec(path->nodes[0], bts);
910         times[1].tv_nsec = btrfs_timespec_nsec(path->nodes[0], bts);
911
912         ret = utimensat(-1, file, times, AT_SYMLINK_NOFOLLOW);
913         if (ret)
914                 fprintf(stderr, "Failed to set times: %s\n", strerror(errno));
915 out:
916         btrfs_free_path(path);
917         return ret;
918 }
919
920 static int search_dir(struct btrfs_root *root, struct btrfs_key *key,
921                       const char *output_rootdir, const char *in_dir,
922                       const regex_t *mreg)
923 {
924         struct btrfs_path *path;
925         struct extent_buffer *leaf;
926         struct btrfs_dir_item *dir_item;
927         struct btrfs_key found_key, location;
928         char filename[BTRFS_NAME_LEN + 1];
929         unsigned long name_ptr;
930         int name_len;
931         int ret = 0;
932         int fd;
933         int loops = 0;
934         u8 type;
935
936         path = btrfs_alloc_path();
937         if (!path) {
938                 fprintf(stderr, "Ran out of memory\n");
939                 return -ENOMEM;
940         }
941
942         key->offset = 0;
943         key->type = BTRFS_DIR_INDEX_KEY;
944
945         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
946         if (ret < 0) {
947                 fprintf(stderr, "Error searching %d\n", ret);
948                 goto out;
949         }
950
951         ret = 0;
952
953         leaf = path->nodes[0];
954         while (!leaf) {
955                 if (verbose > 1)
956                         printf("No leaf after search, looking for the next "
957                                "leaf\n");
958                 ret = next_leaf(root, path);
959                 if (ret < 0) {
960                         fprintf(stderr, "Error getting next leaf %d\n",
961                                 ret);
962                         goto out;
963                 } else if (ret > 0) {
964                         /* No more leaves to search */
965                         if (verbose)
966                                 printf("Reached the end of the tree looking "
967                                        "for the directory\n");
968                         ret = 0;
969                         goto out;
970                 }
971                 leaf = path->nodes[0];
972         }
973
974         while (leaf) {
975                 if (loops++ >= 1024) {
976                         printf("We have looped trying to restore files in %s "
977                                "too many times to be making progress, "
978                                "stopping\n", in_dir);
979                         break;
980                 }
981
982                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
983                         do {
984                                 ret = next_leaf(root, path);
985                                 if (ret < 0) {
986                                         fprintf(stderr, "Error searching %d\n",
987                                                 ret);
988                                         goto out;
989                                 } else if (ret > 0) {
990                                         /* No more leaves to search */
991                                         if (verbose)
992                                                 printf("Reached the end of "
993                                                        "the tree searching the"
994                                                        " directory\n");
995                                         ret = 0;
996                                         goto out;
997                                 }
998                                 leaf = path->nodes[0];
999                         } while (!leaf);
1000                         continue;
1001                 }
1002                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1003                 if (found_key.objectid != key->objectid) {
1004                         if (verbose > 1)
1005                                 printf("Found objectid=%Lu, key=%Lu\n",
1006                                        found_key.objectid, key->objectid);
1007                         break;
1008                 }
1009                 if (found_key.type != key->type) {
1010                         if (verbose > 1)
1011                                 printf("Found type=%u, want=%u\n",
1012                                        found_key.type, key->type);
1013                         break;
1014                 }
1015                 dir_item = btrfs_item_ptr(leaf, path->slots[0],
1016                                           struct btrfs_dir_item);
1017                 name_ptr = (unsigned long)(dir_item + 1);
1018                 name_len = btrfs_dir_name_len(leaf, dir_item);
1019                 read_extent_buffer(leaf, filename, name_ptr, name_len);
1020                 filename[name_len] = '\0';
1021                 type = btrfs_dir_type(leaf, dir_item);
1022                 btrfs_dir_item_key_to_cpu(leaf, dir_item, &location);
1023
1024                 /* full path from root of btrfs being restored */
1025                 snprintf(fs_name, PATH_MAX, "%s/%s", in_dir, filename);
1026
1027                 if (mreg && REG_NOMATCH == regexec(mreg, fs_name, 0, NULL, 0))
1028                         goto next;
1029
1030                 /* full path from system root */
1031                 snprintf(path_name, PATH_MAX, "%s%s", output_rootdir, fs_name);
1032
1033                 /*
1034                  * Restore directories, files, symlinks and metadata.
1035                  */
1036                 if (type == BTRFS_FT_REG_FILE) {
1037                         if (!overwrite_ok(path_name))
1038                                 goto next;
1039
1040                         if (verbose)
1041                                 printf("Restoring %s\n", path_name);
1042                         if (dry_run)
1043                                 goto next;
1044                         fd = open(path_name, O_CREAT|O_WRONLY, 0644);
1045                         if (fd < 0) {
1046                                 fprintf(stderr, "Error creating %s: %d\n",
1047                                         path_name, errno);
1048                                 if (ignore_errors)
1049                                         goto next;
1050                                 ret = -1;
1051                                 goto out;
1052                         }
1053                         loops = 0;
1054                         ret = copy_file(root, fd, &location, path_name);
1055                         close(fd);
1056                         if (ret) {
1057                                 fprintf(stderr, "Error copying data for %s\n",
1058                                         path_name);
1059                                 if (ignore_errors)
1060                                         goto next;
1061                                 goto out;
1062                         }
1063                 } else if (type == BTRFS_FT_DIR) {
1064                         struct btrfs_root *search_root = root;
1065                         char *dir = strdup(fs_name);
1066
1067                         if (!dir) {
1068                                 fprintf(stderr, "Ran out of memory\n");
1069                                 ret = -ENOMEM;
1070                                 goto out;
1071                         }
1072
1073                         if (location.type == BTRFS_ROOT_ITEM_KEY) {
1074                                 /*
1075                                  * If we are a snapshot and this is the index
1076                                  * object to ourselves just skip it.
1077                                  */
1078                                 if (location.objectid ==
1079                                     root->root_key.objectid) {
1080                                         free(dir);
1081                                         goto next;
1082                                 }
1083
1084                                 location.offset = (u64)-1;
1085                                 search_root = btrfs_read_fs_root(root->fs_info,
1086                                                                  &location);
1087                                 if (IS_ERR(search_root)) {
1088                                         free(dir);
1089                                         fprintf(stderr, "Error reading "
1090                                                 "subvolume %s: %lu\n",
1091                                                 path_name,
1092                                                 PTR_ERR(search_root));
1093                                         if (ignore_errors)
1094                                                 goto next;
1095                                         ret = PTR_ERR(search_root);
1096                                         goto out;
1097                                 }
1098
1099                                 /*
1100                                  * A subvolume will have a key.offset of 0, a
1101                                  * snapshot will have key.offset of a transid.
1102                                  */
1103                                 if (search_root->root_key.offset != 0 &&
1104                                     get_snaps == 0) {
1105                                         free(dir);
1106                                         printf("Skipping snapshot %s\n",
1107                                                filename);
1108                                         goto next;
1109                                 }
1110                                 location.objectid = BTRFS_FIRST_FREE_OBJECTID;
1111                         }
1112
1113                         if (verbose)
1114                                 printf("Restoring %s\n", path_name);
1115
1116                         errno = 0;
1117                         if (dry_run)
1118                                 ret = 0;
1119                         else
1120                                 ret = mkdir(path_name, 0755);
1121                         if (ret && errno != EEXIST) {
1122                                 free(dir);
1123                                 fprintf(stderr, "Error mkdiring %s: %d\n",
1124                                         path_name, errno);
1125                                 if (ignore_errors)
1126                                         goto next;
1127                                 ret = -1;
1128                                 goto out;
1129                         }
1130                         loops = 0;
1131                         ret = search_dir(search_root, &location,
1132                                          output_rootdir, dir, mreg);
1133                         free(dir);
1134                         if (ret) {
1135                                 fprintf(stderr, "Error searching %s\n",
1136                                         path_name);
1137                                 if (ignore_errors)
1138                                         goto next;
1139                                 goto out;
1140                         }
1141                 } else if (type == BTRFS_FT_SYMLINK) {
1142                         if (restore_symlinks)
1143                                 ret = copy_symlink(root, &location, path_name);
1144                         if (ret < 0) {
1145                                 if (ignore_errors)
1146                                         goto next;
1147                                 btrfs_free_path(path);
1148                                 return ret;
1149                         }
1150                 }
1151 next:
1152                 path->slots[0]++;
1153         }
1154
1155         if (restore_metadata) {
1156                 snprintf(path_name, PATH_MAX, "%s%s", output_rootdir, in_dir);
1157                 fd = open(path_name, O_RDONLY);
1158                 if (fd < 0) {
1159                         fprintf(stderr, "ERROR: Failed to access %s to restore metadata\n",
1160                                         path_name);
1161                         if (!ignore_errors) {
1162                                 ret = -1;
1163                                 goto out;
1164                         }
1165                 } else {
1166                         /*
1167                          * Set owner/mode/time on the directory as well
1168                          */
1169                         key->type = BTRFS_INODE_ITEM_KEY;
1170                         ret = copy_metadata(root, fd, key);
1171                         close(fd);
1172                         if (ret && !ignore_errors)
1173                                 goto out;
1174                 }
1175         }
1176
1177         if (verbose)
1178                 printf("Done searching %s\n", in_dir);
1179 out:
1180         btrfs_free_path(path);
1181         return ret;
1182 }
1183
1184 static int do_list_roots(struct btrfs_root *root)
1185 {
1186         struct btrfs_key key;
1187         struct btrfs_key found_key;
1188         struct btrfs_disk_key disk_key;
1189         struct btrfs_path *path;
1190         struct extent_buffer *leaf;
1191         struct btrfs_root_item ri;
1192         unsigned long offset;
1193         int slot;
1194         int ret;
1195
1196         root = root->fs_info->tree_root;
1197         path = btrfs_alloc_path();
1198         if (!path) {
1199                 fprintf(stderr, "Failed to alloc path\n");
1200                 return -ENOMEM;
1201         }
1202
1203         key.offset = 0;
1204         key.objectid = 0;
1205         key.type = BTRFS_ROOT_ITEM_KEY;
1206
1207         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1208         if (ret < 0) {
1209                 fprintf(stderr, "Failed to do search %d\n", ret);
1210                 btrfs_free_path(path);
1211                 return -1;
1212         }
1213
1214         leaf = path->nodes[0];
1215
1216         while (1) {
1217                 slot = path->slots[0];
1218                 if (slot >= btrfs_header_nritems(leaf)) {
1219                         ret = btrfs_next_leaf(root, path);
1220                         if (ret)
1221                                 break;
1222                         leaf = path->nodes[0];
1223                         slot = path->slots[0];
1224                 }
1225                 btrfs_item_key(leaf, &disk_key, slot);
1226                 btrfs_disk_key_to_cpu(&found_key, &disk_key);
1227                 if (found_key.type != BTRFS_ROOT_ITEM_KEY) {
1228                         path->slots[0]++;
1229                         continue;
1230                 }
1231
1232                 offset = btrfs_item_ptr_offset(leaf, slot);
1233                 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
1234                 printf(" tree ");
1235                 btrfs_print_key(&disk_key);
1236                 printf(" %Lu level %d\n", btrfs_root_bytenr(&ri),
1237                        btrfs_root_level(&ri));
1238                 path->slots[0]++;
1239         }
1240         btrfs_free_path(path);
1241
1242         return 0;
1243 }
1244
1245 static struct btrfs_root *open_fs(const char *dev, u64 root_location,
1246                                   int super_mirror, int list_roots)
1247 {
1248         struct btrfs_fs_info *fs_info = NULL;
1249         struct btrfs_root *root = NULL;
1250         u64 bytenr;
1251         int i;
1252
1253         for (i = super_mirror; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1254                 bytenr = btrfs_sb_offset(i);
1255                 fs_info = open_ctree_fs_info(dev, bytenr, root_location, 0,
1256                                              OPEN_CTREE_PARTIAL);
1257                 if (fs_info)
1258                         break;
1259                 fprintf(stderr, "Could not open root, trying backup super\n");
1260         }
1261
1262         if (!fs_info)
1263                 return NULL;
1264
1265         /*
1266          * All we really need to succeed is reading the chunk tree, everything
1267          * else we can do by hand, since we only need to read the tree root and
1268          * the fs_root.
1269          */
1270         if (!extent_buffer_uptodate(fs_info->tree_root->node)) {
1271                 u64 generation;
1272
1273                 root = fs_info->tree_root;
1274                 if (!root_location)
1275                         root_location = btrfs_super_root(fs_info->super_copy);
1276                 generation = btrfs_super_generation(fs_info->super_copy);
1277                 root->node = read_tree_block(root, root_location,
1278                                              root->nodesize, generation);
1279                 if (!extent_buffer_uptodate(root->node)) {
1280                         fprintf(stderr, "Error opening tree root\n");
1281                         close_ctree(root);
1282                         return NULL;
1283                 }
1284         }
1285
1286         if (!list_roots && !fs_info->fs_root) {
1287                 struct btrfs_key key;
1288
1289                 key.objectid = BTRFS_FS_TREE_OBJECTID;
1290                 key.type = BTRFS_ROOT_ITEM_KEY;
1291                 key.offset = (u64)-1;
1292                 fs_info->fs_root = btrfs_read_fs_root_no_cache(fs_info, &key);
1293                 if (IS_ERR(fs_info->fs_root)) {
1294                         fprintf(stderr, "Couldn't read fs root: %ld\n",
1295                                 PTR_ERR(fs_info->fs_root));
1296                         close_ctree(fs_info->tree_root);
1297                         return NULL;
1298                 }
1299         }
1300
1301         if (list_roots && do_list_roots(fs_info->tree_root)) {
1302                 close_ctree(fs_info->tree_root);
1303                 return NULL;
1304         }
1305
1306         return fs_info->fs_root;
1307 }
1308
1309 static int find_first_dir(struct btrfs_root *root, u64 *objectid)
1310 {
1311         struct btrfs_path *path;
1312         struct btrfs_key found_key;
1313         struct btrfs_key key;
1314         int ret = -1;
1315         int i;
1316
1317         key.objectid = 0;
1318         key.type = BTRFS_DIR_INDEX_KEY;
1319         key.offset = 0;
1320
1321         path = btrfs_alloc_path();
1322         if (!path) {
1323                 fprintf(stderr, "Ran out of memory\n");
1324                 return ret;
1325         }
1326
1327         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1328         if (ret < 0) {
1329                 fprintf(stderr, "Error searching %d\n", ret);
1330                 goto out;
1331         }
1332
1333         if (!path->nodes[0]) {
1334                 fprintf(stderr, "No leaf!\n");
1335                 goto out;
1336         }
1337 again:
1338         for (i = path->slots[0];
1339              i < btrfs_header_nritems(path->nodes[0]); i++) {
1340                 btrfs_item_key_to_cpu(path->nodes[0], &found_key, i);
1341                 if (found_key.type != key.type)
1342                         continue;
1343
1344                 printf("Using objectid %Lu for first dir\n",
1345                        found_key.objectid);
1346                 *objectid = found_key.objectid;
1347                 ret = 0;
1348                 goto out;
1349         }
1350         do {
1351                 ret = next_leaf(root, path);
1352                 if (ret < 0) {
1353                         fprintf(stderr, "Error getting next leaf %d\n",
1354                                 ret);
1355                         goto out;
1356                 } else if (ret > 0) {
1357                         fprintf(stderr, "No more leaves\n");
1358                         goto out;
1359                 }
1360         } while (!path->nodes[0]);
1361         if (path->nodes[0])
1362                 goto again;
1363         printf("Couldn't find a dir index item\n");
1364 out:
1365         btrfs_free_path(path);
1366         return ret;
1367 }
1368
1369 const char * const cmd_restore_usage[] = {
1370         "btrfs restore [options] <device> <path> | -l <device>",
1371         "Try to restore files from a damaged filesystem (unmounted)",
1372         "",
1373         "-s|--snapshots       get snapshots",
1374         "-x|--xattr           restore extended attributes",
1375         "-m|--metadata        restore owner, mode and times",
1376         "-S|--symlink         restore symbolic links",
1377         "-v|--verbose         verbose",
1378         "-i|--ignore-errors   ignore errors",
1379         "-o|--overwrite       overwrite",
1380         "-t <bytenr>          tree location",
1381         "-f <bytenr>          filesystem location",
1382         "-u|--super <mirror>  super mirror",
1383         "-r|--root <rootid>   root objectid",
1384         "-d                   find dir",
1385         "-l|--list-roots      list tree roots",
1386         "-D|--dry-run         dry run (only list files that would be recovered)",
1387         "--path-regex <regex>",
1388         "                     restore only filenames matching regex,",
1389         "                     you have to use following syntax (possibly quoted):",
1390         "                     ^/(|home(|/username(|/Desktop(|/.*))))$",
1391         "-c                   ignore case (--path-regex only)",
1392         NULL
1393 };
1394
1395 int cmd_restore(int argc, char **argv)
1396 {
1397         struct btrfs_root *root;
1398         struct btrfs_key key;
1399         char dir_name[PATH_MAX];
1400         u64 tree_location = 0;
1401         u64 fs_location = 0;
1402         u64 root_objectid = 0;
1403         int len;
1404         int ret;
1405         int super_mirror = 0;
1406         int find_dir = 0;
1407         int list_roots = 0;
1408         const char *match_regstr = NULL;
1409         int match_cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
1410         regex_t match_reg, *mreg = NULL;
1411         char reg_err[256];
1412
1413         while (1) {
1414                 int opt;
1415                 enum { GETOPT_VAL_PATH_REGEX = 256 };
1416                 static const struct option long_options[] = {
1417                         { "path-regex", required_argument, NULL,
1418                                 GETOPT_VAL_PATH_REGEX },
1419                         { "dry-run", no_argument, NULL, 'D'},
1420                         { "metadata", no_argument, NULL, 'm'},
1421                         { "symlinks", no_argument, NULL, 'S'},
1422                         { "snapshots", no_argument, NULL, 's'},
1423                         { "xattr", no_argument, NULL, 'x'},
1424                         { "verbose", no_argument, NULL, 'v'},
1425                         { "ignore-errors", no_argument, NULL, 'i'},
1426                         { "overwrite", no_argument, NULL, 'o'},
1427                         { "super", required_argument, NULL, 'u'},
1428                         { "root", required_argument, NULL, 'r'},
1429                         { "list-roots", no_argument, NULL, 'l'},
1430                         { NULL, 0, NULL, 0}
1431                 };
1432
1433                 opt = getopt_long(argc, argv, "sSxviot:u:dmf:r:lDc", long_options,
1434                                         NULL);
1435                 if (opt < 0)
1436                         break;
1437
1438                 switch (opt) {
1439                         case 's':
1440                                 get_snaps = 1;
1441                                 break;
1442                         case 'v':
1443                                 verbose++;
1444                                 break;
1445                         case 'i':
1446                                 ignore_errors = 1;
1447                                 break;
1448                         case 'o':
1449                                 overwrite = 1;
1450                                 break;
1451                         case 't':
1452                                 tree_location = arg_strtou64(optarg);
1453                                 break;
1454                         case 'f':
1455                                 fs_location = arg_strtou64(optarg);
1456                                 break;
1457                         case 'u':
1458                                 super_mirror = arg_strtou64(optarg);
1459                                 if (super_mirror >= BTRFS_SUPER_MIRROR_MAX) {
1460                                         fprintf(stderr, "Super mirror not "
1461                                                 "valid\n");
1462                                         exit(1);
1463                                 }
1464                                 break;
1465                         case 'd':
1466                                 find_dir = 1;
1467                                 break;
1468                         case 'r':
1469                                 root_objectid = arg_strtou64(optarg);
1470                                 if (!is_fstree(root_objectid)) {
1471                                         fprintf(stderr, "objectid %llu is not a valid fs/file tree\n",
1472                                                         root_objectid);
1473                                         exit(1);
1474                                 }
1475                                 break;
1476                         case 'l':
1477                                 list_roots = 1;
1478                                 break;
1479                         case 'm':
1480                                 restore_metadata = 1;
1481                                 break;
1482                         case 'S':
1483                                 restore_symlinks = 1;
1484                                 break;
1485                         case 'D':
1486                                 dry_run = 1;
1487                                 break;
1488                         case 'c':
1489                                 match_cflags |= REG_ICASE;
1490                                 break;
1491                         case GETOPT_VAL_PATH_REGEX:
1492                                 match_regstr = optarg;
1493                                 break;
1494                         case 'x':
1495                                 get_xattrs = 1;
1496                                 break;
1497                         default:
1498                                 usage(cmd_restore_usage);
1499                 }
1500         }
1501
1502         if (!list_roots && check_argc_min(argc - optind, 2))
1503                 usage(cmd_restore_usage);
1504         else if (list_roots && check_argc_min(argc - optind, 1))
1505                 usage(cmd_restore_usage);
1506
1507         if (fs_location && root_objectid) {
1508                 fprintf(stderr, "don't use -f and -r at the same time.\n");
1509                 return 1;
1510         }
1511
1512         if ((ret = check_mounted(argv[optind])) < 0) {
1513                 fprintf(stderr, "Could not check mount status: %s\n",
1514                         strerror(-ret));
1515                 return 1;
1516         } else if (ret) {
1517                 fprintf(stderr, "%s is currently mounted.  Aborting.\n", argv[optind]);
1518                 return 1;
1519         }
1520
1521         root = open_fs(argv[optind], tree_location, super_mirror, list_roots);
1522         if (root == NULL)
1523                 return 1;
1524
1525         if (list_roots)
1526                 goto out;
1527
1528         if (fs_location != 0) {
1529                 free_extent_buffer(root->node);
1530                 root->node = read_tree_block(root, fs_location, root->nodesize, 0);
1531                 if (!extent_buffer_uptodate(root->node)) {
1532                         fprintf(stderr, "Failed to read fs location\n");
1533                         ret = 1;
1534                         goto out;
1535                 }
1536         }
1537
1538         memset(path_name, 0, PATH_MAX);
1539
1540         if (strlen(argv[optind + 1]) >= PATH_MAX) {
1541                 fprintf(stderr, "ERROR: path too long\n");
1542                 ret = 1;
1543                 goto out;
1544         }
1545         strncpy(dir_name, argv[optind + 1], sizeof dir_name);
1546         dir_name[sizeof dir_name - 1] = 0;
1547
1548         /* Strip the trailing / on the dir name */
1549         len = strlen(dir_name);
1550         while (len && dir_name[--len] == '/') {
1551                 dir_name[len] = '\0';
1552         }
1553
1554         if (root_objectid != 0) {
1555                 struct btrfs_root *orig_root = root;
1556
1557                 key.objectid = root_objectid;
1558                 key.type = BTRFS_ROOT_ITEM_KEY;
1559                 key.offset = (u64)-1;
1560                 root = btrfs_read_fs_root(orig_root->fs_info, &key);
1561                 if (IS_ERR(root)) {
1562                         fprintf(stderr, "fail to read root %llu: %s\n",
1563                                         root_objectid, strerror(-PTR_ERR(root)));
1564                         root = orig_root;
1565                         ret = 1;
1566                         goto out;
1567                 }
1568                 key.type = 0;
1569                 key.offset = 0;
1570         }
1571
1572         if (find_dir) {
1573                 ret = find_first_dir(root, &key.objectid);
1574                 if (ret)
1575                         goto out;
1576         } else {
1577                 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
1578         }
1579
1580         if (match_regstr) {
1581                 ret = regcomp(&match_reg, match_regstr, match_cflags);
1582                 if (ret) {
1583                         regerror(ret, &match_reg, reg_err, sizeof(reg_err));
1584                         fprintf(stderr, "Regex compile failed: %s\n", reg_err);
1585                         goto out;
1586                 }
1587                 mreg = &match_reg;
1588         }
1589
1590         if (dry_run)
1591                 printf("This is a dry-run, no files are going to be restored\n");
1592
1593         ret = search_dir(root, &key, dir_name, "", mreg);
1594
1595 out:
1596         if (mreg)
1597                 regfree(mreg);
1598         close_ctree(root);
1599         return !!ret;
1600 }