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