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