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