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.
19 #define _XOPEN_SOURCE 500
22 #include "kerncompat.h"
30 #include <sys/types.h>
31 #include <lzo/lzoconf.h>
32 #include <lzo/lzo1x.h>
38 #include "print-tree.h"
39 #include "transaction.h"
46 static char fs_name[4096];
47 static char path_name[4096];
48 static int get_snaps = 0;
49 static int verbose = 0;
50 static int ignore_errors = 0;
51 static int overwrite = 0;
54 #define PAGE_CACHE_SIZE 4096
55 #define lzo1x_worst_compress(x) ((x) + ((x) / 16) + 64 + 3)
57 static int decompress_zlib(char *inbuf, char *outbuf, u64 compress_len,
63 memset(&strm, 0, sizeof(strm));
64 ret = inflateInit(&strm);
66 fprintf(stderr, "inflate init returnd %d\n", ret);
70 strm.avail_in = compress_len;
71 strm.next_in = (unsigned char *)inbuf;
72 strm.avail_out = decompress_len;
73 strm.next_out = (unsigned char *)outbuf;
74 ret = inflate(&strm, Z_NO_FLUSH);
75 if (ret != Z_STREAM_END) {
76 (void)inflateEnd(&strm);
77 fprintf(stderr, "failed to inflate: %d\n", ret);
81 (void)inflateEnd(&strm);
84 static inline size_t read_compress_length(unsigned char *buf)
87 memcpy(&dlen, buf, LZO_LEN);
88 return le32_to_cpu(dlen);
91 static int decompress_lzo(unsigned char *inbuf, char *outbuf, u64 compress_len,
102 if (ret != LZO_E_OK) {
103 fprintf(stderr, "lzo init returned %d\n", ret);
107 tot_len = read_compress_length(inbuf);
111 while (tot_in < tot_len) {
112 in_len = read_compress_length(inbuf);
116 new_len = lzo1x_worst_compress(PAGE_CACHE_SIZE);
117 ret = lzo1x_decompress_safe((const unsigned char *)inbuf, in_len,
118 (unsigned char *)outbuf,
119 (void *)&new_len, NULL);
120 if (ret != LZO_E_OK) {
121 fprintf(stderr, "failed to inflate: %d\n", ret);
130 *decompress_len = out_len;
135 static int decompress(char *inbuf, char *outbuf, u64 compress_len,
136 u64 *decompress_len, int compress)
139 case BTRFS_COMPRESS_ZLIB:
140 return decompress_zlib(inbuf, outbuf, compress_len,
142 case BTRFS_COMPRESS_LZO:
143 return decompress_lzo((unsigned char *)inbuf, outbuf, compress_len,
149 fprintf(stderr, "invalid compression type: %d\n", compress);
153 int next_leaf(struct btrfs_root *root, struct btrfs_path *path)
158 struct extent_buffer *c;
159 struct extent_buffer *next = NULL;
162 for (; level < BTRFS_MAX_LEVEL; level++) {
163 if (path->nodes[level])
167 if (level == BTRFS_MAX_LEVEL)
170 slot = path->slots[level] + 1;
172 while(level < BTRFS_MAX_LEVEL) {
173 if (!path->nodes[level])
176 slot = path->slots[level] + offset;
177 c = path->nodes[level];
178 if (slot >= btrfs_header_nritems(c)) {
180 if (level == BTRFS_MAX_LEVEL)
186 reada_for_search(root, path, level, slot, 0);
188 next = read_node_slot(root, c, slot);
193 path->slots[level] = slot;
196 c = path->nodes[level];
197 free_extent_buffer(c);
198 path->nodes[level] = next;
199 path->slots[level] = 0;
203 reada_for_search(root, path, level, 0, 0);
204 next = read_node_slot(root, next, 0);
211 static int copy_one_inline(int fd, struct btrfs_path *path, u64 pos)
213 struct extent_buffer *leaf = path->nodes[0];
214 struct btrfs_file_extent_item *fi;
224 fi = btrfs_item_ptr(leaf, path->slots[0],
225 struct btrfs_file_extent_item);
226 ptr = btrfs_file_extent_inline_start(fi);
227 len = btrfs_file_extent_inline_item_len(leaf,
228 btrfs_item_nr(leaf, path->slots[0]));
229 read_extent_buffer(leaf, buf, ptr, len);
231 compress = btrfs_file_extent_compression(leaf, fi);
232 if (compress == BTRFS_COMPRESS_NONE) {
233 done = pwrite(fd, buf, len, pos);
235 fprintf(stderr, "Short inline write, wanted %d, did "
236 "%zd: %d\n", len, done, errno);
242 ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
243 outbuf = malloc(ram_size);
245 fprintf(stderr, "No memory\n");
249 ret = decompress(buf, outbuf, len, &ram_size, compress);
255 done = pwrite(fd, outbuf, ram_size, pos);
257 if (done < ram_size) {
258 fprintf(stderr, "Short compressed inline write, wanted %Lu, "
259 "did %zd: %d\n", ram_size, done, errno);
266 static int copy_one_extent(struct btrfs_root *root, int fd,
267 struct extent_buffer *leaf,
268 struct btrfs_file_extent_item *fi, u64 pos)
270 struct btrfs_multi_bio *multi = NULL;
271 struct btrfs_device *device;
272 char *inbuf, *outbuf = NULL;
273 ssize_t done, total = 0;
288 compress = btrfs_file_extent_compression(leaf, fi);
289 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
290 disk_size = btrfs_file_extent_disk_num_bytes(leaf, fi);
291 ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
292 offset = btrfs_file_extent_offset(leaf, fi);
293 size_left = disk_size;
296 printf("offset is %Lu\n", offset);
297 /* we found a hole */
301 inbuf = malloc(disk_size);
303 fprintf(stderr, "No memory\n");
307 if (compress != BTRFS_COMPRESS_NONE) {
308 outbuf = malloc(ram_size);
310 fprintf(stderr, "No memory\n");
317 ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
318 bytenr, &length, &multi, mirror_num, NULL);
320 fprintf(stderr, "Error mapping block %d\n", ret);
323 device = multi->stripes[0].dev;
326 dev_bytenr = multi->stripes[0].physical;
329 if (size_left < length)
332 done = pread(dev_fd, inbuf+count, length, dev_bytenr);
333 /* Need both checks, or we miss negative values due to u64 conversion */
334 if (done < 0 || done < length) {
335 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
338 /* mirror_num is 1-indexed, so num_copies is a valid mirror. */
339 if (mirror_num > num_copies) {
341 fprintf(stderr, "Exhausted mirrors trying to read\n");
344 fprintf(stderr, "Trying another mirror\n");
355 if (compress == BTRFS_COMPRESS_NONE) {
356 while (total < ram_size) {
357 done = pwrite(fd, inbuf+total, ram_size-total,
361 fprintf(stderr, "Error writing: %d %s\n", errno, strerror(errno));
370 ret = decompress(inbuf, outbuf, disk_size, &ram_size, compress);
372 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
375 if (mirror_num >= num_copies) {
379 fprintf(stderr, "Trying another mirror\n");
383 while (total < ram_size) {
384 done = pwrite(fd, outbuf+total, ram_size-total, pos+total);
397 static int ask_to_continue(const char *file)
402 printf("We seem to be looping a lot on %s, do you want to keep going "
403 "on ? (y/N): ", file);
405 ret = fgets(buf, 2, stdin);
406 if (*ret == '\n' || tolower(*ret) == 'n')
408 if (tolower(*ret) != 'y') {
409 printf("Please enter either 'y' or 'n': ");
417 static int copy_file(struct btrfs_root *root, int fd, struct btrfs_key *key,
420 struct extent_buffer *leaf;
421 struct btrfs_path *path;
422 struct btrfs_file_extent_item *fi;
423 struct btrfs_inode_item *inode_item;
424 struct btrfs_key found_key;
431 path = btrfs_alloc_path();
433 fprintf(stderr, "Ran out of memory\n");
436 path->skip_locking = 1;
438 ret = btrfs_lookup_inode(NULL, root, path, key, 0);
440 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
441 struct btrfs_inode_item);
442 found_size = btrfs_inode_size(path->nodes[0], inode_item);
444 btrfs_release_path(root, path);
447 key->type = BTRFS_EXTENT_DATA_KEY;
449 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
451 fprintf(stderr, "Error searching %d\n", ret);
452 btrfs_free_path(path);
456 leaf = path->nodes[0];
458 ret = next_leaf(root, path);
460 fprintf(stderr, "Error getting next leaf %d\n",
462 btrfs_free_path(path);
464 } else if (ret > 0) {
465 /* No more leaves to search */
466 btrfs_free_path(path);
469 leaf = path->nodes[0];
473 if (loops++ >= 1024) {
474 ret = ask_to_continue(file);
479 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
481 ret = next_leaf(root, path);
483 fprintf(stderr, "Error searching %d\n", ret);
484 btrfs_free_path(path);
487 /* No more leaves to search */
488 btrfs_free_path(path);
491 leaf = path->nodes[0];
495 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
496 if (found_key.objectid != key->objectid)
498 if (found_key.type != key->type)
500 fi = btrfs_item_ptr(leaf, path->slots[0],
501 struct btrfs_file_extent_item);
502 extent_type = btrfs_file_extent_type(leaf, fi);
503 compression = btrfs_file_extent_compression(leaf, fi);
504 if (compression >= BTRFS_COMPRESS_LAST) {
505 fprintf(stderr, "Don't support compression yet %d\n",
507 btrfs_free_path(path);
511 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC)
513 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
514 ret = copy_one_inline(fd, path, found_key.offset);
516 btrfs_free_path(path);
519 } else if (extent_type == BTRFS_FILE_EXTENT_REG) {
520 ret = copy_one_extent(root, fd, leaf, fi,
523 btrfs_free_path(path);
527 printf("Weird extent type %d\n", extent_type);
533 btrfs_free_path(path);
536 ret = ftruncate(fd, (loff_t)found_size);
543 static int search_dir(struct btrfs_root *root, struct btrfs_key *key,
544 const char *output_rootdir, const char *dir,
547 struct btrfs_path *path;
548 struct extent_buffer *leaf;
549 struct btrfs_dir_item *dir_item;
550 struct btrfs_key found_key, location;
551 char filename[BTRFS_NAME_LEN + 1];
552 unsigned long name_ptr;
559 path = btrfs_alloc_path();
561 fprintf(stderr, "Ran out of memory\n");
564 path->skip_locking = 1;
567 key->type = BTRFS_DIR_INDEX_KEY;
569 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
571 fprintf(stderr, "Error searching %d\n", ret);
572 btrfs_free_path(path);
576 leaf = path->nodes[0];
579 printf("No leaf after search, looking for the next "
581 ret = next_leaf(root, path);
583 fprintf(stderr, "Error getting next leaf %d\n",
585 btrfs_free_path(path);
587 } else if (ret > 0) {
588 /* No more leaves to search */
590 printf("Reached the end of the tree looking "
591 "for the directory\n");
592 btrfs_free_path(path);
595 leaf = path->nodes[0];
599 if (loops++ >= 1024) {
600 printf("We have looped trying to restore files in %s "
601 "too many times to be making progress, "
606 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
608 ret = next_leaf(root, path);
610 fprintf(stderr, "Error searching %d\n",
612 btrfs_free_path(path);
614 } else if (ret > 0) {
615 /* No more leaves to search */
617 printf("Reached the end of "
618 "the tree searching the"
620 btrfs_free_path(path);
623 leaf = path->nodes[0];
627 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
628 if (found_key.objectid != key->objectid) {
630 printf("Found objectid=%Lu, key=%Lu\n",
631 found_key.objectid, key->objectid);
634 if (found_key.type != key->type) {
636 printf("Found type=%u, want=%u\n",
637 found_key.type, key->type);
640 dir_item = btrfs_item_ptr(leaf, path->slots[0],
641 struct btrfs_dir_item);
642 name_ptr = (unsigned long)(dir_item + 1);
643 name_len = btrfs_dir_name_len(leaf, dir_item);
644 read_extent_buffer(leaf, filename, name_ptr, name_len);
645 filename[name_len] = '\0';
646 type = btrfs_dir_type(leaf, dir_item);
647 btrfs_dir_item_key_to_cpu(leaf, dir_item, &location);
649 /* full path from root of btrfs being restored */
650 snprintf(fs_name, 4096, "%s/%s", dir, filename);
652 if (mreg && REG_NOMATCH == regexec(mreg, fs_name, 0, NULL, 0))
655 /* full path from system root */
656 snprintf(path_name, 4096, "%s%s", output_rootdir, fs_name);
659 * At this point we're only going to restore directories and
660 * files, no symlinks or anything else.
662 if (type == BTRFS_FT_REG_FILE) {
667 ret = stat(path_name, &st);
670 if (verbose || !warn)
671 printf("Skipping existing file"
675 printf("If you wish to overwrite use "
676 "the -o option to overwrite\n");
683 printf("Restoring %s\n", path_name);
684 fd = open(path_name, O_CREAT|O_WRONLY, 0644);
686 fprintf(stderr, "Error creating %s: %d\n",
690 btrfs_free_path(path);
694 ret = copy_file(root, fd, &location, path_name);
699 btrfs_free_path(path);
702 } else if (type == BTRFS_FT_DIR) {
703 struct btrfs_root *search_root = root;
704 char *dir = strdup(fs_name);
707 fprintf(stderr, "Ran out of memory\n");
708 btrfs_free_path(path);
712 if (location.type == BTRFS_ROOT_ITEM_KEY) {
714 * If we are a snapshot and this is the index
715 * object to ourselves just skip it.
717 if (location.objectid ==
718 root->root_key.objectid) {
723 location.offset = (u64)-1;
724 search_root = btrfs_read_fs_root(root->fs_info,
726 if (IS_ERR(search_root)) {
728 fprintf(stderr, "Error reading "
729 "subvolume %s: %lu\n",
731 PTR_ERR(search_root));
734 btrfs_free_path(path);
735 return PTR_ERR(search_root);
739 * A subvolume will have a key.offset of 0, a
740 * snapshot will have key.offset of a transid.
742 if (search_root->root_key.offset != 0 &&
745 printf("Skipping snapshot %s\n",
749 location.objectid = BTRFS_FIRST_FREE_OBJECTID;
753 printf("Restoring %s\n", path_name);
756 ret = mkdir(path_name, 0755);
757 if (ret && errno != EEXIST) {
759 fprintf(stderr, "Error mkdiring %s: %d\n",
763 btrfs_free_path(path);
767 ret = search_dir(search_root, &location,
768 output_rootdir, dir, mreg);
773 btrfs_free_path(path);
782 printf("Done searching %s\n", dir);
783 btrfs_free_path(path);
787 static int do_list_roots(struct btrfs_root *root)
789 struct btrfs_key key;
790 struct btrfs_key found_key;
791 struct btrfs_disk_key disk_key;
792 struct btrfs_path *path;
793 struct extent_buffer *leaf;
794 struct btrfs_root_item ri;
795 unsigned long offset;
799 root = root->fs_info->tree_root;
800 path = btrfs_alloc_path();
802 fprintf(stderr, "Failed to alloc path\n");
808 key.type = BTRFS_ROOT_ITEM_KEY;
810 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
812 fprintf(stderr, "Failed to do search %d\n", ret);
813 btrfs_free_path(path);
818 leaf = path->nodes[0];
819 slot = path->slots[0];
820 if (slot >= btrfs_header_nritems(leaf)) {
821 ret = btrfs_next_leaf(root, path);
824 leaf = path->nodes[0];
825 slot = path->slots[0];
827 btrfs_item_key(leaf, &disk_key, slot);
828 btrfs_disk_key_to_cpu(&found_key, &disk_key);
829 if (btrfs_key_type(&found_key) != BTRFS_ROOT_ITEM_KEY) {
834 offset = btrfs_item_ptr_offset(leaf, slot);
835 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
837 btrfs_print_key(&disk_key);
838 printf(" %Lu level %d\n", btrfs_root_bytenr(&ri),
839 btrfs_root_level(&ri));
842 btrfs_free_path(path);
847 static struct btrfs_root *open_fs(const char *dev, u64 root_location,
848 int super_mirror, int list_roots)
850 struct btrfs_fs_info *fs_info = NULL;
851 struct btrfs_root *root = NULL;
855 for (i = super_mirror; i < BTRFS_SUPER_MIRROR_MAX; i++) {
856 bytenr = btrfs_sb_offset(i);
857 fs_info = open_ctree_fs_info(dev, bytenr, root_location, 0, 1);
860 fprintf(stderr, "Could not open root, trying backup super\n");
867 * All we really need to succeed is reading the chunk tree, everything
868 * else we can do by hand, since we only need to read the tree root and
871 if (!extent_buffer_uptodate(fs_info->tree_root->node)) {
874 root = fs_info->tree_root;
876 root_location = btrfs_super_root(fs_info->super_copy);
877 generation = btrfs_super_generation(fs_info->super_copy);
878 root->node = read_tree_block(root, root_location,
879 root->leafsize, generation);
880 if (!extent_buffer_uptodate(root->node)) {
881 fprintf(stderr, "Error opening tree root\n");
887 if (!list_roots && !fs_info->fs_root) {
888 struct btrfs_key key;
890 key.objectid = BTRFS_FS_TREE_OBJECTID;
891 key.type = BTRFS_ROOT_ITEM_KEY;
892 key.offset = (u64)-1;
893 fs_info->fs_root = btrfs_read_fs_root_no_cache(fs_info, &key);
894 if (IS_ERR(fs_info->fs_root)) {
895 fprintf(stderr, "Couldn't read fs root: %ld\n",
896 PTR_ERR(fs_info->fs_root));
897 close_ctree(fs_info->tree_root);
902 if (list_roots && do_list_roots(fs_info->tree_root)) {
903 close_ctree(fs_info->tree_root);
907 return fs_info->fs_root;
910 static int find_first_dir(struct btrfs_root *root, u64 *objectid)
912 struct btrfs_path *path;
913 struct btrfs_key found_key;
914 struct btrfs_key key;
919 key.type = BTRFS_DIR_INDEX_KEY;
922 path = btrfs_alloc_path();
924 fprintf(stderr, "Ran out of memory\n");
928 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
930 fprintf(stderr, "Error searching %d\n", ret);
934 if (!path->nodes[0]) {
935 fprintf(stderr, "No leaf!\n");
939 for (i = path->slots[0];
940 i < btrfs_header_nritems(path->nodes[0]); i++) {
941 btrfs_item_key_to_cpu(path->nodes[0], &found_key, i);
942 if (found_key.type != key.type)
945 printf("Using objectid %Lu for first dir\n",
947 *objectid = found_key.objectid;
952 ret = next_leaf(root, path);
954 fprintf(stderr, "Error getting next leaf %d\n",
957 } else if (ret > 0) {
958 fprintf(stderr, "No more leaves\n");
961 } while (!path->nodes[0]);
964 printf("Couldn't find a dir index item\n");
966 btrfs_free_path(path);
970 const char * const cmd_restore_usage[] = {
971 "btrfs restore [options] <device>",
972 "Try to restore files from a damaged filesystem (unmounted)",
979 "-f <offset> filesystem location",
980 "-u <block> super mirror",
985 int cmd_restore(int argc, char **argv)
987 struct btrfs_root *root;
988 struct btrfs_key key;
990 u64 tree_location = 0;
992 u64 root_objectid = 0;
996 int super_mirror = 0;
999 const char *match_regstr = NULL;
1000 int match_cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
1001 regex_t match_reg, *mreg = NULL;
1004 while ((opt = getopt(argc, argv, "sviot:u:df:r:lcm:")) != -1) {
1021 tree_location = (u64)strtoll(optarg, NULL, 10);
1023 fprintf(stderr, "Tree location not valid\n");
1029 fs_location = (u64)strtoll(optarg, NULL, 10);
1031 fprintf(stderr, "Fs location not valid\n");
1037 super_mirror = (int)strtol(optarg, NULL, 10);
1039 super_mirror >= BTRFS_SUPER_MIRROR_MAX) {
1040 fprintf(stderr, "Super mirror not "
1050 root_objectid = (u64)strtoll(optarg, NULL, 10);
1052 fprintf(stderr, "Root objectid not valid\n");
1060 match_cflags |= REG_ICASE;
1063 match_regstr = optarg;
1066 usage(cmd_restore_usage);
1070 if (!list_roots && optind + 1 >= argc)
1071 usage(cmd_restore_usage);
1072 else if (list_roots && optind >= argc)
1073 usage(cmd_restore_usage);
1075 if ((ret = check_mounted(argv[optind])) < 0) {
1076 fprintf(stderr, "Could not check mount status: %s\n",
1080 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
1084 root = open_fs(argv[optind], tree_location, super_mirror, list_roots);
1091 if (fs_location != 0) {
1092 free_extent_buffer(root->node);
1093 root->node = read_tree_block(root, fs_location, root->leafsize, 0);
1095 fprintf(stderr, "Failed to read fs location\n");
1100 memset(path_name, 0, 4096);
1102 strncpy(dir_name, argv[optind + 1], sizeof dir_name);
1103 dir_name[sizeof dir_name - 1] = 0;
1105 /* Strip the trailing / on the dir name */
1106 len = strlen(dir_name);
1107 while (len && dir_name[--len] == '/') {
1108 dir_name[len] = '\0';
1111 if (root_objectid != 0) {
1112 struct btrfs_root *orig_root = root;
1114 key.objectid = root_objectid;
1115 key.type = BTRFS_ROOT_ITEM_KEY;
1116 key.offset = (u64)-1;
1117 root = btrfs_read_fs_root(orig_root->fs_info, &key);
1119 fprintf(stderr, "Error reading root\n");
1129 ret = find_first_dir(root, &key.objectid);
1133 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
1137 ret = regcomp(&match_reg, match_regstr, match_cflags);
1139 regerror(ret, &match_reg, reg_err, sizeof(reg_err));
1140 fprintf(stderr, "Regex compile failed: %s\n", reg_err);
1146 ret = search_dir(root, &key, dir_name, "", mreg);