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