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