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