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