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