GNU Linux-libre 4.19.211-gnu1
[releases.git] / fs / btrfs / transaction.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5
6 #include <linux/fs.h>
7 #include <linux/slab.h>
8 #include <linux/sched.h>
9 #include <linux/writeback.h>
10 #include <linux/pagemap.h>
11 #include <linux/blkdev.h>
12 #include <linux/uuid.h>
13 #include "ctree.h"
14 #include "disk-io.h"
15 #include "transaction.h"
16 #include "locking.h"
17 #include "tree-log.h"
18 #include "inode-map.h"
19 #include "volumes.h"
20 #include "dev-replace.h"
21 #include "qgroup.h"
22
23 #define BTRFS_ROOT_TRANS_TAG 0
24
25 static const unsigned int btrfs_blocked_trans_types[TRANS_STATE_MAX] = {
26         [TRANS_STATE_RUNNING]           = 0U,
27         [TRANS_STATE_BLOCKED]           =  __TRANS_START,
28         [TRANS_STATE_COMMIT_START]      = (__TRANS_START | __TRANS_ATTACH),
29         [TRANS_STATE_COMMIT_DOING]      = (__TRANS_START |
30                                            __TRANS_ATTACH |
31                                            __TRANS_JOIN |
32                                            __TRANS_JOIN_NOSTART),
33         [TRANS_STATE_UNBLOCKED]         = (__TRANS_START |
34                                            __TRANS_ATTACH |
35                                            __TRANS_JOIN |
36                                            __TRANS_JOIN_NOLOCK |
37                                            __TRANS_JOIN_NOSTART),
38         [TRANS_STATE_COMPLETED]         = (__TRANS_START |
39                                            __TRANS_ATTACH |
40                                            __TRANS_JOIN |
41                                            __TRANS_JOIN_NOLOCK |
42                                            __TRANS_JOIN_NOSTART),
43 };
44
45 void btrfs_put_transaction(struct btrfs_transaction *transaction)
46 {
47         WARN_ON(refcount_read(&transaction->use_count) == 0);
48         if (refcount_dec_and_test(&transaction->use_count)) {
49                 BUG_ON(!list_empty(&transaction->list));
50                 WARN_ON(!RB_EMPTY_ROOT(&transaction->delayed_refs.href_root));
51                 if (transaction->delayed_refs.pending_csums)
52                         btrfs_err(transaction->fs_info,
53                                   "pending csums is %llu",
54                                   transaction->delayed_refs.pending_csums);
55                 while (!list_empty(&transaction->pending_chunks)) {
56                         struct extent_map *em;
57
58                         em = list_first_entry(&transaction->pending_chunks,
59                                               struct extent_map, list);
60                         list_del_init(&em->list);
61                         free_extent_map(em);
62                 }
63                 /*
64                  * If any block groups are found in ->deleted_bgs then it's
65                  * because the transaction was aborted and a commit did not
66                  * happen (things failed before writing the new superblock
67                  * and calling btrfs_finish_extent_commit()), so we can not
68                  * discard the physical locations of the block groups.
69                  */
70                 while (!list_empty(&transaction->deleted_bgs)) {
71                         struct btrfs_block_group_cache *cache;
72
73                         cache = list_first_entry(&transaction->deleted_bgs,
74                                                  struct btrfs_block_group_cache,
75                                                  bg_list);
76                         list_del_init(&cache->bg_list);
77                         btrfs_put_block_group_trimming(cache);
78                         btrfs_put_block_group(cache);
79                 }
80                 kfree(transaction);
81         }
82 }
83
84 static void clear_btree_io_tree(struct extent_io_tree *tree)
85 {
86         spin_lock(&tree->lock);
87         /*
88          * Do a single barrier for the waitqueue_active check here, the state
89          * of the waitqueue should not change once clear_btree_io_tree is
90          * called.
91          */
92         smp_mb();
93         while (!RB_EMPTY_ROOT(&tree->state)) {
94                 struct rb_node *node;
95                 struct extent_state *state;
96
97                 node = rb_first(&tree->state);
98                 state = rb_entry(node, struct extent_state, rb_node);
99                 rb_erase(&state->rb_node, &tree->state);
100                 RB_CLEAR_NODE(&state->rb_node);
101                 /*
102                  * btree io trees aren't supposed to have tasks waiting for
103                  * changes in the flags of extent states ever.
104                  */
105                 ASSERT(!waitqueue_active(&state->wq));
106                 free_extent_state(state);
107
108                 cond_resched_lock(&tree->lock);
109         }
110         spin_unlock(&tree->lock);
111 }
112
113 static noinline void switch_commit_roots(struct btrfs_transaction *trans)
114 {
115         struct btrfs_fs_info *fs_info = trans->fs_info;
116         struct btrfs_root *root, *tmp;
117
118         down_write(&fs_info->commit_root_sem);
119         list_for_each_entry_safe(root, tmp, &trans->switch_commits,
120                                  dirty_list) {
121                 list_del_init(&root->dirty_list);
122                 free_extent_buffer(root->commit_root);
123                 root->commit_root = btrfs_root_node(root);
124                 if (is_fstree(root->objectid))
125                         btrfs_unpin_free_ino(root);
126                 clear_btree_io_tree(&root->dirty_log_pages);
127         }
128
129         /* We can free old roots now. */
130         spin_lock(&trans->dropped_roots_lock);
131         while (!list_empty(&trans->dropped_roots)) {
132                 root = list_first_entry(&trans->dropped_roots,
133                                         struct btrfs_root, root_list);
134                 list_del_init(&root->root_list);
135                 spin_unlock(&trans->dropped_roots_lock);
136                 btrfs_drop_and_free_fs_root(fs_info, root);
137                 spin_lock(&trans->dropped_roots_lock);
138         }
139         spin_unlock(&trans->dropped_roots_lock);
140         up_write(&fs_info->commit_root_sem);
141 }
142
143 static inline void extwriter_counter_inc(struct btrfs_transaction *trans,
144                                          unsigned int type)
145 {
146         if (type & TRANS_EXTWRITERS)
147                 atomic_inc(&trans->num_extwriters);
148 }
149
150 static inline void extwriter_counter_dec(struct btrfs_transaction *trans,
151                                          unsigned int type)
152 {
153         if (type & TRANS_EXTWRITERS)
154                 atomic_dec(&trans->num_extwriters);
155 }
156
157 static inline void extwriter_counter_init(struct btrfs_transaction *trans,
158                                           unsigned int type)
159 {
160         atomic_set(&trans->num_extwriters, ((type & TRANS_EXTWRITERS) ? 1 : 0));
161 }
162
163 static inline int extwriter_counter_read(struct btrfs_transaction *trans)
164 {
165         return atomic_read(&trans->num_extwriters);
166 }
167
168 /*
169  * either allocate a new transaction or hop into the existing one
170  */
171 static noinline int join_transaction(struct btrfs_fs_info *fs_info,
172                                      unsigned int type)
173 {
174         struct btrfs_transaction *cur_trans;
175
176         spin_lock(&fs_info->trans_lock);
177 loop:
178         /* The file system has been taken offline. No new transactions. */
179         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
180                 spin_unlock(&fs_info->trans_lock);
181                 return -EROFS;
182         }
183
184         cur_trans = fs_info->running_transaction;
185         if (cur_trans) {
186                 if (cur_trans->aborted) {
187                         spin_unlock(&fs_info->trans_lock);
188                         return cur_trans->aborted;
189                 }
190                 if (btrfs_blocked_trans_types[cur_trans->state] & type) {
191                         spin_unlock(&fs_info->trans_lock);
192                         return -EBUSY;
193                 }
194                 refcount_inc(&cur_trans->use_count);
195                 atomic_inc(&cur_trans->num_writers);
196                 extwriter_counter_inc(cur_trans, type);
197                 spin_unlock(&fs_info->trans_lock);
198                 return 0;
199         }
200         spin_unlock(&fs_info->trans_lock);
201
202         /*
203          * If we are ATTACH, we just want to catch the current transaction,
204          * and commit it. If there is no transaction, just return ENOENT.
205          */
206         if (type == TRANS_ATTACH)
207                 return -ENOENT;
208
209         /*
210          * JOIN_NOLOCK only happens during the transaction commit, so
211          * it is impossible that ->running_transaction is NULL
212          */
213         BUG_ON(type == TRANS_JOIN_NOLOCK);
214
215         cur_trans = kmalloc(sizeof(*cur_trans), GFP_NOFS);
216         if (!cur_trans)
217                 return -ENOMEM;
218
219         spin_lock(&fs_info->trans_lock);
220         if (fs_info->running_transaction) {
221                 /*
222                  * someone started a transaction after we unlocked.  Make sure
223                  * to redo the checks above
224                  */
225                 kfree(cur_trans);
226                 goto loop;
227         } else if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
228                 spin_unlock(&fs_info->trans_lock);
229                 kfree(cur_trans);
230                 return -EROFS;
231         }
232
233         cur_trans->fs_info = fs_info;
234         atomic_set(&cur_trans->num_writers, 1);
235         extwriter_counter_init(cur_trans, type);
236         init_waitqueue_head(&cur_trans->writer_wait);
237         init_waitqueue_head(&cur_trans->commit_wait);
238         init_waitqueue_head(&cur_trans->pending_wait);
239         cur_trans->state = TRANS_STATE_RUNNING;
240         /*
241          * One for this trans handle, one so it will live on until we
242          * commit the transaction.
243          */
244         refcount_set(&cur_trans->use_count, 2);
245         atomic_set(&cur_trans->pending_ordered, 0);
246         cur_trans->flags = 0;
247         cur_trans->start_time = ktime_get_seconds();
248
249         memset(&cur_trans->delayed_refs, 0, sizeof(cur_trans->delayed_refs));
250
251         cur_trans->delayed_refs.href_root = RB_ROOT;
252         cur_trans->delayed_refs.dirty_extent_root = RB_ROOT;
253         atomic_set(&cur_trans->delayed_refs.num_entries, 0);
254
255         /*
256          * although the tree mod log is per file system and not per transaction,
257          * the log must never go across transaction boundaries.
258          */
259         smp_mb();
260         if (!list_empty(&fs_info->tree_mod_seq_list))
261                 WARN(1, KERN_ERR "BTRFS: tree_mod_seq_list not empty when creating a fresh transaction\n");
262         if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log))
263                 WARN(1, KERN_ERR "BTRFS: tree_mod_log rb tree not empty when creating a fresh transaction\n");
264         atomic64_set(&fs_info->tree_mod_seq, 0);
265
266         spin_lock_init(&cur_trans->delayed_refs.lock);
267
268         INIT_LIST_HEAD(&cur_trans->pending_snapshots);
269         INIT_LIST_HEAD(&cur_trans->pending_chunks);
270         INIT_LIST_HEAD(&cur_trans->switch_commits);
271         INIT_LIST_HEAD(&cur_trans->dirty_bgs);
272         INIT_LIST_HEAD(&cur_trans->io_bgs);
273         INIT_LIST_HEAD(&cur_trans->dropped_roots);
274         mutex_init(&cur_trans->cache_write_mutex);
275         cur_trans->num_dirty_bgs = 0;
276         spin_lock_init(&cur_trans->dirty_bgs_lock);
277         INIT_LIST_HEAD(&cur_trans->deleted_bgs);
278         spin_lock_init(&cur_trans->dropped_roots_lock);
279         list_add_tail(&cur_trans->list, &fs_info->trans_list);
280         extent_io_tree_init(&cur_trans->dirty_pages,
281                              fs_info->btree_inode);
282         fs_info->generation++;
283         cur_trans->transid = fs_info->generation;
284         fs_info->running_transaction = cur_trans;
285         cur_trans->aborted = 0;
286         spin_unlock(&fs_info->trans_lock);
287
288         return 0;
289 }
290
291 /*
292  * this does all the record keeping required to make sure that a reference
293  * counted root is properly recorded in a given transaction.  This is required
294  * to make sure the old root from before we joined the transaction is deleted
295  * when the transaction commits
296  */
297 static int record_root_in_trans(struct btrfs_trans_handle *trans,
298                                struct btrfs_root *root,
299                                int force)
300 {
301         struct btrfs_fs_info *fs_info = root->fs_info;
302
303         if ((test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
304             root->last_trans < trans->transid) || force) {
305                 WARN_ON(root == fs_info->extent_root);
306                 WARN_ON(!force && root->commit_root != root->node);
307
308                 /*
309                  * see below for IN_TRANS_SETUP usage rules
310                  * we have the reloc mutex held now, so there
311                  * is only one writer in this function
312                  */
313                 set_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
314
315                 /* make sure readers find IN_TRANS_SETUP before
316                  * they find our root->last_trans update
317                  */
318                 smp_wmb();
319
320                 spin_lock(&fs_info->fs_roots_radix_lock);
321                 if (root->last_trans == trans->transid && !force) {
322                         spin_unlock(&fs_info->fs_roots_radix_lock);
323                         return 0;
324                 }
325                 radix_tree_tag_set(&fs_info->fs_roots_radix,
326                                    (unsigned long)root->root_key.objectid,
327                                    BTRFS_ROOT_TRANS_TAG);
328                 spin_unlock(&fs_info->fs_roots_radix_lock);
329                 root->last_trans = trans->transid;
330
331                 /* this is pretty tricky.  We don't want to
332                  * take the relocation lock in btrfs_record_root_in_trans
333                  * unless we're really doing the first setup for this root in
334                  * this transaction.
335                  *
336                  * Normally we'd use root->last_trans as a flag to decide
337                  * if we want to take the expensive mutex.
338                  *
339                  * But, we have to set root->last_trans before we
340                  * init the relocation root, otherwise, we trip over warnings
341                  * in ctree.c.  The solution used here is to flag ourselves
342                  * with root IN_TRANS_SETUP.  When this is 1, we're still
343                  * fixing up the reloc trees and everyone must wait.
344                  *
345                  * When this is zero, they can trust root->last_trans and fly
346                  * through btrfs_record_root_in_trans without having to take the
347                  * lock.  smp_wmb() makes sure that all the writes above are
348                  * done before we pop in the zero below
349                  */
350                 btrfs_init_reloc_root(trans, root);
351                 smp_mb__before_atomic();
352                 clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
353         }
354         return 0;
355 }
356
357
358 void btrfs_add_dropped_root(struct btrfs_trans_handle *trans,
359                             struct btrfs_root *root)
360 {
361         struct btrfs_fs_info *fs_info = root->fs_info;
362         struct btrfs_transaction *cur_trans = trans->transaction;
363
364         /* Add ourselves to the transaction dropped list */
365         spin_lock(&cur_trans->dropped_roots_lock);
366         list_add_tail(&root->root_list, &cur_trans->dropped_roots);
367         spin_unlock(&cur_trans->dropped_roots_lock);
368
369         /* Make sure we don't try to update the root at commit time */
370         spin_lock(&fs_info->fs_roots_radix_lock);
371         radix_tree_tag_clear(&fs_info->fs_roots_radix,
372                              (unsigned long)root->root_key.objectid,
373                              BTRFS_ROOT_TRANS_TAG);
374         spin_unlock(&fs_info->fs_roots_radix_lock);
375 }
376
377 int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
378                                struct btrfs_root *root)
379 {
380         struct btrfs_fs_info *fs_info = root->fs_info;
381
382         if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
383                 return 0;
384
385         /*
386          * see record_root_in_trans for comments about IN_TRANS_SETUP usage
387          * and barriers
388          */
389         smp_rmb();
390         if (root->last_trans == trans->transid &&
391             !test_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state))
392                 return 0;
393
394         mutex_lock(&fs_info->reloc_mutex);
395         record_root_in_trans(trans, root, 0);
396         mutex_unlock(&fs_info->reloc_mutex);
397
398         return 0;
399 }
400
401 static inline int is_transaction_blocked(struct btrfs_transaction *trans)
402 {
403         return (trans->state >= TRANS_STATE_BLOCKED &&
404                 trans->state < TRANS_STATE_UNBLOCKED &&
405                 !trans->aborted);
406 }
407
408 /* wait for commit against the current transaction to become unblocked
409  * when this is done, it is safe to start a new transaction, but the current
410  * transaction might not be fully on disk.
411  */
412 static void wait_current_trans(struct btrfs_fs_info *fs_info)
413 {
414         struct btrfs_transaction *cur_trans;
415
416         spin_lock(&fs_info->trans_lock);
417         cur_trans = fs_info->running_transaction;
418         if (cur_trans && is_transaction_blocked(cur_trans)) {
419                 refcount_inc(&cur_trans->use_count);
420                 spin_unlock(&fs_info->trans_lock);
421
422                 wait_event(fs_info->transaction_wait,
423                            cur_trans->state >= TRANS_STATE_UNBLOCKED ||
424                            cur_trans->aborted);
425                 btrfs_put_transaction(cur_trans);
426         } else {
427                 spin_unlock(&fs_info->trans_lock);
428         }
429 }
430
431 static int may_wait_transaction(struct btrfs_fs_info *fs_info, int type)
432 {
433         if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
434                 return 0;
435
436         if (type == TRANS_START)
437                 return 1;
438
439         return 0;
440 }
441
442 static inline bool need_reserve_reloc_root(struct btrfs_root *root)
443 {
444         struct btrfs_fs_info *fs_info = root->fs_info;
445
446         if (!fs_info->reloc_ctl ||
447             !test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
448             root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
449             root->reloc_root)
450                 return false;
451
452         return true;
453 }
454
455 static struct btrfs_trans_handle *
456 start_transaction(struct btrfs_root *root, unsigned int num_items,
457                   unsigned int type, enum btrfs_reserve_flush_enum flush,
458                   bool enforce_qgroups)
459 {
460         struct btrfs_fs_info *fs_info = root->fs_info;
461
462         struct btrfs_trans_handle *h;
463         struct btrfs_transaction *cur_trans;
464         u64 num_bytes = 0;
465         u64 qgroup_reserved = 0;
466         bool reloc_reserved = false;
467         int ret;
468
469         /* Send isn't supposed to start transactions. */
470         ASSERT(current->journal_info != BTRFS_SEND_TRANS_STUB);
471
472         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
473                 return ERR_PTR(-EROFS);
474
475         if (current->journal_info) {
476                 WARN_ON(type & TRANS_EXTWRITERS);
477                 h = current->journal_info;
478                 refcount_inc(&h->use_count);
479                 WARN_ON(refcount_read(&h->use_count) > 2);
480                 h->orig_rsv = h->block_rsv;
481                 h->block_rsv = NULL;
482                 goto got_it;
483         }
484
485         /*
486          * Do the reservation before we join the transaction so we can do all
487          * the appropriate flushing if need be.
488          */
489         if (num_items && root != fs_info->chunk_root) {
490                 qgroup_reserved = num_items * fs_info->nodesize;
491                 ret = btrfs_qgroup_reserve_meta_pertrans(root, qgroup_reserved,
492                                 enforce_qgroups);
493                 if (ret)
494                         return ERR_PTR(ret);
495
496                 num_bytes = btrfs_calc_trans_metadata_size(fs_info, num_items);
497                 /*
498                  * Do the reservation for the relocation root creation
499                  */
500                 if (need_reserve_reloc_root(root)) {
501                         num_bytes += fs_info->nodesize;
502                         reloc_reserved = true;
503                 }
504
505                 ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
506                                           num_bytes, flush);
507                 if (ret)
508                         goto reserve_fail;
509         }
510 again:
511         h = kmem_cache_zalloc(btrfs_trans_handle_cachep, GFP_NOFS);
512         if (!h) {
513                 ret = -ENOMEM;
514                 goto alloc_fail;
515         }
516
517         /*
518          * If we are JOIN_NOLOCK we're already committing a transaction and
519          * waiting on this guy, so we don't need to do the sb_start_intwrite
520          * because we're already holding a ref.  We need this because we could
521          * have raced in and did an fsync() on a file which can kick a commit
522          * and then we deadlock with somebody doing a freeze.
523          *
524          * If we are ATTACH, it means we just want to catch the current
525          * transaction and commit it, so we needn't do sb_start_intwrite(). 
526          */
527         if (type & __TRANS_FREEZABLE)
528                 sb_start_intwrite(fs_info->sb);
529
530         if (may_wait_transaction(fs_info, type))
531                 wait_current_trans(fs_info);
532
533         do {
534                 ret = join_transaction(fs_info, type);
535                 if (ret == -EBUSY) {
536                         wait_current_trans(fs_info);
537                         if (unlikely(type == TRANS_ATTACH ||
538                                      type == TRANS_JOIN_NOSTART))
539                                 ret = -ENOENT;
540                 }
541         } while (ret == -EBUSY);
542
543         if (ret < 0)
544                 goto join_fail;
545
546         cur_trans = fs_info->running_transaction;
547
548         h->transid = cur_trans->transid;
549         h->transaction = cur_trans;
550         h->root = root;
551         refcount_set(&h->use_count, 1);
552         h->fs_info = root->fs_info;
553
554         h->type = type;
555         h->can_flush_pending_bgs = true;
556         INIT_LIST_HEAD(&h->new_bgs);
557
558         smp_mb();
559         if (cur_trans->state >= TRANS_STATE_BLOCKED &&
560             may_wait_transaction(fs_info, type)) {
561                 current->journal_info = h;
562                 btrfs_commit_transaction(h);
563                 goto again;
564         }
565
566         if (num_bytes) {
567                 trace_btrfs_space_reservation(fs_info, "transaction",
568                                               h->transid, num_bytes, 1);
569                 h->block_rsv = &fs_info->trans_block_rsv;
570                 h->bytes_reserved = num_bytes;
571                 h->reloc_reserved = reloc_reserved;
572         }
573
574 got_it:
575         if (!current->journal_info)
576                 current->journal_info = h;
577
578         /*
579          * btrfs_record_root_in_trans() needs to alloc new extents, and may
580          * call btrfs_join_transaction() while we're also starting a
581          * transaction.
582          *
583          * Thus it need to be called after current->journal_info initialized,
584          * or we can deadlock.
585          */
586         btrfs_record_root_in_trans(h, root);
587
588         return h;
589
590 join_fail:
591         if (type & __TRANS_FREEZABLE)
592                 sb_end_intwrite(fs_info->sb);
593         kmem_cache_free(btrfs_trans_handle_cachep, h);
594 alloc_fail:
595         if (num_bytes)
596                 btrfs_block_rsv_release(fs_info, &fs_info->trans_block_rsv,
597                                         num_bytes);
598 reserve_fail:
599         btrfs_qgroup_free_meta_pertrans(root, qgroup_reserved);
600         return ERR_PTR(ret);
601 }
602
603 struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
604                                                    unsigned int num_items)
605 {
606         return start_transaction(root, num_items, TRANS_START,
607                                  BTRFS_RESERVE_FLUSH_ALL, true);
608 }
609
610 struct btrfs_trans_handle *btrfs_start_transaction_fallback_global_rsv(
611                                         struct btrfs_root *root,
612                                         unsigned int num_items,
613                                         int min_factor)
614 {
615         struct btrfs_fs_info *fs_info = root->fs_info;
616         struct btrfs_trans_handle *trans;
617         u64 num_bytes;
618         int ret;
619
620         /*
621          * We have two callers: unlink and block group removal.  The
622          * former should succeed even if we will temporarily exceed
623          * quota and the latter operates on the extent root so
624          * qgroup enforcement is ignored anyway.
625          */
626         trans = start_transaction(root, num_items, TRANS_START,
627                                   BTRFS_RESERVE_FLUSH_ALL, false);
628         if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
629                 return trans;
630
631         trans = btrfs_start_transaction(root, 0);
632         if (IS_ERR(trans))
633                 return trans;
634
635         num_bytes = btrfs_calc_trans_metadata_size(fs_info, num_items);
636         ret = btrfs_cond_migrate_bytes(fs_info, &fs_info->trans_block_rsv,
637                                        num_bytes, min_factor);
638         if (ret) {
639                 btrfs_end_transaction(trans);
640                 return ERR_PTR(ret);
641         }
642
643         trans->block_rsv = &fs_info->trans_block_rsv;
644         trans->bytes_reserved = num_bytes;
645         trace_btrfs_space_reservation(fs_info, "transaction",
646                                       trans->transid, num_bytes, 1);
647
648         return trans;
649 }
650
651 struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
652 {
653         return start_transaction(root, 0, TRANS_JOIN, BTRFS_RESERVE_NO_FLUSH,
654                                  true);
655 }
656
657 struct btrfs_trans_handle *btrfs_join_transaction_nolock(struct btrfs_root *root)
658 {
659         return start_transaction(root, 0, TRANS_JOIN_NOLOCK,
660                                  BTRFS_RESERVE_NO_FLUSH, true);
661 }
662
663 /*
664  * Similar to regular join but it never starts a transaction when none is
665  * running or after waiting for the current one to finish.
666  */
667 struct btrfs_trans_handle *btrfs_join_transaction_nostart(struct btrfs_root *root)
668 {
669         return start_transaction(root, 0, TRANS_JOIN_NOSTART,
670                                  BTRFS_RESERVE_NO_FLUSH, true);
671 }
672
673 /*
674  * btrfs_attach_transaction() - catch the running transaction
675  *
676  * It is used when we want to commit the current the transaction, but
677  * don't want to start a new one.
678  *
679  * Note: If this function return -ENOENT, it just means there is no
680  * running transaction. But it is possible that the inactive transaction
681  * is still in the memory, not fully on disk. If you hope there is no
682  * inactive transaction in the fs when -ENOENT is returned, you should
683  * invoke
684  *     btrfs_attach_transaction_barrier()
685  */
686 struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root)
687 {
688         return start_transaction(root, 0, TRANS_ATTACH,
689                                  BTRFS_RESERVE_NO_FLUSH, true);
690 }
691
692 /*
693  * btrfs_attach_transaction_barrier() - catch the running transaction
694  *
695  * It is similar to the above function, the differentia is this one
696  * will wait for all the inactive transactions until they fully
697  * complete.
698  */
699 struct btrfs_trans_handle *
700 btrfs_attach_transaction_barrier(struct btrfs_root *root)
701 {
702         struct btrfs_trans_handle *trans;
703
704         trans = start_transaction(root, 0, TRANS_ATTACH,
705                                   BTRFS_RESERVE_NO_FLUSH, true);
706         if (trans == ERR_PTR(-ENOENT))
707                 btrfs_wait_for_commit(root->fs_info, 0);
708
709         return trans;
710 }
711
712 /* wait for a transaction commit to be fully complete */
713 static noinline void wait_for_commit(struct btrfs_transaction *commit)
714 {
715         wait_event(commit->commit_wait, commit->state == TRANS_STATE_COMPLETED);
716 }
717
718 int btrfs_wait_for_commit(struct btrfs_fs_info *fs_info, u64 transid)
719 {
720         struct btrfs_transaction *cur_trans = NULL, *t;
721         int ret = 0;
722
723         if (transid) {
724                 if (transid <= fs_info->last_trans_committed)
725                         goto out;
726
727                 /* find specified transaction */
728                 spin_lock(&fs_info->trans_lock);
729                 list_for_each_entry(t, &fs_info->trans_list, list) {
730                         if (t->transid == transid) {
731                                 cur_trans = t;
732                                 refcount_inc(&cur_trans->use_count);
733                                 ret = 0;
734                                 break;
735                         }
736                         if (t->transid > transid) {
737                                 ret = 0;
738                                 break;
739                         }
740                 }
741                 spin_unlock(&fs_info->trans_lock);
742
743                 /*
744                  * The specified transaction doesn't exist, or we
745                  * raced with btrfs_commit_transaction
746                  */
747                 if (!cur_trans) {
748                         if (transid > fs_info->last_trans_committed)
749                                 ret = -EINVAL;
750                         goto out;
751                 }
752         } else {
753                 /* find newest transaction that is committing | committed */
754                 spin_lock(&fs_info->trans_lock);
755                 list_for_each_entry_reverse(t, &fs_info->trans_list,
756                                             list) {
757                         if (t->state >= TRANS_STATE_COMMIT_START) {
758                                 if (t->state == TRANS_STATE_COMPLETED)
759                                         break;
760                                 cur_trans = t;
761                                 refcount_inc(&cur_trans->use_count);
762                                 break;
763                         }
764                 }
765                 spin_unlock(&fs_info->trans_lock);
766                 if (!cur_trans)
767                         goto out;  /* nothing committing|committed */
768         }
769
770         wait_for_commit(cur_trans);
771         btrfs_put_transaction(cur_trans);
772 out:
773         return ret;
774 }
775
776 void btrfs_throttle(struct btrfs_fs_info *fs_info)
777 {
778         wait_current_trans(fs_info);
779 }
780
781 static int should_end_transaction(struct btrfs_trans_handle *trans)
782 {
783         struct btrfs_fs_info *fs_info = trans->fs_info;
784
785         if (btrfs_check_space_for_delayed_refs(trans, fs_info))
786                 return 1;
787
788         return !!btrfs_block_rsv_check(&fs_info->global_block_rsv, 5);
789 }
790
791 int btrfs_should_end_transaction(struct btrfs_trans_handle *trans)
792 {
793         struct btrfs_transaction *cur_trans = trans->transaction;
794         int updates;
795         int err;
796
797         smp_mb();
798         if (cur_trans->state >= TRANS_STATE_BLOCKED ||
799             cur_trans->delayed_refs.flushing)
800                 return 1;
801
802         updates = trans->delayed_ref_updates;
803         trans->delayed_ref_updates = 0;
804         if (updates) {
805                 err = btrfs_run_delayed_refs(trans, updates * 2);
806                 if (err) /* Error code will also eval true */
807                         return err;
808         }
809
810         return should_end_transaction(trans);
811 }
812
813 static void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans)
814
815 {
816         struct btrfs_fs_info *fs_info = trans->fs_info;
817
818         if (!trans->block_rsv) {
819                 ASSERT(!trans->bytes_reserved);
820                 return;
821         }
822
823         if (!trans->bytes_reserved)
824                 return;
825
826         ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
827         trace_btrfs_space_reservation(fs_info, "transaction",
828                                       trans->transid, trans->bytes_reserved, 0);
829         btrfs_block_rsv_release(fs_info, trans->block_rsv,
830                                 trans->bytes_reserved);
831         trans->bytes_reserved = 0;
832 }
833
834 static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
835                                    int throttle)
836 {
837         struct btrfs_fs_info *info = trans->fs_info;
838         struct btrfs_transaction *cur_trans = trans->transaction;
839         u64 transid = trans->transid;
840         unsigned long cur = trans->delayed_ref_updates;
841         int lock = (trans->type != TRANS_JOIN_NOLOCK);
842         int err = 0;
843         int must_run_delayed_refs = 0;
844
845         if (refcount_read(&trans->use_count) > 1) {
846                 refcount_dec(&trans->use_count);
847                 trans->block_rsv = trans->orig_rsv;
848                 return 0;
849         }
850
851         btrfs_trans_release_metadata(trans);
852         trans->block_rsv = NULL;
853
854         if (!list_empty(&trans->new_bgs))
855                 btrfs_create_pending_block_groups(trans);
856
857         trans->delayed_ref_updates = 0;
858         if (!trans->sync) {
859                 must_run_delayed_refs =
860                         btrfs_should_throttle_delayed_refs(trans, info);
861                 cur = max_t(unsigned long, cur, 32);
862
863                 /*
864                  * don't make the caller wait if they are from a NOLOCK
865                  * or ATTACH transaction, it will deadlock with commit
866                  */
867                 if (must_run_delayed_refs == 1 &&
868                     (trans->type & (__TRANS_JOIN_NOLOCK | __TRANS_ATTACH)))
869                         must_run_delayed_refs = 2;
870         }
871
872         btrfs_trans_release_metadata(trans);
873         trans->block_rsv = NULL;
874
875         if (!list_empty(&trans->new_bgs))
876                 btrfs_create_pending_block_groups(trans);
877
878         btrfs_trans_release_chunk_metadata(trans);
879
880         if (lock && should_end_transaction(trans) &&
881             READ_ONCE(cur_trans->state) == TRANS_STATE_RUNNING) {
882                 spin_lock(&info->trans_lock);
883                 if (cur_trans->state == TRANS_STATE_RUNNING)
884                         cur_trans->state = TRANS_STATE_BLOCKED;
885                 spin_unlock(&info->trans_lock);
886         }
887
888         if (lock && READ_ONCE(cur_trans->state) == TRANS_STATE_BLOCKED) {
889                 if (throttle)
890                         return btrfs_commit_transaction(trans);
891                 else
892                         wake_up_process(info->transaction_kthread);
893         }
894
895         if (trans->type & __TRANS_FREEZABLE)
896                 sb_end_intwrite(info->sb);
897
898         WARN_ON(cur_trans != info->running_transaction);
899         WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
900         atomic_dec(&cur_trans->num_writers);
901         extwriter_counter_dec(cur_trans, trans->type);
902
903         cond_wake_up(&cur_trans->writer_wait);
904         btrfs_put_transaction(cur_trans);
905
906         if (current->journal_info == trans)
907                 current->journal_info = NULL;
908
909         if (throttle)
910                 btrfs_run_delayed_iputs(info);
911
912         if (trans->aborted ||
913             test_bit(BTRFS_FS_STATE_ERROR, &info->fs_state)) {
914                 wake_up_process(info->transaction_kthread);
915                 err = -EIO;
916         }
917
918         kmem_cache_free(btrfs_trans_handle_cachep, trans);
919         if (must_run_delayed_refs) {
920                 btrfs_async_run_delayed_refs(info, cur, transid,
921                                              must_run_delayed_refs == 1);
922         }
923         return err;
924 }
925
926 int btrfs_end_transaction(struct btrfs_trans_handle *trans)
927 {
928         return __btrfs_end_transaction(trans, 0);
929 }
930
931 int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans)
932 {
933         return __btrfs_end_transaction(trans, 1);
934 }
935
936 /*
937  * when btree blocks are allocated, they have some corresponding bits set for
938  * them in one of two extent_io trees.  This is used to make sure all of
939  * those extents are sent to disk but does not wait on them
940  */
941 int btrfs_write_marked_extents(struct btrfs_fs_info *fs_info,
942                                struct extent_io_tree *dirty_pages, int mark)
943 {
944         int err = 0;
945         int werr = 0;
946         struct address_space *mapping = fs_info->btree_inode->i_mapping;
947         struct extent_state *cached_state = NULL;
948         u64 start = 0;
949         u64 end;
950
951         atomic_inc(&BTRFS_I(fs_info->btree_inode)->sync_writers);
952         while (!find_first_extent_bit(dirty_pages, start, &start, &end,
953                                       mark, &cached_state)) {
954                 bool wait_writeback = false;
955
956                 err = convert_extent_bit(dirty_pages, start, end,
957                                          EXTENT_NEED_WAIT,
958                                          mark, &cached_state);
959                 /*
960                  * convert_extent_bit can return -ENOMEM, which is most of the
961                  * time a temporary error. So when it happens, ignore the error
962                  * and wait for writeback of this range to finish - because we
963                  * failed to set the bit EXTENT_NEED_WAIT for the range, a call
964                  * to __btrfs_wait_marked_extents() would not know that
965                  * writeback for this range started and therefore wouldn't
966                  * wait for it to finish - we don't want to commit a
967                  * superblock that points to btree nodes/leafs for which
968                  * writeback hasn't finished yet (and without errors).
969                  * We cleanup any entries left in the io tree when committing
970                  * the transaction (through clear_btree_io_tree()).
971                  */
972                 if (err == -ENOMEM) {
973                         err = 0;
974                         wait_writeback = true;
975                 }
976                 if (!err)
977                         err = filemap_fdatawrite_range(mapping, start, end);
978                 if (err)
979                         werr = err;
980                 else if (wait_writeback)
981                         werr = filemap_fdatawait_range(mapping, start, end);
982                 free_extent_state(cached_state);
983                 cached_state = NULL;
984                 cond_resched();
985                 start = end + 1;
986         }
987         atomic_dec(&BTRFS_I(fs_info->btree_inode)->sync_writers);
988         return werr;
989 }
990
991 /*
992  * when btree blocks are allocated, they have some corresponding bits set for
993  * them in one of two extent_io trees.  This is used to make sure all of
994  * those extents are on disk for transaction or log commit.  We wait
995  * on all the pages and clear them from the dirty pages state tree
996  */
997 static int __btrfs_wait_marked_extents(struct btrfs_fs_info *fs_info,
998                                        struct extent_io_tree *dirty_pages)
999 {
1000         int err = 0;
1001         int werr = 0;
1002         struct address_space *mapping = fs_info->btree_inode->i_mapping;
1003         struct extent_state *cached_state = NULL;
1004         u64 start = 0;
1005         u64 end;
1006
1007         while (!find_first_extent_bit(dirty_pages, start, &start, &end,
1008                                       EXTENT_NEED_WAIT, &cached_state)) {
1009                 /*
1010                  * Ignore -ENOMEM errors returned by clear_extent_bit().
1011                  * When committing the transaction, we'll remove any entries
1012                  * left in the io tree. For a log commit, we don't remove them
1013                  * after committing the log because the tree can be accessed
1014                  * concurrently - we do it only at transaction commit time when
1015                  * it's safe to do it (through clear_btree_io_tree()).
1016                  */
1017                 err = clear_extent_bit(dirty_pages, start, end,
1018                                        EXTENT_NEED_WAIT, 0, 0, &cached_state);
1019                 if (err == -ENOMEM)
1020                         err = 0;
1021                 if (!err)
1022                         err = filemap_fdatawait_range(mapping, start, end);
1023                 if (err)
1024                         werr = err;
1025                 free_extent_state(cached_state);
1026                 cached_state = NULL;
1027                 cond_resched();
1028                 start = end + 1;
1029         }
1030         if (err)
1031                 werr = err;
1032         return werr;
1033 }
1034
1035 int btrfs_wait_extents(struct btrfs_fs_info *fs_info,
1036                        struct extent_io_tree *dirty_pages)
1037 {
1038         bool errors = false;
1039         int err;
1040
1041         err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1042         if (test_and_clear_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags))
1043                 errors = true;
1044
1045         if (errors && !err)
1046                 err = -EIO;
1047         return err;
1048 }
1049
1050 int btrfs_wait_tree_log_extents(struct btrfs_root *log_root, int mark)
1051 {
1052         struct btrfs_fs_info *fs_info = log_root->fs_info;
1053         struct extent_io_tree *dirty_pages = &log_root->dirty_log_pages;
1054         bool errors = false;
1055         int err;
1056
1057         ASSERT(log_root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
1058
1059         err = __btrfs_wait_marked_extents(fs_info, dirty_pages);
1060         if ((mark & EXTENT_DIRTY) &&
1061             test_and_clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags))
1062                 errors = true;
1063
1064         if ((mark & EXTENT_NEW) &&
1065             test_and_clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags))
1066                 errors = true;
1067
1068         if (errors && !err)
1069                 err = -EIO;
1070         return err;
1071 }
1072
1073 /*
1074  * When btree blocks are allocated the corresponding extents are marked dirty.
1075  * This function ensures such extents are persisted on disk for transaction or
1076  * log commit.
1077  *
1078  * @trans: transaction whose dirty pages we'd like to write
1079  */
1080 static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
1081 {
1082         int ret;
1083         int ret2;
1084         struct extent_io_tree *dirty_pages = &trans->transaction->dirty_pages;
1085         struct btrfs_fs_info *fs_info = trans->fs_info;
1086         struct blk_plug plug;
1087
1088         blk_start_plug(&plug);
1089         ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
1090         blk_finish_plug(&plug);
1091         ret2 = btrfs_wait_extents(fs_info, dirty_pages);
1092
1093         clear_btree_io_tree(&trans->transaction->dirty_pages);
1094
1095         if (ret)
1096                 return ret;
1097         else if (ret2)
1098                 return ret2;
1099         else
1100                 return 0;
1101 }
1102
1103 /*
1104  * this is used to update the root pointer in the tree of tree roots.
1105  *
1106  * But, in the case of the extent allocation tree, updating the root
1107  * pointer may allocate blocks which may change the root of the extent
1108  * allocation tree.
1109  *
1110  * So, this loops and repeats and makes sure the cowonly root didn't
1111  * change while the root pointer was being updated in the metadata.
1112  */
1113 static int update_cowonly_root(struct btrfs_trans_handle *trans,
1114                                struct btrfs_root *root)
1115 {
1116         int ret;
1117         u64 old_root_bytenr;
1118         u64 old_root_used;
1119         struct btrfs_fs_info *fs_info = root->fs_info;
1120         struct btrfs_root *tree_root = fs_info->tree_root;
1121
1122         old_root_used = btrfs_root_used(&root->root_item);
1123
1124         while (1) {
1125                 old_root_bytenr = btrfs_root_bytenr(&root->root_item);
1126                 if (old_root_bytenr == root->node->start &&
1127                     old_root_used == btrfs_root_used(&root->root_item))
1128                         break;
1129
1130                 btrfs_set_root_node(&root->root_item, root->node);
1131                 ret = btrfs_update_root(trans, tree_root,
1132                                         &root->root_key,
1133                                         &root->root_item);
1134                 if (ret)
1135                         return ret;
1136
1137                 old_root_used = btrfs_root_used(&root->root_item);
1138         }
1139
1140         return 0;
1141 }
1142
1143 /*
1144  * update all the cowonly tree roots on disk
1145  *
1146  * The error handling in this function may not be obvious. Any of the
1147  * failures will cause the file system to go offline. We still need
1148  * to clean up the delayed refs.
1149  */
1150 static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans)
1151 {
1152         struct btrfs_fs_info *fs_info = trans->fs_info;
1153         struct list_head *dirty_bgs = &trans->transaction->dirty_bgs;
1154         struct list_head *io_bgs = &trans->transaction->io_bgs;
1155         struct list_head *next;
1156         struct extent_buffer *eb;
1157         int ret;
1158
1159         eb = btrfs_lock_root_node(fs_info->tree_root);
1160         ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL,
1161                               0, &eb);
1162         btrfs_tree_unlock(eb);
1163         free_extent_buffer(eb);
1164
1165         if (ret)
1166                 return ret;
1167
1168         ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1169         if (ret)
1170                 return ret;
1171
1172         ret = btrfs_run_dev_stats(trans, fs_info);
1173         if (ret)
1174                 return ret;
1175         ret = btrfs_run_dev_replace(trans, fs_info);
1176         if (ret)
1177                 return ret;
1178         ret = btrfs_run_qgroups(trans);
1179         if (ret)
1180                 return ret;
1181
1182         ret = btrfs_setup_space_cache(trans, fs_info);
1183         if (ret)
1184                 return ret;
1185
1186         /* run_qgroups might have added some more refs */
1187         ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1188         if (ret)
1189                 return ret;
1190 again:
1191         while (!list_empty(&fs_info->dirty_cowonly_roots)) {
1192                 struct btrfs_root *root;
1193                 next = fs_info->dirty_cowonly_roots.next;
1194                 list_del_init(next);
1195                 root = list_entry(next, struct btrfs_root, dirty_list);
1196                 clear_bit(BTRFS_ROOT_DIRTY, &root->state);
1197
1198                 if (root != fs_info->extent_root)
1199                         list_add_tail(&root->dirty_list,
1200                                       &trans->transaction->switch_commits);
1201                 ret = update_cowonly_root(trans, root);
1202                 if (ret)
1203                         return ret;
1204                 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1205                 if (ret)
1206                         return ret;
1207         }
1208
1209         while (!list_empty(dirty_bgs) || !list_empty(io_bgs)) {
1210                 ret = btrfs_write_dirty_block_groups(trans, fs_info);
1211                 if (ret)
1212                         return ret;
1213                 ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1214                 if (ret)
1215                         return ret;
1216         }
1217
1218         if (!list_empty(&fs_info->dirty_cowonly_roots))
1219                 goto again;
1220
1221         list_add_tail(&fs_info->extent_root->dirty_list,
1222                       &trans->transaction->switch_commits);
1223         btrfs_after_dev_replace_commit(fs_info);
1224
1225         return 0;
1226 }
1227
1228 /*
1229  * dead roots are old snapshots that need to be deleted.  This allocates
1230  * a dirty root struct and adds it into the list of dead roots that need to
1231  * be deleted
1232  */
1233 void btrfs_add_dead_root(struct btrfs_root *root)
1234 {
1235         struct btrfs_fs_info *fs_info = root->fs_info;
1236
1237         spin_lock(&fs_info->trans_lock);
1238         if (list_empty(&root->root_list))
1239                 list_add_tail(&root->root_list, &fs_info->dead_roots);
1240         spin_unlock(&fs_info->trans_lock);
1241 }
1242
1243 /*
1244  * update all the cowonly tree roots on disk
1245  */
1246 static noinline int commit_fs_roots(struct btrfs_trans_handle *trans)
1247 {
1248         struct btrfs_fs_info *fs_info = trans->fs_info;
1249         struct btrfs_root *gang[8];
1250         int i;
1251         int ret;
1252
1253         spin_lock(&fs_info->fs_roots_radix_lock);
1254         while (1) {
1255                 ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
1256                                                  (void **)gang, 0,
1257                                                  ARRAY_SIZE(gang),
1258                                                  BTRFS_ROOT_TRANS_TAG);
1259                 if (ret == 0)
1260                         break;
1261                 for (i = 0; i < ret; i++) {
1262                         struct btrfs_root *root = gang[i];
1263                         int ret2;
1264
1265                         radix_tree_tag_clear(&fs_info->fs_roots_radix,
1266                                         (unsigned long)root->root_key.objectid,
1267                                         BTRFS_ROOT_TRANS_TAG);
1268                         spin_unlock(&fs_info->fs_roots_radix_lock);
1269
1270                         btrfs_free_log(trans, root);
1271                         btrfs_update_reloc_root(trans, root);
1272
1273                         btrfs_save_ino_cache(root, trans);
1274
1275                         /* see comments in should_cow_block() */
1276                         clear_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1277                         smp_mb__after_atomic();
1278
1279                         if (root->commit_root != root->node) {
1280                                 list_add_tail(&root->dirty_list,
1281                                         &trans->transaction->switch_commits);
1282                                 btrfs_set_root_node(&root->root_item,
1283                                                     root->node);
1284                         }
1285
1286                         ret2 = btrfs_update_root(trans, fs_info->tree_root,
1287                                                 &root->root_key,
1288                                                 &root->root_item);
1289                         if (ret2)
1290                                 return ret2;
1291                         spin_lock(&fs_info->fs_roots_radix_lock);
1292                         btrfs_qgroup_free_meta_all_pertrans(root);
1293                 }
1294         }
1295         spin_unlock(&fs_info->fs_roots_radix_lock);
1296         return 0;
1297 }
1298
1299 /*
1300  * defrag a given btree.
1301  * Every leaf in the btree is read and defragged.
1302  */
1303 int btrfs_defrag_root(struct btrfs_root *root)
1304 {
1305         struct btrfs_fs_info *info = root->fs_info;
1306         struct btrfs_trans_handle *trans;
1307         int ret;
1308
1309         if (test_and_set_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state))
1310                 return 0;
1311
1312         while (1) {
1313                 trans = btrfs_start_transaction(root, 0);
1314                 if (IS_ERR(trans)) {
1315                         ret = PTR_ERR(trans);
1316                         break;
1317                 }
1318
1319                 ret = btrfs_defrag_leaves(trans, root);
1320
1321                 btrfs_end_transaction(trans);
1322                 btrfs_btree_balance_dirty(info);
1323                 cond_resched();
1324
1325                 if (btrfs_fs_closing(info) || ret != -EAGAIN)
1326                         break;
1327
1328                 if (btrfs_defrag_cancelled(info)) {
1329                         btrfs_debug(info, "defrag_root cancelled");
1330                         ret = -EAGAIN;
1331                         break;
1332                 }
1333         }
1334         clear_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state);
1335         return ret;
1336 }
1337
1338 /*
1339  * Do all special snapshot related qgroup dirty hack.
1340  *
1341  * Will do all needed qgroup inherit and dirty hack like switch commit
1342  * roots inside one transaction and write all btree into disk, to make
1343  * qgroup works.
1344  */
1345 static int qgroup_account_snapshot(struct btrfs_trans_handle *trans,
1346                                    struct btrfs_root *src,
1347                                    struct btrfs_root *parent,
1348                                    struct btrfs_qgroup_inherit *inherit,
1349                                    u64 dst_objectid)
1350 {
1351         struct btrfs_fs_info *fs_info = src->fs_info;
1352         int ret;
1353
1354         /*
1355          * Save some performance in the case that qgroups are not
1356          * enabled. If this check races with the ioctl, rescan will
1357          * kick in anyway.
1358          */
1359         if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1360                 return 0;
1361
1362         /*
1363          * Ensure dirty @src will be commited.  Or, after comming
1364          * commit_fs_roots() and switch_commit_roots(), any dirty but not
1365          * recorded root will never be updated again, causing an outdated root
1366          * item.
1367          */
1368         record_root_in_trans(trans, src, 1);
1369
1370         /*
1371          * We are going to commit transaction, see btrfs_commit_transaction()
1372          * comment for reason locking tree_log_mutex
1373          */
1374         mutex_lock(&fs_info->tree_log_mutex);
1375
1376         ret = commit_fs_roots(trans);
1377         if (ret)
1378                 goto out;
1379         ret = btrfs_qgroup_account_extents(trans);
1380         if (ret < 0)
1381                 goto out;
1382
1383         /* Now qgroup are all updated, we can inherit it to new qgroups */
1384         ret = btrfs_qgroup_inherit(trans, src->root_key.objectid, dst_objectid,
1385                                    inherit);
1386         if (ret < 0)
1387                 goto out;
1388
1389         /*
1390          * Now we do a simplified commit transaction, which will:
1391          * 1) commit all subvolume and extent tree
1392          *    To ensure all subvolume and extent tree have a valid
1393          *    commit_root to accounting later insert_dir_item()
1394          * 2) write all btree blocks onto disk
1395          *    This is to make sure later btree modification will be cowed
1396          *    Or commit_root can be populated and cause wrong qgroup numbers
1397          * In this simplified commit, we don't really care about other trees
1398          * like chunk and root tree, as they won't affect qgroup.
1399          * And we don't write super to avoid half committed status.
1400          */
1401         ret = commit_cowonly_roots(trans);
1402         if (ret)
1403                 goto out;
1404         switch_commit_roots(trans->transaction);
1405         ret = btrfs_write_and_wait_transaction(trans);
1406         if (ret)
1407                 btrfs_handle_fs_error(fs_info, ret,
1408                         "Error while writing out transaction for qgroup");
1409
1410 out:
1411         mutex_unlock(&fs_info->tree_log_mutex);
1412
1413         /*
1414          * Force parent root to be updated, as we recorded it before so its
1415          * last_trans == cur_transid.
1416          * Or it won't be committed again onto disk after later
1417          * insert_dir_item()
1418          */
1419         if (!ret)
1420                 record_root_in_trans(trans, parent, 1);
1421         return ret;
1422 }
1423
1424 /*
1425  * new snapshots need to be created at a very specific time in the
1426  * transaction commit.  This does the actual creation.
1427  *
1428  * Note:
1429  * If the error which may affect the commitment of the current transaction
1430  * happens, we should return the error number. If the error which just affect
1431  * the creation of the pending snapshots, just return 0.
1432  */
1433 static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
1434                                    struct btrfs_pending_snapshot *pending)
1435 {
1436
1437         struct btrfs_fs_info *fs_info = trans->fs_info;
1438         struct btrfs_key key;
1439         struct btrfs_root_item *new_root_item;
1440         struct btrfs_root *tree_root = fs_info->tree_root;
1441         struct btrfs_root *root = pending->root;
1442         struct btrfs_root *parent_root;
1443         struct btrfs_block_rsv *rsv;
1444         struct inode *parent_inode;
1445         struct btrfs_path *path;
1446         struct btrfs_dir_item *dir_item;
1447         struct dentry *dentry;
1448         struct extent_buffer *tmp;
1449         struct extent_buffer *old;
1450         struct timespec64 cur_time;
1451         int ret = 0;
1452         u64 to_reserve = 0;
1453         u64 index = 0;
1454         u64 objectid;
1455         u64 root_flags;
1456         uuid_le new_uuid;
1457
1458         ASSERT(pending->path);
1459         path = pending->path;
1460
1461         ASSERT(pending->root_item);
1462         new_root_item = pending->root_item;
1463
1464         pending->error = btrfs_find_free_objectid(tree_root, &objectid);
1465         if (pending->error)
1466                 goto no_free_objectid;
1467
1468         /*
1469          * Make qgroup to skip current new snapshot's qgroupid, as it is
1470          * accounted by later btrfs_qgroup_inherit().
1471          */
1472         btrfs_set_skip_qgroup(trans, objectid);
1473
1474         btrfs_reloc_pre_snapshot(pending, &to_reserve);
1475
1476         if (to_reserve > 0) {
1477                 pending->error = btrfs_block_rsv_add(root,
1478                                                      &pending->block_rsv,
1479                                                      to_reserve,
1480                                                      BTRFS_RESERVE_NO_FLUSH);
1481                 if (pending->error)
1482                         goto clear_skip_qgroup;
1483         }
1484
1485         key.objectid = objectid;
1486         key.offset = (u64)-1;
1487         key.type = BTRFS_ROOT_ITEM_KEY;
1488
1489         rsv = trans->block_rsv;
1490         trans->block_rsv = &pending->block_rsv;
1491         trans->bytes_reserved = trans->block_rsv->reserved;
1492         trace_btrfs_space_reservation(fs_info, "transaction",
1493                                       trans->transid,
1494                                       trans->bytes_reserved, 1);
1495         dentry = pending->dentry;
1496         parent_inode = pending->dir;
1497         parent_root = BTRFS_I(parent_inode)->root;
1498         record_root_in_trans(trans, parent_root, 0);
1499
1500         cur_time = current_time(parent_inode);
1501
1502         /*
1503          * insert the directory item
1504          */
1505         ret = btrfs_set_inode_index(BTRFS_I(parent_inode), &index);
1506         BUG_ON(ret); /* -ENOMEM */
1507
1508         /* check if there is a file/dir which has the same name. */
1509         dir_item = btrfs_lookup_dir_item(NULL, parent_root, path,
1510                                          btrfs_ino(BTRFS_I(parent_inode)),
1511                                          dentry->d_name.name,
1512                                          dentry->d_name.len, 0);
1513         if (dir_item != NULL && !IS_ERR(dir_item)) {
1514                 pending->error = -EEXIST;
1515                 goto dir_item_existed;
1516         } else if (IS_ERR(dir_item)) {
1517                 ret = PTR_ERR(dir_item);
1518                 btrfs_abort_transaction(trans, ret);
1519                 goto fail;
1520         }
1521         btrfs_release_path(path);
1522
1523         /*
1524          * pull in the delayed directory update
1525          * and the delayed inode item
1526          * otherwise we corrupt the FS during
1527          * snapshot
1528          */
1529         ret = btrfs_run_delayed_items(trans);
1530         if (ret) {      /* Transaction aborted */
1531                 btrfs_abort_transaction(trans, ret);
1532                 goto fail;
1533         }
1534
1535         record_root_in_trans(trans, root, 0);
1536         btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
1537         memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
1538         btrfs_check_and_init_root_item(new_root_item);
1539
1540         root_flags = btrfs_root_flags(new_root_item);
1541         if (pending->readonly)
1542                 root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
1543         else
1544                 root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
1545         btrfs_set_root_flags(new_root_item, root_flags);
1546
1547         btrfs_set_root_generation_v2(new_root_item,
1548                         trans->transid);
1549         uuid_le_gen(&new_uuid);
1550         memcpy(new_root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
1551         memcpy(new_root_item->parent_uuid, root->root_item.uuid,
1552                         BTRFS_UUID_SIZE);
1553         if (!(root_flags & BTRFS_ROOT_SUBVOL_RDONLY)) {
1554                 memset(new_root_item->received_uuid, 0,
1555                        sizeof(new_root_item->received_uuid));
1556                 memset(&new_root_item->stime, 0, sizeof(new_root_item->stime));
1557                 memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime));
1558                 btrfs_set_root_stransid(new_root_item, 0);
1559                 btrfs_set_root_rtransid(new_root_item, 0);
1560         }
1561         btrfs_set_stack_timespec_sec(&new_root_item->otime, cur_time.tv_sec);
1562         btrfs_set_stack_timespec_nsec(&new_root_item->otime, cur_time.tv_nsec);
1563         btrfs_set_root_otransid(new_root_item, trans->transid);
1564
1565         old = btrfs_lock_root_node(root);
1566         ret = btrfs_cow_block(trans, root, old, NULL, 0, &old);
1567         if (ret) {
1568                 btrfs_tree_unlock(old);
1569                 free_extent_buffer(old);
1570                 btrfs_abort_transaction(trans, ret);
1571                 goto fail;
1572         }
1573
1574         btrfs_set_lock_blocking(old);
1575
1576         ret = btrfs_copy_root(trans, root, old, &tmp, objectid);
1577         /* clean up in any case */
1578         btrfs_tree_unlock(old);
1579         free_extent_buffer(old);
1580         if (ret) {
1581                 btrfs_abort_transaction(trans, ret);
1582                 goto fail;
1583         }
1584         /* see comments in should_cow_block() */
1585         set_bit(BTRFS_ROOT_FORCE_COW, &root->state);
1586         smp_wmb();
1587
1588         btrfs_set_root_node(new_root_item, tmp);
1589         /* record when the snapshot was created in key.offset */
1590         key.offset = trans->transid;
1591         ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
1592         btrfs_tree_unlock(tmp);
1593         free_extent_buffer(tmp);
1594         if (ret) {
1595                 btrfs_abort_transaction(trans, ret);
1596                 goto fail;
1597         }
1598
1599         /*
1600          * insert root back/forward references
1601          */
1602         ret = btrfs_add_root_ref(trans, objectid,
1603                                  parent_root->root_key.objectid,
1604                                  btrfs_ino(BTRFS_I(parent_inode)), index,
1605                                  dentry->d_name.name, dentry->d_name.len);
1606         if (ret) {
1607                 btrfs_abort_transaction(trans, ret);
1608                 goto fail;
1609         }
1610
1611         key.offset = (u64)-1;
1612         pending->snap = btrfs_read_fs_root_no_name(fs_info, &key);
1613         if (IS_ERR(pending->snap)) {
1614                 ret = PTR_ERR(pending->snap);
1615                 btrfs_abort_transaction(trans, ret);
1616                 goto fail;
1617         }
1618
1619         ret = btrfs_reloc_post_snapshot(trans, pending);
1620         if (ret) {
1621                 btrfs_abort_transaction(trans, ret);
1622                 goto fail;
1623         }
1624
1625         ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1626         if (ret) {
1627                 btrfs_abort_transaction(trans, ret);
1628                 goto fail;
1629         }
1630
1631         /*
1632          * Do special qgroup accounting for snapshot, as we do some qgroup
1633          * snapshot hack to do fast snapshot.
1634          * To co-operate with that hack, we do hack again.
1635          * Or snapshot will be greatly slowed down by a subtree qgroup rescan
1636          */
1637         ret = qgroup_account_snapshot(trans, root, parent_root,
1638                                       pending->inherit, objectid);
1639         if (ret < 0)
1640                 goto fail;
1641
1642         ret = btrfs_insert_dir_item(trans, parent_root,
1643                                     dentry->d_name.name, dentry->d_name.len,
1644                                     BTRFS_I(parent_inode), &key,
1645                                     BTRFS_FT_DIR, index);
1646         /* We have check then name at the beginning, so it is impossible. */
1647         BUG_ON(ret == -EEXIST || ret == -EOVERFLOW);
1648         if (ret) {
1649                 btrfs_abort_transaction(trans, ret);
1650                 goto fail;
1651         }
1652
1653         btrfs_i_size_write(BTRFS_I(parent_inode), parent_inode->i_size +
1654                                          dentry->d_name.len * 2);
1655         parent_inode->i_mtime = parent_inode->i_ctime =
1656                 current_time(parent_inode);
1657         ret = btrfs_update_inode_fallback(trans, parent_root, parent_inode);
1658         if (ret) {
1659                 btrfs_abort_transaction(trans, ret);
1660                 goto fail;
1661         }
1662         ret = btrfs_uuid_tree_add(trans, new_uuid.b, BTRFS_UUID_KEY_SUBVOL,
1663                                   objectid);
1664         if (ret) {
1665                 btrfs_abort_transaction(trans, ret);
1666                 goto fail;
1667         }
1668         if (!btrfs_is_empty_uuid(new_root_item->received_uuid)) {
1669                 ret = btrfs_uuid_tree_add(trans, new_root_item->received_uuid,
1670                                           BTRFS_UUID_KEY_RECEIVED_SUBVOL,
1671                                           objectid);
1672                 if (ret && ret != -EEXIST) {
1673                         btrfs_abort_transaction(trans, ret);
1674                         goto fail;
1675                 }
1676         }
1677
1678         ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
1679         if (ret) {
1680                 btrfs_abort_transaction(trans, ret);
1681                 goto fail;
1682         }
1683
1684 fail:
1685         pending->error = ret;
1686 dir_item_existed:
1687         trans->block_rsv = rsv;
1688         trans->bytes_reserved = 0;
1689 clear_skip_qgroup:
1690         btrfs_clear_skip_qgroup(trans);
1691 no_free_objectid:
1692         kfree(new_root_item);
1693         pending->root_item = NULL;
1694         btrfs_free_path(path);
1695         pending->path = NULL;
1696
1697         return ret;
1698 }
1699
1700 /*
1701  * create all the snapshots we've scheduled for creation
1702  */
1703 static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans)
1704 {
1705         struct btrfs_pending_snapshot *pending, *next;
1706         struct list_head *head = &trans->transaction->pending_snapshots;
1707         int ret = 0;
1708
1709         list_for_each_entry_safe(pending, next, head, list) {
1710                 list_del(&pending->list);
1711                 ret = create_pending_snapshot(trans, pending);
1712                 if (ret)
1713                         break;
1714         }
1715         return ret;
1716 }
1717
1718 static void update_super_roots(struct btrfs_fs_info *fs_info)
1719 {
1720         struct btrfs_root_item *root_item;
1721         struct btrfs_super_block *super;
1722
1723         super = fs_info->super_copy;
1724
1725         root_item = &fs_info->chunk_root->root_item;
1726         super->chunk_root = root_item->bytenr;
1727         super->chunk_root_generation = root_item->generation;
1728         super->chunk_root_level = root_item->level;
1729
1730         root_item = &fs_info->tree_root->root_item;
1731         super->root = root_item->bytenr;
1732         super->generation = root_item->generation;
1733         super->root_level = root_item->level;
1734         if (btrfs_test_opt(fs_info, SPACE_CACHE))
1735                 super->cache_generation = root_item->generation;
1736         if (test_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags))
1737                 super->uuid_tree_generation = root_item->generation;
1738 }
1739
1740 int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
1741 {
1742         struct btrfs_transaction *trans;
1743         int ret = 0;
1744
1745         spin_lock(&info->trans_lock);
1746         trans = info->running_transaction;
1747         if (trans)
1748                 ret = (trans->state >= TRANS_STATE_COMMIT_START);
1749         spin_unlock(&info->trans_lock);
1750         return ret;
1751 }
1752
1753 int btrfs_transaction_blocked(struct btrfs_fs_info *info)
1754 {
1755         struct btrfs_transaction *trans;
1756         int ret = 0;
1757
1758         spin_lock(&info->trans_lock);
1759         trans = info->running_transaction;
1760         if (trans)
1761                 ret = is_transaction_blocked(trans);
1762         spin_unlock(&info->trans_lock);
1763         return ret;
1764 }
1765
1766 /*
1767  * wait for the current transaction commit to start and block subsequent
1768  * transaction joins
1769  */
1770 static void wait_current_trans_commit_start(struct btrfs_fs_info *fs_info,
1771                                             struct btrfs_transaction *trans)
1772 {
1773         wait_event(fs_info->transaction_blocked_wait,
1774                    trans->state >= TRANS_STATE_COMMIT_START || trans->aborted);
1775 }
1776
1777 /*
1778  * wait for the current transaction to start and then become unblocked.
1779  * caller holds ref.
1780  */
1781 static void wait_current_trans_commit_start_and_unblock(
1782                                         struct btrfs_fs_info *fs_info,
1783                                         struct btrfs_transaction *trans)
1784 {
1785         wait_event(fs_info->transaction_wait,
1786                    trans->state >= TRANS_STATE_UNBLOCKED || trans->aborted);
1787 }
1788
1789 /*
1790  * commit transactions asynchronously. once btrfs_commit_transaction_async
1791  * returns, any subsequent transaction will not be allowed to join.
1792  */
1793 struct btrfs_async_commit {
1794         struct btrfs_trans_handle *newtrans;
1795         struct work_struct work;
1796 };
1797
1798 static void do_async_commit(struct work_struct *work)
1799 {
1800         struct btrfs_async_commit *ac =
1801                 container_of(work, struct btrfs_async_commit, work);
1802
1803         /*
1804          * We've got freeze protection passed with the transaction.
1805          * Tell lockdep about it.
1806          */
1807         if (ac->newtrans->type & __TRANS_FREEZABLE)
1808                 __sb_writers_acquired(ac->newtrans->fs_info->sb, SB_FREEZE_FS);
1809
1810         current->journal_info = ac->newtrans;
1811
1812         btrfs_commit_transaction(ac->newtrans);
1813         kfree(ac);
1814 }
1815
1816 int btrfs_commit_transaction_async(struct btrfs_trans_handle *trans,
1817                                    int wait_for_unblock)
1818 {
1819         struct btrfs_fs_info *fs_info = trans->fs_info;
1820         struct btrfs_async_commit *ac;
1821         struct btrfs_transaction *cur_trans;
1822
1823         ac = kmalloc(sizeof(*ac), GFP_NOFS);
1824         if (!ac)
1825                 return -ENOMEM;
1826
1827         INIT_WORK(&ac->work, do_async_commit);
1828         ac->newtrans = btrfs_join_transaction(trans->root);
1829         if (IS_ERR(ac->newtrans)) {
1830                 int err = PTR_ERR(ac->newtrans);
1831                 kfree(ac);
1832                 return err;
1833         }
1834
1835         /* take transaction reference */
1836         cur_trans = trans->transaction;
1837         refcount_inc(&cur_trans->use_count);
1838
1839         btrfs_end_transaction(trans);
1840
1841         /*
1842          * Tell lockdep we've released the freeze rwsem, since the
1843          * async commit thread will be the one to unlock it.
1844          */
1845         if (ac->newtrans->type & __TRANS_FREEZABLE)
1846                 __sb_writers_release(fs_info->sb, SB_FREEZE_FS);
1847
1848         schedule_work(&ac->work);
1849
1850         /* wait for transaction to start and unblock */
1851         if (wait_for_unblock)
1852                 wait_current_trans_commit_start_and_unblock(fs_info, cur_trans);
1853         else
1854                 wait_current_trans_commit_start(fs_info, cur_trans);
1855
1856         if (current->journal_info == trans)
1857                 current->journal_info = NULL;
1858
1859         btrfs_put_transaction(cur_trans);
1860         return 0;
1861 }
1862
1863
1864 static void cleanup_transaction(struct btrfs_trans_handle *trans, int err)
1865 {
1866         struct btrfs_fs_info *fs_info = trans->fs_info;
1867         struct btrfs_transaction *cur_trans = trans->transaction;
1868         DEFINE_WAIT(wait);
1869
1870         WARN_ON(refcount_read(&trans->use_count) > 1);
1871
1872         btrfs_abort_transaction(trans, err);
1873
1874         spin_lock(&fs_info->trans_lock);
1875
1876         /*
1877          * If the transaction is removed from the list, it means this
1878          * transaction has been committed successfully, so it is impossible
1879          * to call the cleanup function.
1880          */
1881         BUG_ON(list_empty(&cur_trans->list));
1882
1883         list_del_init(&cur_trans->list);
1884         if (cur_trans == fs_info->running_transaction) {
1885                 cur_trans->state = TRANS_STATE_COMMIT_DOING;
1886                 spin_unlock(&fs_info->trans_lock);
1887                 wait_event(cur_trans->writer_wait,
1888                            atomic_read(&cur_trans->num_writers) == 1);
1889
1890                 spin_lock(&fs_info->trans_lock);
1891         }
1892         spin_unlock(&fs_info->trans_lock);
1893
1894         btrfs_cleanup_one_transaction(trans->transaction, fs_info);
1895
1896         spin_lock(&fs_info->trans_lock);
1897         if (cur_trans == fs_info->running_transaction)
1898                 fs_info->running_transaction = NULL;
1899         spin_unlock(&fs_info->trans_lock);
1900
1901         if (trans->type & __TRANS_FREEZABLE)
1902                 sb_end_intwrite(fs_info->sb);
1903         btrfs_put_transaction(cur_trans);
1904         btrfs_put_transaction(cur_trans);
1905
1906         trace_btrfs_transaction_commit(trans->root);
1907
1908         if (current->journal_info == trans)
1909                 current->journal_info = NULL;
1910         btrfs_scrub_cancel(fs_info);
1911
1912         kmem_cache_free(btrfs_trans_handle_cachep, trans);
1913 }
1914
1915 static inline int btrfs_start_delalloc_flush(struct btrfs_fs_info *fs_info)
1916 {
1917         /*
1918          * We use writeback_inodes_sb here because if we used
1919          * btrfs_start_delalloc_roots we would deadlock with fs freeze.
1920          * Currently are holding the fs freeze lock, if we do an async flush
1921          * we'll do btrfs_join_transaction() and deadlock because we need to
1922          * wait for the fs freeze lock.  Using the direct flushing we benefit
1923          * from already being in a transaction and our join_transaction doesn't
1924          * have to re-take the fs freeze lock.
1925          */
1926         if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
1927                 writeback_inodes_sb(fs_info->sb, WB_REASON_SYNC);
1928         return 0;
1929 }
1930
1931 static inline void btrfs_wait_delalloc_flush(struct btrfs_fs_info *fs_info)
1932 {
1933         if (btrfs_test_opt(fs_info, FLUSHONCOMMIT))
1934                 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
1935 }
1936
1937 static inline void
1938 btrfs_wait_pending_ordered(struct btrfs_transaction *cur_trans)
1939 {
1940         wait_event(cur_trans->pending_wait,
1941                    atomic_read(&cur_trans->pending_ordered) == 0);
1942 }
1943
1944 int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
1945 {
1946         struct btrfs_fs_info *fs_info = trans->fs_info;
1947         struct btrfs_transaction *cur_trans = trans->transaction;
1948         struct btrfs_transaction *prev_trans = NULL;
1949         int ret;
1950
1951         /*
1952          * Some places just start a transaction to commit it.  We need to make
1953          * sure that if this commit fails that the abort code actually marks the
1954          * transaction as failed, so set trans->dirty to make the abort code do
1955          * the right thing.
1956          */
1957         trans->dirty = true;
1958
1959         /* Stop the commit early if ->aborted is set */
1960         if (unlikely(READ_ONCE(cur_trans->aborted))) {
1961                 ret = cur_trans->aborted;
1962                 btrfs_end_transaction(trans);
1963                 return ret;
1964         }
1965
1966         btrfs_trans_release_metadata(trans);
1967         trans->block_rsv = NULL;
1968
1969         /* make a pass through all the delayed refs we have so far
1970          * any runnings procs may add more while we are here
1971          */
1972         ret = btrfs_run_delayed_refs(trans, 0);
1973         if (ret) {
1974                 btrfs_end_transaction(trans);
1975                 return ret;
1976         }
1977
1978         cur_trans = trans->transaction;
1979
1980         /*
1981          * set the flushing flag so procs in this transaction have to
1982          * start sending their work down.
1983          */
1984         cur_trans->delayed_refs.flushing = 1;
1985         smp_wmb();
1986
1987         if (!list_empty(&trans->new_bgs))
1988                 btrfs_create_pending_block_groups(trans);
1989
1990         ret = btrfs_run_delayed_refs(trans, 0);
1991         if (ret) {
1992                 btrfs_end_transaction(trans);
1993                 return ret;
1994         }
1995
1996         if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
1997                 int run_it = 0;
1998
1999                 /* this mutex is also taken before trying to set
2000                  * block groups readonly.  We need to make sure
2001                  * that nobody has set a block group readonly
2002                  * after a extents from that block group have been
2003                  * allocated for cache files.  btrfs_set_block_group_ro
2004                  * will wait for the transaction to commit if it
2005                  * finds BTRFS_TRANS_DIRTY_BG_RUN set.
2006                  *
2007                  * The BTRFS_TRANS_DIRTY_BG_RUN flag is also used to make sure
2008                  * only one process starts all the block group IO.  It wouldn't
2009                  * hurt to have more than one go through, but there's no
2010                  * real advantage to it either.
2011                  */
2012                 mutex_lock(&fs_info->ro_block_group_mutex);
2013                 if (!test_and_set_bit(BTRFS_TRANS_DIRTY_BG_RUN,
2014                                       &cur_trans->flags))
2015                         run_it = 1;
2016                 mutex_unlock(&fs_info->ro_block_group_mutex);
2017
2018                 if (run_it) {
2019                         ret = btrfs_start_dirty_block_groups(trans);
2020                         if (ret) {
2021                                 btrfs_end_transaction(trans);
2022                                 return ret;
2023                         }
2024                 }
2025         }
2026
2027         spin_lock(&fs_info->trans_lock);
2028         if (cur_trans->state >= TRANS_STATE_COMMIT_START) {
2029                 spin_unlock(&fs_info->trans_lock);
2030                 refcount_inc(&cur_trans->use_count);
2031                 ret = btrfs_end_transaction(trans);
2032
2033                 wait_for_commit(cur_trans);
2034
2035                 if (unlikely(cur_trans->aborted))
2036                         ret = cur_trans->aborted;
2037
2038                 btrfs_put_transaction(cur_trans);
2039
2040                 return ret;
2041         }
2042
2043         cur_trans->state = TRANS_STATE_COMMIT_START;
2044         wake_up(&fs_info->transaction_blocked_wait);
2045
2046         if (cur_trans->list.prev != &fs_info->trans_list) {
2047                 prev_trans = list_entry(cur_trans->list.prev,
2048                                         struct btrfs_transaction, list);
2049                 if (prev_trans->state != TRANS_STATE_COMPLETED) {
2050                         refcount_inc(&prev_trans->use_count);
2051                         spin_unlock(&fs_info->trans_lock);
2052
2053                         wait_for_commit(prev_trans);
2054                         ret = prev_trans->aborted;
2055
2056                         btrfs_put_transaction(prev_trans);
2057                         if (ret)
2058                                 goto cleanup_transaction;
2059                 } else {
2060                         spin_unlock(&fs_info->trans_lock);
2061                 }
2062         } else {
2063                 spin_unlock(&fs_info->trans_lock);
2064                 /*
2065                  * The previous transaction was aborted and was already removed
2066                  * from the list of transactions at fs_info->trans_list. So we
2067                  * abort to prevent writing a new superblock that reflects a
2068                  * corrupt state (pointing to trees with unwritten nodes/leafs).
2069                  */
2070                 if (test_bit(BTRFS_FS_STATE_TRANS_ABORTED, &fs_info->fs_state)) {
2071                         ret = -EROFS;
2072                         goto cleanup_transaction;
2073                 }
2074         }
2075
2076         extwriter_counter_dec(cur_trans, trans->type);
2077
2078         ret = btrfs_start_delalloc_flush(fs_info);
2079         if (ret)
2080                 goto cleanup_transaction;
2081
2082         ret = btrfs_run_delayed_items(trans);
2083         if (ret)
2084                 goto cleanup_transaction;
2085
2086         wait_event(cur_trans->writer_wait,
2087                    extwriter_counter_read(cur_trans) == 0);
2088
2089         /* some pending stuffs might be added after the previous flush. */
2090         ret = btrfs_run_delayed_items(trans);
2091         if (ret)
2092                 goto cleanup_transaction;
2093
2094         btrfs_wait_delalloc_flush(fs_info);
2095
2096         btrfs_wait_pending_ordered(cur_trans);
2097
2098         btrfs_scrub_pause(fs_info);
2099         /*
2100          * Ok now we need to make sure to block out any other joins while we
2101          * commit the transaction.  We could have started a join before setting
2102          * COMMIT_DOING so make sure to wait for num_writers to == 1 again.
2103          */
2104         spin_lock(&fs_info->trans_lock);
2105         cur_trans->state = TRANS_STATE_COMMIT_DOING;
2106         spin_unlock(&fs_info->trans_lock);
2107         wait_event(cur_trans->writer_wait,
2108                    atomic_read(&cur_trans->num_writers) == 1);
2109
2110         /* ->aborted might be set after the previous check, so check it */
2111         if (unlikely(READ_ONCE(cur_trans->aborted))) {
2112                 ret = cur_trans->aborted;
2113                 goto scrub_continue;
2114         }
2115         /*
2116          * the reloc mutex makes sure that we stop
2117          * the balancing code from coming in and moving
2118          * extents around in the middle of the commit
2119          */
2120         mutex_lock(&fs_info->reloc_mutex);
2121
2122         /*
2123          * We needn't worry about the delayed items because we will
2124          * deal with them in create_pending_snapshot(), which is the
2125          * core function of the snapshot creation.
2126          */
2127         ret = create_pending_snapshots(trans);
2128         if (ret) {
2129                 mutex_unlock(&fs_info->reloc_mutex);
2130                 goto scrub_continue;
2131         }
2132
2133         /*
2134          * We insert the dir indexes of the snapshots and update the inode
2135          * of the snapshots' parents after the snapshot creation, so there
2136          * are some delayed items which are not dealt with. Now deal with
2137          * them.
2138          *
2139          * We needn't worry that this operation will corrupt the snapshots,
2140          * because all the tree which are snapshoted will be forced to COW
2141          * the nodes and leaves.
2142          */
2143         ret = btrfs_run_delayed_items(trans);
2144         if (ret) {
2145                 mutex_unlock(&fs_info->reloc_mutex);
2146                 goto scrub_continue;
2147         }
2148
2149         ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
2150         if (ret) {
2151                 mutex_unlock(&fs_info->reloc_mutex);
2152                 goto scrub_continue;
2153         }
2154
2155         /*
2156          * make sure none of the code above managed to slip in a
2157          * delayed item
2158          */
2159         btrfs_assert_delayed_root_empty(fs_info);
2160
2161         WARN_ON(cur_trans != trans->transaction);
2162
2163         /* btrfs_commit_tree_roots is responsible for getting the
2164          * various roots consistent with each other.  Every pointer
2165          * in the tree of tree roots has to point to the most up to date
2166          * root for every subvolume and other tree.  So, we have to keep
2167          * the tree logging code from jumping in and changing any
2168          * of the trees.
2169          *
2170          * At this point in the commit, there can't be any tree-log
2171          * writers, but a little lower down we drop the trans mutex
2172          * and let new people in.  By holding the tree_log_mutex
2173          * from now until after the super is written, we avoid races
2174          * with the tree-log code.
2175          */
2176         mutex_lock(&fs_info->tree_log_mutex);
2177
2178         ret = commit_fs_roots(trans);
2179         if (ret) {
2180                 mutex_unlock(&fs_info->tree_log_mutex);
2181                 mutex_unlock(&fs_info->reloc_mutex);
2182                 goto scrub_continue;
2183         }
2184
2185         /*
2186          * Since the transaction is done, we can apply the pending changes
2187          * before the next transaction.
2188          */
2189         btrfs_apply_pending_changes(fs_info);
2190
2191         /* commit_fs_roots gets rid of all the tree log roots, it is now
2192          * safe to free the root of tree log roots
2193          */
2194         btrfs_free_log_root_tree(trans, fs_info);
2195
2196         /*
2197          * commit_fs_roots() can call btrfs_save_ino_cache(), which generates
2198          * new delayed refs. Must handle them or qgroup can be wrong.
2199          */
2200         ret = btrfs_run_delayed_refs(trans, (unsigned long)-1);
2201         if (ret) {
2202                 mutex_unlock(&fs_info->tree_log_mutex);
2203                 mutex_unlock(&fs_info->reloc_mutex);
2204                 goto scrub_continue;
2205         }
2206
2207         /*
2208          * Since fs roots are all committed, we can get a quite accurate
2209          * new_roots. So let's do quota accounting.
2210          */
2211         ret = btrfs_qgroup_account_extents(trans);
2212         if (ret < 0) {
2213                 mutex_unlock(&fs_info->tree_log_mutex);
2214                 mutex_unlock(&fs_info->reloc_mutex);
2215                 goto scrub_continue;
2216         }
2217
2218         ret = commit_cowonly_roots(trans);
2219         if (ret) {
2220                 mutex_unlock(&fs_info->tree_log_mutex);
2221                 mutex_unlock(&fs_info->reloc_mutex);
2222                 goto scrub_continue;
2223         }
2224
2225         /*
2226          * The tasks which save the space cache and inode cache may also
2227          * update ->aborted, check it.
2228          */
2229         if (unlikely(READ_ONCE(cur_trans->aborted))) {
2230                 ret = cur_trans->aborted;
2231                 mutex_unlock(&fs_info->tree_log_mutex);
2232                 mutex_unlock(&fs_info->reloc_mutex);
2233                 goto scrub_continue;
2234         }
2235
2236         btrfs_prepare_extent_commit(fs_info);
2237
2238         cur_trans = fs_info->running_transaction;
2239
2240         btrfs_set_root_node(&fs_info->tree_root->root_item,
2241                             fs_info->tree_root->node);
2242         list_add_tail(&fs_info->tree_root->dirty_list,
2243                       &cur_trans->switch_commits);
2244
2245         btrfs_set_root_node(&fs_info->chunk_root->root_item,
2246                             fs_info->chunk_root->node);
2247         list_add_tail(&fs_info->chunk_root->dirty_list,
2248                       &cur_trans->switch_commits);
2249
2250         switch_commit_roots(cur_trans);
2251
2252         ASSERT(list_empty(&cur_trans->dirty_bgs));
2253         ASSERT(list_empty(&cur_trans->io_bgs));
2254         update_super_roots(fs_info);
2255
2256         btrfs_set_super_log_root(fs_info->super_copy, 0);
2257         btrfs_set_super_log_root_level(fs_info->super_copy, 0);
2258         memcpy(fs_info->super_for_commit, fs_info->super_copy,
2259                sizeof(*fs_info->super_copy));
2260
2261         btrfs_update_commit_device_size(fs_info);
2262         btrfs_update_commit_device_bytes_used(cur_trans);
2263
2264         clear_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
2265         clear_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
2266
2267         btrfs_trans_release_chunk_metadata(trans);
2268
2269         spin_lock(&fs_info->trans_lock);
2270         cur_trans->state = TRANS_STATE_UNBLOCKED;
2271         fs_info->running_transaction = NULL;
2272         spin_unlock(&fs_info->trans_lock);
2273         mutex_unlock(&fs_info->reloc_mutex);
2274
2275         wake_up(&fs_info->transaction_wait);
2276
2277         ret = btrfs_write_and_wait_transaction(trans);
2278         if (ret) {
2279                 btrfs_handle_fs_error(fs_info, ret,
2280                                       "Error while writing out transaction");
2281                 mutex_unlock(&fs_info->tree_log_mutex);
2282                 goto scrub_continue;
2283         }
2284
2285         ret = write_all_supers(fs_info, 0);
2286         /*
2287          * the super is written, we can safely allow the tree-loggers
2288          * to go about their business
2289          */
2290         mutex_unlock(&fs_info->tree_log_mutex);
2291         if (ret)
2292                 goto scrub_continue;
2293
2294         btrfs_finish_extent_commit(trans);
2295
2296         if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
2297                 btrfs_clear_space_info_full(fs_info);
2298
2299         fs_info->last_trans_committed = cur_trans->transid;
2300         /*
2301          * We needn't acquire the lock here because there is no other task
2302          * which can change it.
2303          */
2304         cur_trans->state = TRANS_STATE_COMPLETED;
2305         wake_up(&cur_trans->commit_wait);
2306         clear_bit(BTRFS_FS_NEED_ASYNC_COMMIT, &fs_info->flags);
2307
2308         spin_lock(&fs_info->trans_lock);
2309         list_del_init(&cur_trans->list);
2310         spin_unlock(&fs_info->trans_lock);
2311
2312         btrfs_put_transaction(cur_trans);
2313         btrfs_put_transaction(cur_trans);
2314
2315         if (trans->type & __TRANS_FREEZABLE)
2316                 sb_end_intwrite(fs_info->sb);
2317
2318         trace_btrfs_transaction_commit(trans->root);
2319
2320         btrfs_scrub_continue(fs_info);
2321
2322         if (current->journal_info == trans)
2323                 current->journal_info = NULL;
2324
2325         kmem_cache_free(btrfs_trans_handle_cachep, trans);
2326
2327         return ret;
2328
2329 scrub_continue:
2330         btrfs_scrub_continue(fs_info);
2331 cleanup_transaction:
2332         btrfs_trans_release_metadata(trans);
2333         btrfs_trans_release_chunk_metadata(trans);
2334         trans->block_rsv = NULL;
2335         btrfs_warn(fs_info, "Skipping commit of aborted transaction.");
2336         if (current->journal_info == trans)
2337                 current->journal_info = NULL;
2338         cleanup_transaction(trans, ret);
2339
2340         return ret;
2341 }
2342
2343 /*
2344  * return < 0 if error
2345  * 0 if there are no more dead_roots at the time of call
2346  * 1 there are more to be processed, call me again
2347  *
2348  * The return value indicates there are certainly more snapshots to delete, but
2349  * if there comes a new one during processing, it may return 0. We don't mind,
2350  * because btrfs_commit_super will poke cleaner thread and it will process it a
2351  * few seconds later.
2352  */
2353 int btrfs_clean_one_deleted_snapshot(struct btrfs_root *root)
2354 {
2355         int ret;
2356         struct btrfs_fs_info *fs_info = root->fs_info;
2357
2358         spin_lock(&fs_info->trans_lock);
2359         if (list_empty(&fs_info->dead_roots)) {
2360                 spin_unlock(&fs_info->trans_lock);
2361                 return 0;
2362         }
2363         root = list_first_entry(&fs_info->dead_roots,
2364                         struct btrfs_root, root_list);
2365         list_del_init(&root->root_list);
2366         spin_unlock(&fs_info->trans_lock);
2367
2368         btrfs_debug(fs_info, "cleaner removing %llu", root->objectid);
2369
2370         btrfs_kill_all_delayed_nodes(root);
2371
2372         if (btrfs_header_backref_rev(root->node) <
2373                         BTRFS_MIXED_BACKREF_REV)
2374                 ret = btrfs_drop_snapshot(root, NULL, 0, 0);
2375         else
2376                 ret = btrfs_drop_snapshot(root, NULL, 1, 0);
2377
2378         return (ret < 0) ? 0 : 1;
2379 }
2380
2381 void btrfs_apply_pending_changes(struct btrfs_fs_info *fs_info)
2382 {
2383         unsigned long prev;
2384         unsigned long bit;
2385
2386         prev = xchg(&fs_info->pending_changes, 0);
2387         if (!prev)
2388                 return;
2389
2390         bit = 1 << BTRFS_PENDING_SET_INODE_MAP_CACHE;
2391         if (prev & bit)
2392                 btrfs_set_opt(fs_info->mount_opt, INODE_MAP_CACHE);
2393         prev &= ~bit;
2394
2395         bit = 1 << BTRFS_PENDING_CLEAR_INODE_MAP_CACHE;
2396         if (prev & bit)
2397                 btrfs_clear_opt(fs_info->mount_opt, INODE_MAP_CACHE);
2398         prev &= ~bit;
2399
2400         bit = 1 << BTRFS_PENDING_COMMIT;
2401         if (prev & bit)
2402                 btrfs_debug(fs_info, "pending commit done");
2403         prev &= ~bit;
2404
2405         if (prev)
2406                 btrfs_warn(fs_info,
2407                         "unknown pending changes left 0x%lx, ignoring", prev);
2408 }