btrfs-progs: Fix error handling for failed reads in restore tool when mirrors exist
[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 #define _XOPEN_SOURCE 500
20 #define _GNU_SOURCE 1
21
22 #include "kerncompat.h"
23
24 #include <ctype.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <sys/stat.h>
30 #include <zlib.h>
31
32 #include "ctree.h"
33 #include "disk-io.h"
34 #include "print-tree.h"
35 #include "transaction.h"
36 #include "list.h"
37 #include "version.h"
38 #include "volumes.h"
39 #include "utils.h"
40 #include "commands.h"
41
42 static char path_name[4096];
43 static int get_snaps = 0;
44 static int verbose = 0;
45 static int ignore_errors = 0;
46 static int overwrite = 0;
47
48 static int decompress(char *inbuf, char *outbuf, u64 compress_len,
49                       u64 decompress_len)
50 {
51         z_stream strm;
52         int ret;
53
54         memset(&strm, 0, sizeof(strm));
55         ret = inflateInit(&strm);
56         if (ret != Z_OK) {
57                 fprintf(stderr, "inflate init returnd %d\n", ret);
58                 return -1;
59         }
60
61         strm.avail_in = compress_len;
62         strm.next_in = (unsigned char *)inbuf;
63         strm.avail_out = decompress_len;
64         strm.next_out = (unsigned char *)outbuf;
65         ret = inflate(&strm, Z_NO_FLUSH);
66         if (ret != Z_STREAM_END) {
67                 (void)inflateEnd(&strm);
68                 fprintf(stderr, "failed to inflate: %d\n", ret);
69                 return -1;
70         }
71
72         (void)inflateEnd(&strm);
73         return 0;
74 }
75
76 int next_leaf(struct btrfs_root *root, struct btrfs_path *path)
77 {
78         int slot;
79         int level = 1;
80         struct extent_buffer *c;
81         struct extent_buffer *next = NULL;
82
83         for (; level < BTRFS_MAX_LEVEL; level++) {
84                 if (path->nodes[level])
85                         break;
86         }
87
88         if (level == BTRFS_MAX_LEVEL)
89                 return 1;
90
91         slot = path->slots[level] + 1;
92
93         while(level < BTRFS_MAX_LEVEL) {
94                 if (!path->nodes[level])
95                         return 1;
96
97                 slot = path->slots[level] + 1;
98                 c = path->nodes[level];
99                 if (slot >= btrfs_header_nritems(c)) {
100                         level++;
101                         if (level == BTRFS_MAX_LEVEL)
102                                 return 1;
103                         continue;
104                 }
105
106                 if (path->reada)
107                         reada_for_search(root, path, level, slot, 0);
108
109                 next = read_node_slot(root, c, slot);
110                 break;
111         }
112         path->slots[level] = slot;
113         while(1) {
114                 level--;
115                 c = path->nodes[level];
116                 free_extent_buffer(c);
117                 path->nodes[level] = next;
118                 path->slots[level] = 0;
119                 if (!level)
120                         break;
121                 if (path->reada)
122                         reada_for_search(root, path, level, 0, 0);
123                 next = read_node_slot(root, next, 0);
124         }
125         return 0;
126 }
127
128 static int copy_one_inline(int fd, struct btrfs_path *path, u64 pos)
129 {
130         struct extent_buffer *leaf = path->nodes[0];
131         struct btrfs_file_extent_item *fi;
132         char buf[4096];
133         char *outbuf;
134         ssize_t done;
135         unsigned long ptr;
136         int ret;
137         int len;
138         int ram_size;
139         int compress;
140
141         fi = btrfs_item_ptr(leaf, path->slots[0],
142                             struct btrfs_file_extent_item);
143         ptr = btrfs_file_extent_inline_start(fi);
144         len = btrfs_file_extent_inline_item_len(leaf,
145                                         btrfs_item_nr(leaf, path->slots[0]));
146         read_extent_buffer(leaf, buf, ptr, len);
147
148         compress = btrfs_file_extent_compression(leaf, fi);
149         if (compress == BTRFS_COMPRESS_NONE) {
150                 done = pwrite(fd, buf, len, pos);
151                 if (done < len) {
152                         fprintf(stderr, "Short inline write, wanted %d, did "
153                                 "%zd: %d\n", len, done, errno);
154                         return -1;
155                 }
156                 return 0;
157         }
158
159         ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
160         outbuf = malloc(ram_size);
161         if (!outbuf) {
162                 fprintf(stderr, "No memory\n");
163                 return -1;
164         }
165
166         ret = decompress(buf, outbuf, len, ram_size);
167         if (ret) {
168                 free(outbuf);
169                 return ret;
170         }
171
172         done = pwrite(fd, outbuf, ram_size, pos);
173         free(outbuf);
174         if (done < ram_size) {
175                 fprintf(stderr, "Short compressed inline write, wanted %d, "
176                         "did %zd: %d\n", ram_size, done, errno);
177                 return -1;
178         }
179
180         return 0;
181 }
182
183 static int copy_one_extent(struct btrfs_root *root, int fd,
184                            struct extent_buffer *leaf,
185                            struct btrfs_file_extent_item *fi, u64 pos)
186 {
187         struct btrfs_multi_bio *multi = NULL;
188         struct btrfs_device *device;
189         char *inbuf, *outbuf = NULL;
190         ssize_t done, total = 0;
191         u64 bytenr;
192         u64 ram_size;
193         u64 disk_size;
194         u64 length;
195         u64 size_left;
196         u64 dev_bytenr;
197         u64 count = 0;
198         int compress;
199         int ret;
200         int dev_fd;
201         int mirror_num = 1;
202         int num_copies;
203
204         compress = btrfs_file_extent_compression(leaf, fi);
205         bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
206         disk_size = btrfs_file_extent_disk_num_bytes(leaf, fi);
207         ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
208         size_left = disk_size;
209
210         /* we found a hole */
211         if (disk_size == 0)
212                 return 0;
213
214         inbuf = malloc(disk_size);
215         if (!inbuf) {
216                 fprintf(stderr, "No memory\n");
217                 return -1;
218         }
219
220         if (compress != BTRFS_COMPRESS_NONE) {
221                 outbuf = malloc(ram_size);
222                 if (!outbuf) {
223                         fprintf(stderr, "No memory\n");
224                         free(inbuf);
225                         return -1;
226                 }
227         }
228 again:
229         length = size_left;
230         ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
231                               bytenr, &length, &multi, mirror_num, NULL);
232         if (ret) {
233                 fprintf(stderr, "Error mapping block %d\n", ret);
234                 goto out;
235         }
236         device = multi->stripes[0].dev;
237         dev_fd = device->fd;
238         device->total_ios++;
239         dev_bytenr = multi->stripes[0].physical;
240         kfree(multi);
241
242         if (size_left < length)
243                 length = size_left;
244
245         done = pread(dev_fd, inbuf+count, length, dev_bytenr);
246         /* Need both checks, or we miss negative values due to u64 conversion */
247         if (done < 0 || done < length) {
248                 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
249                                               bytenr, length);
250                 mirror_num++;
251                 /* mirror_num is 1-indexed, so num_copies is a valid mirror. */
252                 if (mirror_num > num_copies) {
253                         ret = -1;
254                         fprintf(stderr, "Exhausted mirrors trying to read\n");
255                         goto out;
256                 }
257                 fprintf(stderr, "Trying another mirror\n");
258                 goto again;
259         }
260
261         mirror_num = 1;
262         size_left -= length;
263         count += length;
264         bytenr += length;
265         if (size_left)
266                 goto again;
267
268         if (compress == BTRFS_COMPRESS_NONE) {
269                 while (total < ram_size) {
270                         done = pwrite(fd, inbuf+total, ram_size-total,
271                                       pos+total);
272                         if (done < 0) {
273                                 ret = -1;
274                                 fprintf(stderr, "Error writing: %d %s\n", errno, strerror(errno));
275                                 goto out;
276                         }
277                         total += done;
278                 }
279                 ret = 0;
280                 goto out;
281         }
282
283         ret = decompress(inbuf, outbuf, disk_size, ram_size);
284         if (ret) {
285                 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
286                                               bytenr, length);
287                 mirror_num++;
288                 if (mirror_num >= num_copies) {
289                         ret = -1;
290                         goto out;
291                 }
292                 fprintf(stderr, "Trying another mirror\n");
293                 goto again;
294         }
295
296         while (total < ram_size) {
297                 done = pwrite(fd, outbuf+total, ram_size-total, pos+total);
298                 if (done < 0) {
299                         ret = -1;
300                         goto out;
301                 }
302                 total += done;
303         }
304 out:
305         free(inbuf);
306         free(outbuf);
307         return ret;
308 }
309
310 static int ask_to_continue(const char *file)
311 {
312         char buf[2];
313         char *ret;
314
315         printf("We seem to be looping a lot on %s, do you want to keep going "
316                "on ? (y/N): ", file);
317 again:
318         ret = fgets(buf, 2, stdin);
319         if (*ret == '\n' || tolower(*ret) == 'n')
320                 return 1;
321         if (tolower(*ret) != 'y') {
322                 printf("Please enter either 'y' or 'n': ");
323                 goto again;
324         }
325
326         return 0;
327 }
328
329
330 static int copy_file(struct btrfs_root *root, int fd, struct btrfs_key *key,
331                      const char *file)
332 {
333         struct extent_buffer *leaf;
334         struct btrfs_path *path;
335         struct btrfs_file_extent_item *fi;
336         struct btrfs_inode_item *inode_item;
337         struct btrfs_key found_key;
338         int ret;
339         int extent_type;
340         int compression;
341         int loops = 0;
342         u64 found_size = 0;
343
344         path = btrfs_alloc_path();
345         if (!path) {
346                 fprintf(stderr, "Ran out of memory\n");
347                 return -1;
348         }
349         path->skip_locking = 1;
350
351         ret = btrfs_lookup_inode(NULL, root, path, key, 0);
352         if (ret == 0) {
353                 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
354                                     struct btrfs_inode_item);
355                 found_size = btrfs_inode_size(path->nodes[0], inode_item);
356         }
357         btrfs_release_path(root, path);
358
359         key->offset = 0;
360         key->type = BTRFS_EXTENT_DATA_KEY;
361
362         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
363         if (ret < 0) {
364                 fprintf(stderr, "Error searching %d\n", ret);
365                 btrfs_free_path(path);
366                 return ret;
367         }
368
369         leaf = path->nodes[0];
370         while (!leaf) {
371                 ret = next_leaf(root, path);
372                 if (ret < 0) {
373                         fprintf(stderr, "Error getting next leaf %d\n",
374                                 ret);
375                         btrfs_free_path(path);
376                         return ret;
377                 } else if (ret > 0) {
378                         /* No more leaves to search */
379                         btrfs_free_path(path);
380                         return 0;
381                 }
382                 leaf = path->nodes[0];
383         }
384
385         while (1) {
386                 if (loops++ >= 1024) {
387                         ret = ask_to_continue(file);
388                         if (ret)
389                                 break;
390                         loops = 0;
391                 }
392                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
393                         do {
394                                 ret = next_leaf(root, path);
395                                 if (ret < 0) {
396                                         fprintf(stderr, "Error searching %d\n", ret);
397                                         btrfs_free_path(path);
398                                         return ret;
399                                 } else if (ret) {
400                                         /* No more leaves to search */
401                                         btrfs_free_path(path);
402                                         goto set_size;
403                                 }
404                                 leaf = path->nodes[0];
405                         } while (!leaf);
406                         continue;
407                 }
408                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
409                 if (found_key.objectid != key->objectid)
410                         break;
411                 if (found_key.type != key->type)
412                         break;
413                 fi = btrfs_item_ptr(leaf, path->slots[0],
414                                     struct btrfs_file_extent_item);
415                 extent_type = btrfs_file_extent_type(leaf, fi);
416                 compression = btrfs_file_extent_compression(leaf, fi);
417                 if (compression >= BTRFS_COMPRESS_LAST) {
418                         fprintf(stderr, "Don't support compression yet %d\n",
419                                 compression);
420                         btrfs_free_path(path);
421                         return -1;
422                 }
423
424                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC)
425                         goto next;
426                 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
427                         ret = copy_one_inline(fd, path, found_key.offset);
428                         if (ret) {
429                                 btrfs_free_path(path);
430                                 return -1;
431                         }
432                 } else if (extent_type == BTRFS_FILE_EXTENT_REG) {
433                         ret = copy_one_extent(root, fd, leaf, fi,
434                                               found_key.offset);
435                         if (ret) {
436                                 btrfs_free_path(path);
437                                 return ret;
438                         }
439                 } else {
440                         printf("Weird extent type %d\n", extent_type);
441                 }
442 next:
443                 path->slots[0]++;
444         }
445
446         btrfs_free_path(path);
447 set_size:
448         if (found_size) {
449                 ret = ftruncate(fd, (loff_t)found_size);
450                 if (ret)
451                         return ret;
452         }
453         return 0;
454 }
455
456 static int search_dir(struct btrfs_root *root, struct btrfs_key *key,
457                       const char *dir)
458 {
459         struct btrfs_path *path;
460         struct extent_buffer *leaf;
461         struct btrfs_dir_item *dir_item;
462         struct btrfs_key found_key, location;
463         char filename[BTRFS_NAME_LEN + 1];
464         unsigned long name_ptr;
465         int name_len;
466         int ret;
467         int fd;
468         int loops = 0;
469         u8 type;
470
471         path = btrfs_alloc_path();
472         if (!path) {
473                 fprintf(stderr, "Ran out of memory\n");
474                 return -1;
475         }
476         path->skip_locking = 1;
477
478         key->offset = 0;
479         key->type = BTRFS_DIR_INDEX_KEY;
480
481         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
482         if (ret < 0) {
483                 fprintf(stderr, "Error searching %d\n", ret);
484                 btrfs_free_path(path);
485                 return ret;
486         }
487
488         leaf = path->nodes[0];
489         while (!leaf) {
490                 if (verbose > 1)
491                         printf("No leaf after search, looking for the next "
492                                "leaf\n");
493                 ret = next_leaf(root, path);
494                 if (ret < 0) {
495                         fprintf(stderr, "Error getting next leaf %d\n",
496                                 ret);
497                         btrfs_free_path(path);
498                         return ret;
499                 } else if (ret > 0) {
500                         /* No more leaves to search */
501                         if (verbose)
502                                 printf("Reached the end of the tree looking "
503                                        "for the directory\n");
504                         btrfs_free_path(path);
505                         return 0;
506                 }
507                 leaf = path->nodes[0];
508         }
509
510         while (leaf) {
511                 if (loops++ >= 1024) {
512                         printf("We have looped trying to restore files in %s "
513                                "too many times to be making progress, "
514                                "stopping\n", dir);
515                         break;
516                 }
517
518                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
519                         do {
520                                 ret = next_leaf(root, path);
521                                 if (ret < 0) {
522                                         fprintf(stderr, "Error searching %d\n",
523                                                 ret);
524                                         btrfs_free_path(path);
525                                         return ret;
526                                 } else if (ret > 0) {
527                                         /* No more leaves to search */
528                                         if (verbose)
529                                                 printf("Reached the end of "
530                                                        "the tree searching the"
531                                                        " directory\n");
532                                         btrfs_free_path(path);
533                                         return 0;
534                                 }
535                                 leaf = path->nodes[0];
536                         } while (!leaf);
537                         continue;
538                 }
539                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
540                 if (found_key.objectid != key->objectid) {
541                         if (verbose > 1)
542                                 printf("Found objectid=%Lu, key=%Lu\n",
543                                        found_key.objectid, key->objectid);
544                         break;
545                 }
546                 if (found_key.type != key->type) {
547                         if (verbose > 1)
548                                 printf("Found type=%u, want=%u\n",
549                                        found_key.type, key->type);
550                         break;
551                 }
552                 dir_item = btrfs_item_ptr(leaf, path->slots[0],
553                                           struct btrfs_dir_item);
554                 name_ptr = (unsigned long)(dir_item + 1);
555                 name_len = btrfs_dir_name_len(leaf, dir_item);
556                 read_extent_buffer(leaf, filename, name_ptr, name_len);
557                 filename[name_len] = '\0';
558                 type = btrfs_dir_type(leaf, dir_item);
559                 btrfs_dir_item_key_to_cpu(leaf, dir_item, &location);
560
561                 snprintf(path_name, 4096, "%s/%s", dir, filename);
562
563
564                 /*
565                  * At this point we're only going to restore directories and
566                  * files, no symlinks or anything else.
567                  */
568                 if (type == BTRFS_FT_REG_FILE) {
569                         if (!overwrite) {
570                                 static int warn = 0;
571                                 struct stat st;
572
573                                 ret = stat(path_name, &st);
574                                 if (!ret) {
575                                         loops = 0;
576                                         if (verbose || !warn)
577                                                 printf("Skipping existing file"
578                                                        " %s\n", path_name);
579                                         if (warn)
580                                                 goto next;
581                                         printf("If you wish to overwrite use "
582                                                "the -o option to overwrite\n");
583                                         warn = 1;
584                                         goto next;
585                                 }
586                                 ret = 0;
587                         }
588                         if (verbose)
589                                 printf("Restoring %s\n", path_name);
590                         fd = open(path_name, O_CREAT|O_WRONLY, 0644);
591                         if (fd < 0) {
592                                 fprintf(stderr, "Error creating %s: %d\n",
593                                         path_name, errno);
594                                 if (ignore_errors)
595                                         goto next;
596                                 btrfs_free_path(path);
597                                 return -1;
598                         }
599                         loops = 0;
600                         ret = copy_file(root, fd, &location, path_name);
601                         close(fd);
602                         if (ret) {
603                                 if (ignore_errors)
604                                         goto next;
605                                 btrfs_free_path(path);
606                                 return ret;
607                         }
608                 } else if (type == BTRFS_FT_DIR) {
609                         struct btrfs_root *search_root = root;
610                         char *dir = strdup(path_name);
611
612                         if (!dir) {
613                                 fprintf(stderr, "Ran out of memory\n");
614                                 btrfs_free_path(path);
615                                 return -1;
616                         }
617
618                         if (location.type == BTRFS_ROOT_ITEM_KEY) {
619                                 /*
620                                  * If we are a snapshot and this is the index
621                                  * object to ourselves just skip it.
622                                  */
623                                 if (location.objectid ==
624                                     root->root_key.objectid) {
625                                         free(dir);
626                                         goto next;
627                                 }
628
629                                 search_root = btrfs_read_fs_root(root->fs_info,
630                                                                  &location);
631                                 if (IS_ERR(search_root)) {
632                                         free(dir);
633                                         fprintf(stderr, "Error reading "
634                                                 "subvolume %s: %lu\n",
635                                                 path_name,
636                                                 PTR_ERR(search_root));
637                                         if (ignore_errors)
638                                                 goto next;
639                                         btrfs_free_path(path);
640                                         return PTR_ERR(search_root);
641                                 }
642
643                                 /*
644                                  * A subvolume will have a key.offset of 0, a
645                                  * snapshot will have key.offset of a transid.
646                                  */
647                                 if (search_root->root_key.offset != 0 &&
648                                     get_snaps == 0) {
649                                         free(dir);
650                                         printf("Skipping snapshot %s\n",
651                                                filename);
652                                         goto next;
653                                 }
654                                 location.objectid = BTRFS_FIRST_FREE_OBJECTID;
655                         }
656
657                         if (verbose)
658                                 printf("Restoring %s\n", path_name);
659
660                         errno = 0;
661                         ret = mkdir(path_name, 0755);
662                         if (ret && errno != EEXIST) {
663                                 free(dir);
664                                 fprintf(stderr, "Error mkdiring %s: %d\n",
665                                         path_name, errno);
666                                 if (ignore_errors)
667                                         goto next;
668                                 btrfs_free_path(path);
669                                 return -1;
670                         }
671                         loops = 0;
672                         ret = search_dir(search_root, &location, dir);
673                         free(dir);
674                         if (ret) {
675                                 if (ignore_errors)
676                                         goto next;
677                                 btrfs_free_path(path);
678                                 return ret;
679                         }
680                 }
681 next:
682                 path->slots[0]++;
683         }
684
685         if (verbose)
686                 printf("Done searching %s\n", dir);
687         btrfs_free_path(path);
688         return 0;
689 }
690
691 static struct btrfs_root *open_fs(const char *dev, u64 root_location, int super_mirror)
692 {
693         struct btrfs_root *root;
694         u64 bytenr;
695         int i;
696
697         for (i = super_mirror; i < BTRFS_SUPER_MIRROR_MAX; i++) {
698                 bytenr = btrfs_sb_offset(i);
699                 root = open_ctree_recovery(dev, bytenr, root_location);
700                 if (root)
701                         return root;
702                 fprintf(stderr, "Could not open root, trying backup super\n");
703         }
704
705         return NULL;
706 }
707
708 static int find_first_dir(struct btrfs_root *root, u64 *objectid)
709 {
710         struct btrfs_path *path;
711         struct btrfs_key found_key;
712         struct btrfs_key key;
713         int ret = -1;
714         int i;
715
716         key.objectid = 0;
717         key.type = BTRFS_DIR_INDEX_KEY;
718         key.offset = 0;
719
720         path = btrfs_alloc_path();
721         if (!path) {
722                 fprintf(stderr, "Ran out of memory\n");
723                 return ret;
724         }
725
726         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
727         if (ret < 0) {
728                 fprintf(stderr, "Error searching %d\n", ret);
729                 goto out;
730         }
731
732         if (!path->nodes[0]) {
733                 fprintf(stderr, "No leaf!\n");
734                 goto out;
735         }
736 again:
737         for (i = path->slots[0];
738              i < btrfs_header_nritems(path->nodes[0]); i++) {
739                 btrfs_item_key_to_cpu(path->nodes[0], &found_key, i);
740                 if (found_key.type != key.type)
741                         continue;
742
743                 printf("Using objectid %Lu for first dir\n",
744                        found_key.objectid);
745                 *objectid = found_key.objectid;
746                 ret = 0;
747                 goto out;
748         }
749         do {
750                 ret = next_leaf(root, path);
751                 if (ret < 0) {
752                         fprintf(stderr, "Error getting next leaf %d\n",
753                                 ret);
754                         goto out;
755                 } else if (ret > 0) {
756                         fprintf(stderr, "No more leaves\n");
757                         goto out;
758                 }
759         } while (!path->nodes[0]);
760         if (path->nodes[0])
761                 goto again;
762         printf("Couldn't find a dir index item\n");
763 out:
764         btrfs_free_path(path);
765         return ret;
766 }
767
768 const char * const cmd_restore_usage[] = {
769         "btrfs restore [options] <device>",
770         "Try to restore files from a damaged filesystem (unmounted)",
771         "",
772         "-s              get snapshots",
773         "-v              verbose",
774         "-i              ignore errors",
775         "-o              overwrite",
776         "-t              tree location",
777         "-f <offset>     filesystem location",
778         "-u <block>      super mirror",
779         "-d              find dir",
780         NULL
781 };
782
783 int cmd_restore(int argc, char **argv)
784 {
785         struct btrfs_root *root;
786         struct btrfs_key key;
787         char dir_name[128];
788         u64 tree_location = 0;
789         u64 fs_location = 0;
790         u64 root_objectid = 0;
791         int len;
792         int ret;
793         int opt;
794         int super_mirror = 0;
795         int find_dir = 0;
796
797         while ((opt = getopt(argc, argv, "sviot:u:df:r:")) != -1) {
798                 switch (opt) {
799                         case 's':
800                                 get_snaps = 1;
801                                 break;
802                         case 'v':
803                                 verbose++;
804                                 break;
805                         case 'i':
806                                 ignore_errors = 1;
807                                 break;
808                         case 'o':
809                                 overwrite = 1;
810                                 break;
811                         case 't':
812                                 errno = 0;
813                                 tree_location = (u64)strtoll(optarg, NULL, 10);
814                                 if (errno != 0) {
815                                         fprintf(stderr, "Tree location not valid\n");
816                                         exit(1);
817                                 }
818                                 break;
819                         case 'f':
820                                 errno = 0;
821                                 fs_location = (u64)strtoll(optarg, NULL, 10);
822                                 if (errno != 0) {
823                                         fprintf(stderr, "Fs location not valid\n");
824                                         exit(1);
825                                 }
826                                 break;
827                         case 'u':
828                                 errno = 0;
829                                 super_mirror = (int)strtol(optarg, NULL, 10);
830                                 if (errno != 0 ||
831                                     super_mirror >= BTRFS_SUPER_MIRROR_MAX) {
832                                         fprintf(stderr, "Super mirror not "
833                                                 "valid\n");
834                                         exit(1);
835                                 }
836                                 break;
837                         case 'd':
838                                 find_dir = 1;
839                                 break;
840                         case 'r':
841                                 errno = 0;
842                                 root_objectid = (u64)strtoll(optarg, NULL, 10);
843                                 if (errno != 0) {
844                                         fprintf(stderr, "Root objectid not valid\n");
845                                         exit(1);
846                                 }
847                                 break;
848                         default:
849                                 usage(cmd_restore_usage);
850                 }
851         }
852
853         if (optind + 1 >= argc)
854                 usage(cmd_restore_usage);
855
856         if ((ret = check_mounted(argv[optind])) < 0) {
857                 fprintf(stderr, "Could not check mount status: %s\n",
858                         strerror(-ret));
859                 return ret;
860         } else if (ret) {
861                 fprintf(stderr, "%s is currently mounted.  Aborting.\n", argv[optind]);
862                 return 1;
863         }
864
865         root = open_fs(argv[optind], tree_location, super_mirror);
866         if (root == NULL)
867                 return 1;
868
869         if (fs_location != 0) {
870                 free_extent_buffer(root->node);
871                 root->node = read_tree_block(root, fs_location, 4096, 0);
872                 if (!root->node) {
873                         fprintf(stderr, "Failed to read fs location\n");
874                         goto out;
875                 }
876         }
877
878         memset(path_name, 0, 4096);
879
880         strncpy(dir_name, argv[optind + 1], sizeof dir_name);
881         dir_name[sizeof dir_name - 1] = 0;
882
883         /* Strip the trailing / on the dir name */
884         len = strlen(dir_name);
885         while (len && dir_name[--len] == '/') {
886                 dir_name[len] = '\0';
887         }
888
889         if (root_objectid != 0) {
890                 struct btrfs_root *orig_root = root;
891
892                 key.objectid = root_objectid;
893                 key.type = BTRFS_ROOT_ITEM_KEY;
894                 key.offset = (u64)-1;
895                 root = btrfs_read_fs_root(orig_root->fs_info, &key);
896                 if (IS_ERR(root)) {
897                         fprintf(stderr, "Error reading root\n");
898                         root = orig_root;
899                         ret = 1;
900                         goto out;
901                 }
902                 key.type = 0;
903                 key.offset = 0;
904         }
905
906         if (find_dir) {
907                 ret = find_first_dir(root, &key.objectid);
908                 if (ret)
909                         goto out;
910         } else {
911                 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
912         }
913
914         ret = search_dir(root, &key, dir_name);
915
916 out:
917         close_ctree(root);
918         return ret;
919 }