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