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