Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Copyright (C) 2007 Oracle. All rights reserved.
4 */
5
6#include <linux/sched.h>
7#include <linux/sched/signal.h>
8#include <linux/pagemap.h>
9#include <linux/writeback.h>
10#include <linux/blkdev.h>
11#include <linux/sort.h>
12#include <linux/rcupdate.h>
13#include <linux/kthread.h>
14#include <linux/slab.h>
15#include <linux/ratelimit.h>
16#include <linux/percpu_counter.h>
17#include <linux/lockdep.h>
18#include <linux/crc32c.h>
19#include "ctree.h"
20#include "extent-tree.h"
21#include "transaction.h"
22#include "disk-io.h"
23#include "print-tree.h"
24#include "volumes.h"
25#include "raid56.h"
26#include "locking.h"
27#include "free-space-cache.h"
28#include "free-space-tree.h"
29#include "qgroup.h"
30#include "ref-verify.h"
31#include "space-info.h"
32#include "block-rsv.h"
33#include "discard.h"
34#include "zoned.h"
35#include "dev-replace.h"
36#include "fs.h"
37#include "accessors.h"
38#include "root-tree.h"
39#include "file-item.h"
40#include "orphan.h"
41#include "tree-checker.h"
42#include "raid-stripe-tree.h"
43#include "delayed-inode.h"
44
45#undef SCRAMBLE_DELAYED_REFS
46
47
48static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
49 struct btrfs_delayed_ref_head *href,
50 const struct btrfs_delayed_ref_node *node,
51 struct btrfs_delayed_extent_op *extra_op);
52static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
53 struct extent_buffer *leaf,
54 struct btrfs_extent_item *ei);
55static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
56 u64 parent, u64 root_objectid,
57 u64 flags, u64 owner, u64 offset,
58 struct btrfs_key *ins, int ref_mod, u64 oref_root);
59static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
60 const struct btrfs_delayed_ref_node *node,
61 struct btrfs_delayed_extent_op *extent_op);
62static int find_next_key(const struct btrfs_path *path, int level,
63 struct btrfs_key *key);
64
65static int block_group_bits(const struct btrfs_block_group *cache, u64 bits)
66{
67 return (cache->flags & bits) == bits;
68}
69
70/* simple helper to search for an existing data extent at a given offset */
71int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
72{
73 struct btrfs_root *root = btrfs_extent_root(fs_info, start);
74 struct btrfs_key key;
75 BTRFS_PATH_AUTO_FREE(path);
76
77 path = btrfs_alloc_path();
78 if (!path)
79 return -ENOMEM;
80
81 key.objectid = start;
82 key.type = BTRFS_EXTENT_ITEM_KEY;
83 key.offset = len;
84 return btrfs_search_slot(NULL, root, &key, path, 0, 0);
85}
86
87/*
88 * helper function to lookup reference count and flags of a tree block.
89 *
90 * the head node for delayed ref is used to store the sum of all the
91 * reference count modifications queued up in the rbtree. the head
92 * node may also store the extent flags to set. This way you can check
93 * to see what the reference count and extent flags would be if all of
94 * the delayed refs are not processed.
95 */
96int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
97 struct btrfs_fs_info *fs_info, u64 bytenr,
98 u64 offset, int metadata, u64 *refs, u64 *flags,
99 u64 *owning_root)
100{
101 struct btrfs_root *extent_root;
102 struct btrfs_delayed_ref_head *head;
103 struct btrfs_delayed_ref_root *delayed_refs;
104 BTRFS_PATH_AUTO_FREE(path);
105 struct btrfs_key key;
106 u64 num_refs;
107 u64 extent_flags;
108 u64 owner = 0;
109 int ret;
110
111 /*
112 * If we don't have skinny metadata, don't bother doing anything
113 * different
114 */
115 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
116 offset = fs_info->nodesize;
117 metadata = 0;
118 }
119
120 path = btrfs_alloc_path();
121 if (!path)
122 return -ENOMEM;
123
124search_again:
125 key.objectid = bytenr;
126 if (metadata)
127 key.type = BTRFS_METADATA_ITEM_KEY;
128 else
129 key.type = BTRFS_EXTENT_ITEM_KEY;
130 key.offset = offset;
131
132 extent_root = btrfs_extent_root(fs_info, bytenr);
133 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
134 if (ret < 0)
135 return ret;
136
137 if (ret > 0 && key.type == BTRFS_METADATA_ITEM_KEY) {
138 if (path->slots[0]) {
139 path->slots[0]--;
140 btrfs_item_key_to_cpu(path->nodes[0], &key,
141 path->slots[0]);
142 if (key.objectid == bytenr &&
143 key.type == BTRFS_EXTENT_ITEM_KEY &&
144 key.offset == fs_info->nodesize)
145 ret = 0;
146 }
147 }
148
149 if (ret == 0) {
150 struct extent_buffer *leaf = path->nodes[0];
151 struct btrfs_extent_item *ei;
152 const u32 item_size = btrfs_item_size(leaf, path->slots[0]);
153
154 if (unlikely(item_size < sizeof(*ei))) {
155 ret = -EUCLEAN;
156 btrfs_err(fs_info,
157 "unexpected extent item size, has %u expect >= %zu",
158 item_size, sizeof(*ei));
159 btrfs_abort_transaction(trans, ret);
160 return ret;
161 }
162
163 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
164 num_refs = btrfs_extent_refs(leaf, ei);
165 if (unlikely(num_refs == 0)) {
166 ret = -EUCLEAN;
167 btrfs_err(fs_info,
168 "unexpected zero reference count for extent item " BTRFS_KEY_FMT,
169 BTRFS_KEY_FMT_VALUE(&key));
170 btrfs_abort_transaction(trans, ret);
171 return ret;
172 }
173 extent_flags = btrfs_extent_flags(leaf, ei);
174 owner = btrfs_get_extent_owner_root(fs_info, leaf, path->slots[0]);
175 } else {
176 num_refs = 0;
177 extent_flags = 0;
178 ret = 0;
179 }
180
181 delayed_refs = &trans->transaction->delayed_refs;
182 spin_lock(&delayed_refs->lock);
183 head = btrfs_find_delayed_ref_head(fs_info, delayed_refs, bytenr);
184 if (head) {
185 if (!mutex_trylock(&head->mutex)) {
186 refcount_inc(&head->refs);
187 spin_unlock(&delayed_refs->lock);
188
189 btrfs_release_path(path);
190
191 /*
192 * Mutex was contended, block until it's released and try
193 * again
194 */
195 mutex_lock(&head->mutex);
196 mutex_unlock(&head->mutex);
197 btrfs_put_delayed_ref_head(head);
198 goto search_again;
199 }
200 spin_lock(&head->lock);
201 if (head->extent_op && head->extent_op->update_flags)
202 extent_flags |= head->extent_op->flags_to_set;
203
204 num_refs += head->ref_mod;
205 spin_unlock(&head->lock);
206 mutex_unlock(&head->mutex);
207 }
208 spin_unlock(&delayed_refs->lock);
209
210 WARN_ON(num_refs == 0);
211 if (refs)
212 *refs = num_refs;
213 if (flags)
214 *flags = extent_flags;
215 if (owning_root)
216 *owning_root = owner;
217
218 return ret;
219}
220
221/*
222 * Back reference rules. Back refs have three main goals:
223 *
224 * 1) differentiate between all holders of references to an extent so that
225 * when a reference is dropped we can make sure it was a valid reference
226 * before freeing the extent.
227 *
228 * 2) Provide enough information to quickly find the holders of an extent
229 * if we notice a given block is corrupted or bad.
230 *
231 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
232 * maintenance. This is actually the same as #2, but with a slightly
233 * different use case.
234 *
235 * There are two kinds of back refs. The implicit back refs is optimized
236 * for pointers in non-shared tree blocks. For a given pointer in a block,
237 * back refs of this kind provide information about the block's owner tree
238 * and the pointer's key. These information allow us to find the block by
239 * b-tree searching. The full back refs is for pointers in tree blocks not
240 * referenced by their owner trees. The location of tree block is recorded
241 * in the back refs. Actually the full back refs is generic, and can be
242 * used in all cases the implicit back refs is used. The major shortcoming
243 * of the full back refs is its overhead. Every time a tree block gets
244 * COWed, we have to update back refs entry for all pointers in it.
245 *
246 * For a newly allocated tree block, we use implicit back refs for
247 * pointers in it. This means most tree related operations only involve
248 * implicit back refs. For a tree block created in old transaction, the
249 * only way to drop a reference to it is COW it. So we can detect the
250 * event that tree block loses its owner tree's reference and do the
251 * back refs conversion.
252 *
253 * When a tree block is COWed through a tree, there are four cases:
254 *
255 * The reference count of the block is one and the tree is the block's
256 * owner tree. Nothing to do in this case.
257 *
258 * The reference count of the block is one and the tree is not the
259 * block's owner tree. In this case, full back refs is used for pointers
260 * in the block. Remove these full back refs, add implicit back refs for
261 * every pointers in the new block.
262 *
263 * The reference count of the block is greater than one and the tree is
264 * the block's owner tree. In this case, implicit back refs is used for
265 * pointers in the block. Add full back refs for every pointers in the
266 * block, increase lower level extents' reference counts. The original
267 * implicit back refs are entailed to the new block.
268 *
269 * The reference count of the block is greater than one and the tree is
270 * not the block's owner tree. Add implicit back refs for every pointer in
271 * the new block, increase lower level extents' reference count.
272 *
273 * Back Reference Key composing:
274 *
275 * The key objectid corresponds to the first byte in the extent,
276 * The key type is used to differentiate between types of back refs.
277 * There are different meanings of the key offset for different types
278 * of back refs.
279 *
280 * File extents can be referenced by:
281 *
282 * - multiple snapshots, subvolumes, or different generations in one subvol
283 * - different files inside a single subvolume
284 * - different offsets inside a file (bookend extents in file.c)
285 *
286 * The extent ref structure for the implicit back refs has fields for:
287 *
288 * - Objectid of the subvolume root
289 * - objectid of the file holding the reference
290 * - original offset in the file
291 * - how many bookend extents
292 *
293 * The key offset for the implicit back refs is hash of the first
294 * three fields.
295 *
296 * The extent ref structure for the full back refs has field for:
297 *
298 * - number of pointers in the tree leaf
299 *
300 * The key offset for the implicit back refs is the first byte of
301 * the tree leaf
302 *
303 * When a file extent is allocated, The implicit back refs is used.
304 * the fields are filled in:
305 *
306 * (root_key.objectid, inode objectid, offset in file, 1)
307 *
308 * When a file extent is removed file truncation, we find the
309 * corresponding implicit back refs and check the following fields:
310 *
311 * (btrfs_header_owner(leaf), inode objectid, offset in file)
312 *
313 * Btree extents can be referenced by:
314 *
315 * - Different subvolumes
316 *
317 * Both the implicit back refs and the full back refs for tree blocks
318 * only consist of key. The key offset for the implicit back refs is
319 * objectid of block's owner tree. The key offset for the full back refs
320 * is the first byte of parent block.
321 *
322 * When implicit back refs is used, information about the lowest key and
323 * level of the tree block are required. These information are stored in
324 * tree block info structure.
325 */
326
327/*
328 * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
329 * is_data == BTRFS_REF_TYPE_DATA, data type is required,
330 * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
331 */
332int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
333 const struct btrfs_extent_inline_ref *iref,
334 enum btrfs_inline_ref_type is_data)
335{
336 struct btrfs_fs_info *fs_info = eb->fs_info;
337 int type = btrfs_extent_inline_ref_type(eb, iref);
338 u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
339
340 if (type == BTRFS_EXTENT_OWNER_REF_KEY) {
341 ASSERT(btrfs_fs_incompat(fs_info, SIMPLE_QUOTA));
342 return type;
343 }
344
345 if (type == BTRFS_TREE_BLOCK_REF_KEY ||
346 type == BTRFS_SHARED_BLOCK_REF_KEY ||
347 type == BTRFS_SHARED_DATA_REF_KEY ||
348 type == BTRFS_EXTENT_DATA_REF_KEY) {
349 if (is_data == BTRFS_REF_TYPE_BLOCK) {
350 if (type == BTRFS_TREE_BLOCK_REF_KEY)
351 return type;
352 if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
353 ASSERT(fs_info);
354 /*
355 * Every shared one has parent tree block,
356 * which must be aligned to sector size.
357 */
358 if (offset && IS_ALIGNED(offset, fs_info->sectorsize))
359 return type;
360 }
361 } else if (is_data == BTRFS_REF_TYPE_DATA) {
362 if (type == BTRFS_EXTENT_DATA_REF_KEY)
363 return type;
364 if (type == BTRFS_SHARED_DATA_REF_KEY) {
365 ASSERT(fs_info);
366 /*
367 * Every shared one has parent tree block,
368 * which must be aligned to sector size.
369 */
370 if (offset &&
371 IS_ALIGNED(offset, fs_info->sectorsize))
372 return type;
373 }
374 } else {
375 ASSERT(is_data == BTRFS_REF_TYPE_ANY);
376 return type;
377 }
378 }
379
380 WARN_ON(1);
381 btrfs_print_leaf(eb);
382 btrfs_err(fs_info,
383 "eb %llu iref 0x%lx invalid extent inline ref type %d",
384 eb->start, (unsigned long)iref, type);
385
386 return BTRFS_REF_TYPE_INVALID;
387}
388
389u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
390{
391 u32 high_crc = ~(u32)0;
392 u32 low_crc = ~(u32)0;
393 __le64 lenum;
394
395 lenum = cpu_to_le64(root_objectid);
396 high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
397 lenum = cpu_to_le64(owner);
398 low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
399 lenum = cpu_to_le64(offset);
400 low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
401
402 return ((u64)high_crc << 31) ^ (u64)low_crc;
403}
404
405static u64 hash_extent_data_ref_item(const struct extent_buffer *leaf,
406 const struct btrfs_extent_data_ref *ref)
407{
408 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
409 btrfs_extent_data_ref_objectid(leaf, ref),
410 btrfs_extent_data_ref_offset(leaf, ref));
411}
412
413static bool match_extent_data_ref(const struct extent_buffer *leaf,
414 const struct btrfs_extent_data_ref *ref,
415 u64 root_objectid, u64 owner, u64 offset)
416{
417 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
418 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
419 btrfs_extent_data_ref_offset(leaf, ref) != offset)
420 return false;
421 return true;
422}
423
424static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
425 struct btrfs_path *path,
426 u64 bytenr, u64 parent,
427 u64 root_objectid,
428 u64 owner, u64 offset)
429{
430 struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
431 struct btrfs_key key;
432 struct btrfs_extent_data_ref *ref;
433 struct extent_buffer *leaf;
434 u32 nritems;
435 int recow;
436 int ret;
437
438 key.objectid = bytenr;
439 if (parent) {
440 key.type = BTRFS_SHARED_DATA_REF_KEY;
441 key.offset = parent;
442 } else {
443 key.type = BTRFS_EXTENT_DATA_REF_KEY;
444 key.offset = hash_extent_data_ref(root_objectid,
445 owner, offset);
446 }
447again:
448 recow = 0;
449 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
450 if (ret < 0)
451 return ret;
452
453 if (parent) {
454 if (ret)
455 return -ENOENT;
456 return 0;
457 }
458
459 ret = -ENOENT;
460 leaf = path->nodes[0];
461 nritems = btrfs_header_nritems(leaf);
462 while (1) {
463 if (path->slots[0] >= nritems) {
464 ret = btrfs_next_leaf(root, path);
465 if (ret) {
466 if (ret > 0)
467 return -ENOENT;
468 return ret;
469 }
470
471 leaf = path->nodes[0];
472 nritems = btrfs_header_nritems(leaf);
473 recow = 1;
474 }
475
476 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
477 if (key.objectid != bytenr ||
478 key.type != BTRFS_EXTENT_DATA_REF_KEY)
479 goto fail;
480
481 ref = btrfs_item_ptr(leaf, path->slots[0],
482 struct btrfs_extent_data_ref);
483
484 if (match_extent_data_ref(leaf, ref, root_objectid,
485 owner, offset)) {
486 if (recow) {
487 btrfs_release_path(path);
488 goto again;
489 }
490 ret = 0;
491 break;
492 }
493 path->slots[0]++;
494 }
495fail:
496 return ret;
497}
498
499static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
500 struct btrfs_path *path,
501 const struct btrfs_delayed_ref_node *node,
502 u64 bytenr)
503{
504 struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
505 struct btrfs_key key;
506 struct extent_buffer *leaf;
507 u64 owner = btrfs_delayed_ref_owner(node);
508 u64 offset = btrfs_delayed_ref_offset(node);
509 u32 size;
510 u32 num_refs;
511 int ret;
512
513 key.objectid = bytenr;
514 if (node->parent) {
515 key.type = BTRFS_SHARED_DATA_REF_KEY;
516 key.offset = node->parent;
517 size = sizeof(struct btrfs_shared_data_ref);
518 } else {
519 key.type = BTRFS_EXTENT_DATA_REF_KEY;
520 key.offset = hash_extent_data_ref(node->ref_root, owner, offset);
521 size = sizeof(struct btrfs_extent_data_ref);
522 }
523
524 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
525 if (ret && ret != -EEXIST)
526 goto fail;
527
528 leaf = path->nodes[0];
529 if (node->parent) {
530 struct btrfs_shared_data_ref *ref;
531 ref = btrfs_item_ptr(leaf, path->slots[0],
532 struct btrfs_shared_data_ref);
533 if (ret == 0) {
534 btrfs_set_shared_data_ref_count(leaf, ref, node->ref_mod);
535 } else {
536 num_refs = btrfs_shared_data_ref_count(leaf, ref);
537 num_refs += node->ref_mod;
538 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
539 }
540 } else {
541 struct btrfs_extent_data_ref *ref;
542 while (ret == -EEXIST) {
543 ref = btrfs_item_ptr(leaf, path->slots[0],
544 struct btrfs_extent_data_ref);
545 if (match_extent_data_ref(leaf, ref, node->ref_root,
546 owner, offset))
547 break;
548 btrfs_release_path(path);
549 key.offset++;
550 ret = btrfs_insert_empty_item(trans, root, path, &key,
551 size);
552 if (ret && ret != -EEXIST)
553 goto fail;
554
555 leaf = path->nodes[0];
556 }
557 ref = btrfs_item_ptr(leaf, path->slots[0],
558 struct btrfs_extent_data_ref);
559 if (ret == 0) {
560 btrfs_set_extent_data_ref_root(leaf, ref, node->ref_root);
561 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
562 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
563 btrfs_set_extent_data_ref_count(leaf, ref, node->ref_mod);
564 } else {
565 num_refs = btrfs_extent_data_ref_count(leaf, ref);
566 num_refs += node->ref_mod;
567 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
568 }
569 }
570 ret = 0;
571fail:
572 btrfs_release_path(path);
573 return ret;
574}
575
576static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
577 struct btrfs_root *root,
578 struct btrfs_path *path,
579 int refs_to_drop)
580{
581 struct btrfs_key key;
582 struct btrfs_extent_data_ref *ref1 = NULL;
583 struct btrfs_shared_data_ref *ref2 = NULL;
584 struct extent_buffer *leaf;
585 u32 num_refs = 0;
586 int ret = 0;
587
588 leaf = path->nodes[0];
589 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
590
591 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
592 ref1 = btrfs_item_ptr(leaf, path->slots[0],
593 struct btrfs_extent_data_ref);
594 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
595 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
596 ref2 = btrfs_item_ptr(leaf, path->slots[0],
597 struct btrfs_shared_data_ref);
598 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
599 } else {
600 btrfs_err(trans->fs_info,
601 "unrecognized backref key " BTRFS_KEY_FMT,
602 BTRFS_KEY_FMT_VALUE(&key));
603 btrfs_abort_transaction(trans, -EUCLEAN);
604 return -EUCLEAN;
605 }
606
607 BUG_ON(num_refs < refs_to_drop);
608 num_refs -= refs_to_drop;
609
610 if (num_refs == 0) {
611 ret = btrfs_del_item(trans, root, path);
612 } else {
613 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
614 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
615 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
616 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
617 }
618 return ret;
619}
620
621static noinline u32 extent_data_ref_count(const struct btrfs_path *path,
622 const struct btrfs_extent_inline_ref *iref)
623{
624 struct btrfs_key key;
625 struct extent_buffer *leaf;
626 const struct btrfs_extent_data_ref *ref1;
627 const struct btrfs_shared_data_ref *ref2;
628 u32 num_refs = 0;
629 int type;
630
631 leaf = path->nodes[0];
632 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
633
634 if (iref) {
635 /*
636 * If type is invalid, we should have bailed out earlier than
637 * this call.
638 */
639 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
640 ASSERT(type != BTRFS_REF_TYPE_INVALID);
641 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
642 ref1 = (const struct btrfs_extent_data_ref *)(&iref->offset);
643 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
644 } else {
645 ref2 = (const struct btrfs_shared_data_ref *)(iref + 1);
646 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
647 }
648 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
649 ref1 = btrfs_item_ptr(leaf, path->slots[0],
650 struct btrfs_extent_data_ref);
651 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
652 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
653 ref2 = btrfs_item_ptr(leaf, path->slots[0],
654 struct btrfs_shared_data_ref);
655 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
656 } else {
657 WARN_ON(1);
658 }
659 return num_refs;
660}
661
662static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
663 struct btrfs_path *path,
664 u64 bytenr, u64 parent,
665 u64 root_objectid)
666{
667 struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
668 struct btrfs_key key;
669 int ret;
670
671 key.objectid = bytenr;
672 if (parent) {
673 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
674 key.offset = parent;
675 } else {
676 key.type = BTRFS_TREE_BLOCK_REF_KEY;
677 key.offset = root_objectid;
678 }
679
680 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
681 if (ret > 0)
682 ret = -ENOENT;
683 return ret;
684}
685
686static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
687 struct btrfs_path *path,
688 const struct btrfs_delayed_ref_node *node,
689 u64 bytenr)
690{
691 struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
692 struct btrfs_key key;
693 int ret;
694
695 key.objectid = bytenr;
696 if (node->parent) {
697 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
698 key.offset = node->parent;
699 } else {
700 key.type = BTRFS_TREE_BLOCK_REF_KEY;
701 key.offset = node->ref_root;
702 }
703
704 ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
705 btrfs_release_path(path);
706 return ret;
707}
708
709static inline int extent_ref_type(u64 parent, u64 owner)
710{
711 int type;
712 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
713 if (parent > 0)
714 type = BTRFS_SHARED_BLOCK_REF_KEY;
715 else
716 type = BTRFS_TREE_BLOCK_REF_KEY;
717 } else {
718 if (parent > 0)
719 type = BTRFS_SHARED_DATA_REF_KEY;
720 else
721 type = BTRFS_EXTENT_DATA_REF_KEY;
722 }
723 return type;
724}
725
726static int find_next_key(const struct btrfs_path *path, int level,
727 struct btrfs_key *key)
728
729{
730 for (; level < BTRFS_MAX_LEVEL; level++) {
731 if (!path->nodes[level])
732 break;
733 if (path->slots[level] + 1 >=
734 btrfs_header_nritems(path->nodes[level]))
735 continue;
736 if (level == 0)
737 btrfs_item_key_to_cpu(path->nodes[level], key,
738 path->slots[level] + 1);
739 else
740 btrfs_node_key_to_cpu(path->nodes[level], key,
741 path->slots[level] + 1);
742 return 0;
743 }
744 return 1;
745}
746
747/*
748 * look for inline back ref. if back ref is found, *ref_ret is set
749 * to the address of inline back ref, and 0 is returned.
750 *
751 * if back ref isn't found, *ref_ret is set to the address where it
752 * should be inserted, and -ENOENT is returned.
753 *
754 * if insert is true and there are too many inline back refs, the path
755 * points to the extent item, and -EAGAIN is returned.
756 *
757 * NOTE: inline back refs are ordered in the same way that back ref
758 * items in the tree are ordered.
759 */
760static noinline_for_stack
761int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
762 struct btrfs_path *path,
763 struct btrfs_extent_inline_ref **ref_ret,
764 u64 bytenr, u64 num_bytes,
765 u64 parent, u64 root_objectid,
766 u64 owner, u64 offset, int insert)
767{
768 struct btrfs_fs_info *fs_info = trans->fs_info;
769 struct btrfs_root *root = btrfs_extent_root(fs_info, bytenr);
770 struct btrfs_key key;
771 struct extent_buffer *leaf;
772 struct btrfs_extent_item *ei;
773 struct btrfs_extent_inline_ref *iref;
774 u64 flags;
775 u64 item_size;
776 unsigned long ptr;
777 unsigned long end;
778 int extra_size;
779 int type;
780 int want;
781 int ret;
782 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
783 int needed;
784
785 key.objectid = bytenr;
786 key.type = BTRFS_EXTENT_ITEM_KEY;
787 key.offset = num_bytes;
788
789 want = extent_ref_type(parent, owner);
790 if (insert) {
791 extra_size = btrfs_extent_inline_ref_size(want);
792 path->search_for_extension = true;
793 } else
794 extra_size = -1;
795
796 /*
797 * Owner is our level, so we can just add one to get the level for the
798 * block we are interested in.
799 */
800 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
801 key.type = BTRFS_METADATA_ITEM_KEY;
802 key.offset = owner;
803 }
804
805again:
806 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
807 if (ret < 0)
808 goto out;
809
810 /*
811 * We may be a newly converted file system which still has the old fat
812 * extent entries for metadata, so try and see if we have one of those.
813 */
814 if (ret > 0 && skinny_metadata) {
815 skinny_metadata = false;
816 if (path->slots[0]) {
817 path->slots[0]--;
818 btrfs_item_key_to_cpu(path->nodes[0], &key,
819 path->slots[0]);
820 if (key.objectid == bytenr &&
821 key.type == BTRFS_EXTENT_ITEM_KEY &&
822 key.offset == num_bytes)
823 ret = 0;
824 }
825 if (ret) {
826 key.objectid = bytenr;
827 key.type = BTRFS_EXTENT_ITEM_KEY;
828 key.offset = num_bytes;
829 btrfs_release_path(path);
830 goto again;
831 }
832 }
833
834 if (ret && !insert) {
835 ret = -ENOENT;
836 goto out;
837 } else if (WARN_ON(ret)) {
838 btrfs_print_leaf(path->nodes[0]);
839 btrfs_err(fs_info,
840"extent item not found for insert, bytenr %llu num_bytes %llu parent %llu root_objectid %llu owner %llu offset %llu",
841 bytenr, num_bytes, parent, root_objectid, owner,
842 offset);
843 ret = -EUCLEAN;
844 goto out;
845 }
846
847 leaf = path->nodes[0];
848 item_size = btrfs_item_size(leaf, path->slots[0]);
849 if (unlikely(item_size < sizeof(*ei))) {
850 ret = -EUCLEAN;
851 btrfs_err(fs_info,
852 "unexpected extent item size, has %llu expect >= %zu",
853 item_size, sizeof(*ei));
854 btrfs_abort_transaction(trans, ret);
855 goto out;
856 }
857
858 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
859 flags = btrfs_extent_flags(leaf, ei);
860
861 ptr = (unsigned long)(ei + 1);
862 end = (unsigned long)ei + item_size;
863
864 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
865 ptr += sizeof(struct btrfs_tree_block_info);
866 BUG_ON(ptr > end);
867 }
868
869 if (owner >= BTRFS_FIRST_FREE_OBJECTID)
870 needed = BTRFS_REF_TYPE_DATA;
871 else
872 needed = BTRFS_REF_TYPE_BLOCK;
873
874 ret = -ENOENT;
875 while (ptr < end) {
876 iref = (struct btrfs_extent_inline_ref *)ptr;
877 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
878 if (type == BTRFS_EXTENT_OWNER_REF_KEY) {
879 ASSERT(btrfs_fs_incompat(fs_info, SIMPLE_QUOTA));
880 ptr += btrfs_extent_inline_ref_size(type);
881 continue;
882 }
883 if (unlikely(type == BTRFS_REF_TYPE_INVALID)) {
884 ret = -EUCLEAN;
885 goto out;
886 }
887
888 if (want < type)
889 break;
890 if (want > type) {
891 ptr += btrfs_extent_inline_ref_size(type);
892 continue;
893 }
894
895 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
896 struct btrfs_extent_data_ref *dref;
897 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
898 if (match_extent_data_ref(leaf, dref, root_objectid,
899 owner, offset)) {
900 ret = 0;
901 break;
902 }
903 if (hash_extent_data_ref_item(leaf, dref) <
904 hash_extent_data_ref(root_objectid, owner, offset))
905 break;
906 } else {
907 u64 ref_offset;
908 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
909 if (parent > 0) {
910 if (parent == ref_offset) {
911 ret = 0;
912 break;
913 }
914 if (ref_offset < parent)
915 break;
916 } else {
917 if (root_objectid == ref_offset) {
918 ret = 0;
919 break;
920 }
921 if (ref_offset < root_objectid)
922 break;
923 }
924 }
925 ptr += btrfs_extent_inline_ref_size(type);
926 }
927
928 if (unlikely(ptr > end)) {
929 ret = -EUCLEAN;
930 btrfs_print_leaf(path->nodes[0]);
931 btrfs_crit(fs_info,
932"overrun extent record at slot %d while looking for inline extent for root %llu owner %llu offset %llu parent %llu",
933 path->slots[0], root_objectid, owner, offset, parent);
934 goto out;
935 }
936
937 if (ret == -ENOENT && insert) {
938 if (item_size + extra_size >=
939 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
940 ret = -EAGAIN;
941 goto out;
942 }
943
944 if (path->slots[0] + 1 < btrfs_header_nritems(path->nodes[0])) {
945 struct btrfs_key tmp_key;
946
947 btrfs_item_key_to_cpu(path->nodes[0], &tmp_key, path->slots[0] + 1);
948 if (tmp_key.objectid == bytenr &&
949 tmp_key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
950 ret = -EAGAIN;
951 goto out;
952 }
953 goto out_no_entry;
954 }
955
956 if (!path->keep_locks) {
957 btrfs_release_path(path);
958 path->keep_locks = true;
959 goto again;
960 }
961
962 /*
963 * To add new inline back ref, we have to make sure
964 * there is no corresponding back ref item.
965 * For simplicity, we just do not add new inline back
966 * ref if there is any kind of item for this block
967 */
968 if (find_next_key(path, 0, &key) == 0 &&
969 key.objectid == bytenr &&
970 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
971 ret = -EAGAIN;
972 goto out;
973 }
974 }
975out_no_entry:
976 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
977out:
978 if (path->keep_locks) {
979 path->keep_locks = false;
980 btrfs_unlock_up_safe(path, 1);
981 }
982 if (insert)
983 path->search_for_extension = false;
984 return ret;
985}
986
987/*
988 * helper to add new inline back ref
989 */
990static noinline_for_stack
991void setup_inline_extent_backref(struct btrfs_trans_handle *trans,
992 struct btrfs_path *path,
993 struct btrfs_extent_inline_ref *iref,
994 u64 parent, u64 root_objectid,
995 u64 owner, u64 offset, int refs_to_add,
996 struct btrfs_delayed_extent_op *extent_op)
997{
998 struct extent_buffer *leaf;
999 struct btrfs_extent_item *ei;
1000 unsigned long ptr;
1001 unsigned long end;
1002 unsigned long item_offset;
1003 u64 refs;
1004 int size;
1005 int type;
1006
1007 leaf = path->nodes[0];
1008 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1009 item_offset = (unsigned long)iref - (unsigned long)ei;
1010
1011 type = extent_ref_type(parent, owner);
1012 size = btrfs_extent_inline_ref_size(type);
1013
1014 btrfs_extend_item(trans, path, size);
1015
1016 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1017 refs = btrfs_extent_refs(leaf, ei);
1018 refs += refs_to_add;
1019 btrfs_set_extent_refs(leaf, ei, refs);
1020 if (extent_op)
1021 __run_delayed_extent_op(extent_op, leaf, ei);
1022
1023 ptr = (unsigned long)ei + item_offset;
1024 end = (unsigned long)ei + btrfs_item_size(leaf, path->slots[0]);
1025 if (ptr < end - size)
1026 memmove_extent_buffer(leaf, ptr + size, ptr,
1027 end - size - ptr);
1028
1029 iref = (struct btrfs_extent_inline_ref *)ptr;
1030 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1031 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1032 struct btrfs_extent_data_ref *dref;
1033 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1034 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1035 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1036 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1037 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1038 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1039 struct btrfs_shared_data_ref *sref;
1040 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1041 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1042 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1043 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1044 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1045 } else {
1046 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1047 }
1048}
1049
1050static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1051 struct btrfs_path *path,
1052 struct btrfs_extent_inline_ref **ref_ret,
1053 u64 bytenr, u64 num_bytes, u64 parent,
1054 u64 root_objectid, u64 owner, u64 offset)
1055{
1056 int ret;
1057
1058 ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1059 num_bytes, parent, root_objectid,
1060 owner, offset, 0);
1061 if (ret != -ENOENT)
1062 return ret;
1063
1064 btrfs_release_path(path);
1065 *ref_ret = NULL;
1066
1067 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1068 ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1069 root_objectid);
1070 } else {
1071 ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1072 root_objectid, owner, offset);
1073 }
1074 return ret;
1075}
1076
1077/*
1078 * helper to update/remove inline back ref
1079 */
1080static noinline_for_stack int update_inline_extent_backref(
1081 struct btrfs_trans_handle *trans,
1082 struct btrfs_path *path,
1083 struct btrfs_extent_inline_ref *iref,
1084 int refs_to_mod,
1085 struct btrfs_delayed_extent_op *extent_op)
1086{
1087 struct extent_buffer *leaf = path->nodes[0];
1088 struct btrfs_fs_info *fs_info = leaf->fs_info;
1089 struct btrfs_extent_item *ei;
1090 struct btrfs_extent_data_ref *dref = NULL;
1091 struct btrfs_shared_data_ref *sref = NULL;
1092 unsigned long ptr;
1093 unsigned long end;
1094 u32 item_size;
1095 int size;
1096 int type;
1097 u64 refs;
1098
1099 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1100 refs = btrfs_extent_refs(leaf, ei);
1101 if (unlikely(refs_to_mod < 0 && refs + refs_to_mod <= 0)) {
1102 struct btrfs_key key;
1103 u32 extent_size;
1104
1105 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1106 if (key.type == BTRFS_METADATA_ITEM_KEY)
1107 extent_size = fs_info->nodesize;
1108 else
1109 extent_size = key.offset;
1110 btrfs_print_leaf(leaf);
1111 btrfs_err(fs_info,
1112 "invalid refs_to_mod for extent %llu num_bytes %u, has %d expect >= -%llu",
1113 key.objectid, extent_size, refs_to_mod, refs);
1114 return -EUCLEAN;
1115 }
1116 refs += refs_to_mod;
1117 btrfs_set_extent_refs(leaf, ei, refs);
1118 if (extent_op)
1119 __run_delayed_extent_op(extent_op, leaf, ei);
1120
1121 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1122 /*
1123 * Function btrfs_get_extent_inline_ref_type() has already printed
1124 * error messages.
1125 */
1126 if (unlikely(type == BTRFS_REF_TYPE_INVALID))
1127 return -EUCLEAN;
1128
1129 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1130 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1131 refs = btrfs_extent_data_ref_count(leaf, dref);
1132 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1133 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1134 refs = btrfs_shared_data_ref_count(leaf, sref);
1135 } else {
1136 refs = 1;
1137 /*
1138 * For tree blocks we can only drop one ref for it, and tree
1139 * blocks should not have refs > 1.
1140 *
1141 * Furthermore if we're inserting a new inline backref, we
1142 * won't reach this path either. That would be
1143 * setup_inline_extent_backref().
1144 */
1145 if (unlikely(refs_to_mod != -1)) {
1146 struct btrfs_key key;
1147
1148 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1149
1150 btrfs_print_leaf(leaf);
1151 btrfs_err(fs_info,
1152 "invalid refs_to_mod for tree block %llu, has %d expect -1",
1153 key.objectid, refs_to_mod);
1154 return -EUCLEAN;
1155 }
1156 }
1157
1158 if (unlikely(refs_to_mod < 0 && refs < -refs_to_mod)) {
1159 struct btrfs_key key;
1160 u32 extent_size;
1161
1162 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1163 if (key.type == BTRFS_METADATA_ITEM_KEY)
1164 extent_size = fs_info->nodesize;
1165 else
1166 extent_size = key.offset;
1167 btrfs_print_leaf(leaf);
1168 btrfs_err(fs_info,
1169"invalid refs_to_mod for backref entry, iref %lu extent %llu num_bytes %u, has %d expect >= -%llu",
1170 (unsigned long)iref, key.objectid, extent_size,
1171 refs_to_mod, refs);
1172 return -EUCLEAN;
1173 }
1174 refs += refs_to_mod;
1175
1176 if (refs > 0) {
1177 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1178 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1179 else
1180 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1181 } else {
1182 size = btrfs_extent_inline_ref_size(type);
1183 item_size = btrfs_item_size(leaf, path->slots[0]);
1184 ptr = (unsigned long)iref;
1185 end = (unsigned long)ei + item_size;
1186 if (ptr + size < end)
1187 memmove_extent_buffer(leaf, ptr, ptr + size,
1188 end - ptr - size);
1189 item_size -= size;
1190 btrfs_truncate_item(trans, path, item_size, 1);
1191 }
1192 return 0;
1193}
1194
1195static noinline_for_stack
1196int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1197 struct btrfs_path *path,
1198 u64 bytenr, u64 num_bytes, u64 parent,
1199 u64 root_objectid, u64 owner,
1200 u64 offset, int refs_to_add,
1201 struct btrfs_delayed_extent_op *extent_op)
1202{
1203 struct btrfs_extent_inline_ref *iref;
1204 int ret;
1205
1206 ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1207 num_bytes, parent, root_objectid,
1208 owner, offset, 1);
1209 if (ret == 0) {
1210 /*
1211 * We're adding refs to a tree block we already own, this
1212 * should not happen at all.
1213 */
1214 if (unlikely(owner < BTRFS_FIRST_FREE_OBJECTID)) {
1215 btrfs_print_leaf(path->nodes[0]);
1216 btrfs_crit(trans->fs_info,
1217"adding refs to an existing tree ref, bytenr %llu num_bytes %llu root_objectid %llu slot %u",
1218 bytenr, num_bytes, root_objectid, path->slots[0]);
1219 return -EUCLEAN;
1220 }
1221 ret = update_inline_extent_backref(trans, path, iref,
1222 refs_to_add, extent_op);
1223 } else if (ret == -ENOENT) {
1224 setup_inline_extent_backref(trans, path, iref, parent,
1225 root_objectid, owner, offset,
1226 refs_to_add, extent_op);
1227 ret = 0;
1228 }
1229 return ret;
1230}
1231
1232static int remove_extent_backref(struct btrfs_trans_handle *trans,
1233 struct btrfs_root *root,
1234 struct btrfs_path *path,
1235 struct btrfs_extent_inline_ref *iref,
1236 int refs_to_drop, int is_data)
1237{
1238 int ret = 0;
1239
1240 BUG_ON(!is_data && refs_to_drop != 1);
1241 if (iref)
1242 ret = update_inline_extent_backref(trans, path, iref,
1243 -refs_to_drop, NULL);
1244 else if (is_data)
1245 ret = remove_extent_data_ref(trans, root, path, refs_to_drop);
1246 else
1247 ret = btrfs_del_item(trans, root, path);
1248 return ret;
1249}
1250
1251static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1252 u64 *discarded_bytes)
1253{
1254 int j, ret = 0;
1255 u64 bytes_left, end;
1256 u64 aligned_start = ALIGN(start, SECTOR_SIZE);
1257
1258 /* Adjust the range to be aligned to 512B sectors if necessary. */
1259 if (start != aligned_start) {
1260 len -= aligned_start - start;
1261 len = round_down(len, SECTOR_SIZE);
1262 start = aligned_start;
1263 }
1264
1265 *discarded_bytes = 0;
1266
1267 if (!len)
1268 return 0;
1269
1270 end = start + len;
1271 bytes_left = len;
1272
1273 /* Skip any superblocks on this device. */
1274 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1275 u64 sb_start = btrfs_sb_offset(j);
1276 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1277 u64 size = sb_start - start;
1278
1279 if (!in_range(sb_start, start, bytes_left) &&
1280 !in_range(sb_end, start, bytes_left) &&
1281 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1282 continue;
1283
1284 /*
1285 * Superblock spans beginning of range. Adjust start and
1286 * try again.
1287 */
1288 if (sb_start <= start) {
1289 start += sb_end - start;
1290 if (start > end) {
1291 bytes_left = 0;
1292 break;
1293 }
1294 bytes_left = end - start;
1295 continue;
1296 }
1297
1298 if (size) {
1299 ret = blkdev_issue_discard(bdev, start >> SECTOR_SHIFT,
1300 size >> SECTOR_SHIFT,
1301 GFP_NOFS);
1302 if (!ret)
1303 *discarded_bytes += size;
1304 else if (ret != -EOPNOTSUPP)
1305 return ret;
1306 }
1307
1308 start = sb_end;
1309 if (start > end) {
1310 bytes_left = 0;
1311 break;
1312 }
1313 bytes_left = end - start;
1314 }
1315
1316 while (bytes_left) {
1317 u64 bytes_to_discard = min(BTRFS_MAX_DISCARD_CHUNK_SIZE, bytes_left);
1318
1319 ret = blkdev_issue_discard(bdev, start >> SECTOR_SHIFT,
1320 bytes_to_discard >> SECTOR_SHIFT,
1321 GFP_NOFS);
1322
1323 if (ret) {
1324 if (ret != -EOPNOTSUPP)
1325 break;
1326 continue;
1327 }
1328
1329 start += bytes_to_discard;
1330 bytes_left -= bytes_to_discard;
1331 *discarded_bytes += bytes_to_discard;
1332
1333 if (btrfs_trim_interrupted()) {
1334 ret = -ERESTARTSYS;
1335 break;
1336 }
1337 }
1338
1339 return ret;
1340}
1341
1342static int do_discard_extent(struct btrfs_discard_stripe *stripe, u64 *bytes)
1343{
1344 struct btrfs_device *dev = stripe->dev;
1345 struct btrfs_fs_info *fs_info = dev->fs_info;
1346 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1347 u64 phys = stripe->physical;
1348 u64 len = stripe->length;
1349 u64 discarded = 0;
1350 int ret = 0;
1351
1352 /* Zone reset on a zoned filesystem */
1353 if (btrfs_can_zone_reset(dev, phys, len)) {
1354 u64 src_disc;
1355
1356 ret = btrfs_reset_device_zone(dev, phys, len, &discarded);
1357 if (ret)
1358 goto out;
1359
1360 if (!btrfs_dev_replace_is_ongoing(dev_replace) ||
1361 dev != dev_replace->srcdev)
1362 goto out;
1363
1364 src_disc = discarded;
1365
1366 /* Send to replace target as well */
1367 ret = btrfs_reset_device_zone(dev_replace->tgtdev, phys, len,
1368 &discarded);
1369 discarded += src_disc;
1370 } else if (bdev_max_discard_sectors(stripe->dev->bdev)) {
1371 ret = btrfs_issue_discard(dev->bdev, phys, len, &discarded);
1372 } else {
1373 ret = 0;
1374 *bytes = 0;
1375 }
1376
1377out:
1378 *bytes = discarded;
1379 return ret;
1380}
1381
1382int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1383 u64 num_bytes, u64 *actual_bytes)
1384{
1385 int ret = 0;
1386 u64 discarded_bytes = 0;
1387 u64 end = bytenr + num_bytes;
1388 u64 cur = bytenr;
1389
1390 /*
1391 * Avoid races with device replace and make sure the devices in the
1392 * stripes don't go away while we are discarding.
1393 */
1394 btrfs_bio_counter_inc_blocked(fs_info);
1395 while (cur < end) {
1396 struct btrfs_discard_stripe *stripes;
1397 unsigned int num_stripes;
1398 int i;
1399
1400 num_bytes = end - cur;
1401 stripes = btrfs_map_discard(fs_info, cur, &num_bytes, &num_stripes);
1402 if (IS_ERR(stripes)) {
1403 ret = PTR_ERR(stripes);
1404 if (ret == -EOPNOTSUPP)
1405 ret = 0;
1406 break;
1407 }
1408
1409 for (i = 0; i < num_stripes; i++) {
1410 struct btrfs_discard_stripe *stripe = stripes + i;
1411 u64 bytes;
1412
1413 if (!stripe->dev->bdev) {
1414 ASSERT(btrfs_test_opt(fs_info, DEGRADED));
1415 continue;
1416 }
1417
1418 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
1419 &stripe->dev->dev_state))
1420 continue;
1421
1422 ret = do_discard_extent(stripe, &bytes);
1423 if (ret) {
1424 /*
1425 * Keep going if discard is not supported by the
1426 * device.
1427 */
1428 if (ret != -EOPNOTSUPP)
1429 break;
1430 ret = 0;
1431 } else {
1432 discarded_bytes += bytes;
1433 }
1434 }
1435 kfree(stripes);
1436 if (ret)
1437 break;
1438 cur += num_bytes;
1439 }
1440 btrfs_bio_counter_dec(fs_info);
1441 if (actual_bytes)
1442 *actual_bytes = discarded_bytes;
1443 return ret;
1444}
1445
1446/* Can return -ENOMEM */
1447int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1448 struct btrfs_ref *generic_ref)
1449{
1450 struct btrfs_fs_info *fs_info = trans->fs_info;
1451 int ret;
1452
1453 ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
1454 generic_ref->action);
1455 BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
1456 generic_ref->ref_root == BTRFS_TREE_LOG_OBJECTID);
1457
1458 if (generic_ref->type == BTRFS_REF_METADATA)
1459 ret = btrfs_add_delayed_tree_ref(trans, generic_ref, NULL);
1460 else
1461 ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0);
1462
1463 btrfs_ref_tree_mod(fs_info, generic_ref);
1464
1465 return ret;
1466}
1467
1468/*
1469 * Insert backreference for a given extent.
1470 *
1471 * The counterpart is in __btrfs_free_extent(), with examples and more details
1472 * how it works.
1473 *
1474 * @trans: Handle of transaction
1475 *
1476 * @node: The delayed ref node used to get the bytenr/length for
1477 * extent whose references are incremented.
1478 *
1479 * @extent_op Pointer to a structure, holding information necessary when
1480 * updating a tree block's flags
1481 *
1482 */
1483static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1484 const struct btrfs_delayed_ref_node *node,
1485 struct btrfs_delayed_extent_op *extent_op)
1486{
1487 BTRFS_PATH_AUTO_FREE(path);
1488 struct extent_buffer *leaf;
1489 struct btrfs_extent_item *item;
1490 struct btrfs_key key;
1491 u64 bytenr = node->bytenr;
1492 u64 num_bytes = node->num_bytes;
1493 u64 owner = btrfs_delayed_ref_owner(node);
1494 u64 offset = btrfs_delayed_ref_offset(node);
1495 u64 refs;
1496 int refs_to_add = node->ref_mod;
1497 int ret;
1498
1499 path = btrfs_alloc_path();
1500 if (!path)
1501 return -ENOMEM;
1502
1503 /* this will setup the path even if it fails to insert the back ref */
1504 ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
1505 node->parent, node->ref_root, owner,
1506 offset, refs_to_add, extent_op);
1507 if ((ret < 0 && ret != -EAGAIN) || !ret)
1508 return ret;
1509
1510 /*
1511 * Ok we had -EAGAIN which means we didn't have space to insert and
1512 * inline extent ref, so just update the reference count and add a
1513 * normal backref.
1514 */
1515 leaf = path->nodes[0];
1516 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1517 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1518 refs = btrfs_extent_refs(leaf, item);
1519 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
1520 if (extent_op)
1521 __run_delayed_extent_op(extent_op, leaf, item);
1522
1523 btrfs_release_path(path);
1524
1525 /* now insert the actual backref */
1526 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1527 ret = insert_tree_block_ref(trans, path, node, bytenr);
1528 if (ret)
1529 btrfs_abort_transaction(trans, ret);
1530 } else {
1531 ret = insert_extent_data_ref(trans, path, node, bytenr);
1532 if (ret)
1533 btrfs_abort_transaction(trans, ret);
1534 }
1535
1536 return ret;
1537}
1538
1539static void free_head_ref_squota_rsv(struct btrfs_fs_info *fs_info,
1540 const struct btrfs_delayed_ref_head *href)
1541{
1542 u64 root = href->owning_root;
1543
1544 /*
1545 * Don't check must_insert_reserved, as this is called from contexts
1546 * where it has already been unset.
1547 */
1548 if (btrfs_qgroup_mode(fs_info) != BTRFS_QGROUP_MODE_SIMPLE ||
1549 !href->is_data || !btrfs_is_fstree(root))
1550 return;
1551
1552 btrfs_qgroup_free_refroot(fs_info, root, href->reserved_bytes,
1553 BTRFS_QGROUP_RSV_DATA);
1554}
1555
1556static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
1557 struct btrfs_delayed_ref_head *href,
1558 const struct btrfs_delayed_ref_node *node,
1559 struct btrfs_delayed_extent_op *extent_op,
1560 bool insert_reserved)
1561{
1562 int ret = 0;
1563 u64 parent = 0;
1564 u64 flags = 0;
1565
1566 trace_run_delayed_data_ref(trans->fs_info, node);
1567
1568 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
1569 parent = node->parent;
1570
1571 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1572 struct btrfs_key key;
1573 struct btrfs_squota_delta delta = {
1574 .root = href->owning_root,
1575 .num_bytes = node->num_bytes,
1576 .is_data = true,
1577 .is_inc = true,
1578 .generation = trans->transid,
1579 };
1580 u64 owner = btrfs_delayed_ref_owner(node);
1581 u64 offset = btrfs_delayed_ref_offset(node);
1582
1583 if (extent_op)
1584 flags |= extent_op->flags_to_set;
1585
1586 key.objectid = node->bytenr;
1587 key.type = BTRFS_EXTENT_ITEM_KEY;
1588 key.offset = node->num_bytes;
1589
1590 ret = alloc_reserved_file_extent(trans, parent, node->ref_root,
1591 flags, owner, offset, &key,
1592 node->ref_mod,
1593 href->owning_root);
1594 free_head_ref_squota_rsv(trans->fs_info, href);
1595 if (!ret)
1596 ret = btrfs_record_squota_delta(trans->fs_info, &delta);
1597 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1598 ret = __btrfs_inc_extent_ref(trans, node, extent_op);
1599 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1600 ret = __btrfs_free_extent(trans, href, node, extent_op);
1601 } else {
1602 BUG();
1603 }
1604 return ret;
1605}
1606
1607static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
1608 struct extent_buffer *leaf,
1609 struct btrfs_extent_item *ei)
1610{
1611 u64 flags = btrfs_extent_flags(leaf, ei);
1612 if (extent_op->update_flags) {
1613 flags |= extent_op->flags_to_set;
1614 btrfs_set_extent_flags(leaf, ei, flags);
1615 }
1616
1617 if (extent_op->update_key) {
1618 struct btrfs_tree_block_info *bi;
1619 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
1620 bi = (struct btrfs_tree_block_info *)(ei + 1);
1621 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
1622 }
1623}
1624
1625static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
1626 const struct btrfs_delayed_ref_head *head,
1627 struct btrfs_delayed_extent_op *extent_op)
1628{
1629 struct btrfs_fs_info *fs_info = trans->fs_info;
1630 struct btrfs_root *root;
1631 struct btrfs_key key;
1632 BTRFS_PATH_AUTO_FREE(path);
1633 struct btrfs_extent_item *ei;
1634 struct extent_buffer *leaf;
1635 u32 item_size;
1636 int ret;
1637 int metadata = 1;
1638
1639 if (TRANS_ABORTED(trans))
1640 return 0;
1641
1642 if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
1643 metadata = 0;
1644
1645 path = btrfs_alloc_path();
1646 if (!path)
1647 return -ENOMEM;
1648
1649 key.objectid = head->bytenr;
1650
1651 if (metadata) {
1652 key.type = BTRFS_METADATA_ITEM_KEY;
1653 key.offset = head->level;
1654 } else {
1655 key.type = BTRFS_EXTENT_ITEM_KEY;
1656 key.offset = head->num_bytes;
1657 }
1658
1659 root = btrfs_extent_root(fs_info, key.objectid);
1660again:
1661 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1662 if (ret < 0) {
1663 return ret;
1664 } else if (ret > 0) {
1665 if (metadata) {
1666 if (path->slots[0] > 0) {
1667 path->slots[0]--;
1668 btrfs_item_key_to_cpu(path->nodes[0], &key,
1669 path->slots[0]);
1670 if (key.objectid == head->bytenr &&
1671 key.type == BTRFS_EXTENT_ITEM_KEY &&
1672 key.offset == head->num_bytes)
1673 ret = 0;
1674 }
1675 if (ret > 0) {
1676 btrfs_release_path(path);
1677 metadata = 0;
1678
1679 key.objectid = head->bytenr;
1680 key.type = BTRFS_EXTENT_ITEM_KEY;
1681 key.offset = head->num_bytes;
1682 goto again;
1683 }
1684 } else {
1685 ret = -EUCLEAN;
1686 btrfs_err(fs_info,
1687 "missing extent item for extent %llu num_bytes %llu level %d",
1688 head->bytenr, head->num_bytes, head->level);
1689 return ret;
1690 }
1691 }
1692
1693 leaf = path->nodes[0];
1694 item_size = btrfs_item_size(leaf, path->slots[0]);
1695
1696 if (unlikely(item_size < sizeof(*ei))) {
1697 ret = -EUCLEAN;
1698 btrfs_err(fs_info,
1699 "unexpected extent item size, has %u expect >= %zu",
1700 item_size, sizeof(*ei));
1701 btrfs_abort_transaction(trans, ret);
1702 return ret;
1703 }
1704
1705 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1706 __run_delayed_extent_op(extent_op, leaf, ei);
1707
1708 return ret;
1709}
1710
1711static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
1712 struct btrfs_delayed_ref_head *href,
1713 const struct btrfs_delayed_ref_node *node,
1714 struct btrfs_delayed_extent_op *extent_op,
1715 bool insert_reserved)
1716{
1717 int ret = 0;
1718 struct btrfs_fs_info *fs_info = trans->fs_info;
1719 u64 parent = 0;
1720 u64 ref_root = 0;
1721
1722 trace_run_delayed_tree_ref(trans->fs_info, node);
1723
1724 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1725 parent = node->parent;
1726 ref_root = node->ref_root;
1727
1728 if (unlikely(node->ref_mod != 1)) {
1729 btrfs_err(trans->fs_info,
1730 "btree block %llu has %d references rather than 1: action %d ref_root %llu parent %llu",
1731 node->bytenr, node->ref_mod, node->action, ref_root,
1732 parent);
1733 return -EUCLEAN;
1734 }
1735 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1736 struct btrfs_squota_delta delta = {
1737 .root = href->owning_root,
1738 .num_bytes = fs_info->nodesize,
1739 .is_data = false,
1740 .is_inc = true,
1741 .generation = trans->transid,
1742 };
1743
1744 ret = alloc_reserved_tree_block(trans, node, extent_op);
1745 if (!ret)
1746 btrfs_record_squota_delta(fs_info, &delta);
1747 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1748 ret = __btrfs_inc_extent_ref(trans, node, extent_op);
1749 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1750 ret = __btrfs_free_extent(trans, href, node, extent_op);
1751 } else {
1752 BUG();
1753 }
1754 return ret;
1755}
1756
1757/* helper function to actually process a single delayed ref entry */
1758static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
1759 struct btrfs_delayed_ref_head *href,
1760 const struct btrfs_delayed_ref_node *node,
1761 struct btrfs_delayed_extent_op *extent_op,
1762 bool insert_reserved)
1763{
1764 int ret = 0;
1765
1766 if (TRANS_ABORTED(trans)) {
1767 if (insert_reserved) {
1768 btrfs_pin_extent(trans, node->bytenr, node->num_bytes);
1769 free_head_ref_squota_rsv(trans->fs_info, href);
1770 }
1771 return 0;
1772 }
1773
1774 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
1775 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1776 ret = run_delayed_tree_ref(trans, href, node, extent_op,
1777 insert_reserved);
1778 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
1779 node->type == BTRFS_SHARED_DATA_REF_KEY)
1780 ret = run_delayed_data_ref(trans, href, node, extent_op,
1781 insert_reserved);
1782 else if (node->type == BTRFS_EXTENT_OWNER_REF_KEY)
1783 ret = 0;
1784 else
1785 BUG();
1786 if (ret && insert_reserved)
1787 btrfs_pin_extent(trans, node->bytenr, node->num_bytes);
1788 if (ret < 0)
1789 btrfs_err(trans->fs_info,
1790"failed to run delayed ref for logical %llu num_bytes %llu type %u action %u ref_mod %d: %d",
1791 node->bytenr, node->num_bytes, node->type,
1792 node->action, node->ref_mod, ret);
1793 return ret;
1794}
1795
1796static struct btrfs_delayed_extent_op *cleanup_extent_op(
1797 struct btrfs_delayed_ref_head *head)
1798{
1799 struct btrfs_delayed_extent_op *extent_op = head->extent_op;
1800
1801 if (!extent_op)
1802 return NULL;
1803
1804 if (head->must_insert_reserved) {
1805 head->extent_op = NULL;
1806 btrfs_free_delayed_extent_op(extent_op);
1807 return NULL;
1808 }
1809 return extent_op;
1810}
1811
1812static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
1813 struct btrfs_delayed_ref_head *head)
1814{
1815 struct btrfs_delayed_extent_op *extent_op;
1816 int ret;
1817
1818 extent_op = cleanup_extent_op(head);
1819 if (!extent_op)
1820 return 0;
1821 head->extent_op = NULL;
1822 spin_unlock(&head->lock);
1823 ret = run_delayed_extent_op(trans, head, extent_op);
1824 btrfs_free_delayed_extent_op(extent_op);
1825 return ret ? ret : 1;
1826}
1827
1828u64 btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
1829 struct btrfs_delayed_ref_root *delayed_refs,
1830 struct btrfs_delayed_ref_head *head)
1831{
1832 u64 ret = 0;
1833
1834 /*
1835 * We had csum deletions accounted for in our delayed refs rsv, we need
1836 * to drop the csum leaves for this update from our delayed_refs_rsv.
1837 */
1838 if (head->total_ref_mod < 0 && head->is_data) {
1839 int nr_csums;
1840
1841 spin_lock(&delayed_refs->lock);
1842 delayed_refs->pending_csums -= head->num_bytes;
1843 spin_unlock(&delayed_refs->lock);
1844 nr_csums = btrfs_csum_bytes_to_leaves(fs_info, head->num_bytes);
1845
1846 btrfs_delayed_refs_rsv_release(fs_info, 0, nr_csums);
1847
1848 ret = btrfs_calc_delayed_ref_csum_bytes(fs_info, nr_csums);
1849 }
1850 /* must_insert_reserved can be set only if we didn't run the head ref. */
1851 if (head->must_insert_reserved)
1852 free_head_ref_squota_rsv(fs_info, head);
1853
1854 return ret;
1855}
1856
1857static int cleanup_ref_head(struct btrfs_trans_handle *trans,
1858 struct btrfs_delayed_ref_head *head,
1859 u64 *bytes_released)
1860{
1861
1862 struct btrfs_fs_info *fs_info = trans->fs_info;
1863 struct btrfs_delayed_ref_root *delayed_refs;
1864 int ret;
1865
1866 delayed_refs = &trans->transaction->delayed_refs;
1867
1868 ret = run_and_cleanup_extent_op(trans, head);
1869 if (ret < 0) {
1870 btrfs_unselect_ref_head(delayed_refs, head);
1871 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
1872 return ret;
1873 } else if (ret) {
1874 return ret;
1875 }
1876
1877 /*
1878 * Need to drop our head ref lock and re-acquire the delayed ref lock
1879 * and then re-check to make sure nobody got added.
1880 */
1881 spin_unlock(&head->lock);
1882 spin_lock(&delayed_refs->lock);
1883 spin_lock(&head->lock);
1884 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
1885 spin_unlock(&head->lock);
1886 spin_unlock(&delayed_refs->lock);
1887 return 1;
1888 }
1889 btrfs_delete_ref_head(fs_info, delayed_refs, head);
1890 spin_unlock(&head->lock);
1891 spin_unlock(&delayed_refs->lock);
1892
1893 if (head->must_insert_reserved) {
1894 btrfs_pin_extent(trans, head->bytenr, head->num_bytes);
1895 if (head->is_data) {
1896 struct btrfs_root *csum_root;
1897
1898 csum_root = btrfs_csum_root(fs_info, head->bytenr);
1899 ret = btrfs_del_csums(trans, csum_root, head->bytenr,
1900 head->num_bytes);
1901 }
1902 }
1903
1904 *bytes_released += btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
1905
1906 trace_run_delayed_ref_head(fs_info, head, 0);
1907 btrfs_delayed_ref_unlock(head);
1908 btrfs_put_delayed_ref_head(head);
1909 return ret;
1910}
1911
1912static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
1913 struct btrfs_delayed_ref_head *locked_ref,
1914 u64 *bytes_released)
1915{
1916 struct btrfs_fs_info *fs_info = trans->fs_info;
1917 struct btrfs_delayed_ref_root *delayed_refs;
1918 struct btrfs_delayed_extent_op *extent_op;
1919 struct btrfs_delayed_ref_node *ref;
1920 bool must_insert_reserved;
1921 int ret;
1922
1923 delayed_refs = &trans->transaction->delayed_refs;
1924
1925 lockdep_assert_held(&locked_ref->mutex);
1926 lockdep_assert_held(&locked_ref->lock);
1927
1928 while ((ref = btrfs_select_delayed_ref(locked_ref))) {
1929 if (ref->seq &&
1930 btrfs_check_delayed_seq(fs_info, ref->seq)) {
1931 spin_unlock(&locked_ref->lock);
1932 btrfs_unselect_ref_head(delayed_refs, locked_ref);
1933 return -EAGAIN;
1934 }
1935
1936 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
1937 RB_CLEAR_NODE(&ref->ref_node);
1938 if (!list_empty(&ref->add_list))
1939 list_del(&ref->add_list);
1940 /*
1941 * When we play the delayed ref, also correct the ref_mod on
1942 * head
1943 */
1944 switch (ref->action) {
1945 case BTRFS_ADD_DELAYED_REF:
1946 case BTRFS_ADD_DELAYED_EXTENT:
1947 locked_ref->ref_mod -= ref->ref_mod;
1948 break;
1949 case BTRFS_DROP_DELAYED_REF:
1950 locked_ref->ref_mod += ref->ref_mod;
1951 break;
1952 default:
1953 WARN_ON(1);
1954 }
1955
1956 /*
1957 * Record the must_insert_reserved flag before we drop the
1958 * spin lock.
1959 */
1960 must_insert_reserved = locked_ref->must_insert_reserved;
1961 /*
1962 * Unsetting this on the head ref relinquishes ownership of
1963 * the rsv_bytes, so it is critical that every possible code
1964 * path from here forward frees all reserves including qgroup
1965 * reserve.
1966 */
1967 locked_ref->must_insert_reserved = false;
1968
1969 extent_op = locked_ref->extent_op;
1970 locked_ref->extent_op = NULL;
1971 spin_unlock(&locked_ref->lock);
1972
1973 ret = run_one_delayed_ref(trans, locked_ref, ref, extent_op,
1974 must_insert_reserved);
1975 btrfs_delayed_refs_rsv_release(fs_info, 1, 0);
1976 *bytes_released += btrfs_calc_delayed_ref_bytes(fs_info, 1);
1977
1978 btrfs_free_delayed_extent_op(extent_op);
1979 if (ret) {
1980 btrfs_unselect_ref_head(delayed_refs, locked_ref);
1981 btrfs_put_delayed_ref(ref);
1982 return ret;
1983 }
1984
1985 btrfs_put_delayed_ref(ref);
1986 cond_resched();
1987
1988 spin_lock(&locked_ref->lock);
1989 btrfs_merge_delayed_refs(fs_info, delayed_refs, locked_ref);
1990 }
1991
1992 return 0;
1993}
1994
1995/*
1996 * Returns 0 on success or if called with an already aborted transaction.
1997 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
1998 */
1999static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2000 u64 min_bytes)
2001{
2002 struct btrfs_fs_info *fs_info = trans->fs_info;
2003 struct btrfs_delayed_ref_root *delayed_refs;
2004 struct btrfs_delayed_ref_head *locked_ref = NULL;
2005 int ret;
2006 unsigned long count = 0;
2007 unsigned long max_count = 0;
2008 u64 bytes_processed = 0;
2009
2010 delayed_refs = &trans->transaction->delayed_refs;
2011 if (min_bytes == 0) {
2012 /*
2013 * We may be subject to a harmless race if some task is
2014 * concurrently adding or removing a delayed ref, so silence
2015 * KCSAN and similar tools.
2016 */
2017 max_count = data_race(delayed_refs->num_heads_ready);
2018 min_bytes = U64_MAX;
2019 }
2020
2021 do {
2022 if (!locked_ref) {
2023 locked_ref = btrfs_select_ref_head(fs_info, delayed_refs);
2024 if (IS_ERR_OR_NULL(locked_ref)) {
2025 if (PTR_ERR(locked_ref) == -EAGAIN) {
2026 continue;
2027 } else {
2028 break;
2029 }
2030 }
2031 count++;
2032 }
2033 /*
2034 * We need to try and merge add/drops of the same ref since we
2035 * can run into issues with relocate dropping the implicit ref
2036 * and then it being added back again before the drop can
2037 * finish. If we merged anything we need to re-loop so we can
2038 * get a good ref.
2039 * Or we can get node references of the same type that weren't
2040 * merged when created due to bumps in the tree mod seq, and
2041 * we need to merge them to prevent adding an inline extent
2042 * backref before dropping it (triggering a BUG_ON at
2043 * insert_inline_extent_backref()).
2044 */
2045 spin_lock(&locked_ref->lock);
2046 btrfs_merge_delayed_refs(fs_info, delayed_refs, locked_ref);
2047
2048 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref, &bytes_processed);
2049 if (ret < 0 && ret != -EAGAIN) {
2050 /*
2051 * Error, btrfs_run_delayed_refs_for_head already
2052 * unlocked everything so just bail out
2053 */
2054 return ret;
2055 } else if (!ret) {
2056 /*
2057 * Success, perform the usual cleanup of a processed
2058 * head
2059 */
2060 ret = cleanup_ref_head(trans, locked_ref, &bytes_processed);
2061 if (ret > 0 ) {
2062 /* We dropped our lock, we need to loop. */
2063 ret = 0;
2064 continue;
2065 } else if (ret) {
2066 return ret;
2067 }
2068 }
2069
2070 /*
2071 * Either success case or btrfs_run_delayed_refs_for_head
2072 * returned -EAGAIN, meaning we need to select another head
2073 */
2074
2075 locked_ref = NULL;
2076 cond_resched();
2077 } while ((min_bytes != U64_MAX && bytes_processed < min_bytes) ||
2078 (max_count > 0 && count < max_count) ||
2079 locked_ref);
2080
2081 return 0;
2082}
2083
2084#ifdef SCRAMBLE_DELAYED_REFS
2085/*
2086 * Normally delayed refs get processed in ascending bytenr order. This
2087 * correlates in most cases to the order added. To expose dependencies on this
2088 * order, we start to process the tree in the middle instead of the beginning
2089 */
2090static u64 find_middle(struct rb_root *root)
2091{
2092 struct rb_node *n = root->rb_node;
2093 struct btrfs_delayed_ref_node *entry;
2094 int alt = 1;
2095 u64 middle;
2096 u64 first = 0, last = 0;
2097
2098 n = rb_first(root);
2099 if (n) {
2100 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2101 first = entry->bytenr;
2102 }
2103 n = rb_last(root);
2104 if (n) {
2105 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2106 last = entry->bytenr;
2107 }
2108 n = root->rb_node;
2109
2110 while (n) {
2111 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2112 WARN_ON(!entry->in_tree);
2113
2114 middle = entry->bytenr;
2115
2116 if (alt)
2117 n = n->rb_left;
2118 else
2119 n = n->rb_right;
2120
2121 alt = 1 - alt;
2122 }
2123 return middle;
2124}
2125#endif
2126
2127/*
2128 * Start processing the delayed reference count updates and extent insertions
2129 * we have queued up so far.
2130 *
2131 * @trans: Transaction handle.
2132 * @min_bytes: How many bytes of delayed references to process. After this
2133 * many bytes we stop processing delayed references if there are
2134 * any more. If 0 it means to run all existing delayed references,
2135 * but not new ones added after running all existing ones.
2136 * Use (u64)-1 (U64_MAX) to run all existing delayed references
2137 * plus any new ones that are added.
2138 *
2139 * Returns 0 on success or if called with an aborted transaction
2140 * Returns <0 on error and aborts the transaction
2141 */
2142int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans, u64 min_bytes)
2143{
2144 struct btrfs_fs_info *fs_info = trans->fs_info;
2145 struct btrfs_delayed_ref_root *delayed_refs;
2146 int ret;
2147
2148 /* We'll clean this up in btrfs_cleanup_transaction */
2149 if (TRANS_ABORTED(trans))
2150 return 0;
2151
2152 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2153 return 0;
2154
2155 delayed_refs = &trans->transaction->delayed_refs;
2156again:
2157#ifdef SCRAMBLE_DELAYED_REFS
2158 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2159#endif
2160 ret = __btrfs_run_delayed_refs(trans, min_bytes);
2161 if (unlikely(ret < 0)) {
2162 btrfs_abort_transaction(trans, ret);
2163 return ret;
2164 }
2165
2166 if (min_bytes == U64_MAX) {
2167 btrfs_create_pending_block_groups(trans);
2168
2169 spin_lock(&delayed_refs->lock);
2170 if (xa_empty(&delayed_refs->head_refs)) {
2171 spin_unlock(&delayed_refs->lock);
2172 return 0;
2173 }
2174 spin_unlock(&delayed_refs->lock);
2175
2176 cond_resched();
2177 goto again;
2178 }
2179
2180 return 0;
2181}
2182
2183int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2184 struct extent_buffer *eb, u64 flags)
2185{
2186 struct btrfs_delayed_extent_op *extent_op;
2187 int ret;
2188
2189 extent_op = btrfs_alloc_delayed_extent_op();
2190 if (!extent_op)
2191 return -ENOMEM;
2192
2193 extent_op->flags_to_set = flags;
2194 extent_op->update_flags = true;
2195 extent_op->update_key = false;
2196
2197 ret = btrfs_add_delayed_extent_op(trans, eb->start, eb->len,
2198 btrfs_header_level(eb), extent_op);
2199 if (ret)
2200 btrfs_free_delayed_extent_op(extent_op);
2201 return ret;
2202}
2203
2204static noinline int check_delayed_ref(struct btrfs_inode *inode,
2205 struct btrfs_path *path,
2206 u64 offset, u64 bytenr)
2207{
2208 struct btrfs_root *root = inode->root;
2209 struct btrfs_delayed_ref_head *head;
2210 struct btrfs_delayed_ref_node *ref;
2211 struct btrfs_delayed_ref_root *delayed_refs;
2212 struct btrfs_transaction *cur_trans;
2213 struct rb_node *node;
2214 int ret = 0;
2215
2216 spin_lock(&root->fs_info->trans_lock);
2217 cur_trans = root->fs_info->running_transaction;
2218 if (cur_trans)
2219 refcount_inc(&cur_trans->use_count);
2220 spin_unlock(&root->fs_info->trans_lock);
2221 if (!cur_trans)
2222 return 0;
2223
2224 delayed_refs = &cur_trans->delayed_refs;
2225 spin_lock(&delayed_refs->lock);
2226 head = btrfs_find_delayed_ref_head(root->fs_info, delayed_refs, bytenr);
2227 if (!head) {
2228 spin_unlock(&delayed_refs->lock);
2229 btrfs_put_transaction(cur_trans);
2230 return 0;
2231 }
2232
2233 if (!mutex_trylock(&head->mutex)) {
2234 if (path->nowait) {
2235 spin_unlock(&delayed_refs->lock);
2236 btrfs_put_transaction(cur_trans);
2237 return -EAGAIN;
2238 }
2239
2240 refcount_inc(&head->refs);
2241 spin_unlock(&delayed_refs->lock);
2242
2243 btrfs_release_path(path);
2244
2245 /*
2246 * Mutex was contended, block until it's released and let
2247 * caller try again
2248 */
2249 mutex_lock(&head->mutex);
2250 mutex_unlock(&head->mutex);
2251 btrfs_put_delayed_ref_head(head);
2252 btrfs_put_transaction(cur_trans);
2253 return -EAGAIN;
2254 }
2255 spin_unlock(&delayed_refs->lock);
2256
2257 spin_lock(&head->lock);
2258 /*
2259 * XXX: We should replace this with a proper search function in the
2260 * future.
2261 */
2262 for (node = rb_first_cached(&head->ref_tree); node;
2263 node = rb_next(node)) {
2264 u64 ref_owner;
2265 u64 ref_offset;
2266
2267 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
2268 /* If it's a shared ref we know a cross reference exists */
2269 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
2270 ret = 1;
2271 break;
2272 }
2273
2274 ref_owner = btrfs_delayed_ref_owner(ref);
2275 ref_offset = btrfs_delayed_ref_offset(ref);
2276
2277 /*
2278 * If our ref doesn't match the one we're currently looking at
2279 * then we have a cross reference.
2280 */
2281 if (ref->ref_root != btrfs_root_id(root) ||
2282 ref_owner != btrfs_ino(inode) || ref_offset != offset) {
2283 ret = 1;
2284 break;
2285 }
2286 }
2287 spin_unlock(&head->lock);
2288 mutex_unlock(&head->mutex);
2289 btrfs_put_transaction(cur_trans);
2290 return ret;
2291}
2292
2293/*
2294 * Check if there are references for a data extent other than the one belonging
2295 * to the given inode and offset.
2296 *
2297 * @inode: The only inode we expect to find associated with the data extent.
2298 * @path: A path to use for searching the extent tree.
2299 * @offset: The only offset we expect to find associated with the data extent.
2300 * @bytenr: The logical address of the data extent.
2301 *
2302 * When the extent does not have any other references other than the one we
2303 * expect to find, we always return a value of 0 with the path having a locked
2304 * leaf that contains the extent's extent item - this is necessary to ensure
2305 * we don't race with a task running delayed references, and our caller must
2306 * have such a path when calling check_delayed_ref() - it must lock a delayed
2307 * ref head while holding the leaf locked. In case the extent item is not found
2308 * in the extent tree, we return -ENOENT with the path having the leaf (locked)
2309 * where the extent item should be, in order to prevent races with another task
2310 * running delayed references, so that we don't miss any reference when calling
2311 * check_delayed_ref().
2312 *
2313 * Note: this may return false positives, and this is because we want to be
2314 * quick here as we're called in write paths (when flushing delalloc and
2315 * in the direct IO write path). For example we can have an extent with
2316 * a single reference but that reference is not inlined, or we may have
2317 * many references in the extent tree but we also have delayed references
2318 * that cancel all the reference except the one for our inode and offset,
2319 * but it would be expensive to do such checks and complex due to all
2320 * locking to avoid races between the checks and flushing delayed refs,
2321 * plus non-inline references may be located on leaves other than the one
2322 * that contains the extent item in the extent tree. The important thing
2323 * here is to not return false negatives and that the false positives are
2324 * not very common.
2325 *
2326 * Returns: 0 if there are no cross references and with the path having a locked
2327 * leaf from the extent tree that contains the extent's extent item.
2328 *
2329 * 1 if there are cross references (false positives can happen).
2330 *
2331 * < 0 in case of an error. In case of -ENOENT the leaf in the extent
2332 * tree where the extent item should be located at is read locked and
2333 * accessible in the given path.
2334 */
2335static noinline int check_committed_ref(struct btrfs_inode *inode,
2336 struct btrfs_path *path,
2337 u64 offset, u64 bytenr)
2338{
2339 struct btrfs_root *root = inode->root;
2340 struct btrfs_fs_info *fs_info = root->fs_info;
2341 struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
2342 struct extent_buffer *leaf;
2343 struct btrfs_extent_data_ref *ref;
2344 struct btrfs_extent_inline_ref *iref;
2345 struct btrfs_extent_item *ei;
2346 struct btrfs_key key;
2347 u32 item_size;
2348 u32 expected_size;
2349 int type;
2350 int ret;
2351
2352 key.objectid = bytenr;
2353 key.type = BTRFS_EXTENT_ITEM_KEY;
2354 key.offset = (u64)-1;
2355
2356 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2357 if (ret < 0)
2358 return ret;
2359 if (unlikely(ret == 0)) {
2360 /*
2361 * Key with offset -1 found, there would have to exist an extent
2362 * item with such offset, but this is out of the valid range.
2363 */
2364 return -EUCLEAN;
2365 }
2366
2367 if (path->slots[0] == 0)
2368 return -ENOENT;
2369
2370 path->slots[0]--;
2371 leaf = path->nodes[0];
2372 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2373
2374 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2375 return -ENOENT;
2376
2377 item_size = btrfs_item_size(leaf, path->slots[0]);
2378 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2379 expected_size = sizeof(*ei) + btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY);
2380
2381 /* No inline refs; we need to bail before checking for owner ref. */
2382 if (item_size == sizeof(*ei))
2383 return 1;
2384
2385 /* Check for an owner ref; skip over it to the real inline refs. */
2386 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2387 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
2388 if (btrfs_fs_incompat(fs_info, SIMPLE_QUOTA) && type == BTRFS_EXTENT_OWNER_REF_KEY) {
2389 expected_size += btrfs_extent_inline_ref_size(BTRFS_EXTENT_OWNER_REF_KEY);
2390 iref = (struct btrfs_extent_inline_ref *)(iref + 1);
2391 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
2392 }
2393
2394 /* If extent item has more than 1 inline ref then it's shared */
2395 if (item_size != expected_size)
2396 return 1;
2397
2398 /* If this extent has SHARED_DATA_REF then it's shared */
2399 if (type != BTRFS_EXTENT_DATA_REF_KEY)
2400 return 1;
2401
2402 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2403 if (btrfs_extent_refs(leaf, ei) !=
2404 btrfs_extent_data_ref_count(leaf, ref) ||
2405 btrfs_extent_data_ref_root(leaf, ref) != btrfs_root_id(root) ||
2406 btrfs_extent_data_ref_objectid(leaf, ref) != btrfs_ino(inode) ||
2407 btrfs_extent_data_ref_offset(leaf, ref) != offset)
2408 return 1;
2409
2410 return 0;
2411}
2412
2413int btrfs_cross_ref_exist(struct btrfs_inode *inode, u64 offset,
2414 u64 bytenr, struct btrfs_path *path)
2415{
2416 int ret;
2417
2418 do {
2419 ret = check_committed_ref(inode, path, offset, bytenr);
2420 if (ret && ret != -ENOENT)
2421 goto out;
2422
2423 /*
2424 * The path must have a locked leaf from the extent tree where
2425 * the extent item for our extent is located, in case it exists,
2426 * or where it should be located in case it doesn't exist yet
2427 * because it's new and its delayed ref was not yet flushed.
2428 * We need to lock the delayed ref head at check_delayed_ref(),
2429 * if one exists, while holding the leaf locked in order to not
2430 * race with delayed ref flushing, missing references and
2431 * incorrectly reporting that the extent is not shared.
2432 */
2433 if (IS_ENABLED(CONFIG_BTRFS_ASSERT)) {
2434 struct extent_buffer *leaf = path->nodes[0];
2435
2436 ASSERT(leaf != NULL);
2437 btrfs_assert_tree_read_locked(leaf);
2438
2439 if (ret != -ENOENT) {
2440 struct btrfs_key key;
2441
2442 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2443 ASSERT(key.objectid == bytenr);
2444 ASSERT(key.type == BTRFS_EXTENT_ITEM_KEY);
2445 }
2446 }
2447
2448 ret = check_delayed_ref(inode, path, offset, bytenr);
2449 } while (ret == -EAGAIN && !path->nowait);
2450
2451out:
2452 btrfs_release_path(path);
2453 if (btrfs_is_data_reloc_root(inode->root))
2454 WARN_ON(ret > 0);
2455 return ret;
2456}
2457
2458static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2459 struct btrfs_root *root,
2460 struct extent_buffer *buf,
2461 bool full_backref, bool inc)
2462{
2463 struct btrfs_fs_info *fs_info = root->fs_info;
2464 u64 parent;
2465 u64 ref_root;
2466 u32 nritems;
2467 struct btrfs_key key;
2468 struct btrfs_file_extent_item *fi;
2469 bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC);
2470 int i;
2471 int action;
2472 int level;
2473 int ret = 0;
2474
2475 if (btrfs_is_testing(fs_info))
2476 return 0;
2477
2478 ref_root = btrfs_header_owner(buf);
2479 nritems = btrfs_header_nritems(buf);
2480 level = btrfs_header_level(buf);
2481
2482 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state) && level == 0)
2483 return 0;
2484
2485 if (full_backref)
2486 parent = buf->start;
2487 else
2488 parent = 0;
2489 if (inc)
2490 action = BTRFS_ADD_DELAYED_REF;
2491 else
2492 action = BTRFS_DROP_DELAYED_REF;
2493
2494 for (i = 0; i < nritems; i++) {
2495 struct btrfs_ref ref = {
2496 .action = action,
2497 .parent = parent,
2498 .ref_root = ref_root,
2499 };
2500
2501 if (level == 0) {
2502 btrfs_item_key_to_cpu(buf, &key, i);
2503 if (key.type != BTRFS_EXTENT_DATA_KEY)
2504 continue;
2505 fi = btrfs_item_ptr(buf, i,
2506 struct btrfs_file_extent_item);
2507 if (btrfs_file_extent_type(buf, fi) ==
2508 BTRFS_FILE_EXTENT_INLINE)
2509 continue;
2510 ref.bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2511 if (ref.bytenr == 0)
2512 continue;
2513
2514 ref.num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2515 ref.owning_root = ref_root;
2516
2517 key.offset -= btrfs_file_extent_offset(buf, fi);
2518 btrfs_init_data_ref(&ref, key.objectid, key.offset,
2519 btrfs_root_id(root), for_reloc);
2520 if (inc)
2521 ret = btrfs_inc_extent_ref(trans, &ref);
2522 else
2523 ret = btrfs_free_extent(trans, &ref);
2524 if (ret)
2525 goto fail;
2526 } else {
2527 /* We don't know the owning_root, leave as 0. */
2528 ref.bytenr = btrfs_node_blockptr(buf, i);
2529 ref.num_bytes = fs_info->nodesize;
2530
2531 btrfs_init_tree_ref(&ref, level - 1,
2532 btrfs_root_id(root), for_reloc);
2533 if (inc)
2534 ret = btrfs_inc_extent_ref(trans, &ref);
2535 else
2536 ret = btrfs_free_extent(trans, &ref);
2537 if (ret)
2538 goto fail;
2539 }
2540 }
2541 return 0;
2542fail:
2543 return ret;
2544}
2545
2546int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2547 struct extent_buffer *buf, bool full_backref)
2548{
2549 return __btrfs_mod_ref(trans, root, buf, full_backref, true);
2550}
2551
2552int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2553 struct extent_buffer *buf, bool full_backref)
2554{
2555 return __btrfs_mod_ref(trans, root, buf, full_backref, false);
2556}
2557
2558static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
2559{
2560 struct btrfs_fs_info *fs_info = root->fs_info;
2561 u64 flags;
2562 u64 ret;
2563
2564 if (data)
2565 flags = BTRFS_BLOCK_GROUP_DATA;
2566 else if (root == fs_info->chunk_root)
2567 flags = BTRFS_BLOCK_GROUP_SYSTEM;
2568 else
2569 flags = BTRFS_BLOCK_GROUP_METADATA;
2570
2571 ret = btrfs_get_alloc_profile(fs_info, flags);
2572 return ret;
2573}
2574
2575static u64 first_logical_byte(struct btrfs_fs_info *fs_info)
2576{
2577 struct rb_node *leftmost;
2578 u64 bytenr = 0;
2579
2580 read_lock(&fs_info->block_group_cache_lock);
2581 /* Get the block group with the lowest logical start address. */
2582 leftmost = rb_first_cached(&fs_info->block_group_cache_tree);
2583 if (leftmost) {
2584 struct btrfs_block_group *bg;
2585
2586 bg = rb_entry(leftmost, struct btrfs_block_group, cache_node);
2587 bytenr = bg->start;
2588 }
2589 read_unlock(&fs_info->block_group_cache_lock);
2590
2591 return bytenr;
2592}
2593
2594static int pin_down_extent(struct btrfs_trans_handle *trans,
2595 struct btrfs_block_group *bg,
2596 u64 bytenr, u64 num_bytes, bool reserved)
2597{
2598 struct btrfs_space_info *space_info = bg->space_info;
2599 const u64 reserved_bytes = (reserved ? num_bytes : 0);
2600
2601 spin_lock(&space_info->lock);
2602 spin_lock(&bg->lock);
2603 bg->pinned += num_bytes;
2604 bg->reserved -= reserved_bytes;
2605 spin_unlock(&bg->lock);
2606 space_info->bytes_reserved -= reserved_bytes;
2607 btrfs_space_info_update_bytes_pinned(space_info, num_bytes);
2608 spin_unlock(&space_info->lock);
2609
2610 btrfs_set_extent_bit(&trans->transaction->pinned_extents, bytenr,
2611 bytenr + num_bytes - 1, EXTENT_DIRTY, NULL);
2612 return 0;
2613}
2614
2615int btrfs_pin_extent(struct btrfs_trans_handle *trans, u64 bytenr, u64 num_bytes)
2616{
2617 struct btrfs_block_group *cache;
2618
2619 cache = btrfs_lookup_block_group(trans->fs_info, bytenr);
2620 BUG_ON(!cache); /* Logic error */
2621
2622 pin_down_extent(trans, cache, bytenr, num_bytes, true);
2623
2624 btrfs_put_block_group(cache);
2625 return 0;
2626}
2627
2628int btrfs_pin_extent_for_log_replay(struct btrfs_trans_handle *trans,
2629 const struct extent_buffer *eb)
2630{
2631 struct btrfs_block_group *cache;
2632 int ret;
2633
2634 cache = btrfs_lookup_block_group(trans->fs_info, eb->start);
2635 if (!cache)
2636 return -EINVAL;
2637
2638 /*
2639 * Fully cache the free space first so that our pin removes the free space
2640 * from the cache.
2641 */
2642 ret = btrfs_cache_block_group(cache, true);
2643 if (ret)
2644 goto out;
2645
2646 pin_down_extent(trans, cache, eb->start, eb->len, false);
2647
2648 /* remove us from the free space cache (if we're there at all) */
2649 ret = btrfs_remove_free_space(cache, eb->start, eb->len);
2650out:
2651 btrfs_put_block_group(cache);
2652 return ret;
2653}
2654
2655static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
2656 u64 start, u64 num_bytes)
2657{
2658 int ret;
2659 struct btrfs_block_group *block_group;
2660
2661 block_group = btrfs_lookup_block_group(fs_info, start);
2662 if (!block_group)
2663 return -EINVAL;
2664
2665 ret = btrfs_cache_block_group(block_group, true);
2666 if (ret)
2667 goto out;
2668
2669 ret = btrfs_remove_free_space(block_group, start, num_bytes);
2670out:
2671 btrfs_put_block_group(block_group);
2672 return ret;
2673}
2674
2675int btrfs_exclude_logged_extents(struct extent_buffer *eb)
2676{
2677 struct btrfs_fs_info *fs_info = eb->fs_info;
2678 struct btrfs_file_extent_item *item;
2679 struct btrfs_key key;
2680 int found_type;
2681 int i;
2682 int ret = 0;
2683
2684 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
2685 return 0;
2686
2687 for (i = 0; i < btrfs_header_nritems(eb); i++) {
2688 btrfs_item_key_to_cpu(eb, &key, i);
2689 if (key.type != BTRFS_EXTENT_DATA_KEY)
2690 continue;
2691 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
2692 found_type = btrfs_file_extent_type(eb, item);
2693 if (found_type == BTRFS_FILE_EXTENT_INLINE)
2694 continue;
2695 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
2696 continue;
2697 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
2698 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
2699 ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
2700 if (ret)
2701 break;
2702 }
2703
2704 return ret;
2705}
2706
2707static void
2708btrfs_inc_block_group_reservations(struct btrfs_block_group *bg)
2709{
2710 atomic_inc(&bg->reservations);
2711}
2712
2713/*
2714 * Returns the free cluster for the given space info and sets empty_cluster to
2715 * what it should be based on the mount options.
2716 */
2717static struct btrfs_free_cluster *
2718fetch_cluster_info(struct btrfs_fs_info *fs_info,
2719 struct btrfs_space_info *space_info, u64 *empty_cluster)
2720{
2721 struct btrfs_free_cluster *ret = NULL;
2722
2723 *empty_cluster = 0;
2724 if (btrfs_mixed_space_info(space_info))
2725 return ret;
2726
2727 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
2728 ret = &fs_info->meta_alloc_cluster;
2729 if (btrfs_test_opt(fs_info, SSD))
2730 *empty_cluster = SZ_2M;
2731 else
2732 *empty_cluster = SZ_64K;
2733 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
2734 btrfs_test_opt(fs_info, SSD_SPREAD)) {
2735 *empty_cluster = SZ_2M;
2736 ret = &fs_info->data_alloc_cluster;
2737 }
2738
2739 return ret;
2740}
2741
2742static int unpin_extent_range(struct btrfs_fs_info *fs_info,
2743 u64 start, u64 end,
2744 const bool return_free_space)
2745{
2746 struct btrfs_block_group *cache = NULL;
2747 struct btrfs_space_info *space_info;
2748 struct btrfs_free_cluster *cluster = NULL;
2749 u64 total_unpinned = 0;
2750 u64 empty_cluster = 0;
2751
2752 while (start <= end) {
2753 u64 len;
2754 bool readonly;
2755
2756 if (!cache ||
2757 start >= cache->start + cache->length) {
2758 if (cache)
2759 btrfs_put_block_group(cache);
2760 total_unpinned = 0;
2761 cache = btrfs_lookup_block_group(fs_info, start);
2762 if (unlikely(cache == NULL)) {
2763 /* Logic error, something removed the block group. */
2764 return -EUCLEAN;
2765 }
2766
2767 cluster = fetch_cluster_info(fs_info,
2768 cache->space_info,
2769 &empty_cluster);
2770 empty_cluster <<= 1;
2771 }
2772
2773 len = cache->start + cache->length - start;
2774 len = min(len, end + 1 - start);
2775
2776 if (return_free_space)
2777 btrfs_add_free_space(cache, start, len);
2778
2779 start += len;
2780 total_unpinned += len;
2781 space_info = cache->space_info;
2782
2783 /*
2784 * If this space cluster has been marked as fragmented and we've
2785 * unpinned enough in this block group to potentially allow a
2786 * cluster to be created inside of it go ahead and clear the
2787 * fragmented check.
2788 */
2789 if (cluster && cluster->fragmented &&
2790 total_unpinned > empty_cluster) {
2791 spin_lock(&cluster->lock);
2792 cluster->fragmented = 0;
2793 spin_unlock(&cluster->lock);
2794 }
2795
2796 spin_lock(&space_info->lock);
2797 spin_lock(&cache->lock);
2798 readonly = cache->ro;
2799 cache->pinned -= len;
2800 spin_unlock(&cache->lock);
2801
2802 btrfs_space_info_update_bytes_pinned(space_info, -len);
2803 space_info->max_extent_size = 0;
2804
2805 if (readonly) {
2806 space_info->bytes_readonly += len;
2807 } else if (btrfs_is_zoned(fs_info)) {
2808 /* Need reset before reusing in a zoned block group */
2809 btrfs_space_info_update_bytes_zone_unusable(space_info, len);
2810 } else if (return_free_space) {
2811 btrfs_return_free_space(space_info, len);
2812 }
2813 spin_unlock(&space_info->lock);
2814 }
2815
2816 if (cache)
2817 btrfs_put_block_group(cache);
2818
2819 return 0;
2820}
2821
2822int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
2823{
2824 struct btrfs_fs_info *fs_info = trans->fs_info;
2825 struct btrfs_block_group *block_group, *tmp;
2826 struct list_head *deleted_bgs;
2827 struct extent_io_tree *unpin = &trans->transaction->pinned_extents;
2828 struct extent_state *cached_state = NULL;
2829 u64 start;
2830 u64 end;
2831 int unpin_error = 0;
2832 int ret;
2833
2834 mutex_lock(&fs_info->unused_bg_unpin_mutex);
2835 btrfs_find_first_extent_bit(unpin, 0, &start, &end, EXTENT_DIRTY, &cached_state);
2836
2837 while (!TRANS_ABORTED(trans) && cached_state) {
2838 struct extent_state *next_state;
2839
2840 if (btrfs_test_opt(fs_info, DISCARD_SYNC))
2841 ret = btrfs_discard_extent(fs_info, start,
2842 end + 1 - start, NULL);
2843
2844 next_state = btrfs_next_extent_state(unpin, cached_state);
2845 btrfs_clear_extent_dirty(unpin, start, end, &cached_state);
2846 ret = unpin_extent_range(fs_info, start, end, true);
2847 /*
2848 * If we get an error unpinning an extent range, store the first
2849 * error to return later after trying to unpin all ranges and do
2850 * the sync discards. Our caller will abort the transaction
2851 * (which already wrote new superblocks) and on the next mount
2852 * the space will be available as it was pinned by in-memory
2853 * only structures in this phase.
2854 */
2855 if (ret) {
2856 btrfs_err_rl(fs_info,
2857"failed to unpin extent range [%llu, %llu] when committing transaction %llu: %s (%d)",
2858 start, end, trans->transid,
2859 btrfs_decode_error(ret), ret);
2860 if (!unpin_error)
2861 unpin_error = ret;
2862 }
2863
2864 btrfs_free_extent_state(cached_state);
2865
2866 if (need_resched()) {
2867 btrfs_free_extent_state(next_state);
2868 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2869 cond_resched();
2870 cached_state = NULL;
2871 mutex_lock(&fs_info->unused_bg_unpin_mutex);
2872 btrfs_find_first_extent_bit(unpin, 0, &start, &end,
2873 EXTENT_DIRTY, &cached_state);
2874 } else {
2875 cached_state = next_state;
2876 if (cached_state) {
2877 start = cached_state->start;
2878 end = cached_state->end;
2879 }
2880 }
2881 }
2882 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2883 btrfs_free_extent_state(cached_state);
2884
2885 if (btrfs_test_opt(fs_info, DISCARD_ASYNC)) {
2886 btrfs_discard_calc_delay(&fs_info->discard_ctl);
2887 btrfs_discard_schedule_work(&fs_info->discard_ctl, true);
2888 }
2889
2890 /*
2891 * Transaction is finished. We don't need the lock anymore. We
2892 * do need to clean up the block groups in case of a transaction
2893 * abort.
2894 */
2895 deleted_bgs = &trans->transaction->deleted_bgs;
2896 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
2897 ret = -EROFS;
2898 if (!TRANS_ABORTED(trans))
2899 ret = btrfs_discard_extent(fs_info, block_group->start,
2900 block_group->length, NULL);
2901
2902 /*
2903 * Not strictly necessary to lock, as the block_group should be
2904 * read-only from btrfs_delete_unused_bgs().
2905 */
2906 ASSERT(block_group->ro);
2907 spin_lock(&fs_info->unused_bgs_lock);
2908 list_del_init(&block_group->bg_list);
2909 spin_unlock(&fs_info->unused_bgs_lock);
2910
2911 btrfs_unfreeze_block_group(block_group);
2912 btrfs_put_block_group(block_group);
2913
2914 if (ret) {
2915 const char *errstr = btrfs_decode_error(ret);
2916 btrfs_warn(fs_info,
2917 "discard failed while removing blockgroup: errno=%d %s",
2918 ret, errstr);
2919 }
2920 }
2921
2922 return unpin_error;
2923}
2924
2925/*
2926 * Parse an extent item's inline extents looking for a simple quotas owner ref.
2927 *
2928 * @fs_info: the btrfs_fs_info for this mount
2929 * @leaf: a leaf in the extent tree containing the extent item
2930 * @slot: the slot in the leaf where the extent item is found
2931 *
2932 * Returns the objectid of the root that originally allocated the extent item
2933 * if the inline owner ref is expected and present, otherwise 0.
2934 *
2935 * If an extent item has an owner ref item, it will be the first inline ref
2936 * item. Therefore the logic is to check whether there are any inline ref
2937 * items, then check the type of the first one.
2938 */
2939u64 btrfs_get_extent_owner_root(struct btrfs_fs_info *fs_info,
2940 struct extent_buffer *leaf, int slot)
2941{
2942 struct btrfs_extent_item *ei;
2943 struct btrfs_extent_inline_ref *iref;
2944 struct btrfs_extent_owner_ref *oref;
2945 unsigned long ptr;
2946 unsigned long end;
2947 int type;
2948
2949 if (!btrfs_fs_incompat(fs_info, SIMPLE_QUOTA))
2950 return 0;
2951
2952 ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
2953 ptr = (unsigned long)(ei + 1);
2954 end = (unsigned long)ei + btrfs_item_size(leaf, slot);
2955
2956 /* No inline ref items of any kind, can't check type. */
2957 if (ptr == end)
2958 return 0;
2959
2960 iref = (struct btrfs_extent_inline_ref *)ptr;
2961 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
2962
2963 /* We found an owner ref, get the root out of it. */
2964 if (type == BTRFS_EXTENT_OWNER_REF_KEY) {
2965 oref = (struct btrfs_extent_owner_ref *)(&iref->offset);
2966 return btrfs_extent_owner_ref_root_id(leaf, oref);
2967 }
2968
2969 /* We have inline refs, but not an owner ref. */
2970 return 0;
2971}
2972
2973static int do_free_extent_accounting(struct btrfs_trans_handle *trans,
2974 u64 bytenr, struct btrfs_squota_delta *delta)
2975{
2976 int ret;
2977 u64 num_bytes = delta->num_bytes;
2978
2979 if (delta->is_data) {
2980 struct btrfs_root *csum_root;
2981
2982 csum_root = btrfs_csum_root(trans->fs_info, bytenr);
2983 ret = btrfs_del_csums(trans, csum_root, bytenr, num_bytes);
2984 if (unlikely(ret)) {
2985 btrfs_abort_transaction(trans, ret);
2986 return ret;
2987 }
2988
2989 ret = btrfs_delete_raid_extent(trans, bytenr, num_bytes);
2990 if (unlikely(ret)) {
2991 btrfs_abort_transaction(trans, ret);
2992 return ret;
2993 }
2994 }
2995
2996 ret = btrfs_record_squota_delta(trans->fs_info, delta);
2997 if (unlikely(ret)) {
2998 btrfs_abort_transaction(trans, ret);
2999 return ret;
3000 }
3001
3002 ret = btrfs_add_to_free_space_tree(trans, bytenr, num_bytes);
3003 if (unlikely(ret)) {
3004 btrfs_abort_transaction(trans, ret);
3005 return ret;
3006 }
3007
3008 ret = btrfs_update_block_group(trans, bytenr, num_bytes, false);
3009 if (ret)
3010 btrfs_abort_transaction(trans, ret);
3011
3012 return ret;
3013}
3014
3015#define abort_and_dump(trans, path, fmt, args...) \
3016({ \
3017 btrfs_abort_transaction(trans, -EUCLEAN); \
3018 btrfs_print_leaf(path->nodes[0]); \
3019 btrfs_crit(trans->fs_info, fmt, ##args); \
3020})
3021
3022/*
3023 * Drop one or more refs of @node.
3024 *
3025 * 1. Locate the extent refs.
3026 * It's either inline in EXTENT/METADATA_ITEM or in keyed SHARED_* item.
3027 * Locate it, then reduce the refs number or remove the ref line completely.
3028 *
3029 * 2. Update the refs count in EXTENT/METADATA_ITEM
3030 *
3031 * Inline backref case:
3032 *
3033 * in extent tree we have:
3034 *
3035 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
3036 * refs 2 gen 6 flags DATA
3037 * extent data backref root FS_TREE objectid 258 offset 0 count 1
3038 * extent data backref root FS_TREE objectid 257 offset 0 count 1
3039 *
3040 * This function gets called with:
3041 *
3042 * node->bytenr = 13631488
3043 * node->num_bytes = 1048576
3044 * root_objectid = FS_TREE
3045 * owner_objectid = 257
3046 * owner_offset = 0
3047 * refs_to_drop = 1
3048 *
3049 * Then we should get some like:
3050 *
3051 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
3052 * refs 1 gen 6 flags DATA
3053 * extent data backref root FS_TREE objectid 258 offset 0 count 1
3054 *
3055 * Keyed backref case:
3056 *
3057 * in extent tree we have:
3058 *
3059 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
3060 * refs 754 gen 6 flags DATA
3061 * [...]
3062 * item 2 key (13631488 EXTENT_DATA_REF <HASH>) itemoff 3915 itemsize 28
3063 * extent data backref root FS_TREE objectid 866 offset 0 count 1
3064 *
3065 * This function get called with:
3066 *
3067 * node->bytenr = 13631488
3068 * node->num_bytes = 1048576
3069 * root_objectid = FS_TREE
3070 * owner_objectid = 866
3071 * owner_offset = 0
3072 * refs_to_drop = 1
3073 *
3074 * Then we should get some like:
3075 *
3076 * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
3077 * refs 753 gen 6 flags DATA
3078 *
3079 * And that (13631488 EXTENT_DATA_REF <HASH>) gets removed.
3080 */
3081static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
3082 struct btrfs_delayed_ref_head *href,
3083 const struct btrfs_delayed_ref_node *node,
3084 struct btrfs_delayed_extent_op *extent_op)
3085{
3086 struct btrfs_fs_info *info = trans->fs_info;
3087 struct btrfs_key key;
3088 BTRFS_PATH_AUTO_FREE(path);
3089 struct btrfs_root *extent_root;
3090 struct extent_buffer *leaf;
3091 struct btrfs_extent_item *ei;
3092 struct btrfs_extent_inline_ref *iref;
3093 int ret;
3094 int is_data;
3095 int extent_slot = 0;
3096 int found_extent = 0;
3097 int num_to_del = 1;
3098 int refs_to_drop = node->ref_mod;
3099 u32 item_size;
3100 u64 refs;
3101 u64 bytenr = node->bytenr;
3102 u64 num_bytes = node->num_bytes;
3103 u64 owner_objectid = btrfs_delayed_ref_owner(node);
3104 u64 owner_offset = btrfs_delayed_ref_offset(node);
3105 bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
3106 u64 delayed_ref_root = href->owning_root;
3107
3108 extent_root = btrfs_extent_root(info, bytenr);
3109 ASSERT(extent_root);
3110
3111 path = btrfs_alloc_path();
3112 if (!path)
3113 return -ENOMEM;
3114
3115 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
3116
3117 if (unlikely(!is_data && refs_to_drop != 1)) {
3118 btrfs_crit(info,
3119"invalid refs_to_drop, dropping more than 1 refs for tree block %llu refs_to_drop %u",
3120 node->bytenr, refs_to_drop);
3121 ret = -EINVAL;
3122 btrfs_abort_transaction(trans, ret);
3123 return ret;
3124 }
3125
3126 if (is_data)
3127 skinny_metadata = false;
3128
3129 ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
3130 node->parent, node->ref_root, owner_objectid,
3131 owner_offset);
3132 if (ret == 0) {
3133 /*
3134 * Either the inline backref or the SHARED_DATA_REF/
3135 * SHARED_BLOCK_REF is found
3136 *
3137 * Here is a quick path to locate EXTENT/METADATA_ITEM.
3138 * It's possible the EXTENT/METADATA_ITEM is near current slot.
3139 */
3140 extent_slot = path->slots[0];
3141 while (extent_slot >= 0) {
3142 btrfs_item_key_to_cpu(path->nodes[0], &key,
3143 extent_slot);
3144 if (key.objectid != bytenr)
3145 break;
3146 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
3147 key.offset == num_bytes) {
3148 found_extent = 1;
3149 break;
3150 }
3151 if (key.type == BTRFS_METADATA_ITEM_KEY &&
3152 key.offset == owner_objectid) {
3153 found_extent = 1;
3154 break;
3155 }
3156
3157 /* Quick path didn't find the EXTENT/METADATA_ITEM */
3158 if (path->slots[0] - extent_slot > 5)
3159 break;
3160 extent_slot--;
3161 }
3162
3163 if (!found_extent) {
3164 if (unlikely(iref)) {
3165 abort_and_dump(trans, path,
3166"invalid iref slot %u, no EXTENT/METADATA_ITEM found but has inline extent ref",
3167 path->slots[0]);
3168 return -EUCLEAN;
3169 }
3170 /* Must be SHARED_* item, remove the backref first */
3171 ret = remove_extent_backref(trans, extent_root, path,
3172 NULL, refs_to_drop, is_data);
3173 if (unlikely(ret)) {
3174 btrfs_abort_transaction(trans, ret);
3175 return ret;
3176 }
3177 btrfs_release_path(path);
3178
3179 /* Slow path to locate EXTENT/METADATA_ITEM */
3180 key.objectid = bytenr;
3181 key.type = BTRFS_EXTENT_ITEM_KEY;
3182 key.offset = num_bytes;
3183
3184 if (!is_data && skinny_metadata) {
3185 key.type = BTRFS_METADATA_ITEM_KEY;
3186 key.offset = owner_objectid;
3187 }
3188
3189 ret = btrfs_search_slot(trans, extent_root,
3190 &key, path, -1, 1);
3191 if (ret > 0 && skinny_metadata && path->slots[0]) {
3192 /*
3193 * Couldn't find our skinny metadata item,
3194 * see if we have ye olde extent item.
3195 */
3196 path->slots[0]--;
3197 btrfs_item_key_to_cpu(path->nodes[0], &key,
3198 path->slots[0]);
3199 if (key.objectid == bytenr &&
3200 key.type == BTRFS_EXTENT_ITEM_KEY &&
3201 key.offset == num_bytes)
3202 ret = 0;
3203 }
3204
3205 if (ret > 0 && skinny_metadata) {
3206 skinny_metadata = false;
3207 key.objectid = bytenr;
3208 key.type = BTRFS_EXTENT_ITEM_KEY;
3209 key.offset = num_bytes;
3210 btrfs_release_path(path);
3211 ret = btrfs_search_slot(trans, extent_root,
3212 &key, path, -1, 1);
3213 }
3214
3215 if (ret) {
3216 if (ret > 0)
3217 btrfs_print_leaf(path->nodes[0]);
3218 btrfs_err(info,
3219 "umm, got %d back from search, was looking for %llu, slot %d",
3220 ret, bytenr, path->slots[0]);
3221 }
3222 if (unlikely(ret < 0)) {
3223 btrfs_abort_transaction(trans, ret);
3224 return ret;
3225 }
3226 extent_slot = path->slots[0];
3227 }
3228 } else if (WARN_ON(ret == -ENOENT)) {
3229 abort_and_dump(trans, path,
3230"unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu slot %d",
3231 bytenr, node->parent, node->ref_root, owner_objectid,
3232 owner_offset, path->slots[0]);
3233 return ret;
3234 } else {
3235 btrfs_abort_transaction(trans, ret);
3236 return ret;
3237 }
3238
3239 leaf = path->nodes[0];
3240 item_size = btrfs_item_size(leaf, extent_slot);
3241 if (unlikely(item_size < sizeof(*ei))) {
3242 ret = -EUCLEAN;
3243 btrfs_err(trans->fs_info,
3244 "unexpected extent item size, has %u expect >= %zu",
3245 item_size, sizeof(*ei));
3246 btrfs_abort_transaction(trans, ret);
3247 return ret;
3248 }
3249 ei = btrfs_item_ptr(leaf, extent_slot,
3250 struct btrfs_extent_item);
3251 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
3252 key.type == BTRFS_EXTENT_ITEM_KEY) {
3253 struct btrfs_tree_block_info *bi;
3254
3255 if (unlikely(item_size < sizeof(*ei) + sizeof(*bi))) {
3256 abort_and_dump(trans, path,
3257"invalid extent item size for key (%llu, %u, %llu) slot %u owner %llu, has %u expect >= %zu",
3258 key.objectid, key.type, key.offset,
3259 path->slots[0], owner_objectid, item_size,
3260 sizeof(*ei) + sizeof(*bi));
3261 return -EUCLEAN;
3262 }
3263 bi = (struct btrfs_tree_block_info *)(ei + 1);
3264 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
3265 }
3266
3267 refs = btrfs_extent_refs(leaf, ei);
3268 if (unlikely(refs < refs_to_drop)) {
3269 abort_and_dump(trans, path,
3270 "trying to drop %d refs but we only have %llu for bytenr %llu slot %u",
3271 refs_to_drop, refs, bytenr, path->slots[0]);
3272 return -EUCLEAN;
3273 }
3274 refs -= refs_to_drop;
3275
3276 if (refs > 0) {
3277 if (extent_op)
3278 __run_delayed_extent_op(extent_op, leaf, ei);
3279 /*
3280 * In the case of inline back ref, reference count will
3281 * be updated by remove_extent_backref
3282 */
3283 if (iref) {
3284 if (unlikely(!found_extent)) {
3285 abort_and_dump(trans, path,
3286"invalid iref, got inlined extent ref but no EXTENT/METADATA_ITEM found, slot %u",
3287 path->slots[0]);
3288 return -EUCLEAN;
3289 }
3290 } else {
3291 btrfs_set_extent_refs(leaf, ei, refs);
3292 }
3293 if (found_extent) {
3294 ret = remove_extent_backref(trans, extent_root, path,
3295 iref, refs_to_drop, is_data);
3296 if (unlikely(ret)) {
3297 btrfs_abort_transaction(trans, ret);
3298 return ret;
3299 }
3300 }
3301 } else {
3302 struct btrfs_squota_delta delta = {
3303 .root = delayed_ref_root,
3304 .num_bytes = num_bytes,
3305 .is_data = is_data,
3306 .is_inc = false,
3307 .generation = btrfs_extent_generation(leaf, ei),
3308 };
3309
3310 /* In this branch refs == 1 */
3311 if (found_extent) {
3312 if (unlikely(is_data && refs_to_drop !=
3313 extent_data_ref_count(path, iref))) {
3314 abort_and_dump(trans, path,
3315 "invalid refs_to_drop, current refs %u refs_to_drop %u slot %u",
3316 extent_data_ref_count(path, iref),
3317 refs_to_drop, path->slots[0]);
3318 return -EUCLEAN;
3319 }
3320 if (iref) {
3321 if (unlikely(path->slots[0] != extent_slot)) {
3322 abort_and_dump(trans, path,
3323"invalid iref, extent item key " BTRFS_KEY_FMT " slot %u doesn't have wanted iref",
3324 BTRFS_KEY_FMT_VALUE(&key),
3325 path->slots[0]);
3326 return -EUCLEAN;
3327 }
3328 } else {
3329 /*
3330 * No inline ref, we must be at SHARED_* item,
3331 * And it's single ref, it must be:
3332 * | extent_slot ||extent_slot + 1|
3333 * [ EXTENT/METADATA_ITEM ][ SHARED_* ITEM ]
3334 */
3335 if (unlikely(path->slots[0] != extent_slot + 1)) {
3336 abort_and_dump(trans, path,
3337 "invalid SHARED_* item slot %u, previous item is not EXTENT/METADATA_ITEM",
3338 path->slots[0]);
3339 return -EUCLEAN;
3340 }
3341 path->slots[0] = extent_slot;
3342 num_to_del = 2;
3343 }
3344 }
3345 /*
3346 * We can't infer the data owner from the delayed ref, so we need
3347 * to try to get it from the owning ref item.
3348 *
3349 * If it is not present, then that extent was not written under
3350 * simple quotas mode, so we don't need to account for its deletion.
3351 */
3352 if (is_data)
3353 delta.root = btrfs_get_extent_owner_root(trans->fs_info,
3354 leaf, extent_slot);
3355
3356 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
3357 num_to_del);
3358 if (unlikely(ret)) {
3359 btrfs_abort_transaction(trans, ret);
3360 return ret;
3361 }
3362 btrfs_release_path(path);
3363
3364 ret = do_free_extent_accounting(trans, bytenr, &delta);
3365 }
3366 btrfs_release_path(path);
3367
3368 return ret;
3369}
3370
3371/*
3372 * when we free an block, it is possible (and likely) that we free the last
3373 * delayed ref for that extent as well. This searches the delayed ref tree for
3374 * a given extent, and if there are no other delayed refs to be processed, it
3375 * removes it from the tree.
3376 */
3377static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
3378 u64 bytenr)
3379{
3380 struct btrfs_fs_info *fs_info = trans->fs_info;
3381 struct btrfs_delayed_ref_head *head;
3382 struct btrfs_delayed_ref_root *delayed_refs;
3383 int ret = 0;
3384
3385 delayed_refs = &trans->transaction->delayed_refs;
3386 spin_lock(&delayed_refs->lock);
3387 head = btrfs_find_delayed_ref_head(fs_info, delayed_refs, bytenr);
3388 if (!head)
3389 goto out_delayed_unlock;
3390
3391 spin_lock(&head->lock);
3392 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
3393 goto out;
3394
3395 if (cleanup_extent_op(head) != NULL)
3396 goto out;
3397
3398 /*
3399 * waiting for the lock here would deadlock. If someone else has it
3400 * locked they are already in the process of dropping it anyway
3401 */
3402 if (!mutex_trylock(&head->mutex))
3403 goto out;
3404
3405 btrfs_delete_ref_head(fs_info, delayed_refs, head);
3406 head->processing = false;
3407
3408 spin_unlock(&head->lock);
3409 spin_unlock(&delayed_refs->lock);
3410
3411 BUG_ON(head->extent_op);
3412 if (head->must_insert_reserved)
3413 ret = 1;
3414
3415 btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
3416 mutex_unlock(&head->mutex);
3417 btrfs_put_delayed_ref_head(head);
3418 return ret;
3419out:
3420 spin_unlock(&head->lock);
3421
3422out_delayed_unlock:
3423 spin_unlock(&delayed_refs->lock);
3424 return 0;
3425}
3426
3427int btrfs_free_tree_block(struct btrfs_trans_handle *trans,
3428 u64 root_id,
3429 struct extent_buffer *buf,
3430 u64 parent, int last_ref)
3431{
3432 struct btrfs_fs_info *fs_info = trans->fs_info;
3433 struct btrfs_block_group *bg;
3434 int ret;
3435
3436 if (root_id != BTRFS_TREE_LOG_OBJECTID) {
3437 struct btrfs_ref generic_ref = {
3438 .action = BTRFS_DROP_DELAYED_REF,
3439 .bytenr = buf->start,
3440 .num_bytes = buf->len,
3441 .parent = parent,
3442 .owning_root = btrfs_header_owner(buf),
3443 .ref_root = root_id,
3444 };
3445
3446 /*
3447 * Assert that the extent buffer is not cleared due to
3448 * EXTENT_BUFFER_ZONED_ZEROOUT. Please refer
3449 * btrfs_clear_buffer_dirty() and btree_csum_one_bio() for
3450 * detail.
3451 */
3452 ASSERT(btrfs_header_bytenr(buf) != 0);
3453
3454 btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf), 0, false);
3455 btrfs_ref_tree_mod(fs_info, &generic_ref);
3456 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL);
3457 if (ret < 0)
3458 return ret;
3459 }
3460
3461 if (!last_ref)
3462 return 0;
3463
3464 if (btrfs_header_generation(buf) != trans->transid)
3465 goto out;
3466
3467 if (root_id != BTRFS_TREE_LOG_OBJECTID) {
3468 ret = check_ref_cleanup(trans, buf->start);
3469 if (!ret)
3470 goto out;
3471 }
3472
3473 bg = btrfs_lookup_block_group(fs_info, buf->start);
3474
3475 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
3476 pin_down_extent(trans, bg, buf->start, buf->len, true);
3477 btrfs_put_block_group(bg);
3478 goto out;
3479 }
3480
3481 /*
3482 * If there are tree mod log users we may have recorded mod log
3483 * operations for this node. If we re-allocate this node we
3484 * could replay operations on this node that happened when it
3485 * existed in a completely different root. For example if it
3486 * was part of root A, then was reallocated to root B, and we
3487 * are doing a btrfs_old_search_slot(root b), we could replay
3488 * operations that happened when the block was part of root A,
3489 * giving us an inconsistent view of the btree.
3490 *
3491 * We are safe from races here because at this point no other
3492 * node or root points to this extent buffer, so if after this
3493 * check a new tree mod log user joins we will not have an
3494 * existing log of operations on this node that we have to
3495 * contend with.
3496 */
3497
3498 if (test_bit(BTRFS_FS_TREE_MOD_LOG_USERS, &fs_info->flags)
3499 || btrfs_is_zoned(fs_info)) {
3500 pin_down_extent(trans, bg, buf->start, buf->len, true);
3501 btrfs_put_block_group(bg);
3502 goto out;
3503 }
3504
3505 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
3506
3507 btrfs_add_free_space(bg, buf->start, buf->len);
3508 btrfs_free_reserved_bytes(bg, buf->len, false);
3509 btrfs_put_block_group(bg);
3510 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
3511
3512out:
3513 return 0;
3514}
3515
3516/* Can return -ENOMEM */
3517int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
3518{
3519 struct btrfs_fs_info *fs_info = trans->fs_info;
3520 int ret;
3521
3522 if (btrfs_is_testing(fs_info))
3523 return 0;
3524
3525 /*
3526 * tree log blocks never actually go into the extent allocation
3527 * tree, just update pinning info and exit early.
3528 */
3529 if (ref->ref_root == BTRFS_TREE_LOG_OBJECTID) {
3530 btrfs_pin_extent(trans, ref->bytenr, ref->num_bytes);
3531 ret = 0;
3532 } else if (ref->type == BTRFS_REF_METADATA) {
3533 ret = btrfs_add_delayed_tree_ref(trans, ref, NULL);
3534 } else {
3535 ret = btrfs_add_delayed_data_ref(trans, ref, 0);
3536 }
3537
3538 if (ref->ref_root != BTRFS_TREE_LOG_OBJECTID)
3539 btrfs_ref_tree_mod(fs_info, ref);
3540
3541 return ret;
3542}
3543
3544enum btrfs_loop_type {
3545 /*
3546 * Start caching block groups but do not wait for progress or for them
3547 * to be done.
3548 */
3549 LOOP_CACHING_NOWAIT,
3550
3551 /*
3552 * Wait for the block group free_space >= the space we're waiting for if
3553 * the block group isn't cached.
3554 */
3555 LOOP_CACHING_WAIT,
3556
3557 /*
3558 * Allow allocations to happen from block groups that do not yet have a
3559 * size classification.
3560 */
3561 LOOP_UNSET_SIZE_CLASS,
3562
3563 /*
3564 * Allocate a chunk and then retry the allocation.
3565 */
3566 LOOP_ALLOC_CHUNK,
3567
3568 /*
3569 * Ignore the size class restrictions for this allocation.
3570 */
3571 LOOP_WRONG_SIZE_CLASS,
3572
3573 /*
3574 * Ignore the empty size, only try to allocate the number of bytes
3575 * needed for this allocation.
3576 */
3577 LOOP_NO_EMPTY_SIZE,
3578};
3579
3580static inline void
3581btrfs_lock_block_group(struct btrfs_block_group *cache, bool delalloc)
3582{
3583 if (delalloc)
3584 down_read(&cache->data_rwsem);
3585}
3586
3587static inline void btrfs_grab_block_group(struct btrfs_block_group *cache,
3588 bool delalloc)
3589{
3590 btrfs_get_block_group(cache);
3591 if (delalloc)
3592 down_read(&cache->data_rwsem);
3593}
3594
3595static struct btrfs_block_group *btrfs_lock_cluster(
3596 struct btrfs_block_group *block_group,
3597 struct btrfs_free_cluster *cluster,
3598 bool delalloc)
3599 __acquires(&cluster->refill_lock)
3600{
3601 struct btrfs_block_group *used_bg = NULL;
3602
3603 spin_lock(&cluster->refill_lock);
3604 while (1) {
3605 used_bg = cluster->block_group;
3606 if (!used_bg)
3607 return NULL;
3608
3609 if (used_bg == block_group)
3610 return used_bg;
3611
3612 btrfs_get_block_group(used_bg);
3613
3614 if (!delalloc)
3615 return used_bg;
3616
3617 if (down_read_trylock(&used_bg->data_rwsem))
3618 return used_bg;
3619
3620 spin_unlock(&cluster->refill_lock);
3621
3622 /* We should only have one-level nested. */
3623 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
3624
3625 spin_lock(&cluster->refill_lock);
3626 if (used_bg == cluster->block_group)
3627 return used_bg;
3628
3629 up_read(&used_bg->data_rwsem);
3630 btrfs_put_block_group(used_bg);
3631 }
3632}
3633
3634static inline void
3635btrfs_release_block_group(struct btrfs_block_group *cache, bool delalloc)
3636{
3637 if (delalloc)
3638 up_read(&cache->data_rwsem);
3639 btrfs_put_block_group(cache);
3640}
3641
3642static bool find_free_extent_check_size_class(const struct find_free_extent_ctl *ffe_ctl,
3643 const struct btrfs_block_group *bg)
3644{
3645 if (ffe_ctl->policy == BTRFS_EXTENT_ALLOC_ZONED)
3646 return true;
3647 if (!btrfs_block_group_should_use_size_class(bg))
3648 return true;
3649 if (ffe_ctl->loop >= LOOP_WRONG_SIZE_CLASS)
3650 return true;
3651 if (ffe_ctl->loop >= LOOP_UNSET_SIZE_CLASS &&
3652 bg->size_class == BTRFS_BG_SZ_NONE)
3653 return true;
3654 return ffe_ctl->size_class == bg->size_class;
3655}
3656
3657/*
3658 * Helper function for find_free_extent().
3659 *
3660 * Return -ENOENT to inform caller that we need fallback to unclustered mode.
3661 * Return >0 to inform caller that we find nothing
3662 * Return 0 means we have found a location and set ffe_ctl->found_offset.
3663 */
3664static int find_free_extent_clustered(struct btrfs_block_group *bg,
3665 struct find_free_extent_ctl *ffe_ctl,
3666 struct btrfs_block_group **cluster_bg_ret)
3667{
3668 struct btrfs_block_group *cluster_bg;
3669 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3670 u64 aligned_cluster;
3671 u64 offset;
3672 int ret;
3673
3674 cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc);
3675 if (!cluster_bg)
3676 goto refill_cluster;
3677 if (cluster_bg != bg && (cluster_bg->ro ||
3678 !block_group_bits(cluster_bg, ffe_ctl->flags) ||
3679 !find_free_extent_check_size_class(ffe_ctl, cluster_bg)))
3680 goto release_cluster;
3681
3682 offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
3683 ffe_ctl->num_bytes, cluster_bg->start,
3684 &ffe_ctl->max_extent_size);
3685 if (offset) {
3686 /* We have a block, we're done */
3687 spin_unlock(&last_ptr->refill_lock);
3688 trace_btrfs_reserve_extent_cluster(cluster_bg, ffe_ctl);
3689 *cluster_bg_ret = cluster_bg;
3690 ffe_ctl->found_offset = offset;
3691 return 0;
3692 }
3693 WARN_ON(last_ptr->block_group != cluster_bg);
3694
3695release_cluster:
3696 /*
3697 * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
3698 * lets just skip it and let the allocator find whatever block it can
3699 * find. If we reach this point, we will have tried the cluster
3700 * allocator plenty of times and not have found anything, so we are
3701 * likely way too fragmented for the clustering stuff to find anything.
3702 *
3703 * However, if the cluster is taken from the current block group,
3704 * release the cluster first, so that we stand a better chance of
3705 * succeeding in the unclustered allocation.
3706 */
3707 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
3708 spin_unlock(&last_ptr->refill_lock);
3709 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3710 return -ENOENT;
3711 }
3712
3713 /* This cluster didn't work out, free it and start over */
3714 btrfs_return_cluster_to_free_space(NULL, last_ptr);
3715
3716 if (cluster_bg != bg)
3717 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3718
3719refill_cluster:
3720 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
3721 spin_unlock(&last_ptr->refill_lock);
3722 return -ENOENT;
3723 }
3724
3725 aligned_cluster = max_t(u64,
3726 ffe_ctl->empty_cluster + ffe_ctl->empty_size,
3727 bg->full_stripe_len);
3728 ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
3729 ffe_ctl->num_bytes, aligned_cluster);
3730 if (ret == 0) {
3731 /* Now pull our allocation out of this cluster */
3732 offset = btrfs_alloc_from_cluster(bg, last_ptr,
3733 ffe_ctl->num_bytes, ffe_ctl->search_start,
3734 &ffe_ctl->max_extent_size);
3735 if (offset) {
3736 /* We found one, proceed */
3737 spin_unlock(&last_ptr->refill_lock);
3738 ffe_ctl->found_offset = offset;
3739 trace_btrfs_reserve_extent_cluster(bg, ffe_ctl);
3740 return 0;
3741 }
3742 }
3743 /*
3744 * At this point we either didn't find a cluster or we weren't able to
3745 * allocate a block from our cluster. Free the cluster we've been
3746 * trying to use, and go to the next block group.
3747 */
3748 btrfs_return_cluster_to_free_space(NULL, last_ptr);
3749 spin_unlock(&last_ptr->refill_lock);
3750 return 1;
3751}
3752
3753/*
3754 * Return >0 to inform caller that we find nothing
3755 * Return 0 when we found an free extent and set ffe_ctrl->found_offset
3756 */
3757static int find_free_extent_unclustered(struct btrfs_block_group *bg,
3758 struct find_free_extent_ctl *ffe_ctl)
3759{
3760 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3761 u64 offset;
3762
3763 /*
3764 * We are doing an unclustered allocation, set the fragmented flag so
3765 * we don't bother trying to setup a cluster again until we get more
3766 * space.
3767 */
3768 if (unlikely(last_ptr)) {
3769 spin_lock(&last_ptr->lock);
3770 last_ptr->fragmented = 1;
3771 spin_unlock(&last_ptr->lock);
3772 }
3773 if (ffe_ctl->cached) {
3774 struct btrfs_free_space_ctl *free_space_ctl;
3775
3776 free_space_ctl = bg->free_space_ctl;
3777 spin_lock(&free_space_ctl->tree_lock);
3778 if (free_space_ctl->free_space <
3779 ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
3780 ffe_ctl->empty_size) {
3781 ffe_ctl->total_free_space = max_t(u64,
3782 ffe_ctl->total_free_space,
3783 free_space_ctl->free_space);
3784 spin_unlock(&free_space_ctl->tree_lock);
3785 return 1;
3786 }
3787 spin_unlock(&free_space_ctl->tree_lock);
3788 }
3789
3790 offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
3791 ffe_ctl->num_bytes, ffe_ctl->empty_size,
3792 &ffe_ctl->max_extent_size);
3793 if (!offset)
3794 return 1;
3795 ffe_ctl->found_offset = offset;
3796 return 0;
3797}
3798
3799static int do_allocation_clustered(struct btrfs_block_group *block_group,
3800 struct find_free_extent_ctl *ffe_ctl,
3801 struct btrfs_block_group **bg_ret)
3802{
3803 int ret;
3804
3805 /* We want to try and use the cluster allocator, so lets look there */
3806 if (ffe_ctl->last_ptr && ffe_ctl->use_cluster) {
3807 ret = find_free_extent_clustered(block_group, ffe_ctl, bg_ret);
3808 if (ret >= 0)
3809 return ret;
3810 /* ret == -ENOENT case falls through */
3811 }
3812
3813 return find_free_extent_unclustered(block_group, ffe_ctl);
3814}
3815
3816/*
3817 * Tree-log block group locking
3818 * ============================
3819 *
3820 * fs_info::treelog_bg_lock protects the fs_info::treelog_bg which
3821 * indicates the starting address of a block group, which is reserved only
3822 * for tree-log metadata.
3823 *
3824 * Lock nesting
3825 * ============
3826 *
3827 * space_info::lock
3828 * block_group::lock
3829 * fs_info::treelog_bg_lock
3830 */
3831
3832/*
3833 * Simple allocator for sequential-only block group. It only allows sequential
3834 * allocation. No need to play with trees. This function also reserves the
3835 * bytes as in btrfs_add_reserved_bytes.
3836 */
3837static int do_allocation_zoned(struct btrfs_block_group *block_group,
3838 struct find_free_extent_ctl *ffe_ctl,
3839 struct btrfs_block_group **bg_ret)
3840{
3841 struct btrfs_fs_info *fs_info = block_group->fs_info;
3842 struct btrfs_space_info *space_info = block_group->space_info;
3843 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
3844 u64 start = block_group->start;
3845 u64 num_bytes = ffe_ctl->num_bytes;
3846 u64 avail;
3847 u64 bytenr = block_group->start;
3848 u64 log_bytenr;
3849 u64 data_reloc_bytenr;
3850 int ret = 0;
3851 bool skip = false;
3852
3853 ASSERT(btrfs_is_zoned(block_group->fs_info));
3854
3855 /*
3856 * Do not allow non-tree-log blocks in the dedicated tree-log block
3857 * group, and vice versa.
3858 */
3859 spin_lock(&fs_info->treelog_bg_lock);
3860 log_bytenr = fs_info->treelog_bg;
3861 if (log_bytenr && ((ffe_ctl->for_treelog && bytenr != log_bytenr) ||
3862 (!ffe_ctl->for_treelog && bytenr == log_bytenr)))
3863 skip = true;
3864 spin_unlock(&fs_info->treelog_bg_lock);
3865 if (skip)
3866 return 1;
3867
3868 /*
3869 * Do not allow non-relocation blocks in the dedicated relocation block
3870 * group, and vice versa.
3871 */
3872 spin_lock(&fs_info->relocation_bg_lock);
3873 data_reloc_bytenr = fs_info->data_reloc_bg;
3874 if (data_reloc_bytenr &&
3875 ((ffe_ctl->for_data_reloc && bytenr != data_reloc_bytenr) ||
3876 (!ffe_ctl->for_data_reloc && bytenr == data_reloc_bytenr)))
3877 skip = true;
3878 spin_unlock(&fs_info->relocation_bg_lock);
3879 if (skip)
3880 return 1;
3881
3882 /* Check RO and no space case before trying to activate it */
3883 spin_lock(&block_group->lock);
3884 if (block_group->ro || btrfs_zoned_bg_is_full(block_group)) {
3885 ret = 1;
3886 /*
3887 * May need to clear fs_info->{treelog,data_reloc}_bg.
3888 * Return the error after taking the locks.
3889 */
3890 }
3891 spin_unlock(&block_group->lock);
3892
3893 /* Metadata block group is activated at write time. */
3894 if (!ret && (block_group->flags & BTRFS_BLOCK_GROUP_DATA) &&
3895 !btrfs_zone_activate(block_group)) {
3896 ret = 1;
3897 /*
3898 * May need to clear fs_info->{treelog,data_reloc}_bg.
3899 * Return the error after taking the locks.
3900 */
3901 }
3902
3903 spin_lock(&space_info->lock);
3904 spin_lock(&block_group->lock);
3905 spin_lock(&fs_info->treelog_bg_lock);
3906 spin_lock(&fs_info->relocation_bg_lock);
3907
3908 if (ret)
3909 goto out;
3910
3911 ASSERT(!ffe_ctl->for_treelog ||
3912 block_group->start == fs_info->treelog_bg ||
3913 fs_info->treelog_bg == 0);
3914 ASSERT(!ffe_ctl->for_data_reloc ||
3915 block_group->start == fs_info->data_reloc_bg ||
3916 fs_info->data_reloc_bg == 0);
3917
3918 if (block_group->ro ||
3919 (!ffe_ctl->for_data_reloc &&
3920 test_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags))) {
3921 ret = 1;
3922 goto out;
3923 }
3924
3925 /*
3926 * Do not allow currently using block group to be tree-log dedicated
3927 * block group.
3928 */
3929 if (ffe_ctl->for_treelog && !fs_info->treelog_bg &&
3930 (block_group->used || block_group->reserved)) {
3931 ret = 1;
3932 goto out;
3933 }
3934
3935 /*
3936 * Do not allow currently used block group to be the data relocation
3937 * dedicated block group.
3938 */
3939 if (ffe_ctl->for_data_reloc && !fs_info->data_reloc_bg &&
3940 (block_group->used || block_group->reserved)) {
3941 ret = 1;
3942 goto out;
3943 }
3944
3945 WARN_ON_ONCE(block_group->alloc_offset > block_group->zone_capacity);
3946 avail = block_group->zone_capacity - block_group->alloc_offset;
3947 if (avail < num_bytes) {
3948 if (ffe_ctl->max_extent_size < avail) {
3949 /*
3950 * With sequential allocator, free space is always
3951 * contiguous
3952 */
3953 ffe_ctl->max_extent_size = avail;
3954 ffe_ctl->total_free_space = avail;
3955 }
3956 ret = 1;
3957 goto out;
3958 }
3959
3960 if (ffe_ctl->for_treelog && !fs_info->treelog_bg)
3961 fs_info->treelog_bg = block_group->start;
3962
3963 if (ffe_ctl->for_data_reloc) {
3964 if (!fs_info->data_reloc_bg)
3965 fs_info->data_reloc_bg = block_group->start;
3966 /*
3967 * Do not allow allocations from this block group, unless it is
3968 * for data relocation. Compared to increasing the ->ro, setting
3969 * the ->zoned_data_reloc_ongoing flag still allows nocow
3970 * writers to come in. See btrfs_inc_nocow_writers().
3971 *
3972 * We need to disable an allocation to avoid an allocation of
3973 * regular (non-relocation data) extent. With mix of relocation
3974 * extents and regular extents, we can dispatch WRITE commands
3975 * (for relocation extents) and ZONE APPEND commands (for
3976 * regular extents) at the same time to the same zone, which
3977 * easily break the write pointer.
3978 *
3979 * Also, this flag avoids this block group to be zone finished.
3980 */
3981 set_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags);
3982 }
3983
3984 ffe_ctl->found_offset = start + block_group->alloc_offset;
3985 block_group->alloc_offset += num_bytes;
3986 spin_lock(&ctl->tree_lock);
3987 ctl->free_space -= num_bytes;
3988 spin_unlock(&ctl->tree_lock);
3989
3990 /*
3991 * We do not check if found_offset is aligned to stripesize. The
3992 * address is anyway rewritten when using zone append writing.
3993 */
3994
3995 ffe_ctl->search_start = ffe_ctl->found_offset;
3996
3997out:
3998 if (ret && ffe_ctl->for_treelog)
3999 fs_info->treelog_bg = 0;
4000 if (ret && ffe_ctl->for_data_reloc)
4001 fs_info->data_reloc_bg = 0;
4002 spin_unlock(&fs_info->relocation_bg_lock);
4003 spin_unlock(&fs_info->treelog_bg_lock);
4004 spin_unlock(&block_group->lock);
4005 spin_unlock(&space_info->lock);
4006 return ret;
4007}
4008
4009static int do_allocation(struct btrfs_block_group *block_group,
4010 struct find_free_extent_ctl *ffe_ctl,
4011 struct btrfs_block_group **bg_ret)
4012{
4013 switch (ffe_ctl->policy) {
4014 case BTRFS_EXTENT_ALLOC_CLUSTERED:
4015 return do_allocation_clustered(block_group, ffe_ctl, bg_ret);
4016 case BTRFS_EXTENT_ALLOC_ZONED:
4017 return do_allocation_zoned(block_group, ffe_ctl, bg_ret);
4018 default:
4019 BUG();
4020 }
4021}
4022
4023static void release_block_group(struct btrfs_block_group *block_group,
4024 struct find_free_extent_ctl *ffe_ctl,
4025 bool delalloc)
4026{
4027 switch (ffe_ctl->policy) {
4028 case BTRFS_EXTENT_ALLOC_CLUSTERED:
4029 ffe_ctl->retry_uncached = false;
4030 break;
4031 case BTRFS_EXTENT_ALLOC_ZONED:
4032 /* Nothing to do */
4033 break;
4034 default:
4035 BUG();
4036 }
4037
4038 BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
4039 ffe_ctl->index);
4040 btrfs_release_block_group(block_group, delalloc);
4041}
4042
4043static void found_extent_clustered(struct find_free_extent_ctl *ffe_ctl,
4044 struct btrfs_key *ins)
4045{
4046 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
4047
4048 if (!ffe_ctl->use_cluster && last_ptr) {
4049 spin_lock(&last_ptr->lock);
4050 last_ptr->window_start = ins->objectid;
4051 spin_unlock(&last_ptr->lock);
4052 }
4053}
4054
4055static void found_extent(struct find_free_extent_ctl *ffe_ctl,
4056 struct btrfs_key *ins)
4057{
4058 switch (ffe_ctl->policy) {
4059 case BTRFS_EXTENT_ALLOC_CLUSTERED:
4060 found_extent_clustered(ffe_ctl, ins);
4061 break;
4062 case BTRFS_EXTENT_ALLOC_ZONED:
4063 /* Nothing to do */
4064 break;
4065 default:
4066 BUG();
4067 }
4068}
4069
4070static int can_allocate_chunk_zoned(struct btrfs_fs_info *fs_info,
4071 struct find_free_extent_ctl *ffe_ctl)
4072{
4073 /* Block group's activeness is not a requirement for METADATA block groups. */
4074 if (!(ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA))
4075 return 0;
4076
4077 /* If we can activate new zone, just allocate a chunk and use it */
4078 if (btrfs_can_activate_zone(fs_info->fs_devices, ffe_ctl->flags))
4079 return 0;
4080
4081 /*
4082 * We already reached the max active zones. Try to finish one block
4083 * group to make a room for a new block group. This is only possible
4084 * for a data block group because btrfs_zone_finish() may need to wait
4085 * for a running transaction which can cause a deadlock for metadata
4086 * allocation.
4087 */
4088 if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA) {
4089 int ret = btrfs_zone_finish_one_bg(fs_info);
4090
4091 if (ret == 1)
4092 return 0;
4093 else if (ret < 0)
4094 return ret;
4095 }
4096
4097 /*
4098 * If we have enough free space left in an already active block group
4099 * and we can't activate any other zone now, do not allow allocating a
4100 * new chunk and let find_free_extent() retry with a smaller size.
4101 */
4102 if (ffe_ctl->max_extent_size >= ffe_ctl->min_alloc_size)
4103 return -ENOSPC;
4104
4105 /*
4106 * Even min_alloc_size is not left in any block groups. Since we cannot
4107 * activate a new block group, allocating it may not help. Let's tell a
4108 * caller to try again and hope it progress something by writing some
4109 * parts of the region. That is only possible for data block groups,
4110 * where a part of the region can be written.
4111 */
4112 if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA)
4113 return -EAGAIN;
4114
4115 /*
4116 * We cannot activate a new block group and no enough space left in any
4117 * block groups. So, allocating a new block group may not help. But,
4118 * there is nothing to do anyway, so let's go with it.
4119 */
4120 return 0;
4121}
4122
4123static int can_allocate_chunk(struct btrfs_fs_info *fs_info,
4124 struct find_free_extent_ctl *ffe_ctl)
4125{
4126 switch (ffe_ctl->policy) {
4127 case BTRFS_EXTENT_ALLOC_CLUSTERED:
4128 return 0;
4129 case BTRFS_EXTENT_ALLOC_ZONED:
4130 return can_allocate_chunk_zoned(fs_info, ffe_ctl);
4131 default:
4132 BUG();
4133 }
4134}
4135
4136/*
4137 * Return >0 means caller needs to re-search for free extent
4138 * Return 0 means we have the needed free extent.
4139 * Return <0 means we failed to locate any free extent.
4140 */
4141static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
4142 struct btrfs_key *ins,
4143 struct find_free_extent_ctl *ffe_ctl,
4144 struct btrfs_space_info *space_info,
4145 bool full_search)
4146{
4147 struct btrfs_root *root = fs_info->chunk_root;
4148 int ret;
4149
4150 if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
4151 ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
4152 ffe_ctl->orig_have_caching_bg = true;
4153
4154 if (ins->objectid) {
4155 found_extent(ffe_ctl, ins);
4156 return 0;
4157 }
4158
4159 if (ffe_ctl->loop >= LOOP_CACHING_WAIT && ffe_ctl->have_caching_bg)
4160 return 1;
4161
4162 ffe_ctl->index++;
4163 if (ffe_ctl->index < BTRFS_NR_RAID_TYPES)
4164 return 1;
4165
4166 /* See the comments for btrfs_loop_type for an explanation of the phases. */
4167 if (ffe_ctl->loop < LOOP_NO_EMPTY_SIZE) {
4168 ffe_ctl->index = 0;
4169 /*
4170 * We want to skip the LOOP_CACHING_WAIT step if we don't have
4171 * any uncached bgs and we've already done a full search
4172 * through.
4173 */
4174 if (ffe_ctl->loop == LOOP_CACHING_NOWAIT &&
4175 (!ffe_ctl->orig_have_caching_bg && full_search))
4176 ffe_ctl->loop++;
4177 ffe_ctl->loop++;
4178
4179 if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
4180 struct btrfs_trans_handle *trans;
4181 int exist = 0;
4182
4183 /* Check if allocation policy allows to create a new chunk */
4184 ret = can_allocate_chunk(fs_info, ffe_ctl);
4185 if (ret)
4186 return ret;
4187
4188 trans = current->journal_info;
4189 if (trans)
4190 exist = 1;
4191 else
4192 trans = btrfs_join_transaction(root);
4193
4194 if (IS_ERR(trans)) {
4195 ret = PTR_ERR(trans);
4196 return ret;
4197 }
4198
4199 ret = btrfs_chunk_alloc(trans, space_info, ffe_ctl->flags,
4200 CHUNK_ALLOC_FORCE_FOR_EXTENT);
4201
4202 /* Do not bail out on ENOSPC since we can do more. */
4203 if (ret == -ENOSPC) {
4204 ret = 0;
4205 ffe_ctl->loop++;
4206 }
4207 else if (ret < 0)
4208 btrfs_abort_transaction(trans, ret);
4209 else
4210 ret = 0;
4211 if (!exist)
4212 btrfs_end_transaction(trans);
4213 if (ret)
4214 return ret;
4215 }
4216
4217 if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
4218 if (ffe_ctl->policy != BTRFS_EXTENT_ALLOC_CLUSTERED)
4219 return -ENOSPC;
4220
4221 /*
4222 * Don't loop again if we already have no empty_size and
4223 * no empty_cluster.
4224 */
4225 if (ffe_ctl->empty_size == 0 &&
4226 ffe_ctl->empty_cluster == 0)
4227 return -ENOSPC;
4228 ffe_ctl->empty_size = 0;
4229 ffe_ctl->empty_cluster = 0;
4230 }
4231 return 1;
4232 }
4233 return -ENOSPC;
4234}
4235
4236static int prepare_allocation_clustered(struct btrfs_fs_info *fs_info,
4237 struct find_free_extent_ctl *ffe_ctl,
4238 struct btrfs_space_info *space_info,
4239 struct btrfs_key *ins)
4240{
4241 /*
4242 * If our free space is heavily fragmented we may not be able to make
4243 * big contiguous allocations, so instead of doing the expensive search
4244 * for free space, simply return ENOSPC with our max_extent_size so we
4245 * can go ahead and search for a more manageable chunk.
4246 *
4247 * If our max_extent_size is large enough for our allocation simply
4248 * disable clustering since we will likely not be able to find enough
4249 * space to create a cluster and induce latency trying.
4250 */
4251 if (space_info->max_extent_size) {
4252 spin_lock(&space_info->lock);
4253 if (space_info->max_extent_size &&
4254 ffe_ctl->num_bytes > space_info->max_extent_size) {
4255 ins->offset = space_info->max_extent_size;
4256 spin_unlock(&space_info->lock);
4257 return -ENOSPC;
4258 } else if (space_info->max_extent_size) {
4259 ffe_ctl->use_cluster = false;
4260 }
4261 spin_unlock(&space_info->lock);
4262 }
4263
4264 ffe_ctl->last_ptr = fetch_cluster_info(fs_info, space_info,
4265 &ffe_ctl->empty_cluster);
4266 if (ffe_ctl->last_ptr) {
4267 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
4268
4269 spin_lock(&last_ptr->lock);
4270 if (last_ptr->block_group)
4271 ffe_ctl->hint_byte = last_ptr->window_start;
4272 if (last_ptr->fragmented) {
4273 /*
4274 * We still set window_start so we can keep track of the
4275 * last place we found an allocation to try and save
4276 * some time.
4277 */
4278 ffe_ctl->hint_byte = last_ptr->window_start;
4279 ffe_ctl->use_cluster = false;
4280 }
4281 spin_unlock(&last_ptr->lock);
4282 }
4283
4284 return 0;
4285}
4286
4287static int prepare_allocation_zoned(struct btrfs_fs_info *fs_info,
4288 struct find_free_extent_ctl *ffe_ctl,
4289 struct btrfs_space_info *space_info)
4290{
4291 if (ffe_ctl->for_treelog) {
4292 spin_lock(&fs_info->treelog_bg_lock);
4293 if (fs_info->treelog_bg)
4294 ffe_ctl->hint_byte = fs_info->treelog_bg;
4295 spin_unlock(&fs_info->treelog_bg_lock);
4296 } else if (ffe_ctl->for_data_reloc) {
4297 spin_lock(&fs_info->relocation_bg_lock);
4298 if (fs_info->data_reloc_bg)
4299 ffe_ctl->hint_byte = fs_info->data_reloc_bg;
4300 spin_unlock(&fs_info->relocation_bg_lock);
4301 } else if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA) {
4302 struct btrfs_block_group *block_group;
4303
4304 spin_lock(&fs_info->zone_active_bgs_lock);
4305 list_for_each_entry(block_group, &fs_info->zone_active_bgs, active_bg_list) {
4306 /*
4307 * No lock is OK here because avail is monotonically
4308 * decreasing, and this is just a hint.
4309 */
4310 u64 avail = block_group->zone_capacity - block_group->alloc_offset;
4311
4312 if (block_group_bits(block_group, ffe_ctl->flags) &&
4313 block_group->space_info == space_info &&
4314 avail >= ffe_ctl->num_bytes) {
4315 ffe_ctl->hint_byte = block_group->start;
4316 break;
4317 }
4318 }
4319 spin_unlock(&fs_info->zone_active_bgs_lock);
4320 }
4321
4322 return 0;
4323}
4324
4325static int prepare_allocation(struct btrfs_fs_info *fs_info,
4326 struct find_free_extent_ctl *ffe_ctl,
4327 struct btrfs_space_info *space_info,
4328 struct btrfs_key *ins)
4329{
4330 switch (ffe_ctl->policy) {
4331 case BTRFS_EXTENT_ALLOC_CLUSTERED:
4332 return prepare_allocation_clustered(fs_info, ffe_ctl,
4333 space_info, ins);
4334 case BTRFS_EXTENT_ALLOC_ZONED:
4335 return prepare_allocation_zoned(fs_info, ffe_ctl, space_info);
4336 default:
4337 BUG();
4338 }
4339}
4340
4341/*
4342 * walks the btree of allocated extents and find a hole of a given size.
4343 * The key ins is changed to record the hole:
4344 * ins->objectid == start position
4345 * ins->flags = BTRFS_EXTENT_ITEM_KEY
4346 * ins->offset == the size of the hole.
4347 * Any available blocks before search_start are skipped.
4348 *
4349 * If there is no suitable free space, we will record the max size of
4350 * the free space extent currently.
4351 *
4352 * The overall logic and call chain:
4353 *
4354 * find_free_extent()
4355 * |- Iterate through all block groups
4356 * | |- Get a valid block group
4357 * | |- Try to do clustered allocation in that block group
4358 * | |- Try to do unclustered allocation in that block group
4359 * | |- Check if the result is valid
4360 * | | |- If valid, then exit
4361 * | |- Jump to next block group
4362 * |
4363 * |- Push harder to find free extents
4364 * |- If not found, re-iterate all block groups
4365 */
4366static noinline int find_free_extent(struct btrfs_root *root,
4367 struct btrfs_key *ins,
4368 struct find_free_extent_ctl *ffe_ctl)
4369{
4370 struct btrfs_fs_info *fs_info = root->fs_info;
4371 int ret = 0;
4372 int cache_block_group_error = 0;
4373 struct btrfs_block_group *block_group = NULL;
4374 struct btrfs_space_info *space_info;
4375 bool full_search = false;
4376
4377 WARN_ON(ffe_ctl->num_bytes < fs_info->sectorsize);
4378
4379 ffe_ctl->search_start = 0;
4380 /* For clustered allocation */
4381 ffe_ctl->empty_cluster = 0;
4382 ffe_ctl->last_ptr = NULL;
4383 ffe_ctl->use_cluster = true;
4384 ffe_ctl->have_caching_bg = false;
4385 ffe_ctl->orig_have_caching_bg = false;
4386 ffe_ctl->index = btrfs_bg_flags_to_raid_index(ffe_ctl->flags);
4387 ffe_ctl->loop = 0;
4388 ffe_ctl->retry_uncached = false;
4389 ffe_ctl->cached = 0;
4390 ffe_ctl->max_extent_size = 0;
4391 ffe_ctl->total_free_space = 0;
4392 ffe_ctl->found_offset = 0;
4393 ffe_ctl->policy = BTRFS_EXTENT_ALLOC_CLUSTERED;
4394 ffe_ctl->size_class = btrfs_calc_block_group_size_class(ffe_ctl->num_bytes);
4395
4396 if (btrfs_is_zoned(fs_info))
4397 ffe_ctl->policy = BTRFS_EXTENT_ALLOC_ZONED;
4398
4399 ins->type = BTRFS_EXTENT_ITEM_KEY;
4400 ins->objectid = 0;
4401 ins->offset = 0;
4402
4403 trace_btrfs_find_free_extent(root, ffe_ctl);
4404
4405 space_info = btrfs_find_space_info(fs_info, ffe_ctl->flags);
4406 if (btrfs_is_zoned(fs_info) && space_info) {
4407 /* Use dedicated sub-space_info for dedicated block group users. */
4408 if (ffe_ctl->for_data_reloc) {
4409 space_info = space_info->sub_group[0];
4410 ASSERT(space_info->subgroup_id == BTRFS_SUB_GROUP_DATA_RELOC);
4411 } else if (ffe_ctl->for_treelog) {
4412 space_info = space_info->sub_group[0];
4413 ASSERT(space_info->subgroup_id == BTRFS_SUB_GROUP_TREELOG);
4414 }
4415 }
4416 if (!space_info) {
4417 btrfs_err(fs_info, "no space info for %llu, tree-log %d, relocation %d",
4418 ffe_ctl->flags, ffe_ctl->for_treelog, ffe_ctl->for_data_reloc);
4419 return -ENOSPC;
4420 }
4421
4422 ret = prepare_allocation(fs_info, ffe_ctl, space_info, ins);
4423 if (ret < 0)
4424 return ret;
4425
4426 ffe_ctl->search_start = max(ffe_ctl->search_start,
4427 first_logical_byte(fs_info));
4428 ffe_ctl->search_start = max(ffe_ctl->search_start, ffe_ctl->hint_byte);
4429 if (ffe_ctl->search_start == ffe_ctl->hint_byte) {
4430 block_group = btrfs_lookup_block_group(fs_info,
4431 ffe_ctl->search_start);
4432 /*
4433 * we don't want to use the block group if it doesn't match our
4434 * allocation bits, or if its not cached.
4435 *
4436 * However if we are re-searching with an ideal block group
4437 * picked out then we don't care that the block group is cached.
4438 */
4439 if (block_group && block_group_bits(block_group, ffe_ctl->flags) &&
4440 block_group->space_info == space_info &&
4441 block_group->cached != BTRFS_CACHE_NO) {
4442 down_read(&space_info->groups_sem);
4443 if (list_empty(&block_group->list) ||
4444 block_group->ro) {
4445 /*
4446 * someone is removing this block group,
4447 * we can't jump into the have_block_group
4448 * target because our list pointers are not
4449 * valid
4450 */
4451 btrfs_put_block_group(block_group);
4452 up_read(&space_info->groups_sem);
4453 } else {
4454 ffe_ctl->index = btrfs_bg_flags_to_raid_index(
4455 block_group->flags);
4456 btrfs_lock_block_group(block_group,
4457 ffe_ctl->delalloc);
4458 ffe_ctl->hinted = true;
4459 goto have_block_group;
4460 }
4461 } else if (block_group) {
4462 btrfs_put_block_group(block_group);
4463 }
4464 }
4465search:
4466 trace_btrfs_find_free_extent_search_loop(root, ffe_ctl);
4467 ffe_ctl->have_caching_bg = false;
4468 if (ffe_ctl->index == btrfs_bg_flags_to_raid_index(ffe_ctl->flags) ||
4469 ffe_ctl->index == 0)
4470 full_search = true;
4471 down_read(&space_info->groups_sem);
4472 list_for_each_entry(block_group,
4473 &space_info->block_groups[ffe_ctl->index], list) {
4474 struct btrfs_block_group *bg_ret;
4475
4476 ffe_ctl->hinted = false;
4477 /* If the block group is read-only, we can skip it entirely. */
4478 if (unlikely(block_group->ro)) {
4479 if (ffe_ctl->for_treelog)
4480 btrfs_clear_treelog_bg(block_group);
4481 if (ffe_ctl->for_data_reloc)
4482 btrfs_clear_data_reloc_bg(block_group);
4483 continue;
4484 }
4485
4486 btrfs_grab_block_group(block_group, ffe_ctl->delalloc);
4487 ffe_ctl->search_start = block_group->start;
4488
4489 /*
4490 * this can happen if we end up cycling through all the
4491 * raid types, but we want to make sure we only allocate
4492 * for the proper type.
4493 */
4494 if (!block_group_bits(block_group, ffe_ctl->flags)) {
4495 u64 extra = BTRFS_BLOCK_GROUP_DUP |
4496 BTRFS_BLOCK_GROUP_RAID1_MASK |
4497 BTRFS_BLOCK_GROUP_RAID56_MASK |
4498 BTRFS_BLOCK_GROUP_RAID10;
4499
4500 /*
4501 * if they asked for extra copies and this block group
4502 * doesn't provide them, bail. This does allow us to
4503 * fill raid0 from raid1.
4504 */
4505 if ((ffe_ctl->flags & extra) && !(block_group->flags & extra))
4506 goto loop;
4507
4508 /*
4509 * This block group has different flags than we want.
4510 * It's possible that we have MIXED_GROUP flag but no
4511 * block group is mixed. Just skip such block group.
4512 */
4513 btrfs_release_block_group(block_group, ffe_ctl->delalloc);
4514 continue;
4515 }
4516
4517have_block_group:
4518 trace_btrfs_find_free_extent_have_block_group(root, ffe_ctl, block_group);
4519 ffe_ctl->cached = btrfs_block_group_done(block_group);
4520 if (unlikely(!ffe_ctl->cached)) {
4521 ffe_ctl->have_caching_bg = true;
4522 ret = btrfs_cache_block_group(block_group, false);
4523
4524 /*
4525 * If we get ENOMEM here or something else we want to
4526 * try other block groups, because it may not be fatal.
4527 * However if we can't find anything else we need to
4528 * save our return here so that we return the actual
4529 * error that caused problems, not ENOSPC.
4530 */
4531 if (ret < 0) {
4532 if (!cache_block_group_error)
4533 cache_block_group_error = ret;
4534 ret = 0;
4535 goto loop;
4536 }
4537 ret = 0;
4538 }
4539
4540 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR)) {
4541 if (!cache_block_group_error)
4542 cache_block_group_error = -EIO;
4543 goto loop;
4544 }
4545
4546 if (!find_free_extent_check_size_class(ffe_ctl, block_group))
4547 goto loop;
4548
4549 bg_ret = NULL;
4550 ret = do_allocation(block_group, ffe_ctl, &bg_ret);
4551 if (ret > 0)
4552 goto loop;
4553
4554 if (bg_ret && bg_ret != block_group) {
4555 btrfs_release_block_group(block_group, ffe_ctl->delalloc);
4556 block_group = bg_ret;
4557 }
4558
4559 /* Checks */
4560 ffe_ctl->search_start = round_up(ffe_ctl->found_offset,
4561 fs_info->stripesize);
4562
4563 /* move on to the next group */
4564 if (ffe_ctl->search_start + ffe_ctl->num_bytes >
4565 block_group->start + block_group->length) {
4566 btrfs_add_free_space_unused(block_group,
4567 ffe_ctl->found_offset,
4568 ffe_ctl->num_bytes);
4569 goto loop;
4570 }
4571
4572 if (ffe_ctl->found_offset < ffe_ctl->search_start)
4573 btrfs_add_free_space_unused(block_group,
4574 ffe_ctl->found_offset,
4575 ffe_ctl->search_start - ffe_ctl->found_offset);
4576
4577 ret = btrfs_add_reserved_bytes(block_group, ffe_ctl->ram_bytes,
4578 ffe_ctl->num_bytes,
4579 ffe_ctl->delalloc,
4580 ffe_ctl->loop >= LOOP_WRONG_SIZE_CLASS);
4581 if (ret == -EAGAIN) {
4582 btrfs_add_free_space_unused(block_group,
4583 ffe_ctl->found_offset,
4584 ffe_ctl->num_bytes);
4585 goto loop;
4586 }
4587 btrfs_inc_block_group_reservations(block_group);
4588
4589 /* we are all good, lets return */
4590 ins->objectid = ffe_ctl->search_start;
4591 ins->offset = ffe_ctl->num_bytes;
4592
4593 trace_btrfs_reserve_extent(block_group, ffe_ctl);
4594 btrfs_release_block_group(block_group, ffe_ctl->delalloc);
4595 break;
4596loop:
4597 if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
4598 !ffe_ctl->retry_uncached) {
4599 ffe_ctl->retry_uncached = true;
4600 btrfs_wait_block_group_cache_progress(block_group,
4601 ffe_ctl->num_bytes +
4602 ffe_ctl->empty_cluster +
4603 ffe_ctl->empty_size);
4604 goto have_block_group;
4605 }
4606 release_block_group(block_group, ffe_ctl, ffe_ctl->delalloc);
4607 cond_resched();
4608 }
4609 up_read(&space_info->groups_sem);
4610
4611 ret = find_free_extent_update_loop(fs_info, ins, ffe_ctl, space_info,
4612 full_search);
4613 if (ret > 0)
4614 goto search;
4615
4616 if (ret == -ENOSPC && !cache_block_group_error) {
4617 /*
4618 * Use ffe_ctl->total_free_space as fallback if we can't find
4619 * any contiguous hole.
4620 */
4621 if (!ffe_ctl->max_extent_size)
4622 ffe_ctl->max_extent_size = ffe_ctl->total_free_space;
4623 spin_lock(&space_info->lock);
4624 space_info->max_extent_size = ffe_ctl->max_extent_size;
4625 spin_unlock(&space_info->lock);
4626 ins->offset = ffe_ctl->max_extent_size;
4627 } else if (ret == -ENOSPC) {
4628 ret = cache_block_group_error;
4629 }
4630 return ret;
4631}
4632
4633/*
4634 * Entry point to the extent allocator. Tries to find a hole that is at least
4635 * as big as @num_bytes.
4636 *
4637 * @root - The root that will contain this extent
4638 *
4639 * @ram_bytes - The amount of space in ram that @num_bytes take. This
4640 * is used for accounting purposes. This value differs
4641 * from @num_bytes only in the case of compressed extents.
4642 *
4643 * @num_bytes - Number of bytes to allocate on-disk.
4644 *
4645 * @min_alloc_size - Indicates the minimum amount of space that the
4646 * allocator should try to satisfy. In some cases
4647 * @num_bytes may be larger than what is required and if
4648 * the filesystem is fragmented then allocation fails.
4649 * However, the presence of @min_alloc_size gives a
4650 * chance to try and satisfy the smaller allocation.
4651 *
4652 * @empty_size - A hint that you plan on doing more COW. This is the
4653 * size in bytes the allocator should try to find free
4654 * next to the block it returns. This is just a hint and
4655 * may be ignored by the allocator.
4656 *
4657 * @hint_byte - Hint to the allocator to start searching above the byte
4658 * address passed. It might be ignored.
4659 *
4660 * @ins - This key is modified to record the found hole. It will
4661 * have the following values:
4662 * ins->objectid == start position
4663 * ins->flags = BTRFS_EXTENT_ITEM_KEY
4664 * ins->offset == the size of the hole.
4665 *
4666 * @is_data - Boolean flag indicating whether an extent is
4667 * allocated for data (true) or metadata (false)
4668 *
4669 * @delalloc - Boolean flag indicating whether this allocation is for
4670 * delalloc or not. If 'true' data_rwsem of block groups
4671 * is going to be acquired.
4672 *
4673 *
4674 * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
4675 * case -ENOSPC is returned then @ins->offset will contain the size of the
4676 * largest available hole the allocator managed to find.
4677 */
4678int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
4679 u64 num_bytes, u64 min_alloc_size,
4680 u64 empty_size, u64 hint_byte,
4681 struct btrfs_key *ins, bool is_data, bool delalloc)
4682{
4683 struct btrfs_fs_info *fs_info = root->fs_info;
4684 struct find_free_extent_ctl ffe_ctl = {};
4685 bool final_tried = num_bytes == min_alloc_size;
4686 u64 flags;
4687 int ret;
4688 bool for_treelog = (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID);
4689 bool for_data_reloc = (btrfs_is_data_reloc_root(root) && is_data);
4690
4691 flags = get_alloc_profile_by_root(root, is_data);
4692again:
4693 WARN_ON(num_bytes < fs_info->sectorsize);
4694
4695 ffe_ctl.ram_bytes = ram_bytes;
4696 ffe_ctl.num_bytes = num_bytes;
4697 ffe_ctl.min_alloc_size = min_alloc_size;
4698 ffe_ctl.empty_size = empty_size;
4699 ffe_ctl.flags = flags;
4700 ffe_ctl.delalloc = delalloc;
4701 ffe_ctl.hint_byte = hint_byte;
4702 ffe_ctl.for_treelog = for_treelog;
4703 ffe_ctl.for_data_reloc = for_data_reloc;
4704
4705 ret = find_free_extent(root, ins, &ffe_ctl);
4706 if (!ret && !is_data) {
4707 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
4708 } else if (ret == -ENOSPC) {
4709 if (!final_tried && ins->offset) {
4710 num_bytes = min(num_bytes >> 1, ins->offset);
4711 num_bytes = round_down(num_bytes,
4712 fs_info->sectorsize);
4713 num_bytes = max(num_bytes, min_alloc_size);
4714 ram_bytes = num_bytes;
4715 if (num_bytes == min_alloc_size)
4716 final_tried = true;
4717 goto again;
4718 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4719 struct btrfs_space_info *sinfo;
4720
4721 sinfo = btrfs_find_space_info(fs_info, flags);
4722 btrfs_err(fs_info,
4723 "allocation failed flags %llu, wanted %llu tree-log %d, relocation: %d",
4724 flags, num_bytes, for_treelog, for_data_reloc);
4725 if (sinfo)
4726 btrfs_dump_space_info(sinfo, num_bytes, 1);
4727 }
4728 }
4729
4730 return ret;
4731}
4732
4733int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len,
4734 bool is_delalloc)
4735{
4736 struct btrfs_block_group *cache;
4737
4738 cache = btrfs_lookup_block_group(fs_info, start);
4739 if (!cache) {
4740 btrfs_err(fs_info, "Unable to find block group for %llu",
4741 start);
4742 return -ENOSPC;
4743 }
4744
4745 btrfs_add_free_space(cache, start, len);
4746 btrfs_free_reserved_bytes(cache, len, is_delalloc);
4747 trace_btrfs_reserved_extent_free(fs_info, start, len);
4748
4749 btrfs_put_block_group(cache);
4750 return 0;
4751}
4752
4753int btrfs_pin_reserved_extent(struct btrfs_trans_handle *trans,
4754 const struct extent_buffer *eb)
4755{
4756 struct btrfs_block_group *cache;
4757 int ret = 0;
4758
4759 cache = btrfs_lookup_block_group(trans->fs_info, eb->start);
4760 if (!cache) {
4761 btrfs_err(trans->fs_info, "unable to find block group for %llu",
4762 eb->start);
4763 return -ENOSPC;
4764 }
4765
4766 ret = pin_down_extent(trans, cache, eb->start, eb->len, true);
4767 btrfs_put_block_group(cache);
4768 return ret;
4769}
4770
4771static int alloc_reserved_extent(struct btrfs_trans_handle *trans, u64 bytenr,
4772 u64 num_bytes)
4773{
4774 struct btrfs_fs_info *fs_info = trans->fs_info;
4775 int ret;
4776
4777 ret = btrfs_remove_from_free_space_tree(trans, bytenr, num_bytes);
4778 if (ret)
4779 return ret;
4780
4781 ret = btrfs_update_block_group(trans, bytenr, num_bytes, true);
4782 if (ret) {
4783 ASSERT(!ret);
4784 btrfs_err(fs_info, "update block group failed for %llu %llu",
4785 bytenr, num_bytes);
4786 return ret;
4787 }
4788
4789 trace_btrfs_reserved_extent_alloc(fs_info, bytenr, num_bytes);
4790 return 0;
4791}
4792
4793static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4794 u64 parent, u64 root_objectid,
4795 u64 flags, u64 owner, u64 offset,
4796 struct btrfs_key *ins, int ref_mod, u64 oref_root)
4797{
4798 struct btrfs_fs_info *fs_info = trans->fs_info;
4799 struct btrfs_root *extent_root;
4800 int ret;
4801 struct btrfs_extent_item *extent_item;
4802 struct btrfs_extent_owner_ref *oref;
4803 struct btrfs_extent_inline_ref *iref;
4804 struct btrfs_path *path;
4805 struct extent_buffer *leaf;
4806 int type;
4807 u32 size;
4808 const bool simple_quota = (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE);
4809
4810 if (parent > 0)
4811 type = BTRFS_SHARED_DATA_REF_KEY;
4812 else
4813 type = BTRFS_EXTENT_DATA_REF_KEY;
4814
4815 size = sizeof(*extent_item);
4816 if (simple_quota)
4817 size += btrfs_extent_inline_ref_size(BTRFS_EXTENT_OWNER_REF_KEY);
4818 size += btrfs_extent_inline_ref_size(type);
4819
4820 path = btrfs_alloc_path();
4821 if (!path)
4822 return -ENOMEM;
4823
4824 extent_root = btrfs_extent_root(fs_info, ins->objectid);
4825 ret = btrfs_insert_empty_item(trans, extent_root, path, ins, size);
4826 if (ret) {
4827 btrfs_free_path(path);
4828 return ret;
4829 }
4830
4831 leaf = path->nodes[0];
4832 extent_item = btrfs_item_ptr(leaf, path->slots[0],
4833 struct btrfs_extent_item);
4834 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
4835 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4836 btrfs_set_extent_flags(leaf, extent_item,
4837 flags | BTRFS_EXTENT_FLAG_DATA);
4838
4839 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4840 if (simple_quota) {
4841 btrfs_set_extent_inline_ref_type(leaf, iref, BTRFS_EXTENT_OWNER_REF_KEY);
4842 oref = (struct btrfs_extent_owner_ref *)(&iref->offset);
4843 btrfs_set_extent_owner_ref_root_id(leaf, oref, oref_root);
4844 iref = (struct btrfs_extent_inline_ref *)(oref + 1);
4845 }
4846 btrfs_set_extent_inline_ref_type(leaf, iref, type);
4847
4848 if (parent > 0) {
4849 struct btrfs_shared_data_ref *ref;
4850 ref = (struct btrfs_shared_data_ref *)(iref + 1);
4851 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
4852 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
4853 } else {
4854 struct btrfs_extent_data_ref *ref;
4855 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
4856 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
4857 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
4858 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
4859 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
4860 }
4861
4862 btrfs_free_path(path);
4863
4864 return alloc_reserved_extent(trans, ins->objectid, ins->offset);
4865}
4866
4867static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
4868 const struct btrfs_delayed_ref_node *node,
4869 struct btrfs_delayed_extent_op *extent_op)
4870{
4871 struct btrfs_fs_info *fs_info = trans->fs_info;
4872 struct btrfs_root *extent_root;
4873 int ret;
4874 struct btrfs_extent_item *extent_item;
4875 struct btrfs_key extent_key;
4876 struct btrfs_tree_block_info *block_info;
4877 struct btrfs_extent_inline_ref *iref;
4878 struct btrfs_path *path;
4879 struct extent_buffer *leaf;
4880 u32 size = sizeof(*extent_item) + sizeof(*iref);
4881 const u64 flags = (extent_op ? extent_op->flags_to_set : 0);
4882 /* The owner of a tree block is the level. */
4883 int level = btrfs_delayed_ref_owner(node);
4884 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
4885
4886 extent_key.objectid = node->bytenr;
4887 if (skinny_metadata) {
4888 /* The owner of a tree block is the level. */
4889 extent_key.offset = level;
4890 extent_key.type = BTRFS_METADATA_ITEM_KEY;
4891 } else {
4892 extent_key.offset = node->num_bytes;
4893 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
4894 size += sizeof(*block_info);
4895 }
4896
4897 path = btrfs_alloc_path();
4898 if (!path)
4899 return -ENOMEM;
4900
4901 extent_root = btrfs_extent_root(fs_info, extent_key.objectid);
4902 ret = btrfs_insert_empty_item(trans, extent_root, path, &extent_key,
4903 size);
4904 if (ret) {
4905 btrfs_free_path(path);
4906 return ret;
4907 }
4908
4909 leaf = path->nodes[0];
4910 extent_item = btrfs_item_ptr(leaf, path->slots[0],
4911 struct btrfs_extent_item);
4912 btrfs_set_extent_refs(leaf, extent_item, 1);
4913 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4914 btrfs_set_extent_flags(leaf, extent_item,
4915 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
4916
4917 if (skinny_metadata) {
4918 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4919 } else {
4920 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
4921 btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
4922 btrfs_set_tree_block_level(leaf, block_info, level);
4923 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
4924 }
4925
4926 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
4927 btrfs_set_extent_inline_ref_type(leaf, iref,
4928 BTRFS_SHARED_BLOCK_REF_KEY);
4929 btrfs_set_extent_inline_ref_offset(leaf, iref, node->parent);
4930 } else {
4931 btrfs_set_extent_inline_ref_type(leaf, iref,
4932 BTRFS_TREE_BLOCK_REF_KEY);
4933 btrfs_set_extent_inline_ref_offset(leaf, iref, node->ref_root);
4934 }
4935
4936 btrfs_free_path(path);
4937
4938 return alloc_reserved_extent(trans, node->bytenr, fs_info->nodesize);
4939}
4940
4941int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4942 struct btrfs_root *root, u64 owner,
4943 u64 offset, u64 ram_bytes,
4944 struct btrfs_key *ins)
4945{
4946 struct btrfs_ref generic_ref = {
4947 .action = BTRFS_ADD_DELAYED_EXTENT,
4948 .bytenr = ins->objectid,
4949 .num_bytes = ins->offset,
4950 .owning_root = btrfs_root_id(root),
4951 .ref_root = btrfs_root_id(root),
4952 };
4953
4954 ASSERT(generic_ref.ref_root != BTRFS_TREE_LOG_OBJECTID);
4955
4956 if (btrfs_is_data_reloc_root(root) && btrfs_is_fstree(root->relocation_src_root))
4957 generic_ref.owning_root = root->relocation_src_root;
4958
4959 btrfs_init_data_ref(&generic_ref, owner, offset, 0, false);
4960 btrfs_ref_tree_mod(root->fs_info, &generic_ref);
4961
4962 return btrfs_add_delayed_data_ref(trans, &generic_ref, ram_bytes);
4963}
4964
4965/*
4966 * this is used by the tree logging recovery code. It records that
4967 * an extent has been allocated and makes sure to clear the free
4968 * space cache bits as well
4969 */
4970int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
4971 u64 root_objectid, u64 owner, u64 offset,
4972 struct btrfs_key *ins)
4973{
4974 struct btrfs_fs_info *fs_info = trans->fs_info;
4975 int ret;
4976 struct btrfs_block_group *block_group;
4977 struct btrfs_space_info *space_info;
4978 const struct btrfs_squota_delta delta = {
4979 .root = root_objectid,
4980 .num_bytes = ins->offset,
4981 .generation = trans->transid,
4982 .is_data = true,
4983 .is_inc = true,
4984 };
4985
4986 /*
4987 * Mixed block groups will exclude before processing the log so we only
4988 * need to do the exclude dance if this fs isn't mixed.
4989 */
4990 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
4991 ret = __exclude_logged_extent(fs_info, ins->objectid,
4992 ins->offset);
4993 if (ret)
4994 return ret;
4995 }
4996
4997 block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
4998 if (!block_group)
4999 return -EINVAL;
5000
5001 space_info = block_group->space_info;
5002 spin_lock(&space_info->lock);
5003 spin_lock(&block_group->lock);
5004 space_info->bytes_reserved += ins->offset;
5005 block_group->reserved += ins->offset;
5006 spin_unlock(&block_group->lock);
5007 spin_unlock(&space_info->lock);
5008
5009 ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
5010 offset, ins, 1, root_objectid);
5011 if (ret)
5012 btrfs_pin_extent(trans, ins->objectid, ins->offset);
5013 ret = btrfs_record_squota_delta(fs_info, &delta);
5014 btrfs_put_block_group(block_group);
5015 return ret;
5016}
5017
5018#ifdef CONFIG_BTRFS_DEBUG
5019/*
5020 * Extra safety check in case the extent tree is corrupted and extent allocator
5021 * chooses to use a tree block which is already used and locked.
5022 */
5023static bool check_eb_lock_owner(const struct extent_buffer *eb)
5024{
5025 if (eb->lock_owner == current->pid) {
5026 btrfs_err_rl(eb->fs_info,
5027"tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
5028 eb->start, btrfs_header_owner(eb), current->pid);
5029 return true;
5030 }
5031 return false;
5032}
5033#else
5034static bool check_eb_lock_owner(struct extent_buffer *eb)
5035{
5036 return false;
5037}
5038#endif
5039
5040static struct extent_buffer *
5041btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
5042 u64 bytenr, int level, u64 owner,
5043 enum btrfs_lock_nesting nest)
5044{
5045 struct btrfs_fs_info *fs_info = root->fs_info;
5046 struct extent_buffer *buf;
5047 u64 lockdep_owner = owner;
5048
5049 buf = btrfs_find_create_tree_block(fs_info, bytenr, owner, level);
5050 if (IS_ERR(buf))
5051 return buf;
5052
5053 if (unlikely(check_eb_lock_owner(buf))) {
5054 free_extent_buffer(buf);
5055 return ERR_PTR(-EUCLEAN);
5056 }
5057
5058 /*
5059 * The reloc trees are just snapshots, so we need them to appear to be
5060 * just like any other fs tree WRT lockdep.
5061 *
5062 * The exception however is in replace_path() in relocation, where we
5063 * hold the lock on the original fs root and then search for the reloc
5064 * root. At that point we need to make sure any reloc root buffers are
5065 * set to the BTRFS_TREE_RELOC_OBJECTID lockdep class in order to make
5066 * lockdep happy.
5067 */
5068 if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID &&
5069 !test_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &root->state))
5070 lockdep_owner = BTRFS_FS_TREE_OBJECTID;
5071
5072 /* btrfs_clear_buffer_dirty() accesses generation field. */
5073 btrfs_set_header_generation(buf, trans->transid);
5074
5075 /*
5076 * This needs to stay, because we could allocate a freed block from an
5077 * old tree into a new tree, so we need to make sure this new block is
5078 * set to the appropriate level and owner.
5079 */
5080 btrfs_set_buffer_lockdep_class(lockdep_owner, buf, level);
5081
5082 btrfs_tree_lock_nested(buf, nest);
5083 btrfs_clear_buffer_dirty(trans, buf);
5084 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
5085 clear_bit(EXTENT_BUFFER_ZONED_ZEROOUT, &buf->bflags);
5086
5087 set_extent_buffer_uptodate(buf);
5088
5089 memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
5090 btrfs_set_header_level(buf, level);
5091 btrfs_set_header_bytenr(buf, buf->start);
5092 btrfs_set_header_generation(buf, trans->transid);
5093 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
5094 btrfs_set_header_owner(buf, owner);
5095 write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
5096 write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
5097 if (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID) {
5098 buf->log_index = root->log_transid % 2;
5099 /*
5100 * we allow two log transactions at a time, use different
5101 * EXTENT bit to differentiate dirty pages.
5102 */
5103 if (buf->log_index == 0)
5104 btrfs_set_extent_bit(&root->dirty_log_pages, buf->start,
5105 buf->start + buf->len - 1,
5106 EXTENT_DIRTY_LOG1, NULL);
5107 else
5108 btrfs_set_extent_bit(&root->dirty_log_pages, buf->start,
5109 buf->start + buf->len - 1,
5110 EXTENT_DIRTY_LOG2, NULL);
5111 } else {
5112 buf->log_index = -1;
5113 btrfs_set_extent_bit(&trans->transaction->dirty_pages, buf->start,
5114 buf->start + buf->len - 1, EXTENT_DIRTY, NULL);
5115 }
5116 /* this returns a buffer locked for blocking */
5117 return buf;
5118}
5119
5120/*
5121 * finds a free extent and does all the dirty work required for allocation
5122 * returns the tree buffer or an ERR_PTR on error.
5123 */
5124struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
5125 struct btrfs_root *root,
5126 u64 parent, u64 root_objectid,
5127 const struct btrfs_disk_key *key,
5128 int level, u64 hint,
5129 u64 empty_size,
5130 u64 reloc_src_root,
5131 enum btrfs_lock_nesting nest)
5132{
5133 struct btrfs_fs_info *fs_info = root->fs_info;
5134 struct btrfs_key ins;
5135 struct btrfs_block_rsv *block_rsv;
5136 struct extent_buffer *buf;
5137 u64 flags = 0;
5138 int ret;
5139 u32 blocksize = fs_info->nodesize;
5140 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
5141 u64 owning_root;
5142
5143#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
5144 if (btrfs_is_testing(fs_info)) {
5145 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
5146 level, root_objectid, nest);
5147 if (!IS_ERR(buf))
5148 root->alloc_bytenr += blocksize;
5149 return buf;
5150 }
5151#endif
5152
5153 block_rsv = btrfs_use_block_rsv(trans, root, blocksize);
5154 if (IS_ERR(block_rsv))
5155 return ERR_CAST(block_rsv);
5156
5157 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
5158 empty_size, hint, &ins, false, false);
5159 if (ret)
5160 goto out_unuse;
5161
5162 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
5163 root_objectid, nest);
5164 if (IS_ERR(buf)) {
5165 ret = PTR_ERR(buf);
5166 goto out_free_reserved;
5167 }
5168 owning_root = btrfs_header_owner(buf);
5169
5170 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
5171 if (parent == 0)
5172 parent = ins.objectid;
5173 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5174 owning_root = reloc_src_root;
5175 } else
5176 BUG_ON(parent > 0);
5177
5178 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
5179 struct btrfs_delayed_extent_op *extent_op;
5180 struct btrfs_ref generic_ref = {
5181 .action = BTRFS_ADD_DELAYED_EXTENT,
5182 .bytenr = ins.objectid,
5183 .num_bytes = ins.offset,
5184 .parent = parent,
5185 .owning_root = owning_root,
5186 .ref_root = root_objectid,
5187 };
5188
5189 if (!skinny_metadata || flags != 0) {
5190 extent_op = btrfs_alloc_delayed_extent_op();
5191 if (!extent_op) {
5192 ret = -ENOMEM;
5193 goto out_free_buf;
5194 }
5195 if (key)
5196 memcpy(&extent_op->key, key, sizeof(extent_op->key));
5197 else
5198 memset(&extent_op->key, 0, sizeof(extent_op->key));
5199 extent_op->flags_to_set = flags;
5200 extent_op->update_key = (skinny_metadata ? false : true);
5201 extent_op->update_flags = (flags != 0);
5202 } else {
5203 extent_op = NULL;
5204 }
5205
5206 btrfs_init_tree_ref(&generic_ref, level, btrfs_root_id(root), false);
5207 btrfs_ref_tree_mod(fs_info, &generic_ref);
5208 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, extent_op);
5209 if (ret) {
5210 btrfs_free_delayed_extent_op(extent_op);
5211 goto out_free_buf;
5212 }
5213 }
5214 return buf;
5215
5216out_free_buf:
5217 btrfs_tree_unlock(buf);
5218 free_extent_buffer(buf);
5219out_free_reserved:
5220 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, false);
5221out_unuse:
5222 btrfs_unuse_block_rsv(fs_info, block_rsv, blocksize);
5223 return ERR_PTR(ret);
5224}
5225
5226struct walk_control {
5227 u64 refs[BTRFS_MAX_LEVEL];
5228 u64 flags[BTRFS_MAX_LEVEL];
5229 struct btrfs_key update_progress;
5230 struct btrfs_key drop_progress;
5231 int drop_level;
5232 int stage;
5233 int level;
5234 int shared_level;
5235 int update_ref;
5236 int keep_locks;
5237 int reada_slot;
5238 int reada_count;
5239 int restarted;
5240 /* Indicate that extent info needs to be looked up when walking the tree. */
5241 int lookup_info;
5242};
5243
5244/*
5245 * This is our normal stage. We are traversing blocks the current snapshot owns
5246 * and we are dropping any of our references to any children we are able to, and
5247 * then freeing the block once we've processed all of the children.
5248 */
5249#define DROP_REFERENCE 1
5250
5251/*
5252 * We enter this stage when we have to walk into a child block (meaning we can't
5253 * simply drop our reference to it from our current parent node) and there are
5254 * more than one reference on it. If we are the owner of any of the children
5255 * blocks from the current parent node then we have to do the FULL_BACKREF dance
5256 * on them in order to drop our normal ref and add the shared ref.
5257 */
5258#define UPDATE_BACKREF 2
5259
5260/*
5261 * Decide if we need to walk down into this node to adjust the references.
5262 *
5263 * @root: the root we are currently deleting
5264 * @wc: the walk control for this deletion
5265 * @eb: the parent eb that we're currently visiting
5266 * @refs: the number of refs for wc->level - 1
5267 * @flags: the flags for wc->level - 1
5268 * @slot: the slot in the eb that we're currently checking
5269 *
5270 * This is meant to be called when we're evaluating if a node we point to at
5271 * wc->level should be read and walked into, or if we can simply delete our
5272 * reference to it. We return true if we should walk into the node, false if we
5273 * can skip it.
5274 *
5275 * We have assertions in here to make sure this is called correctly. We assume
5276 * that sanity checking on the blocks read to this point has been done, so any
5277 * corrupted file systems must have been caught before calling this function.
5278 */
5279static bool visit_node_for_delete(struct btrfs_root *root, struct walk_control *wc,
5280 struct extent_buffer *eb, u64 flags, int slot)
5281{
5282 struct btrfs_key key;
5283 u64 generation;
5284 int level = wc->level;
5285
5286 ASSERT(level > 0);
5287 ASSERT(wc->refs[level - 1] > 0);
5288
5289 /*
5290 * The update backref stage we only want to skip if we already have
5291 * FULL_BACKREF set, otherwise we need to read.
5292 */
5293 if (wc->stage == UPDATE_BACKREF) {
5294 if (level == 1 && flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5295 return false;
5296 return true;
5297 }
5298
5299 /*
5300 * We're the last ref on this block, we must walk into it and process
5301 * any refs it's pointing at.
5302 */
5303 if (wc->refs[level - 1] == 1)
5304 return true;
5305
5306 /*
5307 * If we're already FULL_BACKREF then we know we can just drop our
5308 * current reference.
5309 */
5310 if (level == 1 && flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5311 return false;
5312
5313 /*
5314 * This block is older than our creation generation, we can drop our
5315 * reference to it.
5316 */
5317 generation = btrfs_node_ptr_generation(eb, slot);
5318 if (!wc->update_ref || generation <= btrfs_root_origin_generation(root))
5319 return false;
5320
5321 /*
5322 * This block was processed from a previous snapshot deletion run, we
5323 * can skip it.
5324 */
5325 btrfs_node_key_to_cpu(eb, &key, slot);
5326 if (btrfs_comp_cpu_keys(&key, &wc->update_progress) < 0)
5327 return false;
5328
5329 /* All other cases we need to wander into the node. */
5330 return true;
5331}
5332
5333static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
5334 struct btrfs_root *root,
5335 struct walk_control *wc,
5336 struct btrfs_path *path)
5337{
5338 struct btrfs_fs_info *fs_info = root->fs_info;
5339 u64 bytenr;
5340 u64 generation;
5341 u64 refs;
5342 u64 flags;
5343 u32 nritems;
5344 struct extent_buffer *eb;
5345 int ret;
5346 int slot;
5347 int nread = 0;
5348
5349 if (path->slots[wc->level] < wc->reada_slot) {
5350 wc->reada_count = wc->reada_count * 2 / 3;
5351 wc->reada_count = max(wc->reada_count, 2);
5352 } else {
5353 wc->reada_count = wc->reada_count * 3 / 2;
5354 wc->reada_count = min_t(int, wc->reada_count,
5355 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
5356 }
5357
5358 eb = path->nodes[wc->level];
5359 nritems = btrfs_header_nritems(eb);
5360
5361 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
5362 if (nread >= wc->reada_count)
5363 break;
5364
5365 cond_resched();
5366 bytenr = btrfs_node_blockptr(eb, slot);
5367 generation = btrfs_node_ptr_generation(eb, slot);
5368
5369 if (slot == path->slots[wc->level])
5370 goto reada;
5371
5372 if (wc->stage == UPDATE_BACKREF &&
5373 generation <= btrfs_root_origin_generation(root))
5374 continue;
5375
5376 /* We don't lock the tree block, it's OK to be racy here */
5377 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
5378 wc->level - 1, 1, &refs,
5379 &flags, NULL);
5380 /* We don't care about errors in readahead. */
5381 if (ret < 0)
5382 continue;
5383
5384 /*
5385 * This could be racey, it's conceivable that we raced and end
5386 * up with a bogus refs count, if that's the case just skip, if
5387 * we are actually corrupt we will notice when we look up
5388 * everything again with our locks.
5389 */
5390 if (refs == 0)
5391 continue;
5392
5393 /* If we don't need to visit this node don't reada. */
5394 if (!visit_node_for_delete(root, wc, eb, flags, slot))
5395 continue;
5396reada:
5397 btrfs_readahead_node_child(eb, slot);
5398 nread++;
5399 }
5400 wc->reada_slot = slot;
5401}
5402
5403/*
5404 * helper to process tree block while walking down the tree.
5405 *
5406 * when wc->stage == UPDATE_BACKREF, this function updates
5407 * back refs for pointers in the block.
5408 *
5409 * NOTE: return value 1 means we should stop walking down.
5410 */
5411static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
5412 struct btrfs_root *root,
5413 struct btrfs_path *path,
5414 struct walk_control *wc)
5415{
5416 struct btrfs_fs_info *fs_info = root->fs_info;
5417 int level = wc->level;
5418 struct extent_buffer *eb = path->nodes[level];
5419 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5420 int ret;
5421
5422 if (wc->stage == UPDATE_BACKREF && btrfs_header_owner(eb) != btrfs_root_id(root))
5423 return 1;
5424
5425 /*
5426 * when reference count of tree block is 1, it won't increase
5427 * again. once full backref flag is set, we never clear it.
5428 */
5429 if (wc->lookup_info &&
5430 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
5431 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
5432 ASSERT(path->locks[level]);
5433 ret = btrfs_lookup_extent_info(trans, fs_info,
5434 eb->start, level, 1,
5435 &wc->refs[level],
5436 &wc->flags[level],
5437 NULL);
5438 if (ret)
5439 return ret;
5440 if (unlikely(wc->refs[level] == 0)) {
5441 btrfs_err(fs_info, "bytenr %llu has 0 references, expect > 0",
5442 eb->start);
5443 return -EUCLEAN;
5444 }
5445 }
5446
5447 if (wc->stage == DROP_REFERENCE) {
5448 if (wc->refs[level] > 1)
5449 return 1;
5450
5451 if (path->locks[level] && !wc->keep_locks) {
5452 btrfs_tree_unlock_rw(eb, path->locks[level]);
5453 path->locks[level] = 0;
5454 }
5455 return 0;
5456 }
5457
5458 /* wc->stage == UPDATE_BACKREF */
5459 if (!(wc->flags[level] & flag)) {
5460 ASSERT(path->locks[level]);
5461 ret = btrfs_inc_ref(trans, root, eb, 1);
5462 if (unlikely(ret)) {
5463 btrfs_abort_transaction(trans, ret);
5464 return ret;
5465 }
5466 ret = btrfs_dec_ref(trans, root, eb, 0);
5467 if (unlikely(ret)) {
5468 btrfs_abort_transaction(trans, ret);
5469 return ret;
5470 }
5471 ret = btrfs_set_disk_extent_flags(trans, eb, flag);
5472 if (unlikely(ret)) {
5473 btrfs_abort_transaction(trans, ret);
5474 return ret;
5475 }
5476 wc->flags[level] |= flag;
5477 }
5478
5479 /*
5480 * the block is shared by multiple trees, so it's not good to
5481 * keep the tree lock
5482 */
5483 if (path->locks[level] && level > 0) {
5484 btrfs_tree_unlock_rw(eb, path->locks[level]);
5485 path->locks[level] = 0;
5486 }
5487 return 0;
5488}
5489
5490/*
5491 * This is used to verify a ref exists for this root to deal with a bug where we
5492 * would have a drop_progress key that hadn't been updated properly.
5493 */
5494static int check_ref_exists(struct btrfs_trans_handle *trans,
5495 struct btrfs_root *root, u64 bytenr, u64 parent,
5496 int level)
5497{
5498 struct btrfs_delayed_ref_root *delayed_refs;
5499 struct btrfs_delayed_ref_head *head;
5500 BTRFS_PATH_AUTO_FREE(path);
5501 struct btrfs_extent_inline_ref *iref;
5502 int ret;
5503 bool exists = false;
5504
5505 path = btrfs_alloc_path();
5506 if (!path)
5507 return -ENOMEM;
5508again:
5509 ret = lookup_extent_backref(trans, path, &iref, bytenr,
5510 root->fs_info->nodesize, parent,
5511 btrfs_root_id(root), level, 0);
5512 if (ret != -ENOENT) {
5513 /*
5514 * If we get 0 then we found our reference, return 1, else
5515 * return the error if it's not -ENOENT;
5516 */
5517 return (ret < 0 ) ? ret : 1;
5518 }
5519
5520 /*
5521 * We could have a delayed ref with this reference, so look it up while
5522 * we're holding the path open to make sure we don't race with the
5523 * delayed ref running.
5524 */
5525 delayed_refs = &trans->transaction->delayed_refs;
5526 spin_lock(&delayed_refs->lock);
5527 head = btrfs_find_delayed_ref_head(root->fs_info, delayed_refs, bytenr);
5528 if (!head)
5529 goto out;
5530 if (!mutex_trylock(&head->mutex)) {
5531 /*
5532 * We're contended, means that the delayed ref is running, get a
5533 * reference and wait for the ref head to be complete and then
5534 * try again.
5535 */
5536 refcount_inc(&head->refs);
5537 spin_unlock(&delayed_refs->lock);
5538
5539 btrfs_release_path(path);
5540
5541 mutex_lock(&head->mutex);
5542 mutex_unlock(&head->mutex);
5543 btrfs_put_delayed_ref_head(head);
5544 goto again;
5545 }
5546
5547 exists = btrfs_find_delayed_tree_ref(head, btrfs_root_id(root), parent);
5548 mutex_unlock(&head->mutex);
5549out:
5550 spin_unlock(&delayed_refs->lock);
5551 return exists ? 1 : 0;
5552}
5553
5554/*
5555 * We may not have an uptodate block, so if we are going to walk down into this
5556 * block we need to drop the lock, read it off of the disk, re-lock it and
5557 * return to continue dropping the snapshot.
5558 */
5559static int check_next_block_uptodate(struct btrfs_trans_handle *trans,
5560 struct btrfs_root *root,
5561 struct btrfs_path *path,
5562 struct walk_control *wc,
5563 struct extent_buffer *next)
5564{
5565 struct btrfs_tree_parent_check check = { 0 };
5566 u64 generation;
5567 int level = wc->level;
5568 int ret;
5569
5570 btrfs_assert_tree_write_locked(next);
5571
5572 generation = btrfs_node_ptr_generation(path->nodes[level], path->slots[level]);
5573
5574 if (btrfs_buffer_uptodate(next, generation, false))
5575 return 0;
5576
5577 check.level = level - 1;
5578 check.transid = generation;
5579 check.owner_root = btrfs_root_id(root);
5580 check.has_first_key = true;
5581 btrfs_node_key_to_cpu(path->nodes[level], &check.first_key, path->slots[level]);
5582
5583 btrfs_tree_unlock(next);
5584 if (level == 1)
5585 reada_walk_down(trans, root, wc, path);
5586 ret = btrfs_read_extent_buffer(next, &check);
5587 if (ret) {
5588 free_extent_buffer(next);
5589 return ret;
5590 }
5591 btrfs_tree_lock(next);
5592 wc->lookup_info = 1;
5593 return 0;
5594}
5595
5596/*
5597 * If we determine that we don't have to visit wc->level - 1 then we need to
5598 * determine if we can drop our reference.
5599 *
5600 * If we are UPDATE_BACKREF then we will not, we need to update our backrefs.
5601 *
5602 * If we are DROP_REFERENCE this will figure out if we need to drop our current
5603 * reference, skipping it if we dropped it from a previous uncompleted drop, or
5604 * dropping it if we still have a reference to it.
5605 */
5606static int maybe_drop_reference(struct btrfs_trans_handle *trans, struct btrfs_root *root,
5607 struct btrfs_path *path, struct walk_control *wc,
5608 struct extent_buffer *next, u64 owner_root)
5609{
5610 struct btrfs_ref ref = {
5611 .action = BTRFS_DROP_DELAYED_REF,
5612 .bytenr = next->start,
5613 .num_bytes = root->fs_info->nodesize,
5614 .owning_root = owner_root,
5615 .ref_root = btrfs_root_id(root),
5616 };
5617 int level = wc->level;
5618 int ret;
5619
5620 /* We are UPDATE_BACKREF, we're not dropping anything. */
5621 if (wc->stage == UPDATE_BACKREF)
5622 return 0;
5623
5624 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5625 ref.parent = path->nodes[level]->start;
5626 } else {
5627 ASSERT(btrfs_root_id(root) == btrfs_header_owner(path->nodes[level]));
5628 if (unlikely(btrfs_root_id(root) != btrfs_header_owner(path->nodes[level]))) {
5629 btrfs_err(root->fs_info, "mismatched block owner");
5630 return -EIO;
5631 }
5632 }
5633
5634 /*
5635 * If we had a drop_progress we need to verify the refs are set as
5636 * expected. If we find our ref then we know that from here on out
5637 * everything should be correct, and we can clear the
5638 * ->restarted flag.
5639 */
5640 if (wc->restarted) {
5641 ret = check_ref_exists(trans, root, next->start, ref.parent,
5642 level - 1);
5643 if (ret <= 0)
5644 return ret;
5645 ret = 0;
5646 wc->restarted = 0;
5647 }
5648
5649 /*
5650 * Reloc tree doesn't contribute to qgroup numbers, and we have already
5651 * accounted them at merge time (replace_path), thus we could skip
5652 * expensive subtree trace here.
5653 */
5654 if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID &&
5655 wc->refs[level - 1] > 1) {
5656 u64 generation = btrfs_node_ptr_generation(path->nodes[level],
5657 path->slots[level]);
5658
5659 ret = btrfs_qgroup_trace_subtree(trans, next, generation, level - 1);
5660 if (ret) {
5661 btrfs_err_rl(root->fs_info,
5662"error %d accounting shared subtree, quota is out of sync, rescan required",
5663 ret);
5664 }
5665 }
5666
5667 /*
5668 * We need to update the next key in our walk control so we can update
5669 * the drop_progress key accordingly. We don't care if find_next_key
5670 * doesn't find a key because that means we're at the end and are going
5671 * to clean up now.
5672 */
5673 wc->drop_level = level;
5674 find_next_key(path, level, &wc->drop_progress);
5675
5676 btrfs_init_tree_ref(&ref, level - 1, 0, false);
5677 return btrfs_free_extent(trans, &ref);
5678}
5679
5680/*
5681 * helper to process tree block pointer.
5682 *
5683 * when wc->stage == DROP_REFERENCE, this function checks
5684 * reference count of the block pointed to. if the block
5685 * is shared and we need update back refs for the subtree
5686 * rooted at the block, this function changes wc->stage to
5687 * UPDATE_BACKREF. if the block is shared and there is no
5688 * need to update back, this function drops the reference
5689 * to the block.
5690 *
5691 * NOTE: return value 1 means we should stop walking down.
5692 */
5693static noinline int do_walk_down(struct btrfs_trans_handle *trans,
5694 struct btrfs_root *root,
5695 struct btrfs_path *path,
5696 struct walk_control *wc)
5697{
5698 struct btrfs_fs_info *fs_info = root->fs_info;
5699 u64 bytenr;
5700 u64 generation;
5701 u64 owner_root = 0;
5702 struct extent_buffer *next;
5703 int level = wc->level;
5704 int ret = 0;
5705
5706 generation = btrfs_node_ptr_generation(path->nodes[level],
5707 path->slots[level]);
5708 /*
5709 * if the lower level block was created before the snapshot
5710 * was created, we know there is no need to update back refs
5711 * for the subtree
5712 */
5713 if (wc->stage == UPDATE_BACKREF &&
5714 generation <= btrfs_root_origin_generation(root)) {
5715 wc->lookup_info = 1;
5716 return 1;
5717 }
5718
5719 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
5720
5721 next = btrfs_find_create_tree_block(fs_info, bytenr, btrfs_root_id(root),
5722 level - 1);
5723 if (IS_ERR(next))
5724 return PTR_ERR(next);
5725
5726 btrfs_tree_lock(next);
5727
5728 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
5729 &wc->refs[level - 1],
5730 &wc->flags[level - 1],
5731 &owner_root);
5732 if (ret < 0)
5733 goto out_unlock;
5734
5735 if (unlikely(wc->refs[level - 1] == 0)) {
5736 btrfs_err(fs_info, "bytenr %llu has 0 references, expect > 0",
5737 bytenr);
5738 ret = -EUCLEAN;
5739 goto out_unlock;
5740 }
5741 wc->lookup_info = 0;
5742
5743 /* If we don't have to walk into this node skip it. */
5744 if (!visit_node_for_delete(root, wc, path->nodes[level],
5745 wc->flags[level - 1], path->slots[level]))
5746 goto skip;
5747
5748 /*
5749 * We have to walk down into this node, and if we're currently at the
5750 * DROP_REFERENCE stage and this block is shared then we need to switch
5751 * to the UPDATE_BACKREF stage in order to convert to FULL_BACKREF.
5752 */
5753 if (wc->stage == DROP_REFERENCE && wc->refs[level - 1] > 1) {
5754 wc->stage = UPDATE_BACKREF;
5755 wc->shared_level = level - 1;
5756 }
5757
5758 ret = check_next_block_uptodate(trans, root, path, wc, next);
5759 if (ret)
5760 return ret;
5761
5762 level--;
5763 ASSERT(level == btrfs_header_level(next));
5764 if (unlikely(level != btrfs_header_level(next))) {
5765 btrfs_err(root->fs_info, "mismatched level");
5766 ret = -EIO;
5767 goto out_unlock;
5768 }
5769 path->nodes[level] = next;
5770 path->slots[level] = 0;
5771 path->locks[level] = BTRFS_WRITE_LOCK;
5772 wc->level = level;
5773 if (wc->level == 1)
5774 wc->reada_slot = 0;
5775 return 0;
5776skip:
5777 ret = maybe_drop_reference(trans, root, path, wc, next, owner_root);
5778 if (ret)
5779 goto out_unlock;
5780 wc->refs[level - 1] = 0;
5781 wc->flags[level - 1] = 0;
5782 wc->lookup_info = 1;
5783 ret = 1;
5784
5785out_unlock:
5786 btrfs_tree_unlock(next);
5787 free_extent_buffer(next);
5788
5789 return ret;
5790}
5791
5792/*
5793 * helper to process tree block while walking up the tree.
5794 *
5795 * when wc->stage == DROP_REFERENCE, this function drops
5796 * reference count on the block.
5797 *
5798 * when wc->stage == UPDATE_BACKREF, this function changes
5799 * wc->stage back to DROP_REFERENCE if we changed wc->stage
5800 * to UPDATE_BACKREF previously while processing the block.
5801 *
5802 * NOTE: return value 1 means we should stop walking up.
5803 */
5804static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
5805 struct btrfs_root *root,
5806 struct btrfs_path *path,
5807 struct walk_control *wc)
5808{
5809 struct btrfs_fs_info *fs_info = root->fs_info;
5810 int ret = 0;
5811 int level = wc->level;
5812 struct extent_buffer *eb = path->nodes[level];
5813 u64 parent = 0;
5814
5815 if (wc->stage == UPDATE_BACKREF) {
5816 ASSERT(wc->shared_level >= level);
5817 if (level < wc->shared_level)
5818 goto out;
5819
5820 ret = find_next_key(path, level + 1, &wc->update_progress);
5821 if (ret > 0)
5822 wc->update_ref = 0;
5823
5824 wc->stage = DROP_REFERENCE;
5825 wc->shared_level = -1;
5826 path->slots[level] = 0;
5827
5828 /*
5829 * check reference count again if the block isn't locked.
5830 * we should start walking down the tree again if reference
5831 * count is one.
5832 */
5833 if (!path->locks[level]) {
5834 ASSERT(level > 0);
5835 btrfs_tree_lock(eb);
5836 path->locks[level] = BTRFS_WRITE_LOCK;
5837
5838 ret = btrfs_lookup_extent_info(trans, fs_info,
5839 eb->start, level, 1,
5840 &wc->refs[level],
5841 &wc->flags[level],
5842 NULL);
5843 if (ret < 0) {
5844 btrfs_tree_unlock_rw(eb, path->locks[level]);
5845 path->locks[level] = 0;
5846 return ret;
5847 }
5848 if (unlikely(wc->refs[level] == 0)) {
5849 btrfs_tree_unlock_rw(eb, path->locks[level]);
5850 btrfs_err(fs_info, "bytenr %llu has 0 references, expect > 0",
5851 eb->start);
5852 return -EUCLEAN;
5853 }
5854 if (wc->refs[level] == 1) {
5855 btrfs_tree_unlock_rw(eb, path->locks[level]);
5856 path->locks[level] = 0;
5857 return 1;
5858 }
5859 }
5860 }
5861
5862 /* wc->stage == DROP_REFERENCE */
5863 ASSERT(path->locks[level] || wc->refs[level] == 1);
5864
5865 if (wc->refs[level] == 1) {
5866 if (level == 0) {
5867 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5868 ret = btrfs_dec_ref(trans, root, eb, 1);
5869 if (ret) {
5870 btrfs_abort_transaction(trans, ret);
5871 return ret;
5872 }
5873 } else {
5874 ret = btrfs_dec_ref(trans, root, eb, 0);
5875 if (unlikely(ret)) {
5876 btrfs_abort_transaction(trans, ret);
5877 return ret;
5878 }
5879 }
5880 if (btrfs_is_fstree(btrfs_root_id(root))) {
5881 ret = btrfs_qgroup_trace_leaf_items(trans, eb);
5882 if (ret) {
5883 btrfs_err_rl(fs_info,
5884 "error %d accounting leaf items, quota is out of sync, rescan required",
5885 ret);
5886 }
5887 }
5888 }
5889 /* Make block locked assertion in btrfs_clear_buffer_dirty happy. */
5890 if (!path->locks[level]) {
5891 btrfs_tree_lock(eb);
5892 path->locks[level] = BTRFS_WRITE_LOCK;
5893 }
5894 btrfs_clear_buffer_dirty(trans, eb);
5895 }
5896
5897 if (eb == root->node) {
5898 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5899 parent = eb->start;
5900 else if (unlikely(btrfs_root_id(root) != btrfs_header_owner(eb)))
5901 goto owner_mismatch;
5902 } else {
5903 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5904 parent = path->nodes[level + 1]->start;
5905 else if (unlikely(btrfs_root_id(root) !=
5906 btrfs_header_owner(path->nodes[level + 1])))
5907 goto owner_mismatch;
5908 }
5909
5910 ret = btrfs_free_tree_block(trans, btrfs_root_id(root), eb, parent,
5911 wc->refs[level] == 1);
5912 if (ret < 0)
5913 btrfs_abort_transaction(trans, ret);
5914out:
5915 wc->refs[level] = 0;
5916 wc->flags[level] = 0;
5917 return ret;
5918
5919owner_mismatch:
5920 btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
5921 btrfs_header_owner(eb), btrfs_root_id(root));
5922 return -EUCLEAN;
5923}
5924
5925/*
5926 * walk_down_tree consists of two steps.
5927 *
5928 * walk_down_proc(). Look up the reference count and reference of our current
5929 * wc->level. At this point path->nodes[wc->level] should be populated and
5930 * uptodate, and in most cases should already be locked. If we are in
5931 * DROP_REFERENCE and our refcount is > 1 then we've entered a shared node and
5932 * we can walk back up the tree. If we are UPDATE_BACKREF we have to set
5933 * FULL_BACKREF on this node if it's not already set, and then do the
5934 * FULL_BACKREF conversion dance, which is to drop the root reference and add
5935 * the shared reference to all of this nodes children.
5936 *
5937 * do_walk_down(). This is where we actually start iterating on the children of
5938 * our current path->nodes[wc->level]. For DROP_REFERENCE that means dropping
5939 * our reference to the children that return false from visit_node_for_delete(),
5940 * which has various conditions where we know we can just drop our reference
5941 * without visiting the node. For UPDATE_BACKREF we will skip any children that
5942 * visit_node_for_delete() returns false for, only walking down when necessary.
5943 * The bulk of the work for UPDATE_BACKREF occurs in the walk_up_tree() part of
5944 * snapshot deletion.
5945 */
5946static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
5947 struct btrfs_root *root,
5948 struct btrfs_path *path,
5949 struct walk_control *wc)
5950{
5951 int level = wc->level;
5952 int ret = 0;
5953
5954 wc->lookup_info = 1;
5955 while (level >= 0) {
5956 ret = walk_down_proc(trans, root, path, wc);
5957 if (ret)
5958 break;
5959
5960 if (level == 0)
5961 break;
5962
5963 if (path->slots[level] >=
5964 btrfs_header_nritems(path->nodes[level]))
5965 break;
5966
5967 ret = do_walk_down(trans, root, path, wc);
5968 if (ret > 0) {
5969 path->slots[level]++;
5970 continue;
5971 } else if (ret < 0)
5972 break;
5973 level = wc->level;
5974 }
5975 return (ret == 1) ? 0 : ret;
5976}
5977
5978/*
5979 * walk_up_tree() is responsible for making sure we visit every slot on our
5980 * current node, and if we're at the end of that node then we call
5981 * walk_up_proc() on our current node which will do one of a few things based on
5982 * our stage.
5983 *
5984 * UPDATE_BACKREF. If we wc->level is currently less than our wc->shared_level
5985 * then we need to walk back up the tree, and then going back down into the
5986 * other slots via walk_down_tree to update any other children from our original
5987 * wc->shared_level. Once we're at or above our wc->shared_level we can switch
5988 * back to DROP_REFERENCE, lookup the current nodes refs and flags, and carry on.
5989 *
5990 * DROP_REFERENCE. If our refs == 1 then we're going to free this tree block.
5991 * If we're level 0 then we need to btrfs_dec_ref() on all of the data extents
5992 * in our current leaf. After that we call btrfs_free_tree_block() on the
5993 * current node and walk up to the next node to walk down the next slot.
5994 */
5995static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
5996 struct btrfs_root *root,
5997 struct btrfs_path *path,
5998 struct walk_control *wc, int max_level)
5999{
6000 int level = wc->level;
6001 int ret;
6002
6003 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
6004 while (level < max_level && path->nodes[level]) {
6005 wc->level = level;
6006 if (path->slots[level] + 1 <
6007 btrfs_header_nritems(path->nodes[level])) {
6008 path->slots[level]++;
6009 return 0;
6010 } else {
6011 ret = walk_up_proc(trans, root, path, wc);
6012 if (ret > 0)
6013 return 0;
6014 if (ret < 0)
6015 return ret;
6016
6017 if (path->locks[level]) {
6018 btrfs_tree_unlock_rw(path->nodes[level],
6019 path->locks[level]);
6020 path->locks[level] = 0;
6021 }
6022 free_extent_buffer(path->nodes[level]);
6023 path->nodes[level] = NULL;
6024 level++;
6025 }
6026 }
6027 return 1;
6028}
6029
6030/*
6031 * drop a subvolume tree.
6032 *
6033 * this function traverses the tree freeing any blocks that only
6034 * referenced by the tree.
6035 *
6036 * when a shared tree block is found. this function decreases its
6037 * reference count by one. if update_ref is true, this function
6038 * also make sure backrefs for the shared block and all lower level
6039 * blocks are properly updated.
6040 *
6041 * If called with for_reloc set, may exit early with -EAGAIN
6042 */
6043int btrfs_drop_snapshot(struct btrfs_root *root, bool update_ref, bool for_reloc)
6044{
6045 const bool is_reloc_root = (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID);
6046 struct btrfs_fs_info *fs_info = root->fs_info;
6047 struct btrfs_path *path;
6048 struct btrfs_trans_handle *trans;
6049 struct btrfs_root *tree_root = fs_info->tree_root;
6050 struct btrfs_root_item *root_item = &root->root_item;
6051 struct walk_control AUTO_KFREE(wc);
6052 struct btrfs_key key;
6053 const u64 rootid = btrfs_root_id(root);
6054 int ret = 0;
6055 int level;
6056 bool root_dropped = false;
6057 bool unfinished_drop = false;
6058
6059 btrfs_debug(fs_info, "Drop subvolume %llu", btrfs_root_id(root));
6060
6061 path = btrfs_alloc_path();
6062 if (!path) {
6063 ret = -ENOMEM;
6064 goto out;
6065 }
6066
6067 wc = kzalloc(sizeof(*wc), GFP_NOFS);
6068 if (!wc) {
6069 ret = -ENOMEM;
6070 goto out_free;
6071 }
6072
6073 /*
6074 * Use join to avoid potential EINTR from transaction start. See
6075 * wait_reserve_ticket and the whole reservation callchain.
6076 */
6077 if (for_reloc)
6078 trans = btrfs_join_transaction(tree_root);
6079 else
6080 trans = btrfs_start_transaction(tree_root, 0);
6081 if (IS_ERR(trans)) {
6082 ret = PTR_ERR(trans);
6083 goto out_free;
6084 }
6085
6086 ret = btrfs_run_delayed_items(trans);
6087 if (ret)
6088 goto out_end_trans;
6089
6090 /*
6091 * This will help us catch people modifying the fs tree while we're
6092 * dropping it. It is unsafe to mess with the fs tree while it's being
6093 * dropped as we unlock the root node and parent nodes as we walk down
6094 * the tree, assuming nothing will change. If something does change
6095 * then we'll have stale information and drop references to blocks we've
6096 * already dropped.
6097 */
6098 set_bit(BTRFS_ROOT_DELETING, &root->state);
6099 unfinished_drop = test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state);
6100
6101 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
6102 level = btrfs_header_level(root->node);
6103 path->nodes[level] = btrfs_lock_root_node(root);
6104 path->slots[level] = 0;
6105 path->locks[level] = BTRFS_WRITE_LOCK;
6106 memset(&wc->update_progress, 0,
6107 sizeof(wc->update_progress));
6108 } else {
6109 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
6110 memcpy(&wc->update_progress, &key,
6111 sizeof(wc->update_progress));
6112
6113 level = btrfs_root_drop_level(root_item);
6114 BUG_ON(level == 0);
6115 path->lowest_level = level;
6116 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6117 path->lowest_level = 0;
6118 if (ret < 0)
6119 goto out_end_trans;
6120
6121 WARN_ON(ret > 0);
6122 ret = 0;
6123
6124 /*
6125 * unlock our path, this is safe because only this
6126 * function is allowed to delete this snapshot
6127 */
6128 btrfs_unlock_up_safe(path, 0);
6129
6130 level = btrfs_header_level(root->node);
6131 while (1) {
6132 btrfs_tree_lock(path->nodes[level]);
6133 path->locks[level] = BTRFS_WRITE_LOCK;
6134
6135 /*
6136 * btrfs_lookup_extent_info() returns 0 for success,
6137 * or < 0 for error.
6138 */
6139 ret = btrfs_lookup_extent_info(trans, fs_info,
6140 path->nodes[level]->start,
6141 level, 1, &wc->refs[level],
6142 &wc->flags[level], NULL);
6143 if (ret < 0)
6144 goto out_end_trans;
6145
6146 BUG_ON(wc->refs[level] == 0);
6147
6148 if (level == btrfs_root_drop_level(root_item))
6149 break;
6150
6151 btrfs_tree_unlock(path->nodes[level]);
6152 path->locks[level] = 0;
6153 WARN_ON(wc->refs[level] != 1);
6154 level--;
6155 }
6156 }
6157
6158 wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
6159 wc->level = level;
6160 wc->shared_level = -1;
6161 wc->stage = DROP_REFERENCE;
6162 wc->update_ref = update_ref;
6163 wc->keep_locks = 0;
6164 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
6165
6166 while (1) {
6167
6168 ret = walk_down_tree(trans, root, path, wc);
6169 if (unlikely(ret < 0)) {
6170 btrfs_abort_transaction(trans, ret);
6171 break;
6172 }
6173
6174 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
6175 if (unlikely(ret < 0)) {
6176 btrfs_abort_transaction(trans, ret);
6177 break;
6178 }
6179
6180 if (ret > 0) {
6181 BUG_ON(wc->stage != DROP_REFERENCE);
6182 ret = 0;
6183 break;
6184 }
6185
6186 if (wc->stage == DROP_REFERENCE) {
6187 wc->drop_level = wc->level;
6188 btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
6189 &wc->drop_progress,
6190 path->slots[wc->drop_level]);
6191 }
6192 btrfs_cpu_key_to_disk(&root_item->drop_progress,
6193 &wc->drop_progress);
6194 btrfs_set_root_drop_level(root_item, wc->drop_level);
6195
6196 BUG_ON(wc->level == 0);
6197 if (btrfs_should_end_transaction(trans) ||
6198 (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
6199 ret = btrfs_update_root(trans, tree_root,
6200 &root->root_key,
6201 root_item);
6202 if (unlikely(ret)) {
6203 btrfs_abort_transaction(trans, ret);
6204 goto out_end_trans;
6205 }
6206
6207 if (!is_reloc_root)
6208 btrfs_set_last_root_drop_gen(fs_info, trans->transid);
6209
6210 btrfs_end_transaction_throttle(trans);
6211 if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
6212 btrfs_debug(fs_info,
6213 "drop snapshot early exit");
6214 ret = -EAGAIN;
6215 goto out_free;
6216 }
6217
6218 /*
6219 * Use join to avoid potential EINTR from transaction
6220 * start. See wait_reserve_ticket and the whole
6221 * reservation callchain.
6222 */
6223 if (for_reloc)
6224 trans = btrfs_join_transaction(tree_root);
6225 else
6226 trans = btrfs_start_transaction(tree_root, 0);
6227 if (IS_ERR(trans)) {
6228 ret = PTR_ERR(trans);
6229 goto out_free;
6230 }
6231 }
6232 }
6233 btrfs_release_path(path);
6234 if (ret)
6235 goto out_end_trans;
6236
6237 ret = btrfs_del_root(trans, &root->root_key);
6238 if (unlikely(ret)) {
6239 btrfs_abort_transaction(trans, ret);
6240 goto out_end_trans;
6241 }
6242
6243 if (!is_reloc_root) {
6244 ret = btrfs_find_root(tree_root, &root->root_key, path,
6245 NULL, NULL);
6246 if (unlikely(ret < 0)) {
6247 btrfs_abort_transaction(trans, ret);
6248 goto out_end_trans;
6249 } else if (ret > 0) {
6250 ret = 0;
6251 /*
6252 * If we fail to delete the orphan item this time
6253 * around, it'll get picked up the next time.
6254 *
6255 * The most common failure here is just -ENOENT.
6256 */
6257 btrfs_del_orphan_item(trans, tree_root, btrfs_root_id(root));
6258 }
6259 }
6260
6261 /*
6262 * This subvolume is going to be completely dropped, and won't be
6263 * recorded as dirty roots, thus pertrans meta rsv will not be freed at
6264 * commit transaction time. So free it here manually.
6265 */
6266 btrfs_qgroup_convert_reserved_meta(root, INT_MAX);
6267 btrfs_qgroup_free_meta_all_pertrans(root);
6268
6269 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state))
6270 btrfs_add_dropped_root(trans, root);
6271 else
6272 btrfs_put_root(root);
6273 root_dropped = true;
6274out_end_trans:
6275 if (!is_reloc_root)
6276 btrfs_set_last_root_drop_gen(fs_info, trans->transid);
6277
6278 btrfs_end_transaction_throttle(trans);
6279out_free:
6280 btrfs_free_path(path);
6281out:
6282 if (!ret && root_dropped) {
6283 ret = btrfs_qgroup_cleanup_dropped_subvolume(fs_info, rootid);
6284 if (ret < 0)
6285 btrfs_warn_rl(fs_info,
6286 "failed to cleanup qgroup 0/%llu: %d",
6287 rootid, ret);
6288 ret = 0;
6289 }
6290 /*
6291 * We were an unfinished drop root, check to see if there are any
6292 * pending, and if not clear and wake up any waiters.
6293 */
6294 if (!ret && unfinished_drop)
6295 btrfs_maybe_wake_unfinished_drop(fs_info);
6296
6297 /*
6298 * So if we need to stop dropping the snapshot for whatever reason we
6299 * need to make sure to add it back to the dead root list so that we
6300 * keep trying to do the work later. This also cleans up roots if we
6301 * don't have it in the radix (like when we recover after a power fail
6302 * or unmount) so we don't leak memory.
6303 */
6304 if (!for_reloc && !root_dropped)
6305 btrfs_add_dead_root(root);
6306 return ret;
6307}
6308
6309/*
6310 * drop subtree rooted at tree block 'node'.
6311 *
6312 * NOTE: this function will unlock and release tree block 'node'
6313 * only used by relocation code
6314 */
6315int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
6316 struct btrfs_root *root,
6317 struct extent_buffer *node,
6318 struct extent_buffer *parent)
6319{
6320 struct btrfs_fs_info *fs_info = root->fs_info;
6321 BTRFS_PATH_AUTO_FREE(path);
6322 struct walk_control AUTO_KFREE(wc);
6323 int level;
6324 int parent_level;
6325 int ret = 0;
6326
6327 BUG_ON(btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID);
6328
6329 path = btrfs_alloc_path();
6330 if (!path)
6331 return -ENOMEM;
6332
6333 wc = kzalloc(sizeof(*wc), GFP_NOFS);
6334 if (!wc)
6335 return -ENOMEM;
6336
6337 btrfs_assert_tree_write_locked(parent);
6338 parent_level = btrfs_header_level(parent);
6339 refcount_inc(&parent->refs);
6340 path->nodes[parent_level] = parent;
6341 path->slots[parent_level] = btrfs_header_nritems(parent);
6342
6343 btrfs_assert_tree_write_locked(node);
6344 level = btrfs_header_level(node);
6345 path->nodes[level] = node;
6346 path->slots[level] = 0;
6347 path->locks[level] = BTRFS_WRITE_LOCK;
6348
6349 wc->refs[parent_level] = 1;
6350 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
6351 wc->level = level;
6352 wc->shared_level = -1;
6353 wc->stage = DROP_REFERENCE;
6354 wc->update_ref = 0;
6355 wc->keep_locks = 1;
6356 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
6357
6358 while (1) {
6359 ret = walk_down_tree(trans, root, path, wc);
6360 if (ret < 0)
6361 return ret;
6362
6363 ret = walk_up_tree(trans, root, path, wc, parent_level);
6364 if (ret) {
6365 if (ret < 0)
6366 return ret;
6367 break;
6368 }
6369 }
6370
6371 return 0;
6372}
6373
6374/*
6375 * Unpin the extent range in an error context and don't add the space back.
6376 * Errors are not propagated further.
6377 */
6378void btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info, u64 start, u64 end)
6379{
6380 unpin_extent_range(fs_info, start, end, false);
6381}
6382
6383/*
6384 * It used to be that old block groups would be left around forever.
6385 * Iterating over them would be enough to trim unused space. Since we
6386 * now automatically remove them, we also need to iterate over unallocated
6387 * space.
6388 *
6389 * We don't want a transaction for this since the discard may take a
6390 * substantial amount of time. We don't require that a transaction be
6391 * running, but we do need to take a running transaction into account
6392 * to ensure that we're not discarding chunks that were released or
6393 * allocated in the current transaction.
6394 *
6395 * Holding the chunks lock will prevent other threads from allocating
6396 * or releasing chunks, but it won't prevent a running transaction
6397 * from committing and releasing the memory that the pending chunks
6398 * list head uses. For that, we need to take a reference to the
6399 * transaction and hold the commit root sem. We only need to hold
6400 * it while performing the free space search since we have already
6401 * held back allocations.
6402 */
6403static int btrfs_trim_free_extents(struct btrfs_device *device, u64 *trimmed)
6404{
6405 u64 start = BTRFS_DEVICE_RANGE_RESERVED, len = 0, end = 0;
6406 int ret;
6407
6408 *trimmed = 0;
6409
6410 /* Discard not supported = nothing to do. */
6411 if (!bdev_max_discard_sectors(device->bdev))
6412 return 0;
6413
6414 /* Not writable = nothing to do. */
6415 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
6416 return 0;
6417
6418 /* No free space = nothing to do. */
6419 if (device->total_bytes <= device->bytes_used)
6420 return 0;
6421
6422 ret = 0;
6423
6424 while (1) {
6425 struct btrfs_fs_info *fs_info = device->fs_info;
6426 u64 bytes;
6427
6428 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
6429 if (ret)
6430 break;
6431
6432 btrfs_find_first_clear_extent_bit(&device->alloc_state, start,
6433 &start, &end,
6434 CHUNK_TRIMMED | CHUNK_ALLOCATED);
6435
6436 /* Check if there are any CHUNK_* bits left */
6437 if (start > device->total_bytes) {
6438 DEBUG_WARN();
6439 btrfs_warn(fs_info,
6440"ignoring attempt to trim beyond device size: offset %llu length %llu device %s device size %llu",
6441 start, end - start + 1,
6442 btrfs_dev_name(device),
6443 device->total_bytes);
6444 mutex_unlock(&fs_info->chunk_mutex);
6445 ret = 0;
6446 break;
6447 }
6448
6449 /* Ensure we skip the reserved space on each device. */
6450 start = max_t(u64, start, BTRFS_DEVICE_RANGE_RESERVED);
6451
6452 /*
6453 * If find_first_clear_extent_bit find a range that spans the
6454 * end of the device it will set end to -1, in this case it's up
6455 * to the caller to trim the value to the size of the device.
6456 */
6457 end = min(end, device->total_bytes - 1);
6458
6459 len = end - start + 1;
6460
6461 /* We didn't find any extents */
6462 if (!len) {
6463 mutex_unlock(&fs_info->chunk_mutex);
6464 ret = 0;
6465 break;
6466 }
6467
6468 ret = btrfs_issue_discard(device->bdev, start, len,
6469 &bytes);
6470 if (!ret)
6471 btrfs_set_extent_bit(&device->alloc_state, start,
6472 start + bytes - 1, CHUNK_TRIMMED, NULL);
6473 mutex_unlock(&fs_info->chunk_mutex);
6474
6475 if (ret)
6476 break;
6477
6478 start += len;
6479 *trimmed += bytes;
6480
6481 if (btrfs_trim_interrupted()) {
6482 ret = -ERESTARTSYS;
6483 break;
6484 }
6485
6486 cond_resched();
6487 }
6488
6489 return ret;
6490}
6491
6492/*
6493 * Trim the whole filesystem by:
6494 * 1) trimming the free space in each block group
6495 * 2) trimming the unallocated space on each device
6496 *
6497 * This will also continue trimming even if a block group or device encounters
6498 * an error. The return value will be the last error, or 0 if nothing bad
6499 * happens.
6500 */
6501int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
6502{
6503 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6504 struct btrfs_block_group *cache = NULL;
6505 struct btrfs_device *device;
6506 u64 group_trimmed;
6507 u64 range_end = U64_MAX;
6508 u64 start;
6509 u64 end;
6510 u64 trimmed = 0;
6511 u64 bg_failed = 0;
6512 u64 dev_failed = 0;
6513 int bg_ret = 0;
6514 int dev_ret = 0;
6515 int ret = 0;
6516
6517 if (range->start == U64_MAX)
6518 return -EINVAL;
6519
6520 /*
6521 * Check range overflow if range->len is set.
6522 * The default range->len is U64_MAX.
6523 */
6524 if (range->len != U64_MAX &&
6525 check_add_overflow(range->start, range->len, &range_end))
6526 return -EINVAL;
6527
6528 cache = btrfs_lookup_first_block_group(fs_info, range->start);
6529 for (; cache; cache = btrfs_next_block_group(cache)) {
6530 if (cache->start >= range_end) {
6531 btrfs_put_block_group(cache);
6532 break;
6533 }
6534
6535 start = max(range->start, cache->start);
6536 end = min(range_end, cache->start + cache->length);
6537
6538 if (end - start >= range->minlen) {
6539 if (!btrfs_block_group_done(cache)) {
6540 ret = btrfs_cache_block_group(cache, true);
6541 if (ret) {
6542 bg_failed++;
6543 bg_ret = ret;
6544 continue;
6545 }
6546 }
6547 ret = btrfs_trim_block_group(cache,
6548 &group_trimmed,
6549 start,
6550 end,
6551 range->minlen);
6552
6553 trimmed += group_trimmed;
6554 if (ret) {
6555 bg_failed++;
6556 bg_ret = ret;
6557 continue;
6558 }
6559 }
6560 }
6561
6562 if (bg_failed)
6563 btrfs_warn(fs_info,
6564 "failed to trim %llu block group(s), last error %d",
6565 bg_failed, bg_ret);
6566
6567 mutex_lock(&fs_devices->device_list_mutex);
6568 list_for_each_entry(device, &fs_devices->devices, dev_list) {
6569 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
6570 continue;
6571
6572 ret = btrfs_trim_free_extents(device, &group_trimmed);
6573
6574 trimmed += group_trimmed;
6575 if (ret) {
6576 dev_failed++;
6577 dev_ret = ret;
6578 break;
6579 }
6580 }
6581 mutex_unlock(&fs_devices->device_list_mutex);
6582
6583 if (dev_failed)
6584 btrfs_warn(fs_info,
6585 "failed to trim %llu device(s), last error %d",
6586 dev_failed, dev_ret);
6587 range->len = trimmed;
6588 if (bg_ret)
6589 return bg_ret;
6590 return dev_ret;
6591}