btrfs-progs: drop blocksize from read_tree_block
[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_fs_info *fs_info,
178                                             u64 bytenr, u32 blocksize)
179 {
180         return find_extent_buffer(&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_fs_info *fs_info, u64 bytenr,
191                           u32 blocksize, 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(fs_info, bytenr, blocksize);
199         if (!(eb && btrfs_buffer_uptodate(eb, parent_transid)) &&
200             !btrfs_map_block(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(struct btrfs_fs_info *fs_info, u64 bytenr,
303                 u64 parent_transid)
304 {
305         int ret;
306         struct extent_buffer *eb;
307         u64 best_transid = 0;
308         u32 sectorsize = fs_info->sectorsize;
309         u32 nodesize = fs_info->nodesize;
310         u32 blocksize = 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_fs_info *fs_info, char *data, u64 logical,
388                      u64 *len, int mirror)
389 {
390         u64 offset = 0;
391         struct btrfs_multi_bio *multi = NULL;
392         struct btrfs_device *device;
393         int ret = 0;
394         u64 max_len = *len;
395
396         ret = btrfs_map_block(fs_info, READ, logical, len, &multi, mirror,
397                               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_fs_info *fs_info, 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(fs_info, WRITE, eb->start, &length,
431                               &multi, 0, &raid_map);
432
433         if (raid_map) {
434                 ret = write_raid56_with_parity(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_fs_info *fs_info,
453                      struct extent_buffer *eb)
454 {
455         if (check_tree_block(fs_info, eb)) {
456                 print_tree_block_error(fs_info, eb,
457                                 check_tree_block(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(fs_info, eb, 0);
466
467         return write_and_map_eb(fs_info, 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 btrfs_fs_info *fs_info = root->fs_info;
552         struct extent_buffer *eb;
553         struct extent_io_tree *tree = &fs_info->extent_cache;
554         int ret;
555
556         while(1) {
557                 ret = find_first_extent_bit(tree, 0, &start, &end,
558                                             EXTENT_DIRTY);
559                 if (ret)
560                         break;
561                 while(start <= end) {
562                         eb = find_first_extent_buffer(tree, start);
563                         BUG_ON(!eb || eb->start != start);
564                         ret = write_tree_block(trans, fs_info, eb);
565                         BUG_ON(ret);
566                         start += eb->len;
567                         clear_extent_buffer_dirty(eb);
568                         free_extent_buffer(eb);
569                 }
570         }
571         return 0;
572 }
573
574 int btrfs_commit_transaction(struct btrfs_trans_handle *trans,
575                              struct btrfs_root *root)
576 {
577         u64 transid = trans->transid;
578         int ret = 0;
579         struct btrfs_fs_info *fs_info = root->fs_info;
580
581         if (root->commit_root == root->node)
582                 goto commit_tree;
583         if (root == root->fs_info->tree_root)
584                 goto commit_tree;
585         if (root == root->fs_info->chunk_root)
586                 goto commit_tree;
587
588         free_extent_buffer(root->commit_root);
589         root->commit_root = NULL;
590
591         btrfs_set_root_bytenr(&root->root_item, root->node->start);
592         btrfs_set_root_generation(&root->root_item, trans->transid);
593         root->root_item.level = btrfs_header_level(root->node);
594         ret = btrfs_update_root(trans, root->fs_info->tree_root,
595                                 &root->root_key, &root->root_item);
596         BUG_ON(ret);
597 commit_tree:
598         ret = commit_tree_roots(trans, fs_info);
599         BUG_ON(ret);
600         ret = __commit_transaction(trans, root);
601         BUG_ON(ret);
602         write_ctree_super(trans, fs_info);
603         btrfs_finish_extent_commit(trans, fs_info->extent_root,
604                                    &fs_info->pinned_extents);
605         kfree(trans);
606         free_extent_buffer(root->commit_root);
607         root->commit_root = NULL;
608         fs_info->running_transaction = NULL;
609         fs_info->last_trans_committed = transid;
610         return 0;
611 }
612
613 static int find_and_setup_root(struct btrfs_root *tree_root,
614                                struct btrfs_fs_info *fs_info,
615                                u64 objectid, struct btrfs_root *root)
616 {
617         int ret;
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         generation = btrfs_root_generation(&root->root_item);
627         root->node = read_tree_block(fs_info,
628                         btrfs_root_bytenr(&root->root_item), generation);
629         if (!extent_buffer_uptodate(root->node))
630                 return -EIO;
631
632         return 0;
633 }
634
635 static int find_and_setup_log_root(struct btrfs_root *tree_root,
636                                struct btrfs_fs_info *fs_info,
637                                struct btrfs_super_block *disk_super)
638 {
639         u64 blocknr = btrfs_super_log_root(disk_super);
640         struct btrfs_root *log_root = malloc(sizeof(struct btrfs_root));
641
642         if (!log_root)
643                 return -ENOMEM;
644
645         if (blocknr == 0) {
646                 free(log_root);
647                 return 0;
648         }
649
650         btrfs_setup_root(log_root, fs_info,
651                          BTRFS_TREE_LOG_OBJECTID);
652
653         log_root->node = read_tree_block(fs_info, blocknr,
654                                      btrfs_super_generation(disk_super) + 1);
655
656         fs_info->log_root_tree = log_root;
657
658         if (!extent_buffer_uptodate(log_root->node)) {
659                 free_extent_buffer(log_root->node);
660                 free(log_root);
661                 fs_info->log_root_tree = NULL;
662                 return -EIO;
663         }
664
665         return 0;
666 }
667
668 int btrfs_free_fs_root(struct btrfs_root *root)
669 {
670         if (root->node)
671                 free_extent_buffer(root->node);
672         if (root->commit_root)
673                 free_extent_buffer(root->commit_root);
674         kfree(root);
675         return 0;
676 }
677
678 static void __free_fs_root(struct rb_node *node)
679 {
680         struct btrfs_root *root;
681
682         root = container_of(node, struct btrfs_root, rb_node);
683         btrfs_free_fs_root(root);
684 }
685
686 FREE_RB_BASED_TREE(fs_roots, __free_fs_root);
687
688 struct btrfs_root *btrfs_read_fs_root_no_cache(struct btrfs_fs_info *fs_info,
689                                                struct btrfs_key *location)
690 {
691         struct btrfs_root *root;
692         struct btrfs_root *tree_root = fs_info->tree_root;
693         struct btrfs_path *path;
694         struct extent_buffer *l;
695         u64 generation;
696         int ret = 0;
697
698         root = calloc(1, sizeof(*root));
699         if (!root)
700                 return ERR_PTR(-ENOMEM);
701         if (location->offset == (u64)-1) {
702                 ret = find_and_setup_root(tree_root, fs_info,
703                                           location->objectid, root);
704                 if (ret) {
705                         free(root);
706                         return ERR_PTR(ret);
707                 }
708                 goto insert;
709         }
710
711         btrfs_setup_root(root, fs_info,
712                          location->objectid);
713
714         path = btrfs_alloc_path();
715         if (!path) {
716                 free(root);
717                 return ERR_PTR(-ENOMEM);
718         }
719
720         ret = btrfs_search_slot(NULL, tree_root, location, path, 0, 0);
721         if (ret != 0) {
722                 if (ret > 0)
723                         ret = -ENOENT;
724                 goto out;
725         }
726         l = path->nodes[0];
727         read_extent_buffer(l, &root->root_item,
728                btrfs_item_ptr_offset(l, path->slots[0]),
729                sizeof(root->root_item));
730         memcpy(&root->root_key, location, sizeof(*location));
731         ret = 0;
732 out:
733         btrfs_free_path(path);
734         if (ret) {
735                 free(root);
736                 return ERR_PTR(ret);
737         }
738         generation = btrfs_root_generation(&root->root_item);
739         root->node = read_tree_block(fs_info,
740                         btrfs_root_bytenr(&root->root_item), generation);
741         if (!extent_buffer_uptodate(root->node)) {
742                 free(root);
743                 return ERR_PTR(-EIO);
744         }
745 insert:
746         root->ref_cows = 1;
747         return root;
748 }
749
750 static int btrfs_fs_roots_compare_objectids(struct rb_node *node,
751                                             void *data)
752 {
753         u64 objectid = *((u64 *)data);
754         struct btrfs_root *root;
755
756         root = rb_entry(node, struct btrfs_root, rb_node);
757         if (objectid > root->objectid)
758                 return 1;
759         else if (objectid < root->objectid)
760                 return -1;
761         else
762                 return 0;
763 }
764
765 static int btrfs_fs_roots_compare_roots(struct rb_node *node1,
766                                         struct rb_node *node2)
767 {
768         struct btrfs_root *root;
769
770         root = rb_entry(node2, struct btrfs_root, rb_node);
771         return btrfs_fs_roots_compare_objectids(node1, (void *)&root->objectid);
772 }
773
774 struct btrfs_root *btrfs_read_fs_root(struct btrfs_fs_info *fs_info,
775                                       struct btrfs_key *location)
776 {
777         struct btrfs_root *root;
778         struct rb_node *node;
779         int ret;
780         u64 objectid = location->objectid;
781
782         if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
783                 return fs_info->tree_root;
784         if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
785                 return fs_info->extent_root;
786         if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
787                 return fs_info->chunk_root;
788         if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
789                 return fs_info->dev_root;
790         if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
791                 return fs_info->csum_root;
792         if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
793                 return fs_info->quota_enabled ? fs_info->quota_root :
794                                 ERR_PTR(-ENOENT);
795
796         BUG_ON(location->objectid == BTRFS_TREE_RELOC_OBJECTID ||
797                location->offset != (u64)-1);
798
799         node = rb_search(&fs_info->fs_root_tree, (void *)&objectid,
800                          btrfs_fs_roots_compare_objectids, NULL);
801         if (node)
802                 return container_of(node, struct btrfs_root, rb_node);
803
804         root = btrfs_read_fs_root_no_cache(fs_info, location);
805         if (IS_ERR(root))
806                 return root;
807
808         ret = rb_insert(&fs_info->fs_root_tree, &root->rb_node,
809                         btrfs_fs_roots_compare_roots);
810         BUG_ON(ret);
811         return root;
812 }
813
814 void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
815 {
816         if (fs_info->quota_root)
817                 free(fs_info->quota_root);
818
819         free(fs_info->tree_root);
820         free(fs_info->extent_root);
821         free(fs_info->chunk_root);
822         free(fs_info->dev_root);
823         free(fs_info->csum_root);
824         free(fs_info->free_space_root);
825         free(fs_info->super_copy);
826         free(fs_info->log_root_tree);
827         free(fs_info);
828 }
829
830 struct btrfs_fs_info *btrfs_new_fs_info(int writable, u64 sb_bytenr)
831 {
832         struct btrfs_fs_info *fs_info;
833
834         fs_info = calloc(1, sizeof(struct btrfs_fs_info));
835         if (!fs_info)
836                 return NULL;
837
838         fs_info->tree_root = calloc(1, sizeof(struct btrfs_root));
839         fs_info->extent_root = calloc(1, sizeof(struct btrfs_root));
840         fs_info->chunk_root = calloc(1, sizeof(struct btrfs_root));
841         fs_info->dev_root = calloc(1, sizeof(struct btrfs_root));
842         fs_info->csum_root = calloc(1, sizeof(struct btrfs_root));
843         fs_info->quota_root = calloc(1, sizeof(struct btrfs_root));
844         fs_info->free_space_root = calloc(1, sizeof(struct btrfs_root));
845         fs_info->super_copy = calloc(1, BTRFS_SUPER_INFO_SIZE);
846
847         if (!fs_info->tree_root || !fs_info->extent_root ||
848             !fs_info->chunk_root || !fs_info->dev_root ||
849             !fs_info->csum_root || !fs_info->quota_root ||
850             !fs_info->free_space_root || !fs_info->super_copy)
851                 goto free_all;
852
853         extent_io_tree_init(&fs_info->extent_cache);
854         extent_io_tree_init(&fs_info->free_space_cache);
855         extent_io_tree_init(&fs_info->block_group_cache);
856         extent_io_tree_init(&fs_info->pinned_extents);
857         extent_io_tree_init(&fs_info->pending_del);
858         extent_io_tree_init(&fs_info->extent_ins);
859         fs_info->excluded_extents = NULL;
860
861         fs_info->fs_root_tree = RB_ROOT;
862         cache_tree_init(&fs_info->mapping_tree.cache_tree);
863
864         mutex_init(&fs_info->fs_mutex);
865         INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
866         INIT_LIST_HEAD(&fs_info->space_info);
867         INIT_LIST_HEAD(&fs_info->recow_ebs);
868
869         if (!writable)
870                 fs_info->readonly = 1;
871
872         fs_info->super_bytenr = sb_bytenr;
873         fs_info->data_alloc_profile = (u64)-1;
874         fs_info->metadata_alloc_profile = (u64)-1;
875         fs_info->system_alloc_profile = fs_info->metadata_alloc_profile;
876         return fs_info;
877 free_all:
878         btrfs_free_fs_info(fs_info);
879         return NULL;
880 }
881
882 int btrfs_check_fs_compatibility(struct btrfs_super_block *sb,
883                                  unsigned int flags)
884 {
885         u64 features;
886
887         features = btrfs_super_incompat_flags(sb) &
888                    ~BTRFS_FEATURE_INCOMPAT_SUPP;
889         if (features) {
890                 printk("couldn't open because of unsupported "
891                        "option features (%Lx).\n",
892                        (unsigned long long)features);
893                 return -ENOTSUP;
894         }
895
896         features = btrfs_super_incompat_flags(sb);
897         if (!(features & BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF)) {
898                 features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
899                 btrfs_set_super_incompat_flags(sb, features);
900         }
901
902         features = btrfs_super_compat_ro_flags(sb);
903         if (flags & OPEN_CTREE_WRITES) {
904                 if (flags & OPEN_CTREE_INVALIDATE_FST) {
905                         /* Clear the FREE_SPACE_TREE_VALID bit on disk... */
906                         features &= ~BTRFS_FEATURE_COMPAT_RO_FREE_SPACE_TREE_VALID;
907                         btrfs_set_super_compat_ro_flags(sb, features);
908                         /* ... and ignore the free space tree bit. */
909                         features &= ~BTRFS_FEATURE_COMPAT_RO_FREE_SPACE_TREE;
910                 }
911                 if (features & ~BTRFS_FEATURE_COMPAT_RO_SUPP) {
912                         printk("couldn't open RDWR because of unsupported "
913                                "option features (%Lx).\n",
914                                (unsigned long long)features);
915                         return -ENOTSUP;
916                 }
917
918         }
919         return 0;
920 }
921
922 static int find_best_backup_root(struct btrfs_super_block *super)
923 {
924         struct btrfs_root_backup *backup;
925         u64 orig_gen = btrfs_super_generation(super);
926         u64 gen = 0;
927         int best_index = 0;
928         int i;
929
930         for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
931                 backup = super->super_roots + i;
932                 if (btrfs_backup_tree_root_gen(backup) != orig_gen &&
933                     btrfs_backup_tree_root_gen(backup) > gen) {
934                         best_index = i;
935                         gen = btrfs_backup_tree_root_gen(backup);
936                 }
937         }
938         return best_index;
939 }
940
941 static int setup_root_or_create_block(struct btrfs_fs_info *fs_info,
942                                       unsigned flags,
943                                       struct btrfs_root *info_root,
944                                       u64 objectid, char *str)
945 {
946         struct btrfs_super_block *sb = fs_info->super_copy;
947         struct btrfs_root *root = fs_info->tree_root;
948         u32 nodesize = btrfs_super_nodesize(sb);
949         int ret;
950
951         ret = find_and_setup_root(root, fs_info, objectid, info_root);
952         if (ret) {
953                 printk("Couldn't setup %s tree\n", str);
954                 if (!(flags & OPEN_CTREE_PARTIAL))
955                         return -EIO;
956                 /*
957                  * Need a blank node here just so we don't screw up in the
958                  * million of places that assume a root has a valid ->node
959                  */
960                 info_root->node =
961                         btrfs_find_create_tree_block(fs_info, 0, nodesize);
962                 if (!info_root->node)
963                         return -ENOMEM;
964                 clear_extent_buffer_uptodate(info_root->node);
965         }
966
967         return 0;
968 }
969
970 int btrfs_setup_all_roots(struct btrfs_fs_info *fs_info, u64 root_tree_bytenr,
971                           unsigned flags)
972 {
973         struct btrfs_super_block *sb = fs_info->super_copy;
974         struct btrfs_root *root;
975         struct btrfs_key key;
976         u64 generation;
977         int ret;
978
979         root = fs_info->tree_root;
980         btrfs_setup_root(root, fs_info, BTRFS_ROOT_TREE_OBJECTID);
981         generation = btrfs_super_generation(sb);
982
983         if (!root_tree_bytenr && !(flags & OPEN_CTREE_BACKUP_ROOT)) {
984                 root_tree_bytenr = btrfs_super_root(sb);
985         } else if (flags & OPEN_CTREE_BACKUP_ROOT) {
986                 struct btrfs_root_backup *backup;
987                 int index = find_best_backup_root(sb);
988                 if (index >= BTRFS_NUM_BACKUP_ROOTS) {
989                         fprintf(stderr, "Invalid backup root number\n");
990                         return -EIO;
991                 }
992                 backup = fs_info->super_copy->super_roots + index;
993                 root_tree_bytenr = btrfs_backup_tree_root(backup);
994                 generation = btrfs_backup_tree_root_gen(backup);
995         }
996
997         root->node = read_tree_block(fs_info, root_tree_bytenr, generation);
998         if (!extent_buffer_uptodate(root->node)) {
999                 fprintf(stderr, "Couldn't read tree root\n");
1000                 return -EIO;
1001         }
1002
1003         ret = setup_root_or_create_block(fs_info, flags, fs_info->extent_root,
1004                                          BTRFS_EXTENT_TREE_OBJECTID, "extent");
1005         if (ret)
1006                 return ret;
1007         fs_info->extent_root->track_dirty = 1;
1008
1009         ret = find_and_setup_root(root, fs_info, BTRFS_DEV_TREE_OBJECTID,
1010                                   fs_info->dev_root);
1011         if (ret) {
1012                 printk("Couldn't setup device tree\n");
1013                 return -EIO;
1014         }
1015         fs_info->dev_root->track_dirty = 1;
1016
1017         ret = setup_root_or_create_block(fs_info, flags, fs_info->csum_root,
1018                                          BTRFS_CSUM_TREE_OBJECTID, "csum");
1019         if (ret)
1020                 return ret;
1021         fs_info->csum_root->track_dirty = 1;
1022
1023         ret = find_and_setup_root(root, fs_info, BTRFS_QUOTA_TREE_OBJECTID,
1024                                   fs_info->quota_root);
1025         if (ret) {
1026                 free(fs_info->quota_root);
1027                 fs_info->quota_root = NULL;
1028         } else {
1029                 fs_info->quota_enabled = 1;
1030         }
1031
1032         if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
1033                 ret = find_and_setup_root(root, fs_info, BTRFS_FREE_SPACE_TREE_OBJECTID,
1034                                           fs_info->free_space_root);
1035                 if (ret) {
1036                         printk("Couldn't read free space tree\n");
1037                         return -EIO;
1038                 }
1039                 fs_info->free_space_root->track_dirty = 1;
1040         }
1041
1042         ret = find_and_setup_log_root(root, fs_info, sb);
1043         if (ret) {
1044                 printk("Couldn't setup log root tree\n");
1045                 if (!(flags & OPEN_CTREE_PARTIAL))
1046                         return -EIO;
1047         }
1048
1049         fs_info->generation = generation;
1050         fs_info->last_trans_committed = generation;
1051         if (extent_buffer_uptodate(fs_info->extent_root->node) &&
1052             !(flags & OPEN_CTREE_NO_BLOCK_GROUPS))
1053                 btrfs_read_block_groups(fs_info->tree_root);
1054
1055         key.objectid = BTRFS_FS_TREE_OBJECTID;
1056         key.type = BTRFS_ROOT_ITEM_KEY;
1057         key.offset = (u64)-1;
1058         fs_info->fs_root = btrfs_read_fs_root(fs_info, &key);
1059
1060         if (IS_ERR(fs_info->fs_root))
1061                 return -EIO;
1062         return 0;
1063 }
1064
1065 void btrfs_release_all_roots(struct btrfs_fs_info *fs_info)
1066 {
1067         if (fs_info->free_space_root)
1068                 free_extent_buffer(fs_info->free_space_root->node);
1069         if (fs_info->quota_root)
1070                 free_extent_buffer(fs_info->quota_root->node);
1071         if (fs_info->csum_root)
1072                 free_extent_buffer(fs_info->csum_root->node);
1073         if (fs_info->dev_root)
1074                 free_extent_buffer(fs_info->dev_root->node);
1075         if (fs_info->extent_root)
1076                 free_extent_buffer(fs_info->extent_root->node);
1077         if (fs_info->tree_root)
1078                 free_extent_buffer(fs_info->tree_root->node);
1079         if (fs_info->log_root_tree)
1080                 free_extent_buffer(fs_info->log_root_tree->node);
1081         if (fs_info->chunk_root)
1082                 free_extent_buffer(fs_info->chunk_root->node);
1083 }
1084
1085 static void free_map_lookup(struct cache_extent *ce)
1086 {
1087         struct map_lookup *map;
1088
1089         map = container_of(ce, struct map_lookup, ce);
1090         kfree(map);
1091 }
1092
1093 FREE_EXTENT_CACHE_BASED_TREE(mapping_cache, free_map_lookup);
1094
1095 void btrfs_cleanup_all_caches(struct btrfs_fs_info *fs_info)
1096 {
1097         while (!list_empty(&fs_info->recow_ebs)) {
1098                 struct extent_buffer *eb;
1099                 eb = list_first_entry(&fs_info->recow_ebs,
1100                                       struct extent_buffer, recow);
1101                 list_del_init(&eb->recow);
1102                 free_extent_buffer(eb);
1103         }
1104         free_mapping_cache_tree(&fs_info->mapping_tree.cache_tree);
1105         extent_io_tree_cleanup(&fs_info->extent_cache);
1106         extent_io_tree_cleanup(&fs_info->free_space_cache);
1107         extent_io_tree_cleanup(&fs_info->block_group_cache);
1108         extent_io_tree_cleanup(&fs_info->pinned_extents);
1109         extent_io_tree_cleanup(&fs_info->pending_del);
1110         extent_io_tree_cleanup(&fs_info->extent_ins);
1111 }
1112
1113 int btrfs_scan_fs_devices(int fd, const char *path,
1114                           struct btrfs_fs_devices **fs_devices,
1115                           u64 sb_bytenr, unsigned sbflags,
1116                           int skip_devices)
1117 {
1118         u64 total_devs;
1119         u64 dev_size;
1120         off_t seek_ret;
1121         int ret;
1122         if (!sb_bytenr)
1123                 sb_bytenr = BTRFS_SUPER_INFO_OFFSET;
1124
1125         seek_ret = lseek(fd, 0, SEEK_END);
1126         if (seek_ret < 0)
1127                 return -errno;
1128
1129         dev_size = seek_ret;
1130         lseek(fd, 0, SEEK_SET);
1131         if (sb_bytenr > dev_size) {
1132                 error("superblock bytenr %llu is larger than device size %llu",
1133                                 (unsigned long long)sb_bytenr,
1134                                 (unsigned long long)dev_size);
1135                 return -EINVAL;
1136         }
1137
1138         ret = btrfs_scan_one_device(fd, path, fs_devices,
1139                                     &total_devs, sb_bytenr, sbflags);
1140         if (ret) {
1141                 fprintf(stderr, "No valid Btrfs found on %s\n", path);
1142                 return ret;
1143         }
1144
1145         if (!skip_devices && total_devs != 1) {
1146                 ret = btrfs_scan_devices();
1147                 if (ret)
1148                         return ret;
1149         }
1150         return 0;
1151 }
1152
1153 int btrfs_setup_chunk_tree_and_device_map(struct btrfs_fs_info *fs_info,
1154                                           u64 chunk_root_bytenr)
1155 {
1156         struct btrfs_super_block *sb = fs_info->super_copy;
1157         u64 generation;
1158         int ret;
1159
1160         btrfs_setup_root(fs_info->chunk_root, fs_info,
1161                         BTRFS_CHUNK_TREE_OBJECTID);
1162
1163         ret = btrfs_read_sys_array(fs_info);
1164         if (ret)
1165                 return ret;
1166
1167         generation = btrfs_super_chunk_root_generation(sb);
1168
1169         if (chunk_root_bytenr && !IS_ALIGNED(chunk_root_bytenr,
1170                                             fs_info->sectorsize)) {
1171                 warning("chunk_root_bytenr %llu is unaligned to %u, ignore it",
1172                         chunk_root_bytenr, fs_info->sectorsize);
1173                 chunk_root_bytenr = 0;
1174         }
1175
1176         if (!chunk_root_bytenr)
1177                 chunk_root_bytenr = btrfs_super_chunk_root(sb);
1178         else
1179                 generation = 0;
1180
1181         fs_info->chunk_root->node = read_tree_block(fs_info,
1182                                                     chunk_root_bytenr,
1183                                                     generation);
1184         if (!extent_buffer_uptodate(fs_info->chunk_root->node)) {
1185                 if (fs_info->ignore_chunk_tree_error) {
1186                         warning("cannot read chunk root, continue anyway");
1187                         fs_info->chunk_root = NULL;
1188                         return 0;
1189                 } else {
1190                         error("cannot read chunk root");
1191                         return -EIO;
1192                 }
1193         }
1194
1195         if (!(btrfs_super_flags(sb) & BTRFS_SUPER_FLAG_METADUMP)) {
1196                 ret = btrfs_read_chunk_tree(fs_info);
1197                 if (ret) {
1198                         fprintf(stderr, "Couldn't read chunk tree\n");
1199                         return ret;
1200                 }
1201         }
1202         return 0;
1203 }
1204
1205 static struct btrfs_fs_info *__open_ctree_fd(int fp, const char *path,
1206                                              u64 sb_bytenr,
1207                                              u64 root_tree_bytenr,
1208                                              u64 chunk_root_bytenr,
1209                                              unsigned flags)
1210 {
1211         struct btrfs_fs_info *fs_info;
1212         struct btrfs_super_block *disk_super;
1213         struct btrfs_fs_devices *fs_devices = NULL;
1214         struct extent_buffer *eb;
1215         int ret;
1216         int oflags;
1217         unsigned sbflags = SBREAD_DEFAULT;
1218
1219         if (sb_bytenr == 0)
1220                 sb_bytenr = BTRFS_SUPER_INFO_OFFSET;
1221
1222         /* try to drop all the caches */
1223         if (posix_fadvise(fp, 0, 0, POSIX_FADV_DONTNEED))
1224                 fprintf(stderr, "Warning, could not drop caches\n");
1225
1226         fs_info = btrfs_new_fs_info(flags & OPEN_CTREE_WRITES, sb_bytenr);
1227         if (!fs_info) {
1228                 fprintf(stderr, "Failed to allocate memory for fs_info\n");
1229                 return NULL;
1230         }
1231         if (flags & OPEN_CTREE_RESTORE)
1232                 fs_info->on_restoring = 1;
1233         if (flags & OPEN_CTREE_SUPPRESS_CHECK_BLOCK_ERRORS)
1234                 fs_info->suppress_check_block_errors = 1;
1235         if (flags & OPEN_CTREE_IGNORE_FSID_MISMATCH)
1236                 fs_info->ignore_fsid_mismatch = 1;
1237         if (flags & OPEN_CTREE_IGNORE_CHUNK_TREE_ERROR)
1238                 fs_info->ignore_chunk_tree_error = 1;
1239
1240         if ((flags & OPEN_CTREE_RECOVER_SUPER)
1241              && (flags & OPEN_CTREE_FS_PARTIAL)) {
1242                 fprintf(stderr,
1243                     "cannot open a partially created filesystem for recovery");
1244                 goto out;
1245         }
1246
1247         if (flags & OPEN_CTREE_FS_PARTIAL)
1248                 sbflags = SBREAD_PARTIAL;
1249
1250         ret = btrfs_scan_fs_devices(fp, path, &fs_devices, sb_bytenr, sbflags,
1251                         (flags & OPEN_CTREE_NO_DEVICES));
1252         if (ret)
1253                 goto out;
1254
1255         fs_info->fs_devices = fs_devices;
1256         if (flags & OPEN_CTREE_WRITES)
1257                 oflags = O_RDWR;
1258         else
1259                 oflags = O_RDONLY;
1260
1261         if (flags & OPEN_CTREE_EXCLUSIVE)
1262                 oflags |= O_EXCL;
1263
1264         ret = btrfs_open_devices(fs_devices, oflags);
1265         if (ret)
1266                 goto out;
1267
1268         disk_super = fs_info->super_copy;
1269         if (flags & OPEN_CTREE_RECOVER_SUPER)
1270                 ret = btrfs_read_dev_super(fs_devices->latest_bdev, disk_super,
1271                                 sb_bytenr, SBREAD_RECOVER);
1272         else
1273                 ret = btrfs_read_dev_super(fp, disk_super, sb_bytenr,
1274                                 sbflags);
1275         if (ret) {
1276                 printk("No valid btrfs found\n");
1277                 goto out_devices;
1278         }
1279
1280         if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_CHANGING_FSID &&
1281             !fs_info->ignore_fsid_mismatch) {
1282                 fprintf(stderr, "ERROR: Filesystem UUID change in progress\n");
1283                 goto out_devices;
1284         }
1285
1286         memcpy(fs_info->fsid, &disk_super->fsid, BTRFS_FSID_SIZE);
1287         fs_info->sectorsize = btrfs_super_sectorsize(disk_super);
1288         fs_info->nodesize = btrfs_super_nodesize(disk_super);
1289         fs_info->stripesize = btrfs_super_stripesize(disk_super);
1290
1291         ret = btrfs_check_fs_compatibility(fs_info->super_copy, flags);
1292         if (ret)
1293                 goto out_devices;
1294
1295         ret = btrfs_setup_chunk_tree_and_device_map(fs_info, chunk_root_bytenr);
1296         if (ret)
1297                 goto out_chunk;
1298
1299         /* Chunk tree root is unable to read, return directly */
1300         if (!fs_info->chunk_root)
1301                 return fs_info;
1302
1303         eb = fs_info->chunk_root->node;
1304         read_extent_buffer(eb, fs_info->chunk_tree_uuid,
1305                            btrfs_header_chunk_tree_uuid(eb),
1306                            BTRFS_UUID_SIZE);
1307
1308         ret = btrfs_setup_all_roots(fs_info, root_tree_bytenr, flags);
1309         if (ret && !(flags & __OPEN_CTREE_RETURN_CHUNK_ROOT) &&
1310             !fs_info->ignore_chunk_tree_error)
1311                 goto out_chunk;
1312
1313         return fs_info;
1314
1315 out_chunk:
1316         btrfs_release_all_roots(fs_info);
1317         btrfs_cleanup_all_caches(fs_info);
1318 out_devices:
1319         btrfs_close_devices(fs_devices);
1320 out:
1321         btrfs_free_fs_info(fs_info);
1322         return NULL;
1323 }
1324
1325 struct btrfs_fs_info *open_ctree_fs_info(const char *filename,
1326                                          u64 sb_bytenr, u64 root_tree_bytenr,
1327                                          u64 chunk_root_bytenr,
1328                                          unsigned flags)
1329 {
1330         int fp;
1331         int ret;
1332         struct btrfs_fs_info *info;
1333         int oflags = O_RDWR;
1334         struct stat st;
1335
1336         ret = stat(filename, &st);
1337         if (ret < 0) {
1338                 error("cannot stat '%s': %s", filename, strerror(errno));
1339                 return NULL;
1340         }
1341         if (!(((st.st_mode & S_IFMT) == S_IFREG) || ((st.st_mode & S_IFMT) == S_IFBLK))) {
1342                 error("not a regular file or block device: %s", filename);
1343                 return NULL;
1344         }
1345
1346         if (!(flags & OPEN_CTREE_WRITES))
1347                 oflags = O_RDONLY;
1348
1349         fp = open(filename, oflags);
1350         if (fp < 0) {
1351                 error("cannot open '%s': %s", filename, strerror(errno));
1352                 return NULL;
1353         }
1354         info = __open_ctree_fd(fp, filename, sb_bytenr, root_tree_bytenr,
1355                                chunk_root_bytenr, flags);
1356         close(fp);
1357         return info;
1358 }
1359
1360 struct btrfs_root *open_ctree(const char *filename, u64 sb_bytenr,
1361                               unsigned flags)
1362 {
1363         struct btrfs_fs_info *info;
1364
1365         /* This flags may not return fs_info with any valid root */
1366         BUG_ON(flags & OPEN_CTREE_IGNORE_CHUNK_TREE_ERROR);
1367         info = open_ctree_fs_info(filename, sb_bytenr, 0, 0, flags);
1368         if (!info)
1369                 return NULL;
1370         if (flags & __OPEN_CTREE_RETURN_CHUNK_ROOT)
1371                 return info->chunk_root;
1372         return info->fs_root;
1373 }
1374
1375 struct btrfs_root *open_ctree_fd(int fp, const char *path, u64 sb_bytenr,
1376                                  unsigned flags)
1377 {
1378         struct btrfs_fs_info *info;
1379
1380         /* This flags may not return fs_info with any valid root */
1381         if (flags & OPEN_CTREE_IGNORE_CHUNK_TREE_ERROR) {
1382                 error("invalid open_ctree flags: 0x%llx",
1383                                 (unsigned long long)flags);
1384                 return NULL;
1385         }
1386         info = __open_ctree_fd(fp, path, sb_bytenr, 0, 0, flags);
1387         if (!info)
1388                 return NULL;
1389         if (flags & __OPEN_CTREE_RETURN_CHUNK_ROOT)
1390                 return info->chunk_root;
1391         return info->fs_root;
1392 }
1393
1394 /*
1395  * Check if the super is valid:
1396  * - nodesize/sectorsize - minimum, maximum, alignment
1397  * - tree block starts   - alignment
1398  * - number of devices   - something sane
1399  * - sys array size      - maximum
1400  */
1401 static int check_super(struct btrfs_super_block *sb, unsigned sbflags)
1402 {
1403         u8 result[BTRFS_CSUM_SIZE];
1404         u32 crc;
1405         u16 csum_type;
1406         int csum_size;
1407
1408         if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
1409                 if (btrfs_super_magic(sb) == BTRFS_MAGIC_PARTIAL) {
1410                         if (!(sbflags & SBREAD_PARTIAL)) {
1411                                 error("superblock magic doesn't match");
1412                                 return -EIO;
1413                         }
1414                 }
1415         }
1416
1417         csum_type = btrfs_super_csum_type(sb);
1418         if (csum_type >= ARRAY_SIZE(btrfs_csum_sizes)) {
1419                 error("unsupported checksum algorithm %u", csum_type);
1420                 return -EIO;
1421         }
1422         csum_size = btrfs_csum_sizes[csum_type];
1423
1424         crc = ~(u32)0;
1425         crc = btrfs_csum_data((char *)sb + BTRFS_CSUM_SIZE, crc,
1426                               BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
1427         btrfs_csum_final(crc, result);
1428
1429         if (memcmp(result, sb->csum, csum_size)) {
1430                 error("superblock checksum mismatch");
1431                 return -EIO;
1432         }
1433         if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
1434                 error("tree_root level too big: %d >= %d",
1435                         btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
1436                 goto error_out;
1437         }
1438         if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
1439                 error("chunk_root level too big: %d >= %d",
1440                         btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
1441                 goto error_out;
1442         }
1443         if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
1444                 error("log_root level too big: %d >= %d",
1445                         btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
1446                 goto error_out;
1447         }
1448
1449         if (!IS_ALIGNED(btrfs_super_root(sb), 4096)) {
1450                 error("tree_root block unaligned: %llu", btrfs_super_root(sb));
1451                 goto error_out;
1452         }
1453         if (!IS_ALIGNED(btrfs_super_chunk_root(sb), 4096)) {
1454                 error("chunk_root block unaligned: %llu",
1455                         btrfs_super_chunk_root(sb));
1456                 goto error_out;
1457         }
1458         if (!IS_ALIGNED(btrfs_super_log_root(sb), 4096)) {
1459                 error("log_root block unaligned: %llu",
1460                         btrfs_super_log_root(sb));
1461                 goto error_out;
1462         }
1463         if (btrfs_super_nodesize(sb) < 4096) {
1464                 error("nodesize too small: %u < 4096",
1465                         btrfs_super_nodesize(sb));
1466                 goto error_out;
1467         }
1468         if (!IS_ALIGNED(btrfs_super_nodesize(sb), 4096)) {
1469                 error("nodesize unaligned: %u", btrfs_super_nodesize(sb));
1470                 goto error_out;
1471         }
1472         if (btrfs_super_sectorsize(sb) < 4096) {
1473                 error("sectorsize too small: %u < 4096",
1474                         btrfs_super_sectorsize(sb));
1475                 goto error_out;
1476         }
1477         if (!IS_ALIGNED(btrfs_super_sectorsize(sb), 4096)) {
1478                 error("sectorsize unaligned: %u", btrfs_super_sectorsize(sb));
1479                 goto error_out;
1480         }
1481         if (btrfs_super_total_bytes(sb) == 0) {
1482                 error("invalid total_bytes 0");
1483                 goto error_out;
1484         }
1485         if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
1486                 error("invalid bytes_used %llu", btrfs_super_bytes_used(sb));
1487                 goto error_out;
1488         }
1489         if ((btrfs_super_stripesize(sb) != 4096)
1490                 && (btrfs_super_stripesize(sb) != btrfs_super_sectorsize(sb))) {
1491                 error("invalid stripesize %u", btrfs_super_stripesize(sb));
1492                 goto error_out;
1493         }
1494
1495         if (memcmp(sb->fsid, sb->dev_item.fsid, BTRFS_UUID_SIZE) != 0) {
1496                 char fsid[BTRFS_UUID_UNPARSED_SIZE];
1497                 char dev_fsid[BTRFS_UUID_UNPARSED_SIZE];
1498
1499                 uuid_unparse(sb->fsid, fsid);
1500                 uuid_unparse(sb->dev_item.fsid, dev_fsid);
1501                 error("dev_item UUID does not match fsid: %s != %s",
1502                         dev_fsid, fsid);
1503                 goto error_out;
1504         }
1505
1506         /*
1507          * Hint to catch really bogus numbers, bitflips or so
1508          */
1509         if (btrfs_super_num_devices(sb) > (1UL << 31)) {
1510                 warning("suspicious number of devices: %llu",
1511                         btrfs_super_num_devices(sb));
1512         }
1513
1514         if (btrfs_super_num_devices(sb) == 0) {
1515                 error("number of devices is 0");
1516                 goto error_out;
1517         }
1518
1519         /*
1520          * Obvious sys_chunk_array corruptions, it must hold at least one key
1521          * and one chunk
1522          */
1523         if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
1524                 error("system chunk array too big %u > %u",
1525                       btrfs_super_sys_array_size(sb),
1526                       BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
1527                 goto error_out;
1528         }
1529         if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
1530                         + sizeof(struct btrfs_chunk)) {
1531                 error("system chunk array too small %u < %zu",
1532                       btrfs_super_sys_array_size(sb),
1533                       sizeof(struct btrfs_disk_key) +
1534                       sizeof(struct btrfs_chunk));
1535                 goto error_out;
1536         }
1537
1538         return 0;
1539
1540 error_out:
1541         error("superblock checksum matches but it has invalid members");
1542         return -EIO;
1543 }
1544
1545 int btrfs_read_dev_super(int fd, struct btrfs_super_block *sb, u64 sb_bytenr,
1546                          unsigned sbflags)
1547 {
1548         u8 fsid[BTRFS_FSID_SIZE];
1549         int fsid_is_initialized = 0;
1550         char tmp[BTRFS_SUPER_INFO_SIZE];
1551         struct btrfs_super_block *buf = (struct btrfs_super_block *)tmp;
1552         int i;
1553         int ret;
1554         int max_super = sbflags & SBREAD_RECOVER ? BTRFS_SUPER_MIRROR_MAX : 1;
1555         u64 transid = 0;
1556         u64 bytenr;
1557
1558         if (sb_bytenr != BTRFS_SUPER_INFO_OFFSET) {
1559                 ret = pread64(fd, buf, BTRFS_SUPER_INFO_SIZE, sb_bytenr);
1560                 /* real error */
1561                 if (ret < 0)
1562                         return -errno;
1563
1564                 /* Not large enough sb, return -ENOENT instead of normal -EIO */
1565                 if (ret < BTRFS_SUPER_INFO_SIZE)
1566                         return -ENOENT;
1567
1568                 if (btrfs_super_bytenr(buf) != sb_bytenr)
1569                         return -EIO;
1570
1571                 ret = check_super(buf, sbflags);
1572                 if (ret < 0)
1573                         return ret;
1574                 memcpy(sb, buf, BTRFS_SUPER_INFO_SIZE);
1575                 return 0;
1576         }
1577
1578         /*
1579         * we would like to check all the supers, but that would make
1580         * a btrfs mount succeed after a mkfs from a different FS.
1581         * So, we need to add a special mount option to scan for
1582         * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1583         */
1584
1585         for (i = 0; i < max_super; i++) {
1586                 bytenr = btrfs_sb_offset(i);
1587                 ret = pread64(fd, buf, BTRFS_SUPER_INFO_SIZE, bytenr);
1588                 if (ret < BTRFS_SUPER_INFO_SIZE)
1589                         break;
1590
1591                 if (btrfs_super_bytenr(buf) != bytenr )
1592                         continue;
1593                 /* if magic is NULL, the device was removed */
1594                 if (btrfs_super_magic(buf) == 0 && i == 0)
1595                         break;
1596                 if (check_super(buf, sbflags))
1597                         continue;
1598
1599                 if (!fsid_is_initialized) {
1600                         memcpy(fsid, buf->fsid, sizeof(fsid));
1601                         fsid_is_initialized = 1;
1602                 } else if (memcmp(fsid, buf->fsid, sizeof(fsid))) {
1603                         /*
1604                          * the superblocks (the original one and
1605                          * its backups) contain data of different
1606                          * filesystems -> the super cannot be trusted
1607                          */
1608                         continue;
1609                 }
1610
1611                 if (btrfs_super_generation(buf) > transid) {
1612                         memcpy(sb, buf, BTRFS_SUPER_INFO_SIZE);
1613                         transid = btrfs_super_generation(buf);
1614                 }
1615         }
1616
1617         return transid > 0 ? 0 : -1;
1618 }
1619
1620 static int write_dev_supers(struct btrfs_fs_info *fs_info,
1621                             struct btrfs_super_block *sb,
1622                             struct btrfs_device *device)
1623 {
1624         u64 bytenr;
1625         u32 crc;
1626         int i, ret;
1627
1628         if (fs_info->super_bytenr != BTRFS_SUPER_INFO_OFFSET) {
1629                 btrfs_set_super_bytenr(sb, fs_info->super_bytenr);
1630                 crc = ~(u32)0;
1631                 crc = btrfs_csum_data((char *)sb + BTRFS_CSUM_SIZE, crc,
1632                                       BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
1633                 btrfs_csum_final(crc, &sb->csum[0]);
1634
1635                 /*
1636                  * super_copy is BTRFS_SUPER_INFO_SIZE bytes and is
1637                  * zero filled, we can use it directly
1638                  */
1639                 ret = pwrite64(device->fd, fs_info->super_copy,
1640                                 BTRFS_SUPER_INFO_SIZE,
1641                                 fs_info->super_bytenr);
1642                 if (ret != BTRFS_SUPER_INFO_SIZE)
1643                         goto write_err;
1644                 return 0;
1645         }
1646
1647         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1648                 bytenr = btrfs_sb_offset(i);
1649                 if (bytenr + BTRFS_SUPER_INFO_SIZE > device->total_bytes)
1650                         break;
1651
1652                 btrfs_set_super_bytenr(sb, bytenr);
1653
1654                 crc = ~(u32)0;
1655                 crc = btrfs_csum_data((char *)sb + BTRFS_CSUM_SIZE, crc,
1656                                       BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE);
1657                 btrfs_csum_final(crc, &sb->csum[0]);
1658
1659                 /*
1660                  * super_copy is BTRFS_SUPER_INFO_SIZE bytes and is
1661                  * zero filled, we can use it directly
1662                  */
1663                 ret = pwrite64(device->fd, fs_info->super_copy,
1664                                 BTRFS_SUPER_INFO_SIZE, bytenr);
1665                 if (ret != BTRFS_SUPER_INFO_SIZE)
1666                         goto write_err;
1667         }
1668
1669         return 0;
1670
1671 write_err:
1672         if (ret > 0)
1673                 fprintf(stderr, "WARNING: failed to write all sb data\n");
1674         else
1675                 fprintf(stderr, "WARNING: failed to write sb: %s\n",
1676                         strerror(errno));
1677         return ret;
1678 }
1679
1680 int write_all_supers(struct btrfs_fs_info *fs_info)
1681 {
1682         struct list_head *cur;
1683         struct list_head *head = &fs_info->fs_devices->devices;
1684         struct btrfs_device *dev;
1685         struct btrfs_super_block *sb;
1686         struct btrfs_dev_item *dev_item;
1687         int ret;
1688         u64 flags;
1689
1690         sb = fs_info->super_copy;
1691         dev_item = &sb->dev_item;
1692         list_for_each(cur, head) {
1693                 dev = list_entry(cur, struct btrfs_device, dev_list);
1694                 if (!dev->writeable)
1695                         continue;
1696
1697                 btrfs_set_stack_device_generation(dev_item, 0);
1698                 btrfs_set_stack_device_type(dev_item, dev->type);
1699                 btrfs_set_stack_device_id(dev_item, dev->devid);
1700                 btrfs_set_stack_device_total_bytes(dev_item, dev->total_bytes);
1701                 btrfs_set_stack_device_bytes_used(dev_item, dev->bytes_used);
1702                 btrfs_set_stack_device_io_align(dev_item, dev->io_align);
1703                 btrfs_set_stack_device_io_width(dev_item, dev->io_width);
1704                 btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
1705                 memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
1706                 memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_UUID_SIZE);
1707
1708                 flags = btrfs_super_flags(sb);
1709                 btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
1710
1711                 ret = write_dev_supers(fs_info, sb, dev);
1712                 BUG_ON(ret);
1713         }
1714         return 0;
1715 }
1716
1717 int write_ctree_super(struct btrfs_trans_handle *trans,
1718                       struct btrfs_fs_info *fs_info)
1719 {
1720         int ret;
1721         struct btrfs_root *tree_root = fs_info->tree_root;
1722         struct btrfs_root *chunk_root = fs_info->chunk_root;
1723
1724         if (fs_info->readonly)
1725                 return 0;
1726
1727         btrfs_set_super_generation(fs_info->super_copy,
1728                                    trans->transid);
1729         btrfs_set_super_root(fs_info->super_copy,
1730                              tree_root->node->start);
1731         btrfs_set_super_root_level(fs_info->super_copy,
1732                                    btrfs_header_level(tree_root->node));
1733         btrfs_set_super_chunk_root(fs_info->super_copy,
1734                                    chunk_root->node->start);
1735         btrfs_set_super_chunk_root_level(fs_info->super_copy,
1736                                          btrfs_header_level(chunk_root->node));
1737         btrfs_set_super_chunk_root_generation(fs_info->super_copy,
1738                                 btrfs_header_generation(chunk_root->node));
1739
1740         ret = write_all_supers(fs_info);
1741         if (ret)
1742                 fprintf(stderr, "failed to write new super block err %d\n", ret);
1743         return ret;
1744 }
1745
1746 int close_ctree_fs_info(struct btrfs_fs_info *fs_info)
1747 {
1748         int ret;
1749         struct btrfs_trans_handle *trans;
1750         struct btrfs_root *root = fs_info->tree_root;
1751
1752         if (fs_info->last_trans_committed !=
1753             fs_info->generation) {
1754                 BUG_ON(!root);
1755                 trans = btrfs_start_transaction(root, 1);
1756                 btrfs_commit_transaction(trans, root);
1757                 trans = btrfs_start_transaction(root, 1);
1758                 ret = commit_tree_roots(trans, fs_info);
1759                 BUG_ON(ret);
1760                 ret = __commit_transaction(trans, root);
1761                 BUG_ON(ret);
1762                 write_ctree_super(trans, fs_info);
1763                 kfree(trans);
1764         }
1765
1766         if (fs_info->finalize_on_close) {
1767                 btrfs_set_super_magic(fs_info->super_copy, BTRFS_MAGIC);
1768                 root->fs_info->finalize_on_close = 0;
1769                 ret = write_all_supers(fs_info);
1770                 if (ret)
1771                         fprintf(stderr,
1772                                 "failed to write new super block err %d\n", ret);
1773         }
1774         btrfs_free_block_groups(fs_info);
1775
1776         free_fs_roots_tree(&fs_info->fs_root_tree);
1777
1778         btrfs_release_all_roots(fs_info);
1779         ret = btrfs_close_devices(fs_info->fs_devices);
1780         btrfs_cleanup_all_caches(fs_info);
1781         btrfs_free_fs_info(fs_info);
1782         return ret;
1783 }
1784
1785 int clean_tree_block(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1786                      struct extent_buffer *eb)
1787 {
1788         return clear_extent_buffer_dirty(eb);
1789 }
1790
1791 void btrfs_mark_buffer_dirty(struct extent_buffer *eb)
1792 {
1793         set_extent_buffer_dirty(eb);
1794 }
1795
1796 int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid)
1797 {
1798         int ret;
1799
1800         ret = extent_buffer_uptodate(buf);
1801         if (!ret)
1802                 return ret;
1803
1804         ret = verify_parent_transid(buf->tree, buf, parent_transid, 1);
1805         return !ret;
1806 }
1807
1808 int btrfs_set_buffer_uptodate(struct extent_buffer *eb)
1809 {
1810         return set_extent_buffer_uptodate(eb);
1811 }