root/fs/btrfs/transaction.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. btrfs_put_transaction
  2. switch_commit_roots
  3. extwriter_counter_inc
  4. extwriter_counter_dec
  5. extwriter_counter_init
  6. extwriter_counter_read
  7. btrfs_trans_release_chunk_metadata
  8. join_transaction
  9. record_root_in_trans
  10. btrfs_add_dropped_root
  11. btrfs_record_root_in_trans
  12. is_transaction_blocked
  13. wait_current_trans
  14. may_wait_transaction
  15. need_reserve_reloc_root
  16. start_transaction
  17. btrfs_start_transaction
  18. btrfs_start_transaction_fallback_global_rsv
  19. btrfs_join_transaction
  20. btrfs_join_transaction_nolock
  21. btrfs_join_transaction_nostart
  22. btrfs_attach_transaction
  23. btrfs_attach_transaction_barrier
  24. wait_for_commit
  25. btrfs_wait_for_commit
  26. btrfs_throttle
  27. should_end_transaction
  28. btrfs_should_end_transaction
  29. btrfs_trans_release_metadata
  30. __btrfs_end_transaction
  31. btrfs_end_transaction
  32. btrfs_end_transaction_throttle
  33. btrfs_write_marked_extents
  34. __btrfs_wait_marked_extents
  35. btrfs_wait_extents
  36. btrfs_wait_tree_log_extents
  37. btrfs_write_and_wait_transaction
  38. update_cowonly_root
  39. commit_cowonly_roots
  40. btrfs_add_dead_root
  41. commit_fs_roots
  42. btrfs_defrag_root
  43. qgroup_account_snapshot
  44. create_pending_snapshot
  45. create_pending_snapshots
  46. update_super_roots
  47. btrfs_transaction_in_commit
  48. btrfs_transaction_blocked
  49. wait_current_trans_commit_start
  50. wait_current_trans_commit_start_and_unblock
  51. do_async_commit
  52. btrfs_commit_transaction_async
  53. cleanup_transaction
  54. btrfs_cleanup_pending_block_groups
  55. btrfs_start_delalloc_flush
  56. btrfs_wait_delalloc_flush
  57. btrfs_commit_transaction
  58. btrfs_clean_one_deleted_snapshot
  59. btrfs_apply_pending_changes

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

/* [<][>][^][v][top][bottom][index][help] */