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