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