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