block: remove per-queue plugging
[linux-2.6.git] / fs / btrfs / 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 <linux/fs.h>
20 #include <linux/blkdev.h>
21 #include <linux/scatterlist.h>
22 #include <linux/swap.h>
23 #include <linux/radix-tree.h>
24 #include <linux/writeback.h>
25 #include <linux/buffer_head.h>
26 #include <linux/workqueue.h>
27 #include <linux/kthread.h>
28 #include <linux/freezer.h>
29 #include <linux/crc32c.h>
30 #include <linux/slab.h>
31 #include <linux/migrate.h>
32 #include "compat.h"
33 #include "ctree.h"
34 #include "disk-io.h"
35 #include "transaction.h"
36 #include "btrfs_inode.h"
37 #include "volumes.h"
38 #include "print-tree.h"
39 #include "async-thread.h"
40 #include "locking.h"
41 #include "tree-log.h"
42 #include "free-space-cache.h"
43
44 static struct extent_io_ops btree_extent_io_ops;
45 static void end_workqueue_fn(struct btrfs_work *work);
46 static void free_fs_root(struct btrfs_root *root);
47 static void btrfs_check_super_valid(struct btrfs_fs_info *fs_info,
48                                     int read_only);
49 static int btrfs_destroy_ordered_operations(struct btrfs_root *root);
50 static int btrfs_destroy_ordered_extents(struct btrfs_root *root);
51 static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
52                                       struct btrfs_root *root);
53 static int btrfs_destroy_pending_snapshots(struct btrfs_transaction *t);
54 static int btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
55 static int btrfs_destroy_marked_extents(struct btrfs_root *root,
56                                         struct extent_io_tree *dirty_pages,
57                                         int mark);
58 static int btrfs_destroy_pinned_extent(struct btrfs_root *root,
59                                        struct extent_io_tree *pinned_extents);
60 static int btrfs_cleanup_transaction(struct btrfs_root *root);
61
62 /*
63  * end_io_wq structs are used to do processing in task context when an IO is
64  * complete.  This is used during reads to verify checksums, and it is used
65  * by writes to insert metadata for new file extents after IO is complete.
66  */
67 struct end_io_wq {
68         struct bio *bio;
69         bio_end_io_t *end_io;
70         void *private;
71         struct btrfs_fs_info *info;
72         int error;
73         int metadata;
74         struct list_head list;
75         struct btrfs_work work;
76 };
77
78 /*
79  * async submit bios are used to offload expensive checksumming
80  * onto the worker threads.  They checksum file and metadata bios
81  * just before they are sent down the IO stack.
82  */
83 struct async_submit_bio {
84         struct inode *inode;
85         struct bio *bio;
86         struct list_head list;
87         extent_submit_bio_hook_t *submit_bio_start;
88         extent_submit_bio_hook_t *submit_bio_done;
89         int rw;
90         int mirror_num;
91         unsigned long bio_flags;
92         /*
93          * bio_offset is optional, can be used if the pages in the bio
94          * can't tell us where in the file the bio should go
95          */
96         u64 bio_offset;
97         struct btrfs_work work;
98 };
99
100 /* These are used to set the lockdep class on the extent buffer locks.
101  * The class is set by the readpage_end_io_hook after the buffer has
102  * passed csum validation but before the pages are unlocked.
103  *
104  * The lockdep class is also set by btrfs_init_new_buffer on freshly
105  * allocated blocks.
106  *
107  * The class is based on the level in the tree block, which allows lockdep
108  * to know that lower nodes nest inside the locks of higher nodes.
109  *
110  * We also add a check to make sure the highest level of the tree is
111  * the same as our lockdep setup here.  If BTRFS_MAX_LEVEL changes, this
112  * code needs update as well.
113  */
114 #ifdef CONFIG_DEBUG_LOCK_ALLOC
115 # if BTRFS_MAX_LEVEL != 8
116 #  error
117 # endif
118 static struct lock_class_key btrfs_eb_class[BTRFS_MAX_LEVEL + 1];
119 static const char *btrfs_eb_name[BTRFS_MAX_LEVEL + 1] = {
120         /* leaf */
121         "btrfs-extent-00",
122         "btrfs-extent-01",
123         "btrfs-extent-02",
124         "btrfs-extent-03",
125         "btrfs-extent-04",
126         "btrfs-extent-05",
127         "btrfs-extent-06",
128         "btrfs-extent-07",
129         /* highest possible level */
130         "btrfs-extent-08",
131 };
132 #endif
133
134 /*
135  * extents on the btree inode are pretty simple, there's one extent
136  * that covers the entire device
137  */
138 static struct extent_map *btree_get_extent(struct inode *inode,
139                 struct page *page, size_t page_offset, u64 start, u64 len,
140                 int create)
141 {
142         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
143         struct extent_map *em;
144         int ret;
145
146         read_lock(&em_tree->lock);
147         em = lookup_extent_mapping(em_tree, start, len);
148         if (em) {
149                 em->bdev =
150                         BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev;
151                 read_unlock(&em_tree->lock);
152                 goto out;
153         }
154         read_unlock(&em_tree->lock);
155
156         em = alloc_extent_map(GFP_NOFS);
157         if (!em) {
158                 em = ERR_PTR(-ENOMEM);
159                 goto out;
160         }
161         em->start = 0;
162         em->len = (u64)-1;
163         em->block_len = (u64)-1;
164         em->block_start = 0;
165         em->bdev = BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev;
166
167         write_lock(&em_tree->lock);
168         ret = add_extent_mapping(em_tree, em);
169         if (ret == -EEXIST) {
170                 u64 failed_start = em->start;
171                 u64 failed_len = em->len;
172
173                 free_extent_map(em);
174                 em = lookup_extent_mapping(em_tree, start, len);
175                 if (em) {
176                         ret = 0;
177                 } else {
178                         em = lookup_extent_mapping(em_tree, failed_start,
179                                                    failed_len);
180                         ret = -EIO;
181                 }
182         } else if (ret) {
183                 free_extent_map(em);
184                 em = NULL;
185         }
186         write_unlock(&em_tree->lock);
187
188         if (ret)
189                 em = ERR_PTR(ret);
190 out:
191         return em;
192 }
193
194 u32 btrfs_csum_data(struct btrfs_root *root, char *data, u32 seed, size_t len)
195 {
196         return crc32c(seed, data, len);
197 }
198
199 void btrfs_csum_final(u32 crc, char *result)
200 {
201         *(__le32 *)result = ~cpu_to_le32(crc);
202 }
203
204 /*
205  * compute the csum for a btree block, and either verify it or write it
206  * into the csum field of the block.
207  */
208 static int csum_tree_block(struct btrfs_root *root, struct extent_buffer *buf,
209                            int verify)
210 {
211         u16 csum_size =
212                 btrfs_super_csum_size(&root->fs_info->super_copy);
213         char *result = NULL;
214         unsigned long len;
215         unsigned long cur_len;
216         unsigned long offset = BTRFS_CSUM_SIZE;
217         char *map_token = NULL;
218         char *kaddr;
219         unsigned long map_start;
220         unsigned long map_len;
221         int err;
222         u32 crc = ~(u32)0;
223         unsigned long inline_result;
224
225         len = buf->len - offset;
226         while (len > 0) {
227                 err = map_private_extent_buffer(buf, offset, 32,
228                                         &map_token, &kaddr,
229                                         &map_start, &map_len, KM_USER0);
230                 if (err)
231                         return 1;
232                 cur_len = min(len, map_len - (offset - map_start));
233                 crc = btrfs_csum_data(root, kaddr + offset - map_start,
234                                       crc, cur_len);
235                 len -= cur_len;
236                 offset += cur_len;
237                 unmap_extent_buffer(buf, map_token, KM_USER0);
238         }
239         if (csum_size > sizeof(inline_result)) {
240                 result = kzalloc(csum_size * sizeof(char), GFP_NOFS);
241                 if (!result)
242                         return 1;
243         } else {
244                 result = (char *)&inline_result;
245         }
246
247         btrfs_csum_final(crc, result);
248
249         if (verify) {
250                 if (memcmp_extent_buffer(buf, result, 0, csum_size)) {
251                         u32 val;
252                         u32 found = 0;
253                         memcpy(&found, result, csum_size);
254
255                         read_extent_buffer(buf, &val, 0, csum_size);
256                         if (printk_ratelimit()) {
257                                 printk(KERN_INFO "btrfs: %s checksum verify "
258                                        "failed on %llu wanted %X found %X "
259                                        "level %d\n",
260                                        root->fs_info->sb->s_id,
261                                        (unsigned long long)buf->start, val, found,
262                                        btrfs_header_level(buf));
263                         }
264                         if (result != (char *)&inline_result)
265                                 kfree(result);
266                         return 1;
267                 }
268         } else {
269                 write_extent_buffer(buf, result, 0, csum_size);
270         }
271         if (result != (char *)&inline_result)
272                 kfree(result);
273         return 0;
274 }
275
276 /*
277  * we can't consider a given block up to date unless the transid of the
278  * block matches the transid in the parent node's pointer.  This is how we
279  * detect blocks that either didn't get written at all or got written
280  * in the wrong place.
281  */
282 static int verify_parent_transid(struct extent_io_tree *io_tree,
283                                  struct extent_buffer *eb, u64 parent_transid)
284 {
285         struct extent_state *cached_state = NULL;
286         int ret;
287
288         if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
289                 return 0;
290
291         lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
292                          0, &cached_state, GFP_NOFS);
293         if (extent_buffer_uptodate(io_tree, eb, cached_state) &&
294             btrfs_header_generation(eb) == parent_transid) {
295                 ret = 0;
296                 goto out;
297         }
298         if (printk_ratelimit()) {
299                 printk("parent transid verify failed on %llu wanted %llu "
300                        "found %llu\n",
301                        (unsigned long long)eb->start,
302                        (unsigned long long)parent_transid,
303                        (unsigned long long)btrfs_header_generation(eb));
304         }
305         ret = 1;
306         clear_extent_buffer_uptodate(io_tree, eb, &cached_state);
307 out:
308         unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
309                              &cached_state, GFP_NOFS);
310         return ret;
311 }
312
313 /*
314  * helper to read a given tree block, doing retries as required when
315  * the checksums don't match and we have alternate mirrors to try.
316  */
317 static int btree_read_extent_buffer_pages(struct btrfs_root *root,
318                                           struct extent_buffer *eb,
319                                           u64 start, u64 parent_transid)
320 {
321         struct extent_io_tree *io_tree;
322         int ret;
323         int num_copies = 0;
324         int mirror_num = 0;
325
326         io_tree = &BTRFS_I(root->fs_info->btree_inode)->io_tree;
327         while (1) {
328                 ret = read_extent_buffer_pages(io_tree, eb, start, 1,
329                                                btree_get_extent, mirror_num);
330                 if (!ret &&
331                     !verify_parent_transid(io_tree, eb, parent_transid))
332                         return ret;
333
334                 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
335                                               eb->start, eb->len);
336                 if (num_copies == 1)
337                         return ret;
338
339                 mirror_num++;
340                 if (mirror_num > num_copies)
341                         return ret;
342         }
343         return -EIO;
344 }
345
346 /*
347  * checksum a dirty tree block before IO.  This has extra checks to make sure
348  * we only fill in the checksum field in the first page of a multi-page block
349  */
350
351 static int csum_dirty_buffer(struct btrfs_root *root, struct page *page)
352 {
353         struct extent_io_tree *tree;
354         u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
355         u64 found_start;
356         unsigned long len;
357         struct extent_buffer *eb;
358         int ret;
359
360         tree = &BTRFS_I(page->mapping->host)->io_tree;
361
362         if (page->private == EXTENT_PAGE_PRIVATE) {
363                 WARN_ON(1);
364                 goto out;
365         }
366         if (!page->private) {
367                 WARN_ON(1);
368                 goto out;
369         }
370         len = page->private >> 2;
371         WARN_ON(len == 0);
372
373         eb = alloc_extent_buffer(tree, start, len, page, GFP_NOFS);
374         if (eb == NULL) {
375                 WARN_ON(1);
376                 goto out;
377         }
378         ret = btree_read_extent_buffer_pages(root, eb, start + PAGE_CACHE_SIZE,
379                                              btrfs_header_generation(eb));
380         BUG_ON(ret);
381         WARN_ON(!btrfs_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN));
382
383         found_start = btrfs_header_bytenr(eb);
384         if (found_start != start) {
385                 WARN_ON(1);
386                 goto err;
387         }
388         if (eb->first_page != page) {
389                 WARN_ON(1);
390                 goto err;
391         }
392         if (!PageUptodate(page)) {
393                 WARN_ON(1);
394                 goto err;
395         }
396         csum_tree_block(root, eb, 0);
397 err:
398         free_extent_buffer(eb);
399 out:
400         return 0;
401 }
402
403 static int check_tree_block_fsid(struct btrfs_root *root,
404                                  struct extent_buffer *eb)
405 {
406         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
407         u8 fsid[BTRFS_UUID_SIZE];
408         int ret = 1;
409
410         read_extent_buffer(eb, fsid, (unsigned long)btrfs_header_fsid(eb),
411                            BTRFS_FSID_SIZE);
412         while (fs_devices) {
413                 if (!memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE)) {
414                         ret = 0;
415                         break;
416                 }
417                 fs_devices = fs_devices->seed;
418         }
419         return ret;
420 }
421
422 #ifdef CONFIG_DEBUG_LOCK_ALLOC
423 void btrfs_set_buffer_lockdep_class(struct extent_buffer *eb, int level)
424 {
425         lockdep_set_class_and_name(&eb->lock,
426                            &btrfs_eb_class[level],
427                            btrfs_eb_name[level]);
428 }
429 #endif
430
431 static int btree_readpage_end_io_hook(struct page *page, u64 start, u64 end,
432                                struct extent_state *state)
433 {
434         struct extent_io_tree *tree;
435         u64 found_start;
436         int found_level;
437         unsigned long len;
438         struct extent_buffer *eb;
439         struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
440         int ret = 0;
441
442         tree = &BTRFS_I(page->mapping->host)->io_tree;
443         if (page->private == EXTENT_PAGE_PRIVATE)
444                 goto out;
445         if (!page->private)
446                 goto out;
447
448         len = page->private >> 2;
449         WARN_ON(len == 0);
450
451         eb = alloc_extent_buffer(tree, start, len, page, GFP_NOFS);
452         if (eb == NULL) {
453                 ret = -EIO;
454                 goto out;
455         }
456
457         found_start = btrfs_header_bytenr(eb);
458         if (found_start != start) {
459                 if (printk_ratelimit()) {
460                         printk(KERN_INFO "btrfs bad tree block start "
461                                "%llu %llu\n",
462                                (unsigned long long)found_start,
463                                (unsigned long long)eb->start);
464                 }
465                 ret = -EIO;
466                 goto err;
467         }
468         if (eb->first_page != page) {
469                 printk(KERN_INFO "btrfs bad first page %lu %lu\n",
470                        eb->first_page->index, page->index);
471                 WARN_ON(1);
472                 ret = -EIO;
473                 goto err;
474         }
475         if (check_tree_block_fsid(root, eb)) {
476                 if (printk_ratelimit()) {
477                         printk(KERN_INFO "btrfs bad fsid on block %llu\n",
478                                (unsigned long long)eb->start);
479                 }
480                 ret = -EIO;
481                 goto err;
482         }
483         found_level = btrfs_header_level(eb);
484
485         btrfs_set_buffer_lockdep_class(eb, found_level);
486
487         ret = csum_tree_block(root, eb, 1);
488         if (ret)
489                 ret = -EIO;
490
491         end = min_t(u64, eb->len, PAGE_CACHE_SIZE);
492         end = eb->start + end - 1;
493 err:
494         free_extent_buffer(eb);
495 out:
496         return ret;
497 }
498
499 static void end_workqueue_bio(struct bio *bio, int err)
500 {
501         struct end_io_wq *end_io_wq = bio->bi_private;
502         struct btrfs_fs_info *fs_info;
503
504         fs_info = end_io_wq->info;
505         end_io_wq->error = err;
506         end_io_wq->work.func = end_workqueue_fn;
507         end_io_wq->work.flags = 0;
508
509         if (bio->bi_rw & REQ_WRITE) {
510                 if (end_io_wq->metadata == 1)
511                         btrfs_queue_worker(&fs_info->endio_meta_write_workers,
512                                            &end_io_wq->work);
513                 else if (end_io_wq->metadata == 2)
514                         btrfs_queue_worker(&fs_info->endio_freespace_worker,
515                                            &end_io_wq->work);
516                 else
517                         btrfs_queue_worker(&fs_info->endio_write_workers,
518                                            &end_io_wq->work);
519         } else {
520                 if (end_io_wq->metadata)
521                         btrfs_queue_worker(&fs_info->endio_meta_workers,
522                                            &end_io_wq->work);
523                 else
524                         btrfs_queue_worker(&fs_info->endio_workers,
525                                            &end_io_wq->work);
526         }
527 }
528
529 /*
530  * For the metadata arg you want
531  *
532  * 0 - if data
533  * 1 - if normal metadta
534  * 2 - if writing to the free space cache area
535  */
536 int btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
537                         int metadata)
538 {
539         struct end_io_wq *end_io_wq;
540         end_io_wq = kmalloc(sizeof(*end_io_wq), GFP_NOFS);
541         if (!end_io_wq)
542                 return -ENOMEM;
543
544         end_io_wq->private = bio->bi_private;
545         end_io_wq->end_io = bio->bi_end_io;
546         end_io_wq->info = info;
547         end_io_wq->error = 0;
548         end_io_wq->bio = bio;
549         end_io_wq->metadata = metadata;
550
551         bio->bi_private = end_io_wq;
552         bio->bi_end_io = end_workqueue_bio;
553         return 0;
554 }
555
556 unsigned long btrfs_async_submit_limit(struct btrfs_fs_info *info)
557 {
558         unsigned long limit = min_t(unsigned long,
559                                     info->workers.max_workers,
560                                     info->fs_devices->open_devices);
561         return 256 * limit;
562 }
563
564 int btrfs_congested_async(struct btrfs_fs_info *info, int iodone)
565 {
566         return atomic_read(&info->nr_async_bios) >
567                 btrfs_async_submit_limit(info);
568 }
569
570 static void run_one_async_start(struct btrfs_work *work)
571 {
572         struct async_submit_bio *async;
573
574         async = container_of(work, struct  async_submit_bio, work);
575         async->submit_bio_start(async->inode, async->rw, async->bio,
576                                async->mirror_num, async->bio_flags,
577                                async->bio_offset);
578 }
579
580 static void run_one_async_done(struct btrfs_work *work)
581 {
582         struct btrfs_fs_info *fs_info;
583         struct async_submit_bio *async;
584         int limit;
585
586         async = container_of(work, struct  async_submit_bio, work);
587         fs_info = BTRFS_I(async->inode)->root->fs_info;
588
589         limit = btrfs_async_submit_limit(fs_info);
590         limit = limit * 2 / 3;
591
592         atomic_dec(&fs_info->nr_async_submits);
593
594         if (atomic_read(&fs_info->nr_async_submits) < limit &&
595             waitqueue_active(&fs_info->async_submit_wait))
596                 wake_up(&fs_info->async_submit_wait);
597
598         async->submit_bio_done(async->inode, async->rw, async->bio,
599                                async->mirror_num, async->bio_flags,
600                                async->bio_offset);
601 }
602
603 static void run_one_async_free(struct btrfs_work *work)
604 {
605         struct async_submit_bio *async;
606
607         async = container_of(work, struct  async_submit_bio, work);
608         kfree(async);
609 }
610
611 int btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct inode *inode,
612                         int rw, struct bio *bio, int mirror_num,
613                         unsigned long bio_flags,
614                         u64 bio_offset,
615                         extent_submit_bio_hook_t *submit_bio_start,
616                         extent_submit_bio_hook_t *submit_bio_done)
617 {
618         struct async_submit_bio *async;
619
620         async = kmalloc(sizeof(*async), GFP_NOFS);
621         if (!async)
622                 return -ENOMEM;
623
624         async->inode = inode;
625         async->rw = rw;
626         async->bio = bio;
627         async->mirror_num = mirror_num;
628         async->submit_bio_start = submit_bio_start;
629         async->submit_bio_done = submit_bio_done;
630
631         async->work.func = run_one_async_start;
632         async->work.ordered_func = run_one_async_done;
633         async->work.ordered_free = run_one_async_free;
634
635         async->work.flags = 0;
636         async->bio_flags = bio_flags;
637         async->bio_offset = bio_offset;
638
639         atomic_inc(&fs_info->nr_async_submits);
640
641         if (rw & REQ_SYNC)
642                 btrfs_set_work_high_prio(&async->work);
643
644         btrfs_queue_worker(&fs_info->workers, &async->work);
645
646         while (atomic_read(&fs_info->async_submit_draining) &&
647               atomic_read(&fs_info->nr_async_submits)) {
648                 wait_event(fs_info->async_submit_wait,
649                            (atomic_read(&fs_info->nr_async_submits) == 0));
650         }
651
652         return 0;
653 }
654
655 static int btree_csum_one_bio(struct bio *bio)
656 {
657         struct bio_vec *bvec = bio->bi_io_vec;
658         int bio_index = 0;
659         struct btrfs_root *root;
660
661         WARN_ON(bio->bi_vcnt <= 0);
662         while (bio_index < bio->bi_vcnt) {
663                 root = BTRFS_I(bvec->bv_page->mapping->host)->root;
664                 csum_dirty_buffer(root, bvec->bv_page);
665                 bio_index++;
666                 bvec++;
667         }
668         return 0;
669 }
670
671 static int __btree_submit_bio_start(struct inode *inode, int rw,
672                                     struct bio *bio, int mirror_num,
673                                     unsigned long bio_flags,
674                                     u64 bio_offset)
675 {
676         /*
677          * when we're called for a write, we're already in the async
678          * submission context.  Just jump into btrfs_map_bio
679          */
680         btree_csum_one_bio(bio);
681         return 0;
682 }
683
684 static int __btree_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
685                                  int mirror_num, unsigned long bio_flags,
686                                  u64 bio_offset)
687 {
688         /*
689          * when we're called for a write, we're already in the async
690          * submission context.  Just jump into btrfs_map_bio
691          */
692         return btrfs_map_bio(BTRFS_I(inode)->root, rw, bio, mirror_num, 1);
693 }
694
695 static int btree_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
696                                  int mirror_num, unsigned long bio_flags,
697                                  u64 bio_offset)
698 {
699         int ret;
700
701         ret = btrfs_bio_wq_end_io(BTRFS_I(inode)->root->fs_info,
702                                           bio, 1);
703         BUG_ON(ret);
704
705         if (!(rw & REQ_WRITE)) {
706                 /*
707                  * called for a read, do the setup so that checksum validation
708                  * can happen in the async kernel threads
709                  */
710                 return btrfs_map_bio(BTRFS_I(inode)->root, rw, bio,
711                                      mirror_num, 0);
712         }
713
714         /*
715          * kthread helpers are used to submit writes so that checksumming
716          * can happen in parallel across all CPUs
717          */
718         return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
719                                    inode, rw, bio, mirror_num, 0,
720                                    bio_offset,
721                                    __btree_submit_bio_start,
722                                    __btree_submit_bio_done);
723 }
724
725 #ifdef CONFIG_MIGRATION
726 static int btree_migratepage(struct address_space *mapping,
727                         struct page *newpage, struct page *page)
728 {
729         /*
730          * we can't safely write a btree page from here,
731          * we haven't done the locking hook
732          */
733         if (PageDirty(page))
734                 return -EAGAIN;
735         /*
736          * Buffers may be managed in a filesystem specific way.
737          * We must have no buffers or drop them.
738          */
739         if (page_has_private(page) &&
740             !try_to_release_page(page, GFP_KERNEL))
741                 return -EAGAIN;
742         return migrate_page(mapping, newpage, page);
743 }
744 #endif
745
746 static int btree_writepage(struct page *page, struct writeback_control *wbc)
747 {
748         struct extent_io_tree *tree;
749         struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
750         struct extent_buffer *eb;
751         int was_dirty;
752
753         tree = &BTRFS_I(page->mapping->host)->io_tree;
754         if (!(current->flags & PF_MEMALLOC)) {
755                 return extent_write_full_page(tree, page,
756                                               btree_get_extent, wbc);
757         }
758
759         redirty_page_for_writepage(wbc, page);
760         eb = btrfs_find_tree_block(root, page_offset(page), PAGE_CACHE_SIZE);
761         WARN_ON(!eb);
762
763         was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
764         if (!was_dirty) {
765                 spin_lock(&root->fs_info->delalloc_lock);
766                 root->fs_info->dirty_metadata_bytes += PAGE_CACHE_SIZE;
767                 spin_unlock(&root->fs_info->delalloc_lock);
768         }
769         free_extent_buffer(eb);
770
771         unlock_page(page);
772         return 0;
773 }
774
775 static int btree_writepages(struct address_space *mapping,
776                             struct writeback_control *wbc)
777 {
778         struct extent_io_tree *tree;
779         tree = &BTRFS_I(mapping->host)->io_tree;
780         if (wbc->sync_mode == WB_SYNC_NONE) {
781                 struct btrfs_root *root = BTRFS_I(mapping->host)->root;
782                 u64 num_dirty;
783                 unsigned long thresh = 32 * 1024 * 1024;
784
785                 if (wbc->for_kupdate)
786                         return 0;
787
788                 /* this is a bit racy, but that's ok */
789                 num_dirty = root->fs_info->dirty_metadata_bytes;
790                 if (num_dirty < thresh)
791                         return 0;
792         }
793         return extent_writepages(tree, mapping, btree_get_extent, wbc);
794 }
795
796 static int btree_readpage(struct file *file, struct page *page)
797 {
798         struct extent_io_tree *tree;
799         tree = &BTRFS_I(page->mapping->host)->io_tree;
800         return extent_read_full_page(tree, page, btree_get_extent);
801 }
802
803 static int btree_releasepage(struct page *page, gfp_t gfp_flags)
804 {
805         struct extent_io_tree *tree;
806         struct extent_map_tree *map;
807         int ret;
808
809         if (PageWriteback(page) || PageDirty(page))
810                 return 0;
811
812         tree = &BTRFS_I(page->mapping->host)->io_tree;
813         map = &BTRFS_I(page->mapping->host)->extent_tree;
814
815         ret = try_release_extent_state(map, tree, page, gfp_flags);
816         if (!ret)
817                 return 0;
818
819         ret = try_release_extent_buffer(tree, page);
820         if (ret == 1) {
821                 ClearPagePrivate(page);
822                 set_page_private(page, 0);
823                 page_cache_release(page);
824         }
825
826         return ret;
827 }
828
829 static void btree_invalidatepage(struct page *page, unsigned long offset)
830 {
831         struct extent_io_tree *tree;
832         tree = &BTRFS_I(page->mapping->host)->io_tree;
833         extent_invalidatepage(tree, page, offset);
834         btree_releasepage(page, GFP_NOFS);
835         if (PagePrivate(page)) {
836                 printk(KERN_WARNING "btrfs warning page private not zero "
837                        "on page %llu\n", (unsigned long long)page_offset(page));
838                 ClearPagePrivate(page);
839                 set_page_private(page, 0);
840                 page_cache_release(page);
841         }
842 }
843
844 static const struct address_space_operations btree_aops = {
845         .readpage       = btree_readpage,
846         .writepage      = btree_writepage,
847         .writepages     = btree_writepages,
848         .releasepage    = btree_releasepage,
849         .invalidatepage = btree_invalidatepage,
850 #ifdef CONFIG_MIGRATION
851         .migratepage    = btree_migratepage,
852 #endif
853 };
854
855 int readahead_tree_block(struct btrfs_root *root, u64 bytenr, u32 blocksize,
856                          u64 parent_transid)
857 {
858         struct extent_buffer *buf = NULL;
859         struct inode *btree_inode = root->fs_info->btree_inode;
860         int ret = 0;
861
862         buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
863         if (!buf)
864                 return 0;
865         read_extent_buffer_pages(&BTRFS_I(btree_inode)->io_tree,
866                                  buf, 0, 0, btree_get_extent, 0);
867         free_extent_buffer(buf);
868         return ret;
869 }
870
871 struct extent_buffer *btrfs_find_tree_block(struct btrfs_root *root,
872                                             u64 bytenr, u32 blocksize)
873 {
874         struct inode *btree_inode = root->fs_info->btree_inode;
875         struct extent_buffer *eb;
876         eb = find_extent_buffer(&BTRFS_I(btree_inode)->io_tree,
877                                 bytenr, blocksize, GFP_NOFS);
878         return eb;
879 }
880
881 struct extent_buffer *btrfs_find_create_tree_block(struct btrfs_root *root,
882                                                  u64 bytenr, u32 blocksize)
883 {
884         struct inode *btree_inode = root->fs_info->btree_inode;
885         struct extent_buffer *eb;
886
887         eb = alloc_extent_buffer(&BTRFS_I(btree_inode)->io_tree,
888                                  bytenr, blocksize, NULL, GFP_NOFS);
889         return eb;
890 }
891
892
893 int btrfs_write_tree_block(struct extent_buffer *buf)
894 {
895         return filemap_fdatawrite_range(buf->first_page->mapping, buf->start,
896                                         buf->start + buf->len - 1);
897 }
898
899 int btrfs_wait_tree_block_writeback(struct extent_buffer *buf)
900 {
901         return filemap_fdatawait_range(buf->first_page->mapping,
902                                        buf->start, buf->start + buf->len - 1);
903 }
904
905 struct extent_buffer *read_tree_block(struct btrfs_root *root, u64 bytenr,
906                                       u32 blocksize, u64 parent_transid)
907 {
908         struct extent_buffer *buf = NULL;
909         int ret;
910
911         buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
912         if (!buf)
913                 return NULL;
914
915         ret = btree_read_extent_buffer_pages(root, buf, 0, parent_transid);
916
917         if (ret == 0)
918                 set_bit(EXTENT_BUFFER_UPTODATE, &buf->bflags);
919         return buf;
920
921 }
922
923 int clean_tree_block(struct btrfs_trans_handle *trans, struct btrfs_root *root,
924                      struct extent_buffer *buf)
925 {
926         struct inode *btree_inode = root->fs_info->btree_inode;
927         if (btrfs_header_generation(buf) ==
928             root->fs_info->running_transaction->transid) {
929                 btrfs_assert_tree_locked(buf);
930
931                 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
932                         spin_lock(&root->fs_info->delalloc_lock);
933                         if (root->fs_info->dirty_metadata_bytes >= buf->len)
934                                 root->fs_info->dirty_metadata_bytes -= buf->len;
935                         else
936                                 WARN_ON(1);
937                         spin_unlock(&root->fs_info->delalloc_lock);
938                 }
939
940                 /* ugh, clear_extent_buffer_dirty needs to lock the page */
941                 btrfs_set_lock_blocking(buf);
942                 clear_extent_buffer_dirty(&BTRFS_I(btree_inode)->io_tree,
943                                           buf);
944         }
945         return 0;
946 }
947
948 static int __setup_root(u32 nodesize, u32 leafsize, u32 sectorsize,
949                         u32 stripesize, struct btrfs_root *root,
950                         struct btrfs_fs_info *fs_info,
951                         u64 objectid)
952 {
953         root->node = NULL;
954         root->commit_root = NULL;
955         root->sectorsize = sectorsize;
956         root->nodesize = nodesize;
957         root->leafsize = leafsize;
958         root->stripesize = stripesize;
959         root->ref_cows = 0;
960         root->track_dirty = 0;
961         root->in_radix = 0;
962         root->orphan_item_inserted = 0;
963         root->orphan_cleanup_state = 0;
964
965         root->fs_info = fs_info;
966         root->objectid = objectid;
967         root->last_trans = 0;
968         root->highest_objectid = 0;
969         root->name = NULL;
970         root->in_sysfs = 0;
971         root->inode_tree = RB_ROOT;
972         root->block_rsv = NULL;
973         root->orphan_block_rsv = NULL;
974
975         INIT_LIST_HEAD(&root->dirty_list);
976         INIT_LIST_HEAD(&root->orphan_list);
977         INIT_LIST_HEAD(&root->root_list);
978         spin_lock_init(&root->node_lock);
979         spin_lock_init(&root->orphan_lock);
980         spin_lock_init(&root->inode_lock);
981         spin_lock_init(&root->accounting_lock);
982         mutex_init(&root->objectid_mutex);
983         mutex_init(&root->log_mutex);
984         init_waitqueue_head(&root->log_writer_wait);
985         init_waitqueue_head(&root->log_commit_wait[0]);
986         init_waitqueue_head(&root->log_commit_wait[1]);
987         atomic_set(&root->log_commit[0], 0);
988         atomic_set(&root->log_commit[1], 0);
989         atomic_set(&root->log_writers, 0);
990         root->log_batch = 0;
991         root->log_transid = 0;
992         root->last_log_commit = 0;
993         extent_io_tree_init(&root->dirty_log_pages,
994                              fs_info->btree_inode->i_mapping, GFP_NOFS);
995
996         memset(&root->root_key, 0, sizeof(root->root_key));
997         memset(&root->root_item, 0, sizeof(root->root_item));
998         memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
999         memset(&root->root_kobj, 0, sizeof(root->root_kobj));
1000         root->defrag_trans_start = fs_info->generation;
1001         init_completion(&root->kobj_unregister);
1002         root->defrag_running = 0;
1003         root->root_key.objectid = objectid;
1004         root->anon_super.s_root = NULL;
1005         root->anon_super.s_dev = 0;
1006         INIT_LIST_HEAD(&root->anon_super.s_list);
1007         INIT_LIST_HEAD(&root->anon_super.s_instances);
1008         init_rwsem(&root->anon_super.s_umount);
1009
1010         return 0;
1011 }
1012
1013 static int find_and_setup_root(struct btrfs_root *tree_root,
1014                                struct btrfs_fs_info *fs_info,
1015                                u64 objectid,
1016                                struct btrfs_root *root)
1017 {
1018         int ret;
1019         u32 blocksize;
1020         u64 generation;
1021
1022         __setup_root(tree_root->nodesize, tree_root->leafsize,
1023                      tree_root->sectorsize, tree_root->stripesize,
1024                      root, fs_info, objectid);
1025         ret = btrfs_find_last_root(tree_root, objectid,
1026                                    &root->root_item, &root->root_key);
1027         if (ret > 0)
1028                 return -ENOENT;
1029         BUG_ON(ret);
1030
1031         generation = btrfs_root_generation(&root->root_item);
1032         blocksize = btrfs_level_size(root, btrfs_root_level(&root->root_item));
1033         root->node = read_tree_block(root, btrfs_root_bytenr(&root->root_item),
1034                                      blocksize, generation);
1035         if (!root->node || !btrfs_buffer_uptodate(root->node, generation)) {
1036                 free_extent_buffer(root->node);
1037                 return -EIO;
1038         }
1039         root->commit_root = btrfs_root_node(root);
1040         return 0;
1041 }
1042
1043 static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
1044                                          struct btrfs_fs_info *fs_info)
1045 {
1046         struct btrfs_root *root;
1047         struct btrfs_root *tree_root = fs_info->tree_root;
1048         struct extent_buffer *leaf;
1049
1050         root = kzalloc(sizeof(*root), GFP_NOFS);
1051         if (!root)
1052                 return ERR_PTR(-ENOMEM);
1053
1054         __setup_root(tree_root->nodesize, tree_root->leafsize,
1055                      tree_root->sectorsize, tree_root->stripesize,
1056                      root, fs_info, BTRFS_TREE_LOG_OBJECTID);
1057
1058         root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
1059         root->root_key.type = BTRFS_ROOT_ITEM_KEY;
1060         root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
1061         /*
1062          * log trees do not get reference counted because they go away
1063          * before a real commit is actually done.  They do store pointers
1064          * to file data extents, and those reference counts still get
1065          * updated (along with back refs to the log tree).
1066          */
1067         root->ref_cows = 0;
1068
1069         leaf = btrfs_alloc_free_block(trans, root, root->leafsize, 0,
1070                                       BTRFS_TREE_LOG_OBJECTID, NULL, 0, 0, 0);
1071         if (IS_ERR(leaf)) {
1072                 kfree(root);
1073                 return ERR_CAST(leaf);
1074         }
1075
1076         memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
1077         btrfs_set_header_bytenr(leaf, leaf->start);
1078         btrfs_set_header_generation(leaf, trans->transid);
1079         btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
1080         btrfs_set_header_owner(leaf, BTRFS_TREE_LOG_OBJECTID);
1081         root->node = leaf;
1082
1083         write_extent_buffer(root->node, root->fs_info->fsid,
1084                             (unsigned long)btrfs_header_fsid(root->node),
1085                             BTRFS_FSID_SIZE);
1086         btrfs_mark_buffer_dirty(root->node);
1087         btrfs_tree_unlock(root->node);
1088         return root;
1089 }
1090
1091 int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
1092                              struct btrfs_fs_info *fs_info)
1093 {
1094         struct btrfs_root *log_root;
1095
1096         log_root = alloc_log_tree(trans, fs_info);
1097         if (IS_ERR(log_root))
1098                 return PTR_ERR(log_root);
1099         WARN_ON(fs_info->log_root_tree);
1100         fs_info->log_root_tree = log_root;
1101         return 0;
1102 }
1103
1104 int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
1105                        struct btrfs_root *root)
1106 {
1107         struct btrfs_root *log_root;
1108         struct btrfs_inode_item *inode_item;
1109
1110         log_root = alloc_log_tree(trans, root->fs_info);
1111         if (IS_ERR(log_root))
1112                 return PTR_ERR(log_root);
1113
1114         log_root->last_trans = trans->transid;
1115         log_root->root_key.offset = root->root_key.objectid;
1116
1117         inode_item = &log_root->root_item.inode;
1118         inode_item->generation = cpu_to_le64(1);
1119         inode_item->size = cpu_to_le64(3);
1120         inode_item->nlink = cpu_to_le32(1);
1121         inode_item->nbytes = cpu_to_le64(root->leafsize);
1122         inode_item->mode = cpu_to_le32(S_IFDIR | 0755);
1123
1124         btrfs_set_root_node(&log_root->root_item, log_root->node);
1125
1126         WARN_ON(root->log_root);
1127         root->log_root = log_root;
1128         root->log_transid = 0;
1129         root->last_log_commit = 0;
1130         return 0;
1131 }
1132
1133 struct btrfs_root *btrfs_read_fs_root_no_radix(struct btrfs_root *tree_root,
1134                                                struct btrfs_key *location)
1135 {
1136         struct btrfs_root *root;
1137         struct btrfs_fs_info *fs_info = tree_root->fs_info;
1138         struct btrfs_path *path;
1139         struct extent_buffer *l;
1140         u64 generation;
1141         u32 blocksize;
1142         int ret = 0;
1143
1144         root = kzalloc(sizeof(*root), GFP_NOFS);
1145         if (!root)
1146                 return ERR_PTR(-ENOMEM);
1147         if (location->offset == (u64)-1) {
1148                 ret = find_and_setup_root(tree_root, fs_info,
1149                                           location->objectid, root);
1150                 if (ret) {
1151                         kfree(root);
1152                         return ERR_PTR(ret);
1153                 }
1154                 goto out;
1155         }
1156
1157         __setup_root(tree_root->nodesize, tree_root->leafsize,
1158                      tree_root->sectorsize, tree_root->stripesize,
1159                      root, fs_info, location->objectid);
1160
1161         path = btrfs_alloc_path();
1162         BUG_ON(!path);
1163         ret = btrfs_search_slot(NULL, tree_root, location, path, 0, 0);
1164         if (ret == 0) {
1165                 l = path->nodes[0];
1166                 read_extent_buffer(l, &root->root_item,
1167                                 btrfs_item_ptr_offset(l, path->slots[0]),
1168                                 sizeof(root->root_item));
1169                 memcpy(&root->root_key, location, sizeof(*location));
1170         }
1171         btrfs_free_path(path);
1172         if (ret) {
1173                 kfree(root);
1174                 if (ret > 0)
1175                         ret = -ENOENT;
1176                 return ERR_PTR(ret);
1177         }
1178
1179         generation = btrfs_root_generation(&root->root_item);
1180         blocksize = btrfs_level_size(root, btrfs_root_level(&root->root_item));
1181         root->node = read_tree_block(root, btrfs_root_bytenr(&root->root_item),
1182                                      blocksize, generation);
1183         root->commit_root = btrfs_root_node(root);
1184         BUG_ON(!root->node);
1185 out:
1186         if (location->objectid != BTRFS_TREE_LOG_OBJECTID)
1187                 root->ref_cows = 1;
1188
1189         return root;
1190 }
1191
1192 struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
1193                                         u64 root_objectid)
1194 {
1195         struct btrfs_root *root;
1196
1197         if (root_objectid == BTRFS_ROOT_TREE_OBJECTID)
1198                 return fs_info->tree_root;
1199         if (root_objectid == BTRFS_EXTENT_TREE_OBJECTID)
1200                 return fs_info->extent_root;
1201
1202         root = radix_tree_lookup(&fs_info->fs_roots_radix,
1203                                  (unsigned long)root_objectid);
1204         return root;
1205 }
1206
1207 struct btrfs_root *btrfs_read_fs_root_no_name(struct btrfs_fs_info *fs_info,
1208                                               struct btrfs_key *location)
1209 {
1210         struct btrfs_root *root;
1211         int ret;
1212
1213         if (location->objectid == BTRFS_ROOT_TREE_OBJECTID)
1214                 return fs_info->tree_root;
1215         if (location->objectid == BTRFS_EXTENT_TREE_OBJECTID)
1216                 return fs_info->extent_root;
1217         if (location->objectid == BTRFS_CHUNK_TREE_OBJECTID)
1218                 return fs_info->chunk_root;
1219         if (location->objectid == BTRFS_DEV_TREE_OBJECTID)
1220                 return fs_info->dev_root;
1221         if (location->objectid == BTRFS_CSUM_TREE_OBJECTID)
1222                 return fs_info->csum_root;
1223 again:
1224         spin_lock(&fs_info->fs_roots_radix_lock);
1225         root = radix_tree_lookup(&fs_info->fs_roots_radix,
1226                                  (unsigned long)location->objectid);
1227         spin_unlock(&fs_info->fs_roots_radix_lock);
1228         if (root)
1229                 return root;
1230
1231         root = btrfs_read_fs_root_no_radix(fs_info->tree_root, location);
1232         if (IS_ERR(root))
1233                 return root;
1234
1235         set_anon_super(&root->anon_super, NULL);
1236
1237         if (btrfs_root_refs(&root->root_item) == 0) {
1238                 ret = -ENOENT;
1239                 goto fail;
1240         }
1241
1242         ret = btrfs_find_orphan_item(fs_info->tree_root, location->objectid);
1243         if (ret < 0)
1244                 goto fail;
1245         if (ret == 0)
1246                 root->orphan_item_inserted = 1;
1247
1248         ret = radix_tree_preload(GFP_NOFS & ~__GFP_HIGHMEM);
1249         if (ret)
1250                 goto fail;
1251
1252         spin_lock(&fs_info->fs_roots_radix_lock);
1253         ret = radix_tree_insert(&fs_info->fs_roots_radix,
1254                                 (unsigned long)root->root_key.objectid,
1255                                 root);
1256         if (ret == 0)
1257                 root->in_radix = 1;
1258
1259         spin_unlock(&fs_info->fs_roots_radix_lock);
1260         radix_tree_preload_end();
1261         if (ret) {
1262                 if (ret == -EEXIST) {
1263                         free_fs_root(root);
1264                         goto again;
1265                 }
1266                 goto fail;
1267         }
1268
1269         ret = btrfs_find_dead_roots(fs_info->tree_root,
1270                                     root->root_key.objectid);
1271         WARN_ON(ret);
1272         return root;
1273 fail:
1274         free_fs_root(root);
1275         return ERR_PTR(ret);
1276 }
1277
1278 struct btrfs_root *btrfs_read_fs_root(struct btrfs_fs_info *fs_info,
1279                                       struct btrfs_key *location,
1280                                       const char *name, int namelen)
1281 {
1282         return btrfs_read_fs_root_no_name(fs_info, location);
1283 #if 0
1284         struct btrfs_root *root;
1285         int ret;
1286
1287         root = btrfs_read_fs_root_no_name(fs_info, location);
1288         if (!root)
1289                 return NULL;
1290
1291         if (root->in_sysfs)
1292                 return root;
1293
1294         ret = btrfs_set_root_name(root, name, namelen);
1295         if (ret) {
1296                 free_extent_buffer(root->node);
1297                 kfree(root);
1298                 return ERR_PTR(ret);
1299         }
1300
1301         ret = btrfs_sysfs_add_root(root);
1302         if (ret) {
1303                 free_extent_buffer(root->node);
1304                 kfree(root->name);
1305                 kfree(root);
1306                 return ERR_PTR(ret);
1307         }
1308         root->in_sysfs = 1;
1309         return root;
1310 #endif
1311 }
1312
1313 static int btrfs_congested_fn(void *congested_data, int bdi_bits)
1314 {
1315         struct btrfs_fs_info *info = (struct btrfs_fs_info *)congested_data;
1316         int ret = 0;
1317         struct btrfs_device *device;
1318         struct backing_dev_info *bdi;
1319
1320         list_for_each_entry(device, &info->fs_devices->devices, dev_list) {
1321                 if (!device->bdev)
1322                         continue;
1323                 bdi = blk_get_backing_dev_info(device->bdev);
1324                 if (bdi && bdi_congested(bdi, bdi_bits)) {
1325                         ret = 1;
1326                         break;
1327                 }
1328         }
1329         return ret;
1330 }
1331
1332 /*
1333  * If this fails, caller must call bdi_destroy() to get rid of the
1334  * bdi again.
1335  */
1336 static int setup_bdi(struct btrfs_fs_info *info, struct backing_dev_info *bdi)
1337 {
1338         int err;
1339
1340         bdi->capabilities = BDI_CAP_MAP_COPY;
1341         err = bdi_setup_and_register(bdi, "btrfs", BDI_CAP_MAP_COPY);
1342         if (err)
1343                 return err;
1344
1345         bdi->ra_pages   = default_backing_dev_info.ra_pages;
1346         bdi->congested_fn       = btrfs_congested_fn;
1347         bdi->congested_data     = info;
1348         return 0;
1349 }
1350
1351 static int bio_ready_for_csum(struct bio *bio)
1352 {
1353         u64 length = 0;
1354         u64 buf_len = 0;
1355         u64 start = 0;
1356         struct page *page;
1357         struct extent_io_tree *io_tree = NULL;
1358         struct bio_vec *bvec;
1359         int i;
1360         int ret;
1361
1362         bio_for_each_segment(bvec, bio, i) {
1363                 page = bvec->bv_page;
1364                 if (page->private == EXTENT_PAGE_PRIVATE) {
1365                         length += bvec->bv_len;
1366                         continue;
1367                 }
1368                 if (!page->private) {
1369                         length += bvec->bv_len;
1370                         continue;
1371                 }
1372                 length = bvec->bv_len;
1373                 buf_len = page->private >> 2;
1374                 start = page_offset(page) + bvec->bv_offset;
1375                 io_tree = &BTRFS_I(page->mapping->host)->io_tree;
1376         }
1377         /* are we fully contained in this bio? */
1378         if (buf_len <= length)
1379                 return 1;
1380
1381         ret = extent_range_uptodate(io_tree, start + length,
1382                                     start + buf_len - 1);
1383         return ret;
1384 }
1385
1386 /*
1387  * called by the kthread helper functions to finally call the bio end_io
1388  * functions.  This is where read checksum verification actually happens
1389  */
1390 static void end_workqueue_fn(struct btrfs_work *work)
1391 {
1392         struct bio *bio;
1393         struct end_io_wq *end_io_wq;
1394         struct btrfs_fs_info *fs_info;
1395         int error;
1396
1397         end_io_wq = container_of(work, struct end_io_wq, work);
1398         bio = end_io_wq->bio;
1399         fs_info = end_io_wq->info;
1400
1401         /* metadata bio reads are special because the whole tree block must
1402          * be checksummed at once.  This makes sure the entire block is in
1403          * ram and up to date before trying to verify things.  For
1404          * blocksize <= pagesize, it is basically a noop
1405          */
1406         if (!(bio->bi_rw & REQ_WRITE) && end_io_wq->metadata &&
1407             !bio_ready_for_csum(bio)) {
1408                 btrfs_queue_worker(&fs_info->endio_meta_workers,
1409                                    &end_io_wq->work);
1410                 return;
1411         }
1412         error = end_io_wq->error;
1413         bio->bi_private = end_io_wq->private;
1414         bio->bi_end_io = end_io_wq->end_io;
1415         kfree(end_io_wq);
1416         bio_endio(bio, error);
1417 }
1418
1419 static int cleaner_kthread(void *arg)
1420 {
1421         struct btrfs_root *root = arg;
1422
1423         do {
1424                 vfs_check_frozen(root->fs_info->sb, SB_FREEZE_WRITE);
1425
1426                 if (!(root->fs_info->sb->s_flags & MS_RDONLY) &&
1427                     mutex_trylock(&root->fs_info->cleaner_mutex)) {
1428                         btrfs_run_delayed_iputs(root);
1429                         btrfs_clean_old_snapshots(root);
1430                         mutex_unlock(&root->fs_info->cleaner_mutex);
1431                 }
1432
1433                 if (freezing(current)) {
1434                         refrigerator();
1435                 } else {
1436                         set_current_state(TASK_INTERRUPTIBLE);
1437                         if (!kthread_should_stop())
1438                                 schedule();
1439                         __set_current_state(TASK_RUNNING);
1440                 }
1441         } while (!kthread_should_stop());
1442         return 0;
1443 }
1444
1445 static int transaction_kthread(void *arg)
1446 {
1447         struct btrfs_root *root = arg;
1448         struct btrfs_trans_handle *trans;
1449         struct btrfs_transaction *cur;
1450         u64 transid;
1451         unsigned long now;
1452         unsigned long delay;
1453         int ret;
1454
1455         do {
1456                 delay = HZ * 30;
1457                 vfs_check_frozen(root->fs_info->sb, SB_FREEZE_WRITE);
1458                 mutex_lock(&root->fs_info->transaction_kthread_mutex);
1459
1460                 spin_lock(&root->fs_info->new_trans_lock);
1461                 cur = root->fs_info->running_transaction;
1462                 if (!cur) {
1463                         spin_unlock(&root->fs_info->new_trans_lock);
1464                         goto sleep;
1465                 }
1466
1467                 now = get_seconds();
1468                 if (!cur->blocked &&
1469                     (now < cur->start_time || now - cur->start_time < 30)) {
1470                         spin_unlock(&root->fs_info->new_trans_lock);
1471                         delay = HZ * 5;
1472                         goto sleep;
1473                 }
1474                 transid = cur->transid;
1475                 spin_unlock(&root->fs_info->new_trans_lock);
1476
1477                 trans = btrfs_join_transaction(root, 1);
1478                 BUG_ON(IS_ERR(trans));
1479                 if (transid == trans->transid) {
1480                         ret = btrfs_commit_transaction(trans, root);
1481                         BUG_ON(ret);
1482                 } else {
1483                         btrfs_end_transaction(trans, root);
1484                 }
1485 sleep:
1486                 wake_up_process(root->fs_info->cleaner_kthread);
1487                 mutex_unlock(&root->fs_info->transaction_kthread_mutex);
1488
1489                 if (freezing(current)) {
1490                         refrigerator();
1491                 } else {
1492                         set_current_state(TASK_INTERRUPTIBLE);
1493                         if (!kthread_should_stop() &&
1494                             !btrfs_transaction_blocked(root->fs_info))
1495                                 schedule_timeout(delay);
1496                         __set_current_state(TASK_RUNNING);
1497                 }
1498         } while (!kthread_should_stop());
1499         return 0;
1500 }
1501
1502 struct btrfs_root *open_ctree(struct super_block *sb,
1503                               struct btrfs_fs_devices *fs_devices,
1504                               char *options)
1505 {
1506         u32 sectorsize;
1507         u32 nodesize;
1508         u32 leafsize;
1509         u32 blocksize;
1510         u32 stripesize;
1511         u64 generation;
1512         u64 features;
1513         struct btrfs_key location;
1514         struct buffer_head *bh;
1515         struct btrfs_root *extent_root = kzalloc(sizeof(struct btrfs_root),
1516                                                  GFP_NOFS);
1517         struct btrfs_root *csum_root = kzalloc(sizeof(struct btrfs_root),
1518                                                  GFP_NOFS);
1519         struct btrfs_root *tree_root = btrfs_sb(sb);
1520         struct btrfs_fs_info *fs_info = tree_root->fs_info;
1521         struct btrfs_root *chunk_root = kzalloc(sizeof(struct btrfs_root),
1522                                                 GFP_NOFS);
1523         struct btrfs_root *dev_root = kzalloc(sizeof(struct btrfs_root),
1524                                               GFP_NOFS);
1525         struct btrfs_root *log_tree_root;
1526
1527         int ret;
1528         int err = -EINVAL;
1529
1530         struct btrfs_super_block *disk_super;
1531
1532         if (!extent_root || !tree_root || !fs_info ||
1533             !chunk_root || !dev_root || !csum_root) {
1534                 err = -ENOMEM;
1535                 goto fail;
1536         }
1537
1538         ret = init_srcu_struct(&fs_info->subvol_srcu);
1539         if (ret) {
1540                 err = ret;
1541                 goto fail;
1542         }
1543
1544         ret = setup_bdi(fs_info, &fs_info->bdi);
1545         if (ret) {
1546                 err = ret;
1547                 goto fail_srcu;
1548         }
1549
1550         fs_info->btree_inode = new_inode(sb);
1551         if (!fs_info->btree_inode) {
1552                 err = -ENOMEM;
1553                 goto fail_bdi;
1554         }
1555
1556         INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
1557         INIT_LIST_HEAD(&fs_info->trans_list);
1558         INIT_LIST_HEAD(&fs_info->dead_roots);
1559         INIT_LIST_HEAD(&fs_info->delayed_iputs);
1560         INIT_LIST_HEAD(&fs_info->hashers);
1561         INIT_LIST_HEAD(&fs_info->delalloc_inodes);
1562         INIT_LIST_HEAD(&fs_info->ordered_operations);
1563         INIT_LIST_HEAD(&fs_info->caching_block_groups);
1564         spin_lock_init(&fs_info->delalloc_lock);
1565         spin_lock_init(&fs_info->new_trans_lock);
1566         spin_lock_init(&fs_info->ref_cache_lock);
1567         spin_lock_init(&fs_info->fs_roots_radix_lock);
1568         spin_lock_init(&fs_info->delayed_iput_lock);
1569
1570         init_completion(&fs_info->kobj_unregister);
1571         fs_info->tree_root = tree_root;
1572         fs_info->extent_root = extent_root;
1573         fs_info->csum_root = csum_root;
1574         fs_info->chunk_root = chunk_root;
1575         fs_info->dev_root = dev_root;
1576         fs_info->fs_devices = fs_devices;
1577         INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
1578         INIT_LIST_HEAD(&fs_info->space_info);
1579         btrfs_mapping_init(&fs_info->mapping_tree);
1580         btrfs_init_block_rsv(&fs_info->global_block_rsv);
1581         btrfs_init_block_rsv(&fs_info->delalloc_block_rsv);
1582         btrfs_init_block_rsv(&fs_info->trans_block_rsv);
1583         btrfs_init_block_rsv(&fs_info->chunk_block_rsv);
1584         btrfs_init_block_rsv(&fs_info->empty_block_rsv);
1585         INIT_LIST_HEAD(&fs_info->durable_block_rsv_list);
1586         mutex_init(&fs_info->durable_block_rsv_mutex);
1587         atomic_set(&fs_info->nr_async_submits, 0);
1588         atomic_set(&fs_info->async_delalloc_pages, 0);
1589         atomic_set(&fs_info->async_submit_draining, 0);
1590         atomic_set(&fs_info->nr_async_bios, 0);
1591         fs_info->sb = sb;
1592         fs_info->max_inline = 8192 * 1024;
1593         fs_info->metadata_ratio = 0;
1594
1595         fs_info->thread_pool_size = min_t(unsigned long,
1596                                           num_online_cpus() + 2, 8);
1597
1598         INIT_LIST_HEAD(&fs_info->ordered_extents);
1599         spin_lock_init(&fs_info->ordered_extent_lock);
1600
1601         sb->s_blocksize = 4096;
1602         sb->s_blocksize_bits = blksize_bits(4096);
1603         sb->s_bdi = &fs_info->bdi;
1604
1605         fs_info->btree_inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
1606         fs_info->btree_inode->i_nlink = 1;
1607         /*
1608          * we set the i_size on the btree inode to the max possible int.
1609          * the real end of the address space is determined by all of
1610          * the devices in the system
1611          */
1612         fs_info->btree_inode->i_size = OFFSET_MAX;
1613         fs_info->btree_inode->i_mapping->a_ops = &btree_aops;
1614         fs_info->btree_inode->i_mapping->backing_dev_info = &fs_info->bdi;
1615
1616         RB_CLEAR_NODE(&BTRFS_I(fs_info->btree_inode)->rb_node);
1617         extent_io_tree_init(&BTRFS_I(fs_info->btree_inode)->io_tree,
1618                              fs_info->btree_inode->i_mapping,
1619                              GFP_NOFS);
1620         extent_map_tree_init(&BTRFS_I(fs_info->btree_inode)->extent_tree,
1621                              GFP_NOFS);
1622
1623         BTRFS_I(fs_info->btree_inode)->io_tree.ops = &btree_extent_io_ops;
1624
1625         BTRFS_I(fs_info->btree_inode)->root = tree_root;
1626         memset(&BTRFS_I(fs_info->btree_inode)->location, 0,
1627                sizeof(struct btrfs_key));
1628         BTRFS_I(fs_info->btree_inode)->dummy_inode = 1;
1629         insert_inode_hash(fs_info->btree_inode);
1630
1631         spin_lock_init(&fs_info->block_group_cache_lock);
1632         fs_info->block_group_cache_tree = RB_ROOT;
1633
1634         extent_io_tree_init(&fs_info->freed_extents[0],
1635                              fs_info->btree_inode->i_mapping, GFP_NOFS);
1636         extent_io_tree_init(&fs_info->freed_extents[1],
1637                              fs_info->btree_inode->i_mapping, GFP_NOFS);
1638         fs_info->pinned_extents = &fs_info->freed_extents[0];
1639         fs_info->do_barriers = 1;
1640
1641
1642         mutex_init(&fs_info->trans_mutex);
1643         mutex_init(&fs_info->ordered_operations_mutex);
1644         mutex_init(&fs_info->tree_log_mutex);
1645         mutex_init(&fs_info->chunk_mutex);
1646         mutex_init(&fs_info->transaction_kthread_mutex);
1647         mutex_init(&fs_info->cleaner_mutex);
1648         mutex_init(&fs_info->volume_mutex);
1649         init_rwsem(&fs_info->extent_commit_sem);
1650         init_rwsem(&fs_info->cleanup_work_sem);
1651         init_rwsem(&fs_info->subvol_sem);
1652
1653         btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
1654         btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
1655
1656         init_waitqueue_head(&fs_info->transaction_throttle);
1657         init_waitqueue_head(&fs_info->transaction_wait);
1658         init_waitqueue_head(&fs_info->transaction_blocked_wait);
1659         init_waitqueue_head(&fs_info->async_submit_wait);
1660
1661         __setup_root(4096, 4096, 4096, 4096, tree_root,
1662                      fs_info, BTRFS_ROOT_TREE_OBJECTID);
1663
1664         bh = btrfs_read_dev_super(fs_devices->latest_bdev);
1665         if (!bh) {
1666                 err = -EINVAL;
1667                 goto fail_iput;
1668         }
1669
1670         memcpy(&fs_info->super_copy, bh->b_data, sizeof(fs_info->super_copy));
1671         memcpy(&fs_info->super_for_commit, &fs_info->super_copy,
1672                sizeof(fs_info->super_for_commit));
1673         brelse(bh);
1674
1675         memcpy(fs_info->fsid, fs_info->super_copy.fsid, BTRFS_FSID_SIZE);
1676
1677         disk_super = &fs_info->super_copy;
1678         if (!btrfs_super_root(disk_super))
1679                 goto fail_iput;
1680
1681         /* check FS state, whether FS is broken. */
1682         fs_info->fs_state |= btrfs_super_flags(disk_super);
1683
1684         btrfs_check_super_valid(fs_info, sb->s_flags & MS_RDONLY);
1685
1686         ret = btrfs_parse_options(tree_root, options);
1687         if (ret) {
1688                 err = ret;
1689                 goto fail_iput;
1690         }
1691
1692         features = btrfs_super_incompat_flags(disk_super) &
1693                 ~BTRFS_FEATURE_INCOMPAT_SUPP;
1694         if (features) {
1695                 printk(KERN_ERR "BTRFS: couldn't mount because of "
1696                        "unsupported optional features (%Lx).\n",
1697                        (unsigned long long)features);
1698                 err = -EINVAL;
1699                 goto fail_iput;
1700         }
1701
1702         features = btrfs_super_incompat_flags(disk_super);
1703         features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
1704         if (tree_root->fs_info->compress_type & BTRFS_COMPRESS_LZO)
1705                 features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
1706         btrfs_set_super_incompat_flags(disk_super, features);
1707
1708         features = btrfs_super_compat_ro_flags(disk_super) &
1709                 ~BTRFS_FEATURE_COMPAT_RO_SUPP;
1710         if (!(sb->s_flags & MS_RDONLY) && features) {
1711                 printk(KERN_ERR "BTRFS: couldn't mount RDWR because of "
1712                        "unsupported option features (%Lx).\n",
1713                        (unsigned long long)features);
1714                 err = -EINVAL;
1715                 goto fail_iput;
1716         }
1717
1718         btrfs_init_workers(&fs_info->generic_worker,
1719                            "genwork", 1, NULL);
1720
1721         btrfs_init_workers(&fs_info->workers, "worker",
1722                            fs_info->thread_pool_size,
1723                            &fs_info->generic_worker);
1724
1725         btrfs_init_workers(&fs_info->delalloc_workers, "delalloc",
1726                            fs_info->thread_pool_size,
1727                            &fs_info->generic_worker);
1728
1729         btrfs_init_workers(&fs_info->submit_workers, "submit",
1730                            min_t(u64, fs_devices->num_devices,
1731                            fs_info->thread_pool_size),
1732                            &fs_info->generic_worker);
1733
1734         /* a higher idle thresh on the submit workers makes it much more
1735          * likely that bios will be send down in a sane order to the
1736          * devices
1737          */
1738         fs_info->submit_workers.idle_thresh = 64;
1739
1740         fs_info->workers.idle_thresh = 16;
1741         fs_info->workers.ordered = 1;
1742
1743         fs_info->delalloc_workers.idle_thresh = 2;
1744         fs_info->delalloc_workers.ordered = 1;
1745
1746         btrfs_init_workers(&fs_info->fixup_workers, "fixup", 1,
1747                            &fs_info->generic_worker);
1748         btrfs_init_workers(&fs_info->endio_workers, "endio",
1749                            fs_info->thread_pool_size,
1750                            &fs_info->generic_worker);
1751         btrfs_init_workers(&fs_info->endio_meta_workers, "endio-meta",
1752                            fs_info->thread_pool_size,
1753                            &fs_info->generic_worker);
1754         btrfs_init_workers(&fs_info->endio_meta_write_workers,
1755                            "endio-meta-write", fs_info->thread_pool_size,
1756                            &fs_info->generic_worker);
1757         btrfs_init_workers(&fs_info->endio_write_workers, "endio-write",
1758                            fs_info->thread_pool_size,
1759                            &fs_info->generic_worker);
1760         btrfs_init_workers(&fs_info->endio_freespace_worker, "freespace-write",
1761                            1, &fs_info->generic_worker);
1762
1763         /*
1764          * endios are largely parallel and should have a very
1765          * low idle thresh
1766          */
1767         fs_info->endio_workers.idle_thresh = 4;
1768         fs_info->endio_meta_workers.idle_thresh = 4;
1769
1770         fs_info->endio_write_workers.idle_thresh = 2;
1771         fs_info->endio_meta_write_workers.idle_thresh = 2;
1772
1773         btrfs_start_workers(&fs_info->workers, 1);
1774         btrfs_start_workers(&fs_info->generic_worker, 1);
1775         btrfs_start_workers(&fs_info->submit_workers, 1);
1776         btrfs_start_workers(&fs_info->delalloc_workers, 1);
1777         btrfs_start_workers(&fs_info->fixup_workers, 1);
1778         btrfs_start_workers(&fs_info->endio_workers, 1);
1779         btrfs_start_workers(&fs_info->endio_meta_workers, 1);
1780         btrfs_start_workers(&fs_info->endio_meta_write_workers, 1);
1781         btrfs_start_workers(&fs_info->endio_write_workers, 1);
1782         btrfs_start_workers(&fs_info->endio_freespace_worker, 1);
1783
1784         fs_info->bdi.ra_pages *= btrfs_super_num_devices(disk_super);
1785         fs_info->bdi.ra_pages = max(fs_info->bdi.ra_pages,
1786                                     4 * 1024 * 1024 / PAGE_CACHE_SIZE);
1787
1788         nodesize = btrfs_super_nodesize(disk_super);
1789         leafsize = btrfs_super_leafsize(disk_super);
1790         sectorsize = btrfs_super_sectorsize(disk_super);
1791         stripesize = btrfs_super_stripesize(disk_super);
1792         tree_root->nodesize = nodesize;
1793         tree_root->leafsize = leafsize;
1794         tree_root->sectorsize = sectorsize;
1795         tree_root->stripesize = stripesize;
1796
1797         sb->s_blocksize = sectorsize;
1798         sb->s_blocksize_bits = blksize_bits(sectorsize);
1799
1800         if (strncmp((char *)(&disk_super->magic), BTRFS_MAGIC,
1801                     sizeof(disk_super->magic))) {
1802                 printk(KERN_INFO "btrfs: valid FS not found on %s\n", sb->s_id);
1803                 goto fail_sb_buffer;
1804         }
1805
1806         mutex_lock(&fs_info->chunk_mutex);
1807         ret = btrfs_read_sys_array(tree_root);
1808         mutex_unlock(&fs_info->chunk_mutex);
1809         if (ret) {
1810                 printk(KERN_WARNING "btrfs: failed to read the system "
1811                        "array on %s\n", sb->s_id);
1812                 goto fail_sb_buffer;
1813         }
1814
1815         blocksize = btrfs_level_size(tree_root,
1816                                      btrfs_super_chunk_root_level(disk_super));
1817         generation = btrfs_super_chunk_root_generation(disk_super);
1818
1819         __setup_root(nodesize, leafsize, sectorsize, stripesize,
1820                      chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
1821
1822         chunk_root->node = read_tree_block(chunk_root,
1823                                            btrfs_super_chunk_root(disk_super),
1824                                            blocksize, generation);
1825         BUG_ON(!chunk_root->node);
1826         if (!test_bit(EXTENT_BUFFER_UPTODATE, &chunk_root->node->bflags)) {
1827                 printk(KERN_WARNING "btrfs: failed to read chunk root on %s\n",
1828                        sb->s_id);
1829                 goto fail_chunk_root;
1830         }
1831         btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
1832         chunk_root->commit_root = btrfs_root_node(chunk_root);
1833
1834         read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
1835            (unsigned long)btrfs_header_chunk_tree_uuid(chunk_root->node),
1836            BTRFS_UUID_SIZE);
1837
1838         mutex_lock(&fs_info->chunk_mutex);
1839         ret = btrfs_read_chunk_tree(chunk_root);
1840         mutex_unlock(&fs_info->chunk_mutex);
1841         if (ret) {
1842                 printk(KERN_WARNING "btrfs: failed to read chunk tree on %s\n",
1843                        sb->s_id);
1844                 goto fail_chunk_root;
1845         }
1846
1847         btrfs_close_extra_devices(fs_devices);
1848
1849         blocksize = btrfs_level_size(tree_root,
1850                                      btrfs_super_root_level(disk_super));
1851         generation = btrfs_super_generation(disk_super);
1852
1853         tree_root->node = read_tree_block(tree_root,
1854                                           btrfs_super_root(disk_super),
1855                                           blocksize, generation);
1856         if (!tree_root->node)
1857                 goto fail_chunk_root;
1858         if (!test_bit(EXTENT_BUFFER_UPTODATE, &tree_root->node->bflags)) {
1859                 printk(KERN_WARNING "btrfs: failed to read tree root on %s\n",
1860                        sb->s_id);
1861                 goto fail_tree_root;
1862         }
1863         btrfs_set_root_node(&tree_root->root_item, tree_root->node);
1864         tree_root->commit_root = btrfs_root_node(tree_root);
1865
1866         ret = find_and_setup_root(tree_root, fs_info,
1867                                   BTRFS_EXTENT_TREE_OBJECTID, extent_root);
1868         if (ret)
1869                 goto fail_tree_root;
1870         extent_root->track_dirty = 1;
1871
1872         ret = find_and_setup_root(tree_root, fs_info,
1873                                   BTRFS_DEV_TREE_OBJECTID, dev_root);
1874         if (ret)
1875                 goto fail_extent_root;
1876         dev_root->track_dirty = 1;
1877
1878         ret = find_and_setup_root(tree_root, fs_info,
1879                                   BTRFS_CSUM_TREE_OBJECTID, csum_root);
1880         if (ret)
1881                 goto fail_dev_root;
1882
1883         csum_root->track_dirty = 1;
1884
1885         fs_info->generation = generation;
1886         fs_info->last_trans_committed = generation;
1887         fs_info->data_alloc_profile = (u64)-1;
1888         fs_info->metadata_alloc_profile = (u64)-1;
1889         fs_info->system_alloc_profile = fs_info->metadata_alloc_profile;
1890
1891         ret = btrfs_read_block_groups(extent_root);
1892         if (ret) {
1893                 printk(KERN_ERR "Failed to read block groups: %d\n", ret);
1894                 goto fail_block_groups;
1895         }
1896
1897         fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
1898                                                "btrfs-cleaner");
1899         if (IS_ERR(fs_info->cleaner_kthread))
1900                 goto fail_block_groups;
1901
1902         fs_info->transaction_kthread = kthread_run(transaction_kthread,
1903                                                    tree_root,
1904                                                    "btrfs-transaction");
1905         if (IS_ERR(fs_info->transaction_kthread))
1906                 goto fail_cleaner;
1907
1908         if (!btrfs_test_opt(tree_root, SSD) &&
1909             !btrfs_test_opt(tree_root, NOSSD) &&
1910             !fs_info->fs_devices->rotating) {
1911                 printk(KERN_INFO "Btrfs detected SSD devices, enabling SSD "
1912                        "mode\n");
1913                 btrfs_set_opt(fs_info->mount_opt, SSD);
1914         }
1915
1916         /* do not make disk changes in broken FS */
1917         if (btrfs_super_log_root(disk_super) != 0 &&
1918             !(fs_info->fs_state & BTRFS_SUPER_FLAG_ERROR)) {
1919                 u64 bytenr = btrfs_super_log_root(disk_super);
1920
1921                 if (fs_devices->rw_devices == 0) {
1922                         printk(KERN_WARNING "Btrfs log replay required "
1923                                "on RO media\n");
1924                         err = -EIO;
1925                         goto fail_trans_kthread;
1926                 }
1927                 blocksize =
1928                      btrfs_level_size(tree_root,
1929                                       btrfs_super_log_root_level(disk_super));
1930
1931                 log_tree_root = kzalloc(sizeof(struct btrfs_root), GFP_NOFS);
1932                 if (!log_tree_root) {
1933                         err = -ENOMEM;
1934                         goto fail_trans_kthread;
1935                 }
1936
1937                 __setup_root(nodesize, leafsize, sectorsize, stripesize,
1938                              log_tree_root, fs_info, BTRFS_TREE_LOG_OBJECTID);
1939
1940                 log_tree_root->node = read_tree_block(tree_root, bytenr,
1941                                                       blocksize,
1942                                                       generation + 1);
1943                 ret = btrfs_recover_log_trees(log_tree_root);
1944                 BUG_ON(ret);
1945
1946                 if (sb->s_flags & MS_RDONLY) {
1947                         ret =  btrfs_commit_super(tree_root);
1948                         BUG_ON(ret);
1949                 }
1950         }
1951
1952         ret = btrfs_find_orphan_roots(tree_root);
1953         BUG_ON(ret);
1954
1955         if (!(sb->s_flags & MS_RDONLY)) {
1956                 ret = btrfs_cleanup_fs_roots(fs_info);
1957                 BUG_ON(ret);
1958
1959                 ret = btrfs_recover_relocation(tree_root);
1960                 if (ret < 0) {
1961                         printk(KERN_WARNING
1962                                "btrfs: failed to recover relocation\n");
1963                         err = -EINVAL;
1964                         goto fail_trans_kthread;
1965                 }
1966         }
1967
1968         location.objectid = BTRFS_FS_TREE_OBJECTID;
1969         location.type = BTRFS_ROOT_ITEM_KEY;
1970         location.offset = (u64)-1;
1971
1972         fs_info->fs_root = btrfs_read_fs_root_no_name(fs_info, &location);
1973         if (!fs_info->fs_root)
1974                 goto fail_trans_kthread;
1975         if (IS_ERR(fs_info->fs_root)) {
1976                 err = PTR_ERR(fs_info->fs_root);
1977                 goto fail_trans_kthread;
1978         }
1979
1980         if (!(sb->s_flags & MS_RDONLY)) {
1981                 down_read(&fs_info->cleanup_work_sem);
1982                 btrfs_orphan_cleanup(fs_info->fs_root);
1983                 btrfs_orphan_cleanup(fs_info->tree_root);
1984                 up_read(&fs_info->cleanup_work_sem);
1985         }
1986
1987         return tree_root;
1988
1989 fail_trans_kthread:
1990         kthread_stop(fs_info->transaction_kthread);
1991 fail_cleaner:
1992         kthread_stop(fs_info->cleaner_kthread);
1993
1994         /*
1995          * make sure we're done with the btree inode before we stop our
1996          * kthreads
1997          */
1998         filemap_write_and_wait(fs_info->btree_inode->i_mapping);
1999         invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
2000
2001 fail_block_groups:
2002         btrfs_free_block_groups(fs_info);
2003         free_extent_buffer(csum_root->node);
2004         free_extent_buffer(csum_root->commit_root);
2005 fail_dev_root:
2006         free_extent_buffer(dev_root->node);
2007         free_extent_buffer(dev_root->commit_root);
2008 fail_extent_root:
2009         free_extent_buffer(extent_root->node);
2010         free_extent_buffer(extent_root->commit_root);
2011 fail_tree_root:
2012         free_extent_buffer(tree_root->node);
2013         free_extent_buffer(tree_root->commit_root);
2014 fail_chunk_root:
2015         free_extent_buffer(chunk_root->node);
2016         free_extent_buffer(chunk_root->commit_root);
2017 fail_sb_buffer:
2018         btrfs_stop_workers(&fs_info->generic_worker);
2019         btrfs_stop_workers(&fs_info->fixup_workers);
2020         btrfs_stop_workers(&fs_info->delalloc_workers);
2021         btrfs_stop_workers(&fs_info->workers);
2022         btrfs_stop_workers(&fs_info->endio_workers);
2023         btrfs_stop_workers(&fs_info->endio_meta_workers);
2024         btrfs_stop_workers(&fs_info->endio_meta_write_workers);
2025         btrfs_stop_workers(&fs_info->endio_write_workers);
2026         btrfs_stop_workers(&fs_info->endio_freespace_worker);
2027         btrfs_stop_workers(&fs_info->submit_workers);
2028 fail_iput:
2029         invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
2030         iput(fs_info->btree_inode);
2031
2032         btrfs_close_devices(fs_info->fs_devices);
2033         btrfs_mapping_tree_free(&fs_info->mapping_tree);
2034 fail_bdi:
2035         bdi_destroy(&fs_info->bdi);
2036 fail_srcu:
2037         cleanup_srcu_struct(&fs_info->subvol_srcu);
2038 fail:
2039         kfree(extent_root);
2040         kfree(tree_root);
2041         kfree(fs_info);
2042         kfree(chunk_root);
2043         kfree(dev_root);
2044         kfree(csum_root);
2045         return ERR_PTR(err);
2046 }
2047
2048 static void btrfs_end_buffer_write_sync(struct buffer_head *bh, int uptodate)
2049 {
2050         char b[BDEVNAME_SIZE];
2051
2052         if (uptodate) {
2053                 set_buffer_uptodate(bh);
2054         } else {
2055                 if (printk_ratelimit()) {
2056                         printk(KERN_WARNING "lost page write due to "
2057                                         "I/O error on %s\n",
2058                                        bdevname(bh->b_bdev, b));
2059                 }
2060                 /* note, we dont' set_buffer_write_io_error because we have
2061                  * our own ways of dealing with the IO errors
2062                  */
2063                 clear_buffer_uptodate(bh);
2064         }
2065         unlock_buffer(bh);
2066         put_bh(bh);
2067 }
2068
2069 struct buffer_head *btrfs_read_dev_super(struct block_device *bdev)
2070 {
2071         struct buffer_head *bh;
2072         struct buffer_head *latest = NULL;
2073         struct btrfs_super_block *super;
2074         int i;
2075         u64 transid = 0;
2076         u64 bytenr;
2077
2078         /* we would like to check all the supers, but that would make
2079          * a btrfs mount succeed after a mkfs from a different FS.
2080          * So, we need to add a special mount option to scan for
2081          * later supers, using BTRFS_SUPER_MIRROR_MAX instead
2082          */
2083         for (i = 0; i < 1; i++) {
2084                 bytenr = btrfs_sb_offset(i);
2085                 if (bytenr + 4096 >= i_size_read(bdev->bd_inode))
2086                         break;
2087                 bh = __bread(bdev, bytenr / 4096, 4096);
2088                 if (!bh)
2089                         continue;
2090
2091                 super = (struct btrfs_super_block *)bh->b_data;
2092                 if (btrfs_super_bytenr(super) != bytenr ||
2093                     strncmp((char *)(&super->magic), BTRFS_MAGIC,
2094                             sizeof(super->magic))) {
2095                         brelse(bh);
2096                         continue;
2097                 }
2098
2099                 if (!latest || btrfs_super_generation(super) > transid) {
2100                         brelse(latest);
2101                         latest = bh;
2102                         transid = btrfs_super_generation(super);
2103                 } else {
2104                         brelse(bh);
2105                 }
2106         }
2107         return latest;
2108 }
2109
2110 /*
2111  * this should be called twice, once with wait == 0 and
2112  * once with wait == 1.  When wait == 0 is done, all the buffer heads
2113  * we write are pinned.
2114  *
2115  * They are released when wait == 1 is done.
2116  * max_mirrors must be the same for both runs, and it indicates how
2117  * many supers on this one device should be written.
2118  *
2119  * max_mirrors == 0 means to write them all.
2120  */
2121 static int write_dev_supers(struct btrfs_device *device,
2122                             struct btrfs_super_block *sb,
2123                             int do_barriers, int wait, int max_mirrors)
2124 {
2125         struct buffer_head *bh;
2126         int i;
2127         int ret;
2128         int errors = 0;
2129         u32 crc;
2130         u64 bytenr;
2131         int last_barrier = 0;
2132
2133         if (max_mirrors == 0)
2134                 max_mirrors = BTRFS_SUPER_MIRROR_MAX;
2135
2136         /* make sure only the last submit_bh does a barrier */
2137         if (do_barriers) {
2138                 for (i = 0; i < max_mirrors; i++) {
2139                         bytenr = btrfs_sb_offset(i);
2140                         if (bytenr + BTRFS_SUPER_INFO_SIZE >=
2141                             device->total_bytes)
2142                                 break;
2143                         last_barrier = i;
2144                 }
2145         }
2146
2147         for (i = 0; i < max_mirrors; i++) {
2148                 bytenr = btrfs_sb_offset(i);
2149                 if (bytenr + BTRFS_SUPER_INFO_SIZE >= device->total_bytes)
2150                         break;
2151
2152                 if (wait) {
2153                         bh = __find_get_block(device->bdev, bytenr / 4096,
2154                                               BTRFS_SUPER_INFO_SIZE);
2155                         BUG_ON(!bh);
2156                         wait_on_buffer(bh);
2157                         if (!buffer_uptodate(bh))
2158                                 errors++;
2159
2160                         /* drop our reference */
2161                         brelse(bh);
2162
2163                         /* drop the reference from the wait == 0 run */
2164                         brelse(bh);
2165                         continue;
2166                 } else {
2167                         btrfs_set_super_bytenr(sb, bytenr);
2168
2169                         crc = ~(u32)0;
2170                         crc = btrfs_csum_data(NULL, (char *)sb +
2171                                               BTRFS_CSUM_SIZE, crc,
2172                                               BTRFS_SUPER_INFO_SIZE -
2173                                               BTRFS_CSUM_SIZE);
2174                         btrfs_csum_final(crc, sb->csum);
2175
2176                         /*
2177                          * one reference for us, and we leave it for the
2178                          * caller
2179                          */
2180                         bh = __getblk(device->bdev, bytenr / 4096,
2181                                       BTRFS_SUPER_INFO_SIZE);
2182                         memcpy(bh->b_data, sb, BTRFS_SUPER_INFO_SIZE);
2183
2184                         /* one reference for submit_bh */
2185                         get_bh(bh);
2186
2187                         set_buffer_uptodate(bh);
2188                         lock_buffer(bh);
2189                         bh->b_end_io = btrfs_end_buffer_write_sync;
2190                 }
2191
2192                 if (i == last_barrier && do_barriers)
2193                         ret = submit_bh(WRITE_FLUSH_FUA, bh);
2194                 else
2195                         ret = submit_bh(WRITE_SYNC, bh);
2196
2197                 if (ret)
2198                         errors++;
2199         }
2200         return errors < i ? 0 : -1;
2201 }
2202
2203 int write_all_supers(struct btrfs_root *root, int max_mirrors)
2204 {
2205         struct list_head *head;
2206         struct btrfs_device *dev;
2207         struct btrfs_super_block *sb;
2208         struct btrfs_dev_item *dev_item;
2209         int ret;
2210         int do_barriers;
2211         int max_errors;
2212         int total_errors = 0;
2213         u64 flags;
2214
2215         max_errors = btrfs_super_num_devices(&root->fs_info->super_copy) - 1;
2216         do_barriers = !btrfs_test_opt(root, NOBARRIER);
2217
2218         sb = &root->fs_info->super_for_commit;
2219         dev_item = &sb->dev_item;
2220
2221         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2222         head = &root->fs_info->fs_devices->devices;
2223         list_for_each_entry(dev, head, dev_list) {
2224                 if (!dev->bdev) {
2225                         total_errors++;
2226                         continue;
2227                 }
2228                 if (!dev->in_fs_metadata || !dev->writeable)
2229                         continue;
2230
2231                 btrfs_set_stack_device_generation(dev_item, 0);
2232                 btrfs_set_stack_device_type(dev_item, dev->type);
2233                 btrfs_set_stack_device_id(dev_item, dev->devid);
2234                 btrfs_set_stack_device_total_bytes(dev_item, dev->total_bytes);
2235                 btrfs_set_stack_device_bytes_used(dev_item, dev->bytes_used);
2236                 btrfs_set_stack_device_io_align(dev_item, dev->io_align);
2237                 btrfs_set_stack_device_io_width(dev_item, dev->io_width);
2238                 btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
2239                 memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
2240                 memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_UUID_SIZE);
2241
2242                 flags = btrfs_super_flags(sb);
2243                 btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
2244
2245                 ret = write_dev_supers(dev, sb, do_barriers, 0, max_mirrors);
2246                 if (ret)
2247                         total_errors++;
2248         }
2249         if (total_errors > max_errors) {
2250                 printk(KERN_ERR "btrfs: %d errors while writing supers\n",
2251                        total_errors);
2252                 BUG();
2253         }
2254
2255         total_errors = 0;
2256         list_for_each_entry(dev, head, dev_list) {
2257                 if (!dev->bdev)
2258                         continue;
2259                 if (!dev->in_fs_metadata || !dev->writeable)
2260                         continue;
2261
2262                 ret = write_dev_supers(dev, sb, do_barriers, 1, max_mirrors);
2263                 if (ret)
2264                         total_errors++;
2265         }
2266         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2267         if (total_errors > max_errors) {
2268                 printk(KERN_ERR "btrfs: %d errors while writing supers\n",
2269                        total_errors);
2270                 BUG();
2271         }
2272         return 0;
2273 }
2274
2275 int write_ctree_super(struct btrfs_trans_handle *trans,
2276                       struct btrfs_root *root, int max_mirrors)
2277 {
2278         int ret;
2279
2280         ret = write_all_supers(root, max_mirrors);
2281         return ret;
2282 }
2283
2284 int btrfs_free_fs_root(struct btrfs_fs_info *fs_info, struct btrfs_root *root)
2285 {
2286         spin_lock(&fs_info->fs_roots_radix_lock);
2287         radix_tree_delete(&fs_info->fs_roots_radix,
2288                           (unsigned long)root->root_key.objectid);
2289         spin_unlock(&fs_info->fs_roots_radix_lock);
2290
2291         if (btrfs_root_refs(&root->root_item) == 0)
2292                 synchronize_srcu(&fs_info->subvol_srcu);
2293
2294         free_fs_root(root);
2295         return 0;
2296 }
2297
2298 static void free_fs_root(struct btrfs_root *root)
2299 {
2300         WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
2301         if (root->anon_super.s_dev) {
2302                 down_write(&root->anon_super.s_umount);
2303                 kill_anon_super(&root->anon_super);
2304         }
2305         free_extent_buffer(root->node);
2306         free_extent_buffer(root->commit_root);
2307         kfree(root->name);
2308         kfree(root);
2309 }
2310
2311 static int del_fs_roots(struct btrfs_fs_info *fs_info)
2312 {
2313         int ret;
2314         struct btrfs_root *gang[8];
2315         int i;
2316
2317         while (!list_empty(&fs_info->dead_roots)) {
2318                 gang[0] = list_entry(fs_info->dead_roots.next,
2319                                      struct btrfs_root, root_list);
2320                 list_del(&gang[0]->root_list);
2321
2322                 if (gang[0]->in_radix) {
2323                         btrfs_free_fs_root(fs_info, gang[0]);
2324                 } else {
2325                         free_extent_buffer(gang[0]->node);
2326                         free_extent_buffer(gang[0]->commit_root);
2327                         kfree(gang[0]);
2328                 }
2329         }
2330
2331         while (1) {
2332                 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2333                                              (void **)gang, 0,
2334                                              ARRAY_SIZE(gang));
2335                 if (!ret)
2336                         break;
2337                 for (i = 0; i < ret; i++)
2338                         btrfs_free_fs_root(fs_info, gang[i]);
2339         }
2340         return 0;
2341 }
2342
2343 int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
2344 {
2345         u64 root_objectid = 0;
2346         struct btrfs_root *gang[8];
2347         int i;
2348         int ret;
2349
2350         while (1) {
2351                 ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
2352                                              (void **)gang, root_objectid,
2353                                              ARRAY_SIZE(gang));
2354                 if (!ret)
2355                         break;
2356
2357                 root_objectid = gang[ret - 1]->root_key.objectid + 1;
2358                 for (i = 0; i < ret; i++) {
2359                         root_objectid = gang[i]->root_key.objectid;
2360                         btrfs_orphan_cleanup(gang[i]);
2361                 }
2362                 root_objectid++;
2363         }
2364         return 0;
2365 }
2366
2367 int btrfs_commit_super(struct btrfs_root *root)
2368 {
2369         struct btrfs_trans_handle *trans;
2370         int ret;
2371
2372         mutex_lock(&root->fs_info->cleaner_mutex);
2373         btrfs_run_delayed_iputs(root);
2374         btrfs_clean_old_snapshots(root);
2375         mutex_unlock(&root->fs_info->cleaner_mutex);
2376
2377         /* wait until ongoing cleanup work done */
2378         down_write(&root->fs_info->cleanup_work_sem);
2379         up_write(&root->fs_info->cleanup_work_sem);
2380
2381         trans = btrfs_join_transaction(root, 1);
2382         if (IS_ERR(trans))
2383                 return PTR_ERR(trans);
2384         ret = btrfs_commit_transaction(trans, root);
2385         BUG_ON(ret);
2386         /* run commit again to drop the original snapshot */
2387         trans = btrfs_join_transaction(root, 1);
2388         if (IS_ERR(trans))
2389                 return PTR_ERR(trans);
2390         btrfs_commit_transaction(trans, root);
2391         ret = btrfs_write_and_wait_transaction(NULL, root);
2392         BUG_ON(ret);
2393
2394         ret = write_ctree_super(NULL, root, 0);
2395         return ret;
2396 }
2397
2398 int close_ctree(struct btrfs_root *root)
2399 {
2400         struct btrfs_fs_info *fs_info = root->fs_info;
2401         int ret;
2402
2403         fs_info->closing = 1;
2404         smp_mb();
2405
2406         btrfs_put_block_group_cache(fs_info);
2407
2408         /*
2409          * Here come 2 situations when btrfs is broken to flip readonly:
2410          *
2411          * 1. when btrfs flips readonly somewhere else before
2412          * btrfs_commit_super, sb->s_flags has MS_RDONLY flag,
2413          * and btrfs will skip to write sb directly to keep
2414          * ERROR state on disk.
2415          *
2416          * 2. when btrfs flips readonly just in btrfs_commit_super,
2417          * and in such case, btrfs cannnot write sb via btrfs_commit_super,
2418          * and since fs_state has been set BTRFS_SUPER_FLAG_ERROR flag,
2419          * btrfs will cleanup all FS resources first and write sb then.
2420          */
2421         if (!(fs_info->sb->s_flags & MS_RDONLY)) {
2422                 ret = btrfs_commit_super(root);
2423                 if (ret)
2424                         printk(KERN_ERR "btrfs: commit super ret %d\n", ret);
2425         }
2426
2427         if (fs_info->fs_state & BTRFS_SUPER_FLAG_ERROR) {
2428                 ret = btrfs_error_commit_super(root);
2429                 if (ret)
2430                         printk(KERN_ERR "btrfs: commit super ret %d\n", ret);
2431         }
2432
2433         kthread_stop(root->fs_info->transaction_kthread);
2434         kthread_stop(root->fs_info->cleaner_kthread);
2435
2436         fs_info->closing = 2;
2437         smp_mb();
2438
2439         if (fs_info->delalloc_bytes) {
2440                 printk(KERN_INFO "btrfs: at unmount delalloc count %llu\n",
2441                        (unsigned long long)fs_info->delalloc_bytes);
2442         }
2443         if (fs_info->total_ref_cache_size) {
2444                 printk(KERN_INFO "btrfs: at umount reference cache size %llu\n",
2445                        (unsigned long long)fs_info->total_ref_cache_size);
2446         }
2447
2448         free_extent_buffer(fs_info->extent_root->node);
2449         free_extent_buffer(fs_info->extent_root->commit_root);
2450         free_extent_buffer(fs_info->tree_root->node);
2451         free_extent_buffer(fs_info->tree_root->commit_root);
2452         free_extent_buffer(root->fs_info->chunk_root->node);
2453         free_extent_buffer(root->fs_info->chunk_root->commit_root);
2454         free_extent_buffer(root->fs_info->dev_root->node);
2455         free_extent_buffer(root->fs_info->dev_root->commit_root);
2456         free_extent_buffer(root->fs_info->csum_root->node);
2457         free_extent_buffer(root->fs_info->csum_root->commit_root);
2458
2459         btrfs_free_block_groups(root->fs_info);
2460
2461         del_fs_roots(fs_info);
2462
2463         iput(fs_info->btree_inode);
2464
2465         btrfs_stop_workers(&fs_info->generic_worker);
2466         btrfs_stop_workers(&fs_info->fixup_workers);
2467         btrfs_stop_workers(&fs_info->delalloc_workers);
2468         btrfs_stop_workers(&fs_info->workers);
2469         btrfs_stop_workers(&fs_info->endio_workers);
2470         btrfs_stop_workers(&fs_info->endio_meta_workers);
2471         btrfs_stop_workers(&fs_info->endio_meta_write_workers);
2472         btrfs_stop_workers(&fs_info->endio_write_workers);
2473         btrfs_stop_workers(&fs_info->endio_freespace_worker);
2474         btrfs_stop_workers(&fs_info->submit_workers);
2475
2476         btrfs_close_devices(fs_info->fs_devices);
2477         btrfs_mapping_tree_free(&fs_info->mapping_tree);
2478
2479         bdi_destroy(&fs_info->bdi);
2480         cleanup_srcu_struct(&fs_info->subvol_srcu);
2481
2482         kfree(fs_info->extent_root);
2483         kfree(fs_info->tree_root);
2484         kfree(fs_info->chunk_root);
2485         kfree(fs_info->dev_root);
2486         kfree(fs_info->csum_root);
2487         kfree(fs_info);
2488
2489         return 0;
2490 }
2491
2492 int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid)
2493 {
2494         int ret;
2495         struct inode *btree_inode = buf->first_page->mapping->host;
2496
2497         ret = extent_buffer_uptodate(&BTRFS_I(btree_inode)->io_tree, buf,
2498                                      NULL);
2499         if (!ret)
2500                 return ret;
2501
2502         ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
2503                                     parent_transid);
2504         return !ret;
2505 }
2506
2507 int btrfs_set_buffer_uptodate(struct extent_buffer *buf)
2508 {
2509         struct inode *btree_inode = buf->first_page->mapping->host;
2510         return set_extent_buffer_uptodate(&BTRFS_I(btree_inode)->io_tree,
2511                                           buf);
2512 }
2513
2514 void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
2515 {
2516         struct btrfs_root *root = BTRFS_I(buf->first_page->mapping->host)->root;
2517         u64 transid = btrfs_header_generation(buf);
2518         struct inode *btree_inode = root->fs_info->btree_inode;
2519         int was_dirty;
2520
2521         btrfs_assert_tree_locked(buf);
2522         if (transid != root->fs_info->generation) {
2523                 printk(KERN_CRIT "btrfs transid mismatch buffer %llu, "
2524                        "found %llu running %llu\n",
2525                         (unsigned long long)buf->start,
2526                         (unsigned long long)transid,
2527                         (unsigned long long)root->fs_info->generation);
2528                 WARN_ON(1);
2529         }
2530         was_dirty = set_extent_buffer_dirty(&BTRFS_I(btree_inode)->io_tree,
2531                                             buf);
2532         if (!was_dirty) {
2533                 spin_lock(&root->fs_info->delalloc_lock);
2534                 root->fs_info->dirty_metadata_bytes += buf->len;
2535                 spin_unlock(&root->fs_info->delalloc_lock);
2536         }
2537 }
2538
2539 void btrfs_btree_balance_dirty(struct btrfs_root *root, unsigned long nr)
2540 {
2541         /*
2542          * looks as though older kernels can get into trouble with
2543          * this code, they end up stuck in balance_dirty_pages forever
2544          */
2545         u64 num_dirty;
2546         unsigned long thresh = 32 * 1024 * 1024;
2547
2548         if (current->flags & PF_MEMALLOC)
2549                 return;
2550
2551         num_dirty = root->fs_info->dirty_metadata_bytes;
2552
2553         if (num_dirty > thresh) {
2554                 balance_dirty_pages_ratelimited_nr(
2555                                    root->fs_info->btree_inode->i_mapping, 1);
2556         }
2557         return;
2558 }
2559
2560 int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid)
2561 {
2562         struct btrfs_root *root = BTRFS_I(buf->first_page->mapping->host)->root;
2563         int ret;
2564         ret = btree_read_extent_buffer_pages(root, buf, 0, parent_transid);
2565         if (ret == 0)
2566                 set_bit(EXTENT_BUFFER_UPTODATE, &buf->bflags);
2567         return ret;
2568 }
2569
2570 int btree_lock_page_hook(struct page *page)
2571 {
2572         struct inode *inode = page->mapping->host;
2573         struct btrfs_root *root = BTRFS_I(inode)->root;
2574         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2575         struct extent_buffer *eb;
2576         unsigned long len;
2577         u64 bytenr = page_offset(page);
2578
2579         if (page->private == EXTENT_PAGE_PRIVATE)
2580                 goto out;
2581
2582         len = page->private >> 2;
2583         eb = find_extent_buffer(io_tree, bytenr, len, GFP_NOFS);
2584         if (!eb)
2585                 goto out;
2586
2587         btrfs_tree_lock(eb);
2588         btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
2589
2590         if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
2591                 spin_lock(&root->fs_info->delalloc_lock);
2592                 if (root->fs_info->dirty_metadata_bytes >= eb->len)
2593                         root->fs_info->dirty_metadata_bytes -= eb->len;
2594                 else
2595                         WARN_ON(1);
2596                 spin_unlock(&root->fs_info->delalloc_lock);
2597         }
2598
2599         btrfs_tree_unlock(eb);
2600         free_extent_buffer(eb);
2601 out:
2602         lock_page(page);
2603         return 0;
2604 }
2605
2606 static void btrfs_check_super_valid(struct btrfs_fs_info *fs_info,
2607                               int read_only)
2608 {
2609         if (read_only)
2610                 return;
2611
2612         if (fs_info->fs_state & BTRFS_SUPER_FLAG_ERROR)
2613                 printk(KERN_WARNING "warning: mount fs with errors, "
2614                        "running btrfsck is recommended\n");
2615 }
2616
2617 int btrfs_error_commit_super(struct btrfs_root *root)
2618 {
2619         int ret;
2620
2621         mutex_lock(&root->fs_info->cleaner_mutex);
2622         btrfs_run_delayed_iputs(root);
2623         mutex_unlock(&root->fs_info->cleaner_mutex);
2624
2625         down_write(&root->fs_info->cleanup_work_sem);
2626         up_write(&root->fs_info->cleanup_work_sem);
2627
2628         /* cleanup FS via transaction */
2629         btrfs_cleanup_transaction(root);
2630
2631         ret = write_ctree_super(NULL, root, 0);
2632
2633         return ret;
2634 }
2635
2636 static int btrfs_destroy_ordered_operations(struct btrfs_root *root)
2637 {
2638         struct btrfs_inode *btrfs_inode;
2639         struct list_head splice;
2640
2641         INIT_LIST_HEAD(&splice);
2642
2643         mutex_lock(&root->fs_info->ordered_operations_mutex);
2644         spin_lock(&root->fs_info->ordered_extent_lock);
2645
2646         list_splice_init(&root->fs_info->ordered_operations, &splice);
2647         while (!list_empty(&splice)) {
2648                 btrfs_inode = list_entry(splice.next, struct btrfs_inode,
2649                                          ordered_operations);
2650
2651                 list_del_init(&btrfs_inode->ordered_operations);
2652
2653                 btrfs_invalidate_inodes(btrfs_inode->root);
2654         }
2655
2656         spin_unlock(&root->fs_info->ordered_extent_lock);
2657         mutex_unlock(&root->fs_info->ordered_operations_mutex);
2658
2659         return 0;
2660 }
2661
2662 static int btrfs_destroy_ordered_extents(struct btrfs_root *root)
2663 {
2664         struct list_head splice;
2665         struct btrfs_ordered_extent *ordered;
2666         struct inode *inode;
2667
2668         INIT_LIST_HEAD(&splice);
2669
2670         spin_lock(&root->fs_info->ordered_extent_lock);
2671
2672         list_splice_init(&root->fs_info->ordered_extents, &splice);
2673         while (!list_empty(&splice)) {
2674                 ordered = list_entry(splice.next, struct btrfs_ordered_extent,
2675                                      root_extent_list);
2676
2677                 list_del_init(&ordered->root_extent_list);
2678                 atomic_inc(&ordered->refs);
2679
2680                 /* the inode may be getting freed (in sys_unlink path). */
2681                 inode = igrab(ordered->inode);
2682
2683                 spin_unlock(&root->fs_info->ordered_extent_lock);
2684                 if (inode)
2685                         iput(inode);
2686
2687                 atomic_set(&ordered->refs, 1);
2688                 btrfs_put_ordered_extent(ordered);
2689
2690                 spin_lock(&root->fs_info->ordered_extent_lock);
2691         }
2692
2693         spin_unlock(&root->fs_info->ordered_extent_lock);
2694
2695         return 0;
2696 }
2697
2698 static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
2699                                       struct btrfs_root *root)
2700 {
2701         struct rb_node *node;
2702         struct btrfs_delayed_ref_root *delayed_refs;
2703         struct btrfs_delayed_ref_node *ref;
2704         int ret = 0;
2705
2706         delayed_refs = &trans->delayed_refs;
2707
2708         spin_lock(&delayed_refs->lock);
2709         if (delayed_refs->num_entries == 0) {
2710                 printk(KERN_INFO "delayed_refs has NO entry\n");
2711                 return ret;
2712         }
2713
2714         node = rb_first(&delayed_refs->root);
2715         while (node) {
2716                 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2717                 node = rb_next(node);
2718
2719                 ref->in_tree = 0;
2720                 rb_erase(&ref->rb_node, &delayed_refs->root);
2721                 delayed_refs->num_entries--;
2722
2723                 atomic_set(&ref->refs, 1);
2724                 if (btrfs_delayed_ref_is_head(ref)) {
2725                         struct btrfs_delayed_ref_head *head;
2726
2727                         head = btrfs_delayed_node_to_head(ref);
2728                         mutex_lock(&head->mutex);
2729                         kfree(head->extent_op);
2730                         delayed_refs->num_heads--;
2731                         if (list_empty(&head->cluster))
2732                                 delayed_refs->num_heads_ready--;
2733                         list_del_init(&head->cluster);
2734                         mutex_unlock(&head->mutex);
2735                 }
2736
2737                 spin_unlock(&delayed_refs->lock);
2738                 btrfs_put_delayed_ref(ref);
2739
2740                 cond_resched();
2741                 spin_lock(&delayed_refs->lock);
2742         }
2743
2744         spin_unlock(&delayed_refs->lock);
2745
2746         return ret;
2747 }
2748
2749 static int btrfs_destroy_pending_snapshots(struct btrfs_transaction *t)
2750 {
2751         struct btrfs_pending_snapshot *snapshot;
2752         struct list_head splice;
2753
2754         INIT_LIST_HEAD(&splice);
2755
2756         list_splice_init(&t->pending_snapshots, &splice);
2757
2758         while (!list_empty(&splice)) {
2759                 snapshot = list_entry(splice.next,
2760                                       struct btrfs_pending_snapshot,
2761                                       list);
2762
2763                 list_del_init(&snapshot->list);
2764
2765                 kfree(snapshot);
2766         }
2767
2768         return 0;
2769 }
2770
2771 static int btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
2772 {
2773         struct btrfs_inode *btrfs_inode;
2774         struct list_head splice;
2775
2776         INIT_LIST_HEAD(&splice);
2777
2778         list_splice_init(&root->fs_info->delalloc_inodes, &splice);
2779
2780         spin_lock(&root->fs_info->delalloc_lock);
2781
2782         while (!list_empty(&splice)) {
2783                 btrfs_inode = list_entry(splice.next, struct btrfs_inode,
2784                                     delalloc_inodes);
2785
2786                 list_del_init(&btrfs_inode->delalloc_inodes);
2787
2788                 btrfs_invalidate_inodes(btrfs_inode->root);
2789         }
2790
2791         spin_unlock(&root->fs_info->delalloc_lock);
2792
2793         return 0;
2794 }
2795
2796 static int btrfs_destroy_marked_extents(struct btrfs_root *root,
2797                                         struct extent_io_tree *dirty_pages,
2798                                         int mark)
2799 {
2800         int ret;
2801         struct page *page;
2802         struct inode *btree_inode = root->fs_info->btree_inode;
2803         struct extent_buffer *eb;
2804         u64 start = 0;
2805         u64 end;
2806         u64 offset;
2807         unsigned long index;
2808
2809         while (1) {
2810                 ret = find_first_extent_bit(dirty_pages, start, &start, &end,
2811                                             mark);
2812                 if (ret)
2813                         break;
2814
2815                 clear_extent_bits(dirty_pages, start, end, mark, GFP_NOFS);
2816                 while (start <= end) {
2817                         index = start >> PAGE_CACHE_SHIFT;
2818                         start = (u64)(index + 1) << PAGE_CACHE_SHIFT;
2819                         page = find_get_page(btree_inode->i_mapping, index);
2820                         if (!page)
2821                                 continue;
2822                         offset = page_offset(page);
2823
2824                         spin_lock(&dirty_pages->buffer_lock);
2825                         eb = radix_tree_lookup(
2826                              &(&BTRFS_I(page->mapping->host)->io_tree)->buffer,
2827                                                offset >> PAGE_CACHE_SHIFT);
2828                         spin_unlock(&dirty_pages->buffer_lock);
2829                         if (eb) {
2830                                 ret = test_and_clear_bit(EXTENT_BUFFER_DIRTY,
2831                                                          &eb->bflags);
2832                                 atomic_set(&eb->refs, 1);
2833                         }
2834                         if (PageWriteback(page))
2835                                 end_page_writeback(page);
2836
2837                         lock_page(page);
2838                         if (PageDirty(page)) {
2839                                 clear_page_dirty_for_io(page);
2840                                 spin_lock_irq(&page->mapping->tree_lock);
2841                                 radix_tree_tag_clear(&page->mapping->page_tree,
2842                                                         page_index(page),
2843                                                         PAGECACHE_TAG_DIRTY);
2844                                 spin_unlock_irq(&page->mapping->tree_lock);
2845                         }
2846
2847                         page->mapping->a_ops->invalidatepage(page, 0);
2848                         unlock_page(page);
2849                 }
2850         }
2851
2852         return ret;
2853 }
2854
2855 static int btrfs_destroy_pinned_extent(struct btrfs_root *root,
2856                                        struct extent_io_tree *pinned_extents)
2857 {
2858         struct extent_io_tree *unpin;
2859         u64 start;
2860         u64 end;
2861         int ret;
2862
2863         unpin = pinned_extents;
2864         while (1) {
2865                 ret = find_first_extent_bit(unpin, 0, &start, &end,
2866                                             EXTENT_DIRTY);
2867                 if (ret)
2868                         break;
2869
2870                 /* opt_discard */
2871                 ret = btrfs_error_discard_extent(root, start, end + 1 - start);
2872
2873                 clear_extent_dirty(unpin, start, end, GFP_NOFS);
2874                 btrfs_error_unpin_extent_range(root, start, end);
2875                 cond_resched();
2876         }
2877
2878         return 0;
2879 }
2880
2881 static int btrfs_cleanup_transaction(struct btrfs_root *root)
2882 {
2883         struct btrfs_transaction *t;
2884         LIST_HEAD(list);
2885
2886         WARN_ON(1);
2887
2888         mutex_lock(&root->fs_info->trans_mutex);
2889         mutex_lock(&root->fs_info->transaction_kthread_mutex);
2890
2891         list_splice_init(&root->fs_info->trans_list, &list);
2892         while (!list_empty(&list)) {
2893                 t = list_entry(list.next, struct btrfs_transaction, list);
2894                 if (!t)
2895                         break;
2896
2897                 btrfs_destroy_ordered_operations(root);
2898
2899                 btrfs_destroy_ordered_extents(root);
2900
2901                 btrfs_destroy_delayed_refs(t, root);
2902
2903                 btrfs_block_rsv_release(root,
2904                                         &root->fs_info->trans_block_rsv,
2905                                         t->dirty_pages.dirty_bytes);
2906
2907                 /* FIXME: cleanup wait for commit */
2908                 t->in_commit = 1;
2909                 t->blocked = 1;
2910                 if (waitqueue_active(&root->fs_info->transaction_blocked_wait))
2911                         wake_up(&root->fs_info->transaction_blocked_wait);
2912
2913                 t->blocked = 0;
2914                 if (waitqueue_active(&root->fs_info->transaction_wait))
2915                         wake_up(&root->fs_info->transaction_wait);
2916                 mutex_unlock(&root->fs_info->trans_mutex);
2917
2918                 mutex_lock(&root->fs_info->trans_mutex);
2919                 t->commit_done = 1;
2920                 if (waitqueue_active(&t->commit_wait))
2921                         wake_up(&t->commit_wait);
2922                 mutex_unlock(&root->fs_info->trans_mutex);
2923
2924                 mutex_lock(&root->fs_info->trans_mutex);
2925
2926                 btrfs_destroy_pending_snapshots(t);
2927
2928                 btrfs_destroy_delalloc_inodes(root);
2929
2930                 spin_lock(&root->fs_info->new_trans_lock);
2931                 root->fs_info->running_transaction = NULL;
2932                 spin_unlock(&root->fs_info->new_trans_lock);
2933
2934                 btrfs_destroy_marked_extents(root, &t->dirty_pages,
2935                                              EXTENT_DIRTY);
2936
2937                 btrfs_destroy_pinned_extent(root,
2938                                             root->fs_info->pinned_extents);
2939
2940                 t->use_count = 0;
2941                 list_del_init(&t->list);
2942                 memset(t, 0, sizeof(*t));
2943                 kmem_cache_free(btrfs_transaction_cachep, t);
2944         }
2945
2946         mutex_unlock(&root->fs_info->transaction_kthread_mutex);
2947         mutex_unlock(&root->fs_info->trans_mutex);
2948
2949         return 0;
2950 }
2951
2952 static struct extent_io_ops btree_extent_io_ops = {
2953         .write_cache_pages_lock_hook = btree_lock_page_hook,
2954         .readpage_end_io_hook = btree_readpage_end_io_hook,
2955         .submit_bio_hook = btree_submit_bio_hook,
2956         /* note we're sharing with inode.c for the merge bio hook */
2957         .merge_bio_hook = btrfs_merge_bio_hook,
2958 };