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