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