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