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