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