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