Btrfs-progs: fix some build warnings on 32bit platform
[platform/upstream/btrfs-progs.git] / cmds-restore.c
1 /*
2  * Copyright (C) 2011 Red Hat.  All rights reserved.
3  *
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.
7  *
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.
12  *
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.
17  */
18
19 #define _XOPEN_SOURCE 500
20 #define _GNU_SOURCE 1
21
22 #include "kerncompat.h"
23
24 #include <ctype.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include <lzo/lzoconf.h>
32 #include <lzo/lzo1x.h>
33 #include <zlib.h>
34 #include <regex.h>
35 #include <getopt.h>
36 #include <sys/types.h>
37 #include <sys/xattr.h>
38
39 #include "ctree.h"
40 #include "disk-io.h"
41 #include "print-tree.h"
42 #include "transaction.h"
43 #include "list.h"
44 #include "version.h"
45 #include "volumes.h"
46 #include "utils.h"
47 #include "commands.h"
48
49 static char fs_name[4096];
50 static char path_name[4096];
51 static int get_snaps = 0;
52 static int verbose = 0;
53 static int ignore_errors = 0;
54 static int overwrite = 0;
55 static int get_xattrs = 0;
56 static int dry_run = 0;
57
58 #define LZO_LEN 4
59 #define PAGE_CACHE_SIZE 4096
60 #define lzo1x_worst_compress(x) ((x) + ((x) / 16) + 64 + 3)
61
62 static int decompress_zlib(char *inbuf, char *outbuf, u64 compress_len,
63                            u64 decompress_len)
64 {
65         z_stream strm;
66         int ret;
67
68         memset(&strm, 0, sizeof(strm));
69         ret = inflateInit(&strm);
70         if (ret != Z_OK) {
71                 fprintf(stderr, "inflate init returnd %d\n", ret);
72                 return -1;
73         }
74
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                 fprintf(stderr, "failed to inflate: %d\n", ret);
83                 return -1;
84         }
85
86         (void)inflateEnd(&strm);
87         return 0;
88 }
89 static inline size_t read_compress_length(unsigned char *buf)
90 {
91         __le32 dlen;
92         memcpy(&dlen, buf, LZO_LEN);
93         return le32_to_cpu(dlen);
94 }
95
96 static int decompress_lzo(unsigned char *inbuf, char *outbuf, u64 compress_len,
97                           u64 *decompress_len)
98 {
99         size_t new_len;
100         size_t in_len;
101         size_t out_len = 0;
102         size_t tot_len;
103         size_t tot_in;
104         int ret;
105
106         ret = lzo_init();
107         if (ret != LZO_E_OK) {
108                 fprintf(stderr, "lzo init returned %d\n", ret);
109                 return -1;
110         }
111
112         tot_len = read_compress_length(inbuf);
113         inbuf += LZO_LEN;
114         tot_in = LZO_LEN;
115
116         while (tot_in < tot_len) {
117                 in_len = read_compress_length(inbuf);
118
119                 if ((tot_in + LZO_LEN + in_len) > tot_len) {
120                         fprintf(stderr, "bad compress length %lu\n",
121                                 (unsigned long)in_len);
122                         return -1;
123                 }
124
125                 inbuf += LZO_LEN;
126                 tot_in += LZO_LEN;
127
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);
134                         return -1;
135                 }
136                 out_len += new_len;
137                 outbuf += new_len;
138                 inbuf += in_len;
139                 tot_in += in_len;
140         }
141
142         *decompress_len = out_len;
143
144         return 0;
145 }
146
147 static int decompress(char *inbuf, char *outbuf, u64 compress_len,
148                       u64 *decompress_len, int compress)
149 {
150         switch (compress) {
151         case BTRFS_COMPRESS_ZLIB:
152                 return decompress_zlib(inbuf, outbuf, compress_len,
153                                        *decompress_len);
154         case BTRFS_COMPRESS_LZO:
155                 return decompress_lzo((unsigned char *)inbuf, outbuf, compress_len,
156                                       decompress_len);
157         default:
158                 break;
159         }
160
161         fprintf(stderr, "invalid compression type: %d\n", compress);
162         return -1;
163 }
164
165 static int next_leaf(struct btrfs_root *root, struct btrfs_path *path)
166 {
167         int slot;
168         int level = 1;
169         int offset = 1;
170         struct extent_buffer *c;
171         struct extent_buffer *next = NULL;
172
173 again:
174         for (; level < BTRFS_MAX_LEVEL; level++) {
175                 if (path->nodes[level])
176                         break;
177         }
178
179         if (level == BTRFS_MAX_LEVEL)
180                 return 1;
181
182         slot = path->slots[level] + 1;
183
184         while(level < BTRFS_MAX_LEVEL) {
185                 if (!path->nodes[level])
186                         return 1;
187
188                 slot = path->slots[level] + offset;
189                 c = path->nodes[level];
190                 if (slot >= btrfs_header_nritems(c)) {
191                         level++;
192                         if (level == BTRFS_MAX_LEVEL)
193                                 return 1;
194                         continue;
195                 }
196
197                 if (path->reada)
198                         reada_for_search(root, path, level, slot, 0);
199
200                 next = read_node_slot(root, c, slot);
201                 if (next)
202                         break;
203                 offset++;
204         }
205         path->slots[level] = slot;
206         while(1) {
207                 level--;
208                 c = path->nodes[level];
209                 free_extent_buffer(c);
210                 path->nodes[level] = next;
211                 path->slots[level] = 0;
212                 if (!level)
213                         break;
214                 if (path->reada)
215                         reada_for_search(root, path, level, 0, 0);
216                 next = read_node_slot(root, next, 0);
217                 if (!next)
218                         goto again;
219         }
220         return 0;
221 }
222
223 static int copy_one_inline(int fd, struct btrfs_path *path, u64 pos)
224 {
225         struct extent_buffer *leaf = path->nodes[0];
226         struct btrfs_file_extent_item *fi;
227         char buf[4096];
228         char *outbuf;
229         u64 ram_size;
230         ssize_t done;
231         unsigned long ptr;
232         int ret;
233         int len;
234         int compress;
235
236         fi = btrfs_item_ptr(leaf, path->slots[0],
237                             struct btrfs_file_extent_item);
238         ptr = btrfs_file_extent_inline_start(fi);
239         len = btrfs_file_extent_inline_len(leaf, path->slots[0], fi);
240         read_extent_buffer(leaf, buf, ptr, len);
241
242         compress = btrfs_file_extent_compression(leaf, fi);
243         if (compress == BTRFS_COMPRESS_NONE) {
244                 done = pwrite(fd, buf, len, pos);
245                 if (done < len) {
246                         fprintf(stderr, "Short inline write, wanted %d, did "
247                                 "%zd: %d\n", len, done, errno);
248                         return -1;
249                 }
250                 return 0;
251         }
252
253         ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
254         outbuf = malloc(ram_size);
255         if (!outbuf) {
256                 fprintf(stderr, "No memory\n");
257                 return -ENOMEM;
258         }
259
260         ret = decompress(buf, outbuf, len, &ram_size, compress);
261         if (ret) {
262                 free(outbuf);
263                 return ret;
264         }
265
266         done = pwrite(fd, outbuf, ram_size, pos);
267         free(outbuf);
268         if (done < ram_size) {
269                 fprintf(stderr, "Short compressed inline write, wanted %Lu, "
270                         "did %zd: %d\n", ram_size, done, errno);
271                 return -1;
272         }
273
274         return 0;
275 }
276
277 static int copy_one_extent(struct btrfs_root *root, int fd,
278                            struct extent_buffer *leaf,
279                            struct btrfs_file_extent_item *fi, u64 pos)
280 {
281         struct btrfs_multi_bio *multi = NULL;
282         struct btrfs_device *device;
283         char *inbuf, *outbuf = NULL;
284         ssize_t done, total = 0;
285         u64 bytenr;
286         u64 ram_size;
287         u64 disk_size;
288         u64 num_bytes;
289         u64 length;
290         u64 size_left;
291         u64 dev_bytenr;
292         u64 offset;
293         u64 count = 0;
294         int compress;
295         int ret;
296         int dev_fd;
297         int mirror_num = 1;
298         int num_copies;
299
300         compress = btrfs_file_extent_compression(leaf, fi);
301         bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
302         disk_size = btrfs_file_extent_disk_num_bytes(leaf, fi);
303         ram_size = btrfs_file_extent_ram_bytes(leaf, fi);
304         offset = btrfs_file_extent_offset(leaf, fi);
305         num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
306         size_left = disk_size;
307         if (compress == BTRFS_COMPRESS_NONE)
308                 bytenr += offset;
309
310         if (offset)
311                 printf("offset is %Lu\n", offset);
312         /* we found a hole */
313         if (disk_size == 0)
314                 return 0;
315
316         inbuf = malloc(size_left);
317         if (!inbuf) {
318                 fprintf(stderr, "No memory\n");
319                 return -ENOMEM;
320         }
321
322         if (compress != BTRFS_COMPRESS_NONE) {
323                 outbuf = malloc(ram_size);
324                 if (!outbuf) {
325                         fprintf(stderr, "No memory\n");
326                         free(inbuf);
327                         return -ENOMEM;
328                 }
329         }
330 again:
331         length = size_left;
332         ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
333                               bytenr, &length, &multi, mirror_num, NULL);
334         if (ret) {
335                 fprintf(stderr, "Error mapping block %d\n", ret);
336                 goto out;
337         }
338         device = multi->stripes[0].dev;
339         dev_fd = device->fd;
340         device->total_ios++;
341         dev_bytenr = multi->stripes[0].physical;
342         kfree(multi);
343
344         if (size_left < length)
345                 length = size_left;
346
347         done = pread(dev_fd, inbuf+count, length, dev_bytenr);
348         /* Need both checks, or we miss negative values due to u64 conversion */
349         if (done < 0 || done < length) {
350                 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
351                                               bytenr, length);
352                 mirror_num++;
353                 /* mirror_num is 1-indexed, so num_copies is a valid mirror. */
354                 if (mirror_num > num_copies) {
355                         ret = -1;
356                         fprintf(stderr, "Exhausted mirrors trying to read\n");
357                         goto out;
358                 }
359                 fprintf(stderr, "Trying another mirror\n");
360                 goto again;
361         }
362
363         mirror_num = 1;
364         size_left -= length;
365         count += length;
366         bytenr += length;
367         if (size_left)
368                 goto again;
369
370         if (compress == BTRFS_COMPRESS_NONE) {
371                 while (total < num_bytes) {
372                         done = pwrite(fd, inbuf+total, num_bytes-total,
373                                       pos+total);
374                         if (done < 0) {
375                                 ret = -1;
376                                 fprintf(stderr, "Error writing: %d %s\n", errno, strerror(errno));
377                                 goto out;
378                         }
379                         total += done;
380                 }
381                 ret = 0;
382                 goto out;
383         }
384
385         ret = decompress(inbuf, outbuf, disk_size, &ram_size, compress);
386         if (ret) {
387                 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
388                                               bytenr, length);
389                 mirror_num++;
390                 if (mirror_num >= num_copies) {
391                         ret = -1;
392                         goto out;
393                 }
394                 fprintf(stderr, "Trying another mirror\n");
395                 goto again;
396         }
397
398         while (total < num_bytes) {
399                 done = pwrite(fd, outbuf + offset + total,
400                               num_bytes - total,
401                               pos + total);
402                 if (done < 0) {
403                         ret = -1;
404                         goto out;
405                 }
406                 total += done;
407         }
408 out:
409         free(inbuf);
410         free(outbuf);
411         return ret;
412 }
413
414 static int ask_to_continue(const char *file)
415 {
416         char buf[2];
417         char *ret;
418
419         printf("We seem to be looping a lot on %s, do you want to keep going "
420                "on ? (y/N): ", file);
421 again:
422         ret = fgets(buf, 2, stdin);
423         if (*ret == '\n' || tolower(*ret) == 'n')
424                 return 1;
425         if (tolower(*ret) != 'y') {
426                 printf("Please enter either 'y' or 'n': ");
427                 goto again;
428         }
429
430         return 0;
431 }
432
433
434 static int set_file_xattrs(struct btrfs_root *root, u64 inode,
435                            int fd, const char *file_name)
436 {
437         struct btrfs_key key;
438         struct btrfs_path *path;
439         struct extent_buffer *leaf;
440         struct btrfs_dir_item *di;
441         u32 name_len = 0;
442         u32 data_len = 0;
443         u32 len = 0;
444         u32 cur, total_len;
445         char *name = NULL;
446         char *data = NULL;
447         int ret = 0;
448
449         key.objectid = inode;
450         key.type = BTRFS_XATTR_ITEM_KEY;
451         key.offset = 0;
452
453         path = btrfs_alloc_path();
454         if (!path)
455                 return -ENOMEM;
456
457         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
458         if (ret < 0)
459                 goto out;
460
461         leaf = path->nodes[0];
462         while (1) {
463                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
464                         do {
465                                 ret = next_leaf(root, path);
466                                 if (ret < 0) {
467                                         fprintf(stderr,
468                                                 "Error searching for extended attributes: %d\n",
469                                                 ret);
470                                         goto out;
471                                 } else if (ret) {
472                                         /* No more leaves to search */
473                                         ret = 0;
474                                         goto out;
475                                 }
476                                 leaf = path->nodes[0];
477                         } while (!leaf);
478                         continue;
479                 }
480
481                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
482                 if (key.type != BTRFS_XATTR_ITEM_KEY || key.objectid != inode)
483                         break;
484                 cur = 0;
485                 total_len = btrfs_item_size_nr(leaf, path->slots[0]);
486                 di = btrfs_item_ptr(leaf, path->slots[0],
487                                     struct btrfs_dir_item);
488
489                 while (cur < total_len) {
490                         len = btrfs_dir_name_len(leaf, di);
491                         if (len > name_len) {
492                                 free(name);
493                                 name = (char *) malloc(len + 1);
494                                 if (!name) {
495                                         ret = -ENOMEM;
496                                         goto out;
497                                 }
498                         }
499                         read_extent_buffer(leaf, name,
500                                            (unsigned long)(di + 1), len);
501                         name[len] = '\0';
502                         name_len = len;
503
504                         len = btrfs_dir_data_len(leaf, di);
505                         if (len > data_len) {
506                                 free(data);
507                                 data = (char *) malloc(len);
508                                 if (!data) {
509                                         ret = -ENOMEM;
510                                         goto out;
511                                 }
512                         }
513                         read_extent_buffer(leaf, data,
514                                            (unsigned long)(di + 1) + name_len,
515                                            len);
516                         data_len = len;
517
518                         if (fsetxattr(fd, name, data, data_len, 0)) {
519                                 int err = errno;
520
521                                 fprintf(stderr,
522                                         "Error setting extended attribute %s on file %s: %s\n",
523                                         name, file_name, strerror(err));
524                         }
525
526                         len = sizeof(*di) + name_len + data_len;
527                         cur += len;
528                         di = (struct btrfs_dir_item *)((char *)di + len);
529                 }
530                 path->slots[0]++;
531         }
532         ret = 0;
533 out:
534         btrfs_free_path(path);
535         free(name);
536         free(data);
537
538         return ret;
539 }
540
541
542 static int copy_file(struct btrfs_root *root, int fd, struct btrfs_key *key,
543                      const char *file)
544 {
545         struct extent_buffer *leaf;
546         struct btrfs_path *path;
547         struct btrfs_file_extent_item *fi;
548         struct btrfs_inode_item *inode_item;
549         struct btrfs_key found_key;
550         int ret;
551         int extent_type;
552         int compression;
553         int loops = 0;
554         u64 found_size = 0;
555
556         path = btrfs_alloc_path();
557         if (!path) {
558                 fprintf(stderr, "Ran out of memory\n");
559                 return -ENOMEM;
560         }
561         path->skip_locking = 1;
562
563         ret = btrfs_lookup_inode(NULL, root, path, key, 0);
564         if (ret == 0) {
565                 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
566                                     struct btrfs_inode_item);
567                 found_size = btrfs_inode_size(path->nodes[0], inode_item);
568         }
569         btrfs_release_path(path);
570
571         key->offset = 0;
572         key->type = BTRFS_EXTENT_DATA_KEY;
573
574         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
575         if (ret < 0) {
576                 fprintf(stderr, "Error searching %d\n", ret);
577                 btrfs_free_path(path);
578                 return ret;
579         }
580
581         leaf = path->nodes[0];
582         while (!leaf) {
583                 ret = next_leaf(root, path);
584                 if (ret < 0) {
585                         fprintf(stderr, "Error getting next leaf %d\n",
586                                 ret);
587                         btrfs_free_path(path);
588                         return ret;
589                 } else if (ret > 0) {
590                         /* No more leaves to search */
591                         btrfs_free_path(path);
592                         return 0;
593                 }
594                 leaf = path->nodes[0];
595         }
596
597         while (1) {
598                 if (loops++ >= 1024) {
599                         ret = ask_to_continue(file);
600                         if (ret)
601                                 break;
602                         loops = 0;
603                 }
604                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
605                         do {
606                                 ret = next_leaf(root, path);
607                                 if (ret < 0) {
608                                         fprintf(stderr, "Error searching %d\n", ret);
609                                         btrfs_free_path(path);
610                                         return ret;
611                                 } else if (ret) {
612                                         /* No more leaves to search */
613                                         btrfs_free_path(path);
614                                         goto set_size;
615                                 }
616                                 leaf = path->nodes[0];
617                         } while (!leaf);
618                         continue;
619                 }
620                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
621                 if (found_key.objectid != key->objectid)
622                         break;
623                 if (found_key.type != key->type)
624                         break;
625                 fi = btrfs_item_ptr(leaf, path->slots[0],
626                                     struct btrfs_file_extent_item);
627                 extent_type = btrfs_file_extent_type(leaf, fi);
628                 compression = btrfs_file_extent_compression(leaf, fi);
629                 if (compression >= BTRFS_COMPRESS_LAST) {
630                         fprintf(stderr, "Don't support compression yet %d\n",
631                                 compression);
632                         btrfs_free_path(path);
633                         return -1;
634                 }
635
636                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC)
637                         goto next;
638                 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
639                         ret = copy_one_inline(fd, path, found_key.offset);
640                         if (ret) {
641                                 btrfs_free_path(path);
642                                 return -1;
643                         }
644                 } else if (extent_type == BTRFS_FILE_EXTENT_REG) {
645                         ret = copy_one_extent(root, fd, leaf, fi,
646                                               found_key.offset);
647                         if (ret) {
648                                 btrfs_free_path(path);
649                                 return ret;
650                         }
651                 } else {
652                         printf("Weird extent type %d\n", extent_type);
653                 }
654 next:
655                 path->slots[0]++;
656         }
657
658         btrfs_free_path(path);
659 set_size:
660         if (found_size) {
661                 ret = ftruncate(fd, (loff_t)found_size);
662                 if (ret)
663                         return ret;
664         }
665         if (get_xattrs) {
666                 ret = set_file_xattrs(root, key->objectid, fd, file);
667                 if (ret)
668                         return ret;
669         }
670         return 0;
671 }
672
673 static int search_dir(struct btrfs_root *root, struct btrfs_key *key,
674                       const char *output_rootdir, const char *in_dir,
675                       const regex_t *mreg)
676 {
677         struct btrfs_path *path;
678         struct extent_buffer *leaf;
679         struct btrfs_dir_item *dir_item;
680         struct btrfs_key found_key, location;
681         char filename[BTRFS_NAME_LEN + 1];
682         unsigned long name_ptr;
683         int name_len;
684         int ret;
685         int fd;
686         int loops = 0;
687         u8 type;
688
689         path = btrfs_alloc_path();
690         if (!path) {
691                 fprintf(stderr, "Ran out of memory\n");
692                 return -ENOMEM;
693         }
694         path->skip_locking = 1;
695
696         key->offset = 0;
697         key->type = BTRFS_DIR_INDEX_KEY;
698
699         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
700         if (ret < 0) {
701                 fprintf(stderr, "Error searching %d\n", ret);
702                 btrfs_free_path(path);
703                 return ret;
704         }
705
706         leaf = path->nodes[0];
707         while (!leaf) {
708                 if (verbose > 1)
709                         printf("No leaf after search, looking for the next "
710                                "leaf\n");
711                 ret = next_leaf(root, path);
712                 if (ret < 0) {
713                         fprintf(stderr, "Error getting next leaf %d\n",
714                                 ret);
715                         btrfs_free_path(path);
716                         return ret;
717                 } else if (ret > 0) {
718                         /* No more leaves to search */
719                         if (verbose)
720                                 printf("Reached the end of the tree looking "
721                                        "for the directory\n");
722                         btrfs_free_path(path);
723                         return 0;
724                 }
725                 leaf = path->nodes[0];
726         }
727
728         while (leaf) {
729                 if (loops++ >= 1024) {
730                         printf("We have looped trying to restore files in %s "
731                                "too many times to be making progress, "
732                                "stopping\n", in_dir);
733                         break;
734                 }
735
736                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
737                         do {
738                                 ret = next_leaf(root, path);
739                                 if (ret < 0) {
740                                         fprintf(stderr, "Error searching %d\n",
741                                                 ret);
742                                         btrfs_free_path(path);
743                                         return ret;
744                                 } else if (ret > 0) {
745                                         /* No more leaves to search */
746                                         if (verbose)
747                                                 printf("Reached the end of "
748                                                        "the tree searching the"
749                                                        " directory\n");
750                                         btrfs_free_path(path);
751                                         return 0;
752                                 }
753                                 leaf = path->nodes[0];
754                         } while (!leaf);
755                         continue;
756                 }
757                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
758                 if (found_key.objectid != key->objectid) {
759                         if (verbose > 1)
760                                 printf("Found objectid=%Lu, key=%Lu\n",
761                                        found_key.objectid, key->objectid);
762                         break;
763                 }
764                 if (found_key.type != key->type) {
765                         if (verbose > 1)
766                                 printf("Found type=%u, want=%u\n",
767                                        found_key.type, key->type);
768                         break;
769                 }
770                 dir_item = btrfs_item_ptr(leaf, path->slots[0],
771                                           struct btrfs_dir_item);
772                 name_ptr = (unsigned long)(dir_item + 1);
773                 name_len = btrfs_dir_name_len(leaf, dir_item);
774                 read_extent_buffer(leaf, filename, name_ptr, name_len);
775                 filename[name_len] = '\0';
776                 type = btrfs_dir_type(leaf, dir_item);
777                 btrfs_dir_item_key_to_cpu(leaf, dir_item, &location);
778
779                 /* full path from root of btrfs being restored */
780                 snprintf(fs_name, 4096, "%s/%s", in_dir, filename);
781
782                 if (mreg && REG_NOMATCH == regexec(mreg, fs_name, 0, NULL, 0))
783                         goto next;
784
785                 /* full path from system root */
786                 snprintf(path_name, 4096, "%s%s", output_rootdir, fs_name);
787
788                 /*
789                  * At this point we're only going to restore directories and
790                  * files, no symlinks or anything else.
791                  */
792                 if (type == BTRFS_FT_REG_FILE) {
793                         if (!overwrite) {
794                                 static int warn = 0;
795                                 struct stat st;
796
797                                 ret = stat(path_name, &st);
798                                 if (!ret) {
799                                         loops = 0;
800                                         if (verbose || !warn)
801                                                 printf("Skipping existing file"
802                                                        " %s\n", path_name);
803                                         if (warn)
804                                                 goto next;
805                                         printf("If you wish to overwrite use "
806                                                "the -o option to overwrite\n");
807                                         warn = 1;
808                                         goto next;
809                                 }
810                                 ret = 0;
811                         }
812                         if (verbose)
813                                 printf("Restoring %s\n", path_name);
814                         if (dry_run)
815                                 goto next;
816                         fd = open(path_name, O_CREAT|O_WRONLY, 0644);
817                         if (fd < 0) {
818                                 fprintf(stderr, "Error creating %s: %d\n",
819                                         path_name, errno);
820                                 if (ignore_errors)
821                                         goto next;
822                                 btrfs_free_path(path);
823                                 return -1;
824                         }
825                         loops = 0;
826                         ret = copy_file(root, fd, &location, path_name);
827                         close(fd);
828                         if (ret) {
829                                 if (ignore_errors)
830                                         goto next;
831                                 btrfs_free_path(path);
832                                 return ret;
833                         }
834                 } else if (type == BTRFS_FT_DIR) {
835                         struct btrfs_root *search_root = root;
836                         char *dir = strdup(fs_name);
837
838                         if (!dir) {
839                                 fprintf(stderr, "Ran out of memory\n");
840                                 btrfs_free_path(path);
841                                 return -ENOMEM;
842                         }
843
844                         if (location.type == BTRFS_ROOT_ITEM_KEY) {
845                                 /*
846                                  * If we are a snapshot and this is the index
847                                  * object to ourselves just skip it.
848                                  */
849                                 if (location.objectid ==
850                                     root->root_key.objectid) {
851                                         free(dir);
852                                         goto next;
853                                 }
854
855                                 location.offset = (u64)-1;
856                                 search_root = btrfs_read_fs_root(root->fs_info,
857                                                                  &location);
858                                 if (IS_ERR(search_root)) {
859                                         free(dir);
860                                         fprintf(stderr, "Error reading "
861                                                 "subvolume %s: %lu\n",
862                                                 path_name,
863                                                 PTR_ERR(search_root));
864                                         if (ignore_errors)
865                                                 goto next;
866                                         btrfs_free_path(path);
867                                         return PTR_ERR(search_root);
868                                 }
869
870                                 /*
871                                  * A subvolume will have a key.offset of 0, a
872                                  * snapshot will have key.offset of a transid.
873                                  */
874                                 if (search_root->root_key.offset != 0 &&
875                                     get_snaps == 0) {
876                                         free(dir);
877                                         printf("Skipping snapshot %s\n",
878                                                filename);
879                                         goto next;
880                                 }
881                                 location.objectid = BTRFS_FIRST_FREE_OBJECTID;
882                         }
883
884                         if (verbose)
885                                 printf("Restoring %s\n", path_name);
886
887                         errno = 0;
888                         if (dry_run)
889                                 ret = 0;
890                         else
891                                 ret = mkdir(path_name, 0755);
892                         if (ret && errno != EEXIST) {
893                                 free(dir);
894                                 fprintf(stderr, "Error mkdiring %s: %d\n",
895                                         path_name, errno);
896                                 if (ignore_errors)
897                                         goto next;
898                                 btrfs_free_path(path);
899                                 return -1;
900                         }
901                         loops = 0;
902                         ret = search_dir(search_root, &location,
903                                          output_rootdir, dir, mreg);
904                         free(dir);
905                         if (ret) {
906                                 if (ignore_errors)
907                                         goto next;
908                                 btrfs_free_path(path);
909                                 return ret;
910                         }
911                 }
912 next:
913                 path->slots[0]++;
914         }
915
916         if (verbose)
917                 printf("Done searching %s\n", in_dir);
918         btrfs_free_path(path);
919         return 0;
920 }
921
922 static int do_list_roots(struct btrfs_root *root)
923 {
924         struct btrfs_key key;
925         struct btrfs_key found_key;
926         struct btrfs_disk_key disk_key;
927         struct btrfs_path *path;
928         struct extent_buffer *leaf;
929         struct btrfs_root_item ri;
930         unsigned long offset;
931         int slot;
932         int ret;
933
934         root = root->fs_info->tree_root;
935         path = btrfs_alloc_path();
936         if (!path) {
937                 fprintf(stderr, "Failed to alloc path\n");
938                 return -ENOMEM;
939         }
940
941         key.offset = 0;
942         key.objectid = 0;
943         key.type = BTRFS_ROOT_ITEM_KEY;
944
945         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
946         if (ret < 0) {
947                 fprintf(stderr, "Failed to do search %d\n", ret);
948                 btrfs_free_path(path);
949                 return -1;
950         }
951
952         while (1) {
953                 leaf = path->nodes[0];
954                 slot = path->slots[0];
955                 if (slot >= btrfs_header_nritems(leaf)) {
956                         ret = btrfs_next_leaf(root, path);
957                         if (ret)
958                                 break;
959                         leaf = path->nodes[0];
960                         slot = path->slots[0];
961                 }
962                 btrfs_item_key(leaf, &disk_key, slot);
963                 btrfs_disk_key_to_cpu(&found_key, &disk_key);
964                 if (btrfs_key_type(&found_key) != BTRFS_ROOT_ITEM_KEY) {
965                         path->slots[0]++;
966                         continue;
967                 }
968
969                 offset = btrfs_item_ptr_offset(leaf, slot);
970                 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
971                 printf(" tree ");
972                 btrfs_print_key(&disk_key);
973                 printf(" %Lu level %d\n", btrfs_root_bytenr(&ri),
974                        btrfs_root_level(&ri));
975                 path->slots[0]++;
976         }
977         btrfs_free_path(path);
978
979         return 0;
980 }
981
982 static struct btrfs_root *open_fs(const char *dev, u64 root_location,
983                                   int super_mirror, int list_roots)
984 {
985         struct btrfs_fs_info *fs_info = NULL;
986         struct btrfs_root *root = NULL;
987         u64 bytenr;
988         int i;
989
990         for (i = super_mirror; i < BTRFS_SUPER_MIRROR_MAX; i++) {
991                 bytenr = btrfs_sb_offset(i);
992                 fs_info = open_ctree_fs_info(dev, bytenr, root_location,
993                                              OPEN_CTREE_PARTIAL);
994                 if (fs_info)
995                         break;
996                 fprintf(stderr, "Could not open root, trying backup super\n");
997         }
998
999         if (!fs_info)
1000                 return NULL;
1001
1002         /*
1003          * All we really need to succeed is reading the chunk tree, everything
1004          * else we can do by hand, since we only need to read the tree root and
1005          * the fs_root.
1006          */
1007         if (!extent_buffer_uptodate(fs_info->tree_root->node)) {
1008                 u64 generation;
1009
1010                 root = fs_info->tree_root;
1011                 if (!root_location)
1012                         root_location = btrfs_super_root(fs_info->super_copy);
1013                 generation = btrfs_super_generation(fs_info->super_copy);
1014                 root->node = read_tree_block(root, root_location,
1015                                              root->leafsize, generation);
1016                 if (!extent_buffer_uptodate(root->node)) {
1017                         fprintf(stderr, "Error opening tree root\n");
1018                         close_ctree(root);
1019                         return NULL;
1020                 }
1021         }
1022
1023         if (!list_roots && !fs_info->fs_root) {
1024                 struct btrfs_key key;
1025
1026                 key.objectid = BTRFS_FS_TREE_OBJECTID;
1027                 key.type = BTRFS_ROOT_ITEM_KEY;
1028                 key.offset = (u64)-1;
1029                 fs_info->fs_root = btrfs_read_fs_root_no_cache(fs_info, &key);
1030                 if (IS_ERR(fs_info->fs_root)) {
1031                         fprintf(stderr, "Couldn't read fs root: %ld\n",
1032                                 PTR_ERR(fs_info->fs_root));
1033                         close_ctree(fs_info->tree_root);
1034                         return NULL;
1035                 }
1036         }
1037
1038         if (list_roots && do_list_roots(fs_info->tree_root)) {
1039                 close_ctree(fs_info->tree_root);
1040                 return NULL;
1041         }
1042
1043         return fs_info->fs_root;
1044 }
1045
1046 static int find_first_dir(struct btrfs_root *root, u64 *objectid)
1047 {
1048         struct btrfs_path *path;
1049         struct btrfs_key found_key;
1050         struct btrfs_key key;
1051         int ret = -1;
1052         int i;
1053
1054         key.objectid = 0;
1055         key.type = BTRFS_DIR_INDEX_KEY;
1056         key.offset = 0;
1057
1058         path = btrfs_alloc_path();
1059         if (!path) {
1060                 fprintf(stderr, "Ran out of memory\n");
1061                 return ret;
1062         }
1063
1064         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1065         if (ret < 0) {
1066                 fprintf(stderr, "Error searching %d\n", ret);
1067                 goto out;
1068         }
1069
1070         if (!path->nodes[0]) {
1071                 fprintf(stderr, "No leaf!\n");
1072                 goto out;
1073         }
1074 again:
1075         for (i = path->slots[0];
1076              i < btrfs_header_nritems(path->nodes[0]); i++) {
1077                 btrfs_item_key_to_cpu(path->nodes[0], &found_key, i);
1078                 if (found_key.type != key.type)
1079                         continue;
1080
1081                 printf("Using objectid %Lu for first dir\n",
1082                        found_key.objectid);
1083                 *objectid = found_key.objectid;
1084                 ret = 0;
1085                 goto out;
1086         }
1087         do {
1088                 ret = next_leaf(root, path);
1089                 if (ret < 0) {
1090                         fprintf(stderr, "Error getting next leaf %d\n",
1091                                 ret);
1092                         goto out;
1093                 } else if (ret > 0) {
1094                         fprintf(stderr, "No more leaves\n");
1095                         goto out;
1096                 }
1097         } while (!path->nodes[0]);
1098         if (path->nodes[0])
1099                 goto again;
1100         printf("Couldn't find a dir index item\n");
1101 out:
1102         btrfs_free_path(path);
1103         return ret;
1104 }
1105
1106 static struct option long_options[] = {
1107         { "path-regex", 1, NULL, 256},
1108         { "dry-run", 0, NULL, 'D'},
1109         { NULL, 0, NULL, 0}
1110 };
1111
1112 const char * const cmd_restore_usage[] = {
1113         "btrfs restore [options] <device> <path> | -l <device>",
1114         "Try to restore files from a damaged filesystem (unmounted)",
1115         "",
1116         "-s              get snapshots",
1117         "-x              get extended attributes",
1118         "-v              verbose",
1119         "-i              ignore errors",
1120         "-o              overwrite",
1121         "-t <bytenr>     tree location",
1122         "-f <bytenr>     filesystem location",
1123         "-u <mirror>     super mirror",
1124         "-r <rootid>     root objectid",
1125         "-d              find dir",
1126         "-l              list tree roots",
1127         "-D|--dry-run    dry run (only list files that would be recovered)",
1128         "--path-regex <regex>",
1129         "                restore only filenames matching regex,",
1130         "                you have to use following syntax (possibly quoted):",
1131         "                ^/(|home(|/username(|/Desktop(|/.*))))$",
1132         "-c              ignore case (--path-regrex only)",
1133         NULL
1134 };
1135
1136 int cmd_restore(int argc, char **argv)
1137 {
1138         struct btrfs_root *root;
1139         struct btrfs_key key;
1140         char dir_name[128];
1141         u64 tree_location = 0;
1142         u64 fs_location = 0;
1143         u64 root_objectid = 0;
1144         int len;
1145         int ret;
1146         int opt;
1147         int option_index = 0;
1148         int super_mirror = 0;
1149         int find_dir = 0;
1150         int list_roots = 0;
1151         const char *match_regstr = NULL;
1152         int match_cflags = REG_EXTENDED | REG_NOSUB | REG_NEWLINE;
1153         regex_t match_reg, *mreg = NULL;
1154         char reg_err[256];
1155
1156         while ((opt = getopt_long(argc, argv, "sxviot:u:df:r:lDc", long_options,
1157                                         &option_index)) != -1) {
1158
1159                 switch (opt) {
1160                         case 's':
1161                                 get_snaps = 1;
1162                                 break;
1163                         case 'v':
1164                                 verbose++;
1165                                 break;
1166                         case 'i':
1167                                 ignore_errors = 1;
1168                                 break;
1169                         case 'o':
1170                                 overwrite = 1;
1171                                 break;
1172                         case 't':
1173                                 tree_location = arg_strtou64(optarg);
1174                                 break;
1175                         case 'f':
1176                                 fs_location = arg_strtou64(optarg);
1177                                 break;
1178                         case 'u':
1179                                 super_mirror = arg_strtou64(optarg);
1180                                 if (super_mirror >= BTRFS_SUPER_MIRROR_MAX) {
1181                                         fprintf(stderr, "Super mirror not "
1182                                                 "valid\n");
1183                                         exit(1);
1184                                 }
1185                                 break;
1186                         case 'd':
1187                                 find_dir = 1;
1188                                 break;
1189                         case 'r':
1190                                 root_objectid = arg_strtou64(optarg);
1191                                 if (!is_fstree(root_objectid)) {
1192                                         fprintf(stderr, "objectid %llu is not a valid fs/file tree\n",
1193                                                         root_objectid);
1194                                         exit(1);
1195                                 }
1196                                 break;
1197                         case 'l':
1198                                 list_roots = 1;
1199                                 break;
1200                         case 'D':
1201                                 dry_run = 1;
1202                                 break;
1203                         case 'c':
1204                                 match_cflags |= REG_ICASE;
1205                                 break;
1206                         /* long option without single letter alternative */
1207                         case 256:
1208                                 match_regstr = optarg;
1209                                 break;
1210                         case 'x':
1211                                 get_xattrs = 1;
1212                                 break;
1213                         default:
1214                                 usage(cmd_restore_usage);
1215                 }
1216         }
1217
1218         set_argv0(argv);
1219         if (!list_roots && check_argc_min(argc - optind, 2))
1220                 usage(cmd_restore_usage);
1221         else if (list_roots && check_argc_min(argc - optind, 1))
1222                 usage(cmd_restore_usage);
1223
1224         if (fs_location && root_objectid) {
1225                 fprintf(stderr, "don't use -f and -r at the same time.\n");
1226                 return 1;
1227         }
1228
1229         if ((ret = check_mounted(argv[optind])) < 0) {
1230                 fprintf(stderr, "Could not check mount status: %s\n",
1231                         strerror(-ret));
1232                 return 1;
1233         } else if (ret) {
1234                 fprintf(stderr, "%s is currently mounted.  Aborting.\n", argv[optind]);
1235                 return 1;
1236         }
1237
1238         root = open_fs(argv[optind], tree_location, super_mirror, list_roots);
1239         if (root == NULL)
1240                 return 1;
1241
1242         if (list_roots)
1243                 goto out;
1244
1245         if (fs_location != 0) {
1246                 free_extent_buffer(root->node);
1247                 root->node = read_tree_block(root, fs_location, root->leafsize, 0);
1248                 if (!root->node) {
1249                         fprintf(stderr, "Failed to read fs location\n");
1250                         ret = 1;
1251                         goto out;
1252                 }
1253         }
1254
1255         memset(path_name, 0, 4096);
1256
1257         strncpy(dir_name, argv[optind + 1], sizeof dir_name);
1258         dir_name[sizeof dir_name - 1] = 0;
1259
1260         /* Strip the trailing / on the dir name */
1261         len = strlen(dir_name);
1262         while (len && dir_name[--len] == '/') {
1263                 dir_name[len] = '\0';
1264         }
1265
1266         if (root_objectid != 0) {
1267                 struct btrfs_root *orig_root = root;
1268
1269                 key.objectid = root_objectid;
1270                 key.type = BTRFS_ROOT_ITEM_KEY;
1271                 key.offset = (u64)-1;
1272                 root = btrfs_read_fs_root(orig_root->fs_info, &key);
1273                 if (IS_ERR(root)) {
1274                         fprintf(stderr, "fail to read root %llu: %s\n",
1275                                         root_objectid, strerror(-PTR_ERR(root)));
1276                         root = orig_root;
1277                         ret = 1;
1278                         goto out;
1279                 }
1280                 key.type = 0;
1281                 key.offset = 0;
1282         }
1283
1284         if (find_dir) {
1285                 ret = find_first_dir(root, &key.objectid);
1286                 if (ret)
1287                         goto out;
1288         } else {
1289                 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
1290         }
1291
1292         if (match_regstr) {
1293                 ret = regcomp(&match_reg, match_regstr, match_cflags);
1294                 if (ret) {
1295                         regerror(ret, &match_reg, reg_err, sizeof(reg_err));
1296                         fprintf(stderr, "Regex compile failed: %s\n", reg_err);
1297                         goto out;
1298                 }
1299                 mreg = &match_reg;
1300         }
1301
1302         if (dry_run)
1303                 printf("This is a dry-run, no files are going to be restored\n");
1304
1305         ret = search_dir(root, &key, dir_name, "", mreg);
1306
1307 out:
1308         if (mreg)
1309                 regfree(mreg);
1310         close_ctree(root);
1311         return !!ret;
1312 }