2 * Copyright (C) 2011 Red Hat. All rights reserved.
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.
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.
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.
20 #include "kerncompat.h"
28 #include <sys/types.h>
29 #include <lzo/lzoconf.h>
30 #include <lzo/lzo1x.h>
34 #include <sys/types.h>
35 #include <sys/xattr.h>
39 #include "print-tree.h"
40 #include "transaction.h"
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;
59 #define lzo1x_worst_compress(x) ((x) + ((x) / 16) + 64 + 3)
61 static int decompress_zlib(char *inbuf, char *outbuf, u64 compress_len,
67 memset(&strm, 0, sizeof(strm));
68 ret = inflateInit(&strm);
70 error("zlib init returned %d", ret);
74 strm.avail_in = compress_len;
75 strm.next_in = (unsigned char *)inbuf;
76 strm.avail_out = decompress_len;
77 strm.next_out = (unsigned char *)outbuf;
78 ret = inflate(&strm, Z_NO_FLUSH);
79 if (ret != Z_STREAM_END) {
80 (void)inflateEnd(&strm);
81 error("zlib inflate failed: %d", ret);
85 (void)inflateEnd(&strm);
88 static inline size_t read_compress_length(unsigned char *buf)
91 memcpy(&dlen, buf, LZO_LEN);
92 return le32_to_cpu(dlen);
95 static int decompress_lzo(struct btrfs_root *root, unsigned char *inbuf,
96 char *outbuf, u64 compress_len, u64 *decompress_len)
106 if (ret != LZO_E_OK) {
107 error("lzo init returned %d", ret);
111 tot_len = read_compress_length(inbuf);
115 while (tot_in < tot_len) {
118 in_len = read_compress_length(inbuf);
120 if ((tot_in + LZO_LEN + in_len) > tot_len) {
121 error("bad compress length %lu",
122 (unsigned long)in_len);
128 new_len = lzo1x_worst_compress(root->sectorsize);
129 ret = lzo1x_decompress_safe((const unsigned char *)inbuf, in_len,
130 (unsigned char *)outbuf,
131 (void *)&new_len, NULL);
132 if (ret != LZO_E_OK) {
133 error("lzo decompress failed: %d", ret);
142 * If the 4 byte header does not fit to the rest of the page we
143 * have to move to the next one, unless we read some garbage
145 mod_page = tot_in % root->sectorsize;
146 rem_page = root->sectorsize - mod_page;
147 if (rem_page < LZO_LEN) {
153 *decompress_len = out_len;
158 static int decompress(struct btrfs_root *root, char *inbuf, char *outbuf,
159 u64 compress_len, u64 *decompress_len, int compress)
162 case BTRFS_COMPRESS_ZLIB:
163 return decompress_zlib(inbuf, outbuf, compress_len,
165 case BTRFS_COMPRESS_LZO:
166 return decompress_lzo(root, (unsigned char *)inbuf, outbuf,
167 compress_len, decompress_len);
172 error("invalid compression type: %d", compress);
176 static int next_leaf(struct btrfs_root *root, struct btrfs_path *path)
181 struct extent_buffer *c;
182 struct extent_buffer *next = NULL;
185 for (; level < BTRFS_MAX_LEVEL; level++) {
186 if (path->nodes[level])
190 if (level >= BTRFS_MAX_LEVEL)
193 slot = path->slots[level] + 1;
195 while(level < BTRFS_MAX_LEVEL) {
196 if (!path->nodes[level])
199 slot = path->slots[level] + offset;
200 c = path->nodes[level];
201 if (slot >= btrfs_header_nritems(c)) {
203 if (level == BTRFS_MAX_LEVEL)
210 reada_for_search(root, path, level, slot, 0);
212 next = read_node_slot(root, c, slot);
213 if (extent_buffer_uptodate(next))
217 path->slots[level] = slot;
220 c = path->nodes[level];
221 free_extent_buffer(c);
222 path->nodes[level] = next;
223 path->slots[level] = 0;
227 reada_for_search(root, path, level, 0, 0);
228 next = read_node_slot(root, next, 0);
229 if (!extent_buffer_uptodate(next))
235 static int copy_one_inline(struct btrfs_root *root, int fd,
236 struct btrfs_path *path, u64 pos)
238 struct extent_buffer *leaf = path->nodes[0];
239 struct btrfs_file_extent_item *fi;
250 fi = btrfs_item_ptr(leaf, path->slots[0],
251 struct btrfs_file_extent_item);
252 ptr = btrfs_file_extent_inline_start(fi);
253 len = btrfs_file_extent_inline_len(leaf, path->slots[0], fi);
254 inline_item_len = btrfs_file_extent_inline_item_len(leaf, btrfs_item_nr(path->slots[0]));
255 read_extent_buffer(leaf, buf, ptr, inline_item_len);
257 compress = btrfs_file_extent_compression(leaf, fi);
258 if (compress == BTRFS_COMPRESS_NONE) {
259 done = pwrite(fd, buf, len, pos);
261 fprintf(stderr, "Short inline write, wanted %d, did "
262 "%zd: %d\n", len, done, errno);
268 ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
269 outbuf = calloc(1, ram_size);
271 error("not enough memory");
275 ret = decompress(root, buf, outbuf, len, &ram_size, compress);
281 done = pwrite(fd, outbuf, ram_size, pos);
283 if (done < ram_size) {
284 fprintf(stderr, "Short compressed inline write, wanted %Lu, "
285 "did %zd: %d\n", ram_size, done, errno);
292 static int copy_one_extent(struct btrfs_root *root, int fd,
293 struct extent_buffer *leaf,
294 struct btrfs_file_extent_item *fi, u64 pos)
296 struct btrfs_multi_bio *multi = NULL;
297 struct btrfs_device *device;
298 char *inbuf, *outbuf = NULL;
299 ssize_t done, total = 0;
315 compress = btrfs_file_extent_compression(leaf, fi);
316 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
317 disk_size = btrfs_file_extent_disk_num_bytes(leaf, fi);
318 ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
319 offset = btrfs_file_extent_offset(leaf, fi);
320 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
321 size_left = disk_size;
322 if (compress == BTRFS_COMPRESS_NONE)
325 if (verbose && offset)
326 printf("offset is %Lu\n", offset);
327 /* we found a hole */
331 inbuf = malloc(size_left);
333 error("not enough memory\n");
337 if (compress != BTRFS_COMPRESS_NONE) {
338 outbuf = calloc(1, ram_size);
340 error("not enough memory");
347 ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
348 bytenr, &length, &multi, mirror_num, NULL);
350 error("cannot map block logical %llu length %llu: %d",
351 (unsigned long long)bytenr,
352 (unsigned long long)length, ret);
355 device = multi->stripes[0].dev;
358 dev_bytenr = multi->stripes[0].physical;
361 if (size_left < length)
364 done = pread(dev_fd, inbuf+count, length, dev_bytenr);
365 /* Need both checks, or we miss negative values due to u64 conversion */
366 if (done < 0 || done < length) {
367 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
370 /* mirror_num is 1-indexed, so num_copies is a valid mirror. */
371 if (mirror_num > num_copies) {
373 error("exhausted mirrors trying to read (%d > %d)",
374 mirror_num, num_copies);
377 fprintf(stderr, "Trying another mirror\n");
388 if (compress == BTRFS_COMPRESS_NONE) {
389 while (total < num_bytes) {
390 done = pwrite(fd, inbuf+total, num_bytes-total,
394 error("cannot write data: %d %s", errno, strerror(errno));
403 ret = decompress(root, inbuf, outbuf, disk_size, &ram_size, compress);
405 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
408 if (mirror_num >= num_copies) {
412 fprintf(stderr, "Trying another mirror\n");
416 while (total < num_bytes) {
417 done = pwrite(fd, outbuf + offset + total,
438 static enum loop_response ask_to_continue(const char *file)
443 printf("We seem to be looping a lot on %s, do you want to keep going "
444 "on ? (y/N/a): ", file);
446 ret = fgets(buf, 2, stdin);
447 if (*ret == '\n' || tolower(*ret) == 'n')
449 if (tolower(*ret) == 'a')
451 if (tolower(*ret) != 'y') {
452 printf("Please enter one of 'y', 'n', or 'a': ");
456 return LOOP_CONTINUE;
460 static int set_file_xattrs(struct btrfs_root *root, u64 inode,
461 int fd, const char *file_name)
463 struct btrfs_key key;
464 struct btrfs_path path;
465 struct extent_buffer *leaf;
466 struct btrfs_dir_item *di;
475 btrfs_init_path(&path);
476 key.objectid = inode;
477 key.type = BTRFS_XATTR_ITEM_KEY;
479 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
483 leaf = path.nodes[0];
485 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
487 ret = next_leaf(root, &path);
489 error("searching for extended attributes: %d\n",
493 /* No more leaves to search */
497 leaf = path.nodes[0];
502 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
503 if (key.type != BTRFS_XATTR_ITEM_KEY || key.objectid != inode)
506 total_len = btrfs_item_size_nr(leaf, path.slots[0]);
507 di = btrfs_item_ptr(leaf, path.slots[0],
508 struct btrfs_dir_item);
510 while (cur < total_len) {
511 len = btrfs_dir_name_len(leaf, di);
512 if (len > name_len) {
514 name = (char *) malloc(len + 1);
520 read_extent_buffer(leaf, name,
521 (unsigned long)(di + 1), len);
525 len = btrfs_dir_data_len(leaf, di);
526 if (len > data_len) {
528 data = (char *) malloc(len);
534 read_extent_buffer(leaf, data,
535 (unsigned long)(di + 1) + name_len,
539 if (fsetxattr(fd, name, data, data_len, 0))
540 error("setting extended attribute %s on file %s: %s",
541 name, file_name, strerror(errno));
543 len = sizeof(*di) + name_len + data_len;
545 di = (struct btrfs_dir_item *)((char *)di + len);
551 btrfs_release_path(&path);
558 static int copy_metadata(struct btrfs_root *root, int fd,
559 struct btrfs_key *key)
561 struct btrfs_path *path;
562 struct btrfs_inode_item *inode_item;
565 path = btrfs_alloc_path();
567 error("not enough memory");
571 ret = btrfs_lookup_inode(NULL, root, path, key, 0);
573 struct btrfs_timespec *bts;
574 struct timespec times[2];
576 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
577 struct btrfs_inode_item);
579 ret = fchown(fd, btrfs_inode_uid(path->nodes[0], inode_item),
580 btrfs_inode_gid(path->nodes[0], inode_item));
582 error("failed to change owner: %s", strerror(errno));
586 ret = fchmod(fd, btrfs_inode_mode(path->nodes[0], inode_item));
588 error("failed to change mode: %s", strerror(errno));
592 bts = btrfs_inode_atime(inode_item);
593 times[0].tv_sec = btrfs_timespec_sec(path->nodes[0], bts);
594 times[0].tv_nsec = btrfs_timespec_nsec(path->nodes[0], bts);
596 bts = btrfs_inode_mtime(inode_item);
597 times[1].tv_sec = btrfs_timespec_sec(path->nodes[0], bts);
598 times[1].tv_nsec = btrfs_timespec_nsec(path->nodes[0], bts);
600 ret = futimens(fd, times);
602 error("failed to set times: %s", strerror(errno));
607 btrfs_free_path(path);
611 static int copy_file(struct btrfs_root *root, int fd, struct btrfs_key *key,
614 struct extent_buffer *leaf;
615 struct btrfs_path *path;
616 struct btrfs_file_extent_item *fi;
617 struct btrfs_inode_item *inode_item;
618 struct btrfs_timespec *bts;
619 struct btrfs_key found_key;
625 struct timespec times[2];
628 path = btrfs_alloc_path();
630 error("not enough memory");
634 ret = btrfs_lookup_inode(NULL, root, path, key, 0);
636 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
637 struct btrfs_inode_item);
638 found_size = btrfs_inode_size(path->nodes[0], inode_item);
640 if (restore_metadata) {
642 * Change the ownership and mode now, set times when
643 * copyout is finished.
646 ret = fchown(fd, btrfs_inode_uid(path->nodes[0], inode_item),
647 btrfs_inode_gid(path->nodes[0], inode_item));
648 if (ret && !ignore_errors)
651 ret = fchmod(fd, btrfs_inode_mode(path->nodes[0], inode_item));
652 if (ret && !ignore_errors)
655 bts = btrfs_inode_atime(inode_item);
656 times[0].tv_sec = btrfs_timespec_sec(path->nodes[0], bts);
657 times[0].tv_nsec = btrfs_timespec_nsec(path->nodes[0], bts);
659 bts = btrfs_inode_mtime(inode_item);
660 times[1].tv_sec = btrfs_timespec_sec(path->nodes[0], bts);
661 times[1].tv_nsec = btrfs_timespec_nsec(path->nodes[0], bts);
665 btrfs_release_path(path);
668 key->type = BTRFS_EXTENT_DATA_KEY;
670 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
672 error("searching extent data returned %d", ret);
676 leaf = path->nodes[0];
678 ret = next_leaf(root, path);
680 error("cannot get next leaf: %d", ret);
682 } else if (ret > 0) {
683 /* No more leaves to search */
687 leaf = path->nodes[0];
691 if (loops >= 0 && loops++ >= 1024) {
692 enum loop_response resp;
694 resp = ask_to_continue(file);
695 if (resp == LOOP_STOP)
697 else if (resp == LOOP_CONTINUE)
699 else if (resp == LOOP_DONTASK)
702 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
704 ret = next_leaf(root, path);
706 fprintf(stderr, "Error searching %d\n", ret);
709 /* No more leaves to search */
710 btrfs_free_path(path);
713 leaf = path->nodes[0];
717 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
718 if (found_key.objectid != key->objectid)
720 if (found_key.type != key->type)
722 fi = btrfs_item_ptr(leaf, path->slots[0],
723 struct btrfs_file_extent_item);
724 extent_type = btrfs_file_extent_type(leaf, fi);
725 compression = btrfs_file_extent_compression(leaf, fi);
726 if (compression >= BTRFS_COMPRESS_LAST) {
727 warning("compression type %d not supported",
733 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC)
735 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
736 ret = copy_one_inline(root, fd, path, found_key.offset);
739 } else if (extent_type == BTRFS_FILE_EXTENT_REG) {
740 ret = copy_one_extent(root, fd, leaf, fi,
745 warning("weird extent type %d", extent_type);
751 btrfs_free_path(path);
754 ret = ftruncate(fd, (loff_t)found_size);
759 ret = set_file_xattrs(root, key->objectid, fd, file);
763 if (restore_metadata && times_ok) {
764 ret = futimens(fd, times);
771 btrfs_free_path(path);
777 * 0 if the file exists and should be skipped.
778 * 1 if the file does NOT exist
779 * 2 if the file exists but is OK to overwrite
781 static int overwrite_ok(const char * path)
787 /* don't be fooled by symlinks */
788 ret = fstatat(-1, path_name, &st, AT_SYMLINK_NOFOLLOW);
794 if (verbose || !warn)
795 printf("Skipping existing file"
798 printf("If you wish to overwrite use -o\n");
805 static int copy_symlink(struct btrfs_root *root, struct btrfs_key *key,
808 struct btrfs_path *path;
809 struct extent_buffer *leaf;
810 struct btrfs_file_extent_item *extent_item;
811 struct btrfs_inode_item *inode_item;
815 struct btrfs_timespec *bts;
816 struct timespec times[2];
818 ret = overwrite_ok(path_name);
820 return 0; /* skip this file */
822 /* symlink() can't overwrite, so unlink first */
824 ret = unlink(path_name);
826 fprintf(stderr, "failed to unlink '%s' for overwrite\n",
832 key->type = BTRFS_EXTENT_DATA_KEY;
835 path = btrfs_alloc_path();
839 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
843 leaf = path->nodes[0];
845 fprintf(stderr, "Error getting leaf for symlink '%s'\n", file);
850 extent_item = btrfs_item_ptr(leaf, path->slots[0],
851 struct btrfs_file_extent_item);
853 len = btrfs_file_extent_inline_item_len(leaf,
854 btrfs_item_nr(path->slots[0]));
855 if (len >= PATH_MAX) {
856 fprintf(stderr, "Symlink '%s' target length %d is longer than PATH_MAX\n",
862 name_offset = (unsigned long) extent_item
863 + offsetof(struct btrfs_file_extent_item, disk_bytenr);
864 read_extent_buffer(leaf, symlink_target, name_offset, len);
866 symlink_target[len] = 0;
869 ret = symlink(symlink_target, path_name);
871 fprintf(stderr, "Failed to restore symlink '%s': %s\n",
872 path_name, strerror(errno));
876 printf("SYMLINK: '%s' => '%s'\n", path_name, symlink_target);
879 if (!restore_metadata)
883 * Symlink metadata operates differently than files/directories, so do
886 key->type = BTRFS_INODE_ITEM_KEY;
889 btrfs_release_path(path);
891 ret = btrfs_lookup_inode(NULL, root, path, key, 0);
893 fprintf(stderr, "Failed to lookup inode for '%s'\n", file);
897 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
898 struct btrfs_inode_item);
900 ret = fchownat(-1, file, btrfs_inode_uid(path->nodes[0], inode_item),
901 btrfs_inode_gid(path->nodes[0], inode_item),
902 AT_SYMLINK_NOFOLLOW);
904 fprintf(stderr, "Failed to change owner: %s\n",
909 bts = btrfs_inode_atime(inode_item);
910 times[0].tv_sec = btrfs_timespec_sec(path->nodes[0], bts);
911 times[0].tv_nsec = btrfs_timespec_nsec(path->nodes[0], bts);
913 bts = btrfs_inode_mtime(inode_item);
914 times[1].tv_sec = btrfs_timespec_sec(path->nodes[0], bts);
915 times[1].tv_nsec = btrfs_timespec_nsec(path->nodes[0], bts);
917 ret = utimensat(-1, file, times, AT_SYMLINK_NOFOLLOW);
919 fprintf(stderr, "Failed to set times: %s\n", strerror(errno));
921 btrfs_free_path(path);
925 static int search_dir(struct btrfs_root *root, struct btrfs_key *key,
926 const char *output_rootdir, const char *in_dir,
929 struct btrfs_path *path;
930 struct extent_buffer *leaf;
931 struct btrfs_dir_item *dir_item;
932 struct btrfs_key found_key, location;
933 char filename[BTRFS_NAME_LEN + 1];
934 unsigned long name_ptr;
941 path = btrfs_alloc_path();
943 fprintf(stderr, "Ran out of memory\n");
948 key->type = BTRFS_DIR_INDEX_KEY;
950 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
952 fprintf(stderr, "Error searching %d\n", ret);
958 leaf = path->nodes[0];
961 printf("No leaf after search, looking for the next "
963 ret = next_leaf(root, path);
965 fprintf(stderr, "Error getting next leaf %d\n",
968 } else if (ret > 0) {
969 /* No more leaves to search */
971 printf("Reached the end of the tree looking "
972 "for the directory\n");
976 leaf = path->nodes[0];
980 if (loops++ >= 1024) {
981 printf("We have looped trying to restore files in %s "
982 "too many times to be making progress, "
983 "stopping\n", in_dir);
987 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
989 ret = next_leaf(root, path);
991 fprintf(stderr, "Error searching %d\n",
994 } else if (ret > 0) {
995 /* No more leaves to search */
997 printf("Reached the end of "
998 "the tree searching the"
1003 leaf = path->nodes[0];
1007 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1008 if (found_key.objectid != key->objectid) {
1010 printf("Found objectid=%Lu, key=%Lu\n",
1011 found_key.objectid, key->objectid);
1014 if (found_key.type != key->type) {
1016 printf("Found type=%u, want=%u\n",
1017 found_key.type, key->type);
1020 dir_item = btrfs_item_ptr(leaf, path->slots[0],
1021 struct btrfs_dir_item);
1022 name_ptr = (unsigned long)(dir_item + 1);
1023 name_len = btrfs_dir_name_len(leaf, dir_item);
1024 read_extent_buffer(leaf, filename, name_ptr, name_len);
1025 filename[name_len] = '\0';
1026 type = btrfs_dir_type(leaf, dir_item);
1027 btrfs_dir_item_key_to_cpu(leaf, dir_item, &location);
1029 /* full path from root of btrfs being restored */
1030 snprintf(fs_name, PATH_MAX, "%s/%s", in_dir, filename);
1032 if (mreg && REG_NOMATCH == regexec(mreg, fs_name, 0, NULL, 0))
1035 /* full path from system root */
1036 snprintf(path_name, PATH_MAX, "%s%s", output_rootdir, fs_name);
1039 * Restore directories, files, symlinks and metadata.
1041 if (type == BTRFS_FT_REG_FILE) {
1042 if (!overwrite_ok(path_name))
1046 printf("Restoring %s\n", path_name);
1049 fd = open(path_name, O_CREAT|O_WRONLY, 0644);
1051 fprintf(stderr, "Error creating %s: %d\n",
1059 ret = copy_file(root, fd, &location, path_name);
1062 fprintf(stderr, "Error copying data for %s\n",
1068 } else if (type == BTRFS_FT_DIR) {
1069 struct btrfs_root *search_root = root;
1070 char *dir = strdup(fs_name);
1073 fprintf(stderr, "Ran out of memory\n");
1078 if (location.type == BTRFS_ROOT_ITEM_KEY) {
1080 * If we are a snapshot and this is the index
1081 * object to ourselves just skip it.
1083 if (location.objectid ==
1084 root->root_key.objectid) {
1089 location.offset = (u64)-1;
1090 search_root = btrfs_read_fs_root(root->fs_info,
1092 if (IS_ERR(search_root)) {
1094 fprintf(stderr, "Error reading "
1095 "subvolume %s: %lu\n",
1097 PTR_ERR(search_root));
1100 ret = PTR_ERR(search_root);
1105 * A subvolume will have a key.offset of 0, a
1106 * snapshot will have key.offset of a transid.
1108 if (search_root->root_key.offset != 0 &&
1111 printf("Skipping snapshot %s\n",
1115 location.objectid = BTRFS_FIRST_FREE_OBJECTID;
1119 printf("Restoring %s\n", path_name);
1125 ret = mkdir(path_name, 0755);
1126 if (ret && errno != EEXIST) {
1128 fprintf(stderr, "Error mkdiring %s: %d\n",
1136 ret = search_dir(search_root, &location,
1137 output_rootdir, dir, mreg);
1140 fprintf(stderr, "Error searching %s\n",
1146 } else if (type == BTRFS_FT_SYMLINK) {
1147 if (restore_symlinks)
1148 ret = copy_symlink(root, &location, path_name);
1152 btrfs_free_path(path);
1160 if (restore_metadata) {
1161 snprintf(path_name, PATH_MAX, "%s%s", output_rootdir, in_dir);
1162 fd = open(path_name, O_RDONLY);
1164 fprintf(stderr, "ERROR: Failed to access %s to restore metadata\n",
1166 if (!ignore_errors) {
1172 * Set owner/mode/time on the directory as well
1174 key->type = BTRFS_INODE_ITEM_KEY;
1175 ret = copy_metadata(root, fd, key);
1177 if (ret && !ignore_errors)
1183 printf("Done searching %s\n", in_dir);
1185 btrfs_free_path(path);
1189 static int do_list_roots(struct btrfs_root *root)
1191 struct btrfs_key key;
1192 struct btrfs_key found_key;
1193 struct btrfs_disk_key disk_key;
1194 struct btrfs_path *path;
1195 struct extent_buffer *leaf;
1196 struct btrfs_root_item ri;
1197 unsigned long offset;
1201 root = root->fs_info->tree_root;
1202 path = btrfs_alloc_path();
1204 fprintf(stderr, "Failed to alloc path\n");
1210 key.type = BTRFS_ROOT_ITEM_KEY;
1212 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1214 fprintf(stderr, "Failed to do search %d\n", ret);
1215 btrfs_free_path(path);
1219 leaf = path->nodes[0];
1222 slot = path->slots[0];
1223 if (slot >= btrfs_header_nritems(leaf)) {
1224 ret = btrfs_next_leaf(root, path);
1227 leaf = path->nodes[0];
1228 slot = path->slots[0];
1230 btrfs_item_key(leaf, &disk_key, slot);
1231 btrfs_disk_key_to_cpu(&found_key, &disk_key);
1232 if (found_key.type != BTRFS_ROOT_ITEM_KEY) {
1237 offset = btrfs_item_ptr_offset(leaf, slot);
1238 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
1240 btrfs_print_key(&disk_key);
1241 printf(" %Lu level %d\n", btrfs_root_bytenr(&ri),
1242 btrfs_root_level(&ri));
1245 btrfs_free_path(path);
1250 static struct btrfs_root *open_fs(const char *dev, u64 root_location,
1251 int super_mirror, int list_roots)
1253 struct btrfs_fs_info *fs_info = NULL;
1254 struct btrfs_root *root = NULL;
1258 for (i = super_mirror; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1259 bytenr = btrfs_sb_offset(i);
1260 fs_info = open_ctree_fs_info(dev, bytenr, root_location, 0,
1261 OPEN_CTREE_PARTIAL);
1264 fprintf(stderr, "Could not open root, trying backup super\n");
1271 * All we really need to succeed is reading the chunk tree, everything
1272 * else we can do by hand, since we only need to read the tree root and
1275 if (!extent_buffer_uptodate(fs_info->tree_root->node)) {
1278 root = fs_info->tree_root;
1280 root_location = btrfs_super_root(fs_info->super_copy);
1281 generation = btrfs_super_generation(fs_info->super_copy);
1282 root->node = read_tree_block(root, root_location,
1283 root->nodesize, generation);
1284 if (!extent_buffer_uptodate(root->node)) {
1285 fprintf(stderr, "Error opening tree root\n");
1291 if (!list_roots && !fs_info->fs_root) {
1292 struct btrfs_key key;
1294 key.objectid = BTRFS_FS_TREE_OBJECTID;
1295 key.type = BTRFS_ROOT_ITEM_KEY;
1296 key.offset = (u64)-1;
1297 fs_info->fs_root = btrfs_read_fs_root_no_cache(fs_info, &key);
1298 if (IS_ERR(fs_info->fs_root)) {
1299 fprintf(stderr, "Couldn't read fs root: %ld\n",
1300 PTR_ERR(fs_info->fs_root));
1301 close_ctree(fs_info->tree_root);
1306 if (list_roots && do_list_roots(fs_info->tree_root)) {
1307 close_ctree(fs_info->tree_root);
1311 return fs_info->fs_root;
1314 static int find_first_dir(struct btrfs_root *root, u64 *objectid)
1316 struct btrfs_path *path;
1317 struct btrfs_key found_key;
1318 struct btrfs_key key;
1323 key.type = BTRFS_DIR_INDEX_KEY;
1326 path = btrfs_alloc_path();
1328 fprintf(stderr, "Ran out of memory\n");
1332 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1334 fprintf(stderr, "Error searching %d\n", ret);
1338 if (!path->nodes[0]) {
1339 fprintf(stderr, "No leaf!\n");
1343 for (i = path->slots[0];
1344 i < btrfs_header_nritems(path->nodes[0]); i++) {
1345 btrfs_item_key_to_cpu(path->nodes[0], &found_key, i);
1346 if (found_key.type != key.type)
1349 printf("Using objectid %Lu for first dir\n",
1350 found_key.objectid);
1351 *objectid = found_key.objectid;
1356 ret = next_leaf(root, path);
1358 fprintf(stderr, "Error getting next leaf %d\n",
1361 } else if (ret > 0) {
1362 fprintf(stderr, "No more leaves\n");
1365 } while (!path->nodes[0]);
1368 printf("Couldn't find a dir index item\n");
1370 btrfs_free_path(path);
1374 const char * const cmd_restore_usage[] = {
1375 "btrfs restore [options] <device> <path> | -l <device>",
1376 "Try to restore files from a damaged filesystem (unmounted)",
1378 "-s|--snapshots get snapshots",
1379 "-x|--xattr restore extended attributes",
1380 "-m|--metadata restore owner, mode and times",
1381 "-S|--symlink restore symbolic links",
1382 "-v|--verbose verbose",
1383 "-i|--ignore-errors ignore errors",
1384 "-o|--overwrite overwrite",
1385 "-t <bytenr> tree location",
1386 "-f <bytenr> filesystem location",
1387 "-u|--super <mirror> super mirror",
1388 "-r|--root <rootid> root objectid",
1390 "-l|--list-roots list tree roots",
1391 "-D|--dry-run dry run (only list files that would be recovered)",
1392 "--path-regex <regex>",
1393 " restore only filenames matching regex,",
1394 " you have to use following syntax (possibly quoted):",
1395 " ^/(|home(|/username(|/Desktop(|/.*))))$",
1396 "-c ignore case (--path-regex only)",
1400 int cmd_restore(int argc, char **argv)
1402 struct btrfs_root *root;
1403 struct btrfs_key key;
1404 char dir_name[PATH_MAX];
1405 u64 tree_location = 0;
1406 u64 fs_location = 0;
1407 u64 root_objectid = 0;
1410 int super_mirror = 0;
1413 const char *match_regstr = NULL;
1414 int match_cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
1415 regex_t match_reg, *mreg = NULL;
1420 enum { GETOPT_VAL_PATH_REGEX = 256 };
1421 static const struct option long_options[] = {
1422 { "path-regex", required_argument, NULL,
1423 GETOPT_VAL_PATH_REGEX },
1424 { "dry-run", no_argument, NULL, 'D'},
1425 { "metadata", no_argument, NULL, 'm'},
1426 { "symlinks", no_argument, NULL, 'S'},
1427 { "snapshots", no_argument, NULL, 's'},
1428 { "xattr", no_argument, NULL, 'x'},
1429 { "verbose", no_argument, NULL, 'v'},
1430 { "ignore-errors", no_argument, NULL, 'i'},
1431 { "overwrite", no_argument, NULL, 'o'},
1432 { "super", required_argument, NULL, 'u'},
1433 { "root", required_argument, NULL, 'r'},
1434 { "list-roots", no_argument, NULL, 'l'},
1438 opt = getopt_long(argc, argv, "sSxviot:u:dmf:r:lDc", long_options,
1457 tree_location = arg_strtou64(optarg);
1460 fs_location = arg_strtou64(optarg);
1463 super_mirror = arg_strtou64(optarg);
1464 if (super_mirror >= BTRFS_SUPER_MIRROR_MAX) {
1465 fprintf(stderr, "Super mirror not "
1474 root_objectid = arg_strtou64(optarg);
1475 if (!is_fstree(root_objectid)) {
1476 fprintf(stderr, "objectid %llu is not a valid fs/file tree\n",
1485 restore_metadata = 1;
1488 restore_symlinks = 1;
1494 match_cflags |= REG_ICASE;
1496 case GETOPT_VAL_PATH_REGEX:
1497 match_regstr = optarg;
1503 usage(cmd_restore_usage);
1507 if (!list_roots && check_argc_min(argc - optind, 2))
1508 usage(cmd_restore_usage);
1509 else if (list_roots && check_argc_min(argc - optind, 1))
1510 usage(cmd_restore_usage);
1512 if (fs_location && root_objectid) {
1513 fprintf(stderr, "don't use -f and -r at the same time.\n");
1517 if ((ret = check_mounted(argv[optind])) < 0) {
1518 fprintf(stderr, "Could not check mount status: %s\n",
1522 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
1526 root = open_fs(argv[optind], tree_location, super_mirror, list_roots);
1533 if (fs_location != 0) {
1534 free_extent_buffer(root->node);
1535 root->node = read_tree_block(root, fs_location, root->nodesize, 0);
1536 if (!extent_buffer_uptodate(root->node)) {
1537 fprintf(stderr, "Failed to read fs location\n");
1543 memset(path_name, 0, PATH_MAX);
1545 if (strlen(argv[optind + 1]) >= PATH_MAX) {
1546 fprintf(stderr, "ERROR: path too long\n");
1550 strncpy(dir_name, argv[optind + 1], sizeof dir_name);
1551 dir_name[sizeof dir_name - 1] = 0;
1553 /* Strip the trailing / on the dir name */
1554 len = strlen(dir_name);
1555 while (len && dir_name[--len] == '/') {
1556 dir_name[len] = '\0';
1559 if (root_objectid != 0) {
1560 struct btrfs_root *orig_root = root;
1562 key.objectid = root_objectid;
1563 key.type = BTRFS_ROOT_ITEM_KEY;
1564 key.offset = (u64)-1;
1565 root = btrfs_read_fs_root(orig_root->fs_info, &key);
1567 fprintf(stderr, "fail to read root %llu: %s\n",
1568 root_objectid, strerror(-PTR_ERR(root)));
1578 ret = find_first_dir(root, &key.objectid);
1582 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
1586 ret = regcomp(&match_reg, match_regstr, match_cflags);
1588 regerror(ret, &match_reg, reg_err, sizeof(reg_err));
1589 fprintf(stderr, "Regex compile failed: %s\n", reg_err);
1596 printf("This is a dry-run, no files are going to be restored\n");
1598 ret = search_dir(root, &key, dir_name, "", mreg);