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