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