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>
37 #include <sys/types.h>
38 #include <sys/xattr.h>
42 #include "print-tree.h"
43 #include "transaction.h"
50 static char fs_name[PATH_MAX];
51 static char path_name[PATH_MAX];
52 static char symlink_target[PATH_MAX];
53 static int get_snaps = 0;
54 static int verbose = 0;
55 static int restore_metadata = 0;
56 static int restore_symlinks = 0;
57 static int ignore_errors = 0;
58 static int overwrite = 0;
59 static int get_xattrs = 0;
60 static int dry_run = 0;
63 #define lzo1x_worst_compress(x) ((x) + ((x) / 16) + 64 + 3)
65 static int decompress_zlib(char *inbuf, char *outbuf, u64 compress_len,
71 memset(&strm, 0, sizeof(strm));
72 ret = inflateInit(&strm);
74 error("zlib init returned %d", ret);
78 strm.avail_in = compress_len;
79 strm.next_in = (unsigned char *)inbuf;
80 strm.avail_out = decompress_len;
81 strm.next_out = (unsigned char *)outbuf;
82 ret = inflate(&strm, Z_NO_FLUSH);
83 if (ret != Z_STREAM_END) {
84 (void)inflateEnd(&strm);
85 error("zlib inflate failed: %d", ret);
89 (void)inflateEnd(&strm);
92 static inline size_t read_compress_length(unsigned char *buf)
95 memcpy(&dlen, buf, LZO_LEN);
96 return le32_to_cpu(dlen);
99 static int decompress_lzo(struct btrfs_root *root, unsigned char *inbuf,
100 char *outbuf, u64 compress_len, u64 *decompress_len)
110 if (ret != LZO_E_OK) {
111 error("lzo init returned %d", ret);
115 tot_len = read_compress_length(inbuf);
119 while (tot_in < tot_len) {
122 in_len = read_compress_length(inbuf);
124 if ((tot_in + LZO_LEN + in_len) > tot_len) {
125 error("bad compress length %lu",
126 (unsigned long)in_len);
132 new_len = lzo1x_worst_compress(root->fs_info->sectorsize);
133 ret = lzo1x_decompress_safe((const unsigned char *)inbuf, in_len,
134 (unsigned char *)outbuf,
135 (void *)&new_len, NULL);
136 if (ret != LZO_E_OK) {
137 error("lzo decompress failed: %d", ret);
146 * If the 4 byte header does not fit to the rest of the page we
147 * have to move to the next one, unless we read some garbage
149 mod_page = tot_in % root->fs_info->sectorsize;
150 rem_page = root->fs_info->sectorsize - mod_page;
151 if (rem_page < LZO_LEN) {
157 *decompress_len = out_len;
162 static int decompress_zstd(const char *inbuf, char *outbuf, u64 compress_len,
165 #if !BTRFSRESTORE_ZSTD
166 error("btrfs not compiled with zstd support");
172 ZSTD_inBuffer in = {inbuf, compress_len, 0};
173 ZSTD_outBuffer out = {outbuf, decompress_len, 0};
175 strm = ZSTD_createDStream();
177 error("zstd create failed");
181 zret = ZSTD_initDStream(strm);
182 if (ZSTD_isError(zret)) {
183 error("zstd init failed: %s", ZSTD_getErrorName(zret));
188 zret = ZSTD_decompressStream(strm, &out, &in);
189 if (ZSTD_isError(zret)) {
190 error("zstd decompress failed %s\n", ZSTD_getErrorName(zret));
195 error("zstd frame incomplete");
201 ZSTD_freeDStream(strm);
206 static int decompress(struct btrfs_root *root, char *inbuf, char *outbuf,
207 u64 compress_len, u64 *decompress_len, int compress)
210 case BTRFS_COMPRESS_ZLIB:
211 return decompress_zlib(inbuf, outbuf, compress_len,
213 case BTRFS_COMPRESS_LZO:
214 return decompress_lzo(root, (unsigned char *)inbuf, outbuf,
215 compress_len, decompress_len);
216 case BTRFS_COMPRESS_ZSTD:
217 return decompress_zstd(inbuf, outbuf, compress_len,
223 error("invalid compression type: %d", compress);
227 static int next_leaf(struct btrfs_root *root, struct btrfs_path *path)
232 struct extent_buffer *c;
233 struct extent_buffer *next = NULL;
234 struct btrfs_fs_info *fs_info = root->fs_info;
237 for (; level < BTRFS_MAX_LEVEL; level++) {
238 if (path->nodes[level])
242 if (level >= BTRFS_MAX_LEVEL)
245 slot = path->slots[level] + 1;
247 while(level < BTRFS_MAX_LEVEL) {
248 if (!path->nodes[level])
251 slot = path->slots[level] + offset;
252 c = path->nodes[level];
253 if (slot >= btrfs_header_nritems(c)) {
255 if (level == BTRFS_MAX_LEVEL)
262 reada_for_search(root, path, level, slot, 0);
264 next = read_node_slot(fs_info, c, slot);
265 if (extent_buffer_uptodate(next))
269 path->slots[level] = slot;
272 c = path->nodes[level];
273 free_extent_buffer(c);
274 path->nodes[level] = next;
275 path->slots[level] = 0;
279 reada_for_search(root, path, level, 0, 0);
280 next = read_node_slot(fs_info, next, 0);
281 if (!extent_buffer_uptodate(next))
287 static int copy_one_inline(struct btrfs_root *root, int fd,
288 struct btrfs_path *path, u64 pos)
290 struct extent_buffer *leaf = path->nodes[0];
291 struct btrfs_file_extent_item *fi;
302 fi = btrfs_item_ptr(leaf, path->slots[0],
303 struct btrfs_file_extent_item);
304 ptr = btrfs_file_extent_inline_start(fi);
305 len = btrfs_file_extent_inline_len(leaf, path->slots[0], fi);
306 inline_item_len = btrfs_file_extent_inline_item_len(leaf, btrfs_item_nr(path->slots[0]));
307 read_extent_buffer(leaf, buf, ptr, inline_item_len);
309 compress = btrfs_file_extent_compression(leaf, fi);
310 if (compress == BTRFS_COMPRESS_NONE) {
311 done = pwrite(fd, buf, len, pos);
313 fprintf(stderr, "Short inline write, wanted %d, did "
314 "%zd: %d\n", len, done, errno);
320 ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
321 outbuf = calloc(1, ram_size);
323 error("not enough memory");
327 ret = decompress(root, buf, outbuf, len, &ram_size, compress);
333 done = pwrite(fd, outbuf, ram_size, pos);
335 if (done < ram_size) {
336 fprintf(stderr, "Short compressed inline write, wanted %Lu, "
337 "did %zd: %d\n", ram_size, done, errno);
344 static int copy_one_extent(struct btrfs_root *root, int fd,
345 struct extent_buffer *leaf,
346 struct btrfs_file_extent_item *fi, u64 pos)
348 struct btrfs_multi_bio *multi = NULL;
349 struct btrfs_device *device;
350 char *inbuf, *outbuf = NULL;
351 ssize_t done, total = 0;
367 compress = btrfs_file_extent_compression(leaf, fi);
368 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
369 disk_size = btrfs_file_extent_disk_num_bytes(leaf, fi);
370 ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
371 offset = btrfs_file_extent_offset(leaf, fi);
372 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
373 size_left = disk_size;
374 if (compress == BTRFS_COMPRESS_NONE)
377 if (verbose && offset)
378 printf("offset is %Lu\n", offset);
379 /* we found a hole */
383 inbuf = malloc(size_left);
385 error("not enough memory");
389 if (compress != BTRFS_COMPRESS_NONE) {
390 outbuf = calloc(1, ram_size);
392 error("not enough memory");
399 ret = btrfs_map_block(root->fs_info, READ, bytenr, &length, &multi,
402 error("cannot map block logical %llu length %llu: %d",
403 (unsigned long long)bytenr,
404 (unsigned long long)length, ret);
407 device = multi->stripes[0].dev;
410 dev_bytenr = multi->stripes[0].physical;
413 if (size_left < length)
416 done = pread(dev_fd, inbuf+count, length, dev_bytenr);
417 /* Need both checks, or we miss negative values due to u64 conversion */
418 if (done < 0 || done < length) {
419 num_copies = btrfs_num_copies(root->fs_info, bytenr, length);
421 /* mirror_num is 1-indexed, so num_copies is a valid mirror. */
422 if (mirror_num > num_copies) {
424 error("exhausted mirrors trying to read (%d > %d)",
425 mirror_num, num_copies);
428 fprintf(stderr, "Trying another mirror\n");
439 if (compress == BTRFS_COMPRESS_NONE) {
440 while (total < num_bytes) {
441 done = pwrite(fd, inbuf+total, num_bytes-total,
445 error("cannot write data: %d %m", errno);
454 ret = decompress(root, inbuf, outbuf, disk_size, &ram_size, compress);
456 num_copies = btrfs_num_copies(root->fs_info, bytenr, length);
458 if (mirror_num >= num_copies) {
462 fprintf(stderr, "Trying another mirror\n");
466 while (total < num_bytes) {
467 done = pwrite(fd, outbuf + offset + total,
488 static enum loop_response ask_to_continue(const char *file)
493 printf("We seem to be looping a lot on %s, do you want to keep going "
494 "on ? (y/N/a): ", file);
496 ret = fgets(buf, 2, stdin);
497 if (*ret == '\n' || tolower(*ret) == 'n')
499 if (tolower(*ret) == 'a')
501 if (tolower(*ret) != 'y') {
502 printf("Please enter one of 'y', 'n', or 'a': ");
506 return LOOP_CONTINUE;
510 static int set_file_xattrs(struct btrfs_root *root, u64 inode,
511 int fd, const char *file_name)
513 struct btrfs_key key;
514 struct btrfs_path path;
515 struct extent_buffer *leaf;
516 struct btrfs_dir_item *di;
525 btrfs_init_path(&path);
526 key.objectid = inode;
527 key.type = BTRFS_XATTR_ITEM_KEY;
529 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
533 leaf = path.nodes[0];
535 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
537 ret = next_leaf(root, &path);
539 error("searching for extended attributes: %d",
543 /* No more leaves to search */
547 leaf = path.nodes[0];
552 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
553 if (key.type != BTRFS_XATTR_ITEM_KEY || key.objectid != inode)
556 total_len = btrfs_item_size_nr(leaf, path.slots[0]);
557 di = btrfs_item_ptr(leaf, path.slots[0],
558 struct btrfs_dir_item);
560 while (cur < total_len) {
561 len = btrfs_dir_name_len(leaf, di);
562 if (len > name_len) {
564 name = (char *) malloc(len + 1);
570 read_extent_buffer(leaf, name,
571 (unsigned long)(di + 1), len);
575 len = btrfs_dir_data_len(leaf, di);
576 if (len > data_len) {
578 data = (char *) malloc(len);
584 read_extent_buffer(leaf, data,
585 (unsigned long)(di + 1) + name_len,
589 if (fsetxattr(fd, name, data, data_len, 0))
590 error("setting extended attribute %s on file %s: %m",
593 len = sizeof(*di) + name_len + data_len;
595 di = (struct btrfs_dir_item *)((char *)di + len);
601 btrfs_release_path(&path);
608 static int copy_metadata(struct btrfs_root *root, int fd,
609 struct btrfs_key *key)
611 struct btrfs_path path;
612 struct btrfs_inode_item *inode_item;
615 btrfs_init_path(&path);
616 ret = btrfs_lookup_inode(NULL, root, &path, key, 0);
618 struct btrfs_timespec *bts;
619 struct timespec times[2];
621 inode_item = btrfs_item_ptr(path.nodes[0], path.slots[0],
622 struct btrfs_inode_item);
624 ret = fchown(fd, btrfs_inode_uid(path.nodes[0], inode_item),
625 btrfs_inode_gid(path.nodes[0], inode_item));
627 error("failed to change owner: %m");
631 ret = fchmod(fd, btrfs_inode_mode(path.nodes[0], inode_item));
633 error("failed to change mode: %m");
637 bts = btrfs_inode_atime(inode_item);
638 times[0].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
639 times[0].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
641 bts = btrfs_inode_mtime(inode_item);
642 times[1].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
643 times[1].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
645 ret = futimens(fd, times);
647 error("failed to set times: %m");
652 btrfs_release_path(&path);
656 static int copy_file(struct btrfs_root *root, int fd, struct btrfs_key *key,
659 struct extent_buffer *leaf;
660 struct btrfs_path path;
661 struct btrfs_file_extent_item *fi;
662 struct btrfs_inode_item *inode_item;
663 struct btrfs_timespec *bts;
664 struct btrfs_key found_key;
670 struct timespec times[2];
673 btrfs_init_path(&path);
674 ret = btrfs_lookup_inode(NULL, root, &path, key, 0);
676 inode_item = btrfs_item_ptr(path.nodes[0], path.slots[0],
677 struct btrfs_inode_item);
678 found_size = btrfs_inode_size(path.nodes[0], inode_item);
680 if (restore_metadata) {
682 * Change the ownership and mode now, set times when
683 * copyout is finished.
686 ret = fchown(fd, btrfs_inode_uid(path.nodes[0], inode_item),
687 btrfs_inode_gid(path.nodes[0], inode_item));
688 if (ret && !ignore_errors)
691 ret = fchmod(fd, btrfs_inode_mode(path.nodes[0], inode_item));
692 if (ret && !ignore_errors)
695 bts = btrfs_inode_atime(inode_item);
696 times[0].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
697 times[0].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
699 bts = btrfs_inode_mtime(inode_item);
700 times[1].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
701 times[1].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
705 btrfs_release_path(&path);
708 key->type = BTRFS_EXTENT_DATA_KEY;
710 ret = btrfs_search_slot(NULL, root, key, &path, 0, 0);
712 error("searching extent data returned %d", ret);
716 leaf = path.nodes[0];
718 ret = next_leaf(root, &path);
720 error("cannot get next leaf: %d", ret);
722 } else if (ret > 0) {
723 /* No more leaves to search */
727 leaf = path.nodes[0];
731 if (loops >= 0 && loops++ >= 1024) {
732 enum loop_response resp;
734 resp = ask_to_continue(file);
735 if (resp == LOOP_STOP)
737 else if (resp == LOOP_CONTINUE)
739 else if (resp == LOOP_DONTASK)
742 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
744 ret = next_leaf(root, &path);
746 fprintf(stderr, "Error searching %d\n", ret);
749 /* No more leaves to search */
750 btrfs_release_path(&path);
753 leaf = path.nodes[0];
757 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
758 if (found_key.objectid != key->objectid)
760 if (found_key.type != key->type)
762 fi = btrfs_item_ptr(leaf, path.slots[0],
763 struct btrfs_file_extent_item);
764 extent_type = btrfs_file_extent_type(leaf, fi);
765 compression = btrfs_file_extent_compression(leaf, fi);
766 if (compression >= BTRFS_COMPRESS_LAST) {
767 warning("compression type %d not supported",
773 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC)
775 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
776 ret = copy_one_inline(root, fd, &path, found_key.offset);
779 } else if (extent_type == BTRFS_FILE_EXTENT_REG) {
780 ret = copy_one_extent(root, fd, leaf, fi,
785 warning("weird extent type %d", extent_type);
791 btrfs_release_path(&path);
794 ret = ftruncate(fd, (loff_t)found_size);
799 ret = set_file_xattrs(root, key->objectid, fd, file);
803 if (restore_metadata && times_ok) {
804 ret = futimens(fd, times);
811 btrfs_release_path(&path);
817 * 0 if the file exists and should be skipped.
818 * 1 if the file does NOT exist
819 * 2 if the file exists but is OK to overwrite
821 static int overwrite_ok(const char * path)
827 /* don't be fooled by symlinks */
828 ret = fstatat(-1, path_name, &st, AT_SYMLINK_NOFOLLOW);
834 if (verbose || !warn)
835 printf("Skipping existing file"
838 printf("If you wish to overwrite use -o\n");
845 static int copy_symlink(struct btrfs_root *root, struct btrfs_key *key,
848 struct btrfs_path path;
849 struct extent_buffer *leaf;
850 struct btrfs_file_extent_item *extent_item;
851 struct btrfs_inode_item *inode_item;
855 struct btrfs_timespec *bts;
856 struct timespec times[2];
858 ret = overwrite_ok(path_name);
860 return 0; /* skip this file */
862 /* symlink() can't overwrite, so unlink first */
864 ret = unlink(path_name);
866 fprintf(stderr, "failed to unlink '%s' for overwrite\n",
872 btrfs_init_path(&path);
873 key->type = BTRFS_EXTENT_DATA_KEY;
875 ret = btrfs_search_slot(NULL, root, key, &path, 0, 0);
879 leaf = path.nodes[0];
881 fprintf(stderr, "Error getting leaf for symlink '%s'\n", file);
886 extent_item = btrfs_item_ptr(leaf, path.slots[0],
887 struct btrfs_file_extent_item);
889 len = btrfs_file_extent_inline_item_len(leaf,
890 btrfs_item_nr(path.slots[0]));
891 if (len >= PATH_MAX) {
892 fprintf(stderr, "Symlink '%s' target length %d is longer than PATH_MAX\n",
898 name_offset = (unsigned long) extent_item
899 + offsetof(struct btrfs_file_extent_item, disk_bytenr);
900 read_extent_buffer(leaf, symlink_target, name_offset, len);
902 symlink_target[len] = 0;
905 ret = symlink(symlink_target, path_name);
907 fprintf(stderr, "Failed to restore symlink '%s': %m\n",
912 printf("SYMLINK: '%s' => '%s'\n", path_name, symlink_target);
915 if (!restore_metadata)
919 * Symlink metadata operates differently than files/directories, so do
922 key->type = BTRFS_INODE_ITEM_KEY;
925 btrfs_release_path(&path);
927 ret = btrfs_lookup_inode(NULL, root, &path, key, 0);
929 fprintf(stderr, "Failed to lookup inode for '%s'\n", file);
933 inode_item = btrfs_item_ptr(path.nodes[0], path.slots[0],
934 struct btrfs_inode_item);
936 ret = fchownat(-1, file, btrfs_inode_uid(path.nodes[0], inode_item),
937 btrfs_inode_gid(path.nodes[0], inode_item),
938 AT_SYMLINK_NOFOLLOW);
940 fprintf(stderr, "Failed to change owner: %m\n");
944 bts = btrfs_inode_atime(inode_item);
945 times[0].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
946 times[0].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
948 bts = btrfs_inode_mtime(inode_item);
949 times[1].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
950 times[1].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
952 ret = utimensat(-1, file, times, AT_SYMLINK_NOFOLLOW);
954 fprintf(stderr, "Failed to set times: %m\n");
956 btrfs_release_path(&path);
960 static int search_dir(struct btrfs_root *root, struct btrfs_key *key,
961 const char *output_rootdir, const char *in_dir,
964 struct btrfs_path path;
965 struct extent_buffer *leaf;
966 struct btrfs_dir_item *dir_item;
967 struct btrfs_key found_key, location;
968 char filename[BTRFS_NAME_LEN + 1];
969 unsigned long name_ptr;
976 btrfs_init_path(&path);
978 key->type = BTRFS_DIR_INDEX_KEY;
979 ret = btrfs_search_slot(NULL, root, key, &path, 0, 0);
981 fprintf(stderr, "Error searching %d\n", ret);
987 leaf = path.nodes[0];
990 printf("No leaf after search, looking for the next "
992 ret = next_leaf(root, &path);
994 fprintf(stderr, "Error getting next leaf %d\n",
997 } else if (ret > 0) {
998 /* No more leaves to search */
1000 printf("Reached the end of the tree looking "
1001 "for the directory\n");
1005 leaf = path.nodes[0];
1009 if (loops++ >= 1024) {
1010 printf("We have looped trying to restore files in %s "
1011 "too many times to be making progress, "
1012 "stopping\n", in_dir);
1016 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1018 ret = next_leaf(root, &path);
1020 fprintf(stderr, "Error searching %d\n",
1023 } else if (ret > 0) {
1024 /* No more leaves to search */
1026 printf("Reached the end of "
1027 "the tree searching the"
1032 leaf = path.nodes[0];
1036 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
1037 if (found_key.objectid != key->objectid) {
1039 printf("Found objectid=%Lu, key=%Lu\n",
1040 found_key.objectid, key->objectid);
1043 if (found_key.type != key->type) {
1045 printf("Found type=%u, want=%u\n",
1046 found_key.type, key->type);
1049 dir_item = btrfs_item_ptr(leaf, path.slots[0],
1050 struct btrfs_dir_item);
1051 name_ptr = (unsigned long)(dir_item + 1);
1052 name_len = btrfs_dir_name_len(leaf, dir_item);
1053 read_extent_buffer(leaf, filename, name_ptr, name_len);
1054 filename[name_len] = '\0';
1055 type = btrfs_dir_type(leaf, dir_item);
1056 btrfs_dir_item_key_to_cpu(leaf, dir_item, &location);
1058 /* full path from root of btrfs being restored */
1059 snprintf(fs_name, PATH_MAX, "%s/%s", in_dir, filename);
1061 if (mreg && REG_NOMATCH == regexec(mreg, fs_name, 0, NULL, 0))
1064 /* full path from system root */
1065 snprintf(path_name, PATH_MAX, "%s%s", output_rootdir, fs_name);
1068 * Restore directories, files, symlinks and metadata.
1070 if (type == BTRFS_FT_REG_FILE) {
1071 if (!overwrite_ok(path_name))
1075 printf("Restoring %s\n", path_name);
1078 fd = open(path_name, O_CREAT|O_WRONLY, 0644);
1080 fprintf(stderr, "Error creating %s: %d\n",
1088 ret = copy_file(root, fd, &location, path_name);
1091 fprintf(stderr, "Error copying data for %s\n",
1097 } else if (type == BTRFS_FT_DIR) {
1098 struct btrfs_root *search_root = root;
1099 char *dir = strdup(fs_name);
1102 fprintf(stderr, "Ran out of memory\n");
1107 if (location.type == BTRFS_ROOT_ITEM_KEY) {
1109 * If we are a snapshot and this is the index
1110 * object to ourselves just skip it.
1112 if (location.objectid ==
1113 root->root_key.objectid) {
1118 location.offset = (u64)-1;
1119 search_root = btrfs_read_fs_root(root->fs_info,
1121 if (IS_ERR(search_root)) {
1123 fprintf(stderr, "Error reading "
1124 "subvolume %s: %lu\n",
1126 PTR_ERR(search_root));
1129 ret = PTR_ERR(search_root);
1134 * A subvolume will have a key.offset of 0, a
1135 * snapshot will have key.offset of a transid.
1137 if (search_root->root_key.offset != 0 &&
1140 printf("Skipping snapshot %s\n",
1144 location.objectid = BTRFS_FIRST_FREE_OBJECTID;
1148 printf("Restoring %s\n", path_name);
1154 ret = mkdir(path_name, 0755);
1155 if (ret && errno != EEXIST) {
1157 fprintf(stderr, "Error mkdiring %s: %d\n",
1165 ret = search_dir(search_root, &location,
1166 output_rootdir, dir, mreg);
1169 fprintf(stderr, "Error searching %s\n",
1175 } else if (type == BTRFS_FT_SYMLINK) {
1176 if (restore_symlinks)
1177 ret = copy_symlink(root, &location, path_name);
1181 btrfs_release_path(&path);
1189 if (restore_metadata) {
1190 snprintf(path_name, PATH_MAX, "%s%s", output_rootdir, in_dir);
1191 fd = open(path_name, O_RDONLY);
1193 fprintf(stderr, "ERROR: Failed to access %s to restore metadata\n",
1195 if (!ignore_errors) {
1201 * Set owner/mode/time on the directory as well
1203 key->type = BTRFS_INODE_ITEM_KEY;
1204 ret = copy_metadata(root, fd, key);
1206 if (ret && !ignore_errors)
1212 printf("Done searching %s\n", in_dir);
1214 btrfs_release_path(&path);
1218 static int do_list_roots(struct btrfs_root *root)
1220 struct btrfs_key key;
1221 struct btrfs_key found_key;
1222 struct btrfs_disk_key disk_key;
1223 struct btrfs_path path;
1224 struct extent_buffer *leaf;
1225 struct btrfs_root_item ri;
1226 unsigned long offset;
1230 root = root->fs_info->tree_root;
1232 btrfs_init_path(&path);
1235 key.type = BTRFS_ROOT_ITEM_KEY;
1236 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1238 fprintf(stderr, "Failed to do search %d\n", ret);
1239 btrfs_release_path(&path);
1243 leaf = path.nodes[0];
1246 slot = path.slots[0];
1247 if (slot >= btrfs_header_nritems(leaf)) {
1248 ret = btrfs_next_leaf(root, &path);
1251 leaf = path.nodes[0];
1252 slot = path.slots[0];
1254 btrfs_item_key(leaf, &disk_key, slot);
1255 btrfs_disk_key_to_cpu(&found_key, &disk_key);
1256 if (found_key.type != BTRFS_ROOT_ITEM_KEY) {
1261 offset = btrfs_item_ptr_offset(leaf, slot);
1262 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
1264 btrfs_print_key(&disk_key);
1265 printf(" %Lu level %d\n", btrfs_root_bytenr(&ri),
1266 btrfs_root_level(&ri));
1269 btrfs_release_path(&path);
1274 static struct btrfs_root *open_fs(const char *dev, u64 root_location,
1275 int super_mirror, int list_roots)
1277 struct btrfs_fs_info *fs_info = NULL;
1278 struct btrfs_root *root = NULL;
1282 for (i = super_mirror; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1283 bytenr = btrfs_sb_offset(i);
1286 * Restore won't allocate extent and doesn't care anything
1287 * in extent tree. Skip block group item search will allow
1288 * restore to be executed on heavily damaged fs.
1290 fs_info = open_ctree_fs_info(dev, bytenr, root_location, 0,
1291 OPEN_CTREE_PARTIAL |
1292 OPEN_CTREE_NO_BLOCK_GROUPS);
1295 fprintf(stderr, "Could not open root, trying backup super\n");
1302 * All we really need to succeed is reading the chunk tree, everything
1303 * else we can do by hand, since we only need to read the tree root and
1306 if (!extent_buffer_uptodate(fs_info->tree_root->node)) {
1309 root = fs_info->tree_root;
1311 root_location = btrfs_super_root(fs_info->super_copy);
1312 generation = btrfs_super_generation(fs_info->super_copy);
1313 root->node = read_tree_block(fs_info, root_location,
1315 if (!extent_buffer_uptodate(root->node)) {
1316 fprintf(stderr, "Error opening tree root\n");
1322 if (!list_roots && !fs_info->fs_root) {
1323 struct btrfs_key key;
1325 key.objectid = BTRFS_FS_TREE_OBJECTID;
1326 key.type = BTRFS_ROOT_ITEM_KEY;
1327 key.offset = (u64)-1;
1328 fs_info->fs_root = btrfs_read_fs_root_no_cache(fs_info, &key);
1329 if (IS_ERR(fs_info->fs_root)) {
1330 fprintf(stderr, "Couldn't read fs root: %ld\n",
1331 PTR_ERR(fs_info->fs_root));
1332 close_ctree(fs_info->tree_root);
1337 if (list_roots && do_list_roots(fs_info->tree_root)) {
1338 close_ctree(fs_info->tree_root);
1342 return fs_info->fs_root;
1345 static int find_first_dir(struct btrfs_root *root, u64 *objectid)
1347 struct btrfs_path path;
1348 struct btrfs_key found_key;
1349 struct btrfs_key key;
1353 btrfs_init_path(&path);
1355 key.type = BTRFS_DIR_INDEX_KEY;
1357 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1359 fprintf(stderr, "Error searching %d\n", ret);
1363 if (!path.nodes[0]) {
1364 fprintf(stderr, "No leaf!\n");
1368 for (i = path.slots[0];
1369 i < btrfs_header_nritems(path.nodes[0]); i++) {
1370 btrfs_item_key_to_cpu(path.nodes[0], &found_key, i);
1371 if (found_key.type != key.type)
1374 printf("Using objectid %Lu for first dir\n",
1375 found_key.objectid);
1376 *objectid = found_key.objectid;
1381 ret = next_leaf(root, &path);
1383 fprintf(stderr, "Error getting next leaf %d\n",
1386 } else if (ret > 0) {
1387 fprintf(stderr, "No more leaves\n");
1390 } while (!path.nodes[0]);
1393 printf("Couldn't find a dir index item\n");
1395 btrfs_release_path(&path);
1399 const char * const cmd_restore_usage[] = {
1400 "btrfs restore [options] <device> <path> | -l <device>",
1401 "Try to restore files from a damaged filesystem (unmounted)",
1403 "-s|--snapshots get snapshots",
1404 "-x|--xattr restore extended attributes",
1405 "-m|--metadata restore owner, mode and times",
1406 "-S|--symlink restore symbolic links",
1407 "-v|--verbose verbose",
1408 "-i|--ignore-errors ignore errors",
1409 "-o|--overwrite overwrite",
1410 "-t <bytenr> tree location",
1411 "-f <bytenr> filesystem location",
1412 "-u|--super <mirror> super mirror",
1413 "-r|--root <rootid> root objectid",
1415 "-l|--list-roots list tree roots",
1416 "-D|--dry-run dry run (only list files that would be recovered)",
1417 "--path-regex <regex>",
1418 " restore only filenames matching regex,",
1419 " you have to use following syntax (possibly quoted):",
1420 " ^/(|home(|/username(|/Desktop(|/.*))))$",
1421 "-c ignore case (--path-regex only)",
1425 int cmd_restore(int argc, char **argv)
1427 struct btrfs_root *root;
1428 struct btrfs_key key;
1429 char dir_name[PATH_MAX];
1430 u64 tree_location = 0;
1431 u64 fs_location = 0;
1432 u64 root_objectid = 0;
1435 int super_mirror = 0;
1438 const char *match_regstr = NULL;
1439 int match_cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
1440 regex_t match_reg, *mreg = NULL;
1445 enum { GETOPT_VAL_PATH_REGEX = 256 };
1446 static const struct option long_options[] = {
1447 { "path-regex", required_argument, NULL,
1448 GETOPT_VAL_PATH_REGEX },
1449 { "dry-run", no_argument, NULL, 'D'},
1450 { "metadata", no_argument, NULL, 'm'},
1451 { "symlinks", no_argument, NULL, 'S'},
1452 { "snapshots", no_argument, NULL, 's'},
1453 { "xattr", no_argument, NULL, 'x'},
1454 { "verbose", no_argument, NULL, 'v'},
1455 { "ignore-errors", no_argument, NULL, 'i'},
1456 { "overwrite", no_argument, NULL, 'o'},
1457 { "super", required_argument, NULL, 'u'},
1458 { "root", required_argument, NULL, 'r'},
1459 { "list-roots", no_argument, NULL, 'l'},
1463 opt = getopt_long(argc, argv, "sSxviot:u:dmf:r:lDc", long_options,
1482 tree_location = arg_strtou64(optarg);
1485 fs_location = arg_strtou64(optarg);
1488 super_mirror = arg_strtou64(optarg);
1489 if (super_mirror >= BTRFS_SUPER_MIRROR_MAX) {
1490 fprintf(stderr, "Super mirror not "
1499 root_objectid = arg_strtou64(optarg);
1500 if (!is_fstree(root_objectid)) {
1501 fprintf(stderr, "objectid %llu is not a valid fs/file tree\n",
1510 restore_metadata = 1;
1513 restore_symlinks = 1;
1519 match_cflags |= REG_ICASE;
1521 case GETOPT_VAL_PATH_REGEX:
1522 match_regstr = optarg;
1528 usage(cmd_restore_usage);
1532 if (!list_roots && check_argc_min(argc - optind, 2))
1533 usage(cmd_restore_usage);
1534 else if (list_roots && check_argc_min(argc - optind, 1))
1535 usage(cmd_restore_usage);
1537 if (fs_location && root_objectid) {
1538 fprintf(stderr, "don't use -f and -r at the same time.\n");
1542 if ((ret = check_mounted(argv[optind])) < 0) {
1543 fprintf(stderr, "Could not check mount status: %s\n",
1547 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
1551 root = open_fs(argv[optind], tree_location, super_mirror, list_roots);
1558 if (fs_location != 0) {
1559 free_extent_buffer(root->node);
1560 root->node = read_tree_block(root->fs_info, fs_location, 0);
1561 if (!extent_buffer_uptodate(root->node)) {
1562 fprintf(stderr, "Failed to read fs location\n");
1568 memset(path_name, 0, PATH_MAX);
1570 if (strlen(argv[optind + 1]) >= PATH_MAX) {
1571 fprintf(stderr, "ERROR: path too long\n");
1575 strncpy(dir_name, argv[optind + 1], sizeof dir_name);
1576 dir_name[sizeof dir_name - 1] = 0;
1578 /* Strip the trailing / on the dir name */
1579 len = strlen(dir_name);
1580 while (len && dir_name[--len] == '/') {
1581 dir_name[len] = '\0';
1584 if (root_objectid != 0) {
1585 struct btrfs_root *orig_root = root;
1587 key.objectid = root_objectid;
1588 key.type = BTRFS_ROOT_ITEM_KEY;
1589 key.offset = (u64)-1;
1590 root = btrfs_read_fs_root(orig_root->fs_info, &key);
1592 fprintf(stderr, "fail to read root %llu: %s\n",
1593 root_objectid, strerror(-PTR_ERR(root)));
1603 ret = find_first_dir(root, &key.objectid);
1607 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
1611 ret = regcomp(&match_reg, match_regstr, match_cflags);
1613 regerror(ret, &match_reg, reg_err, sizeof(reg_err));
1614 fprintf(stderr, "Regex compile failed: %s\n", reg_err);
1621 printf("This is a dry-run, no files are going to be restored\n");
1623 ret = search_dir(root, &key, dir_name, "", mreg);