btrfs-progs: Refactor csum_tree_block to use btrfs_fs_info
[platform/upstream/btrfs-progs.git] / disk-io.c
1 /*
2  * Copyright (C) 2007 Oracle.  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 #include <stdio.h>
20 #include <stdlib.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <fcntl.h>
24 #include <unistd.h>
25 #include <uuid/uuid.h>
26 #include "kerncompat.h"
27 #include "radix-tree.h"
28 #include "ctree.h"
29 #include "disk-io.h"
30 #include "volumes.h"
31 #include "transaction.h"
32 #include "crc32c.h"
33 #include "utils.h"
34 #include "print-tree.h"
35 #include "rbtree-utils.h"
36
37 /* specified errno for check_tree_block */
38 #define BTRFS_BAD_BYTENR                (-1)
39 #define BTRFS_BAD_FSID                  (-2)
40 #define BTRFS_BAD_LEVEL                 (-3)
41 #define BTRFS_BAD_NRITEMS               (-4)
42
43 /* Calculate max possible nritems for a leaf/node */
44 static u32 max_nritems(u8 level, u32 nodesize)
45 {
46
47         if (level == 0)
48                 return ((nodesize - sizeof(struct btrfs_header)) /
49                         sizeof(struct btrfs_item));
50         return ((nodesize - sizeof(struct btrfs_header)) /
51                 sizeof(struct btrfs_key_ptr));
52 }
53
54 static int check_tree_block(struct btrfs_fs_info *fs_info,
55                             struct extent_buffer *buf)
56 {
57
58         struct btrfs_fs_devices *fs_devices;
59         u32 nodesize = fs_info->nodesize;
60         int ret = BTRFS_BAD_FSID;
61
62         if (buf->start != btrfs_header_bytenr(buf))
63                 return BTRFS_BAD_BYTENR;
64         if (btrfs_header_level(buf) >= BTRFS_MAX_LEVEL)
65                 return BTRFS_BAD_LEVEL;
66         if (btrfs_header_nritems(buf) > max_nritems(btrfs_header_level(buf),
67                                                     nodesize))
68                 return BTRFS_BAD_NRITEMS;
69
70         /* Only leaf can be empty */
71         if (btrfs_header_nritems(buf) == 0 &&
72             btrfs_header_level(buf) != 0)
73                 return BTRFS_BAD_NRITEMS;
74
75         fs_devices = fs_info->fs_devices;
76         while (fs_devices) {
77                 if (fs_info->ignore_fsid_mismatch ||
78                     !memcmp_extent_buffer(buf, fs_devices->fsid,
79                                           btrfs_header_fsid(),
80                                           BTRFS_FSID_SIZE)) {
81                         ret = 0;
82                         break;
83                 }
84                 fs_devices = fs_devices->seed;
85         }
86         return ret;
87 }
88
89 static void print_tree_block_error(struct btrfs_fs_info *fs_info,
90                                 struct extent_buffer *eb,
91                                 int err)
92 {
93         char fs_uuid[BTRFS_UUID_UNPARSED_SIZE] = {'\0'};
94         char found_uuid[BTRFS_UUID_UNPARSED_SIZE] = {'\0'};
95         u8 buf[BTRFS_UUID_SIZE];
96
97         switch (err) {
98         case BTRFS_BAD_FSID:
99                 read_extent_buffer(eb, buf, btrfs_header_fsid(),
100                                    BTRFS_UUID_SIZE);
101                 uuid_unparse(buf, found_uuid);
102                 uuid_unparse(fs_info->fsid, fs_uuid);
103                 fprintf(stderr, "fsid mismatch, want=%s, have=%s\n",
104                         fs_uuid, found_uuid);
105                 break;
106         case BTRFS_BAD_BYTENR:
107                 fprintf(stderr, "bytenr mismatch, want=%llu, have=%llu\n",
108                         eb->start, btrfs_header_bytenr(eb));
109                 break;
110         case BTRFS_BAD_LEVEL:
111                 fprintf(stderr, "bad level, %u > %u\n",
112                         btrfs_header_level(eb), BTRFS_MAX_LEVEL);
113                 break;
114         case BTRFS_BAD_NRITEMS:
115                 fprintf(stderr, "invalid nr_items: %u\n",
116                         btrfs_header_nritems(eb));
117                 break;
118         }
119 }
120
121 u32 btrfs_csum_data(char *data, u32 seed, size_t len)
122 {
123         return crc32c(seed, data, len);
124 }
125
126 void btrfs_csum_final(u32 crc, u8 *result)
127 {
128         put_unaligned_le32(~crc, result);
129 }
130
131 static int __csum_tree_block_size(struct extent_buffer *buf, u16 csum_size,
132                                   int verify, int silent)
133 {
134         u8 result[BTRFS_CSUM_SIZE];
135         u32 len;
136         u32 crc = ~(u32)0;
137
138         len = buf->len - BTRFS_CSUM_SIZE;
139         crc = crc32c(crc, buf->data + BTRFS_CSUM_SIZE, len);
140         btrfs_csum_final(crc, result);
141
142         if (verify) {
143                 if (memcmp_extent_buffer(buf, result, 0, csum_size)) {
144                         if (!silent)
145                                 printk("checksum verify failed on %llu found %08X wanted %08X\n",
146                                        (unsigned long long)buf->start,
147                                        *((u32 *)result),
148                                        *((u32*)(char *)buf->data));
149                         return 1;
150                 }
151         } else {
152                 write_extent_buffer(buf, result, 0, csum_size);
153         }
154         return 0;
155 }
156
157 int csum_tree_block_size(struct extent_buffer *buf, u16 csum_size, int verify)
158 {
159         return __csum_tree_block_size(buf, csum_size, verify, 0);
160 }
161
162 int verify_tree_block_csum_silent(struct extent_buffer *buf, u16 csum_size)
163 {
164         return __csum_tree_block_size(buf, csum_size, 1, 1);
165 }
166
167 int csum_tree_block(struct btrfs_fs_info *fs_info,
168                     struct extent_buffer *buf, int verify)
169 {
170         u16 csum_size =
171                 btrfs_super_csum_size(fs_info->super_copy);
172         if (verify && fs_info->suppress_check_block_errors)
173                 return verify_tree_block_csum_silent(buf, csum_size);
174         return csum_tree_block_size(buf, csum_size, verify);
175 }
176
177 struct extent_buffer *btrfs_find_tree_block(struct btrfs_root *root,
178                                             u64 bytenr, u32 blocksize)
179 {
180         return find_extent_buffer(&root->fs_info->extent_cache,
181                                   bytenr, blocksize);
182 }
183
184 struct extent_buffer* btrfs_find_create_tree_block(
185                 struct btrfs_fs_info *fs_info, u64 bytenr, u32 blocksize)
186 {
187         return alloc_extent_buffer(&fs_info->extent_cache, bytenr, blocksize);
188 }
189
190 void readahead_tree_block(struct btrfs_root *root, u64 bytenr, u32 blocksize,
191                           u64 parent_transid)
192 {
193         struct extent_buffer *eb;
194         u64 length;
195         struct btrfs_multi_bio *multi = NULL;
196         struct btrfs_device *device;
197
198         eb = btrfs_find_tree_block(root, bytenr, blocksize);
199         if (!(eb && btrfs_buffer_uptodate(eb, parent_transid)) &&
200             !btrfs_map_block(root->fs_info, READ, bytenr, &length, &multi, 0,
201                              NULL)) {
202                 device = multi->stripes[0].dev;
203                 device->total_ios++;
204                 blocksize = min(blocksize, (u32)SZ_64K);
205                 readahead(device->fd, multi->stripes[0].physical, blocksize);
206         }
207
208         free_extent_buffer(eb);
209         kfree(multi);
210 }
211
212 static int verify_parent_transid(struct extent_io_tree *io_tree,
213                                  struct extent_buffer *eb, u64 parent_transid,
214                                  int ignore)
215 {
216         int ret;
217
218         if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
219                 return 0;
220
221         if (extent_buffer_uptodate(eb) &&
222             btrfs_header_generation(eb) == parent_transid) {
223                 ret = 0;
224                 goto out;
225         }
226         printk("parent transid verify failed on %llu wanted %llu found %llu\n",
227                (unsigned long long)eb->start,
228                (unsigned long long)parent_transid,
229                (unsigned long long)btrfs_header_generation(eb));
230         if (ignore) {
231                 eb->flags |= EXTENT_BAD_TRANSID;
232                 printk("Ignoring transid failure\n");
233                 return 0;
234         }
235
236         ret = 1;
237 out:
238         clear_extent_buffer_uptodate(eb);
239         return ret;
240
241 }
242
243
244 int read_whole_eb(struct btrfs_fs_info *info, struct extent_buffer *eb, int mirror)
245 {
246         unsigned long offset = 0;
247         struct btrfs_multi_bio *multi = NULL;
248         struct btrfs_device *device;
249         int ret = 0;
250         u64 read_len;
251         unsigned long bytes_left = eb->len;
252
253         while (bytes_left) {
254                 read_len = bytes_left;
255                 device = NULL;
256
257                 if (!info->on_restoring &&
258                     eb->start != BTRFS_SUPER_INFO_OFFSET) {
259                         ret = btrfs_map_block(info, READ, eb->start + offset,
260                                               &read_len, &multi, mirror, NULL);
261                         if (ret) {
262                                 printk("Couldn't map the block %Lu\n", eb->start + offset);
263                                 kfree(multi);
264                                 return -EIO;
265                         }
266                         device = multi->stripes[0].dev;
267
268                         if (device->fd <= 0) {
269                                 kfree(multi);
270                                 return -EIO;
271                         }
272
273                         eb->fd = device->fd;
274                         device->total_ios++;
275                         eb->dev_bytenr = multi->stripes[0].physical;
276                         kfree(multi);
277                         multi = NULL;
278                 } else {
279                         /* special case for restore metadump */
280                         list_for_each_entry(device, &info->fs_devices->devices, dev_list) {
281                                 if (device->devid == 1)
282                                         break;
283                         }
284
285                         eb->fd = device->fd;
286                         eb->dev_bytenr = eb->start;
287                         device->total_ios++;
288                 }
289
290                 if (read_len > bytes_left)
291                         read_len = bytes_left;
292
293                 ret = read_extent_from_disk(eb, offset, read_len);
294                 if (ret)
295                         return -EIO;
296                 offset += read_len;
297                 bytes_left -= read_len;
298         }
299         return 0;
300 }
301
302 struct extent_buffer* read_tree_block(
303                 struct btrfs_fs_info *fs_info, u64 bytenr, u32 blocksize,
304                 u64 parent_transid)
305 {
306         int ret;
307         struct extent_buffer *eb;
308         u64 best_transid = 0;
309         u32 sectorsize = fs_info->sectorsize;
310         u32 nodesize = fs_info->nodesize;
311         int mirror_num = 0;
312         int good_mirror = 0;
313         int num_copies;
314         int ignore = 0;
315
316         /*
317          * Don't even try to create tree block for unaligned tree block
318          * bytenr.
319          * Such unaligned tree block will free overlapping extent buffer,
320          * causing use-after-free bugs for fuzzed images.
321          */
322         if (bytenr < sectorsize || !IS_ALIGNED(bytenr, sectorsize)) {
323                 error("tree block bytenr %llu is not aligned to sectorsize %u",
324                       bytenr, sectorsize);
325                 return ERR_PTR(-EIO);
326         }
327         if (blocksize < nodesize || !IS_ALIGNED(blocksize, nodesize)) {
328                 error("tree block size %u is not aligned to nodesize %u",
329                       blocksize, nodesize);
330                 return ERR_PTR(-EIO);
331         }
332
333         eb = btrfs_find_create_tree_block(fs_info, bytenr, blocksize);
334         if (!eb)
335                 return ERR_PTR(-ENOMEM);
336
337         if (btrfs_buffer_uptodate(eb, parent_transid))
338                 return eb;
339
340         while (1) {
341                 ret = read_whole_eb(fs_info, eb, mirror_num);
342                 if (ret == 0 && csum_tree_block(fs_info, eb, 1) == 0 &&
343                     check_tree_block(fs_info, eb) == 0 &&
344                     verify_parent_transid(eb->tree, eb, parent_transid, ignore)
345                     == 0) {
346                         if (eb->flags & EXTENT_BAD_TRANSID &&
347                             list_empty(&eb->recow)) {
348                                 list_add_tail(&eb->recow,
349                                               &fs_info->recow_ebs);
350                                 eb->refs++;
351                         }
352                         btrfs_set_buffer_uptodate(eb);
353                         return eb;
354                 }
355                 if (ignore) {
356                         if (check_tree_block(fs_info, eb)) {
357                                 if (!fs_info->suppress_check_block_errors)
358                                         print_tree_block_error(fs_info, eb,
359                                                 check_tree_block(fs_info, eb));
360                         } else {
361                                 if (!fs_info->suppress_check_block_errors)
362                                         fprintf(stderr, "Csum didn't match\n");
363                         }
364                         ret = -EIO;
365                         break;
366                 }
367                 num_copies = btrfs_num_copies(fs_info, eb->start, eb->len);
368                 if (num_copies == 1) {
369                         ignore = 1;
370                         continue;
371                 }
372                 if (btrfs_header_generation(eb) > best_transid && mirror_num) {
373                         best_transid = btrfs_header_generation(eb);
374                         good_mirror = mirror_num;
375                 }
376                 mirror_num++;
377                 if (mirror_num > num_copies) {
378                         mirror_num = good_mirror;
379                         ignore = 1;
380                         continue;
381                 }
382         }
383         free_extent_buffer(eb);
384         return ERR_PTR(ret);
385 }
386
387 int read_extent_data(struct btrfs_root *root, char *data,
388                            u64 logical, u64 *len, int mirror)
389 {
390         u64 offset = 0;
391         struct btrfs_multi_bio *multi = NULL;
392         struct btrfs_fs_info *info = root->fs_info;
393         struct btrfs_device *device;
394         int ret = 0;
395         u64 max_len = *len;
396
397         ret = btrfs_map_block(info, READ, logical, len, &multi, mirror, NULL);
398         if (ret) {
399                 fprintf(stderr, "Couldn't map the block %llu\n",
400                                 logical + offset);
401                 goto err;
402         }
403         device = multi->stripes[0].dev;
404
405         if (device->fd <= 0)
406                 goto err;
407         if (*len > max_len)
408                 *len = max_len;
409
410         ret = pread64(device->fd, data, *len, multi->stripes[0].physical);
411         if (ret != *len)
412                 ret = -EIO;
413         else
414                 ret = 0;
415 err:
416         kfree(multi);
417         return ret;
418 }
419
420 int write_and_map_eb(struct btrfs_root *root, struct extent_buffer *eb)
421 {
422         int ret;
423         int dev_nr;
424         u64 length;
425         u64 *raid_map = NULL;
426         struct btrfs_multi_bio *multi = NULL;
427
428         dev_nr = 0;
429         length = eb->len;
430         ret = btrfs_map_block(root->fs_info, WRITE, eb->start, &length,
431                               &multi, 0, &raid_map);
432
433         if (raid_map) {
434                 ret = write_raid56_with_parity(root->fs_info, eb, multi,
435                                                length, raid_map);
436                 BUG_ON(ret);
437         } else while (dev_nr < multi->num_stripes) {
438                 BUG_ON(ret);
439                 eb->fd = multi->stripes[dev_nr].dev->fd;
440                 eb->dev_bytenr = multi->stripes[dev_nr].physical;
441                 multi->stripes[dev_nr].dev->total_ios++;
442                 dev_nr++;
443                 ret = write_extent_to_disk(eb);
444                 BUG_ON(ret);
445         }
446         kfree(raid_map);
447         kfree(multi);
448         return 0;
449 }
450
451 int write_tree_block(struct btrfs_trans_handle *trans,
452                      struct btrfs_root *root,
453                      struct extent_buffer *eb)
454 {
455         if (check_tree_block(root->fs_info, eb)) {
456                 print_tree_block_error(root->fs_info, eb,
457                                 check_tree_block(root->fs_info, eb));
458                 BUG();
459         }
460
461         if (trans && !btrfs_buffer_uptodate(eb, trans->transid))
462                 BUG();
463
464         btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
465         csum_tree_block(root->fs_info, eb, 0);
466
467         return write_and_map_eb(root, eb);
468 }
469
470 void btrfs_setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
471                       u64 objectid)
472 {
473         root->node = NULL;
474         root->commit_root = NULL;
475         root->ref_cows = 0;
476         root->track_dirty = 0;
477
478         root->fs_info = fs_info;
479         root->objectid = objectid;
480         root->last_trans = 0;
481         root->last_inode_alloc = 0;
482
483         INIT_LIST_HEAD(&root->dirty_list);
484         INIT_LIST_HEAD(&root->orphan_data_extents);
485         memset(&root->root_key, 0, sizeof(root->root_key));
486         memset(&root->root_item, 0, sizeof(root->root_item));
487         root->root_key.objectid = objectid;
488 }
489
490 static int update_cowonly_root(struct btrfs_trans_handle *trans,
491                                struct btrfs_root *root)
492 {
493         int ret;
494         u64 old_root_bytenr;
495         struct btrfs_root *tree_root = root->fs_info->tree_root;
496
497         btrfs_write_dirty_block_groups(trans, root);
498         while(1) {
499                 old_root_bytenr = btrfs_root_bytenr(&root->root_item);
500                 if (old_root_bytenr == root->node->start)
501                         break;
502                 btrfs_set_root_bytenr(&root->root_item,
503                                        root->node->start);
504                 btrfs_set_root_generation(&root->root_item,
505                                           trans->transid);
506                 root->root_item.level = btrfs_header_level(root->node);
507                 ret = btrfs_update_root(trans, tree_root,
508                                         &root->root_key,
509                                         &root->root_item);
510                 BUG_ON(ret);
511                 btrfs_write_dirty_block_groups(trans, root);
512         }
513         return 0;
514 }
515
516 static int commit_tree_roots(struct btrfs_trans_handle *trans,
517                              struct btrfs_fs_info *fs_info)
518 {
519         struct btrfs_root *root;
520         struct list_head *next;
521         struct extent_buffer *eb;
522         int ret;
523
524         if (fs_info->readonly)
525                 return 0;
526
527         eb = fs_info->tree_root->node;
528         extent_buffer_get(eb);
529         ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL, 0, &eb);
530         free_extent_buffer(eb);
531         if (ret)
532                 return ret;
533
534         while(!list_empty(&fs_info->dirty_cowonly_roots)) {
535                 next = fs_info->dirty_cowonly_roots.next;
536                 list_del_init(next);
537                 root = list_entry(next, struct btrfs_root, dirty_list);
538                 update_cowonly_root(trans, root);
539                 free_extent_buffer(root->commit_root);
540                 root->commit_root = NULL;
541         }
542
543         return 0;
544 }
545
546 static int __commit_transaction(struct btrfs_trans_handle *trans,
547                                 struct btrfs_root *root)
548 {
549         u64 start;
550         u64 end;
551         struct extent_buffer *eb;
552         struct extent_io_tree *tree = &root->fs_info->extent_cache;
553         int ret;
554
555         while(1) {
556                 ret = find_first_extent_bit(tree, 0, &start, &end,
557                                             EXTENT_DIRTY);
558                 if (ret)
559                         break;
560                 while(start <= end) {
561                         eb = find_first_extent_buffer(tree, start);
562                         BUG_ON(!eb || eb->start != start);
563                         ret = write_tree_block(trans, root, eb);
564                         BUG_ON(ret);
565                         start += eb->len;
566                         clear_extent_buffer_dirty(eb);
567                         free_extent_buffer(eb);
568                 }
569         }
570         return 0;
571 }
572
573 int btrfs_commit_transaction(struct btrfs_trans_handle *trans,
574                              struct btrfs_root *root)
575 {
576         u64 transid = trans->transid;
577         int ret = 0;
578         struct btrfs_fs_info *fs_info = root->fs_info;
579
580         if (root->commit_root == root->node)
581                 goto commit_tree;
582         if (root == root->fs_info->tree_root)
583                 goto commit_tree;
584         if (root == root->fs_info->chunk_root)
585                 goto commit_tree;
586
587         free_extent_buffer(root->commit_root);
588         root->commit_root = NULL;
589
590         btrfs_set_root_bytenr(&root->root_item, root->node->start);
591         btrfs_set_root_generation(&root->root_item, trans->transid);
592         root->root_item.level = btrfs_header_level(root->node);
593         ret = btrfs_update_root(trans, root->fs_info->tree_root,
594                                 &root->root_key, &root->root_item);
595         BUG_ON(ret);
596 commit_tree:
597         ret = commit_tree_roots(trans, fs_info);
598         BUG_ON(ret);
599         ret = __commit_transaction(trans, root);
600         BUG_ON(ret);
601         write_ctree_super(trans, root);
602         btrfs_finish_extent_commit(trans, fs_info->extent_root,
603                                    &fs_info->pinned_extents);
604         kfree(trans);
605         free_extent_buffer(root->commit_root);
606         root->commit_root = NULL;
607         fs_info->running_transaction = NULL;
608         fs_info->last_trans_committed = transid;
609         return 0;
610 }
611
612 static int find_and_setup_root(struct btrfs_root *tree_root,
613                                struct btrfs_fs_info *fs_info,
614                                u64 objectid, struct btrfs_root *root)
615 {
616         int ret;
617         u32 blocksize;
618         u64 generation;
619
620         btrfs_setup_root(root, fs_info, objectid);
621         ret = btrfs_find_last_root(tree_root, objectid,
622                                    &root->root_item, &root->root_key);
623         if (ret)
624                 return ret;
625
626         blocksize = fs_info->nodesize;
627         generation = btrfs_root_generation(&root->root_item);
628         root->node = read_tree_block(fs_info,
629                         btrfs_root_bytenr(&root->root_item),
630                         blocksize, generation);
631         if (!extent_buffer_uptodate(root->node))
632                 return -EIO;
633
634         return 0;
635 }
636
637 static int find_and_setup_log_root(struct btrfs_root *tree_root,
638                                struct btrfs_fs_info *fs_info,
639                                struct btrfs_super_block *disk_super)
640 {
641         u32 blocksize;
642         u64 blocknr = btrfs_super_log_root(disk_super);
643         struct btrfs_root *log_root = malloc(sizeof(struct btrfs_root));
644
645         if (!log_root)
646                 return -ENOMEM;
647
648         if (blocknr == 0) {
649                 free(log_root);
650                 return 0;
651         }
652
653         blocksize = fs_info->nodesize;
654
655         btrfs_setup_root(log_root, fs_info,
656                          BTRFS_TREE_LOG_OBJECTID);
657
658         log_root->node = read_tree_block(fs_info, blocknr,
659                                      blocksize,
660                                      btrfs_super_generation(disk_super) + 1);
661
662         fs_info->log_root_tree = log_root;
663
664         if (!extent_buffer_uptodate(log_root->node)) {
665                 free_extent_buffer(log_root->node);
666                 free(log_root);
667                 fs_info->log_root_tree = NULL;
668                 return -EIO;
669         }
670
671         return 0;
672 }
673
674 int btrfs_free_fs_root(struct btrfs_root *root)
675 {
676         if (root->node)
677                 free_extent_buffer(root->node);
678         if (root->commit_root)
679                 free_extent_buffer(root->commit_root);
680         kfree(root);
681         return 0;
682 }
683
684 static void __free_fs_root(struct rb_node *node)
685 {
686         struct btrfs_root *root;
687
688         root = container_of(node, struct btrfs_root, rb_node);
689         btrfs_free_fs_root(root);
690 }
691
692 FREE_RB_BASED_TREE(fs_roots, __free_fs_root);
693
694 struct btrfs_root *btrfs_read_fs_root_no_cache(struct btrfs_fs_info *fs_info,
695                                                struct btrfs_key *location)
696 {
697         struct btrfs_root *root;
698         struct btrfs_root *tree_root = fs_info->tree_root;
699         struct btrfs_path *path;
700         struct extent_buffer *l;
701         u64 generation;
702         u32 blocksize;
703         int ret = 0;
704
705         root = calloc(1, sizeof(*root));
706         if (!root)
707                 return ERR_PTR(-ENOMEM);
708         if (location->offset == (u64)-1) {
709                 ret = find_and_setup_root(tree_root, fs_info,
710                                           location->objectid, root);
711                 if (ret) {
712                         free(root);
713                         return ERR_PTR(ret);
714                 }
715                 goto insert;
716         }
717
718         btrfs_setup_root(root, fs_info,
719                          location->objectid);
720
721         path = btrfs_alloc_path();
722         if (!path) {
723                 free(root);
724                 return ERR_PTR(-ENOMEM);
725         }
726
727         ret = btrfs_search_slot(NULL, tree_root, location, path, 0, 0);
728         if (ret != 0) {
729                 if (ret > 0)
730                         ret = -ENOENT;
731                 goto out;
732         }
733         l = path->nodes[0];
734         read_extent_buffer(l, &root->root_item,
735                btrfs_item_ptr_offset(l, path->slots[0]),
736                sizeof(root->root_item));
737         memcpy(&root->root_key, location, sizeof(*location));
738         ret = 0;
739 out:
740         btrfs_free_path(path);
741         if (ret) {
742                 free(root);
743                 return ERR_PTR(ret);
744         }
745         generation = btrfs_root_generation(&root->root_item);
746         blocksize = fs_info->nodesize;
747         root->node = read_tree_block(fs_info,
748                         btrfs_root_bytenr(&root->root_item),
749                         blocksize, generation);
750         if (!extent_buffer_uptodate(root->node)) {
751                 free(root);
752                 return ERR_PTR(-EIO);
753         }
754 insert:
755         root->ref_cows = 1;
756         return root;
757 }
758
759 static int btrfs_fs_roots_compare_objectids(struct rb_node *node,
760                                             void *data)
761 {
762         u64 objectid = *((u64 *)data);
763         struct btrfs_root *root;
764
765         root = rb_entry(node, struct btrfs_root, rb_node);
766         if (objectid > root->objectid)
767                 return 1;
768         else if (objectid < root->objectid)
769                 return -1;
770         else
771                 return 0;
772 }
773
774 static int btrfs_fs_roots_compare_roots(struct rb_node *node1,
775                                         struct rb_node *node2)
776 {
777         struct btrfs_root *root;
778
779         root = rb_entry(node2, struct btrfs_root, rb_node);
780         return btrfs_fs_roots_compare_objectids(node1, (void *)&root->objectid);
781 }
782
783 struct btrfs_root *btrfs_read_fs_root(struct btrfs_fs_info *fs_info,
784                                       struct btrfs_key *location)
785 {
786         struct btrfs_root *root;
787         struct rb_node *node;
788         int ret;
789         u64 objectid = location->objectid;
790
791         if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
792                 return fs_info->tree_root;
793         if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
794                 return fs_info->extent_root;
795         if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
796                 return fs_info->chunk_root;
797         if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
798                 return fs_info->dev_root;
799         if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
800                 return fs_info->csum_root;
801         if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
802                 return fs_info->quota_enabled ? fs_info->quota_root :
803                                 ERR_PTR(-ENOENT);
804
805         BUG_ON(location->objectid == BTRFS_TREE_RELOC_OBJECTID ||
806                location->offset != (u64)-1);
807
808         node = rb_search(&fs_info->fs_root_tree, (void *)&objectid,
809                          btrfs_fs_roots_compare_objectids, NULL);
810         if (node)
811                 return container_of(node, struct btrfs_root, rb_node);
812
813         root = btrfs_read_fs_root_no_cache(fs_info, location);
814         if (IS_ERR(root))
815                 return root;
816
817         ret = rb_insert(&fs_info->fs_root_tree, &root->rb_node,
818                         btrfs_fs_roots_compare_roots);
819         BUG_ON(ret);
820         return root;
821 }
822
823 void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
824 {
825         if (fs_info->quota_root)
826                 free(fs_info->quota_root);
827
828         free(fs_info->tree_root);
829         free(fs_info->extent_root);
830         free(fs_info->chunk_root);
831         free(fs_info->dev_root);
832         free(fs_info->csum_root);
833         free(fs_info->free_space_root);
834         free(fs_info->super_copy);
835         free(fs_info->log_root_tree);
836         free(fs_info);
837 }
838
839 struct btrfs_fs_info *btrfs_new_fs_info(int writable, u64 sb_bytenr)
840 {
841         struct btrfs_fs_info *fs_info;
842
843         fs_info = calloc(1, sizeof(struct btrfs_fs_info));
844         if (!fs_info)
845                 return NULL;
846
847         fs_info->tree_root = calloc(1, sizeof(struct btrfs_root));
848         fs_info->extent_root = calloc(1, sizeof(struct btrfs_root));
849         fs_info->chunk_root = calloc(1, sizeof(struct btrfs_root));
850         fs_info->dev_root = calloc(1, sizeof(struct btrfs_root));
851         fs_info->csum_root = calloc(1, sizeof(struct btrfs_root));
852         fs_info->quota_root = calloc(1, sizeof(struct btrfs_root));
853         fs_info->free_space_root = calloc(1, sizeof(struct btrfs_root));
854         fs_info->super_copy = calloc(1, BTRFS_SUPER_INFO_SIZE);
855
856         if (!fs_info->tree_root || !fs_info->extent_root ||
857             !fs_info->chunk_root || !fs_info->dev_root ||
858             !fs_info->csum_root || !fs_info->quota_root ||
859             !fs_info->free_space_root || !fs_info->super_copy)
860                 goto free_all;
861
862         extent_io_tree_init(&fs_info->extent_cache);
863         extent_io_tree_init(&fs_info->free_space_cache);
864         extent_io_tree_init(&fs_info->block_group_cache);
865         extent_io_tree_init(&fs_info->pinned_extents);
866         extent_io_tree_init(&fs_info->pending_del);
867         extent_io_tree_init(&fs_info->extent_ins);
868         fs_info->excluded_extents = NULL;
869
870         fs_info->fs_root_tree = RB_ROOT;
871         cache_tree_init(&fs_info->mapping_tree.cache_tree);
872
873         mutex_init(&fs_info->fs_mutex);
874         INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
875         INIT_LIST_HEAD(&fs_info->space_info);
876         INIT_LIST_HEAD(&fs_info->recow_ebs);
877
878         if (!writable)
879                 fs_info->readonly = 1;
880
881         fs_info->super_bytenr = sb_bytenr;
882         fs_info->data_alloc_profile = (u64)-1;
883         fs_info->metadata_alloc_profile = (u64)-1;
884         fs_info->system_alloc_profile = fs_info->metadata_alloc_profile;
885         return fs_info;
886 free_all:
887         btrfs_free_fs_info(fs_info);
888         return NULL;
889 }
890
891 int btrfs_check_fs_compatibility(struct btrfs_super_block *sb,
892                                  unsigned int flags)
893 {
894         u64 features;
895
896         features = btrfs_super_incompat_flags(sb) &
897                    ~BTRFS_FEATURE_INCOMPAT_SUPP;
898         if (features) {
899                 printk("couldn't open because of unsupported "
900                        "option features (%Lx).\n",
901                        (unsigned long long)features);
902                 return -ENOTSUP;
903         }
904
905         features = btrfs_super_incompat_flags(sb);
906         if (!(features & BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF)) {
907                 features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
908                 btrfs_set_super_incompat_flags(sb, features);
909         }
910
911         features = btrfs_super_compat_ro_flags(sb);
912         if (flags & OPEN_CTREE_WRITES) {
913                 if (flags & OPEN_CTREE_INVALIDATE_FST) {
914                         /* Clear the FREE_SPACE_TREE_VALID bit on disk... */
915                         features &= ~BTRFS_FEATURE_COMPAT_RO_FREE_SPACE_TREE_VALID;
916                         btrfs_set_super_compat_ro_flags(sb, features);
917                         /* ... and ignore the free space tree bit. */
918                         features &= ~BTRFS_FEATURE_COMPAT_RO_FREE_SPACE_TREE;
919                 }
920                 if (features & ~BTRFS_FEATURE_COMPAT_RO_SUPP) {
921                         printk("couldn't open RDWR because of unsupported "
922                                "option features (%Lx).\n",
923                                (unsigned long long)features);
924                         return -ENOTSUP;
925                 }
926
927         }
928         return 0;
929 }
930
931 static int find_best_backup_root(struct btrfs_super_block *super)
932 {
933         struct btrfs_root_backup *backup;
934         u64 orig_gen = btrfs_super_generation(super);
935         u64 gen = 0;
936         int best_index = 0;
937         int i;
938
939         for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
940                 backup = super->super_roots + i;
941                 if (btrfs_backup_tree_root_gen(backup) != orig_gen &&
942                     btrfs_backup_tree_root_gen(backup) > gen) {
943                         best_index = i;
944                         gen = btrfs_backup_tree_root_gen(backup);
945                 }
946         }
947         return best_index;
948 }
949
950 static int setup_root_or_create_block(struct btrfs_fs_info *fs_info,
951                                       unsigned flags,
952                                       struct btrfs_root *info_root,
953                                       u64 objectid, char *str)
954 {
955         struct btrfs_super_block *sb = fs_info->super_copy;
956         struct btrfs_root *root = fs_info->tree_root;
957         u32 nodesize = btrfs_super_nodesize(sb);
958         int ret;
959
960         ret = find_and_setup_root(root, fs_info, objectid, info_root);
961         if (ret) {
962                 printk("Couldn't setup %s tree\n", str);
963                 if (!(flags & OPEN_CTREE_PARTIAL))
964                         return -EIO;
965                 /*
966                  * Need a blank node here just so we don't screw up in the
967                  * million of places that assume a root has a valid ->node
968                  */
969                 info_root->node =
970                         btrfs_find_create_tree_block(fs_info, 0, nodesize);
971                 if (!info_root->node)
972                         return -ENOMEM;
973                 clear_extent_buffer_uptodate(info_root->node);
974         }
975
976         return 0;
977 }
978
979 int btrfs_setup_all_roots(struct btrfs_fs_info *fs_info, u64 root_tree_bytenr,
980                           unsigned flags)
981 {
982         struct btrfs_super_block *sb = fs_info->super_copy;
983         struct btrfs_root *root;
984         struct btrfs_key key;
985         u64 generation;
986         u32 blocksize;
987         int ret;
988
989         root = fs_info->tree_root;
990         btrfs_setup_root(root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
991         blocksize = fs_info->nodesize;
992         generation = btrfs_super_generation(sb);
993
994         if (!root_tree_bytenr && !(flags & OPEN_CTREE_BACKUP_ROOT)) {
995                 root_tree_bytenr = btrfs_super_root(sb);
996         } else if (flags & OPEN_CTREE_BACKUP_ROOT) {
997                 struct btrfs_root_backup *backup;
998                 int index = find_best_backup_root(sb);
999                 if (index >= BTRFS_NUM_BACKUP_ROOTS) {
1000                         fprintf(stderr, "Invalid backup root number\n");
1001                         return -EIO;
1002                 }
1003                 backup = fs_info->super_copy->super_roots + index;
1004                 root_tree_bytenr = btrfs_backup_tree_root(backup);
1005                 generation = btrfs_backup_tree_root_gen(backup);
1006         }
1007
1008         root->node = read_tree_block(fs_info, root_tree_bytenr, blocksize,
1009                                      generation);
1010         if (!extent_buffer_uptodate(root->node)) {
1011                 fprintf(stderr, "Couldn't read tree root\n");
1012                 return -EIO;
1013         }
1014
1015         ret = setup_root_or_create_block(fs_info, flags, fs_info->extent_root,
1016                                          BTRFS_EXTENT_TREE_OBJECTID, "extent");
1017         if (ret)
1018                 return ret;
1019         fs_info->extent_root->track_dirty = 1;
1020
1021         ret = find_and_setup_root(root, fs_info, BTRFS_DEV_TREE_OBJECTID,
1022                                   fs_info->dev_root);
1023         if (ret) {
1024                 printk("Couldn't setup device tree\n");
1025                 return -EIO;
1026         }
1027         fs_info->dev_root->track_dirty = 1;
1028
1029         ret = setup_root_or_create_block(fs_info, flags, fs_info->csum_root,
1030                                          BTRFS_CSUM_TREE_OBJECTID, "csum");
1031         if (ret)
1032                 return ret;
1033         fs_info->csum_root->track_dirty = 1;
1034
1035         ret = find_and_setup_root(root, fs_info, BTRFS_QUOTA_TREE_OBJECTID,
1036                                   fs_info->quota_root);
1037         if (ret) {
1038                 free(fs_info->quota_root);
1039                 fs_info->quota_root = NULL;
1040         } else {
1041                 fs_info->quota_enabled = 1;
1042         }
1043
1044         if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
1045                 ret = find_and_setup_root(root, fs_info, BTRFS_FREE_SPACE_TREE_OBJECTID,
1046                                           fs_info->free_space_root);
1047                 if (ret) {
1048                         printk("Couldn't read free space tree\n");
1049                         return -EIO;
1050                 }
1051                 fs_info->free_space_root->track_dirty = 1;
1052         }
1053
1054         ret = find_and_setup_log_root(root, fs_info, sb);
1055         if (ret) {
1056                 printk("Couldn't setup log root tree\n");
1057                 if (!(flags & OPEN_CTREE_PARTIAL))
1058                         return -EIO;
1059         }
1060
1061         fs_info->generation = generation;
1062         fs_info->last_trans_committed = generation;
1063         if (extent_buffer_uptodate(fs_info->extent_root->node) &&
1064             !(flags & OPEN_CTREE_NO_BLOCK_GROUPS))
1065                 btrfs_read_block_groups(fs_info->tree_root);
1066
1067         key.objectid = BTRFS_FS_TREE_OBJECTID;
1068         key.type = BTRFS_ROOT_ITEM_KEY;
1069         key.offset = (u64)-1;
1070         fs_info->fs_root = btrfs_read_fs_root(fs_info, &key);
1071
1072         if (IS_ERR(fs_info->fs_root))
1073                 return -EIO;
1074         return 0;
1075 }
1076
1077 void btrfs_release_all_roots(struct btrfs_fs_info *fs_info)
1078 {
1079         if (fs_info->free_space_root)
1080                 free_extent_buffer(fs_info->free_space_root->node);
1081         if (fs_info->quota_root)
1082                 free_extent_buffer(fs_info->quota_root->node);
1083         if (fs_info->csum_root)
1084                 free_extent_buffer(fs_info->csum_root->node);
1085         if (fs_info->dev_root)
1086                 free_extent_buffer(fs_info->dev_root->node);
1087         if (fs_info->extent_root)
1088                 free_extent_buffer(fs_info->extent_root->node);
1089         if (fs_info->tree_root)
1090                 free_extent_buffer(fs_info->tree_root->node);
1091         if (fs_info->log_root_tree)
1092                 free_extent_buffer(fs_info->log_root_tree->node);
1093         if (fs_info->chunk_root)
1094                 free_extent_buffer(fs_info->chunk_root->node);
1095 }
1096
1097 static void free_map_lookup(struct cache_extent *ce)
1098 {
1099         struct map_lookup *map;
1100
1101         map = container_of(ce, struct map_lookup, ce);
1102         kfree(map);
1103 }
1104
1105 FREE_EXTENT_CACHE_BASED_TREE(mapping_cache, free_map_lookup);
1106
1107 void btrfs_cleanup_all_caches(struct btrfs_fs_info *fs_info)
1108 {
1109         while (!list_empty(&fs_info->recow_ebs)) {
1110                 struct extent_buffer *eb;
1111                 eb = list_first_entry(&fs_info->recow_ebs,
1112                                       struct extent_buffer, recow);
1113                 list_del_init(&eb->recow);
1114                 free_extent_buffer(eb);
1115         }
1116         free_mapping_cache_tree(&fs_info->mapping_tree.cache_tree);
1117         extent_io_tree_cleanup(&fs_info->extent_cache);
1118         extent_io_tree_cleanup(&fs_info->free_space_cache);
1119         extent_io_tree_cleanup(&fs_info->block_group_cache);
1120         extent_io_tree_cleanup(&fs_info->pinned_extents);
1121         extent_io_tree_cleanup(&fs_info->pending_del);
1122         extent_io_tree_cleanup(&fs_info->extent_ins);
1123 }
1124
1125 int btrfs_scan_fs_devices(int fd, const char *path,
1126                           struct btrfs_fs_devices **fs_devices,
1127                           u64 sb_bytenr, unsigned sbflags,
1128                           int skip_devices)
1129 {
1130         u64 total_devs;
1131         u64 dev_size;
1132         off_t seek_ret;
1133         int ret;
1134         if (!sb_bytenr)
1135                 sb_bytenr = BTRFS_SUPER_INFO_OFFSET;
1136
1137         seek_ret = lseek(fd, 0, SEEK_END);
1138         if (seek_ret < 0)
1139                 return -errno;
1140
1141         dev_size = seek_ret;
1142         lseek(fd, 0, SEEK_SET);
1143         if (sb_bytenr > dev_size) {
1144                 error("superblock bytenr %llu is larger than device size %llu",
1145                                 (unsigned long long)sb_bytenr,
1146                                 (unsigned long long)dev_size);
1147                 return -EINVAL;
1148         }
1149
1150         ret = btrfs_scan_one_device(fd, path, fs_devices,
1151                                     &total_devs, sb_bytenr, sbflags);
1152         if (ret) {
1153                 fprintf(stderr, "No valid Btrfs found on %s\n", path);
1154                 return ret;
1155         }
1156
1157         if (!skip_devices && total_devs != 1) {
1158                 ret = btrfs_scan_devices();
1159                 if (ret)
1160                         return ret;
1161         }
1162         return 0;
1163 }
1164
1165 int btrfs_setup_chunk_tree_and_device_map(struct btrfs_fs_info *fs_info,
1166                                           u64 chunk_root_bytenr)
1167 {
1168         struct btrfs_super_block *sb = fs_info->super_copy;
1169         u64 generation;
1170         int ret;
1171
1172         btrfs_setup_root(fs_info->chunk_root, fs_info,
1173                         BTRFS_CHUNK_TREE_OBJECTID);
1174
1175         ret = btrfs_read_sys_array(fs_info->chunk_root);
1176         if (ret)
1177                 return ret;
1178
1179         generation = btrfs_super_chunk_root_generation(sb);
1180
1181         if (chunk_root_bytenr && !IS_ALIGNED(chunk_root_bytenr,
1182                                             fs_info->sectorsize)) {
1183                 warning("chunk_root_bytenr %llu is unaligned to %u, ignore it",
1184                         chunk_root_bytenr, fs_info->sectorsize);
1185                 chunk_root_bytenr = 0;
1186         }
1187
1188         if (!chunk_root_bytenr)
1189                 chunk_root_bytenr = btrfs_super_chunk_root(sb);
1190         else
1191                 generation = 0;
1192
1193         fs_info->chunk_root->node = read_tree_block(fs_info,
1194                                                     chunk_root_bytenr,
1195                                                     fs_info->nodesize,
1196                                                     generation);
1197         if (!extent_buffer_uptodate(fs_info->chunk_root->node)) {
1198                 if (fs_info->ignore_chunk_tree_error) {
1199                         warning("cannot read chunk root, continue anyway");
1200                         fs_info->chunk_root = NULL;
1201                         return 0;
1202                 } else {
1203                         error("cannot read chunk root");
1204                         return -EIO;
1205                 }
1206         }
1207
1208         if (!(btrfs_super_flags(sb) & BTRFS_SUPER_FLAG_METADUMP)) {
1209                 ret = btrfs_read_chunk_tree(fs_info->chunk_root);
1210                 if (ret) {
1211                         fprintf(stderr, "Couldn't read chunk tree\n");
1212                         return ret;
1213                 }
1214         }
1215         return 0;
1216 }
1217
1218 static struct btrfs_fs_info *__open_ctree_fd(int fp, const char *path,
1219                                              u64 sb_bytenr,
1220                                              u64 root_tree_bytenr,
1221                                              u64 chunk_root_bytenr,
1222                                              unsigned flags)
1223 {
1224         struct btrfs_fs_info *fs_info;
1225         struct btrfs_super_block *disk_super;
1226         struct btrfs_fs_devices *fs_devices = NULL;
1227         struct extent_buffer *eb;
1228         int ret;
1229         int oflags;
1230         unsigned sbflags = SBREAD_DEFAULT;
1231
1232         if (sb_bytenr == 0)
1233                 sb_bytenr = BTRFS_SUPER_INFO_OFFSET;
1234
1235         /* try to drop all the caches */
1236         if (posix_fadvise(fp, 0, 0, POSIX_FADV_DONTNEED))
1237                 fprintf(stderr, "Warning, could not drop caches\n");
1238
1239         fs_info = btrfs_new_fs_info(flags & OPEN_CTREE_WRITES, sb_bytenr);
1240         if (!fs_info) {
1241                 fprintf(stderr, "Failed to allocate memory for fs_info\n");
1242                 return NULL;
1243         }
1244         if (flags & OPEN_CTREE_RESTORE)
1245                 fs_info->on_restoring = 1;
1246         if (flags & OPEN_CTREE_SUPPRESS_CHECK_BLOCK_ERRORS)
1247                 fs_info->suppress_check_block_errors = 1;
1248         if (flags & OPEN_CTREE_IGNORE_FSID_MISMATCH)
1249                 fs_info->ignore_fsid_mismatch = 1;
1250         if (flags & OPEN_CTREE_IGNORE_CHUNK_TREE_ERROR)
1251                 fs_info->ignore_chunk_tree_error = 1;
1252
1253         if ((flags & OPEN_CTREE_RECOVER_SUPER)
1254              && (flags & OPEN_CTREE_FS_PARTIAL)) {
1255                 fprintf(stderr,
1256                     "cannot open a partially created filesystem for recovery");
1257                 goto out;
1258         }
1259
1260         if (flags & OPEN_CTREE_FS_PARTIAL)
1261                 sbflags = SBREAD_PARTIAL;
1262
1263         ret = btrfs_scan_fs_devices(fp, path, &fs_devices, sb_bytenr, sbflags,
1264                         (flags & OPEN_CTREE_NO_DEVICES));
1265         if (ret)
1266                 goto out;
1267
1268         fs_info->fs_devices = fs_devices;
1269         if (flags & OPEN_CTREE_WRITES)
1270                 oflags = O_RDWR;
1271         else
1272                 oflags = O_RDONLY;
1273
1274         if (flags & OPEN_CTREE_EXCLUSIVE)
1275                 oflags |= O_EXCL;
1276
1277         ret = btrfs_open_devices(fs_devices, oflags);
1278         if (ret)
1279                 goto out;
1280
1281         disk_super = fs_info->super_copy;
1282         if (flags & OPEN_CTREE_RECOVER_SUPER)
1283                 ret = btrfs_read_dev_super(fs_devices->latest_bdev, disk_super,
1284                                 sb_bytenr, SBREAD_RECOVER);
1285         else
1286                 ret = btrfs_read_dev_super(fp, disk_super, sb_bytenr,
1287                                 sbflags);
1288         if (ret) {
1289                 printk("No valid btrfs found\n");
1290                 goto out_devices;
1291         }
1292
1293         if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_CHANGING_FSID &&
1294             !fs_info->ignore_fsid_mismatch) {
1295                 fprintf(stderr, "ERROR: Filesystem UUID change in progress\n");
1296                 goto out_devices;
1297         }
1298
1299         memcpy(fs_info->fsid, &disk_super->fsid, BTRFS_FSID_SIZE);
1300         fs_info->sectorsize = btrfs_super_sectorsize(disk_super);
1301         fs_info->nodesize = btrfs_super_nodesize(disk_super);
1302         fs_info->stripesize = btrfs_super_stripesize(disk_super);
1303
1304         ret = btrfs_check_fs_compatibility(fs_info->super_copy, flags);
1305         if (ret)
1306                 goto out_devices;
1307
1308         ret = btrfs_setup_chunk_tree_and_device_map(fs_info, chunk_root_bytenr);
1309         if (ret)
1310                 goto out_chunk;
1311
1312         /* Chunk tree root is unable to read, return directly */
1313         if (!fs_info->chunk_root)
1314                 return fs_info;
1315
1316         eb = fs_info->chunk_root->node;
1317         read_extent_buffer(eb, fs_info->chunk_tree_uuid,
1318                            btrfs_header_chunk_tree_uuid(eb),
1319                            BTRFS_UUID_SIZE);
1320
1321         ret = btrfs_setup_all_roots(fs_info, root_tree_bytenr, flags);
1322         if (ret && !(flags & __OPEN_CTREE_RETURN_CHUNK_ROOT) &&
1323             !fs_info->ignore_chunk_tree_error)
1324                 goto out_chunk;
1325
1326         return fs_info;
1327
1328 out_chunk:
1329         btrfs_release_all_roots(fs_info);
1330         btrfs_cleanup_all_caches(fs_info);
1331 out_devices:
1332         btrfs_close_devices(fs_devices);
1333 out:
1334         btrfs_free_fs_info(fs_info);
1335         return NULL;
1336 }
1337
1338 struct btrfs_fs_info *open_ctree_fs_info(const char *filename,
1339                                          u64 sb_bytenr, u64 root_tree_bytenr,
1340                                          u64 chunk_root_bytenr,
1341                                          unsigned flags)
1342 {
1343         int fp;
1344         int ret;
1345         struct btrfs_fs_info *info;
1346         int oflags = O_RDWR;
1347         struct stat st;
1348
1349         ret = stat(filename, &st);
1350         if (ret < 0) {
1351                 error("cannot stat '%s': %s", filename, strerror(errno));
1352                 return NULL;
1353         }
1354         if (!(((st.st_mode & S_IFMT) == S_IFREG) || ((st.st_mode & S_IFMT) == S_IFBLK))) {
1355                 error("not a regular file or block device: %s", filename);
1356                 return NULL;
1357         }
1358
1359         if (!(flags & OPEN_CTREE_WRITES))
1360                 oflags = O_RDONLY;
1361
1362         fp = open(filename, oflags);
1363         if (fp < 0) {
1364                 error("cannot open '%s': %s", filename, strerror(errno));
1365                 return NULL;
1366         }
1367         info = __open_ctree_fd(fp, filename, sb_bytenr, root_tree_bytenr,
1368                                chunk_root_bytenr, flags);
1369         close(fp);
1370         return info;
1371 }
1372
1373 struct btrfs_root *open_ctree(const char *filename, u64 sb_bytenr,
1374                               unsigned flags)
1375 {
1376         struct btrfs_fs_info *info;
1377
1378         /* This flags may not return fs_info with any valid root */
1379         BUG_ON(flags & OPEN_CTREE_IGNORE_CHUNK_TREE_ERROR);
1380         info = open_ctree_fs_info(filename, sb_bytenr, 0, 0, flags);
1381         if (!info)
1382                 return NULL;
1383         if (flags & __OPEN_CTREE_RETURN_CHUNK_ROOT)
1384                 return info->chunk_root;
1385         return info->fs_root;
1386 }
1387
1388 struct btrfs_root *open_ctree_fd(int fp, const char *path, u64 sb_bytenr,
1389                                  unsigned flags)
1390 {
1391         struct btrfs_fs_info *info;
1392
1393         /* This flags may not return fs_info with any valid root */
1394         if (flags & OPEN_CTREE_IGNORE_CHUNK_TREE_ERROR) {
1395                 error("invalid open_ctree flags: 0x%llx",
1396                                 (unsigned long long)flags);
1397                 return NULL;
1398         }
1399         info = __open_ctree_fd(fp, path, sb_bytenr, 0, 0, flags);
1400         if (!info)
1401                 return NULL;
1402         if (flags & __OPEN_CTREE_RETURN_CHUNK_ROOT)
1403                 return info->chunk_root;
1404         return info->fs_root;
1405 }
1406
1407 /*
1408  * Check if the super is valid:
1409  * - nodesize/sectorsize - minimum, maximum, alignment
1410  * - tree block starts   - alignment
1411  * - number of devices   - something sane
1412  * - sys array size      - maximum
1413  */
1414 static int check_super(struct btrfs_super_block *sb, unsigned sbflags)
1415 {
1416         u8 result[BTRFS_CSUM_SIZE];
1417         u32 crc;
1418         u16 csum_type;
1419         int csum_size;
1420
1421         if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
1422                 if (btrfs_super_magic(sb) == BTRFS_MAGIC_PARTIAL) {
1423                         if (!(sbflags & SBREAD_PARTIAL)) {
1424                                 error("superblock magic doesn't match");
1425                                 return -EIO;
1426                         }
1427                 }
1428         }
1429
1430         csum_type = btrfs_super_csum_type(sb);
1431         if (csum_type >= ARRAY_SIZE(btrfs_csum_sizes)) {
1432                 error("unsupported checksum algorithm %u", csum_type);
1433                 return -EIO;
1434         }
1435         csum_size = btrfs_csum_sizes[csum_type];
1436
1437         crc = ~(u32)0;
1438         crc = btrfs_csum_data((char *)sb + BTRFS_CSUM_SIZE, crc,
1439                               BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
1440         btrfs_csum_final(crc, result);
1441
1442         if (memcmp(result, sb->csum, csum_size)) {
1443                 error("superblock checksum mismatch");
1444                 return -EIO;
1445         }
1446         if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
1447                 error("tree_root level too big: %d >= %d",
1448                         btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
1449                 goto error_out;
1450         }
1451         if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
1452                 error("chunk_root level too big: %d >= %d",
1453                         btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
1454                 goto error_out;
1455         }
1456         if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
1457                 error("log_root level too big: %d >= %d",
1458                         btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
1459                 goto error_out;
1460         }
1461
1462         if (!IS_ALIGNED(btrfs_super_root(sb), 4096)) {
1463                 error("tree_root block unaligned: %llu", btrfs_super_root(sb));
1464                 goto error_out;
1465         }
1466         if (!IS_ALIGNED(btrfs_super_chunk_root(sb), 4096)) {
1467                 error("chunk_root block unaligned: %llu",
1468                         btrfs_super_chunk_root(sb));
1469                 goto error_out;
1470         }
1471         if (!IS_ALIGNED(btrfs_super_log_root(sb), 4096)) {
1472                 error("log_root block unaligned: %llu",
1473                         btrfs_super_log_root(sb));
1474                 goto error_out;
1475         }
1476         if (btrfs_super_nodesize(sb) < 4096) {
1477                 error("nodesize too small: %u < 4096",
1478                         btrfs_super_nodesize(sb));
1479                 goto error_out;
1480         }
1481         if (!IS_ALIGNED(btrfs_super_nodesize(sb), 4096)) {
1482                 error("nodesize unaligned: %u", btrfs_super_nodesize(sb));
1483                 goto error_out;
1484         }
1485         if (btrfs_super_sectorsize(sb) < 4096) {
1486                 error("sectorsize too small: %u < 4096",
1487                         btrfs_super_sectorsize(sb));
1488                 goto error_out;
1489         }
1490         if (!IS_ALIGNED(btrfs_super_sectorsize(sb), 4096)) {
1491                 error("sectorsize unaligned: %u", btrfs_super_sectorsize(sb));
1492                 goto error_out;
1493         }
1494         if (btrfs_super_total_bytes(sb) == 0) {
1495                 error("invalid total_bytes 0");
1496                 goto error_out;
1497         }
1498         if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
1499                 error("invalid bytes_used %llu", btrfs_super_bytes_used(sb));
1500                 goto error_out;
1501         }
1502         if ((btrfs_super_stripesize(sb) != 4096)
1503                 && (btrfs_super_stripesize(sb) != btrfs_super_sectorsize(sb))) {
1504                 error("invalid stripesize %u", btrfs_super_stripesize(sb));
1505                 goto error_out;
1506         }
1507
1508         if (memcmp(sb->fsid, sb->dev_item.fsid, BTRFS_UUID_SIZE) != 0) {
1509                 char fsid[BTRFS_UUID_UNPARSED_SIZE];
1510                 char dev_fsid[BTRFS_UUID_UNPARSED_SIZE];
1511
1512                 uuid_unparse(sb->fsid, fsid);
1513                 uuid_unparse(sb->dev_item.fsid, dev_fsid);
1514                 error("dev_item UUID does not match fsid: %s != %s",
1515                         dev_fsid, fsid);
1516                 goto error_out;
1517         }
1518
1519         /*
1520          * Hint to catch really bogus numbers, bitflips or so
1521          */
1522         if (btrfs_super_num_devices(sb) > (1UL << 31)) {
1523                 warning("suspicious number of devices: %llu",
1524                         btrfs_super_num_devices(sb));
1525         }
1526
1527         if (btrfs_super_num_devices(sb) == 0) {
1528                 error("number of devices is 0");
1529                 goto error_out;
1530         }
1531
1532         /*
1533          * Obvious sys_chunk_array corruptions, it must hold at least one key
1534          * and one chunk
1535          */
1536         if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
1537                 error("system chunk array too big %u > %u",
1538                       btrfs_super_sys_array_size(sb),
1539                       BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
1540                 goto error_out;
1541         }
1542         if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
1543                         + sizeof(struct btrfs_chunk)) {
1544                 error("system chunk array too small %u < %zu",
1545                       btrfs_super_sys_array_size(sb),
1546                       sizeof(struct btrfs_disk_key) +
1547                       sizeof(struct btrfs_chunk));
1548                 goto error_out;
1549         }
1550
1551         return 0;
1552
1553 error_out:
1554         error("superblock checksum matches but it has invalid members");
1555         return -EIO;
1556 }
1557
1558 int btrfs_read_dev_super(int fd, struct btrfs_super_block *sb, u64 sb_bytenr,
1559                          unsigned sbflags)
1560 {
1561         u8 fsid[BTRFS_FSID_SIZE];
1562         int fsid_is_initialized = 0;
1563         char tmp[BTRFS_SUPER_INFO_SIZE];
1564         struct btrfs_super_block *buf = (struct btrfs_super_block *)tmp;
1565         int i;
1566         int ret;
1567         int max_super = sbflags & SBREAD_RECOVER ? BTRFS_SUPER_MIRROR_MAX : 1;
1568         u64 transid = 0;
1569         u64 bytenr;
1570
1571         if (sb_bytenr != BTRFS_SUPER_INFO_OFFSET) {
1572                 ret = pread64(fd, buf, BTRFS_SUPER_INFO_SIZE, sb_bytenr);
1573                 /* real error */
1574                 if (ret < 0)
1575                         return -errno;
1576
1577                 /* Not large enough sb, return -ENOENT instead of normal -EIO */
1578                 if (ret < BTRFS_SUPER_INFO_SIZE)
1579                         return -ENOENT;
1580
1581                 if (btrfs_super_bytenr(buf) != sb_bytenr)
1582                         return -EIO;
1583
1584                 ret = check_super(buf, sbflags);
1585                 if (ret < 0)
1586                         return ret;
1587                 memcpy(sb, buf, BTRFS_SUPER_INFO_SIZE);
1588                 return 0;
1589         }
1590
1591         /*
1592         * we would like to check all the supers, but that would make
1593         * a btrfs mount succeed after a mkfs from a different FS.
1594         * So, we need to add a special mount option to scan for
1595         * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1596         */
1597
1598         for (i = 0; i < max_super; i++) {
1599                 bytenr = btrfs_sb_offset(i);
1600                 ret = pread64(fd, buf, BTRFS_SUPER_INFO_SIZE, bytenr);
1601                 if (ret < BTRFS_SUPER_INFO_SIZE)
1602                         break;
1603
1604                 if (btrfs_super_bytenr(buf) != bytenr )
1605                         continue;
1606                 /* if magic is NULL, the device was removed */
1607                 if (btrfs_super_magic(buf) == 0 && i == 0)
1608                         break;
1609                 if (check_super(buf, sbflags))
1610                         continue;
1611
1612                 if (!fsid_is_initialized) {
1613                         memcpy(fsid, buf->fsid, sizeof(fsid));
1614                         fsid_is_initialized = 1;
1615                 } else if (memcmp(fsid, buf->fsid, sizeof(fsid))) {
1616                         /*
1617                          * the superblocks (the original one and
1618                          * its backups) contain data of different
1619                          * filesystems -> the super cannot be trusted
1620                          */
1621                         continue;
1622                 }
1623
1624                 if (btrfs_super_generation(buf) > transid) {
1625                         memcpy(sb, buf, BTRFS_SUPER_INFO_SIZE);
1626                         transid = btrfs_super_generation(buf);
1627                 }
1628         }
1629
1630         return transid > 0 ? 0 : -1;
1631 }
1632
1633 static int write_dev_supers(struct btrfs_root *root,
1634                             struct btrfs_super_block *sb,
1635                             struct btrfs_device *device)
1636 {
1637         u64 bytenr;
1638         u32 crc;
1639         int i, ret;
1640
1641         if (root->fs_info->super_bytenr != BTRFS_SUPER_INFO_OFFSET) {
1642                 btrfs_set_super_bytenr(sb, root->fs_info->super_bytenr);
1643                 crc = ~(u32)0;
1644                 crc = btrfs_csum_data((char *)sb + BTRFS_CSUM_SIZE, crc,
1645                                       BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
1646                 btrfs_csum_final(crc, &sb->csum[0]);
1647
1648                 /*
1649                  * super_copy is BTRFS_SUPER_INFO_SIZE bytes and is
1650                  * zero filled, we can use it directly
1651                  */
1652                 ret = pwrite64(device->fd, root->fs_info->super_copy,
1653                                 BTRFS_SUPER_INFO_SIZE,
1654                                 root->fs_info->super_bytenr);
1655                 if (ret != BTRFS_SUPER_INFO_SIZE)
1656                         goto write_err;
1657                 return 0;
1658         }
1659
1660         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1661                 bytenr = btrfs_sb_offset(i);
1662                 if (bytenr + BTRFS_SUPER_INFO_SIZE > device->total_bytes)
1663                         break;
1664
1665                 btrfs_set_super_bytenr(sb, bytenr);
1666
1667                 crc = ~(u32)0;
1668                 crc = btrfs_csum_data((char *)sb + BTRFS_CSUM_SIZE, crc,
1669                                       BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
1670                 btrfs_csum_final(crc, &sb->csum[0]);
1671
1672                 /*
1673                  * super_copy is BTRFS_SUPER_INFO_SIZE bytes and is
1674                  * zero filled, we can use it directly
1675                  */
1676                 ret = pwrite64(device->fd, root->fs_info->super_copy,
1677                                 BTRFS_SUPER_INFO_SIZE, bytenr);
1678                 if (ret != BTRFS_SUPER_INFO_SIZE)
1679                         goto write_err;
1680         }
1681
1682         return 0;
1683
1684 write_err:
1685         if (ret > 0)
1686                 fprintf(stderr, "WARNING: failed to write all sb data\n");
1687         else
1688                 fprintf(stderr, "WARNING: failed to write sb: %s\n",
1689                         strerror(errno));
1690         return ret;
1691 }
1692
1693 int write_all_supers(struct btrfs_root *root)
1694 {
1695         struct list_head *cur;
1696         struct list_head *head = &root->fs_info->fs_devices->devices;
1697         struct btrfs_device *dev;
1698         struct btrfs_super_block *sb;
1699         struct btrfs_dev_item *dev_item;
1700         int ret;
1701         u64 flags;
1702
1703         sb = root->fs_info->super_copy;
1704         dev_item = &sb->dev_item;
1705         list_for_each(cur, head) {
1706                 dev = list_entry(cur, struct btrfs_device, dev_list);
1707                 if (!dev->writeable)
1708                         continue;
1709
1710                 btrfs_set_stack_device_generation(dev_item, 0);
1711                 btrfs_set_stack_device_type(dev_item, dev->type);
1712                 btrfs_set_stack_device_id(dev_item, dev->devid);
1713                 btrfs_set_stack_device_total_bytes(dev_item, dev->total_bytes);
1714                 btrfs_set_stack_device_bytes_used(dev_item, dev->bytes_used);
1715                 btrfs_set_stack_device_io_align(dev_item, dev->io_align);
1716                 btrfs_set_stack_device_io_width(dev_item, dev->io_width);
1717                 btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
1718                 memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
1719                 memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_UUID_SIZE);
1720
1721                 flags = btrfs_super_flags(sb);
1722                 btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
1723
1724                 ret = write_dev_supers(root, sb, dev);
1725                 BUG_ON(ret);
1726         }
1727         return 0;
1728 }
1729
1730 int write_ctree_super(struct btrfs_trans_handle *trans,
1731                       struct btrfs_root *root)
1732 {
1733         int ret;
1734         struct btrfs_root *tree_root = root->fs_info->tree_root;
1735         struct btrfs_root *chunk_root = root->fs_info->chunk_root;
1736
1737         if (root->fs_info->readonly)
1738                 return 0;
1739
1740         btrfs_set_super_generation(root->fs_info->super_copy,
1741                                    trans->transid);
1742         btrfs_set_super_root(root->fs_info->super_copy,
1743                              tree_root->node->start);
1744         btrfs_set_super_root_level(root->fs_info->super_copy,
1745                                    btrfs_header_level(tree_root->node));
1746         btrfs_set_super_chunk_root(root->fs_info->super_copy,
1747                                    chunk_root->node->start);
1748         btrfs_set_super_chunk_root_level(root->fs_info->super_copy,
1749                                          btrfs_header_level(chunk_root->node));
1750         btrfs_set_super_chunk_root_generation(root->fs_info->super_copy,
1751                                 btrfs_header_generation(chunk_root->node));
1752
1753         ret = write_all_supers(root);
1754         if (ret)
1755                 fprintf(stderr, "failed to write new super block err %d\n", ret);
1756         return ret;
1757 }
1758
1759 int close_ctree_fs_info(struct btrfs_fs_info *fs_info)
1760 {
1761         int ret;
1762         struct btrfs_trans_handle *trans;
1763         struct btrfs_root *root = fs_info->tree_root;
1764
1765         if (fs_info->last_trans_committed !=
1766             fs_info->generation) {
1767                 BUG_ON(!root);
1768                 trans = btrfs_start_transaction(root, 1);
1769                 btrfs_commit_transaction(trans, root);
1770                 trans = btrfs_start_transaction(root, 1);
1771                 ret = commit_tree_roots(trans, fs_info);
1772                 BUG_ON(ret);
1773                 ret = __commit_transaction(trans, root);
1774                 BUG_ON(ret);
1775                 write_ctree_super(trans, root);
1776                 kfree(trans);
1777         }
1778
1779         if (fs_info->finalize_on_close) {
1780                 btrfs_set_super_magic(fs_info->super_copy, BTRFS_MAGIC);
1781                 root->fs_info->finalize_on_close = 0;
1782                 ret = write_all_supers(root);
1783                 if (ret)
1784                         fprintf(stderr,
1785                                 "failed to write new super block err %d\n", ret);
1786         }
1787         btrfs_free_block_groups(fs_info);
1788
1789         free_fs_roots_tree(&fs_info->fs_root_tree);
1790
1791         btrfs_release_all_roots(fs_info);
1792         ret = btrfs_close_devices(fs_info->fs_devices);
1793         btrfs_cleanup_all_caches(fs_info);
1794         btrfs_free_fs_info(fs_info);
1795         return ret;
1796 }
1797
1798 int clean_tree_block(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1799                      struct extent_buffer *eb)
1800 {
1801         return clear_extent_buffer_dirty(eb);
1802 }
1803
1804 void btrfs_mark_buffer_dirty(struct extent_buffer *eb)
1805 {
1806         set_extent_buffer_dirty(eb);
1807 }
1808
1809 int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid)
1810 {
1811         int ret;
1812
1813         ret = extent_buffer_uptodate(buf);
1814         if (!ret)
1815                 return ret;
1816
1817         ret = verify_parent_transid(buf->tree, buf, parent_transid, 1);
1818         return !ret;
1819 }
1820
1821 int btrfs_set_buffer_uptodate(struct extent_buffer *eb)
1822 {
1823         return set_extent_buffer_uptodate(eb);
1824 }