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 int get_snaps = 0;
49 static int verbose = 0;
50 static int restore_metadata = 0;
51 static int ignore_errors = 0;
52 static int overwrite = 0;
53 static int get_xattrs = 0;
54 static int dry_run = 0;
57 #define PAGE_CACHE_SIZE 4096
58 #define lzo1x_worst_compress(x) ((x) + ((x) / 16) + 64 + 3)
60 static int decompress_zlib(char *inbuf, char *outbuf, u64 compress_len,
66 memset(&strm, 0, sizeof(strm));
67 ret = inflateInit(&strm);
69 fprintf(stderr, "inflate init returnd %d\n", ret);
73 strm.avail_in = compress_len;
74 strm.next_in = (unsigned char *)inbuf;
75 strm.avail_out = decompress_len;
76 strm.next_out = (unsigned char *)outbuf;
77 ret = inflate(&strm, Z_NO_FLUSH);
78 if (ret != Z_STREAM_END) {
79 (void)inflateEnd(&strm);
80 fprintf(stderr, "failed to inflate: %d\n", ret);
84 (void)inflateEnd(&strm);
87 static inline size_t read_compress_length(unsigned char *buf)
90 memcpy(&dlen, buf, LZO_LEN);
91 return le32_to_cpu(dlen);
94 static int decompress_lzo(unsigned char *inbuf, char *outbuf, u64 compress_len,
105 if (ret != LZO_E_OK) {
106 fprintf(stderr, "lzo init returned %d\n", ret);
110 tot_len = read_compress_length(inbuf);
114 while (tot_in < tot_len) {
117 in_len = read_compress_length(inbuf);
119 if ((tot_in + LZO_LEN + in_len) > tot_len) {
120 fprintf(stderr, "bad compress length %lu\n",
121 (unsigned long)in_len);
128 new_len = lzo1x_worst_compress(PAGE_CACHE_SIZE);
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 fprintf(stderr, "failed to inflate: %d\n", 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 % PAGE_CACHE_SIZE;
146 rem_page = PAGE_CACHE_SIZE - mod_page;
147 if (rem_page < LZO_LEN) {
153 *decompress_len = out_len;
158 static int decompress(char *inbuf, char *outbuf, u64 compress_len,
159 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((unsigned char *)inbuf, outbuf, compress_len,
172 fprintf(stderr, "invalid compression type: %d\n", 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(int fd, struct btrfs_path *path, u64 pos)
237 struct extent_buffer *leaf = path->nodes[0];
238 struct btrfs_file_extent_item *fi;
249 fi = btrfs_item_ptr(leaf, path->slots[0],
250 struct btrfs_file_extent_item);
251 ptr = btrfs_file_extent_inline_start(fi);
252 len = btrfs_file_extent_inline_len(leaf, path->slots[0], fi);
253 inline_item_len = btrfs_file_extent_inline_item_len(leaf, btrfs_item_nr(path->slots[0]));
254 read_extent_buffer(leaf, buf, ptr, inline_item_len);
256 compress = btrfs_file_extent_compression(leaf, fi);
257 if (compress == BTRFS_COMPRESS_NONE) {
258 done = pwrite(fd, buf, len, pos);
260 fprintf(stderr, "Short inline write, wanted %d, did "
261 "%zd: %d\n", len, done, errno);
267 ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
268 outbuf = calloc(1, ram_size);
270 fprintf(stderr, "No memory\n");
274 ret = decompress(buf, outbuf, len, &ram_size, compress);
280 done = pwrite(fd, outbuf, ram_size, pos);
282 if (done < ram_size) {
283 fprintf(stderr, "Short compressed inline write, wanted %Lu, "
284 "did %zd: %d\n", ram_size, done, errno);
291 static int copy_one_extent(struct btrfs_root *root, int fd,
292 struct extent_buffer *leaf,
293 struct btrfs_file_extent_item *fi, u64 pos)
295 struct btrfs_multi_bio *multi = NULL;
296 struct btrfs_device *device;
297 char *inbuf, *outbuf = NULL;
298 ssize_t done, total = 0;
314 compress = btrfs_file_extent_compression(leaf, fi);
315 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
316 disk_size = btrfs_file_extent_disk_num_bytes(leaf, fi);
317 ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
318 offset = btrfs_file_extent_offset(leaf, fi);
319 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
320 size_left = disk_size;
321 if (compress == BTRFS_COMPRESS_NONE)
324 if (verbose && offset)
325 printf("offset is %Lu\n", offset);
326 /* we found a hole */
330 inbuf = malloc(size_left);
332 fprintf(stderr, "No memory\n");
336 if (compress != BTRFS_COMPRESS_NONE) {
337 outbuf = calloc(1, ram_size);
339 fprintf(stderr, "No memory\n");
346 ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
347 bytenr, &length, &multi, mirror_num, NULL);
349 fprintf(stderr, "Error mapping block %d\n", ret);
352 device = multi->stripes[0].dev;
355 dev_bytenr = multi->stripes[0].physical;
358 if (size_left < length)
361 done = pread(dev_fd, inbuf+count, length, dev_bytenr);
362 /* Need both checks, or we miss negative values due to u64 conversion */
363 if (done < 0 || done < length) {
364 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
367 /* mirror_num is 1-indexed, so num_copies is a valid mirror. */
368 if (mirror_num > num_copies) {
370 fprintf(stderr, "Exhausted mirrors trying to read\n");
373 fprintf(stderr, "Trying another mirror\n");
384 if (compress == BTRFS_COMPRESS_NONE) {
385 while (total < num_bytes) {
386 done = pwrite(fd, inbuf+total, num_bytes-total,
390 fprintf(stderr, "Error writing: %d %s\n", errno, strerror(errno));
399 ret = decompress(inbuf, outbuf, disk_size, &ram_size, compress);
401 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
404 if (mirror_num >= num_copies) {
408 fprintf(stderr, "Trying another mirror\n");
412 while (total < num_bytes) {
413 done = pwrite(fd, outbuf + offset + total,
434 static enum loop_response ask_to_continue(const char *file)
439 printf("We seem to be looping a lot on %s, do you want to keep going "
440 "on ? (y/N/a): ", file);
442 ret = fgets(buf, 2, stdin);
443 if (*ret == '\n' || tolower(*ret) == 'n')
445 if (tolower(*ret) == 'a')
447 if (tolower(*ret) != 'y') {
448 printf("Please enter one of 'y', 'n', or 'a': ");
452 return LOOP_CONTINUE;
456 static int set_file_xattrs(struct btrfs_root *root, u64 inode,
457 int fd, const char *file_name)
459 struct btrfs_key key;
460 struct btrfs_path *path;
461 struct extent_buffer *leaf;
462 struct btrfs_dir_item *di;
471 key.objectid = inode;
472 key.type = BTRFS_XATTR_ITEM_KEY;
475 path = btrfs_alloc_path();
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);
490 "Error searching for extended attributes: %d\n",
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)) {
544 "Error setting extended attribute %s on file %s: %s\n",
545 name, file_name, strerror(err));
548 len = sizeof(*di) + name_len + data_len;
550 di = (struct btrfs_dir_item *)((char *)di + len);
556 btrfs_free_path(path);
563 static int copy_metadata(struct btrfs_root *root, int fd,
564 struct btrfs_key *key)
566 struct btrfs_path *path;
567 struct btrfs_inode_item *inode_item;
570 path = btrfs_alloc_path();
572 fprintf(stderr, "ERROR: Ran out of memory\n");
576 ret = btrfs_lookup_inode(NULL, root, path, key, 0);
578 struct btrfs_timespec *bts;
579 struct timespec times[2];
581 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
582 struct btrfs_inode_item);
584 ret = fchown(fd, btrfs_inode_uid(path->nodes[0], inode_item),
585 btrfs_inode_gid(path->nodes[0], inode_item));
587 fprintf(stderr, "ERROR: Failed to change owner: %s\n",
592 ret = fchmod(fd, btrfs_inode_mode(path->nodes[0], inode_item));
594 fprintf(stderr, "ERROR: Failed to change mode: %s\n",
599 bts = btrfs_inode_atime(inode_item);
600 times[0].tv_sec = btrfs_timespec_sec(path->nodes[0], bts);
601 times[0].tv_nsec = btrfs_timespec_nsec(path->nodes[0], bts);
603 bts = btrfs_inode_mtime(inode_item);
604 times[1].tv_sec = btrfs_timespec_sec(path->nodes[0], bts);
605 times[1].tv_nsec = btrfs_timespec_nsec(path->nodes[0], bts);
607 ret = futimens(fd, times);
609 fprintf(stderr, "ERROR: Failed to set times: %s\n",
615 btrfs_free_path(path);
619 static int copy_file(struct btrfs_root *root, int fd, struct btrfs_key *key,
622 struct extent_buffer *leaf;
623 struct btrfs_path *path;
624 struct btrfs_file_extent_item *fi;
625 struct btrfs_inode_item *inode_item;
626 struct btrfs_timespec *bts;
627 struct btrfs_key found_key;
633 struct timespec times[2];
636 path = btrfs_alloc_path();
638 fprintf(stderr, "Ran out of memory\n");
642 ret = btrfs_lookup_inode(NULL, root, path, key, 0);
644 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
645 struct btrfs_inode_item);
646 found_size = btrfs_inode_size(path->nodes[0], inode_item);
648 if (restore_metadata) {
650 * Change the ownership and mode now, set times when
651 * copyout is finished.
654 ret = fchown(fd, btrfs_inode_uid(path->nodes[0], inode_item),
655 btrfs_inode_gid(path->nodes[0], inode_item));
656 if (ret && !ignore_errors)
659 ret = fchmod(fd, btrfs_inode_mode(path->nodes[0], inode_item));
660 if (ret && !ignore_errors)
663 bts = btrfs_inode_atime(inode_item);
664 times[0].tv_sec = btrfs_timespec_sec(path->nodes[0], bts);
665 times[0].tv_nsec = btrfs_timespec_nsec(path->nodes[0], bts);
667 bts = btrfs_inode_mtime(inode_item);
668 times[1].tv_sec = btrfs_timespec_sec(path->nodes[0], bts);
669 times[1].tv_nsec = btrfs_timespec_nsec(path->nodes[0], bts);
673 btrfs_release_path(path);
676 key->type = BTRFS_EXTENT_DATA_KEY;
678 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
680 fprintf(stderr, "Error searching %d\n", ret);
684 leaf = path->nodes[0];
686 ret = next_leaf(root, path);
688 fprintf(stderr, "Error getting next leaf %d\n",
691 } else if (ret > 0) {
692 /* No more leaves to search */
696 leaf = path->nodes[0];
700 if (loops >= 0 && loops++ >= 1024) {
701 enum loop_response resp;
703 resp = ask_to_continue(file);
704 if (resp == LOOP_STOP)
706 else if (resp == LOOP_CONTINUE)
708 else if (resp == LOOP_DONTASK)
711 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
713 ret = next_leaf(root, path);
715 fprintf(stderr, "Error searching %d\n", ret);
718 /* No more leaves to search */
719 btrfs_free_path(path);
722 leaf = path->nodes[0];
726 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
727 if (found_key.objectid != key->objectid)
729 if (found_key.type != key->type)
731 fi = btrfs_item_ptr(leaf, path->slots[0],
732 struct btrfs_file_extent_item);
733 extent_type = btrfs_file_extent_type(leaf, fi);
734 compression = btrfs_file_extent_compression(leaf, fi);
735 if (compression >= BTRFS_COMPRESS_LAST) {
736 fprintf(stderr, "Don't support compression yet %d\n",
742 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC)
744 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
745 ret = copy_one_inline(fd, path, found_key.offset);
748 } else if (extent_type == BTRFS_FILE_EXTENT_REG) {
749 ret = copy_one_extent(root, fd, leaf, fi,
754 printf("Weird extent type %d\n", extent_type);
760 btrfs_free_path(path);
763 ret = ftruncate(fd, (loff_t)found_size);
768 ret = set_file_xattrs(root, key->objectid, fd, file);
772 if (restore_metadata && times_ok) {
773 ret = futimens(fd, times);
780 btrfs_free_path(path);
784 static int search_dir(struct btrfs_root *root, struct btrfs_key *key,
785 const char *output_rootdir, const char *in_dir,
788 struct btrfs_path *path;
789 struct extent_buffer *leaf;
790 struct btrfs_dir_item *dir_item;
791 struct btrfs_key found_key, location;
792 char filename[BTRFS_NAME_LEN + 1];
793 unsigned long name_ptr;
800 path = btrfs_alloc_path();
802 fprintf(stderr, "Ran out of memory\n");
807 key->type = BTRFS_DIR_INDEX_KEY;
809 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
811 fprintf(stderr, "Error searching %d\n", ret);
817 leaf = path->nodes[0];
820 printf("No leaf after search, looking for the next "
822 ret = next_leaf(root, path);
824 fprintf(stderr, "Error getting next leaf %d\n",
827 } else if (ret > 0) {
828 /* No more leaves to search */
830 printf("Reached the end of the tree looking "
831 "for the directory\n");
835 leaf = path->nodes[0];
839 if (loops++ >= 1024) {
840 printf("We have looped trying to restore files in %s "
841 "too many times to be making progress, "
842 "stopping\n", in_dir);
846 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
848 ret = next_leaf(root, path);
850 fprintf(stderr, "Error searching %d\n",
853 } else if (ret > 0) {
854 /* No more leaves to search */
856 printf("Reached the end of "
857 "the tree searching the"
862 leaf = path->nodes[0];
866 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
867 if (found_key.objectid != key->objectid) {
869 printf("Found objectid=%Lu, key=%Lu\n",
870 found_key.objectid, key->objectid);
873 if (found_key.type != key->type) {
875 printf("Found type=%u, want=%u\n",
876 found_key.type, key->type);
879 dir_item = btrfs_item_ptr(leaf, path->slots[0],
880 struct btrfs_dir_item);
881 name_ptr = (unsigned long)(dir_item + 1);
882 name_len = btrfs_dir_name_len(leaf, dir_item);
883 read_extent_buffer(leaf, filename, name_ptr, name_len);
884 filename[name_len] = '\0';
885 type = btrfs_dir_type(leaf, dir_item);
886 btrfs_dir_item_key_to_cpu(leaf, dir_item, &location);
888 /* full path from root of btrfs being restored */
889 snprintf(fs_name, PATH_MAX, "%s/%s", in_dir, filename);
891 if (mreg && REG_NOMATCH == regexec(mreg, fs_name, 0, NULL, 0))
894 /* full path from system root */
895 snprintf(path_name, PATH_MAX, "%s%s", output_rootdir, fs_name);
898 * At this point we're only going to restore directories and
899 * files, no symlinks or anything else.
901 if (type == BTRFS_FT_REG_FILE) {
906 ret = stat(path_name, &st);
909 if (verbose || !warn)
910 printf("Skipping existing file"
914 printf("If you wish to overwrite use "
915 "the -o option to overwrite\n");
922 printf("Restoring %s\n", path_name);
925 fd = open(path_name, O_CREAT|O_WRONLY, 0644);
927 fprintf(stderr, "Error creating %s: %d\n",
935 ret = copy_file(root, fd, &location, path_name);
938 fprintf(stderr, "Error copying data for %s\n",
944 } else if (type == BTRFS_FT_DIR) {
945 struct btrfs_root *search_root = root;
946 char *dir = strdup(fs_name);
949 fprintf(stderr, "Ran out of memory\n");
954 if (location.type == BTRFS_ROOT_ITEM_KEY) {
956 * If we are a snapshot and this is the index
957 * object to ourselves just skip it.
959 if (location.objectid ==
960 root->root_key.objectid) {
965 location.offset = (u64)-1;
966 search_root = btrfs_read_fs_root(root->fs_info,
968 if (IS_ERR(search_root)) {
970 fprintf(stderr, "Error reading "
971 "subvolume %s: %lu\n",
973 PTR_ERR(search_root));
976 ret = PTR_ERR(search_root);
981 * A subvolume will have a key.offset of 0, a
982 * snapshot will have key.offset of a transid.
984 if (search_root->root_key.offset != 0 &&
987 printf("Skipping snapshot %s\n",
991 location.objectid = BTRFS_FIRST_FREE_OBJECTID;
995 printf("Restoring %s\n", path_name);
1001 ret = mkdir(path_name, 0755);
1002 if (ret && errno != EEXIST) {
1004 fprintf(stderr, "Error mkdiring %s: %d\n",
1012 ret = search_dir(search_root, &location,
1013 output_rootdir, dir, mreg);
1016 fprintf(stderr, "Error searching %s\n",
1027 if (restore_metadata) {
1028 snprintf(path_name, PATH_MAX, "%s%s", output_rootdir, in_dir);
1029 fd = open(path_name, O_RDONLY);
1031 fprintf(stderr, "ERROR: Failed to access %s to restore metadata\n",
1033 if (!ignore_errors) {
1039 * Set owner/mode/time on the directory as well
1041 key->type = BTRFS_INODE_ITEM_KEY;
1042 ret = copy_metadata(root, fd, key);
1044 if (ret && !ignore_errors)
1050 printf("Done searching %s\n", in_dir);
1052 btrfs_free_path(path);
1056 static int do_list_roots(struct btrfs_root *root)
1058 struct btrfs_key key;
1059 struct btrfs_key found_key;
1060 struct btrfs_disk_key disk_key;
1061 struct btrfs_path *path;
1062 struct extent_buffer *leaf;
1063 struct btrfs_root_item ri;
1064 unsigned long offset;
1068 root = root->fs_info->tree_root;
1069 path = btrfs_alloc_path();
1071 fprintf(stderr, "Failed to alloc path\n");
1077 key.type = BTRFS_ROOT_ITEM_KEY;
1079 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1081 fprintf(stderr, "Failed to do search %d\n", ret);
1082 btrfs_free_path(path);
1086 leaf = path->nodes[0];
1089 slot = path->slots[0];
1090 if (slot >= btrfs_header_nritems(leaf)) {
1091 ret = btrfs_next_leaf(root, path);
1094 leaf = path->nodes[0];
1095 slot = path->slots[0];
1097 btrfs_item_key(leaf, &disk_key, slot);
1098 btrfs_disk_key_to_cpu(&found_key, &disk_key);
1099 if (btrfs_key_type(&found_key) != BTRFS_ROOT_ITEM_KEY) {
1104 offset = btrfs_item_ptr_offset(leaf, slot);
1105 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
1107 btrfs_print_key(&disk_key);
1108 printf(" %Lu level %d\n", btrfs_root_bytenr(&ri),
1109 btrfs_root_level(&ri));
1112 btrfs_free_path(path);
1117 static struct btrfs_root *open_fs(const char *dev, u64 root_location,
1118 int super_mirror, int list_roots)
1120 struct btrfs_fs_info *fs_info = NULL;
1121 struct btrfs_root *root = NULL;
1125 for (i = super_mirror; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1126 bytenr = btrfs_sb_offset(i);
1127 fs_info = open_ctree_fs_info(dev, bytenr, root_location,
1128 OPEN_CTREE_PARTIAL);
1131 fprintf(stderr, "Could not open root, trying backup super\n");
1138 * All we really need to succeed is reading the chunk tree, everything
1139 * else we can do by hand, since we only need to read the tree root and
1142 if (!extent_buffer_uptodate(fs_info->tree_root->node)) {
1145 root = fs_info->tree_root;
1147 root_location = btrfs_super_root(fs_info->super_copy);
1148 generation = btrfs_super_generation(fs_info->super_copy);
1149 root->node = read_tree_block(root, root_location,
1150 root->leafsize, generation);
1151 if (!extent_buffer_uptodate(root->node)) {
1152 fprintf(stderr, "Error opening tree root\n");
1158 if (!list_roots && !fs_info->fs_root) {
1159 struct btrfs_key key;
1161 key.objectid = BTRFS_FS_TREE_OBJECTID;
1162 key.type = BTRFS_ROOT_ITEM_KEY;
1163 key.offset = (u64)-1;
1164 fs_info->fs_root = btrfs_read_fs_root_no_cache(fs_info, &key);
1165 if (IS_ERR(fs_info->fs_root)) {
1166 fprintf(stderr, "Couldn't read fs root: %ld\n",
1167 PTR_ERR(fs_info->fs_root));
1168 close_ctree(fs_info->tree_root);
1173 if (list_roots && do_list_roots(fs_info->tree_root)) {
1174 close_ctree(fs_info->tree_root);
1178 return fs_info->fs_root;
1181 static int find_first_dir(struct btrfs_root *root, u64 *objectid)
1183 struct btrfs_path *path;
1184 struct btrfs_key found_key;
1185 struct btrfs_key key;
1190 key.type = BTRFS_DIR_INDEX_KEY;
1193 path = btrfs_alloc_path();
1195 fprintf(stderr, "Ran out of memory\n");
1199 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1201 fprintf(stderr, "Error searching %d\n", ret);
1205 if (!path->nodes[0]) {
1206 fprintf(stderr, "No leaf!\n");
1210 for (i = path->slots[0];
1211 i < btrfs_header_nritems(path->nodes[0]); i++) {
1212 btrfs_item_key_to_cpu(path->nodes[0], &found_key, i);
1213 if (found_key.type != key.type)
1216 printf("Using objectid %Lu for first dir\n",
1217 found_key.objectid);
1218 *objectid = found_key.objectid;
1223 ret = next_leaf(root, path);
1225 fprintf(stderr, "Error getting next leaf %d\n",
1228 } else if (ret > 0) {
1229 fprintf(stderr, "No more leaves\n");
1232 } while (!path->nodes[0]);
1235 printf("Couldn't find a dir index item\n");
1237 btrfs_free_path(path);
1241 const char * const cmd_restore_usage[] = {
1242 "btrfs restore [options] <device> <path> | -l <device>",
1243 "Try to restore files from a damaged filesystem (unmounted)",
1246 "-x get extended attributes",
1247 "-m|--metadata restore owner, mode and times",
1251 "-t <bytenr> tree location",
1252 "-f <bytenr> filesystem location",
1253 "-u <mirror> super mirror",
1254 "-r <rootid> root objectid",
1256 "-l list tree roots",
1257 "-D|--dry-run dry run (only list files that would be recovered)",
1258 "--path-regex <regex>",
1259 " restore only filenames matching regex,",
1260 " you have to use following syntax (possibly quoted):",
1261 " ^/(|home(|/username(|/Desktop(|/.*))))$",
1262 "-c ignore case (--path-regex only)",
1266 int cmd_restore(int argc, char **argv)
1268 struct btrfs_root *root;
1269 struct btrfs_key key;
1271 u64 tree_location = 0;
1272 u64 fs_location = 0;
1273 u64 root_objectid = 0;
1276 int super_mirror = 0;
1279 const char *match_regstr = NULL;
1280 int match_cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
1281 regex_t match_reg, *mreg = NULL;
1286 static const struct option long_options[] = {
1287 { "path-regex", required_argument, NULL, 256},
1288 { "dry-run", no_argument, NULL, 'D'},
1289 { "metadata", no_argument, NULL, 'm'},
1293 opt = getopt_long(argc, argv, "sxviot:u:dmf:r:lDc", long_options,
1312 tree_location = arg_strtou64(optarg);
1315 fs_location = arg_strtou64(optarg);
1318 super_mirror = arg_strtou64(optarg);
1319 if (super_mirror >= BTRFS_SUPER_MIRROR_MAX) {
1320 fprintf(stderr, "Super mirror not "
1329 root_objectid = arg_strtou64(optarg);
1330 if (!is_fstree(root_objectid)) {
1331 fprintf(stderr, "objectid %llu is not a valid fs/file tree\n",
1340 restore_metadata = 1;
1346 match_cflags |= REG_ICASE;
1348 /* long option without single letter alternative */
1350 match_regstr = optarg;
1356 usage(cmd_restore_usage);
1360 if (!list_roots && check_argc_min(argc - optind, 2))
1361 usage(cmd_restore_usage);
1362 else if (list_roots && check_argc_min(argc - optind, 1))
1363 usage(cmd_restore_usage);
1365 if (fs_location && root_objectid) {
1366 fprintf(stderr, "don't use -f and -r at the same time.\n");
1370 if ((ret = check_mounted(argv[optind])) < 0) {
1371 fprintf(stderr, "Could not check mount status: %s\n",
1375 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
1379 root = open_fs(argv[optind], tree_location, super_mirror, list_roots);
1386 if (fs_location != 0) {
1387 free_extent_buffer(root->node);
1388 root->node = read_tree_block(root, fs_location, root->leafsize, 0);
1389 if (!extent_buffer_uptodate(root->node)) {
1390 fprintf(stderr, "Failed to read fs location\n");
1396 memset(path_name, 0, PATH_MAX);
1398 strncpy(dir_name, argv[optind + 1], sizeof dir_name);
1399 dir_name[sizeof dir_name - 1] = 0;
1401 /* Strip the trailing / on the dir name */
1402 len = strlen(dir_name);
1403 while (len && dir_name[--len] == '/') {
1404 dir_name[len] = '\0';
1407 if (root_objectid != 0) {
1408 struct btrfs_root *orig_root = root;
1410 key.objectid = root_objectid;
1411 key.type = BTRFS_ROOT_ITEM_KEY;
1412 key.offset = (u64)-1;
1413 root = btrfs_read_fs_root(orig_root->fs_info, &key);
1415 fprintf(stderr, "fail to read root %llu: %s\n",
1416 root_objectid, strerror(-PTR_ERR(root)));
1426 ret = find_first_dir(root, &key.objectid);
1430 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
1434 ret = regcomp(&match_reg, match_regstr, match_cflags);
1436 regerror(ret, &match_reg, reg_err, sizeof(reg_err));
1437 fprintf(stderr, "Regex compile failed: %s\n", reg_err);
1444 printf("This is a dry-run, no files are going to be restored\n");
1446 ret = search_dir(root, &key, dir_name, "", mreg);