btrfs-progs: Initialize ret to suppress compiler warning
[btrfs-progs-unstable/devel.git] / cmds-restore.c
blobbdd35bd79b4c10b45ce836c7c949bcf254139256
1 /*
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"
22 #include <ctype.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <lzo/lzoconf.h>
30 #include <lzo/lzo1x.h>
31 #include <zlib.h>
32 #include <regex.h>
33 #include <getopt.h>
34 #include <sys/types.h>
35 #include <sys/xattr.h>
37 #include "ctree.h"
38 #include "disk-io.h"
39 #include "print-tree.h"
40 #include "transaction.h"
41 #include "list.h"
42 #include "volumes.h"
43 #include "utils.h"
44 #include "commands.h"
46 static char fs_name[PATH_MAX];
47 static char path_name[PATH_MAX];
48 static char symlink_target[PATH_MAX];
49 static int get_snaps = 0;
50 static int verbose = 0;
51 static int restore_metadata = 0;
52 static int restore_symlinks = 0;
53 static int ignore_errors = 0;
54 static int overwrite = 0;
55 static int get_xattrs = 0;
56 static int dry_run = 0;
58 #define LZO_LEN 4
59 #define lzo1x_worst_compress(x) ((x) + ((x) / 16) + 64 + 3)
61 static int decompress_zlib(char *inbuf, char *outbuf, u64 compress_len,
62 u64 decompress_len)
64 z_stream strm;
65 int ret;
67 memset(&strm, 0, sizeof(strm));
68 ret = inflateInit(&strm);
69 if (ret != Z_OK) {
70 error("zlib init returned %d", ret);
71 return -1;
74 strm.avail_in = compress_len;
75 strm.next_in = (unsigned char *)inbuf;
76 strm.avail_out = decompress_len;
77 strm.next_out = (unsigned char *)outbuf;
78 ret = inflate(&strm, Z_NO_FLUSH);
79 if (ret != Z_STREAM_END) {
80 (void)inflateEnd(&strm);
81 error("zlib inflate failed: %d", ret);
82 return -1;
85 (void)inflateEnd(&strm);
86 return 0;
88 static inline size_t read_compress_length(unsigned char *buf)
90 __le32 dlen;
91 memcpy(&dlen, buf, LZO_LEN);
92 return le32_to_cpu(dlen);
95 static int decompress_lzo(struct btrfs_root *root, unsigned char *inbuf,
96 char *outbuf, u64 compress_len, u64 *decompress_len)
98 size_t new_len;
99 size_t in_len;
100 size_t out_len = 0;
101 size_t tot_len;
102 size_t tot_in;
103 int ret;
105 ret = lzo_init();
106 if (ret != LZO_E_OK) {
107 error("lzo init returned %d", ret);
108 return -1;
111 tot_len = read_compress_length(inbuf);
112 inbuf += LZO_LEN;
113 tot_in = LZO_LEN;
115 while (tot_in < tot_len) {
116 size_t mod_page;
117 size_t rem_page;
118 in_len = read_compress_length(inbuf);
120 if ((tot_in + LZO_LEN + in_len) > tot_len) {
121 error("bad compress length %lu",
122 (unsigned long)in_len);
123 return -1;
126 inbuf += LZO_LEN;
127 tot_in += LZO_LEN;
128 new_len = lzo1x_worst_compress(root->sectorsize);
129 ret = lzo1x_decompress_safe((const unsigned char *)inbuf, in_len,
130 (unsigned char *)outbuf,
131 (void *)&new_len, NULL);
132 if (ret != LZO_E_OK) {
133 error("lzo decompress failed: %d", ret);
134 return -1;
136 out_len += new_len;
137 outbuf += new_len;
138 inbuf += in_len;
139 tot_in += in_len;
142 * If the 4 byte header does not fit to the rest of the page we
143 * have to move to the next one, unless we read some garbage
145 mod_page = tot_in % root->sectorsize;
146 rem_page = root->sectorsize - mod_page;
147 if (rem_page < LZO_LEN) {
148 inbuf += rem_page;
149 tot_in += rem_page;
153 *decompress_len = out_len;
155 return 0;
158 static int decompress(struct btrfs_root *root, char *inbuf, char *outbuf,
159 u64 compress_len, u64 *decompress_len, int compress)
161 switch (compress) {
162 case BTRFS_COMPRESS_ZLIB:
163 return decompress_zlib(inbuf, outbuf, compress_len,
164 *decompress_len);
165 case BTRFS_COMPRESS_LZO:
166 return decompress_lzo(root, (unsigned char *)inbuf, outbuf,
167 compress_len, decompress_len);
168 default:
169 break;
172 error("invalid compression type: %d", compress);
173 return -1;
176 static int next_leaf(struct btrfs_root *root, struct btrfs_path *path)
178 int slot;
179 int level = 1;
180 int offset = 1;
181 struct extent_buffer *c;
182 struct extent_buffer *next = NULL;
184 again:
185 for (; level < BTRFS_MAX_LEVEL; level++) {
186 if (path->nodes[level])
187 break;
190 if (level >= BTRFS_MAX_LEVEL)
191 return 1;
193 slot = path->slots[level] + 1;
195 while(level < BTRFS_MAX_LEVEL) {
196 if (!path->nodes[level])
197 return 1;
199 slot = path->slots[level] + offset;
200 c = path->nodes[level];
201 if (slot >= btrfs_header_nritems(c)) {
202 level++;
203 if (level == BTRFS_MAX_LEVEL)
204 return 1;
205 offset = 1;
206 continue;
209 if (path->reada)
210 reada_for_search(root, path, level, slot, 0);
212 next = read_node_slot(root, c, slot);
213 if (extent_buffer_uptodate(next))
214 break;
215 offset++;
217 path->slots[level] = slot;
218 while(1) {
219 level--;
220 c = path->nodes[level];
221 free_extent_buffer(c);
222 path->nodes[level] = next;
223 path->slots[level] = 0;
224 if (!level)
225 break;
226 if (path->reada)
227 reada_for_search(root, path, level, 0, 0);
228 next = read_node_slot(root, next, 0);
229 if (!extent_buffer_uptodate(next))
230 goto again;
232 return 0;
235 static int copy_one_inline(struct btrfs_root *root, int fd,
236 struct btrfs_path *path, u64 pos)
238 struct extent_buffer *leaf = path->nodes[0];
239 struct btrfs_file_extent_item *fi;
240 char buf[4096];
241 char *outbuf;
242 u64 ram_size;
243 ssize_t done;
244 unsigned long ptr;
245 int ret;
246 int len;
247 int inline_item_len;
248 int compress;
250 fi = btrfs_item_ptr(leaf, path->slots[0],
251 struct btrfs_file_extent_item);
252 ptr = btrfs_file_extent_inline_start(fi);
253 len = btrfs_file_extent_inline_len(leaf, path->slots[0], fi);
254 inline_item_len = btrfs_file_extent_inline_item_len(leaf, btrfs_item_nr(path->slots[0]));
255 read_extent_buffer(leaf, buf, ptr, inline_item_len);
257 compress = btrfs_file_extent_compression(leaf, fi);
258 if (compress == BTRFS_COMPRESS_NONE) {
259 done = pwrite(fd, buf, len, pos);
260 if (done < len) {
261 fprintf(stderr, "Short inline write, wanted %d, did "
262 "%zd: %d\n", len, done, errno);
263 return -1;
265 return 0;
268 ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
269 outbuf = calloc(1, ram_size);
270 if (!outbuf) {
271 error("not enough memory");
272 return -ENOMEM;
275 ret = decompress(root, buf, outbuf, len, &ram_size, compress);
276 if (ret) {
277 free(outbuf);
278 return ret;
281 done = pwrite(fd, outbuf, ram_size, pos);
282 free(outbuf);
283 if (done < ram_size) {
284 fprintf(stderr, "Short compressed inline write, wanted %Lu, "
285 "did %zd: %d\n", ram_size, done, errno);
286 return -1;
289 return 0;
292 static int copy_one_extent(struct btrfs_root *root, int fd,
293 struct extent_buffer *leaf,
294 struct btrfs_file_extent_item *fi, u64 pos)
296 struct btrfs_multi_bio *multi = NULL;
297 struct btrfs_device *device;
298 char *inbuf, *outbuf = NULL;
299 ssize_t done, total = 0;
300 u64 bytenr;
301 u64 ram_size;
302 u64 disk_size;
303 u64 num_bytes;
304 u64 length;
305 u64 size_left;
306 u64 dev_bytenr;
307 u64 offset;
308 u64 count = 0;
309 int compress;
310 int ret;
311 int dev_fd;
312 int mirror_num = 1;
313 int num_copies;
315 compress = btrfs_file_extent_compression(leaf, fi);
316 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
317 disk_size = btrfs_file_extent_disk_num_bytes(leaf, fi);
318 ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
319 offset = btrfs_file_extent_offset(leaf, fi);
320 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
321 size_left = disk_size;
322 if (compress == BTRFS_COMPRESS_NONE)
323 bytenr += offset;
325 if (verbose && offset)
326 printf("offset is %Lu\n", offset);
327 /* we found a hole */
328 if (disk_size == 0)
329 return 0;
331 inbuf = malloc(size_left);
332 if (!inbuf) {
333 error("not enough memory");
334 return -ENOMEM;
337 if (compress != BTRFS_COMPRESS_NONE) {
338 outbuf = calloc(1, ram_size);
339 if (!outbuf) {
340 error("not enough memory");
341 free(inbuf);
342 return -ENOMEM;
345 again:
346 length = size_left;
347 ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
348 bytenr, &length, &multi, mirror_num, NULL);
349 if (ret) {
350 error("cannot map block logical %llu length %llu: %d",
351 (unsigned long long)bytenr,
352 (unsigned long long)length, ret);
353 goto out;
355 device = multi->stripes[0].dev;
356 dev_fd = device->fd;
357 device->total_ios++;
358 dev_bytenr = multi->stripes[0].physical;
359 free(multi);
361 if (size_left < length)
362 length = size_left;
364 done = pread(dev_fd, inbuf+count, length, dev_bytenr);
365 /* Need both checks, or we miss negative values due to u64 conversion */
366 if (done < 0 || done < length) {
367 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
368 bytenr, length);
369 mirror_num++;
370 /* mirror_num is 1-indexed, so num_copies is a valid mirror. */
371 if (mirror_num > num_copies) {
372 ret = -1;
373 error("exhausted mirrors trying to read (%d > %d)",
374 mirror_num, num_copies);
375 goto out;
377 fprintf(stderr, "Trying another mirror\n");
378 goto again;
381 mirror_num = 1;
382 size_left -= length;
383 count += length;
384 bytenr += length;
385 if (size_left)
386 goto again;
388 if (compress == BTRFS_COMPRESS_NONE) {
389 while (total < num_bytes) {
390 done = pwrite(fd, inbuf+total, num_bytes-total,
391 pos+total);
392 if (done < 0) {
393 ret = -1;
394 error("cannot write data: %d %s", errno, strerror(errno));
395 goto out;
397 total += done;
399 ret = 0;
400 goto out;
403 ret = decompress(root, inbuf, outbuf, disk_size, &ram_size, compress);
404 if (ret) {
405 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
406 bytenr, length);
407 mirror_num++;
408 if (mirror_num >= num_copies) {
409 ret = -1;
410 goto out;
412 fprintf(stderr, "Trying another mirror\n");
413 goto again;
416 while (total < num_bytes) {
417 done = pwrite(fd, outbuf + offset + total,
418 num_bytes - total,
419 pos + total);
420 if (done < 0) {
421 ret = -1;
422 goto out;
424 total += done;
426 out:
427 free(inbuf);
428 free(outbuf);
429 return ret;
432 enum loop_response {
433 LOOP_STOP,
434 LOOP_CONTINUE,
435 LOOP_DONTASK
438 static enum loop_response ask_to_continue(const char *file)
440 char buf[2];
441 char *ret;
443 printf("We seem to be looping a lot on %s, do you want to keep going "
444 "on ? (y/N/a): ", file);
445 again:
446 ret = fgets(buf, 2, stdin);
447 if (*ret == '\n' || tolower(*ret) == 'n')
448 return LOOP_STOP;
449 if (tolower(*ret) == 'a')
450 return LOOP_DONTASK;
451 if (tolower(*ret) != 'y') {
452 printf("Please enter one of 'y', 'n', or 'a': ");
453 goto again;
456 return LOOP_CONTINUE;
460 static int set_file_xattrs(struct btrfs_root *root, u64 inode,
461 int fd, const char *file_name)
463 struct btrfs_key key;
464 struct btrfs_path path;
465 struct extent_buffer *leaf;
466 struct btrfs_dir_item *di;
467 u32 name_len = 0;
468 u32 data_len = 0;
469 u32 len = 0;
470 u32 cur, total_len;
471 char *name = NULL;
472 char *data = NULL;
473 int ret = 0;
475 btrfs_init_path(&path);
476 key.objectid = inode;
477 key.type = BTRFS_XATTR_ITEM_KEY;
478 key.offset = 0;
479 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
480 if (ret < 0)
481 goto out;
483 leaf = path.nodes[0];
484 while (1) {
485 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
486 do {
487 ret = next_leaf(root, &path);
488 if (ret < 0) {
489 error("searching for extended attributes: %d",
490 ret);
491 goto out;
492 } else if (ret) {
493 /* No more leaves to search */
494 ret = 0;
495 goto out;
497 leaf = path.nodes[0];
498 } while (!leaf);
499 continue;
502 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
503 if (key.type != BTRFS_XATTR_ITEM_KEY || key.objectid != inode)
504 break;
505 cur = 0;
506 total_len = btrfs_item_size_nr(leaf, path.slots[0]);
507 di = btrfs_item_ptr(leaf, path.slots[0],
508 struct btrfs_dir_item);
510 while (cur < total_len) {
511 len = btrfs_dir_name_len(leaf, di);
512 if (len > name_len) {
513 free(name);
514 name = (char *) malloc(len + 1);
515 if (!name) {
516 ret = -ENOMEM;
517 goto out;
520 read_extent_buffer(leaf, name,
521 (unsigned long)(di + 1), len);
522 name[len] = '\0';
523 name_len = len;
525 len = btrfs_dir_data_len(leaf, di);
526 if (len > data_len) {
527 free(data);
528 data = (char *) malloc(len);
529 if (!data) {
530 ret = -ENOMEM;
531 goto out;
534 read_extent_buffer(leaf, data,
535 (unsigned long)(di + 1) + name_len,
536 len);
537 data_len = len;
539 if (fsetxattr(fd, name, data, data_len, 0))
540 error("setting extended attribute %s on file %s: %s",
541 name, file_name, strerror(errno));
543 len = sizeof(*di) + name_len + data_len;
544 cur += len;
545 di = (struct btrfs_dir_item *)((char *)di + len);
547 path.slots[0]++;
549 ret = 0;
550 out:
551 btrfs_release_path(&path);
552 free(name);
553 free(data);
555 return ret;
558 static int copy_metadata(struct btrfs_root *root, int fd,
559 struct btrfs_key *key)
561 struct btrfs_path path;
562 struct btrfs_inode_item *inode_item;
563 int ret;
565 btrfs_init_path(&path);
566 ret = btrfs_lookup_inode(NULL, root, &path, key, 0);
567 if (ret == 0) {
568 struct btrfs_timespec *bts;
569 struct timespec times[2];
571 inode_item = btrfs_item_ptr(path.nodes[0], path.slots[0],
572 struct btrfs_inode_item);
574 ret = fchown(fd, btrfs_inode_uid(path.nodes[0], inode_item),
575 btrfs_inode_gid(path.nodes[0], inode_item));
576 if (ret) {
577 error("failed to change owner: %s", strerror(errno));
578 goto out;
581 ret = fchmod(fd, btrfs_inode_mode(path.nodes[0], inode_item));
582 if (ret) {
583 error("failed to change mode: %s", strerror(errno));
584 goto out;
587 bts = btrfs_inode_atime(inode_item);
588 times[0].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
589 times[0].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
591 bts = btrfs_inode_mtime(inode_item);
592 times[1].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
593 times[1].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
595 ret = futimens(fd, times);
596 if (ret) {
597 error("failed to set times: %s", strerror(errno));
598 goto out;
601 out:
602 btrfs_release_path(&path);
603 return ret;
606 static int copy_file(struct btrfs_root *root, int fd, struct btrfs_key *key,
607 const char *file)
609 struct extent_buffer *leaf;
610 struct btrfs_path path;
611 struct btrfs_file_extent_item *fi;
612 struct btrfs_inode_item *inode_item;
613 struct btrfs_timespec *bts;
614 struct btrfs_key found_key;
615 int ret;
616 int extent_type;
617 int compression;
618 int loops = 0;
619 u64 found_size = 0;
620 struct timespec times[2];
621 int times_ok = 0;
623 btrfs_init_path(&path);
624 ret = btrfs_lookup_inode(NULL, root, &path, key, 0);
625 if (ret == 0) {
626 inode_item = btrfs_item_ptr(path.nodes[0], path.slots[0],
627 struct btrfs_inode_item);
628 found_size = btrfs_inode_size(path.nodes[0], inode_item);
630 if (restore_metadata) {
632 * Change the ownership and mode now, set times when
633 * copyout is finished.
636 ret = fchown(fd, btrfs_inode_uid(path.nodes[0], inode_item),
637 btrfs_inode_gid(path.nodes[0], inode_item));
638 if (ret && !ignore_errors)
639 goto out;
641 ret = fchmod(fd, btrfs_inode_mode(path.nodes[0], inode_item));
642 if (ret && !ignore_errors)
643 goto out;
645 bts = btrfs_inode_atime(inode_item);
646 times[0].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
647 times[0].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
649 bts = btrfs_inode_mtime(inode_item);
650 times[1].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
651 times[1].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
652 times_ok = 1;
655 btrfs_release_path(&path);
657 key->offset = 0;
658 key->type = BTRFS_EXTENT_DATA_KEY;
660 ret = btrfs_search_slot(NULL, root, key, &path, 0, 0);
661 if (ret < 0) {
662 error("searching extent data returned %d", ret);
663 goto out;
666 leaf = path.nodes[0];
667 while (!leaf) {
668 ret = next_leaf(root, &path);
669 if (ret < 0) {
670 error("cannot get next leaf: %d", ret);
671 goto out;
672 } else if (ret > 0) {
673 /* No more leaves to search */
674 ret = 0;
675 goto out;
677 leaf = path.nodes[0];
680 while (1) {
681 if (loops >= 0 && loops++ >= 1024) {
682 enum loop_response resp;
684 resp = ask_to_continue(file);
685 if (resp == LOOP_STOP)
686 break;
687 else if (resp == LOOP_CONTINUE)
688 loops = 0;
689 else if (resp == LOOP_DONTASK)
690 loops = -1;
692 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
693 do {
694 ret = next_leaf(root, &path);
695 if (ret < 0) {
696 fprintf(stderr, "Error searching %d\n", ret);
697 goto out;
698 } else if (ret) {
699 /* No more leaves to search */
700 btrfs_release_path(&path);
701 goto set_size;
703 leaf = path.nodes[0];
704 } while (!leaf);
705 continue;
707 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
708 if (found_key.objectid != key->objectid)
709 break;
710 if (found_key.type != key->type)
711 break;
712 fi = btrfs_item_ptr(leaf, path.slots[0],
713 struct btrfs_file_extent_item);
714 extent_type = btrfs_file_extent_type(leaf, fi);
715 compression = btrfs_file_extent_compression(leaf, fi);
716 if (compression >= BTRFS_COMPRESS_LAST) {
717 warning("compression type %d not supported",
718 compression);
719 ret = -1;
720 goto out;
723 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC)
724 goto next;
725 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
726 ret = copy_one_inline(root, fd, &path, found_key.offset);
727 if (ret)
728 goto out;
729 } else if (extent_type == BTRFS_FILE_EXTENT_REG) {
730 ret = copy_one_extent(root, fd, leaf, fi,
731 found_key.offset);
732 if (ret)
733 goto out;
734 } else {
735 warning("weird extent type %d", extent_type);
737 next:
738 path.slots[0]++;
741 btrfs_release_path(&path);
742 set_size:
743 if (found_size) {
744 ret = ftruncate(fd, (loff_t)found_size);
745 if (ret)
746 return ret;
748 if (get_xattrs) {
749 ret = set_file_xattrs(root, key->objectid, fd, file);
750 if (ret)
751 return ret;
753 if (restore_metadata && times_ok) {
754 ret = futimens(fd, times);
755 if (ret)
756 return ret;
758 return 0;
760 out:
761 btrfs_release_path(&path);
762 return ret;
766 * returns:
767 * 0 if the file exists and should be skipped.
768 * 1 if the file does NOT exist
769 * 2 if the file exists but is OK to overwrite
771 static int overwrite_ok(const char * path)
773 static int warn = 0;
774 struct stat st;
775 int ret;
777 /* don't be fooled by symlinks */
778 ret = fstatat(-1, path_name, &st, AT_SYMLINK_NOFOLLOW);
780 if (!ret) {
781 if (overwrite)
782 return 2;
784 if (verbose || !warn)
785 printf("Skipping existing file"
786 " %s\n", path);
787 if (!warn)
788 printf("If you wish to overwrite use -o\n");
789 warn = 1;
790 return 0;
792 return 1;
795 static int copy_symlink(struct btrfs_root *root, struct btrfs_key *key,
796 const char *file)
798 struct btrfs_path path;
799 struct extent_buffer *leaf;
800 struct btrfs_file_extent_item *extent_item;
801 struct btrfs_inode_item *inode_item;
802 u32 len;
803 u32 name_offset;
804 int ret;
805 struct btrfs_timespec *bts;
806 struct timespec times[2];
808 ret = overwrite_ok(path_name);
809 if (ret == 0)
810 return 0; /* skip this file */
812 /* symlink() can't overwrite, so unlink first */
813 if (ret == 2) {
814 ret = unlink(path_name);
815 if (ret) {
816 fprintf(stderr, "failed to unlink '%s' for overwrite\n",
817 path_name);
818 return ret;
822 btrfs_init_path(&path);
823 key->type = BTRFS_EXTENT_DATA_KEY;
824 key->offset = 0;
825 ret = btrfs_search_slot(NULL, root, key, &path, 0, 0);
826 if (ret < 0)
827 goto out;
829 leaf = path.nodes[0];
830 if (!leaf) {
831 fprintf(stderr, "Error getting leaf for symlink '%s'\n", file);
832 ret = -1;
833 goto out;
836 extent_item = btrfs_item_ptr(leaf, path.slots[0],
837 struct btrfs_file_extent_item);
839 len = btrfs_file_extent_inline_item_len(leaf,
840 btrfs_item_nr(path.slots[0]));
841 if (len >= PATH_MAX) {
842 fprintf(stderr, "Symlink '%s' target length %d is longer than PATH_MAX\n",
843 fs_name, len);
844 ret = -1;
845 goto out;
848 name_offset = (unsigned long) extent_item
849 + offsetof(struct btrfs_file_extent_item, disk_bytenr);
850 read_extent_buffer(leaf, symlink_target, name_offset, len);
852 symlink_target[len] = 0;
854 if (!dry_run) {
855 ret = symlink(symlink_target, path_name);
856 if (ret < 0) {
857 fprintf(stderr, "Failed to restore symlink '%s': %s\n",
858 path_name, strerror(errno));
859 goto out;
862 printf("SYMLINK: '%s' => '%s'\n", path_name, symlink_target);
864 ret = 0;
865 if (!restore_metadata)
866 goto out;
869 * Symlink metadata operates differently than files/directories, so do
870 * our own work here.
872 key->type = BTRFS_INODE_ITEM_KEY;
873 key->offset = 0;
875 btrfs_release_path(&path);
877 ret = btrfs_lookup_inode(NULL, root, &path, key, 0);
878 if (ret) {
879 fprintf(stderr, "Failed to lookup inode for '%s'\n", file);
880 goto out;
883 inode_item = btrfs_item_ptr(path.nodes[0], path.slots[0],
884 struct btrfs_inode_item);
886 ret = fchownat(-1, file, btrfs_inode_uid(path.nodes[0], inode_item),
887 btrfs_inode_gid(path.nodes[0], inode_item),
888 AT_SYMLINK_NOFOLLOW);
889 if (ret) {
890 fprintf(stderr, "Failed to change owner: %s\n",
891 strerror(errno));
892 goto out;
895 bts = btrfs_inode_atime(inode_item);
896 times[0].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
897 times[0].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
899 bts = btrfs_inode_mtime(inode_item);
900 times[1].tv_sec = btrfs_timespec_sec(path.nodes[0], bts);
901 times[1].tv_nsec = btrfs_timespec_nsec(path.nodes[0], bts);
903 ret = utimensat(-1, file, times, AT_SYMLINK_NOFOLLOW);
904 if (ret)
905 fprintf(stderr, "Failed to set times: %s\n", strerror(errno));
906 out:
907 btrfs_release_path(&path);
908 return ret;
911 static int search_dir(struct btrfs_root *root, struct btrfs_key *key,
912 const char *output_rootdir, const char *in_dir,
913 const regex_t *mreg)
915 struct btrfs_path path;
916 struct extent_buffer *leaf;
917 struct btrfs_dir_item *dir_item;
918 struct btrfs_key found_key, location;
919 char filename[BTRFS_NAME_LEN + 1];
920 unsigned long name_ptr;
921 int name_len;
922 int ret = 0;
923 int fd;
924 int loops = 0;
925 u8 type;
927 btrfs_init_path(&path);
928 key->offset = 0;
929 key->type = BTRFS_DIR_INDEX_KEY;
930 ret = btrfs_search_slot(NULL, root, key, &path, 0, 0);
931 if (ret < 0) {
932 fprintf(stderr, "Error searching %d\n", ret);
933 goto out;
936 ret = 0;
938 leaf = path.nodes[0];
939 while (!leaf) {
940 if (verbose > 1)
941 printf("No leaf after search, looking for the next "
942 "leaf\n");
943 ret = next_leaf(root, &path);
944 if (ret < 0) {
945 fprintf(stderr, "Error getting next leaf %d\n",
946 ret);
947 goto out;
948 } else if (ret > 0) {
949 /* No more leaves to search */
950 if (verbose)
951 printf("Reached the end of the tree looking "
952 "for the directory\n");
953 ret = 0;
954 goto out;
956 leaf = path.nodes[0];
959 while (leaf) {
960 if (loops++ >= 1024) {
961 printf("We have looped trying to restore files in %s "
962 "too many times to be making progress, "
963 "stopping\n", in_dir);
964 break;
967 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
968 do {
969 ret = next_leaf(root, &path);
970 if (ret < 0) {
971 fprintf(stderr, "Error searching %d\n",
972 ret);
973 goto out;
974 } else if (ret > 0) {
975 /* No more leaves to search */
976 if (verbose)
977 printf("Reached the end of "
978 "the tree searching the"
979 " directory\n");
980 ret = 0;
981 goto out;
983 leaf = path.nodes[0];
984 } while (!leaf);
985 continue;
987 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
988 if (found_key.objectid != key->objectid) {
989 if (verbose > 1)
990 printf("Found objectid=%Lu, key=%Lu\n",
991 found_key.objectid, key->objectid);
992 break;
994 if (found_key.type != key->type) {
995 if (verbose > 1)
996 printf("Found type=%u, want=%u\n",
997 found_key.type, key->type);
998 break;
1000 dir_item = btrfs_item_ptr(leaf, path.slots[0],
1001 struct btrfs_dir_item);
1002 name_ptr = (unsigned long)(dir_item + 1);
1003 name_len = btrfs_dir_name_len(leaf, dir_item);
1004 read_extent_buffer(leaf, filename, name_ptr, name_len);
1005 filename[name_len] = '\0';
1006 type = btrfs_dir_type(leaf, dir_item);
1007 btrfs_dir_item_key_to_cpu(leaf, dir_item, &location);
1009 /* full path from root of btrfs being restored */
1010 snprintf(fs_name, PATH_MAX, "%s/%s", in_dir, filename);
1012 if (mreg && REG_NOMATCH == regexec(mreg, fs_name, 0, NULL, 0))
1013 goto next;
1015 /* full path from system root */
1016 snprintf(path_name, PATH_MAX, "%s%s", output_rootdir, fs_name);
1019 * Restore directories, files, symlinks and metadata.
1021 if (type == BTRFS_FT_REG_FILE) {
1022 if (!overwrite_ok(path_name))
1023 goto next;
1025 if (verbose)
1026 printf("Restoring %s\n", path_name);
1027 if (dry_run)
1028 goto next;
1029 fd = open(path_name, O_CREAT|O_WRONLY, 0644);
1030 if (fd < 0) {
1031 fprintf(stderr, "Error creating %s: %d\n",
1032 path_name, errno);
1033 if (ignore_errors)
1034 goto next;
1035 ret = -1;
1036 goto out;
1038 loops = 0;
1039 ret = copy_file(root, fd, &location, path_name);
1040 close(fd);
1041 if (ret) {
1042 fprintf(stderr, "Error copying data for %s\n",
1043 path_name);
1044 if (ignore_errors)
1045 goto next;
1046 goto out;
1048 } else if (type == BTRFS_FT_DIR) {
1049 struct btrfs_root *search_root = root;
1050 char *dir = strdup(fs_name);
1052 if (!dir) {
1053 fprintf(stderr, "Ran out of memory\n");
1054 ret = -ENOMEM;
1055 goto out;
1058 if (location.type == BTRFS_ROOT_ITEM_KEY) {
1060 * If we are a snapshot and this is the index
1061 * object to ourselves just skip it.
1063 if (location.objectid ==
1064 root->root_key.objectid) {
1065 free(dir);
1066 goto next;
1069 location.offset = (u64)-1;
1070 search_root = btrfs_read_fs_root(root->fs_info,
1071 &location);
1072 if (IS_ERR(search_root)) {
1073 free(dir);
1074 fprintf(stderr, "Error reading "
1075 "subvolume %s: %lu\n",
1076 path_name,
1077 PTR_ERR(search_root));
1078 if (ignore_errors)
1079 goto next;
1080 ret = PTR_ERR(search_root);
1081 goto out;
1085 * A subvolume will have a key.offset of 0, a
1086 * snapshot will have key.offset of a transid.
1088 if (search_root->root_key.offset != 0 &&
1089 get_snaps == 0) {
1090 free(dir);
1091 printf("Skipping snapshot %s\n",
1092 filename);
1093 goto next;
1095 location.objectid = BTRFS_FIRST_FREE_OBJECTID;
1098 if (verbose)
1099 printf("Restoring %s\n", path_name);
1101 errno = 0;
1102 if (dry_run)
1103 ret = 0;
1104 else
1105 ret = mkdir(path_name, 0755);
1106 if (ret && errno != EEXIST) {
1107 free(dir);
1108 fprintf(stderr, "Error mkdiring %s: %d\n",
1109 path_name, errno);
1110 if (ignore_errors)
1111 goto next;
1112 ret = -1;
1113 goto out;
1115 loops = 0;
1116 ret = search_dir(search_root, &location,
1117 output_rootdir, dir, mreg);
1118 free(dir);
1119 if (ret) {
1120 fprintf(stderr, "Error searching %s\n",
1121 path_name);
1122 if (ignore_errors)
1123 goto next;
1124 goto out;
1126 } else if (type == BTRFS_FT_SYMLINK) {
1127 if (restore_symlinks)
1128 ret = copy_symlink(root, &location, path_name);
1129 if (ret < 0) {
1130 if (ignore_errors)
1131 goto next;
1132 btrfs_release_path(&path);
1133 return ret;
1136 next:
1137 path.slots[0]++;
1140 if (restore_metadata) {
1141 snprintf(path_name, PATH_MAX, "%s%s", output_rootdir, in_dir);
1142 fd = open(path_name, O_RDONLY);
1143 if (fd < 0) {
1144 fprintf(stderr, "ERROR: Failed to access %s to restore metadata\n",
1145 path_name);
1146 if (!ignore_errors) {
1147 ret = -1;
1148 goto out;
1150 } else {
1152 * Set owner/mode/time on the directory as well
1154 key->type = BTRFS_INODE_ITEM_KEY;
1155 ret = copy_metadata(root, fd, key);
1156 close(fd);
1157 if (ret && !ignore_errors)
1158 goto out;
1162 if (verbose)
1163 printf("Done searching %s\n", in_dir);
1164 out:
1165 btrfs_release_path(&path);
1166 return ret;
1169 static int do_list_roots(struct btrfs_root *root)
1171 struct btrfs_key key;
1172 struct btrfs_key found_key;
1173 struct btrfs_disk_key disk_key;
1174 struct btrfs_path path;
1175 struct extent_buffer *leaf;
1176 struct btrfs_root_item ri;
1177 unsigned long offset;
1178 int slot;
1179 int ret;
1181 root = root->fs_info->tree_root;
1183 btrfs_init_path(&path);
1184 key.offset = 0;
1185 key.objectid = 0;
1186 key.type = BTRFS_ROOT_ITEM_KEY;
1187 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1188 if (ret < 0) {
1189 fprintf(stderr, "Failed to do search %d\n", ret);
1190 btrfs_release_path(&path);
1191 return -1;
1194 leaf = path.nodes[0];
1196 while (1) {
1197 slot = path.slots[0];
1198 if (slot >= btrfs_header_nritems(leaf)) {
1199 ret = btrfs_next_leaf(root, &path);
1200 if (ret)
1201 break;
1202 leaf = path.nodes[0];
1203 slot = path.slots[0];
1205 btrfs_item_key(leaf, &disk_key, slot);
1206 btrfs_disk_key_to_cpu(&found_key, &disk_key);
1207 if (found_key.type != BTRFS_ROOT_ITEM_KEY) {
1208 path.slots[0]++;
1209 continue;
1212 offset = btrfs_item_ptr_offset(leaf, slot);
1213 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
1214 printf(" tree ");
1215 btrfs_print_key(&disk_key);
1216 printf(" %Lu level %d\n", btrfs_root_bytenr(&ri),
1217 btrfs_root_level(&ri));
1218 path.slots[0]++;
1220 btrfs_release_path(&path);
1222 return 0;
1225 static struct btrfs_root *open_fs(const char *dev, u64 root_location,
1226 int super_mirror, int list_roots)
1228 struct btrfs_fs_info *fs_info = NULL;
1229 struct btrfs_root *root = NULL;
1230 u64 bytenr;
1231 int i;
1233 for (i = super_mirror; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1234 bytenr = btrfs_sb_offset(i);
1235 fs_info = open_ctree_fs_info(dev, bytenr, root_location, 0,
1236 OPEN_CTREE_PARTIAL);
1237 if (fs_info)
1238 break;
1239 fprintf(stderr, "Could not open root, trying backup super\n");
1242 if (!fs_info)
1243 return NULL;
1246 * All we really need to succeed is reading the chunk tree, everything
1247 * else we can do by hand, since we only need to read the tree root and
1248 * the fs_root.
1250 if (!extent_buffer_uptodate(fs_info->tree_root->node)) {
1251 u64 generation;
1253 root = fs_info->tree_root;
1254 if (!root_location)
1255 root_location = btrfs_super_root(fs_info->super_copy);
1256 generation = btrfs_super_generation(fs_info->super_copy);
1257 root->node = read_tree_block(root, root_location,
1258 root->nodesize, generation);
1259 if (!extent_buffer_uptodate(root->node)) {
1260 fprintf(stderr, "Error opening tree root\n");
1261 close_ctree(root);
1262 return NULL;
1266 if (!list_roots && !fs_info->fs_root) {
1267 struct btrfs_key key;
1269 key.objectid = BTRFS_FS_TREE_OBJECTID;
1270 key.type = BTRFS_ROOT_ITEM_KEY;
1271 key.offset = (u64)-1;
1272 fs_info->fs_root = btrfs_read_fs_root_no_cache(fs_info, &key);
1273 if (IS_ERR(fs_info->fs_root)) {
1274 fprintf(stderr, "Couldn't read fs root: %ld\n",
1275 PTR_ERR(fs_info->fs_root));
1276 close_ctree(fs_info->tree_root);
1277 return NULL;
1281 if (list_roots && do_list_roots(fs_info->tree_root)) {
1282 close_ctree(fs_info->tree_root);
1283 return NULL;
1286 return fs_info->fs_root;
1289 static int find_first_dir(struct btrfs_root *root, u64 *objectid)
1291 struct btrfs_path path;
1292 struct btrfs_key found_key;
1293 struct btrfs_key key;
1294 int ret = -1;
1295 int i;
1297 btrfs_init_path(&path);
1298 key.objectid = 0;
1299 key.type = BTRFS_DIR_INDEX_KEY;
1300 key.offset = 0;
1301 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1302 if (ret < 0) {
1303 fprintf(stderr, "Error searching %d\n", ret);
1304 goto out;
1307 if (!path.nodes[0]) {
1308 fprintf(stderr, "No leaf!\n");
1309 goto out;
1311 again:
1312 for (i = path.slots[0];
1313 i < btrfs_header_nritems(path.nodes[0]); i++) {
1314 btrfs_item_key_to_cpu(path.nodes[0], &found_key, i);
1315 if (found_key.type != key.type)
1316 continue;
1318 printf("Using objectid %Lu for first dir\n",
1319 found_key.objectid);
1320 *objectid = found_key.objectid;
1321 ret = 0;
1322 goto out;
1324 do {
1325 ret = next_leaf(root, &path);
1326 if (ret < 0) {
1327 fprintf(stderr, "Error getting next leaf %d\n",
1328 ret);
1329 goto out;
1330 } else if (ret > 0) {
1331 fprintf(stderr, "No more leaves\n");
1332 goto out;
1334 } while (!path.nodes[0]);
1335 if (path.nodes[0])
1336 goto again;
1337 printf("Couldn't find a dir index item\n");
1338 out:
1339 btrfs_release_path(&path);
1340 return ret;
1343 const char * const cmd_restore_usage[] = {
1344 "btrfs restore [options] <device> <path> | -l <device>",
1345 "Try to restore files from a damaged filesystem (unmounted)",
1347 "-s|--snapshots get snapshots",
1348 "-x|--xattr restore extended attributes",
1349 "-m|--metadata restore owner, mode and times",
1350 "-S|--symlink restore symbolic links",
1351 "-v|--verbose verbose",
1352 "-i|--ignore-errors ignore errors",
1353 "-o|--overwrite overwrite",
1354 "-t <bytenr> tree location",
1355 "-f <bytenr> filesystem location",
1356 "-u|--super <mirror> super mirror",
1357 "-r|--root <rootid> root objectid",
1358 "-d find dir",
1359 "-l|--list-roots list tree roots",
1360 "-D|--dry-run dry run (only list files that would be recovered)",
1361 "--path-regex <regex>",
1362 " restore only filenames matching regex,",
1363 " you have to use following syntax (possibly quoted):",
1364 " ^/(|home(|/username(|/Desktop(|/.*))))$",
1365 "-c ignore case (--path-regex only)",
1366 NULL
1369 int cmd_restore(int argc, char **argv)
1371 struct btrfs_root *root;
1372 struct btrfs_key key;
1373 char dir_name[PATH_MAX];
1374 u64 tree_location = 0;
1375 u64 fs_location = 0;
1376 u64 root_objectid = 0;
1377 int len;
1378 int ret;
1379 int super_mirror = 0;
1380 int find_dir = 0;
1381 int list_roots = 0;
1382 const char *match_regstr = NULL;
1383 int match_cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
1384 regex_t match_reg, *mreg = NULL;
1385 char reg_err[256];
1387 while (1) {
1388 int opt;
1389 enum { GETOPT_VAL_PATH_REGEX = 256 };
1390 static const struct option long_options[] = {
1391 { "path-regex", required_argument, NULL,
1392 GETOPT_VAL_PATH_REGEX },
1393 { "dry-run", no_argument, NULL, 'D'},
1394 { "metadata", no_argument, NULL, 'm'},
1395 { "symlinks", no_argument, NULL, 'S'},
1396 { "snapshots", no_argument, NULL, 's'},
1397 { "xattr", no_argument, NULL, 'x'},
1398 { "verbose", no_argument, NULL, 'v'},
1399 { "ignore-errors", no_argument, NULL, 'i'},
1400 { "overwrite", no_argument, NULL, 'o'},
1401 { "super", required_argument, NULL, 'u'},
1402 { "root", required_argument, NULL, 'r'},
1403 { "list-roots", no_argument, NULL, 'l'},
1404 { NULL, 0, NULL, 0}
1407 opt = getopt_long(argc, argv, "sSxviot:u:dmf:r:lDc", long_options,
1408 NULL);
1409 if (opt < 0)
1410 break;
1412 switch (opt) {
1413 case 's':
1414 get_snaps = 1;
1415 break;
1416 case 'v':
1417 verbose++;
1418 break;
1419 case 'i':
1420 ignore_errors = 1;
1421 break;
1422 case 'o':
1423 overwrite = 1;
1424 break;
1425 case 't':
1426 tree_location = arg_strtou64(optarg);
1427 break;
1428 case 'f':
1429 fs_location = arg_strtou64(optarg);
1430 break;
1431 case 'u':
1432 super_mirror = arg_strtou64(optarg);
1433 if (super_mirror >= BTRFS_SUPER_MIRROR_MAX) {
1434 fprintf(stderr, "Super mirror not "
1435 "valid\n");
1436 exit(1);
1438 break;
1439 case 'd':
1440 find_dir = 1;
1441 break;
1442 case 'r':
1443 root_objectid = arg_strtou64(optarg);
1444 if (!is_fstree(root_objectid)) {
1445 fprintf(stderr, "objectid %llu is not a valid fs/file tree\n",
1446 root_objectid);
1447 exit(1);
1449 break;
1450 case 'l':
1451 list_roots = 1;
1452 break;
1453 case 'm':
1454 restore_metadata = 1;
1455 break;
1456 case 'S':
1457 restore_symlinks = 1;
1458 break;
1459 case 'D':
1460 dry_run = 1;
1461 break;
1462 case 'c':
1463 match_cflags |= REG_ICASE;
1464 break;
1465 case GETOPT_VAL_PATH_REGEX:
1466 match_regstr = optarg;
1467 break;
1468 case 'x':
1469 get_xattrs = 1;
1470 break;
1471 default:
1472 usage(cmd_restore_usage);
1476 if (!list_roots && check_argc_min(argc - optind, 2))
1477 usage(cmd_restore_usage);
1478 else if (list_roots && check_argc_min(argc - optind, 1))
1479 usage(cmd_restore_usage);
1481 if (fs_location && root_objectid) {
1482 fprintf(stderr, "don't use -f and -r at the same time.\n");
1483 return 1;
1486 if ((ret = check_mounted(argv[optind])) < 0) {
1487 fprintf(stderr, "Could not check mount status: %s\n",
1488 strerror(-ret));
1489 return 1;
1490 } else if (ret) {
1491 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
1492 return 1;
1495 root = open_fs(argv[optind], tree_location, super_mirror, list_roots);
1496 if (root == NULL)
1497 return 1;
1499 if (list_roots)
1500 goto out;
1502 if (fs_location != 0) {
1503 free_extent_buffer(root->node);
1504 root->node = read_tree_block(root, fs_location, root->nodesize, 0);
1505 if (!extent_buffer_uptodate(root->node)) {
1506 fprintf(stderr, "Failed to read fs location\n");
1507 ret = 1;
1508 goto out;
1512 memset(path_name, 0, PATH_MAX);
1514 if (strlen(argv[optind + 1]) >= PATH_MAX) {
1515 fprintf(stderr, "ERROR: path too long\n");
1516 ret = 1;
1517 goto out;
1519 strncpy(dir_name, argv[optind + 1], sizeof dir_name);
1520 dir_name[sizeof dir_name - 1] = 0;
1522 /* Strip the trailing / on the dir name */
1523 len = strlen(dir_name);
1524 while (len && dir_name[--len] == '/') {
1525 dir_name[len] = '\0';
1528 if (root_objectid != 0) {
1529 struct btrfs_root *orig_root = root;
1531 key.objectid = root_objectid;
1532 key.type = BTRFS_ROOT_ITEM_KEY;
1533 key.offset = (u64)-1;
1534 root = btrfs_read_fs_root(orig_root->fs_info, &key);
1535 if (IS_ERR(root)) {
1536 fprintf(stderr, "fail to read root %llu: %s\n",
1537 root_objectid, strerror(-PTR_ERR(root)));
1538 root = orig_root;
1539 ret = 1;
1540 goto out;
1542 key.type = 0;
1543 key.offset = 0;
1546 if (find_dir) {
1547 ret = find_first_dir(root, &key.objectid);
1548 if (ret)
1549 goto out;
1550 } else {
1551 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
1554 if (match_regstr) {
1555 ret = regcomp(&match_reg, match_regstr, match_cflags);
1556 if (ret) {
1557 regerror(ret, &match_reg, reg_err, sizeof(reg_err));
1558 fprintf(stderr, "Regex compile failed: %s\n", reg_err);
1559 goto out;
1561 mreg = &match_reg;
1564 if (dry_run)
1565 printf("This is a dry-run, no files are going to be restored\n");
1567 ret = search_dir(root, &key, dir_name, "", mreg);
1569 out:
1570 if (mreg)
1571 regfree(mreg);
1572 close_ctree(root);
1573 return !!ret;