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