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"
47 static char fs_name[PATH_MAX];
48 static char path_name[PATH_MAX];
49 static char symlink_target[PATH_MAX];
50 static int get_snaps = 0;
51 static int verbose = 0;
52 static int restore_metadata = 0;
53 static int restore_symlinks = 0;
54 static int ignore_errors = 0;
55 static int overwrite = 0;
56 static int get_xattrs = 0;
57 static int dry_run = 0;
60 #define lzo1x_worst_compress(x) ((x) + ((x) / 16) + 64 + 3)
62 static int decompress_zlib(char *inbuf, char *outbuf, u64 compress_len,
68 memset(&strm, 0, sizeof(strm));
69 ret = inflateInit(&strm);
71 error("zlib init returned %d", ret);
75 strm.avail_in = compress_len;
76 strm.next_in = (unsigned char *)inbuf;
77 strm.avail_out = decompress_len;
78 strm.next_out = (unsigned char *)outbuf;
79 ret = inflate(&strm, Z_NO_FLUSH);
80 if (ret != Z_STREAM_END) {
81 (void)inflateEnd(&strm);
82 error("zlib inflate failed: %d", ret);
86 (void)inflateEnd(&strm);
89 static inline size_t read_compress_length(unsigned char *buf)
92 memcpy(&dlen, buf, LZO_LEN);
93 return le32_to_cpu(dlen);
96 static int decompress_lzo(struct btrfs_root *root, unsigned char *inbuf,
97 char *outbuf, u64 compress_len, u64 *decompress_len)
107 if (ret != LZO_E_OK) {
108 error("lzo init returned %d", ret);
112 tot_len = read_compress_length(inbuf);
116 while (tot_in < tot_len) {
119 in_len = read_compress_length(inbuf);
121 if ((tot_in + LZO_LEN + in_len) > tot_len) {
122 error("bad compress length %lu",
123 (unsigned long)in_len);
129 new_len = lzo1x_worst_compress(root->sectorsize);
130 ret = lzo1x_decompress_safe((const unsigned char *)inbuf, in_len,
131 (unsigned char *)outbuf,
132 (void *)&new_len, NULL);
133 if (ret != LZO_E_OK) {
134 error("lzo decompress failed: %d", ret);
143 * If the 4 byte header does not fit to the rest of the page we
144 * have to move to the next one, unless we read some garbage
146 mod_page = tot_in % root->sectorsize;
147 rem_page = root->sectorsize - mod_page;
148 if (rem_page < LZO_LEN) {
154 *decompress_len = out_len;
159 static int decompress(struct btrfs_root *root, char *inbuf, char *outbuf,
160 u64 compress_len, u64 *decompress_len, int compress)
163 case BTRFS_COMPRESS_ZLIB:
164 return decompress_zlib(inbuf, outbuf, compress_len,
166 case BTRFS_COMPRESS_LZO:
167 return decompress_lzo(root, (unsigned char *)inbuf, outbuf,
168 compress_len, decompress_len);
173 error("invalid compression type: %d", compress);
177 static int next_leaf(struct btrfs_root *root, struct btrfs_path *path)
182 struct extent_buffer *c;
183 struct extent_buffer *next = NULL;
186 for (; level < BTRFS_MAX_LEVEL; level++) {
187 if (path->nodes[level])
191 if (level >= BTRFS_MAX_LEVEL)
194 slot = path->slots[level] + 1;
196 while(level < BTRFS_MAX_LEVEL) {
197 if (!path->nodes[level])
200 slot = path->slots[level] + offset;
201 c = path->nodes[level];
202 if (slot >= btrfs_header_nritems(c)) {
204 if (level == BTRFS_MAX_LEVEL)
211 reada_for_search(root, path, level, slot, 0);
213 next = read_node_slot(root, c, slot);
214 if (extent_buffer_uptodate(next))
218 path->slots[level] = slot;
221 c = path->nodes[level];
222 free_extent_buffer(c);
223 path->nodes[level] = next;
224 path->slots[level] = 0;
228 reada_for_search(root, path, level, 0, 0);
229 next = read_node_slot(root, next, 0);
230 if (!extent_buffer_uptodate(next))
236 static int copy_one_inline(struct btrfs_root *root, int fd,
237 struct btrfs_path *path, u64 pos)
239 struct extent_buffer *leaf = path->nodes[0];
240 struct btrfs_file_extent_item *fi;
251 fi = btrfs_item_ptr(leaf, path->slots[0],
252 struct btrfs_file_extent_item);
253 ptr = btrfs_file_extent_inline_start(fi);
254 len = btrfs_file_extent_inline_len(leaf, path->slots[0], fi);
255 inline_item_len = btrfs_file_extent_inline_item_len(leaf, btrfs_item_nr(path->slots[0]));
256 read_extent_buffer(leaf, buf, ptr, inline_item_len);
258 compress = btrfs_file_extent_compression(leaf, fi);
259 if (compress == BTRFS_COMPRESS_NONE) {
260 done = pwrite(fd, buf, len, pos);
262 fprintf(stderr, "Short inline write, wanted %d, did "
263 "%zd: %d\n", len, done, errno);
269 ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
270 outbuf = calloc(1, ram_size);
272 error("not enough memory");
276 ret = decompress(root, buf, outbuf, len, &ram_size, compress);
282 done = pwrite(fd, outbuf, ram_size, pos);
284 if (done < ram_size) {
285 fprintf(stderr, "Short compressed inline write, wanted %Lu, "
286 "did %zd: %d\n", ram_size, done, errno);
293 static int copy_one_extent(struct btrfs_root *root, int fd,
294 struct extent_buffer *leaf,
295 struct btrfs_file_extent_item *fi, u64 pos)
297 struct btrfs_multi_bio *multi = NULL;
298 struct btrfs_device *device;
299 char *inbuf, *outbuf = NULL;
300 ssize_t done, total = 0;
316 compress = btrfs_file_extent_compression(leaf, fi);
317 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
318 disk_size = btrfs_file_extent_disk_num_bytes(leaf, fi);
319 ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
320 offset = btrfs_file_extent_offset(leaf, fi);
321 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
322 size_left = disk_size;
323 if (compress == BTRFS_COMPRESS_NONE)
326 if (verbose && offset)
327 printf("offset is %Lu\n", offset);
328 /* we found a hole */
332 inbuf = malloc(size_left);
334 error("not enough memory");
338 if (compress != BTRFS_COMPRESS_NONE) {
339 outbuf = calloc(1, ram_size);
341 error("not enough memory");
348 ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
349 bytenr, &length, &multi, mirror_num, NULL);
351 error("cannot map block logical %llu length %llu: %d",
352 (unsigned long long)bytenr,
353 (unsigned long long)length, ret);
356 device = multi->stripes[0].dev;
359 dev_bytenr = multi->stripes[0].physical;
362 if (size_left < length)
365 done = pread(dev_fd, inbuf+count, length, dev_bytenr);
366 /* Need both checks, or we miss negative values due to u64 conversion */
367 if (done < 0 || done < length) {
368 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
371 /* mirror_num is 1-indexed, so num_copies is a valid mirror. */
372 if (mirror_num > num_copies) {
374 error("exhausted mirrors trying to read (%d > %d)",
375 mirror_num, num_copies);
378 fprintf(stderr, "Trying another mirror\n");
389 if (compress == BTRFS_COMPRESS_NONE) {
390 while (total < num_bytes) {
391 done = pwrite(fd, inbuf+total, num_bytes-total,
395 error("cannot write data: %d %s", errno, strerror(errno));
404 ret = decompress(root, inbuf, outbuf, disk_size, &ram_size, compress);
406 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
409 if (mirror_num >= num_copies) {
413 fprintf(stderr, "Trying another mirror\n");
417 while (total < num_bytes) {
418 done = pwrite(fd, outbuf + offset + total,
439 static enum loop_response ask_to_continue(const char *file)
444 printf("We seem to be looping a lot on %s, do you want to keep going "
445 "on ? (y/N/a): ", file);
447 ret = fgets(buf, 2, stdin);
448 if (*ret == '\n' || tolower(*ret) == 'n')
450 if (tolower(*ret) == 'a')
452 if (tolower(*ret) != 'y') {
453 printf("Please enter one of 'y', 'n', or 'a': ");
457 return LOOP_CONTINUE;
461 static int set_file_xattrs(struct btrfs_root *root, u64 inode,
462 int fd, const char *file_name)
464 struct btrfs_key key;
465 struct btrfs_path path;
466 struct extent_buffer *leaf;
467 struct btrfs_dir_item *di;
476 btrfs_init_path(&path);
477 key.objectid = inode;
478 key.type = BTRFS_XATTR_ITEM_KEY;
480 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
484 leaf = path.nodes[0];
486 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
488 ret = next_leaf(root, &path);
490 error("searching for extended attributes: %d",
494 /* No more leaves to search */
498 leaf = path.nodes[0];
503 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
504 if (key.type != BTRFS_XATTR_ITEM_KEY || key.objectid != inode)
507 total_len = btrfs_item_size_nr(leaf, path.slots[0]);
508 di = btrfs_item_ptr(leaf, path.slots[0],
509 struct btrfs_dir_item);
511 while (cur < total_len) {
512 len = btrfs_dir_name_len(leaf, di);
513 if (len > name_len) {
515 name = (char *) malloc(len + 1);
521 read_extent_buffer(leaf, name,
522 (unsigned long)(di + 1), len);
526 len = btrfs_dir_data_len(leaf, di);
527 if (len > data_len) {
529 data = (char *) malloc(len);
535 read_extent_buffer(leaf, data,
536 (unsigned long)(di + 1) + name_len,
540 if (fsetxattr(fd, name, data, data_len, 0))
541 error("setting extended attribute %s on file %s: %s",
542 name, file_name, strerror(errno));
544 len = sizeof(*di) + name_len + data_len;
546 di = (struct btrfs_dir_item *)((char *)di + len);
552 btrfs_release_path(&path);
559 static int copy_metadata(struct btrfs_root *root, int fd,
560 struct btrfs_key *key)
562 struct btrfs_path path;
563 struct btrfs_inode_item *inode_item;
566 btrfs_init_path(&path);
567 ret = btrfs_lookup_inode(NULL, root, &path, key, 0);
569 struct btrfs_timespec *bts;
570 struct timespec times[2];
572 inode_item = btrfs_item_ptr(path.nodes[0], path.slots[0],
573 struct btrfs_inode_item);
575 ret = fchown(fd, btrfs_inode_uid(path.nodes[0], inode_item),
576 btrfs_inode_gid(path.nodes[0], inode_item));
578 error("failed to change owner: %s", strerror(errno));
582 ret = fchmod(fd, btrfs_inode_mode(path.nodes[0], inode_item));
584 error("failed to change mode: %s", strerror(errno));
588 bts = btrfs_inode_atime(inode_item);
589 times[0].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
590 times[0].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
592 bts = btrfs_inode_mtime(inode_item);
593 times[1].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
594 times[1].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
596 ret = futimens(fd, times);
598 error("failed to set times: %s", strerror(errno));
603 btrfs_release_path(&path);
607 static int copy_file(struct btrfs_root *root, int fd, struct btrfs_key *key,
610 struct extent_buffer *leaf;
611 struct btrfs_path path;
612 struct btrfs_file_extent_item *fi;
613 struct btrfs_inode_item *inode_item;
614 struct btrfs_timespec *bts;
615 struct btrfs_key found_key;
621 struct timespec times[2];
624 btrfs_init_path(&path);
625 ret = btrfs_lookup_inode(NULL, root, &path, key, 0);
627 inode_item = btrfs_item_ptr(path.nodes[0], path.slots[0],
628 struct btrfs_inode_item);
629 found_size = btrfs_inode_size(path.nodes[0], inode_item);
631 if (restore_metadata) {
633 * Change the ownership and mode now, set times when
634 * copyout is finished.
637 ret = fchown(fd, btrfs_inode_uid(path.nodes[0], inode_item),
638 btrfs_inode_gid(path.nodes[0], inode_item));
639 if (ret && !ignore_errors)
642 ret = fchmod(fd, btrfs_inode_mode(path.nodes[0], inode_item));
643 if (ret && !ignore_errors)
646 bts = btrfs_inode_atime(inode_item);
647 times[0].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
648 times[0].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
650 bts = btrfs_inode_mtime(inode_item);
651 times[1].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
652 times[1].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
656 btrfs_release_path(&path);
659 key->type = BTRFS_EXTENT_DATA_KEY;
661 ret = btrfs_search_slot(NULL, root, key, &path, 0, 0);
663 error("searching extent data returned %d", ret);
667 leaf = path.nodes[0];
669 ret = next_leaf(root, &path);
671 error("cannot get next leaf: %d", ret);
673 } else if (ret > 0) {
674 /* No more leaves to search */
678 leaf = path.nodes[0];
682 if (loops >= 0 && loops++ >= 1024) {
683 enum loop_response resp;
685 resp = ask_to_continue(file);
686 if (resp == LOOP_STOP)
688 else if (resp == LOOP_CONTINUE)
690 else if (resp == LOOP_DONTASK)
693 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
695 ret = next_leaf(root, &path);
697 fprintf(stderr, "Error searching %d\n", ret);
700 /* No more leaves to search */
701 btrfs_release_path(&path);
704 leaf = path.nodes[0];
708 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
709 if (found_key.objectid != key->objectid)
711 if (found_key.type != key->type)
713 fi = btrfs_item_ptr(leaf, path.slots[0],
714 struct btrfs_file_extent_item);
715 extent_type = btrfs_file_extent_type(leaf, fi);
716 compression = btrfs_file_extent_compression(leaf, fi);
717 if (compression >= BTRFS_COMPRESS_LAST) {
718 warning("compression type %d not supported",
724 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC)
726 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
727 ret = copy_one_inline(root, fd, &path, found_key.offset);
730 } else if (extent_type == BTRFS_FILE_EXTENT_REG) {
731 ret = copy_one_extent(root, fd, leaf, fi,
736 warning("weird extent type %d", extent_type);
742 btrfs_release_path(&path);
745 ret = ftruncate(fd, (loff_t)found_size);
750 ret = set_file_xattrs(root, key->objectid, fd, file);
754 if (restore_metadata && times_ok) {
755 ret = futimens(fd, times);
762 btrfs_release_path(&path);
768 * 0 if the file exists and should be skipped.
769 * 1 if the file does NOT exist
770 * 2 if the file exists but is OK to overwrite
772 static int overwrite_ok(const char * path)
778 /* don't be fooled by symlinks */
779 ret = fstatat(-1, path_name, &st, AT_SYMLINK_NOFOLLOW);
785 if (verbose || !warn)
786 printf("Skipping existing file"
789 printf("If you wish to overwrite use -o\n");
796 static int copy_symlink(struct btrfs_root *root, struct btrfs_key *key,
799 struct btrfs_path path;
800 struct extent_buffer *leaf;
801 struct btrfs_file_extent_item *extent_item;
802 struct btrfs_inode_item *inode_item;
806 struct btrfs_timespec *bts;
807 struct timespec times[2];
809 ret = overwrite_ok(path_name);
811 return 0; /* skip this file */
813 /* symlink() can't overwrite, so unlink first */
815 ret = unlink(path_name);
817 fprintf(stderr, "failed to unlink '%s' for overwrite\n",
823 btrfs_init_path(&path);
824 key->type = BTRFS_EXTENT_DATA_KEY;
826 ret = btrfs_search_slot(NULL, root, key, &path, 0, 0);
830 leaf = path.nodes[0];
832 fprintf(stderr, "Error getting leaf for symlink '%s'\n", file);
837 extent_item = btrfs_item_ptr(leaf, path.slots[0],
838 struct btrfs_file_extent_item);
840 len = btrfs_file_extent_inline_item_len(leaf,
841 btrfs_item_nr(path.slots[0]));
842 if (len >= PATH_MAX) {
843 fprintf(stderr, "Symlink '%s' target length %d is longer than PATH_MAX\n",
849 name_offset = (unsigned long) extent_item
850 + offsetof(struct btrfs_file_extent_item, disk_bytenr);
851 read_extent_buffer(leaf, symlink_target, name_offset, len);
853 symlink_target[len] = 0;
856 ret = symlink(symlink_target, path_name);
858 fprintf(stderr, "Failed to restore symlink '%s': %s\n",
859 path_name, strerror(errno));
863 printf("SYMLINK: '%s' => '%s'\n", path_name, symlink_target);
866 if (!restore_metadata)
870 * Symlink metadata operates differently than files/directories, so do
873 key->type = BTRFS_INODE_ITEM_KEY;
876 btrfs_release_path(&path);
878 ret = btrfs_lookup_inode(NULL, root, &path, key, 0);
880 fprintf(stderr, "Failed to lookup inode for '%s'\n", file);
884 inode_item = btrfs_item_ptr(path.nodes[0], path.slots[0],
885 struct btrfs_inode_item);
887 ret = fchownat(-1, file, btrfs_inode_uid(path.nodes[0], inode_item),
888 btrfs_inode_gid(path.nodes[0], inode_item),
889 AT_SYMLINK_NOFOLLOW);
891 fprintf(stderr, "Failed to change owner: %s\n",
896 bts = btrfs_inode_atime(inode_item);
897 times[0].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
898 times[0].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
900 bts = btrfs_inode_mtime(inode_item);
901 times[1].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
902 times[1].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
904 ret = utimensat(-1, file, times, AT_SYMLINK_NOFOLLOW);
906 fprintf(stderr, "Failed to set times: %s\n", strerror(errno));
908 btrfs_release_path(&path);
912 static int search_dir(struct btrfs_root *root, struct btrfs_key *key,
913 const char *output_rootdir, const char *in_dir,
916 struct btrfs_path path;
917 struct extent_buffer *leaf;
918 struct btrfs_dir_item *dir_item;
919 struct btrfs_key found_key, location;
920 char filename[BTRFS_NAME_LEN + 1];
921 unsigned long name_ptr;
928 btrfs_init_path(&path);
930 key->type = BTRFS_DIR_INDEX_KEY;
931 ret = btrfs_search_slot(NULL, root, key, &path, 0, 0);
933 fprintf(stderr, "Error searching %d\n", ret);
939 leaf = path.nodes[0];
942 printf("No leaf after search, looking for the next "
944 ret = next_leaf(root, &path);
946 fprintf(stderr, "Error getting next leaf %d\n",
949 } else if (ret > 0) {
950 /* No more leaves to search */
952 printf("Reached the end of the tree looking "
953 "for the directory\n");
957 leaf = path.nodes[0];
961 if (loops++ >= 1024) {
962 printf("We have looped trying to restore files in %s "
963 "too many times to be making progress, "
964 "stopping\n", in_dir);
968 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
970 ret = next_leaf(root, &path);
972 fprintf(stderr, "Error searching %d\n",
975 } else if (ret > 0) {
976 /* No more leaves to search */
978 printf("Reached the end of "
979 "the tree searching the"
984 leaf = path.nodes[0];
988 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
989 if (found_key.objectid != key->objectid) {
991 printf("Found objectid=%Lu, key=%Lu\n",
992 found_key.objectid, key->objectid);
995 if (found_key.type != key->type) {
997 printf("Found type=%u, want=%u\n",
998 found_key.type, key->type);
1001 dir_item = btrfs_item_ptr(leaf, path.slots[0],
1002 struct btrfs_dir_item);
1003 name_ptr = (unsigned long)(dir_item + 1);
1004 name_len = btrfs_dir_name_len(leaf, dir_item);
1005 read_extent_buffer(leaf, filename, name_ptr, name_len);
1006 filename[name_len] = '\0';
1007 type = btrfs_dir_type(leaf, dir_item);
1008 btrfs_dir_item_key_to_cpu(leaf, dir_item, &location);
1010 /* full path from root of btrfs being restored */
1011 snprintf(fs_name, PATH_MAX, "%s/%s", in_dir, filename);
1013 if (mreg && REG_NOMATCH == regexec(mreg, fs_name, 0, NULL, 0))
1016 /* full path from system root */
1017 snprintf(path_name, PATH_MAX, "%s%s", output_rootdir, fs_name);
1020 * Restore directories, files, symlinks and metadata.
1022 if (type == BTRFS_FT_REG_FILE) {
1023 if (!overwrite_ok(path_name))
1027 printf("Restoring %s\n", path_name);
1030 fd = open(path_name, O_CREAT|O_WRONLY, 0644);
1032 fprintf(stderr, "Error creating %s: %d\n",
1040 ret = copy_file(root, fd, &location, path_name);
1043 fprintf(stderr, "Error copying data for %s\n",
1049 } else if (type == BTRFS_FT_DIR) {
1050 struct btrfs_root *search_root = root;
1051 char *dir = strdup(fs_name);
1054 fprintf(stderr, "Ran out of memory\n");
1059 if (location.type == BTRFS_ROOT_ITEM_KEY) {
1061 * If we are a snapshot and this is the index
1062 * object to ourselves just skip it.
1064 if (location.objectid ==
1065 root->root_key.objectid) {
1070 location.offset = (u64)-1;
1071 search_root = btrfs_read_fs_root(root->fs_info,
1073 if (IS_ERR(search_root)) {
1075 fprintf(stderr, "Error reading "
1076 "subvolume %s: %lu\n",
1078 PTR_ERR(search_root));
1081 ret = PTR_ERR(search_root);
1086 * A subvolume will have a key.offset of 0, a
1087 * snapshot will have key.offset of a transid.
1089 if (search_root->root_key.offset != 0 &&
1092 printf("Skipping snapshot %s\n",
1096 location.objectid = BTRFS_FIRST_FREE_OBJECTID;
1100 printf("Restoring %s\n", path_name);
1106 ret = mkdir(path_name, 0755);
1107 if (ret && errno != EEXIST) {
1109 fprintf(stderr, "Error mkdiring %s: %d\n",
1117 ret = search_dir(search_root, &location,
1118 output_rootdir, dir, mreg);
1121 fprintf(stderr, "Error searching %s\n",
1127 } else if (type == BTRFS_FT_SYMLINK) {
1128 if (restore_symlinks)
1129 ret = copy_symlink(root, &location, path_name);
1133 btrfs_release_path(&path);
1141 if (restore_metadata) {
1142 snprintf(path_name, PATH_MAX, "%s%s", output_rootdir, in_dir);
1143 fd = open(path_name, O_RDONLY);
1145 fprintf(stderr, "ERROR: Failed to access %s to restore metadata\n",
1147 if (!ignore_errors) {
1153 * Set owner/mode/time on the directory as well
1155 key->type = BTRFS_INODE_ITEM_KEY;
1156 ret = copy_metadata(root, fd, key);
1158 if (ret && !ignore_errors)
1164 printf("Done searching %s\n", in_dir);
1166 btrfs_release_path(&path);
1170 static int do_list_roots(struct btrfs_root *root)
1172 struct btrfs_key key;
1173 struct btrfs_key found_key;
1174 struct btrfs_disk_key disk_key;
1175 struct btrfs_path path;
1176 struct extent_buffer *leaf;
1177 struct btrfs_root_item ri;
1178 unsigned long offset;
1182 root = root->fs_info->tree_root;
1184 btrfs_init_path(&path);
1187 key.type = BTRFS_ROOT_ITEM_KEY;
1188 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1190 fprintf(stderr, "Failed to do search %d\n", ret);
1191 btrfs_release_path(&path);
1195 leaf = path.nodes[0];
1198 slot = path.slots[0];
1199 if (slot >= btrfs_header_nritems(leaf)) {
1200 ret = btrfs_next_leaf(root, &path);
1203 leaf = path.nodes[0];
1204 slot = path.slots[0];
1206 btrfs_item_key(leaf, &disk_key, slot);
1207 btrfs_disk_key_to_cpu(&found_key, &disk_key);
1208 if (found_key.type != BTRFS_ROOT_ITEM_KEY) {
1213 offset = btrfs_item_ptr_offset(leaf, slot);
1214 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
1216 btrfs_print_key(&disk_key);
1217 printf(" %Lu level %d\n", btrfs_root_bytenr(&ri),
1218 btrfs_root_level(&ri));
1221 btrfs_release_path(&path);
1226 static struct btrfs_root *open_fs(const char *dev, u64 root_location,
1227 int super_mirror, int list_roots)
1229 struct btrfs_fs_info *fs_info = NULL;
1230 struct btrfs_root *root = NULL;
1234 for (i = super_mirror; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1235 bytenr = btrfs_sb_offset(i);
1236 fs_info = open_ctree_fs_info(dev, bytenr, root_location, 0,
1237 OPEN_CTREE_PARTIAL);
1240 fprintf(stderr, "Could not open root, trying backup super\n");
1247 * All we really need to succeed is reading the chunk tree, everything
1248 * else we can do by hand, since we only need to read the tree root and
1251 if (!extent_buffer_uptodate(fs_info->tree_root->node)) {
1254 root = fs_info->tree_root;
1256 root_location = btrfs_super_root(fs_info->super_copy);
1257 generation = btrfs_super_generation(fs_info->super_copy);
1258 root->node = read_tree_block(root, root_location,
1259 root->nodesize, generation);
1260 if (!extent_buffer_uptodate(root->node)) {
1261 fprintf(stderr, "Error opening tree root\n");
1267 if (!list_roots && !fs_info->fs_root) {
1268 struct btrfs_key key;
1270 key.objectid = BTRFS_FS_TREE_OBJECTID;
1271 key.type = BTRFS_ROOT_ITEM_KEY;
1272 key.offset = (u64)-1;
1273 fs_info->fs_root = btrfs_read_fs_root_no_cache(fs_info, &key);
1274 if (IS_ERR(fs_info->fs_root)) {
1275 fprintf(stderr, "Couldn't read fs root: %ld\n",
1276 PTR_ERR(fs_info->fs_root));
1277 close_ctree(fs_info->tree_root);
1282 if (list_roots && do_list_roots(fs_info->tree_root)) {
1283 close_ctree(fs_info->tree_root);
1287 return fs_info->fs_root;
1290 static int find_first_dir(struct btrfs_root *root, u64 *objectid)
1292 struct btrfs_path path;
1293 struct btrfs_key found_key;
1294 struct btrfs_key key;
1298 btrfs_init_path(&path);
1300 key.type = BTRFS_DIR_INDEX_KEY;
1302 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1304 fprintf(stderr, "Error searching %d\n", ret);
1308 if (!path.nodes[0]) {
1309 fprintf(stderr, "No leaf!\n");
1313 for (i = path.slots[0];
1314 i < btrfs_header_nritems(path.nodes[0]); i++) {
1315 btrfs_item_key_to_cpu(path.nodes[0], &found_key, i);
1316 if (found_key.type != key.type)
1319 printf("Using objectid %Lu for first dir\n",
1320 found_key.objectid);
1321 *objectid = found_key.objectid;
1326 ret = next_leaf(root, &path);
1328 fprintf(stderr, "Error getting next leaf %d\n",
1331 } else if (ret > 0) {
1332 fprintf(stderr, "No more leaves\n");
1335 } while (!path.nodes[0]);
1338 printf("Couldn't find a dir index item\n");
1340 btrfs_release_path(&path);
1344 const char * const cmd_restore_usage[] = {
1345 "btrfs restore [options] <device> <path> | -l <device>",
1346 "Try to restore files from a damaged filesystem (unmounted)",
1348 "-s|--snapshots get snapshots",
1349 "-x|--xattr restore extended attributes",
1350 "-m|--metadata restore owner, mode and times",
1351 "-S|--symlink restore symbolic links",
1352 "-v|--verbose verbose",
1353 "-i|--ignore-errors ignore errors",
1354 "-o|--overwrite overwrite",
1355 "-t <bytenr> tree location",
1356 "-f <bytenr> filesystem location",
1357 "-u|--super <mirror> super mirror",
1358 "-r|--root <rootid> root objectid",
1360 "-l|--list-roots list tree roots",
1361 "-D|--dry-run dry run (only list files that would be recovered)",
1362 "--path-regex <regex>",
1363 " restore only filenames matching regex,",
1364 " you have to use following syntax (possibly quoted):",
1365 " ^/(|home(|/username(|/Desktop(|/.*))))$",
1366 "-c ignore case (--path-regex only)",
1370 int cmd_restore(int argc, char **argv)
1372 struct btrfs_root *root;
1373 struct btrfs_key key;
1374 char dir_name[PATH_MAX];
1375 u64 tree_location = 0;
1376 u64 fs_location = 0;
1377 u64 root_objectid = 0;
1380 int super_mirror = 0;
1383 const char *match_regstr = NULL;
1384 int match_cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
1385 regex_t match_reg, *mreg = NULL;
1390 enum { GETOPT_VAL_PATH_REGEX = 256 };
1391 static const struct option long_options[] = {
1392 { "path-regex", required_argument, NULL,
1393 GETOPT_VAL_PATH_REGEX },
1394 { "dry-run", no_argument, NULL, 'D'},
1395 { "metadata", no_argument, NULL, 'm'},
1396 { "symlinks", no_argument, NULL, 'S'},
1397 { "snapshots", no_argument, NULL, 's'},
1398 { "xattr", no_argument, NULL, 'x'},
1399 { "verbose", no_argument, NULL, 'v'},
1400 { "ignore-errors", no_argument, NULL, 'i'},
1401 { "overwrite", no_argument, NULL, 'o'},
1402 { "super", required_argument, NULL, 'u'},
1403 { "root", required_argument, NULL, 'r'},
1404 { "list-roots", no_argument, NULL, 'l'},
1408 opt = getopt_long(argc, argv, "sSxviot:u:dmf:r:lDc", long_options,
1427 tree_location = arg_strtou64(optarg);
1430 fs_location = arg_strtou64(optarg);
1433 super_mirror = arg_strtou64(optarg);
1434 if (super_mirror >= BTRFS_SUPER_MIRROR_MAX) {
1435 fprintf(stderr, "Super mirror not "
1444 root_objectid = arg_strtou64(optarg);
1445 if (!is_fstree(root_objectid)) {
1446 fprintf(stderr, "objectid %llu is not a valid fs/file tree\n",
1455 restore_metadata = 1;
1458 restore_symlinks = 1;
1464 match_cflags |= REG_ICASE;
1466 case GETOPT_VAL_PATH_REGEX:
1467 match_regstr = optarg;
1473 usage(cmd_restore_usage);
1477 if (!list_roots && check_argc_min(argc - optind, 2))
1478 usage(cmd_restore_usage);
1479 else if (list_roots && check_argc_min(argc - optind, 1))
1480 usage(cmd_restore_usage);
1482 if (fs_location && root_objectid) {
1483 fprintf(stderr, "don't use -f and -r at the same time.\n");
1487 if ((ret = check_mounted(argv[optind])) < 0) {
1488 fprintf(stderr, "Could not check mount status: %s\n",
1492 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
1496 root = open_fs(argv[optind], tree_location, super_mirror, list_roots);
1503 if (fs_location != 0) {
1504 free_extent_buffer(root->node);
1505 root->node = read_tree_block(root, fs_location, root->nodesize, 0);
1506 if (!extent_buffer_uptodate(root->node)) {
1507 fprintf(stderr, "Failed to read fs location\n");
1513 memset(path_name, 0, PATH_MAX);
1515 if (strlen(argv[optind + 1]) >= PATH_MAX) {
1516 fprintf(stderr, "ERROR: path too long\n");
1520 strncpy(dir_name, argv[optind + 1], sizeof dir_name);
1521 dir_name[sizeof dir_name - 1] = 0;
1523 /* Strip the trailing / on the dir name */
1524 len = strlen(dir_name);
1525 while (len && dir_name[--len] == '/') {
1526 dir_name[len] = '\0';
1529 if (root_objectid != 0) {
1530 struct btrfs_root *orig_root = root;
1532 key.objectid = root_objectid;
1533 key.type = BTRFS_ROOT_ITEM_KEY;
1534 key.offset = (u64)-1;
1535 root = btrfs_read_fs_root(orig_root->fs_info, &key);
1537 fprintf(stderr, "fail to read root %llu: %s\n",
1538 root_objectid, strerror(-PTR_ERR(root)));
1548 ret = find_first_dir(root, &key.objectid);
1552 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
1556 ret = regcomp(&match_reg, match_regstr, match_cflags);
1558 regerror(ret, &match_reg, reg_err, sizeof(reg_err));
1559 fprintf(stderr, "Regex compile failed: %s\n", reg_err);
1566 printf("This is a dry-run, no files are going to be restored\n");
1568 ret = search_dir(root, &key, dir_name, "", mreg);