Btrfs: fix the qgroup reserved space is released prematurely
[platform/adaptation/renesas_rcar/renesas_kernel.git] / fs / btrfs / transaction.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/slab.h>
21 #include <linux/sched.h>
22 #include <linux/writeback.h>
23 #include <linux/pagemap.h>
24 #include <linux/blkdev.h>
25 #include <linux/uuid.h>
26 #include "ctree.h"
27 #include "disk-io.h"
28 #include "transaction.h"
29 #include "locking.h"
30 #include "tree-log.h"
31 #include "inode-map.h"
32 #include "volumes.h"
33 #include "dev-replace.h"
34
35 #define BTRFS_ROOT_TRANS_TAG 0
36
37 void put_transaction(struct btrfs_transaction *transaction)
38 {
39         WARN_ON(atomic_read(&transaction->use_count) == 0);
40         if (atomic_dec_and_test(&transaction->use_count)) {
41                 BUG_ON(!list_empty(&transaction->list));
42                 WARN_ON(transaction->delayed_refs.root.rb_node);
43                 kmem_cache_free(btrfs_transaction_cachep, transaction);
44         }
45 }
46
47 static noinline void switch_commit_root(struct btrfs_root *root)
48 {
49         free_extent_buffer(root->commit_root);
50         root->commit_root = btrfs_root_node(root);
51 }
52
53 /*
54  * either allocate a new transaction or hop into the existing one
55  */
56 static noinline int join_transaction(struct btrfs_root *root, int type)
57 {
58         struct btrfs_transaction *cur_trans;
59         struct btrfs_fs_info *fs_info = root->fs_info;
60
61         spin_lock(&fs_info->trans_lock);
62 loop:
63         /* The file system has been taken offline. No new transactions. */
64         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
65                 spin_unlock(&fs_info->trans_lock);
66                 return -EROFS;
67         }
68
69         if (fs_info->trans_no_join) {
70                 /* 
71                  * If we are JOIN_NOLOCK we're already committing a current
72                  * transaction, we just need a handle to deal with something
73                  * when committing the transaction, such as inode cache and
74                  * space cache. It is a special case.
75                  */
76                 if (type != TRANS_JOIN_NOLOCK) {
77                         spin_unlock(&fs_info->trans_lock);
78                         return -EBUSY;
79                 }
80         }
81
82         cur_trans = fs_info->running_transaction;
83         if (cur_trans) {
84                 if (cur_trans->aborted) {
85                         spin_unlock(&fs_info->trans_lock);
86                         return cur_trans->aborted;
87                 }
88                 atomic_inc(&cur_trans->use_count);
89                 atomic_inc(&cur_trans->num_writers);
90                 cur_trans->num_joined++;
91                 spin_unlock(&fs_info->trans_lock);
92                 return 0;
93         }
94         spin_unlock(&fs_info->trans_lock);
95
96         /*
97          * If we are ATTACH, we just want to catch the current transaction,
98          * and commit it. If there is no transaction, just return ENOENT.
99          */
100         if (type == TRANS_ATTACH)
101                 return -ENOENT;
102
103         cur_trans = kmem_cache_alloc(btrfs_transaction_cachep, GFP_NOFS);
104         if (!cur_trans)
105                 return -ENOMEM;
106
107         spin_lock(&fs_info->trans_lock);
108         if (fs_info->running_transaction) {
109                 /*
110                  * someone started a transaction after we unlocked.  Make sure
111                  * to redo the trans_no_join checks above
112                  */
113                 kmem_cache_free(btrfs_transaction_cachep, cur_trans);
114                 cur_trans = fs_info->running_transaction;
115                 goto loop;
116         } else if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
117                 spin_unlock(&fs_info->trans_lock);
118                 kmem_cache_free(btrfs_transaction_cachep, cur_trans);
119                 return -EROFS;
120         }
121
122         atomic_set(&cur_trans->num_writers, 1);
123         cur_trans->num_joined = 0;
124         init_waitqueue_head(&cur_trans->writer_wait);
125         init_waitqueue_head(&cur_trans->commit_wait);
126         cur_trans->in_commit = 0;
127         cur_trans->blocked = 0;
128         /*
129          * One for this trans handle, one so it will live on until we
130          * commit the transaction.
131          */
132         atomic_set(&cur_trans->use_count, 2);
133         cur_trans->commit_done = 0;
134         cur_trans->start_time = get_seconds();
135
136         cur_trans->delayed_refs.root = RB_ROOT;
137         cur_trans->delayed_refs.num_entries = 0;
138         cur_trans->delayed_refs.num_heads_ready = 0;
139         cur_trans->delayed_refs.num_heads = 0;
140         cur_trans->delayed_refs.flushing = 0;
141         cur_trans->delayed_refs.run_delayed_start = 0;
142
143         /*
144          * although the tree mod log is per file system and not per transaction,
145          * the log must never go across transaction boundaries.
146          */
147         smp_mb();
148         if (!list_empty(&fs_info->tree_mod_seq_list))
149                 WARN(1, KERN_ERR "btrfs: tree_mod_seq_list not empty when "
150                         "creating a fresh transaction\n");
151         if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
152                 WARN(1, KERN_ERR "btrfs: tree_mod_log rb tree not empty when "
153                         "creating a fresh transaction\n");
154         atomic_set(&fs_info->tree_mod_seq, 0);
155
156         spin_lock_init(&cur_trans->commit_lock);
157         spin_lock_init(&cur_trans->delayed_refs.lock);
158
159         INIT_LIST_HEAD(&cur_trans->pending_snapshots);
160         INIT_LIST_HEAD(&cur_trans->ordered_operations);
161         list_add_tail(&cur_trans->list, &fs_info->trans_list);
162         extent_io_tree_init(&cur_trans->dirty_pages,
163                              fs_info->btree_inode->i_mapping);
164         fs_info->generation++;
165         cur_trans->transid = fs_info->generation;
166         fs_info->running_transaction = cur_trans;
167         cur_trans->aborted = 0;
168         spin_unlock(&fs_info->trans_lock);
169
170         return 0;
171 }
172
173 /*
174  * this does all the record keeping required to make sure that a reference
175  * counted root is properly recorded in a given transaction.  This is required
176  * to make sure the old root from before we joined the transaction is deleted
177  * when the transaction commits
178  */
179 static int record_root_in_trans(struct btrfs_trans_handle *trans,
180                                struct btrfs_root *root)
181 {
182         if (root->ref_cows && root->last_trans < trans->transid) {
183                 WARN_ON(root == root->fs_info->extent_root);
184                 WARN_ON(root->commit_root != root->node);
185
186                 /*
187                  * see below for in_trans_setup usage rules
188                  * we have the reloc mutex held now, so there
189                  * is only one writer in this function
190                  */
191                 root->in_trans_setup = 1;
192
193                 /* make sure readers find in_trans_setup before
194                  * they find our root->last_trans update
195                  */
196                 smp_wmb();
197
198                 spin_lock(&root->fs_info->fs_roots_radix_lock);
199                 if (root->last_trans == trans->transid) {
200                         spin_unlock(&root->fs_info->fs_roots_radix_lock);
201                         return 0;
202                 }
203                 radix_tree_tag_set(&root->fs_info->fs_roots_radix,
204                            (unsigned long)root->root_key.objectid,
205                            BTRFS_ROOT_TRANS_TAG);
206                 spin_unlock(&root->fs_info->fs_roots_radix_lock);
207                 root->last_trans = trans->transid;
208
209                 /* this is pretty tricky.  We don't want to
210                  * take the relocation lock in btrfs_record_root_in_trans
211                  * unless we're really doing the first setup for this root in
212                  * this transaction.
213                  *
214                  * Normally we'd use root->last_trans as a flag to decide
215                  * if we want to take the expensive mutex.
216                  *
217                  * But, we have to set root->last_trans before we
218                  * init the relocation root, otherwise, we trip over warnings
219                  * in ctree.c.  The solution used here is to flag ourselves
220                  * with root->in_trans_setup.  When this is 1, we're still
221                  * fixing up the reloc trees and everyone must wait.
222                  *
223                  * When this is zero, they can trust root->last_trans and fly
224                  * through btrfs_record_root_in_trans without having to take the
225                  * lock.  smp_wmb() makes sure that all the writes above are
226                  * done before we pop in the zero below
227                  */
228                 btrfs_init_reloc_root(trans, root);
229                 smp_wmb();
230                 root->in_trans_setup = 0;
231         }
232         return 0;
233 }
234
235
236 int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
237                                struct btrfs_root *root)
238 {
239         if (!root->ref_cows)
240                 return 0;
241
242         /*
243          * see record_root_in_trans for comments about in_trans_setup usage
244          * and barriers
245          */
246         smp_rmb();
247         if (root->last_trans == trans->transid &&
248             !root->in_trans_setup)
249                 return 0;
250
251         mutex_lock(&root->fs_info->reloc_mutex);
252         record_root_in_trans(trans, root);
253         mutex_unlock(&root->fs_info->reloc_mutex);
254
255         return 0;
256 }
257
258 /* wait for commit against the current transaction to become unblocked
259  * when this is done, it is safe to start a new transaction, but the current
260  * transaction might not be fully on disk.
261  */
262 static void wait_current_trans(struct btrfs_root *root)
263 {
264         struct btrfs_transaction *cur_trans;
265
266         spin_lock(&root->fs_info->trans_lock);
267         cur_trans = root->fs_info->running_transaction;
268         if (cur_trans && cur_trans->blocked) {
269                 atomic_inc(&cur_trans->use_count);
270                 spin_unlock(&root->fs_info->trans_lock);
271
272                 wait_event(root->fs_info->transaction_wait,
273                            !cur_trans->blocked);
274                 put_transaction(cur_trans);
275         } else {
276                 spin_unlock(&root->fs_info->trans_lock);
277         }
278 }
279
280 static int may_wait_transaction(struct btrfs_root *root, int type)
281 {
282         if (root->fs_info->log_root_recovering)
283                 return 0;
284
285         if (type == TRANS_USERSPACE)
286                 return 1;
287
288         if (type == TRANS_START &&
289             !atomic_read(&root->fs_info->open_ioctl_trans))
290                 return 1;
291
292         return 0;
293 }
294
295 static struct btrfs_trans_handle *
296 start_transaction(struct btrfs_root *root, u64 num_items, int type,
297                   enum btrfs_reserve_flush_enum flush)
298 {
299         struct btrfs_trans_handle *h;
300         struct btrfs_transaction *cur_trans;
301         u64 num_bytes = 0;
302         int ret;
303         u64 qgroup_reserved = 0;
304
305         if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
306                 return ERR_PTR(-EROFS);
307
308         if (current->journal_info) {
309                 WARN_ON(type != TRANS_JOIN && type != TRANS_JOIN_NOLOCK);
310                 h = current->journal_info;
311                 h->use_count++;
312                 WARN_ON(h->use_count > 2);
313                 h->orig_rsv = h->block_rsv;
314                 h->block_rsv = NULL;
315                 goto got_it;
316         }
317
318         /*
319          * Do the reservation before we join the transaction so we can do all
320          * the appropriate flushing if need be.
321          */
322         if (num_items > 0 && root != root->fs_info->chunk_root) {
323                 if (root->fs_info->quota_enabled &&
324                     is_fstree(root->root_key.objectid)) {
325                         qgroup_reserved = num_items * root->leafsize;
326                         ret = btrfs_qgroup_reserve(root, qgroup_reserved);
327                         if (ret)
328                                 return ERR_PTR(ret);
329                 }
330
331                 num_bytes = btrfs_calc_trans_metadata_size(root, num_items);
332                 ret = btrfs_block_rsv_add(root,
333                                           &root->fs_info->trans_block_rsv,
334                                           num_bytes, flush);
335                 if (ret)
336                         goto reserve_fail;
337         }
338 again:
339         h = kmem_cache_alloc(btrfs_trans_handle_cachep, GFP_NOFS);
340         if (!h) {
341                 ret = -ENOMEM;
342                 goto alloc_fail;
343         }
344
345         /*
346          * If we are JOIN_NOLOCK we're already committing a transaction and
347          * waiting on this guy, so we don't need to do the sb_start_intwrite
348          * because we're already holding a ref.  We need this because we could
349          * have raced in and did an fsync() on a file which can kick a commit
350          * and then we deadlock with somebody doing a freeze.
351          *
352          * If we are ATTACH, it means we just want to catch the current
353          * transaction and commit it, so we needn't do sb_start_intwrite(). 
354          */
355         if (type < TRANS_JOIN_NOLOCK)
356                 sb_start_intwrite(root->fs_info->sb);
357
358         if (may_wait_transaction(root, type))
359                 wait_current_trans(root);
360
361         do {
362                 ret = join_transaction(root, type);
363                 if (ret == -EBUSY)
364                         wait_current_trans(root);
365         } while (ret == -EBUSY);
366
367         if (ret < 0) {
368                 /* We must get the transaction if we are JOIN_NOLOCK. */
369                 BUG_ON(type == TRANS_JOIN_NOLOCK);
370                 goto join_fail;
371         }
372
373         cur_trans = root->fs_info->running_transaction;
374
375         h->transid = cur_trans->transid;
376         h->transaction = cur_trans;
377         h->blocks_used = 0;
378         h->bytes_reserved = 0;
379         h->root = root;
380         h->delayed_ref_updates = 0;
381         h->use_count = 1;
382         h->adding_csums = 0;
383         h->block_rsv = NULL;
384         h->orig_rsv = NULL;
385         h->aborted = 0;
386         h->qgroup_reserved = 0;
387         h->delayed_ref_elem.seq = 0;
388         h->type = type;
389         h->allocating_chunk = false;
390         INIT_LIST_HEAD(&h->qgroup_ref_list);
391         INIT_LIST_HEAD(&h->new_bgs);
392
393         smp_mb();
394         if (cur_trans->blocked && may_wait_transaction(root, type)) {
395                 btrfs_commit_transaction(h, root);
396                 goto again;
397         }
398
399         if (num_bytes) {
400                 trace_btrfs_space_reservation(root->fs_info, "transaction",
401                                               h->transid, num_bytes, 1);
402                 h->block_rsv = &root->fs_info->trans_block_rsv;
403                 h->bytes_reserved = num_bytes;
404         }
405         h->qgroup_reserved = qgroup_reserved;
406
407 got_it:
408         btrfs_record_root_in_trans(h, root);
409
410         if (!current->journal_info && type != TRANS_USERSPACE)
411                 current->journal_info = h;
412         return h;
413
414 join_fail:
415         if (type < TRANS_JOIN_NOLOCK)
416                 sb_end_intwrite(root->fs_info->sb);
417         kmem_cache_free(btrfs_trans_handle_cachep, h);
418 alloc_fail:
419         if (num_bytes)
420                 btrfs_block_rsv_release(root, &root->fs_info->trans_block_rsv,
421                                         num_bytes);
422 reserve_fail:
423         if (qgroup_reserved)
424                 btrfs_qgroup_free(root, qgroup_reserved);
425         return ERR_PTR(ret);
426 }
427
428 struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
429                                                    int num_items)
430 {
431         return start_transaction(root, num_items, TRANS_START,
432                                  BTRFS_RESERVE_FLUSH_ALL);
433 }
434
435 struct btrfs_trans_handle *btrfs_start_transaction_lflush(
436                                         struct btrfs_root *root, int num_items)
437 {
438         return start_transaction(root, num_items, TRANS_START,
439                                  BTRFS_RESERVE_FLUSH_LIMIT);
440 }
441
442 struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
443 {
444         return start_transaction(root, 0, TRANS_JOIN, 0);
445 }
446
447 struct btrfs_trans_handle *btrfs_join_transaction_nolock(struct btrfs_root *root)
448 {
449         return start_transaction(root, 0, TRANS_JOIN_NOLOCK, 0);
450 }
451
452 struct btrfs_trans_handle *btrfs_start_ioctl_transaction(struct btrfs_root *root)
453 {
454         return start_transaction(root, 0, TRANS_USERSPACE, 0);
455 }
456
457 struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
458 {
459         return start_transaction(root, 0, TRANS_ATTACH, 0);
460 }
461
462 /* wait for a transaction commit to be fully complete */
463 static noinline void wait_for_commit(struct btrfs_root *root,
464                                     struct btrfs_transaction *commit)
465 {
466         wait_event(commit->commit_wait, commit->commit_done);
467 }
468
469 int btrfs_wait_for_commit(struct btrfs_root *root, u64 transid)
470 {
471         struct btrfs_transaction *cur_trans = NULL, *t;
472         int ret = 0;
473
474         if (transid) {
475                 if (transid <= root->fs_info->last_trans_committed)
476                         goto out;
477
478                 ret = -EINVAL;
479                 /* find specified transaction */
480                 spin_lock(&root->fs_info->trans_lock);
481                 list_for_each_entry(t, &root->fs_info->trans_list, list) {
482                         if (t->transid == transid) {
483                                 cur_trans = t;
484                                 atomic_inc(&cur_trans->use_count);
485                                 ret = 0;
486                                 break;
487                         }
488                         if (t->transid > transid) {
489                                 ret = 0;
490                                 break;
491                         }
492                 }
493                 spin_unlock(&root->fs_info->trans_lock);
494                 /* The specified transaction doesn't exist */
495                 if (!cur_trans)
496                         goto out;
497         } else {
498                 /* find newest transaction that is committing | committed */
499                 spin_lock(&root->fs_info->trans_lock);
500                 list_for_each_entry_reverse(t, &root->fs_info->trans_list,
501                                             list) {
502                         if (t->in_commit) {
503                                 if (t->commit_done)
504                                         break;
505                                 cur_trans = t;
506                                 atomic_inc(&cur_trans->use_count);
507                                 break;
508                         }
509                 }
510                 spin_unlock(&root->fs_info->trans_lock);
511                 if (!cur_trans)
512                         goto out;  /* nothing committing|committed */
513         }
514
515         wait_for_commit(root, cur_trans);
516         put_transaction(cur_trans);
517 out:
518         return ret;
519 }
520
521 void btrfs_throttle(struct btrfs_root *root)
522 {
523         if (!atomic_read(&root->fs_info->open_ioctl_trans))
524                 wait_current_trans(root);
525 }
526
527 static int should_end_transaction(struct btrfs_trans_handle *trans,
528                                   struct btrfs_root *root)
529 {
530         int ret;
531
532         ret = btrfs_block_rsv_check(root, &root->fs_info->global_block_rsv, 5);
533         return ret ? 1 : 0;
534 }
535
536 int btrfs_should_end_transaction(struct btrfs_trans_handle *trans,
537                                  struct btrfs_root *root)
538 {
539         struct btrfs_transaction *cur_trans = trans->transaction;
540         int updates;
541         int err;
542
543         smp_mb();
544         if (cur_trans->blocked || cur_trans->delayed_refs.flushing)
545                 return 1;
546
547         updates = trans->delayed_ref_updates;
548         trans->delayed_ref_updates = 0;
549         if (updates) {
550                 err = btrfs_run_delayed_refs(trans, root, updates);
551                 if (err) /* Error code will also eval true */
552                         return err;
553         }
554
555         return should_end_transaction(trans, root);
556 }
557
558 static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
559                           struct btrfs_root *root, int throttle)
560 {
561         struct btrfs_transaction *cur_trans = trans->transaction;
562         struct btrfs_fs_info *info = root->fs_info;
563         int count = 0;
564         int lock = (trans->type != TRANS_JOIN_NOLOCK);
565         int err = 0;
566
567         if (--trans->use_count) {
568                 trans->block_rsv = trans->orig_rsv;
569                 return 0;
570         }
571
572         /*
573          * do the qgroup accounting as early as possible
574          */
575         err = btrfs_delayed_refs_qgroup_accounting(trans, info);
576
577         btrfs_trans_release_metadata(trans, root);
578         trans->block_rsv = NULL;
579         /*
580          * the same root has to be passed to start_transaction and
581          * end_transaction. Subvolume quota depends on this.
582          */
583         WARN_ON(trans->root != root);
584
585         if (trans->qgroup_reserved) {
586                 btrfs_qgroup_free(root, trans->qgroup_reserved);
587                 trans->qgroup_reserved = 0;
588         }
589
590         if (!list_empty(&trans->new_bgs))
591                 btrfs_create_pending_block_groups(trans, root);
592
593         while (count < 2) {
594                 unsigned long cur = trans->delayed_ref_updates;
595                 trans->delayed_ref_updates = 0;
596                 if (cur &&
597                     trans->transaction->delayed_refs.num_heads_ready > 64) {
598                         trans->delayed_ref_updates = 0;
599                         btrfs_run_delayed_refs(trans, root, cur);
600                 } else {
601                         break;
602                 }
603                 count++;
604         }
605         btrfs_trans_release_metadata(trans, root);
606         trans->block_rsv = NULL;
607
608         if (!list_empty(&trans->new_bgs))
609                 btrfs_create_pending_block_groups(trans, root);
610
611         if (lock && !atomic_read(&root->fs_info->open_ioctl_trans) &&
612             should_end_transaction(trans, root)) {
613                 trans->transaction->blocked = 1;
614                 smp_wmb();
615         }
616
617         if (lock && cur_trans->blocked && !cur_trans->in_commit) {
618                 if (throttle) {
619                         /*
620                          * We may race with somebody else here so end up having
621                          * to call end_transaction on ourselves again, so inc
622                          * our use_count.
623                          */
624                         trans->use_count++;
625                         return btrfs_commit_transaction(trans, root);
626                 } else {
627                         wake_up_process(info->transaction_kthread);
628                 }
629         }
630
631         if (trans->type < TRANS_JOIN_NOLOCK)
632                 sb_end_intwrite(root->fs_info->sb);
633
634         WARN_ON(cur_trans != info->running_transaction);
635         WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
636         atomic_dec(&cur_trans->num_writers);
637
638         smp_mb();
639         if (waitqueue_active(&cur_trans->writer_wait))
640                 wake_up(&cur_trans->writer_wait);
641         put_transaction(cur_trans);
642
643         if (current->journal_info == trans)
644                 current->journal_info = NULL;
645
646         if (throttle)
647                 btrfs_run_delayed_iputs(root);
648
649         if (trans->aborted ||
650             test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
651                 err = -EIO;
652         assert_qgroups_uptodate(trans);
653
654         kmem_cache_free(btrfs_trans_handle_cachep, trans);
655         return err;
656 }
657
658 int btrfs_end_transaction(struct btrfs_trans_handle *trans,
659                           struct btrfs_root *root)
660 {
661         int ret;
662
663         ret = __btrfs_end_transaction(trans, root, 0);
664         if (ret)
665                 return ret;
666         return 0;
667 }
668
669 int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans,
670                                    struct btrfs_root *root)
671 {
672         int ret;
673
674         ret = __btrfs_end_transaction(trans, root, 1);
675         if (ret)
676                 return ret;
677         return 0;
678 }
679
680 int btrfs_end_transaction_dmeta(struct btrfs_trans_handle *trans,
681                                 struct btrfs_root *root)
682 {
683         return __btrfs_end_transaction(trans, root, 1);
684 }
685
686 /*
687  * when btree blocks are allocated, they have some corresponding bits set for
688  * them in one of two extent_io trees.  This is used to make sure all of
689  * those extents are sent to disk but does not wait on them
690  */
691 int btrfs_write_marked_extents(struct btrfs_root *root,
692                                struct extent_io_tree *dirty_pages, int mark)
693 {
694         int err = 0;
695         int werr = 0;
696         struct address_space *mapping = root->fs_info->btree_inode->i_mapping;
697         struct extent_state *cached_state = NULL;
698         u64 start = 0;
699         u64 end;
700
701         while (!find_first_extent_bit(dirty_pages, start, &start, &end,
702                                       mark, &cached_state)) {
703                 convert_extent_bit(dirty_pages, start, end, EXTENT_NEED_WAIT,
704                                    mark, &cached_state, GFP_NOFS);
705                 cached_state = NULL;
706                 err = filemap_fdatawrite_range(mapping, start, end);
707                 if (err)
708                         werr = err;
709                 cond_resched();
710                 start = end + 1;
711         }
712         if (err)
713                 werr = err;
714         return werr;
715 }
716
717 /*
718  * when btree blocks are allocated, they have some corresponding bits set for
719  * them in one of two extent_io trees.  This is used to make sure all of
720  * those extents are on disk for transaction or log commit.  We wait
721  * on all the pages and clear them from the dirty pages state tree
722  */
723 int btrfs_wait_marked_extents(struct btrfs_root *root,
724                               struct extent_io_tree *dirty_pages, int mark)
725 {
726         int err = 0;
727         int werr = 0;
728         struct address_space *mapping = root->fs_info->btree_inode->i_mapping;
729         struct extent_state *cached_state = NULL;
730         u64 start = 0;
731         u64 end;
732
733         while (!find_first_extent_bit(dirty_pages, start, &start, &end,
734                                       EXTENT_NEED_WAIT, &cached_state)) {
735                 clear_extent_bit(dirty_pages, start, end, EXTENT_NEED_WAIT,
736                                  0, 0, &cached_state, GFP_NOFS);
737                 err = filemap_fdatawait_range(mapping, start, end);
738                 if (err)
739                         werr = err;
740                 cond_resched();
741                 start = end + 1;
742         }
743         if (err)
744                 werr = err;
745         return werr;
746 }
747
748 /*
749  * when btree blocks are allocated, they have some corresponding bits set for
750  * them in one of two extent_io trees.  This is used to make sure all of
751  * those extents are on disk for transaction or log commit
752  */
753 int btrfs_write_and_wait_marked_extents(struct btrfs_root *root,
754                                 struct extent_io_tree *dirty_pages, int mark)
755 {
756         int ret;
757         int ret2;
758
759         ret = btrfs_write_marked_extents(root, dirty_pages, mark);
760         ret2 = btrfs_wait_marked_extents(root, dirty_pages, mark);
761
762         if (ret)
763                 return ret;
764         if (ret2)
765                 return ret2;
766         return 0;
767 }
768
769 int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans,
770                                      struct btrfs_root *root)
771 {
772         if (!trans || !trans->transaction) {
773                 struct inode *btree_inode;
774                 btree_inode = root->fs_info->btree_inode;
775                 return filemap_write_and_wait(btree_inode->i_mapping);
776         }
777         return btrfs_write_and_wait_marked_extents(root,
778                                            &trans->transaction->dirty_pages,
779                                            EXTENT_DIRTY);
780 }
781
782 /*
783  * this is used to update the root pointer in the tree of tree roots.
784  *
785  * But, in the case of the extent allocation tree, updating the root
786  * pointer may allocate blocks which may change the root of the extent
787  * allocation tree.
788  *
789  * So, this loops and repeats and makes sure the cowonly root didn't
790  * change while the root pointer was being updated in the metadata.
791  */
792 static int update_cowonly_root(struct btrfs_trans_handle *trans,
793                                struct btrfs_root *root)
794 {
795         int ret;
796         u64 old_root_bytenr;
797         u64 old_root_used;
798         struct btrfs_root *tree_root = root->fs_info->tree_root;
799
800         old_root_used = btrfs_root_used(&root->root_item);
801         btrfs_write_dirty_block_groups(trans, root);
802
803         while (1) {
804                 old_root_bytenr = btrfs_root_bytenr(&root->root_item);
805                 if (old_root_bytenr == root->node->start &&
806                     old_root_used == btrfs_root_used(&root->root_item))
807                         break;
808
809                 btrfs_set_root_node(&root->root_item, root->node);
810                 ret = btrfs_update_root(trans, tree_root,
811                                         &root->root_key,
812                                         &root->root_item);
813                 if (ret)
814                         return ret;
815
816                 old_root_used = btrfs_root_used(&root->root_item);
817                 ret = btrfs_write_dirty_block_groups(trans, root);
818                 if (ret)
819                         return ret;
820         }
821
822         if (root != root->fs_info->extent_root)
823                 switch_commit_root(root);
824
825         return 0;
826 }
827
828 /*
829  * update all the cowonly tree roots on disk
830  *
831  * The error handling in this function may not be obvious. Any of the
832  * failures will cause the file system to go offline. We still need
833  * to clean up the delayed refs.
834  */
835 static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans,
836                                          struct btrfs_root *root)
837 {
838         struct btrfs_fs_info *fs_info = root->fs_info;
839         struct list_head *next;
840         struct extent_buffer *eb;
841         int ret;
842
843         ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1);
844         if (ret)
845                 return ret;
846
847         eb = btrfs_lock_root_node(fs_info->tree_root);
848         ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
849                               0, &eb);
850         btrfs_tree_unlock(eb);
851         free_extent_buffer(eb);
852
853         if (ret)
854                 return ret;
855
856         ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1);
857         if (ret)
858                 return ret;
859
860         ret = btrfs_run_dev_stats(trans, root->fs_info);
861         WARN_ON(ret);
862         ret = btrfs_run_dev_replace(trans, root->fs_info);
863         WARN_ON(ret);
864
865         ret = btrfs_run_qgroups(trans, root->fs_info);
866         BUG_ON(ret);
867
868         /* run_qgroups might have added some more refs */
869         ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1);
870         BUG_ON(ret);
871
872         while (!list_empty(&fs_info->dirty_cowonly_roots)) {
873                 next = fs_info->dirty_cowonly_roots.next;
874                 list_del_init(next);
875                 root = list_entry(next, struct btrfs_root, dirty_list);
876
877                 ret = update_cowonly_root(trans, root);
878                 if (ret)
879                         return ret;
880         }
881
882         down_write(&fs_info->extent_commit_sem);
883         switch_commit_root(fs_info->extent_root);
884         up_write(&fs_info->extent_commit_sem);
885
886         btrfs_after_dev_replace_commit(fs_info);
887
888         return 0;
889 }
890
891 /*
892  * dead roots are old snapshots that need to be deleted.  This allocates
893  * a dirty root struct and adds it into the list of dead roots that need to
894  * be deleted
895  */
896 int btrfs_add_dead_root(struct btrfs_root *root)
897 {
898         spin_lock(&root->fs_info->trans_lock);
899         list_add(&root->root_list, &root->fs_info->dead_roots);
900         spin_unlock(&root->fs_info->trans_lock);
901         return 0;
902 }
903
904 /*
905  * update all the cowonly tree roots on disk
906  */
907 static noinline int commit_fs_roots(struct btrfs_trans_handle *trans,
908                                     struct btrfs_root *root)
909 {
910         struct btrfs_root *gang[8];
911         struct btrfs_fs_info *fs_info = root->fs_info;
912         int i;
913         int ret;
914         int err = 0;
915
916         spin_lock(&fs_info->fs_roots_radix_lock);
917         while (1) {
918                 ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
919                                                  (void **)gang, 0,
920                                                  ARRAY_SIZE(gang),
921                                                  BTRFS_ROOT_TRANS_TAG);
922                 if (ret == 0)
923                         break;
924                 for (i = 0; i < ret; i++) {
925                         root = gang[i];
926                         radix_tree_tag_clear(&fs_info->fs_roots_radix,
927                                         (unsigned long)root->root_key.objectid,
928                                         BTRFS_ROOT_TRANS_TAG);
929                         spin_unlock(&fs_info->fs_roots_radix_lock);
930
931                         btrfs_free_log(trans, root);
932                         btrfs_update_reloc_root(trans, root);
933                         btrfs_orphan_commit_root(trans, root);
934
935                         btrfs_save_ino_cache(root, trans);
936
937                         /* see comments in should_cow_block() */
938                         root->force_cow = 0;
939                         smp_wmb();
940
941                         if (root->commit_root != root->node) {
942                                 mutex_lock(&root->fs_commit_mutex);
943                                 switch_commit_root(root);
944                                 btrfs_unpin_free_ino(root);
945                                 mutex_unlock(&root->fs_commit_mutex);
946
947                                 btrfs_set_root_node(&root->root_item,
948                                                     root->node);
949                         }
950
951                         err = btrfs_update_root(trans, fs_info->tree_root,
952                                                 &root->root_key,
953                                                 &root->root_item);
954                         spin_lock(&fs_info->fs_roots_radix_lock);
955                         if (err)
956                                 break;
957                 }
958         }
959         spin_unlock(&fs_info->fs_roots_radix_lock);
960         return err;
961 }
962
963 /*
964  * defrag a given btree.
965  * Every leaf in the btree is read and defragged.
966  */
967 int btrfs_defrag_root(struct btrfs_root *root)
968 {
969         struct btrfs_fs_info *info = root->fs_info;
970         struct btrfs_trans_handle *trans;
971         int ret;
972
973         if (xchg(&root->defrag_running, 1))
974                 return 0;
975
976         while (1) {
977                 trans = btrfs_start_transaction(root, 0);
978                 if (IS_ERR(trans))
979                         return PTR_ERR(trans);
980
981                 ret = btrfs_defrag_leaves(trans, root);
982
983                 btrfs_end_transaction(trans, root);
984                 btrfs_btree_balance_dirty(info->tree_root);
985                 cond_resched();
986
987                 if (btrfs_fs_closing(root->fs_info) || ret != -EAGAIN)
988                         break;
989
990                 if (btrfs_defrag_cancelled(root->fs_info)) {
991                         printk(KERN_DEBUG "btrfs: defrag_root cancelled\n");
992                         ret = -EAGAIN;
993                         break;
994                 }
995         }
996         root->defrag_running = 0;
997         return ret;
998 }
999
1000 /*
1001  * new snapshots need to be created at a very specific time in the
1002  * transaction commit.  This does the actual creation
1003  */
1004 static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
1005                                    struct btrfs_fs_info *fs_info,
1006                                    struct btrfs_pending_snapshot *pending)
1007 {
1008         struct btrfs_key key;
1009         struct btrfs_root_item *new_root_item;
1010         struct btrfs_root *tree_root = fs_info->tree_root;
1011         struct btrfs_root *root = pending->root;
1012         struct btrfs_root *parent_root;
1013         struct btrfs_block_rsv *rsv;
1014         struct inode *parent_inode;
1015         struct btrfs_path *path;
1016         struct btrfs_dir_item *dir_item;
1017         struct dentry *parent;
1018         struct dentry *dentry;
1019         struct extent_buffer *tmp;
1020         struct extent_buffer *old;
1021         struct timespec cur_time = CURRENT_TIME;
1022         int ret;
1023         u64 to_reserve = 0;
1024         u64 index = 0;
1025         u64 objectid;
1026         u64 root_flags;
1027         uuid_le new_uuid;
1028
1029         path = btrfs_alloc_path();
1030         if (!path) {
1031                 ret = pending->error = -ENOMEM;
1032                 goto path_alloc_fail;
1033         }
1034
1035         new_root_item = kmalloc(sizeof(*new_root_item), GFP_NOFS);
1036         if (!new_root_item) {
1037                 ret = pending->error = -ENOMEM;
1038                 goto root_item_alloc_fail;
1039         }
1040
1041         ret = btrfs_find_free_objectid(tree_root, &objectid);
1042         if (ret) {
1043                 pending->error = ret;
1044                 goto no_free_objectid;
1045         }
1046
1047         btrfs_reloc_pre_snapshot(trans, pending, &to_reserve);
1048
1049         if (to_reserve > 0) {
1050                 ret = btrfs_block_rsv_add(root, &pending->block_rsv,
1051                                           to_reserve,
1052                                           BTRFS_RESERVE_NO_FLUSH);
1053                 if (ret) {
1054                         pending->error = ret;
1055                         goto no_free_objectid;
1056                 }
1057         }
1058
1059         ret = btrfs_qgroup_inherit(trans, fs_info, root->root_key.objectid,
1060                                    objectid, pending->inherit);
1061         if (ret) {
1062                 pending->error = ret;
1063                 goto no_free_objectid;
1064         }
1065
1066         key.objectid = objectid;
1067         key.offset = (u64)-1;
1068         key.type = BTRFS_ROOT_ITEM_KEY;
1069
1070         rsv = trans->block_rsv;
1071         trans->block_rsv = &pending->block_rsv;
1072
1073         dentry = pending->dentry;
1074         parent = dget_parent(dentry);
1075         parent_inode = parent->d_inode;
1076         parent_root = BTRFS_I(parent_inode)->root;
1077         record_root_in_trans(trans, parent_root);
1078
1079         /*
1080          * insert the directory item
1081          */
1082         ret = btrfs_set_inode_index(parent_inode, &index);
1083         BUG_ON(ret); /* -ENOMEM */
1084
1085         /* check if there is a file/dir which has the same name. */
1086         dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
1087                                          btrfs_ino(parent_inode),
1088                                          dentry->d_name.name,
1089                                          dentry->d_name.len, 0);
1090         if (dir_item != NULL && !IS_ERR(dir_item)) {
1091                 pending->error = -EEXIST;
1092                 goto fail;
1093         } else if (IS_ERR(dir_item)) {
1094                 ret = PTR_ERR(dir_item);
1095                 btrfs_abort_transaction(trans, root, ret);
1096                 goto fail;
1097         }
1098         btrfs_release_path(path);
1099
1100         /*
1101          * pull in the delayed directory update
1102          * and the delayed inode item
1103          * otherwise we corrupt the FS during
1104          * snapshot
1105          */
1106         ret = btrfs_run_delayed_items(trans, root);
1107         if (ret) {      /* Transaction aborted */
1108                 btrfs_abort_transaction(trans, root, ret);
1109                 goto fail;
1110         }
1111
1112         record_root_in_trans(trans, root);
1113         btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
1114         memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
1115         btrfs_check_and_init_root_item(new_root_item);
1116
1117         root_flags = btrfs_root_flags(new_root_item);
1118         if (pending->readonly)
1119                 root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1120         else
1121                 root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1122         btrfs_set_root_flags(new_root_item, root_flags);
1123
1124         btrfs_set_root_generation_v2(new_root_item,
1125                         trans->transid);
1126         uuid_le_gen(&new_uuid);
1127         memcpy(new_root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
1128         memcpy(new_root_item->parent_uuid, root->root_item.uuid,
1129                         BTRFS_UUID_SIZE);
1130         new_root_item->otime.sec = cpu_to_le64(cur_time.tv_sec);
1131         new_root_item->otime.nsec = cpu_to_le32(cur_time.tv_nsec);
1132         btrfs_set_root_otransid(new_root_item, trans->transid);
1133         memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
1134         memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
1135         btrfs_set_root_stransid(new_root_item, 0);
1136         btrfs_set_root_rtransid(new_root_item, 0);
1137
1138         old = btrfs_lock_root_node(root);
1139         ret = btrfs_cow_block(trans, root, old, NULL, 0, &old);
1140         if (ret) {
1141                 btrfs_tree_unlock(old);
1142                 free_extent_buffer(old);
1143                 btrfs_abort_transaction(trans, root, ret);
1144                 goto fail;
1145         }
1146
1147         btrfs_set_lock_blocking(old);
1148
1149         ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
1150         /* clean up in any case */
1151         btrfs_tree_unlock(old);
1152         free_extent_buffer(old);
1153         if (ret) {
1154                 btrfs_abort_transaction(trans, root, ret);
1155                 goto fail;
1156         }
1157
1158         /* see comments in should_cow_block() */
1159         root->force_cow = 1;
1160         smp_wmb();
1161
1162         btrfs_set_root_node(new_root_item, tmp);
1163         /* record when the snapshot was created in key.offset */
1164         key.offset = trans->transid;
1165         ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1166         btrfs_tree_unlock(tmp);
1167         free_extent_buffer(tmp);
1168         if (ret) {
1169                 btrfs_abort_transaction(trans, root, ret);
1170                 goto fail;
1171         }
1172
1173         /*
1174          * insert root back/forward references
1175          */
1176         ret = btrfs_add_root_ref(trans, tree_root, objectid,
1177                                  parent_root->root_key.objectid,
1178                                  btrfs_ino(parent_inode), index,
1179                                  dentry->d_name.name, dentry->d_name.len);
1180         if (ret) {
1181                 btrfs_abort_transaction(trans, root, ret);
1182                 goto fail;
1183         }
1184
1185         key.offset = (u64)-1;
1186         pending->snap = btrfs_read_fs_root_no_name(root->fs_info, &key);
1187         if (IS_ERR(pending->snap)) {
1188                 ret = PTR_ERR(pending->snap);
1189                 btrfs_abort_transaction(trans, root, ret);
1190                 goto fail;
1191         }
1192
1193         ret = btrfs_reloc_post_snapshot(trans, pending);
1194         if (ret) {
1195                 btrfs_abort_transaction(trans, root, ret);
1196                 goto fail;
1197         }
1198
1199         ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1);
1200         if (ret) {
1201                 btrfs_abort_transaction(trans, root, ret);
1202                 goto fail;
1203         }
1204
1205         ret = btrfs_insert_dir_item(trans, parent_root,
1206                                     dentry->d_name.name, dentry->d_name.len,
1207                                     parent_inode, &key,
1208                                     BTRFS_FT_DIR, index);
1209         /* We have check then name at the beginning, so it is impossible. */
1210         BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
1211         if (ret) {
1212                 btrfs_abort_transaction(trans, root, ret);
1213                 goto fail;
1214         }
1215
1216         btrfs_i_size_write(parent_inode, parent_inode->i_size +
1217                                          dentry->d_name.len * 2);
1218         parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
1219         ret = btrfs_update_inode_fallback(trans, parent_root, parent_inode);
1220         if (ret)
1221                 btrfs_abort_transaction(trans, root, ret);
1222 fail:
1223         dput(parent);
1224         trans->block_rsv = rsv;
1225 no_free_objectid:
1226         kfree(new_root_item);
1227 root_item_alloc_fail:
1228         btrfs_free_path(path);
1229 path_alloc_fail:
1230         btrfs_block_rsv_release(root, &pending->block_rsv, (u64)-1);
1231         return ret;
1232 }
1233
1234 /*
1235  * create all the snapshots we've scheduled for creation
1236  */
1237 static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans,
1238                                              struct btrfs_fs_info *fs_info)
1239 {
1240         struct btrfs_pending_snapshot *pending;
1241         struct list_head *head = &trans->transaction->pending_snapshots;
1242
1243         list_for_each_entry(pending, head, list)
1244                 create_pending_snapshot(trans, fs_info, pending);
1245         return 0;
1246 }
1247
1248 static void update_super_roots(struct btrfs_root *root)
1249 {
1250         struct btrfs_root_item *root_item;
1251         struct btrfs_super_block *super;
1252
1253         super = root->fs_info->super_copy;
1254
1255         root_item = &root->fs_info->chunk_root->root_item;
1256         super->chunk_root = root_item->bytenr;
1257         super->chunk_root_generation = root_item->generation;
1258         super->chunk_root_level = root_item->level;
1259
1260         root_item = &root->fs_info->tree_root->root_item;
1261         super->root = root_item->bytenr;
1262         super->generation = root_item->generation;
1263         super->root_level = root_item->level;
1264         if (btrfs_test_opt(root, SPACE_CACHE))
1265                 super->cache_generation = root_item->generation;
1266 }
1267
1268 int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1269 {
1270         int ret = 0;
1271         spin_lock(&info->trans_lock);
1272         if (info->running_transaction)
1273                 ret = info->running_transaction->in_commit;
1274         spin_unlock(&info->trans_lock);
1275         return ret;
1276 }
1277
1278 int btrfs_transaction_blocked(struct btrfs_fs_info *info)
1279 {
1280         int ret = 0;
1281         spin_lock(&info->trans_lock);
1282         if (info->running_transaction)
1283                 ret = info->running_transaction->blocked;
1284         spin_unlock(&info->trans_lock);
1285         return ret;
1286 }
1287
1288 /*
1289  * wait for the current transaction commit to start and block subsequent
1290  * transaction joins
1291  */
1292 static void wait_current_trans_commit_start(struct btrfs_root *root,
1293                                             struct btrfs_transaction *trans)
1294 {
1295         wait_event(root->fs_info->transaction_blocked_wait, trans->in_commit);
1296 }
1297
1298 /*
1299  * wait for the current transaction to start and then become unblocked.
1300  * caller holds ref.
1301  */
1302 static void wait_current_trans_commit_start_and_unblock(struct btrfs_root *root,
1303                                          struct btrfs_transaction *trans)
1304 {
1305         wait_event(root->fs_info->transaction_wait,
1306                    trans->commit_done || (trans->in_commit && !trans->blocked));
1307 }
1308
1309 /*
1310  * commit transactions asynchronously. once btrfs_commit_transaction_async
1311  * returns, any subsequent transaction will not be allowed to join.
1312  */
1313 struct btrfs_async_commit {
1314         struct btrfs_trans_handle *newtrans;
1315         struct btrfs_root *root;
1316         struct work_struct work;
1317 };
1318
1319 static void do_async_commit(struct work_struct *work)
1320 {
1321         struct btrfs_async_commit *ac =
1322                 container_of(work, struct btrfs_async_commit, work);
1323
1324         /*
1325          * We've got freeze protection passed with the transaction.
1326          * Tell lockdep about it.
1327          */
1328         if (ac->newtrans->type < TRANS_JOIN_NOLOCK)
1329                 rwsem_acquire_read(
1330                      &ac->root->fs_info->sb->s_writers.lock_map[SB_FREEZE_FS-1],
1331                      0, 1, _THIS_IP_);
1332
1333         current->journal_info = ac->newtrans;
1334
1335         btrfs_commit_transaction(ac->newtrans, ac->root);
1336         kfree(ac);
1337 }
1338
1339 int btrfs_commit_transaction_async(struct btrfs_trans_handle *trans,
1340                                    struct btrfs_root *root,
1341                                    int wait_for_unblock)
1342 {
1343         struct btrfs_async_commit *ac;
1344         struct btrfs_transaction *cur_trans;
1345
1346         ac = kmalloc(sizeof(*ac), GFP_NOFS);
1347         if (!ac)
1348                 return -ENOMEM;
1349
1350         INIT_WORK(&ac->work, do_async_commit);
1351         ac->root = root;
1352         ac->newtrans = btrfs_join_transaction(root);
1353         if (IS_ERR(ac->newtrans)) {
1354                 int err = PTR_ERR(ac->newtrans);
1355                 kfree(ac);
1356                 return err;
1357         }
1358
1359         /* take transaction reference */
1360         cur_trans = trans->transaction;
1361         atomic_inc(&cur_trans->use_count);
1362
1363         btrfs_end_transaction(trans, root);
1364
1365         /*
1366          * Tell lockdep we've released the freeze rwsem, since the
1367          * async commit thread will be the one to unlock it.
1368          */
1369         if (trans->type < TRANS_JOIN_NOLOCK)
1370                 rwsem_release(
1371                         &root->fs_info->sb->s_writers.lock_map[SB_FREEZE_FS-1],
1372                         1, _THIS_IP_);
1373
1374         schedule_work(&ac->work);
1375
1376         /* wait for transaction to start and unblock */
1377         if (wait_for_unblock)
1378                 wait_current_trans_commit_start_and_unblock(root, cur_trans);
1379         else
1380                 wait_current_trans_commit_start(root, cur_trans);
1381
1382         if (current->journal_info == trans)
1383                 current->journal_info = NULL;
1384
1385         put_transaction(cur_trans);
1386         return 0;
1387 }
1388
1389
1390 static void cleanup_transaction(struct btrfs_trans_handle *trans,
1391                                 struct btrfs_root *root, int err)
1392 {
1393         struct btrfs_transaction *cur_trans = trans->transaction;
1394
1395         WARN_ON(trans->use_count > 1);
1396
1397         btrfs_abort_transaction(trans, root, err);
1398
1399         spin_lock(&root->fs_info->trans_lock);
1400         list_del_init(&cur_trans->list);
1401         if (cur_trans == root->fs_info->running_transaction) {
1402                 root->fs_info->running_transaction = NULL;
1403                 root->fs_info->trans_no_join = 0;
1404         }
1405         spin_unlock(&root->fs_info->trans_lock);
1406
1407         btrfs_cleanup_one_transaction(trans->transaction, root);
1408
1409         put_transaction(cur_trans);
1410         put_transaction(cur_trans);
1411
1412         trace_btrfs_transaction_commit(root);
1413
1414         btrfs_scrub_continue(root);
1415
1416         if (current->journal_info == trans)
1417                 current->journal_info = NULL;
1418
1419         kmem_cache_free(btrfs_trans_handle_cachep, trans);
1420 }
1421
1422 static int btrfs_flush_all_pending_stuffs(struct btrfs_trans_handle *trans,
1423                                           struct btrfs_root *root)
1424 {
1425         int flush_on_commit = btrfs_test_opt(root, FLUSHONCOMMIT);
1426         int snap_pending = 0;
1427         int ret;
1428
1429         if (!flush_on_commit) {
1430                 spin_lock(&root->fs_info->trans_lock);
1431                 if (!list_empty(&trans->transaction->pending_snapshots))
1432                         snap_pending = 1;
1433                 spin_unlock(&root->fs_info->trans_lock);
1434         }
1435
1436         if (flush_on_commit || snap_pending) {
1437                 ret = btrfs_start_delalloc_inodes(root, 1);
1438                 if (ret)
1439                         return ret;
1440                 btrfs_wait_ordered_extents(root, 1);
1441         }
1442
1443         ret = btrfs_run_delayed_items(trans, root);
1444         if (ret)
1445                 return ret;
1446
1447         /*
1448          * running the delayed items may have added new refs. account
1449          * them now so that they hinder processing of more delayed refs
1450          * as little as possible.
1451          */
1452         btrfs_delayed_refs_qgroup_accounting(trans, root->fs_info);
1453
1454         /*
1455          * rename don't use btrfs_join_transaction, so, once we
1456          * set the transaction to blocked above, we aren't going
1457          * to get any new ordered operations.  We can safely run
1458          * it here and no for sure that nothing new will be added
1459          * to the list
1460          */
1461         ret = btrfs_run_ordered_operations(trans, root, 1);
1462
1463         return ret;
1464 }
1465
1466 /*
1467  * btrfs_transaction state sequence:
1468  *    in_commit = 0, blocked = 0  (initial)
1469  *    in_commit = 1, blocked = 1
1470  *    blocked = 0
1471  *    commit_done = 1
1472  */
1473 int btrfs_commit_transaction(struct btrfs_trans_handle *trans,
1474                              struct btrfs_root *root)
1475 {
1476         unsigned long joined = 0;
1477         struct btrfs_transaction *cur_trans = trans->transaction;
1478         struct btrfs_transaction *prev_trans = NULL;
1479         DEFINE_WAIT(wait);
1480         int ret;
1481         int should_grow = 0;
1482         unsigned long now = get_seconds();
1483
1484         ret = btrfs_run_ordered_operations(trans, root, 0);
1485         if (ret) {
1486                 btrfs_abort_transaction(trans, root, ret);
1487                 btrfs_end_transaction(trans, root);
1488                 return ret;
1489         }
1490
1491         /* Stop the commit early if ->aborted is set */
1492         if (unlikely(ACCESS_ONCE(cur_trans->aborted))) {
1493                 ret = cur_trans->aborted;
1494                 btrfs_end_transaction(trans, root);
1495                 return ret;
1496         }
1497
1498         /* make a pass through all the delayed refs we have so far
1499          * any runnings procs may add more while we are here
1500          */
1501         ret = btrfs_run_delayed_refs(trans, root, 0);
1502         if (ret) {
1503                 btrfs_end_transaction(trans, root);
1504                 return ret;
1505         }
1506
1507         btrfs_trans_release_metadata(trans, root);
1508         trans->block_rsv = NULL;
1509
1510         cur_trans = trans->transaction;
1511
1512         /*
1513          * set the flushing flag so procs in this transaction have to
1514          * start sending their work down.
1515          */
1516         cur_trans->delayed_refs.flushing = 1;
1517
1518         if (!list_empty(&trans->new_bgs))
1519                 btrfs_create_pending_block_groups(trans, root);
1520
1521         ret = btrfs_run_delayed_refs(trans, root, 0);
1522         if (ret) {
1523                 btrfs_end_transaction(trans, root);
1524                 return ret;
1525         }
1526
1527         spin_lock(&cur_trans->commit_lock);
1528         if (cur_trans->in_commit) {
1529                 spin_unlock(&cur_trans->commit_lock);
1530                 atomic_inc(&cur_trans->use_count);
1531                 ret = btrfs_end_transaction(trans, root);
1532
1533                 wait_for_commit(root, cur_trans);
1534
1535                 put_transaction(cur_trans);
1536
1537                 return ret;
1538         }
1539
1540         trans->transaction->in_commit = 1;
1541         trans->transaction->blocked = 1;
1542         spin_unlock(&cur_trans->commit_lock);
1543         wake_up(&root->fs_info->transaction_blocked_wait);
1544
1545         spin_lock(&root->fs_info->trans_lock);
1546         if (cur_trans->list.prev != &root->fs_info->trans_list) {
1547                 prev_trans = list_entry(cur_trans->list.prev,
1548                                         struct btrfs_transaction, list);
1549                 if (!prev_trans->commit_done) {
1550                         atomic_inc(&prev_trans->use_count);
1551                         spin_unlock(&root->fs_info->trans_lock);
1552
1553                         wait_for_commit(root, prev_trans);
1554
1555                         put_transaction(prev_trans);
1556                 } else {
1557                         spin_unlock(&root->fs_info->trans_lock);
1558                 }
1559         } else {
1560                 spin_unlock(&root->fs_info->trans_lock);
1561         }
1562
1563         if (!btrfs_test_opt(root, SSD) &&
1564             (now < cur_trans->start_time || now - cur_trans->start_time < 1))
1565                 should_grow = 1;
1566
1567         do {
1568                 joined = cur_trans->num_joined;
1569
1570                 WARN_ON(cur_trans != trans->transaction);
1571
1572                 ret = btrfs_flush_all_pending_stuffs(trans, root);
1573                 if (ret)
1574                         goto cleanup_transaction;
1575
1576                 prepare_to_wait(&cur_trans->writer_wait, &wait,
1577                                 TASK_UNINTERRUPTIBLE);
1578
1579                 if (atomic_read(&cur_trans->num_writers) > 1)
1580                         schedule_timeout(MAX_SCHEDULE_TIMEOUT);
1581                 else if (should_grow)
1582                         schedule_timeout(1);
1583
1584                 finish_wait(&cur_trans->writer_wait, &wait);
1585         } while (atomic_read(&cur_trans->num_writers) > 1 ||
1586                  (should_grow && cur_trans->num_joined != joined));
1587
1588         ret = btrfs_flush_all_pending_stuffs(trans, root);
1589         if (ret)
1590                 goto cleanup_transaction;
1591
1592         /*
1593          * Ok now we need to make sure to block out any other joins while we
1594          * commit the transaction.  We could have started a join before setting
1595          * no_join so make sure to wait for num_writers to == 1 again.
1596          */
1597         spin_lock(&root->fs_info->trans_lock);
1598         root->fs_info->trans_no_join = 1;
1599         spin_unlock(&root->fs_info->trans_lock);
1600         wait_event(cur_trans->writer_wait,
1601                    atomic_read(&cur_trans->num_writers) == 1);
1602
1603         /* ->aborted might be set after the previous check, so check it */
1604         if (unlikely(ACCESS_ONCE(cur_trans->aborted))) {
1605                 ret = cur_trans->aborted;
1606                 goto cleanup_transaction;
1607         }
1608         /*
1609          * the reloc mutex makes sure that we stop
1610          * the balancing code from coming in and moving
1611          * extents around in the middle of the commit
1612          */
1613         mutex_lock(&root->fs_info->reloc_mutex);
1614
1615         /*
1616          * We needn't worry about the delayed items because we will
1617          * deal with them in create_pending_snapshot(), which is the
1618          * core function of the snapshot creation.
1619          */
1620         ret = create_pending_snapshots(trans, root->fs_info);
1621         if (ret) {
1622                 mutex_unlock(&root->fs_info->reloc_mutex);
1623                 goto cleanup_transaction;
1624         }
1625
1626         /*
1627          * We insert the dir indexes of the snapshots and update the inode
1628          * of the snapshots' parents after the snapshot creation, so there
1629          * are some delayed items which are not dealt with. Now deal with
1630          * them.
1631          *
1632          * We needn't worry that this operation will corrupt the snapshots,
1633          * because all the tree which are snapshoted will be forced to COW
1634          * the nodes and leaves.
1635          */
1636         ret = btrfs_run_delayed_items(trans, root);
1637         if (ret) {
1638                 mutex_unlock(&root->fs_info->reloc_mutex);
1639                 goto cleanup_transaction;
1640         }
1641
1642         ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1);
1643         if (ret) {
1644                 mutex_unlock(&root->fs_info->reloc_mutex);
1645                 goto cleanup_transaction;
1646         }
1647
1648         /*
1649          * make sure none of the code above managed to slip in a
1650          * delayed item
1651          */
1652         btrfs_assert_delayed_root_empty(root);
1653
1654         WARN_ON(cur_trans != trans->transaction);
1655
1656         btrfs_scrub_pause(root);
1657         /* btrfs_commit_tree_roots is responsible for getting the
1658          * various roots consistent with each other.  Every pointer
1659          * in the tree of tree roots has to point to the most up to date
1660          * root for every subvolume and other tree.  So, we have to keep
1661          * the tree logging code from jumping in and changing any
1662          * of the trees.
1663          *
1664          * At this point in the commit, there can't be any tree-log
1665          * writers, but a little lower down we drop the trans mutex
1666          * and let new people in.  By holding the tree_log_mutex
1667          * from now until after the super is written, we avoid races
1668          * with the tree-log code.
1669          */
1670         mutex_lock(&root->fs_info->tree_log_mutex);
1671
1672         ret = commit_fs_roots(trans, root);
1673         if (ret) {
1674                 mutex_unlock(&root->fs_info->tree_log_mutex);
1675                 mutex_unlock(&root->fs_info->reloc_mutex);
1676                 goto cleanup_transaction;
1677         }
1678
1679         /* commit_fs_roots gets rid of all the tree log roots, it is now
1680          * safe to free the root of tree log roots
1681          */
1682         btrfs_free_log_root_tree(trans, root->fs_info);
1683
1684         ret = commit_cowonly_roots(trans, root);
1685         if (ret) {
1686                 mutex_unlock(&root->fs_info->tree_log_mutex);
1687                 mutex_unlock(&root->fs_info->reloc_mutex);
1688                 goto cleanup_transaction;
1689         }
1690
1691         /*
1692          * The tasks which save the space cache and inode cache may also
1693          * update ->aborted, check it.
1694          */
1695         if (unlikely(ACCESS_ONCE(cur_trans->aborted))) {
1696                 ret = cur_trans->aborted;
1697                 mutex_unlock(&root->fs_info->tree_log_mutex);
1698                 mutex_unlock(&root->fs_info->reloc_mutex);
1699                 goto cleanup_transaction;
1700         }
1701
1702         btrfs_prepare_extent_commit(trans, root);
1703
1704         cur_trans = root->fs_info->running_transaction;
1705
1706         btrfs_set_root_node(&root->fs_info->tree_root->root_item,
1707                             root->fs_info->tree_root->node);
1708         switch_commit_root(root->fs_info->tree_root);
1709
1710         btrfs_set_root_node(&root->fs_info->chunk_root->root_item,
1711                             root->fs_info->chunk_root->node);
1712         switch_commit_root(root->fs_info->chunk_root);
1713
1714         assert_qgroups_uptodate(trans);
1715         update_super_roots(root);
1716
1717         if (!root->fs_info->log_root_recovering) {
1718                 btrfs_set_super_log_root(root->fs_info->super_copy, 0);
1719                 btrfs_set_super_log_root_level(root->fs_info->super_copy, 0);
1720         }
1721
1722         memcpy(root->fs_info->super_for_commit, root->fs_info->super_copy,
1723                sizeof(*root->fs_info->super_copy));
1724
1725         trans->transaction->blocked = 0;
1726         spin_lock(&root->fs_info->trans_lock);
1727         root->fs_info->running_transaction = NULL;
1728         root->fs_info->trans_no_join = 0;
1729         spin_unlock(&root->fs_info->trans_lock);
1730         mutex_unlock(&root->fs_info->reloc_mutex);
1731
1732         wake_up(&root->fs_info->transaction_wait);
1733
1734         ret = btrfs_write_and_wait_transaction(trans, root);
1735         if (ret) {
1736                 btrfs_error(root->fs_info, ret,
1737                             "Error while writing out transaction.");
1738                 mutex_unlock(&root->fs_info->tree_log_mutex);
1739                 goto cleanup_transaction;
1740         }
1741
1742         ret = write_ctree_super(trans, root, 0);
1743         if (ret) {
1744                 mutex_unlock(&root->fs_info->tree_log_mutex);
1745                 goto cleanup_transaction;
1746         }
1747
1748         /*
1749          * the super is written, we can safely allow the tree-loggers
1750          * to go about their business
1751          */
1752         mutex_unlock(&root->fs_info->tree_log_mutex);
1753
1754         btrfs_finish_extent_commit(trans, root);
1755
1756         cur_trans->commit_done = 1;
1757
1758         root->fs_info->last_trans_committed = cur_trans->transid;
1759
1760         wake_up(&cur_trans->commit_wait);
1761
1762         spin_lock(&root->fs_info->trans_lock);
1763         list_del_init(&cur_trans->list);
1764         spin_unlock(&root->fs_info->trans_lock);
1765
1766         put_transaction(cur_trans);
1767         put_transaction(cur_trans);
1768
1769         if (trans->type < TRANS_JOIN_NOLOCK)
1770                 sb_end_intwrite(root->fs_info->sb);
1771
1772         trace_btrfs_transaction_commit(root);
1773
1774         btrfs_scrub_continue(root);
1775
1776         if (current->journal_info == trans)
1777                 current->journal_info = NULL;
1778
1779         kmem_cache_free(btrfs_trans_handle_cachep, trans);
1780
1781         if (current != root->fs_info->transaction_kthread)
1782                 btrfs_run_delayed_iputs(root);
1783
1784         return ret;
1785
1786 cleanup_transaction:
1787         btrfs_trans_release_metadata(trans, root);
1788         trans->block_rsv = NULL;
1789         btrfs_printk(root->fs_info, "Skipping commit of aborted transaction.\n");
1790 //      WARN_ON(1);
1791         if (current->journal_info == trans)
1792                 current->journal_info = NULL;
1793         cleanup_transaction(trans, root, ret);
1794
1795         return ret;
1796 }
1797
1798 /*
1799  * interface function to delete all the snapshots we have scheduled for deletion
1800  */
1801 int btrfs_clean_old_snapshots(struct btrfs_root *root)
1802 {
1803         LIST_HEAD(list);
1804         struct btrfs_fs_info *fs_info = root->fs_info;
1805
1806         spin_lock(&fs_info->trans_lock);
1807         list_splice_init(&fs_info->dead_roots, &list);
1808         spin_unlock(&fs_info->trans_lock);
1809
1810         while (!list_empty(&list)) {
1811                 int ret;
1812
1813                 root = list_entry(list.next, struct btrfs_root, root_list);
1814                 list_del(&root->root_list);
1815
1816                 btrfs_kill_all_delayed_nodes(root);
1817
1818                 if (btrfs_header_backref_rev(root->node) <
1819                     BTRFS_MIXED_BACKREF_REV)
1820                         ret = btrfs_drop_snapshot(root, NULL, 0, 0);
1821                 else
1822                         ret =btrfs_drop_snapshot(root, NULL, 1, 0);
1823                 BUG_ON(ret < 0);
1824         }
1825         return 0;
1826 }