blob: 527396522653496e8671b590c09183b1fa794731 [file] [log] [blame]
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001// 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>
David Brazdil0f672f62019-12-10 10:32:29 +000019#include "misc.h"
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000020#include "tree-log.h"
21#include "disk-io.h"
22#include "print-tree.h"
23#include "volumes.h"
24#include "raid56.h"
25#include "locking.h"
26#include "free-space-cache.h"
27#include "free-space-tree.h"
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000028#include "sysfs.h"
29#include "qgroup.h"
30#include "ref-verify.h"
David Brazdil0f672f62019-12-10 10:32:29 +000031#include "space-info.h"
32#include "block-rsv.h"
33#include "delalloc-space.h"
34#include "block-group.h"
Olivier Deprez0e641232021-09-23 10:07:05 +020035#include "rcu-string.h"
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000036
37#undef SCRAMBLE_DELAYED_REFS
38
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000039
40static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
41 struct btrfs_delayed_ref_node *node, u64 parent,
42 u64 root_objectid, u64 owner_objectid,
43 u64 owner_offset, int refs_to_drop,
44 struct btrfs_delayed_extent_op *extra_op);
45static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
46 struct extent_buffer *leaf,
47 struct btrfs_extent_item *ei);
48static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
49 u64 parent, u64 root_objectid,
50 u64 flags, u64 owner, u64 offset,
51 struct btrfs_key *ins, int ref_mod);
52static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
53 struct btrfs_delayed_ref_node *node,
54 struct btrfs_delayed_extent_op *extent_op);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000055static int find_next_key(struct btrfs_path *path, int level,
56 struct btrfs_key *key);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000057
58static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
59{
60 return (cache->flags & bits) == bits;
61}
62
David Brazdil0f672f62019-12-10 10:32:29 +000063int btrfs_add_excluded_extent(struct btrfs_fs_info *fs_info,
64 u64 start, u64 num_bytes)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000065{
66 u64 end = start + num_bytes - 1;
67 set_extent_bits(&fs_info->freed_extents[0],
68 start, end, EXTENT_UPTODATE);
69 set_extent_bits(&fs_info->freed_extents[1],
70 start, end, EXTENT_UPTODATE);
71 return 0;
72}
73
David Brazdil0f672f62019-12-10 10:32:29 +000074void btrfs_free_excluded_extents(struct btrfs_block_group_cache *cache)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000075{
76 struct btrfs_fs_info *fs_info = cache->fs_info;
77 u64 start, end;
78
79 start = cache->key.objectid;
80 end = start + cache->key.offset - 1;
81
82 clear_extent_bits(&fs_info->freed_extents[0],
83 start, end, EXTENT_UPTODATE);
84 clear_extent_bits(&fs_info->freed_extents[1],
85 start, end, EXTENT_UPTODATE);
86}
87
David Brazdil0f672f62019-12-10 10:32:29 +000088static u64 generic_ref_to_space_flags(struct btrfs_ref *ref)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000089{
David Brazdil0f672f62019-12-10 10:32:29 +000090 if (ref->type == BTRFS_REF_METADATA) {
91 if (ref->tree_ref.root == BTRFS_CHUNK_TREE_OBJECTID)
92 return BTRFS_BLOCK_GROUP_SYSTEM;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000093 else
David Brazdil0f672f62019-12-10 10:32:29 +000094 return BTRFS_BLOCK_GROUP_METADATA;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000095 }
David Brazdil0f672f62019-12-10 10:32:29 +000096 return BTRFS_BLOCK_GROUP_DATA;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000097}
98
David Brazdil0f672f62019-12-10 10:32:29 +000099static void add_pinned_bytes(struct btrfs_fs_info *fs_info,
100 struct btrfs_ref *ref)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000101{
102 struct btrfs_space_info *space_info;
David Brazdil0f672f62019-12-10 10:32:29 +0000103 u64 flags = generic_ref_to_space_flags(ref);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000104
David Brazdil0f672f62019-12-10 10:32:29 +0000105 space_info = btrfs_find_space_info(fs_info, flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000106 ASSERT(space_info);
David Brazdil0f672f62019-12-10 10:32:29 +0000107 percpu_counter_add_batch(&space_info->total_bytes_pinned, ref->len,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000108 BTRFS_TOTAL_BYTES_PINNED_BATCH);
109}
110
David Brazdil0f672f62019-12-10 10:32:29 +0000111static void sub_pinned_bytes(struct btrfs_fs_info *fs_info,
112 struct btrfs_ref *ref)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000113{
David Brazdil0f672f62019-12-10 10:32:29 +0000114 struct btrfs_space_info *space_info;
115 u64 flags = generic_ref_to_space_flags(ref);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000116
David Brazdil0f672f62019-12-10 10:32:29 +0000117 space_info = btrfs_find_space_info(fs_info, flags);
118 ASSERT(space_info);
119 percpu_counter_add_batch(&space_info->total_bytes_pinned, -ref->len,
120 BTRFS_TOTAL_BYTES_PINNED_BATCH);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000121}
122
123/* simple helper to search for an existing data extent at a given offset */
124int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
125{
126 int ret;
127 struct btrfs_key key;
128 struct btrfs_path *path;
129
130 path = btrfs_alloc_path();
131 if (!path)
132 return -ENOMEM;
133
134 key.objectid = start;
135 key.offset = len;
136 key.type = BTRFS_EXTENT_ITEM_KEY;
137 ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
138 btrfs_free_path(path);
139 return ret;
140}
141
142/*
143 * helper function to lookup reference count and flags of a tree block.
144 *
145 * the head node for delayed ref is used to store the sum of all the
146 * reference count modifications queued up in the rbtree. the head
147 * node may also store the extent flags to set. This way you can check
148 * to see what the reference count and extent flags would be if all of
149 * the delayed refs are not processed.
150 */
151int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
152 struct btrfs_fs_info *fs_info, u64 bytenr,
153 u64 offset, int metadata, u64 *refs, u64 *flags)
154{
155 struct btrfs_delayed_ref_head *head;
156 struct btrfs_delayed_ref_root *delayed_refs;
157 struct btrfs_path *path;
158 struct btrfs_extent_item *ei;
159 struct extent_buffer *leaf;
160 struct btrfs_key key;
161 u32 item_size;
162 u64 num_refs;
163 u64 extent_flags;
164 int ret;
165
166 /*
167 * If we don't have skinny metadata, don't bother doing anything
168 * different
169 */
170 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
171 offset = fs_info->nodesize;
172 metadata = 0;
173 }
174
175 path = btrfs_alloc_path();
176 if (!path)
177 return -ENOMEM;
178
179 if (!trans) {
180 path->skip_locking = 1;
181 path->search_commit_root = 1;
182 }
183
184search_again:
185 key.objectid = bytenr;
186 key.offset = offset;
187 if (metadata)
188 key.type = BTRFS_METADATA_ITEM_KEY;
189 else
190 key.type = BTRFS_EXTENT_ITEM_KEY;
191
192 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
193 if (ret < 0)
194 goto out_free;
195
196 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
197 if (path->slots[0]) {
198 path->slots[0]--;
199 btrfs_item_key_to_cpu(path->nodes[0], &key,
200 path->slots[0]);
201 if (key.objectid == bytenr &&
202 key.type == BTRFS_EXTENT_ITEM_KEY &&
203 key.offset == fs_info->nodesize)
204 ret = 0;
205 }
206 }
207
208 if (ret == 0) {
209 leaf = path->nodes[0];
210 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
211 if (item_size >= sizeof(*ei)) {
212 ei = btrfs_item_ptr(leaf, path->slots[0],
213 struct btrfs_extent_item);
214 num_refs = btrfs_extent_refs(leaf, ei);
215 extent_flags = btrfs_extent_flags(leaf, ei);
216 } else {
217 ret = -EINVAL;
218 btrfs_print_v0_err(fs_info);
219 if (trans)
220 btrfs_abort_transaction(trans, ret);
221 else
222 btrfs_handle_fs_error(fs_info, ret, NULL);
223
224 goto out_free;
225 }
226
227 BUG_ON(num_refs == 0);
228 } else {
229 num_refs = 0;
230 extent_flags = 0;
231 ret = 0;
232 }
233
234 if (!trans)
235 goto out;
236
237 delayed_refs = &trans->transaction->delayed_refs;
238 spin_lock(&delayed_refs->lock);
239 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
240 if (head) {
241 if (!mutex_trylock(&head->mutex)) {
242 refcount_inc(&head->refs);
243 spin_unlock(&delayed_refs->lock);
244
245 btrfs_release_path(path);
246
247 /*
248 * Mutex was contended, block until it's released and try
249 * again
250 */
251 mutex_lock(&head->mutex);
252 mutex_unlock(&head->mutex);
253 btrfs_put_delayed_ref_head(head);
254 goto search_again;
255 }
256 spin_lock(&head->lock);
257 if (head->extent_op && head->extent_op->update_flags)
258 extent_flags |= head->extent_op->flags_to_set;
259 else
260 BUG_ON(num_refs == 0);
261
262 num_refs += head->ref_mod;
263 spin_unlock(&head->lock);
264 mutex_unlock(&head->mutex);
265 }
266 spin_unlock(&delayed_refs->lock);
267out:
268 WARN_ON(num_refs == 0);
269 if (refs)
270 *refs = num_refs;
271 if (flags)
272 *flags = extent_flags;
273out_free:
274 btrfs_free_path(path);
275 return ret;
276}
277
278/*
279 * Back reference rules. Back refs have three main goals:
280 *
281 * 1) differentiate between all holders of references to an extent so that
282 * when a reference is dropped we can make sure it was a valid reference
283 * before freeing the extent.
284 *
285 * 2) Provide enough information to quickly find the holders of an extent
286 * if we notice a given block is corrupted or bad.
287 *
288 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
289 * maintenance. This is actually the same as #2, but with a slightly
290 * different use case.
291 *
292 * There are two kinds of back refs. The implicit back refs is optimized
293 * for pointers in non-shared tree blocks. For a given pointer in a block,
294 * back refs of this kind provide information about the block's owner tree
295 * and the pointer's key. These information allow us to find the block by
296 * b-tree searching. The full back refs is for pointers in tree blocks not
297 * referenced by their owner trees. The location of tree block is recorded
298 * in the back refs. Actually the full back refs is generic, and can be
299 * used in all cases the implicit back refs is used. The major shortcoming
300 * of the full back refs is its overhead. Every time a tree block gets
301 * COWed, we have to update back refs entry for all pointers in it.
302 *
303 * For a newly allocated tree block, we use implicit back refs for
304 * pointers in it. This means most tree related operations only involve
305 * implicit back refs. For a tree block created in old transaction, the
306 * only way to drop a reference to it is COW it. So we can detect the
307 * event that tree block loses its owner tree's reference and do the
308 * back refs conversion.
309 *
310 * When a tree block is COWed through a tree, there are four cases:
311 *
312 * The reference count of the block is one and the tree is the block's
313 * owner tree. Nothing to do in this case.
314 *
315 * The reference count of the block is one and the tree is not the
316 * block's owner tree. In this case, full back refs is used for pointers
317 * in the block. Remove these full back refs, add implicit back refs for
318 * every pointers in the new block.
319 *
320 * The reference count of the block is greater than one and the tree is
321 * the block's owner tree. In this case, implicit back refs is used for
322 * pointers in the block. Add full back refs for every pointers in the
323 * block, increase lower level extents' reference counts. The original
324 * implicit back refs are entailed to the new block.
325 *
326 * The reference count of the block is greater than one and the tree is
327 * not the block's owner tree. Add implicit back refs for every pointer in
328 * the new block, increase lower level extents' reference count.
329 *
330 * Back Reference Key composing:
331 *
332 * The key objectid corresponds to the first byte in the extent,
333 * The key type is used to differentiate between types of back refs.
334 * There are different meanings of the key offset for different types
335 * of back refs.
336 *
337 * File extents can be referenced by:
338 *
339 * - multiple snapshots, subvolumes, or different generations in one subvol
340 * - different files inside a single subvolume
341 * - different offsets inside a file (bookend extents in file.c)
342 *
343 * The extent ref structure for the implicit back refs has fields for:
344 *
345 * - Objectid of the subvolume root
346 * - objectid of the file holding the reference
347 * - original offset in the file
348 * - how many bookend extents
349 *
350 * The key offset for the implicit back refs is hash of the first
351 * three fields.
352 *
353 * The extent ref structure for the full back refs has field for:
354 *
355 * - number of pointers in the tree leaf
356 *
357 * The key offset for the implicit back refs is the first byte of
358 * the tree leaf
359 *
360 * When a file extent is allocated, The implicit back refs is used.
361 * the fields are filled in:
362 *
363 * (root_key.objectid, inode objectid, offset in file, 1)
364 *
365 * When a file extent is removed file truncation, we find the
366 * corresponding implicit back refs and check the following fields:
367 *
368 * (btrfs_header_owner(leaf), inode objectid, offset in file)
369 *
370 * Btree extents can be referenced by:
371 *
372 * - Different subvolumes
373 *
374 * Both the implicit back refs and the full back refs for tree blocks
375 * only consist of key. The key offset for the implicit back refs is
376 * objectid of block's owner tree. The key offset for the full back refs
377 * is the first byte of parent block.
378 *
379 * When implicit back refs is used, information about the lowest key and
380 * level of the tree block are required. These information are stored in
381 * tree block info structure.
382 */
383
384/*
385 * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
David Brazdil0f672f62019-12-10 10:32:29 +0000386 * is_data == BTRFS_REF_TYPE_DATA, data type is requiried,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000387 * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
388 */
389int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
390 struct btrfs_extent_inline_ref *iref,
391 enum btrfs_inline_ref_type is_data)
392{
393 int type = btrfs_extent_inline_ref_type(eb, iref);
394 u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
395
396 if (type == BTRFS_TREE_BLOCK_REF_KEY ||
397 type == BTRFS_SHARED_BLOCK_REF_KEY ||
398 type == BTRFS_SHARED_DATA_REF_KEY ||
399 type == BTRFS_EXTENT_DATA_REF_KEY) {
400 if (is_data == BTRFS_REF_TYPE_BLOCK) {
401 if (type == BTRFS_TREE_BLOCK_REF_KEY)
402 return type;
403 if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
404 ASSERT(eb->fs_info);
405 /*
Olivier Deprez0e641232021-09-23 10:07:05 +0200406 * Every shared one has parent tree block,
407 * which must be aligned to sector size.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000408 */
409 if (offset &&
Olivier Deprez0e641232021-09-23 10:07:05 +0200410 IS_ALIGNED(offset, eb->fs_info->sectorsize))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000411 return type;
412 }
413 } else if (is_data == BTRFS_REF_TYPE_DATA) {
414 if (type == BTRFS_EXTENT_DATA_REF_KEY)
415 return type;
416 if (type == BTRFS_SHARED_DATA_REF_KEY) {
417 ASSERT(eb->fs_info);
418 /*
Olivier Deprez0e641232021-09-23 10:07:05 +0200419 * Every shared one has parent tree block,
420 * which must be aligned to sector size.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000421 */
422 if (offset &&
Olivier Deprez0e641232021-09-23 10:07:05 +0200423 IS_ALIGNED(offset, eb->fs_info->sectorsize))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000424 return type;
425 }
426 } else {
427 ASSERT(is_data == BTRFS_REF_TYPE_ANY);
428 return type;
429 }
430 }
431
432 btrfs_print_leaf((struct extent_buffer *)eb);
Olivier Deprez0e641232021-09-23 10:07:05 +0200433 btrfs_err(eb->fs_info,
434 "eb %llu iref 0x%lx invalid extent inline ref type %d",
435 eb->start, (unsigned long)iref, type);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000436 WARN_ON(1);
437
438 return BTRFS_REF_TYPE_INVALID;
439}
440
David Brazdil0f672f62019-12-10 10:32:29 +0000441u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000442{
443 u32 high_crc = ~(u32)0;
444 u32 low_crc = ~(u32)0;
445 __le64 lenum;
446
447 lenum = cpu_to_le64(root_objectid);
David Brazdil0f672f62019-12-10 10:32:29 +0000448 high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000449 lenum = cpu_to_le64(owner);
David Brazdil0f672f62019-12-10 10:32:29 +0000450 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000451 lenum = cpu_to_le64(offset);
David Brazdil0f672f62019-12-10 10:32:29 +0000452 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000453
454 return ((u64)high_crc << 31) ^ (u64)low_crc;
455}
456
457static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
458 struct btrfs_extent_data_ref *ref)
459{
460 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
461 btrfs_extent_data_ref_objectid(leaf, ref),
462 btrfs_extent_data_ref_offset(leaf, ref));
463}
464
465static int match_extent_data_ref(struct extent_buffer *leaf,
466 struct btrfs_extent_data_ref *ref,
467 u64 root_objectid, u64 owner, u64 offset)
468{
469 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
470 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
471 btrfs_extent_data_ref_offset(leaf, ref) != offset)
472 return 0;
473 return 1;
474}
475
476static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
477 struct btrfs_path *path,
478 u64 bytenr, u64 parent,
479 u64 root_objectid,
480 u64 owner, u64 offset)
481{
482 struct btrfs_root *root = trans->fs_info->extent_root;
483 struct btrfs_key key;
484 struct btrfs_extent_data_ref *ref;
485 struct extent_buffer *leaf;
486 u32 nritems;
487 int ret;
488 int recow;
489 int err = -ENOENT;
490
491 key.objectid = bytenr;
492 if (parent) {
493 key.type = BTRFS_SHARED_DATA_REF_KEY;
494 key.offset = parent;
495 } else {
496 key.type = BTRFS_EXTENT_DATA_REF_KEY;
497 key.offset = hash_extent_data_ref(root_objectid,
498 owner, offset);
499 }
500again:
501 recow = 0;
502 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
503 if (ret < 0) {
504 err = ret;
505 goto fail;
506 }
507
508 if (parent) {
509 if (!ret)
510 return 0;
511 goto fail;
512 }
513
514 leaf = path->nodes[0];
515 nritems = btrfs_header_nritems(leaf);
516 while (1) {
517 if (path->slots[0] >= nritems) {
518 ret = btrfs_next_leaf(root, path);
519 if (ret < 0)
520 err = ret;
521 if (ret)
522 goto fail;
523
524 leaf = path->nodes[0];
525 nritems = btrfs_header_nritems(leaf);
526 recow = 1;
527 }
528
529 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
530 if (key.objectid != bytenr ||
531 key.type != BTRFS_EXTENT_DATA_REF_KEY)
532 goto fail;
533
534 ref = btrfs_item_ptr(leaf, path->slots[0],
535 struct btrfs_extent_data_ref);
536
537 if (match_extent_data_ref(leaf, ref, root_objectid,
538 owner, offset)) {
539 if (recow) {
540 btrfs_release_path(path);
541 goto again;
542 }
543 err = 0;
544 break;
545 }
546 path->slots[0]++;
547 }
548fail:
549 return err;
550}
551
552static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
553 struct btrfs_path *path,
554 u64 bytenr, u64 parent,
555 u64 root_objectid, u64 owner,
556 u64 offset, int refs_to_add)
557{
558 struct btrfs_root *root = trans->fs_info->extent_root;
559 struct btrfs_key key;
560 struct extent_buffer *leaf;
561 u32 size;
562 u32 num_refs;
563 int ret;
564
565 key.objectid = bytenr;
566 if (parent) {
567 key.type = BTRFS_SHARED_DATA_REF_KEY;
568 key.offset = parent;
569 size = sizeof(struct btrfs_shared_data_ref);
570 } else {
571 key.type = BTRFS_EXTENT_DATA_REF_KEY;
572 key.offset = hash_extent_data_ref(root_objectid,
573 owner, offset);
574 size = sizeof(struct btrfs_extent_data_ref);
575 }
576
577 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
578 if (ret && ret != -EEXIST)
579 goto fail;
580
581 leaf = path->nodes[0];
582 if (parent) {
583 struct btrfs_shared_data_ref *ref;
584 ref = btrfs_item_ptr(leaf, path->slots[0],
585 struct btrfs_shared_data_ref);
586 if (ret == 0) {
587 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
588 } else {
589 num_refs = btrfs_shared_data_ref_count(leaf, ref);
590 num_refs += refs_to_add;
591 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
592 }
593 } else {
594 struct btrfs_extent_data_ref *ref;
595 while (ret == -EEXIST) {
596 ref = btrfs_item_ptr(leaf, path->slots[0],
597 struct btrfs_extent_data_ref);
598 if (match_extent_data_ref(leaf, ref, root_objectid,
599 owner, offset))
600 break;
601 btrfs_release_path(path);
602 key.offset++;
603 ret = btrfs_insert_empty_item(trans, root, path, &key,
604 size);
605 if (ret && ret != -EEXIST)
606 goto fail;
607
608 leaf = path->nodes[0];
609 }
610 ref = btrfs_item_ptr(leaf, path->slots[0],
611 struct btrfs_extent_data_ref);
612 if (ret == 0) {
613 btrfs_set_extent_data_ref_root(leaf, ref,
614 root_objectid);
615 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
616 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
617 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
618 } else {
619 num_refs = btrfs_extent_data_ref_count(leaf, ref);
620 num_refs += refs_to_add;
621 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
622 }
623 }
624 btrfs_mark_buffer_dirty(leaf);
625 ret = 0;
626fail:
627 btrfs_release_path(path);
628 return ret;
629}
630
631static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
632 struct btrfs_path *path,
633 int refs_to_drop, int *last_ref)
634{
635 struct btrfs_key key;
636 struct btrfs_extent_data_ref *ref1 = NULL;
637 struct btrfs_shared_data_ref *ref2 = NULL;
638 struct extent_buffer *leaf;
639 u32 num_refs = 0;
640 int ret = 0;
641
642 leaf = path->nodes[0];
643 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
644
645 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
646 ref1 = btrfs_item_ptr(leaf, path->slots[0],
647 struct btrfs_extent_data_ref);
648 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
649 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
650 ref2 = btrfs_item_ptr(leaf, path->slots[0],
651 struct btrfs_shared_data_ref);
652 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
653 } else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
654 btrfs_print_v0_err(trans->fs_info);
655 btrfs_abort_transaction(trans, -EINVAL);
656 return -EINVAL;
657 } else {
658 BUG();
659 }
660
661 BUG_ON(num_refs < refs_to_drop);
662 num_refs -= refs_to_drop;
663
664 if (num_refs == 0) {
665 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
666 *last_ref = 1;
667 } else {
668 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
669 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
670 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
671 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
672 btrfs_mark_buffer_dirty(leaf);
673 }
674 return ret;
675}
676
677static noinline u32 extent_data_ref_count(struct btrfs_path *path,
678 struct btrfs_extent_inline_ref *iref)
679{
680 struct btrfs_key key;
681 struct extent_buffer *leaf;
682 struct btrfs_extent_data_ref *ref1;
683 struct btrfs_shared_data_ref *ref2;
684 u32 num_refs = 0;
685 int type;
686
687 leaf = path->nodes[0];
688 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
689
690 BUG_ON(key.type == BTRFS_EXTENT_REF_V0_KEY);
691 if (iref) {
692 /*
693 * If type is invalid, we should have bailed out earlier than
694 * this call.
695 */
696 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
697 ASSERT(type != BTRFS_REF_TYPE_INVALID);
698 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
699 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
700 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
701 } else {
702 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
703 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
704 }
705 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
706 ref1 = btrfs_item_ptr(leaf, path->slots[0],
707 struct btrfs_extent_data_ref);
708 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
709 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
710 ref2 = btrfs_item_ptr(leaf, path->slots[0],
711 struct btrfs_shared_data_ref);
712 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
713 } else {
714 WARN_ON(1);
715 }
716 return num_refs;
717}
718
719static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
720 struct btrfs_path *path,
721 u64 bytenr, u64 parent,
722 u64 root_objectid)
723{
724 struct btrfs_root *root = trans->fs_info->extent_root;
725 struct btrfs_key key;
726 int ret;
727
728 key.objectid = bytenr;
729 if (parent) {
730 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
731 key.offset = parent;
732 } else {
733 key.type = BTRFS_TREE_BLOCK_REF_KEY;
734 key.offset = root_objectid;
735 }
736
737 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
738 if (ret > 0)
739 ret = -ENOENT;
740 return ret;
741}
742
743static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
744 struct btrfs_path *path,
745 u64 bytenr, u64 parent,
746 u64 root_objectid)
747{
748 struct btrfs_key key;
749 int ret;
750
751 key.objectid = bytenr;
752 if (parent) {
753 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
754 key.offset = parent;
755 } else {
756 key.type = BTRFS_TREE_BLOCK_REF_KEY;
757 key.offset = root_objectid;
758 }
759
760 ret = btrfs_insert_empty_item(trans, trans->fs_info->extent_root,
761 path, &key, 0);
762 btrfs_release_path(path);
763 return ret;
764}
765
766static inline int extent_ref_type(u64 parent, u64 owner)
767{
768 int type;
769 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
770 if (parent > 0)
771 type = BTRFS_SHARED_BLOCK_REF_KEY;
772 else
773 type = BTRFS_TREE_BLOCK_REF_KEY;
774 } else {
775 if (parent > 0)
776 type = BTRFS_SHARED_DATA_REF_KEY;
777 else
778 type = BTRFS_EXTENT_DATA_REF_KEY;
779 }
780 return type;
781}
782
783static int find_next_key(struct btrfs_path *path, int level,
784 struct btrfs_key *key)
785
786{
787 for (; level < BTRFS_MAX_LEVEL; level++) {
788 if (!path->nodes[level])
789 break;
790 if (path->slots[level] + 1 >=
791 btrfs_header_nritems(path->nodes[level]))
792 continue;
793 if (level == 0)
794 btrfs_item_key_to_cpu(path->nodes[level], key,
795 path->slots[level] + 1);
796 else
797 btrfs_node_key_to_cpu(path->nodes[level], key,
798 path->slots[level] + 1);
799 return 0;
800 }
801 return 1;
802}
803
804/*
805 * look for inline back ref. if back ref is found, *ref_ret is set
806 * to the address of inline back ref, and 0 is returned.
807 *
808 * if back ref isn't found, *ref_ret is set to the address where it
809 * should be inserted, and -ENOENT is returned.
810 *
811 * if insert is true and there are too many inline back refs, the path
812 * points to the extent item, and -EAGAIN is returned.
813 *
814 * NOTE: inline back refs are ordered in the same way that back ref
815 * items in the tree are ordered.
816 */
817static noinline_for_stack
818int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
819 struct btrfs_path *path,
820 struct btrfs_extent_inline_ref **ref_ret,
821 u64 bytenr, u64 num_bytes,
822 u64 parent, u64 root_objectid,
823 u64 owner, u64 offset, int insert)
824{
825 struct btrfs_fs_info *fs_info = trans->fs_info;
826 struct btrfs_root *root = fs_info->extent_root;
827 struct btrfs_key key;
828 struct extent_buffer *leaf;
829 struct btrfs_extent_item *ei;
830 struct btrfs_extent_inline_ref *iref;
831 u64 flags;
832 u64 item_size;
833 unsigned long ptr;
834 unsigned long end;
835 int extra_size;
836 int type;
837 int want;
838 int ret;
839 int err = 0;
840 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
841 int needed;
842
843 key.objectid = bytenr;
844 key.type = BTRFS_EXTENT_ITEM_KEY;
845 key.offset = num_bytes;
846
847 want = extent_ref_type(parent, owner);
848 if (insert) {
849 extra_size = btrfs_extent_inline_ref_size(want);
850 path->keep_locks = 1;
851 } else
852 extra_size = -1;
853
854 /*
855 * Owner is our level, so we can just add one to get the level for the
856 * block we are interested in.
857 */
858 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
859 key.type = BTRFS_METADATA_ITEM_KEY;
860 key.offset = owner;
861 }
862
863again:
864 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
865 if (ret < 0) {
866 err = ret;
867 goto out;
868 }
869
870 /*
871 * We may be a newly converted file system which still has the old fat
872 * extent entries for metadata, so try and see if we have one of those.
873 */
874 if (ret > 0 && skinny_metadata) {
875 skinny_metadata = false;
876 if (path->slots[0]) {
877 path->slots[0]--;
878 btrfs_item_key_to_cpu(path->nodes[0], &key,
879 path->slots[0]);
880 if (key.objectid == bytenr &&
881 key.type == BTRFS_EXTENT_ITEM_KEY &&
882 key.offset == num_bytes)
883 ret = 0;
884 }
885 if (ret) {
886 key.objectid = bytenr;
887 key.type = BTRFS_EXTENT_ITEM_KEY;
888 key.offset = num_bytes;
889 btrfs_release_path(path);
890 goto again;
891 }
892 }
893
894 if (ret && !insert) {
895 err = -ENOENT;
896 goto out;
897 } else if (WARN_ON(ret)) {
898 err = -EIO;
899 goto out;
900 }
901
902 leaf = path->nodes[0];
903 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
904 if (unlikely(item_size < sizeof(*ei))) {
905 err = -EINVAL;
906 btrfs_print_v0_err(fs_info);
907 btrfs_abort_transaction(trans, err);
908 goto out;
909 }
910
911 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
912 flags = btrfs_extent_flags(leaf, ei);
913
914 ptr = (unsigned long)(ei + 1);
915 end = (unsigned long)ei + item_size;
916
917 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
918 ptr += sizeof(struct btrfs_tree_block_info);
919 BUG_ON(ptr > end);
920 }
921
922 if (owner >= BTRFS_FIRST_FREE_OBJECTID)
923 needed = BTRFS_REF_TYPE_DATA;
924 else
925 needed = BTRFS_REF_TYPE_BLOCK;
926
927 err = -ENOENT;
928 while (1) {
929 if (ptr >= end) {
930 WARN_ON(ptr > end);
931 break;
932 }
933 iref = (struct btrfs_extent_inline_ref *)ptr;
934 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
935 if (type == BTRFS_REF_TYPE_INVALID) {
936 err = -EUCLEAN;
937 goto out;
938 }
939
940 if (want < type)
941 break;
942 if (want > type) {
943 ptr += btrfs_extent_inline_ref_size(type);
944 continue;
945 }
946
947 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
948 struct btrfs_extent_data_ref *dref;
949 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
950 if (match_extent_data_ref(leaf, dref, root_objectid,
951 owner, offset)) {
952 err = 0;
953 break;
954 }
955 if (hash_extent_data_ref_item(leaf, dref) <
956 hash_extent_data_ref(root_objectid, owner, offset))
957 break;
958 } else {
959 u64 ref_offset;
960 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
961 if (parent > 0) {
962 if (parent == ref_offset) {
963 err = 0;
964 break;
965 }
966 if (ref_offset < parent)
967 break;
968 } else {
969 if (root_objectid == ref_offset) {
970 err = 0;
971 break;
972 }
973 if (ref_offset < root_objectid)
974 break;
975 }
976 }
977 ptr += btrfs_extent_inline_ref_size(type);
978 }
979 if (err == -ENOENT && insert) {
980 if (item_size + extra_size >=
981 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
982 err = -EAGAIN;
983 goto out;
984 }
985 /*
986 * To add new inline back ref, we have to make sure
987 * there is no corresponding back ref item.
988 * For simplicity, we just do not add new inline back
989 * ref if there is any kind of item for this block
990 */
991 if (find_next_key(path, 0, &key) == 0 &&
992 key.objectid == bytenr &&
993 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
994 err = -EAGAIN;
995 goto out;
996 }
997 }
998 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
999out:
1000 if (insert) {
1001 path->keep_locks = 0;
1002 btrfs_unlock_up_safe(path, 1);
1003 }
1004 return err;
1005}
1006
1007/*
1008 * helper to add new inline back ref
1009 */
1010static noinline_for_stack
1011void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
1012 struct btrfs_path *path,
1013 struct btrfs_extent_inline_ref *iref,
1014 u64 parent, u64 root_objectid,
1015 u64 owner, u64 offset, int refs_to_add,
1016 struct btrfs_delayed_extent_op *extent_op)
1017{
1018 struct extent_buffer *leaf;
1019 struct btrfs_extent_item *ei;
1020 unsigned long ptr;
1021 unsigned long end;
1022 unsigned long item_offset;
1023 u64 refs;
1024 int size;
1025 int type;
1026
1027 leaf = path->nodes[0];
1028 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1029 item_offset = (unsigned long)iref - (unsigned long)ei;
1030
1031 type = extent_ref_type(parent, owner);
1032 size = btrfs_extent_inline_ref_size(type);
1033
David Brazdil0f672f62019-12-10 10:32:29 +00001034 btrfs_extend_item(path, size);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001035
1036 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1037 refs = btrfs_extent_refs(leaf, ei);
1038 refs += refs_to_add;
1039 btrfs_set_extent_refs(leaf, ei, refs);
1040 if (extent_op)
1041 __run_delayed_extent_op(extent_op, leaf, ei);
1042
1043 ptr = (unsigned long)ei + item_offset;
1044 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1045 if (ptr < end - size)
1046 memmove_extent_buffer(leaf, ptr + size, ptr,
1047 end - size - ptr);
1048
1049 iref = (struct btrfs_extent_inline_ref *)ptr;
1050 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1051 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1052 struct btrfs_extent_data_ref *dref;
1053 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1054 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1055 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1056 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1057 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1058 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1059 struct btrfs_shared_data_ref *sref;
1060 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1061 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1062 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1063 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1064 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1065 } else {
1066 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1067 }
1068 btrfs_mark_buffer_dirty(leaf);
1069}
1070
1071static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1072 struct btrfs_path *path,
1073 struct btrfs_extent_inline_ref **ref_ret,
1074 u64 bytenr, u64 num_bytes, u64 parent,
1075 u64 root_objectid, u64 owner, u64 offset)
1076{
1077 int ret;
1078
1079 ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1080 num_bytes, parent, root_objectid,
1081 owner, offset, 0);
1082 if (ret != -ENOENT)
1083 return ret;
1084
1085 btrfs_release_path(path);
1086 *ref_ret = NULL;
1087
1088 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1089 ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1090 root_objectid);
1091 } else {
1092 ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1093 root_objectid, owner, offset);
1094 }
1095 return ret;
1096}
1097
1098/*
1099 * helper to update/remove inline back ref
1100 */
1101static noinline_for_stack
1102void update_inline_extent_backref(struct btrfs_path *path,
1103 struct btrfs_extent_inline_ref *iref,
1104 int refs_to_mod,
1105 struct btrfs_delayed_extent_op *extent_op,
1106 int *last_ref)
1107{
1108 struct extent_buffer *leaf = path->nodes[0];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001109 struct btrfs_extent_item *ei;
1110 struct btrfs_extent_data_ref *dref = NULL;
1111 struct btrfs_shared_data_ref *sref = NULL;
1112 unsigned long ptr;
1113 unsigned long end;
1114 u32 item_size;
1115 int size;
1116 int type;
1117 u64 refs;
1118
1119 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1120 refs = btrfs_extent_refs(leaf, ei);
1121 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1122 refs += refs_to_mod;
1123 btrfs_set_extent_refs(leaf, ei, refs);
1124 if (extent_op)
1125 __run_delayed_extent_op(extent_op, leaf, ei);
1126
1127 /*
1128 * If type is invalid, we should have bailed out after
1129 * lookup_inline_extent_backref().
1130 */
1131 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1132 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1133
1134 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1135 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1136 refs = btrfs_extent_data_ref_count(leaf, dref);
1137 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1138 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1139 refs = btrfs_shared_data_ref_count(leaf, sref);
1140 } else {
1141 refs = 1;
1142 BUG_ON(refs_to_mod != -1);
1143 }
1144
1145 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1146 refs += refs_to_mod;
1147
1148 if (refs > 0) {
1149 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1150 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1151 else
1152 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1153 } else {
1154 *last_ref = 1;
1155 size = btrfs_extent_inline_ref_size(type);
1156 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1157 ptr = (unsigned long)iref;
1158 end = (unsigned long)ei + item_size;
1159 if (ptr + size < end)
1160 memmove_extent_buffer(leaf, ptr, ptr + size,
1161 end - ptr - size);
1162 item_size -= size;
David Brazdil0f672f62019-12-10 10:32:29 +00001163 btrfs_truncate_item(path, item_size, 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001164 }
1165 btrfs_mark_buffer_dirty(leaf);
1166}
1167
1168static noinline_for_stack
1169int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1170 struct btrfs_path *path,
1171 u64 bytenr, u64 num_bytes, u64 parent,
1172 u64 root_objectid, u64 owner,
1173 u64 offset, int refs_to_add,
1174 struct btrfs_delayed_extent_op *extent_op)
1175{
1176 struct btrfs_extent_inline_ref *iref;
1177 int ret;
1178
1179 ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1180 num_bytes, parent, root_objectid,
1181 owner, offset, 1);
1182 if (ret == 0) {
1183 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1184 update_inline_extent_backref(path, iref, refs_to_add,
1185 extent_op, NULL);
1186 } else if (ret == -ENOENT) {
1187 setup_inline_extent_backref(trans->fs_info, path, iref, parent,
1188 root_objectid, owner, offset,
1189 refs_to_add, extent_op);
1190 ret = 0;
1191 }
1192 return ret;
1193}
1194
1195static int insert_extent_backref(struct btrfs_trans_handle *trans,
1196 struct btrfs_path *path,
1197 u64 bytenr, u64 parent, u64 root_objectid,
1198 u64 owner, u64 offset, int refs_to_add)
1199{
1200 int ret;
1201 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1202 BUG_ON(refs_to_add != 1);
1203 ret = insert_tree_block_ref(trans, path, bytenr, parent,
1204 root_objectid);
1205 } else {
1206 ret = insert_extent_data_ref(trans, path, bytenr, parent,
1207 root_objectid, owner, offset,
1208 refs_to_add);
1209 }
1210 return ret;
1211}
1212
1213static int remove_extent_backref(struct btrfs_trans_handle *trans,
1214 struct btrfs_path *path,
1215 struct btrfs_extent_inline_ref *iref,
1216 int refs_to_drop, int is_data, int *last_ref)
1217{
1218 int ret = 0;
1219
1220 BUG_ON(!is_data && refs_to_drop != 1);
1221 if (iref) {
1222 update_inline_extent_backref(path, iref, -refs_to_drop, NULL,
1223 last_ref);
1224 } else if (is_data) {
1225 ret = remove_extent_data_ref(trans, path, refs_to_drop,
1226 last_ref);
1227 } else {
1228 *last_ref = 1;
1229 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1230 }
1231 return ret;
1232}
1233
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001234static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1235 u64 *discarded_bytes)
1236{
1237 int j, ret = 0;
1238 u64 bytes_left, end;
1239 u64 aligned_start = ALIGN(start, 1 << 9);
1240
1241 if (WARN_ON(start != aligned_start)) {
1242 len -= aligned_start - start;
1243 len = round_down(len, 1 << 9);
1244 start = aligned_start;
1245 }
1246
1247 *discarded_bytes = 0;
1248
1249 if (!len)
1250 return 0;
1251
1252 end = start + len;
1253 bytes_left = len;
1254
1255 /* Skip any superblocks on this device. */
1256 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1257 u64 sb_start = btrfs_sb_offset(j);
1258 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1259 u64 size = sb_start - start;
1260
1261 if (!in_range(sb_start, start, bytes_left) &&
1262 !in_range(sb_end, start, bytes_left) &&
1263 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1264 continue;
1265
1266 /*
1267 * Superblock spans beginning of range. Adjust start and
1268 * try again.
1269 */
1270 if (sb_start <= start) {
1271 start += sb_end - start;
1272 if (start > end) {
1273 bytes_left = 0;
1274 break;
1275 }
1276 bytes_left = end - start;
1277 continue;
1278 }
1279
1280 if (size) {
1281 ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1282 GFP_NOFS, 0);
1283 if (!ret)
1284 *discarded_bytes += size;
1285 else if (ret != -EOPNOTSUPP)
1286 return ret;
1287 }
1288
1289 start = sb_end;
1290 if (start > end) {
1291 bytes_left = 0;
1292 break;
1293 }
1294 bytes_left = end - start;
1295 }
1296
1297 if (bytes_left) {
1298 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
1299 GFP_NOFS, 0);
1300 if (!ret)
1301 *discarded_bytes += bytes_left;
1302 }
1303 return ret;
1304}
1305
1306int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1307 u64 num_bytes, u64 *actual_bytes)
1308{
Olivier Deprez0e641232021-09-23 10:07:05 +02001309 int ret = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001310 u64 discarded_bytes = 0;
Olivier Deprez0e641232021-09-23 10:07:05 +02001311 u64 end = bytenr + num_bytes;
1312 u64 cur = bytenr;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001313 struct btrfs_bio *bbio = NULL;
1314
1315
1316 /*
1317 * Avoid races with device replace and make sure our bbio has devices
1318 * associated to its stripes that don't go away while we are discarding.
1319 */
1320 btrfs_bio_counter_inc_blocked(fs_info);
Olivier Deprez0e641232021-09-23 10:07:05 +02001321 while (cur < end) {
1322 struct btrfs_bio_stripe *stripe;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001323 int i;
1324
Olivier Deprez0e641232021-09-23 10:07:05 +02001325 num_bytes = end - cur;
1326 /* Tell the block device(s) that the sectors can be discarded */
1327 ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, cur,
1328 &num_bytes, &bbio, 0);
1329 /*
1330 * Error can be -ENOMEM, -ENOENT (no such chunk mapping) or
1331 * -EOPNOTSUPP. For any such error, @num_bytes is not updated,
1332 * thus we can't continue anyway.
1333 */
1334 if (ret < 0)
1335 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001336
Olivier Deprez0e641232021-09-23 10:07:05 +02001337 stripe = bbio->stripes;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001338 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
1339 u64 bytes;
1340 struct request_queue *req_q;
Olivier Deprez0e641232021-09-23 10:07:05 +02001341 struct btrfs_device *device = stripe->dev;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001342
Olivier Deprez0e641232021-09-23 10:07:05 +02001343 if (!device->bdev) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001344 ASSERT(btrfs_test_opt(fs_info, DEGRADED));
1345 continue;
1346 }
Olivier Deprez0e641232021-09-23 10:07:05 +02001347 req_q = bdev_get_queue(device->bdev);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001348 if (!blk_queue_discard(req_q))
1349 continue;
1350
Olivier Deprez0e641232021-09-23 10:07:05 +02001351 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
1352 continue;
1353
1354 ret = btrfs_issue_discard(device->bdev,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001355 stripe->physical,
1356 stripe->length,
1357 &bytes);
Olivier Deprez0e641232021-09-23 10:07:05 +02001358 if (!ret) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001359 discarded_bytes += bytes;
Olivier Deprez0e641232021-09-23 10:07:05 +02001360 } else if (ret != -EOPNOTSUPP) {
1361 /*
1362 * Logic errors or -ENOMEM, or -EIO, but
1363 * unlikely to happen.
1364 *
1365 * And since there are two loops, explicitly
1366 * go to out to avoid confusion.
1367 */
1368 btrfs_put_bbio(bbio);
1369 goto out;
1370 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001371
1372 /*
1373 * Just in case we get back EOPNOTSUPP for some reason,
1374 * just ignore the return value so we don't screw up
1375 * people calling discard_extent.
1376 */
1377 ret = 0;
1378 }
1379 btrfs_put_bbio(bbio);
Olivier Deprez0e641232021-09-23 10:07:05 +02001380 cur += num_bytes;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001381 }
Olivier Deprez0e641232021-09-23 10:07:05 +02001382out:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001383 btrfs_bio_counter_dec(fs_info);
1384
1385 if (actual_bytes)
1386 *actual_bytes = discarded_bytes;
1387
1388
1389 if (ret == -EOPNOTSUPP)
1390 ret = 0;
1391 return ret;
1392}
1393
1394/* Can return -ENOMEM */
1395int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
David Brazdil0f672f62019-12-10 10:32:29 +00001396 struct btrfs_ref *generic_ref)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001397{
David Brazdil0f672f62019-12-10 10:32:29 +00001398 struct btrfs_fs_info *fs_info = trans->fs_info;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001399 int old_ref_mod, new_ref_mod;
1400 int ret;
1401
David Brazdil0f672f62019-12-10 10:32:29 +00001402 ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
1403 generic_ref->action);
1404 BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
1405 generic_ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001406
David Brazdil0f672f62019-12-10 10:32:29 +00001407 if (generic_ref->type == BTRFS_REF_METADATA)
1408 ret = btrfs_add_delayed_tree_ref(trans, generic_ref,
1409 NULL, &old_ref_mod, &new_ref_mod);
1410 else
1411 ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001412 &old_ref_mod, &new_ref_mod);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001413
David Brazdil0f672f62019-12-10 10:32:29 +00001414 btrfs_ref_tree_mod(fs_info, generic_ref);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001415
David Brazdil0f672f62019-12-10 10:32:29 +00001416 if (ret == 0 && old_ref_mod < 0 && new_ref_mod >= 0)
1417 sub_pinned_bytes(fs_info, generic_ref);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001418
1419 return ret;
1420}
1421
1422/*
1423 * __btrfs_inc_extent_ref - insert backreference for a given extent
1424 *
1425 * @trans: Handle of transaction
1426 *
1427 * @node: The delayed ref node used to get the bytenr/length for
1428 * extent whose references are incremented.
1429 *
1430 * @parent: If this is a shared extent (BTRFS_SHARED_DATA_REF_KEY/
1431 * BTRFS_SHARED_BLOCK_REF_KEY) then it holds the logical
1432 * bytenr of the parent block. Since new extents are always
1433 * created with indirect references, this will only be the case
1434 * when relocating a shared extent. In that case, root_objectid
1435 * will be BTRFS_TREE_RELOC_OBJECTID. Otheriwse, parent must
1436 * be 0
1437 *
1438 * @root_objectid: The id of the root where this modification has originated,
1439 * this can be either one of the well-known metadata trees or
1440 * the subvolume id which references this extent.
1441 *
1442 * @owner: For data extents it is the inode number of the owning file.
1443 * For metadata extents this parameter holds the level in the
1444 * tree of the extent.
1445 *
1446 * @offset: For metadata extents the offset is ignored and is currently
1447 * always passed as 0. For data extents it is the fileoffset
1448 * this extent belongs to.
1449 *
1450 * @refs_to_add Number of references to add
1451 *
1452 * @extent_op Pointer to a structure, holding information necessary when
1453 * updating a tree block's flags
1454 *
1455 */
1456static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1457 struct btrfs_delayed_ref_node *node,
1458 u64 parent, u64 root_objectid,
1459 u64 owner, u64 offset, int refs_to_add,
1460 struct btrfs_delayed_extent_op *extent_op)
1461{
1462 struct btrfs_path *path;
1463 struct extent_buffer *leaf;
1464 struct btrfs_extent_item *item;
1465 struct btrfs_key key;
1466 u64 bytenr = node->bytenr;
1467 u64 num_bytes = node->num_bytes;
1468 u64 refs;
1469 int ret;
1470
1471 path = btrfs_alloc_path();
1472 if (!path)
1473 return -ENOMEM;
1474
1475 path->reada = READA_FORWARD;
1476 path->leave_spinning = 1;
1477 /* this will setup the path even if it fails to insert the back ref */
1478 ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
1479 parent, root_objectid, owner,
1480 offset, refs_to_add, extent_op);
1481 if ((ret < 0 && ret != -EAGAIN) || !ret)
1482 goto out;
1483
1484 /*
1485 * Ok we had -EAGAIN which means we didn't have space to insert and
1486 * inline extent ref, so just update the reference count and add a
1487 * normal backref.
1488 */
1489 leaf = path->nodes[0];
1490 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1491 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1492 refs = btrfs_extent_refs(leaf, item);
1493 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
1494 if (extent_op)
1495 __run_delayed_extent_op(extent_op, leaf, item);
1496
1497 btrfs_mark_buffer_dirty(leaf);
1498 btrfs_release_path(path);
1499
1500 path->reada = READA_FORWARD;
1501 path->leave_spinning = 1;
1502 /* now insert the actual backref */
1503 ret = insert_extent_backref(trans, path, bytenr, parent, root_objectid,
1504 owner, offset, refs_to_add);
1505 if (ret)
1506 btrfs_abort_transaction(trans, ret);
1507out:
1508 btrfs_free_path(path);
1509 return ret;
1510}
1511
1512static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
1513 struct btrfs_delayed_ref_node *node,
1514 struct btrfs_delayed_extent_op *extent_op,
1515 int insert_reserved)
1516{
1517 int ret = 0;
1518 struct btrfs_delayed_data_ref *ref;
1519 struct btrfs_key ins;
1520 u64 parent = 0;
1521 u64 ref_root = 0;
1522 u64 flags = 0;
1523
1524 ins.objectid = node->bytenr;
1525 ins.offset = node->num_bytes;
1526 ins.type = BTRFS_EXTENT_ITEM_KEY;
1527
1528 ref = btrfs_delayed_node_to_data_ref(node);
1529 trace_run_delayed_data_ref(trans->fs_info, node, ref, node->action);
1530
1531 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
1532 parent = ref->parent;
1533 ref_root = ref->root;
1534
1535 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1536 if (extent_op)
1537 flags |= extent_op->flags_to_set;
1538 ret = alloc_reserved_file_extent(trans, parent, ref_root,
1539 flags, ref->objectid,
1540 ref->offset, &ins,
1541 node->ref_mod);
1542 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1543 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
1544 ref->objectid, ref->offset,
1545 node->ref_mod, extent_op);
1546 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1547 ret = __btrfs_free_extent(trans, node, parent,
1548 ref_root, ref->objectid,
1549 ref->offset, node->ref_mod,
1550 extent_op);
1551 } else {
1552 BUG();
1553 }
1554 return ret;
1555}
1556
1557static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
1558 struct extent_buffer *leaf,
1559 struct btrfs_extent_item *ei)
1560{
1561 u64 flags = btrfs_extent_flags(leaf, ei);
1562 if (extent_op->update_flags) {
1563 flags |= extent_op->flags_to_set;
1564 btrfs_set_extent_flags(leaf, ei, flags);
1565 }
1566
1567 if (extent_op->update_key) {
1568 struct btrfs_tree_block_info *bi;
1569 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
1570 bi = (struct btrfs_tree_block_info *)(ei + 1);
1571 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
1572 }
1573}
1574
1575static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
1576 struct btrfs_delayed_ref_head *head,
1577 struct btrfs_delayed_extent_op *extent_op)
1578{
1579 struct btrfs_fs_info *fs_info = trans->fs_info;
1580 struct btrfs_key key;
1581 struct btrfs_path *path;
1582 struct btrfs_extent_item *ei;
1583 struct extent_buffer *leaf;
1584 u32 item_size;
1585 int ret;
1586 int err = 0;
1587 int metadata = !extent_op->is_data;
1588
Olivier Deprez0e641232021-09-23 10:07:05 +02001589 if (TRANS_ABORTED(trans))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001590 return 0;
1591
1592 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
1593 metadata = 0;
1594
1595 path = btrfs_alloc_path();
1596 if (!path)
1597 return -ENOMEM;
1598
1599 key.objectid = head->bytenr;
1600
1601 if (metadata) {
1602 key.type = BTRFS_METADATA_ITEM_KEY;
1603 key.offset = extent_op->level;
1604 } else {
1605 key.type = BTRFS_EXTENT_ITEM_KEY;
1606 key.offset = head->num_bytes;
1607 }
1608
1609again:
1610 path->reada = READA_FORWARD;
1611 path->leave_spinning = 1;
1612 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
1613 if (ret < 0) {
1614 err = ret;
1615 goto out;
1616 }
1617 if (ret > 0) {
1618 if (metadata) {
1619 if (path->slots[0] > 0) {
1620 path->slots[0]--;
1621 btrfs_item_key_to_cpu(path->nodes[0], &key,
1622 path->slots[0]);
1623 if (key.objectid == head->bytenr &&
1624 key.type == BTRFS_EXTENT_ITEM_KEY &&
1625 key.offset == head->num_bytes)
1626 ret = 0;
1627 }
1628 if (ret > 0) {
1629 btrfs_release_path(path);
1630 metadata = 0;
1631
1632 key.objectid = head->bytenr;
1633 key.offset = head->num_bytes;
1634 key.type = BTRFS_EXTENT_ITEM_KEY;
1635 goto again;
1636 }
1637 } else {
1638 err = -EIO;
1639 goto out;
1640 }
1641 }
1642
1643 leaf = path->nodes[0];
1644 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1645
1646 if (unlikely(item_size < sizeof(*ei))) {
1647 err = -EINVAL;
1648 btrfs_print_v0_err(fs_info);
1649 btrfs_abort_transaction(trans, err);
1650 goto out;
1651 }
1652
1653 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1654 __run_delayed_extent_op(extent_op, leaf, ei);
1655
1656 btrfs_mark_buffer_dirty(leaf);
1657out:
1658 btrfs_free_path(path);
1659 return err;
1660}
1661
1662static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
1663 struct btrfs_delayed_ref_node *node,
1664 struct btrfs_delayed_extent_op *extent_op,
1665 int insert_reserved)
1666{
1667 int ret = 0;
1668 struct btrfs_delayed_tree_ref *ref;
1669 u64 parent = 0;
1670 u64 ref_root = 0;
1671
1672 ref = btrfs_delayed_node_to_tree_ref(node);
1673 trace_run_delayed_tree_ref(trans->fs_info, node, ref, node->action);
1674
1675 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1676 parent = ref->parent;
1677 ref_root = ref->root;
1678
1679 if (node->ref_mod != 1) {
1680 btrfs_err(trans->fs_info,
1681 "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
1682 node->bytenr, node->ref_mod, node->action, ref_root,
1683 parent);
1684 return -EIO;
1685 }
1686 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1687 BUG_ON(!extent_op || !extent_op->update_flags);
1688 ret = alloc_reserved_tree_block(trans, node, extent_op);
1689 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1690 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
1691 ref->level, 0, 1, extent_op);
1692 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1693 ret = __btrfs_free_extent(trans, node, parent, ref_root,
1694 ref->level, 0, 1, extent_op);
1695 } else {
1696 BUG();
1697 }
1698 return ret;
1699}
1700
1701/* helper function to actually process a single delayed ref entry */
1702static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
1703 struct btrfs_delayed_ref_node *node,
1704 struct btrfs_delayed_extent_op *extent_op,
1705 int insert_reserved)
1706{
1707 int ret = 0;
1708
Olivier Deprez0e641232021-09-23 10:07:05 +02001709 if (TRANS_ABORTED(trans)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001710 if (insert_reserved)
1711 btrfs_pin_extent(trans->fs_info, node->bytenr,
1712 node->num_bytes, 1);
1713 return 0;
1714 }
1715
1716 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
1717 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1718 ret = run_delayed_tree_ref(trans, node, extent_op,
1719 insert_reserved);
1720 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
1721 node->type == BTRFS_SHARED_DATA_REF_KEY)
1722 ret = run_delayed_data_ref(trans, node, extent_op,
1723 insert_reserved);
1724 else
1725 BUG();
1726 if (ret && insert_reserved)
1727 btrfs_pin_extent(trans->fs_info, node->bytenr,
1728 node->num_bytes, 1);
1729 return ret;
1730}
1731
1732static inline struct btrfs_delayed_ref_node *
1733select_delayed_ref(struct btrfs_delayed_ref_head *head)
1734{
1735 struct btrfs_delayed_ref_node *ref;
1736
David Brazdil0f672f62019-12-10 10:32:29 +00001737 if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001738 return NULL;
1739
1740 /*
1741 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
1742 * This is to prevent a ref count from going down to zero, which deletes
1743 * the extent item from the extent tree, when there still are references
1744 * to add, which would fail because they would not find the extent item.
1745 */
1746 if (!list_empty(&head->ref_add_list))
1747 return list_first_entry(&head->ref_add_list,
1748 struct btrfs_delayed_ref_node, add_list);
1749
David Brazdil0f672f62019-12-10 10:32:29 +00001750 ref = rb_entry(rb_first_cached(&head->ref_tree),
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001751 struct btrfs_delayed_ref_node, ref_node);
1752 ASSERT(list_empty(&ref->add_list));
1753 return ref;
1754}
1755
1756static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
1757 struct btrfs_delayed_ref_head *head)
1758{
1759 spin_lock(&delayed_refs->lock);
1760 head->processing = 0;
1761 delayed_refs->num_heads_ready++;
1762 spin_unlock(&delayed_refs->lock);
1763 btrfs_delayed_ref_unlock(head);
1764}
1765
David Brazdil0f672f62019-12-10 10:32:29 +00001766static struct btrfs_delayed_extent_op *cleanup_extent_op(
1767 struct btrfs_delayed_ref_head *head)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001768{
1769 struct btrfs_delayed_extent_op *extent_op = head->extent_op;
David Brazdil0f672f62019-12-10 10:32:29 +00001770
1771 if (!extent_op)
1772 return NULL;
1773
1774 if (head->must_insert_reserved) {
1775 head->extent_op = NULL;
1776 btrfs_free_delayed_extent_op(extent_op);
1777 return NULL;
1778 }
1779 return extent_op;
1780}
1781
1782static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
1783 struct btrfs_delayed_ref_head *head)
1784{
1785 struct btrfs_delayed_extent_op *extent_op;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001786 int ret;
1787
David Brazdil0f672f62019-12-10 10:32:29 +00001788 extent_op = cleanup_extent_op(head);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001789 if (!extent_op)
1790 return 0;
1791 head->extent_op = NULL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001792 spin_unlock(&head->lock);
1793 ret = run_delayed_extent_op(trans, head, extent_op);
1794 btrfs_free_delayed_extent_op(extent_op);
1795 return ret ? ret : 1;
1796}
1797
David Brazdil0f672f62019-12-10 10:32:29 +00001798void btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
1799 struct btrfs_delayed_ref_root *delayed_refs,
1800 struct btrfs_delayed_ref_head *head)
1801{
1802 int nr_items = 1; /* Dropping this ref head update. */
1803
1804 if (head->total_ref_mod < 0) {
1805 struct btrfs_space_info *space_info;
1806 u64 flags;
1807
1808 if (head->is_data)
1809 flags = BTRFS_BLOCK_GROUP_DATA;
1810 else if (head->is_system)
1811 flags = BTRFS_BLOCK_GROUP_SYSTEM;
1812 else
1813 flags = BTRFS_BLOCK_GROUP_METADATA;
1814 space_info = btrfs_find_space_info(fs_info, flags);
1815 ASSERT(space_info);
1816 percpu_counter_add_batch(&space_info->total_bytes_pinned,
1817 -head->num_bytes,
1818 BTRFS_TOTAL_BYTES_PINNED_BATCH);
1819
1820 /*
1821 * We had csum deletions accounted for in our delayed refs rsv,
1822 * we need to drop the csum leaves for this update from our
1823 * delayed_refs_rsv.
1824 */
1825 if (head->is_data) {
1826 spin_lock(&delayed_refs->lock);
1827 delayed_refs->pending_csums -= head->num_bytes;
1828 spin_unlock(&delayed_refs->lock);
1829 nr_items += btrfs_csum_bytes_to_leaves(fs_info,
1830 head->num_bytes);
1831 }
1832 }
1833
1834 btrfs_delayed_refs_rsv_release(fs_info, nr_items);
1835}
1836
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001837static int cleanup_ref_head(struct btrfs_trans_handle *trans,
1838 struct btrfs_delayed_ref_head *head)
1839{
1840
1841 struct btrfs_fs_info *fs_info = trans->fs_info;
1842 struct btrfs_delayed_ref_root *delayed_refs;
1843 int ret;
1844
1845 delayed_refs = &trans->transaction->delayed_refs;
1846
David Brazdil0f672f62019-12-10 10:32:29 +00001847 ret = run_and_cleanup_extent_op(trans, head);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001848 if (ret < 0) {
1849 unselect_delayed_ref_head(delayed_refs, head);
1850 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
1851 return ret;
1852 } else if (ret) {
1853 return ret;
1854 }
1855
1856 /*
1857 * Need to drop our head ref lock and re-acquire the delayed ref lock
1858 * and then re-check to make sure nobody got added.
1859 */
1860 spin_unlock(&head->lock);
1861 spin_lock(&delayed_refs->lock);
1862 spin_lock(&head->lock);
David Brazdil0f672f62019-12-10 10:32:29 +00001863 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001864 spin_unlock(&head->lock);
1865 spin_unlock(&delayed_refs->lock);
1866 return 1;
1867 }
David Brazdil0f672f62019-12-10 10:32:29 +00001868 btrfs_delete_ref_head(delayed_refs, head);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001869 spin_unlock(&head->lock);
1870 spin_unlock(&delayed_refs->lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001871
1872 if (head->must_insert_reserved) {
1873 btrfs_pin_extent(fs_info, head->bytenr,
1874 head->num_bytes, 1);
1875 if (head->is_data) {
Olivier Deprez0e641232021-09-23 10:07:05 +02001876 ret = btrfs_del_csums(trans, fs_info->csum_root,
1877 head->bytenr, head->num_bytes);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001878 }
1879 }
1880
David Brazdil0f672f62019-12-10 10:32:29 +00001881 btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
1882
1883 trace_run_delayed_ref_head(fs_info, head, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001884 btrfs_delayed_ref_unlock(head);
1885 btrfs_put_delayed_ref_head(head);
Olivier Deprez0e641232021-09-23 10:07:05 +02001886 return ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001887}
1888
David Brazdil0f672f62019-12-10 10:32:29 +00001889static struct btrfs_delayed_ref_head *btrfs_obtain_ref_head(
1890 struct btrfs_trans_handle *trans)
1891{
1892 struct btrfs_delayed_ref_root *delayed_refs =
1893 &trans->transaction->delayed_refs;
1894 struct btrfs_delayed_ref_head *head = NULL;
1895 int ret;
1896
1897 spin_lock(&delayed_refs->lock);
1898 head = btrfs_select_ref_head(delayed_refs);
1899 if (!head) {
1900 spin_unlock(&delayed_refs->lock);
1901 return head;
1902 }
1903
1904 /*
1905 * Grab the lock that says we are going to process all the refs for
1906 * this head
1907 */
1908 ret = btrfs_delayed_ref_lock(delayed_refs, head);
1909 spin_unlock(&delayed_refs->lock);
1910
1911 /*
1912 * We may have dropped the spin lock to get the head mutex lock, and
1913 * that might have given someone else time to free the head. If that's
1914 * true, it has been removed from our list and we can move on.
1915 */
1916 if (ret == -EAGAIN)
1917 head = ERR_PTR(-EAGAIN);
1918
1919 return head;
1920}
1921
1922static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
1923 struct btrfs_delayed_ref_head *locked_ref,
1924 unsigned long *run_refs)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001925{
1926 struct btrfs_fs_info *fs_info = trans->fs_info;
1927 struct btrfs_delayed_ref_root *delayed_refs;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001928 struct btrfs_delayed_extent_op *extent_op;
David Brazdil0f672f62019-12-10 10:32:29 +00001929 struct btrfs_delayed_ref_node *ref;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001930 int must_insert_reserved = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00001931 int ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001932
1933 delayed_refs = &trans->transaction->delayed_refs;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001934
David Brazdil0f672f62019-12-10 10:32:29 +00001935 lockdep_assert_held(&locked_ref->mutex);
1936 lockdep_assert_held(&locked_ref->lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001937
David Brazdil0f672f62019-12-10 10:32:29 +00001938 while ((ref = select_delayed_ref(locked_ref))) {
1939 if (ref->seq &&
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001940 btrfs_check_delayed_seq(fs_info, ref->seq)) {
1941 spin_unlock(&locked_ref->lock);
1942 unselect_delayed_ref_head(delayed_refs, locked_ref);
David Brazdil0f672f62019-12-10 10:32:29 +00001943 return -EAGAIN;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001944 }
1945
David Brazdil0f672f62019-12-10 10:32:29 +00001946 (*run_refs)++;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001947 ref->in_tree = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00001948 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001949 RB_CLEAR_NODE(&ref->ref_node);
1950 if (!list_empty(&ref->add_list))
1951 list_del(&ref->add_list);
1952 /*
1953 * When we play the delayed ref, also correct the ref_mod on
1954 * head
1955 */
1956 switch (ref->action) {
1957 case BTRFS_ADD_DELAYED_REF:
1958 case BTRFS_ADD_DELAYED_EXTENT:
1959 locked_ref->ref_mod -= ref->ref_mod;
1960 break;
1961 case BTRFS_DROP_DELAYED_REF:
1962 locked_ref->ref_mod += ref->ref_mod;
1963 break;
1964 default:
1965 WARN_ON(1);
1966 }
1967 atomic_dec(&delayed_refs->num_entries);
1968
1969 /*
David Brazdil0f672f62019-12-10 10:32:29 +00001970 * Record the must_insert_reserved flag before we drop the
1971 * spin lock.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001972 */
1973 must_insert_reserved = locked_ref->must_insert_reserved;
1974 locked_ref->must_insert_reserved = 0;
1975
1976 extent_op = locked_ref->extent_op;
1977 locked_ref->extent_op = NULL;
1978 spin_unlock(&locked_ref->lock);
1979
1980 ret = run_one_delayed_ref(trans, ref, extent_op,
1981 must_insert_reserved);
1982
1983 btrfs_free_delayed_extent_op(extent_op);
1984 if (ret) {
1985 unselect_delayed_ref_head(delayed_refs, locked_ref);
1986 btrfs_put_delayed_ref(ref);
1987 btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
1988 ret);
1989 return ret;
1990 }
1991
1992 btrfs_put_delayed_ref(ref);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001993 cond_resched();
David Brazdil0f672f62019-12-10 10:32:29 +00001994
1995 spin_lock(&locked_ref->lock);
1996 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001997 }
1998
David Brazdil0f672f62019-12-10 10:32:29 +00001999 return 0;
2000}
2001
2002/*
2003 * Returns 0 on success or if called with an already aborted transaction.
2004 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2005 */
2006static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2007 unsigned long nr)
2008{
2009 struct btrfs_fs_info *fs_info = trans->fs_info;
2010 struct btrfs_delayed_ref_root *delayed_refs;
2011 struct btrfs_delayed_ref_head *locked_ref = NULL;
2012 ktime_t start = ktime_get();
2013 int ret;
2014 unsigned long count = 0;
2015 unsigned long actual_count = 0;
2016
2017 delayed_refs = &trans->transaction->delayed_refs;
2018 do {
2019 if (!locked_ref) {
2020 locked_ref = btrfs_obtain_ref_head(trans);
2021 if (IS_ERR_OR_NULL(locked_ref)) {
2022 if (PTR_ERR(locked_ref) == -EAGAIN) {
2023 continue;
2024 } else {
2025 break;
2026 }
2027 }
2028 count++;
2029 }
2030 /*
2031 * We need to try and merge add/drops of the same ref since we
2032 * can run into issues with relocate dropping the implicit ref
2033 * and then it being added back again before the drop can
2034 * finish. If we merged anything we need to re-loop so we can
2035 * get a good ref.
2036 * Or we can get node references of the same type that weren't
2037 * merged when created due to bumps in the tree mod seq, and
2038 * we need to merge them to prevent adding an inline extent
2039 * backref before dropping it (triggering a BUG_ON at
2040 * insert_inline_extent_backref()).
2041 */
2042 spin_lock(&locked_ref->lock);
2043 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2044
2045 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref,
2046 &actual_count);
2047 if (ret < 0 && ret != -EAGAIN) {
2048 /*
2049 * Error, btrfs_run_delayed_refs_for_head already
2050 * unlocked everything so just bail out
2051 */
2052 return ret;
2053 } else if (!ret) {
2054 /*
2055 * Success, perform the usual cleanup of a processed
2056 * head
2057 */
2058 ret = cleanup_ref_head(trans, locked_ref);
2059 if (ret > 0 ) {
2060 /* We dropped our lock, we need to loop. */
2061 ret = 0;
2062 continue;
2063 } else if (ret) {
2064 return ret;
2065 }
2066 }
2067
2068 /*
2069 * Either success case or btrfs_run_delayed_refs_for_head
2070 * returned -EAGAIN, meaning we need to select another head
2071 */
2072
2073 locked_ref = NULL;
2074 cond_resched();
2075 } while ((nr != -1 && count < nr) || locked_ref);
2076
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002077 /*
2078 * We don't want to include ref heads since we can have empty ref heads
2079 * and those will drastically skew our runtime down since we just do
2080 * accounting, no actual extent tree updates.
2081 */
2082 if (actual_count > 0) {
2083 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2084 u64 avg;
2085
2086 /*
2087 * We weigh the current average higher than our current runtime
2088 * to avoid large swings in the average.
2089 */
2090 spin_lock(&delayed_refs->lock);
2091 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2092 fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
2093 spin_unlock(&delayed_refs->lock);
2094 }
2095 return 0;
2096}
2097
2098#ifdef SCRAMBLE_DELAYED_REFS
2099/*
2100 * Normally delayed refs get processed in ascending bytenr order. This
2101 * correlates in most cases to the order added. To expose dependencies on this
2102 * order, we start to process the tree in the middle instead of the beginning
2103 */
2104static u64 find_middle(struct rb_root *root)
2105{
2106 struct rb_node *n = root->rb_node;
2107 struct btrfs_delayed_ref_node *entry;
2108 int alt = 1;
2109 u64 middle;
2110 u64 first = 0, last = 0;
2111
2112 n = rb_first(root);
2113 if (n) {
2114 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2115 first = entry->bytenr;
2116 }
2117 n = rb_last(root);
2118 if (n) {
2119 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2120 last = entry->bytenr;
2121 }
2122 n = root->rb_node;
2123
2124 while (n) {
2125 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2126 WARN_ON(!entry->in_tree);
2127
2128 middle = entry->bytenr;
2129
2130 if (alt)
2131 n = n->rb_left;
2132 else
2133 n = n->rb_right;
2134
2135 alt = 1 - alt;
2136 }
2137 return middle;
2138}
2139#endif
2140
2141static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
2142{
2143 u64 num_bytes;
2144
2145 num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2146 sizeof(struct btrfs_extent_inline_ref));
2147 if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2148 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2149
2150 /*
2151 * We don't ever fill up leaves all the way so multiply by 2 just to be
2152 * closer to what we're really going to want to use.
2153 */
2154 return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
2155}
2156
2157/*
2158 * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2159 * would require to store the csums for that many bytes.
2160 */
2161u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
2162{
2163 u64 csum_size;
2164 u64 num_csums_per_leaf;
2165 u64 num_csums;
2166
2167 csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
2168 num_csums_per_leaf = div64_u64(csum_size,
2169 (u64)btrfs_super_csum_size(fs_info->super_copy));
2170 num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
2171 num_csums += num_csums_per_leaf - 1;
2172 num_csums = div64_u64(num_csums, num_csums_per_leaf);
2173 return num_csums;
2174}
2175
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002176/*
2177 * this starts processing the delayed reference count updates and
2178 * extent insertions we have queued up so far. count can be
2179 * 0, which means to process everything in the tree at the start
2180 * of the run (but not newly added entries), or it can be some target
2181 * number you'd like to process.
2182 *
2183 * Returns 0 on success or if called with an aborted transaction
2184 * Returns <0 on error and aborts the transaction
2185 */
2186int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2187 unsigned long count)
2188{
2189 struct btrfs_fs_info *fs_info = trans->fs_info;
2190 struct rb_node *node;
2191 struct btrfs_delayed_ref_root *delayed_refs;
2192 struct btrfs_delayed_ref_head *head;
2193 int ret;
2194 int run_all = count == (unsigned long)-1;
2195
2196 /* We'll clean this up in btrfs_cleanup_transaction */
Olivier Deprez0e641232021-09-23 10:07:05 +02002197 if (TRANS_ABORTED(trans))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002198 return 0;
2199
2200 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2201 return 0;
2202
2203 delayed_refs = &trans->transaction->delayed_refs;
2204 if (count == 0)
2205 count = atomic_read(&delayed_refs->num_entries) * 2;
2206
2207again:
2208#ifdef SCRAMBLE_DELAYED_REFS
2209 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2210#endif
2211 ret = __btrfs_run_delayed_refs(trans, count);
2212 if (ret < 0) {
2213 btrfs_abort_transaction(trans, ret);
2214 return ret;
2215 }
2216
2217 if (run_all) {
David Brazdil0f672f62019-12-10 10:32:29 +00002218 btrfs_create_pending_block_groups(trans);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002219
2220 spin_lock(&delayed_refs->lock);
David Brazdil0f672f62019-12-10 10:32:29 +00002221 node = rb_first_cached(&delayed_refs->href_root);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002222 if (!node) {
2223 spin_unlock(&delayed_refs->lock);
2224 goto out;
2225 }
2226 head = rb_entry(node, struct btrfs_delayed_ref_head,
2227 href_node);
2228 refcount_inc(&head->refs);
2229 spin_unlock(&delayed_refs->lock);
2230
2231 /* Mutex was contended, block until it's released and retry. */
2232 mutex_lock(&head->mutex);
2233 mutex_unlock(&head->mutex);
2234
2235 btrfs_put_delayed_ref_head(head);
2236 cond_resched();
2237 goto again;
2238 }
2239out:
2240 return 0;
2241}
2242
2243int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002244 u64 bytenr, u64 num_bytes, u64 flags,
2245 int level, int is_data)
2246{
2247 struct btrfs_delayed_extent_op *extent_op;
2248 int ret;
2249
2250 extent_op = btrfs_alloc_delayed_extent_op();
2251 if (!extent_op)
2252 return -ENOMEM;
2253
2254 extent_op->flags_to_set = flags;
2255 extent_op->update_flags = true;
2256 extent_op->update_key = false;
2257 extent_op->is_data = is_data ? true : false;
2258 extent_op->level = level;
2259
David Brazdil0f672f62019-12-10 10:32:29 +00002260 ret = btrfs_add_delayed_extent_op(trans, bytenr, num_bytes, extent_op);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002261 if (ret)
2262 btrfs_free_delayed_extent_op(extent_op);
2263 return ret;
2264}
2265
2266static noinline int check_delayed_ref(struct btrfs_root *root,
2267 struct btrfs_path *path,
2268 u64 objectid, u64 offset, u64 bytenr)
2269{
2270 struct btrfs_delayed_ref_head *head;
2271 struct btrfs_delayed_ref_node *ref;
2272 struct btrfs_delayed_data_ref *data_ref;
2273 struct btrfs_delayed_ref_root *delayed_refs;
2274 struct btrfs_transaction *cur_trans;
2275 struct rb_node *node;
2276 int ret = 0;
2277
2278 spin_lock(&root->fs_info->trans_lock);
2279 cur_trans = root->fs_info->running_transaction;
2280 if (cur_trans)
2281 refcount_inc(&cur_trans->use_count);
2282 spin_unlock(&root->fs_info->trans_lock);
2283 if (!cur_trans)
2284 return 0;
2285
2286 delayed_refs = &cur_trans->delayed_refs;
2287 spin_lock(&delayed_refs->lock);
2288 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
2289 if (!head) {
2290 spin_unlock(&delayed_refs->lock);
2291 btrfs_put_transaction(cur_trans);
2292 return 0;
2293 }
2294
2295 if (!mutex_trylock(&head->mutex)) {
2296 refcount_inc(&head->refs);
2297 spin_unlock(&delayed_refs->lock);
2298
2299 btrfs_release_path(path);
2300
2301 /*
2302 * Mutex was contended, block until it's released and let
2303 * caller try again
2304 */
2305 mutex_lock(&head->mutex);
2306 mutex_unlock(&head->mutex);
2307 btrfs_put_delayed_ref_head(head);
2308 btrfs_put_transaction(cur_trans);
2309 return -EAGAIN;
2310 }
2311 spin_unlock(&delayed_refs->lock);
2312
2313 spin_lock(&head->lock);
2314 /*
2315 * XXX: We should replace this with a proper search function in the
2316 * future.
2317 */
David Brazdil0f672f62019-12-10 10:32:29 +00002318 for (node = rb_first_cached(&head->ref_tree); node;
2319 node = rb_next(node)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002320 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
2321 /* If it's a shared ref we know a cross reference exists */
2322 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
2323 ret = 1;
2324 break;
2325 }
2326
2327 data_ref = btrfs_delayed_node_to_data_ref(ref);
2328
2329 /*
2330 * If our ref doesn't match the one we're currently looking at
2331 * then we have a cross reference.
2332 */
2333 if (data_ref->root != root->root_key.objectid ||
2334 data_ref->objectid != objectid ||
2335 data_ref->offset != offset) {
2336 ret = 1;
2337 break;
2338 }
2339 }
2340 spin_unlock(&head->lock);
2341 mutex_unlock(&head->mutex);
2342 btrfs_put_transaction(cur_trans);
2343 return ret;
2344}
2345
2346static noinline int check_committed_ref(struct btrfs_root *root,
2347 struct btrfs_path *path,
Olivier Deprez0e641232021-09-23 10:07:05 +02002348 u64 objectid, u64 offset, u64 bytenr,
2349 bool strict)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002350{
2351 struct btrfs_fs_info *fs_info = root->fs_info;
2352 struct btrfs_root *extent_root = fs_info->extent_root;
2353 struct extent_buffer *leaf;
2354 struct btrfs_extent_data_ref *ref;
2355 struct btrfs_extent_inline_ref *iref;
2356 struct btrfs_extent_item *ei;
2357 struct btrfs_key key;
2358 u32 item_size;
2359 int type;
2360 int ret;
2361
2362 key.objectid = bytenr;
2363 key.offset = (u64)-1;
2364 key.type = BTRFS_EXTENT_ITEM_KEY;
2365
2366 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2367 if (ret < 0)
2368 goto out;
2369 BUG_ON(ret == 0); /* Corruption */
2370
2371 ret = -ENOENT;
2372 if (path->slots[0] == 0)
2373 goto out;
2374
2375 path->slots[0]--;
2376 leaf = path->nodes[0];
2377 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2378
2379 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2380 goto out;
2381
2382 ret = 1;
2383 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2384 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2385
David Brazdil0f672f62019-12-10 10:32:29 +00002386 /* If extent item has more than 1 inline ref then it's shared */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002387 if (item_size != sizeof(*ei) +
2388 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2389 goto out;
2390
Olivier Deprez0e641232021-09-23 10:07:05 +02002391 /*
2392 * If extent created before last snapshot => it's shared unless the
2393 * snapshot has been deleted. Use the heuristic if strict is false.
2394 */
2395 if (!strict &&
2396 (btrfs_extent_generation(leaf, ei) <=
2397 btrfs_root_last_snapshot(&root->root_item)))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002398 goto out;
2399
2400 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2401
David Brazdil0f672f62019-12-10 10:32:29 +00002402 /* If this extent has SHARED_DATA_REF then it's shared */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002403 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
2404 if (type != BTRFS_EXTENT_DATA_REF_KEY)
2405 goto out;
2406
2407 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2408 if (btrfs_extent_refs(leaf, ei) !=
2409 btrfs_extent_data_ref_count(leaf, ref) ||
2410 btrfs_extent_data_ref_root(leaf, ref) !=
2411 root->root_key.objectid ||
2412 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2413 btrfs_extent_data_ref_offset(leaf, ref) != offset)
2414 goto out;
2415
2416 ret = 0;
2417out:
2418 return ret;
2419}
2420
2421int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
Olivier Deprez0e641232021-09-23 10:07:05 +02002422 u64 bytenr, bool strict)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002423{
2424 struct btrfs_path *path;
2425 int ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002426
2427 path = btrfs_alloc_path();
2428 if (!path)
2429 return -ENOMEM;
2430
2431 do {
2432 ret = check_committed_ref(root, path, objectid,
Olivier Deprez0e641232021-09-23 10:07:05 +02002433 offset, bytenr, strict);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002434 if (ret && ret != -ENOENT)
2435 goto out;
2436
David Brazdil0f672f62019-12-10 10:32:29 +00002437 ret = check_delayed_ref(root, path, objectid, offset, bytenr);
2438 } while (ret == -EAGAIN);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002439
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002440out:
2441 btrfs_free_path(path);
2442 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2443 WARN_ON(ret > 0);
2444 return ret;
2445}
2446
2447static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2448 struct btrfs_root *root,
2449 struct extent_buffer *buf,
2450 int full_backref, int inc)
2451{
2452 struct btrfs_fs_info *fs_info = root->fs_info;
2453 u64 bytenr;
2454 u64 num_bytes;
2455 u64 parent;
2456 u64 ref_root;
2457 u32 nritems;
2458 struct btrfs_key key;
2459 struct btrfs_file_extent_item *fi;
David Brazdil0f672f62019-12-10 10:32:29 +00002460 struct btrfs_ref generic_ref = { 0 };
2461 bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002462 int i;
David Brazdil0f672f62019-12-10 10:32:29 +00002463 int action;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002464 int level;
2465 int ret = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002466
2467 if (btrfs_is_testing(fs_info))
2468 return 0;
2469
2470 ref_root = btrfs_header_owner(buf);
2471 nritems = btrfs_header_nritems(buf);
2472 level = btrfs_header_level(buf);
2473
2474 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
2475 return 0;
2476
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002477 if (full_backref)
2478 parent = buf->start;
2479 else
2480 parent = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00002481 if (inc)
2482 action = BTRFS_ADD_DELAYED_REF;
2483 else
2484 action = BTRFS_DROP_DELAYED_REF;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002485
2486 for (i = 0; i < nritems; i++) {
2487 if (level == 0) {
2488 btrfs_item_key_to_cpu(buf, &key, i);
2489 if (key.type != BTRFS_EXTENT_DATA_KEY)
2490 continue;
2491 fi = btrfs_item_ptr(buf, i,
2492 struct btrfs_file_extent_item);
2493 if (btrfs_file_extent_type(buf, fi) ==
2494 BTRFS_FILE_EXTENT_INLINE)
2495 continue;
2496 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2497 if (bytenr == 0)
2498 continue;
2499
2500 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2501 key.offset -= btrfs_file_extent_offset(buf, fi);
David Brazdil0f672f62019-12-10 10:32:29 +00002502 btrfs_init_generic_ref(&generic_ref, action, bytenr,
2503 num_bytes, parent);
2504 generic_ref.real_root = root->root_key.objectid;
2505 btrfs_init_data_ref(&generic_ref, ref_root, key.objectid,
2506 key.offset);
2507 generic_ref.skip_qgroup = for_reloc;
2508 if (inc)
2509 ret = btrfs_inc_extent_ref(trans, &generic_ref);
2510 else
2511 ret = btrfs_free_extent(trans, &generic_ref);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002512 if (ret)
2513 goto fail;
2514 } else {
2515 bytenr = btrfs_node_blockptr(buf, i);
2516 num_bytes = fs_info->nodesize;
David Brazdil0f672f62019-12-10 10:32:29 +00002517 btrfs_init_generic_ref(&generic_ref, action, bytenr,
2518 num_bytes, parent);
2519 generic_ref.real_root = root->root_key.objectid;
2520 btrfs_init_tree_ref(&generic_ref, level - 1, ref_root);
2521 generic_ref.skip_qgroup = for_reloc;
2522 if (inc)
2523 ret = btrfs_inc_extent_ref(trans, &generic_ref);
2524 else
2525 ret = btrfs_free_extent(trans, &generic_ref);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002526 if (ret)
2527 goto fail;
2528 }
2529 }
2530 return 0;
2531fail:
2532 return ret;
2533}
2534
2535int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2536 struct extent_buffer *buf, int full_backref)
2537{
2538 return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
2539}
2540
2541int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2542 struct extent_buffer *buf, int full_backref)
2543{
2544 return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
2545}
2546
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002547int btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
2548{
2549 struct btrfs_block_group_cache *block_group;
2550 int readonly = 0;
2551
2552 block_group = btrfs_lookup_block_group(fs_info, bytenr);
2553 if (!block_group || block_group->ro)
2554 readonly = 1;
2555 if (block_group)
2556 btrfs_put_block_group(block_group);
2557 return readonly;
2558}
2559
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002560static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
2561{
2562 struct btrfs_fs_info *fs_info = root->fs_info;
2563 u64 flags;
2564 u64 ret;
2565
2566 if (data)
2567 flags = BTRFS_BLOCK_GROUP_DATA;
2568 else if (root == fs_info->chunk_root)
2569 flags = BTRFS_BLOCK_GROUP_SYSTEM;
2570 else
2571 flags = BTRFS_BLOCK_GROUP_METADATA;
2572
David Brazdil0f672f62019-12-10 10:32:29 +00002573 ret = btrfs_get_alloc_profile(fs_info, flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002574 return ret;
2575}
2576
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002577static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
2578{
2579 struct btrfs_block_group_cache *cache;
2580 u64 bytenr;
2581
2582 spin_lock(&fs_info->block_group_cache_lock);
2583 bytenr = fs_info->first_logical_byte;
2584 spin_unlock(&fs_info->block_group_cache_lock);
2585
2586 if (bytenr < (u64)-1)
2587 return bytenr;
2588
2589 cache = btrfs_lookup_first_block_group(fs_info, search_start);
2590 if (!cache)
2591 return 0;
2592
2593 bytenr = cache->key.objectid;
2594 btrfs_put_block_group(cache);
2595
2596 return bytenr;
2597}
2598
David Brazdil0f672f62019-12-10 10:32:29 +00002599static int pin_down_extent(struct btrfs_block_group_cache *cache,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002600 u64 bytenr, u64 num_bytes, int reserved)
2601{
David Brazdil0f672f62019-12-10 10:32:29 +00002602 struct btrfs_fs_info *fs_info = cache->fs_info;
2603
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002604 spin_lock(&cache->space_info->lock);
2605 spin_lock(&cache->lock);
2606 cache->pinned += num_bytes;
David Brazdil0f672f62019-12-10 10:32:29 +00002607 btrfs_space_info_update_bytes_pinned(fs_info, cache->space_info,
2608 num_bytes);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002609 if (reserved) {
2610 cache->reserved -= num_bytes;
2611 cache->space_info->bytes_reserved -= num_bytes;
2612 }
2613 spin_unlock(&cache->lock);
2614 spin_unlock(&cache->space_info->lock);
2615
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002616 percpu_counter_add_batch(&cache->space_info->total_bytes_pinned,
2617 num_bytes, BTRFS_TOTAL_BYTES_PINNED_BATCH);
2618 set_extent_dirty(fs_info->pinned_extents, bytenr,
2619 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
2620 return 0;
2621}
2622
2623/*
2624 * this function must be called within transaction
2625 */
2626int btrfs_pin_extent(struct btrfs_fs_info *fs_info,
2627 u64 bytenr, u64 num_bytes, int reserved)
2628{
2629 struct btrfs_block_group_cache *cache;
2630
2631 cache = btrfs_lookup_block_group(fs_info, bytenr);
2632 BUG_ON(!cache); /* Logic error */
2633
David Brazdil0f672f62019-12-10 10:32:29 +00002634 pin_down_extent(cache, bytenr, num_bytes, reserved);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002635
2636 btrfs_put_block_group(cache);
2637 return 0;
2638}
2639
2640/*
2641 * this function must be called within transaction
2642 */
2643int btrfs_pin_extent_for_log_replay(struct btrfs_fs_info *fs_info,
2644 u64 bytenr, u64 num_bytes)
2645{
2646 struct btrfs_block_group_cache *cache;
2647 int ret;
2648
2649 cache = btrfs_lookup_block_group(fs_info, bytenr);
2650 if (!cache)
2651 return -EINVAL;
2652
2653 /*
2654 * pull in the free space cache (if any) so that our pin
2655 * removes the free space from the cache. We have load_only set
2656 * to one because the slow code to read in the free extents does check
2657 * the pinned extents.
2658 */
David Brazdil0f672f62019-12-10 10:32:29 +00002659 btrfs_cache_block_group(cache, 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002660
David Brazdil0f672f62019-12-10 10:32:29 +00002661 pin_down_extent(cache, bytenr, num_bytes, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002662
2663 /* remove us from the free space cache (if we're there at all) */
2664 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
2665 btrfs_put_block_group(cache);
2666 return ret;
2667}
2668
2669static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
2670 u64 start, u64 num_bytes)
2671{
2672 int ret;
2673 struct btrfs_block_group_cache *block_group;
2674 struct btrfs_caching_control *caching_ctl;
2675
2676 block_group = btrfs_lookup_block_group(fs_info, start);
2677 if (!block_group)
2678 return -EINVAL;
2679
David Brazdil0f672f62019-12-10 10:32:29 +00002680 btrfs_cache_block_group(block_group, 0);
2681 caching_ctl = btrfs_get_caching_control(block_group);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002682
2683 if (!caching_ctl) {
2684 /* Logic error */
David Brazdil0f672f62019-12-10 10:32:29 +00002685 BUG_ON(!btrfs_block_group_cache_done(block_group));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002686 ret = btrfs_remove_free_space(block_group, start, num_bytes);
2687 } else {
2688 mutex_lock(&caching_ctl->mutex);
2689
2690 if (start >= caching_ctl->progress) {
David Brazdil0f672f62019-12-10 10:32:29 +00002691 ret = btrfs_add_excluded_extent(fs_info, start,
2692 num_bytes);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002693 } else if (start + num_bytes <= caching_ctl->progress) {
2694 ret = btrfs_remove_free_space(block_group,
2695 start, num_bytes);
2696 } else {
2697 num_bytes = caching_ctl->progress - start;
2698 ret = btrfs_remove_free_space(block_group,
2699 start, num_bytes);
2700 if (ret)
2701 goto out_lock;
2702
2703 num_bytes = (start + num_bytes) -
2704 caching_ctl->progress;
2705 start = caching_ctl->progress;
David Brazdil0f672f62019-12-10 10:32:29 +00002706 ret = btrfs_add_excluded_extent(fs_info, start,
2707 num_bytes);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002708 }
2709out_lock:
2710 mutex_unlock(&caching_ctl->mutex);
David Brazdil0f672f62019-12-10 10:32:29 +00002711 btrfs_put_caching_control(caching_ctl);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002712 }
2713 btrfs_put_block_group(block_group);
2714 return ret;
2715}
2716
David Brazdil0f672f62019-12-10 10:32:29 +00002717int btrfs_exclude_logged_extents(struct extent_buffer *eb)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002718{
David Brazdil0f672f62019-12-10 10:32:29 +00002719 struct btrfs_fs_info *fs_info = eb->fs_info;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002720 struct btrfs_file_extent_item *item;
2721 struct btrfs_key key;
2722 int found_type;
2723 int i;
2724 int ret = 0;
2725
2726 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
2727 return 0;
2728
2729 for (i = 0; i < btrfs_header_nritems(eb); i++) {
2730 btrfs_item_key_to_cpu(eb, &key, i);
2731 if (key.type != BTRFS_EXTENT_DATA_KEY)
2732 continue;
2733 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
2734 found_type = btrfs_file_extent_type(eb, item);
2735 if (found_type == BTRFS_FILE_EXTENT_INLINE)
2736 continue;
2737 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
2738 continue;
2739 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
2740 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
2741 ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
2742 if (ret)
2743 break;
2744 }
2745
2746 return ret;
2747}
2748
2749static void
2750btrfs_inc_block_group_reservations(struct btrfs_block_group_cache *bg)
2751{
2752 atomic_inc(&bg->reservations);
2753}
2754
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002755void btrfs_prepare_extent_commit(struct btrfs_fs_info *fs_info)
2756{
2757 struct btrfs_caching_control *next;
2758 struct btrfs_caching_control *caching_ctl;
2759 struct btrfs_block_group_cache *cache;
2760
2761 down_write(&fs_info->commit_root_sem);
2762
2763 list_for_each_entry_safe(caching_ctl, next,
2764 &fs_info->caching_block_groups, list) {
2765 cache = caching_ctl->block_group;
David Brazdil0f672f62019-12-10 10:32:29 +00002766 if (btrfs_block_group_cache_done(cache)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002767 cache->last_byte_to_unpin = (u64)-1;
2768 list_del_init(&caching_ctl->list);
David Brazdil0f672f62019-12-10 10:32:29 +00002769 btrfs_put_caching_control(caching_ctl);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002770 } else {
2771 cache->last_byte_to_unpin = caching_ctl->progress;
2772 }
2773 }
2774
2775 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
2776 fs_info->pinned_extents = &fs_info->freed_extents[1];
2777 else
2778 fs_info->pinned_extents = &fs_info->freed_extents[0];
2779
2780 up_write(&fs_info->commit_root_sem);
2781
David Brazdil0f672f62019-12-10 10:32:29 +00002782 btrfs_update_global_block_rsv(fs_info);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002783}
2784
2785/*
2786 * Returns the free cluster for the given space info and sets empty_cluster to
2787 * what it should be based on the mount options.
2788 */
2789static struct btrfs_free_cluster *
2790fetch_cluster_info(struct btrfs_fs_info *fs_info,
2791 struct btrfs_space_info *space_info, u64 *empty_cluster)
2792{
2793 struct btrfs_free_cluster *ret = NULL;
2794
2795 *empty_cluster = 0;
2796 if (btrfs_mixed_space_info(space_info))
2797 return ret;
2798
2799 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
2800 ret = &fs_info->meta_alloc_cluster;
2801 if (btrfs_test_opt(fs_info, SSD))
2802 *empty_cluster = SZ_2M;
2803 else
2804 *empty_cluster = SZ_64K;
2805 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
2806 btrfs_test_opt(fs_info, SSD_SPREAD)) {
2807 *empty_cluster = SZ_2M;
2808 ret = &fs_info->data_alloc_cluster;
2809 }
2810
2811 return ret;
2812}
2813
2814static int unpin_extent_range(struct btrfs_fs_info *fs_info,
2815 u64 start, u64 end,
2816 const bool return_free_space)
2817{
2818 struct btrfs_block_group_cache *cache = NULL;
2819 struct btrfs_space_info *space_info;
2820 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
2821 struct btrfs_free_cluster *cluster = NULL;
2822 u64 len;
2823 u64 total_unpinned = 0;
2824 u64 empty_cluster = 0;
2825 bool readonly;
2826
2827 while (start <= end) {
2828 readonly = false;
2829 if (!cache ||
2830 start >= cache->key.objectid + cache->key.offset) {
2831 if (cache)
2832 btrfs_put_block_group(cache);
2833 total_unpinned = 0;
2834 cache = btrfs_lookup_block_group(fs_info, start);
2835 BUG_ON(!cache); /* Logic error */
2836
2837 cluster = fetch_cluster_info(fs_info,
2838 cache->space_info,
2839 &empty_cluster);
2840 empty_cluster <<= 1;
2841 }
2842
2843 len = cache->key.objectid + cache->key.offset - start;
2844 len = min(len, end + 1 - start);
2845
Olivier Deprez0e641232021-09-23 10:07:05 +02002846 if (start < cache->last_byte_to_unpin && return_free_space) {
2847 u64 add_len = min(len, cache->last_byte_to_unpin - start);
2848
2849 btrfs_add_free_space(cache, start, add_len);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002850 }
2851
2852 start += len;
2853 total_unpinned += len;
2854 space_info = cache->space_info;
2855
2856 /*
2857 * If this space cluster has been marked as fragmented and we've
2858 * unpinned enough in this block group to potentially allow a
2859 * cluster to be created inside of it go ahead and clear the
2860 * fragmented check.
2861 */
2862 if (cluster && cluster->fragmented &&
2863 total_unpinned > empty_cluster) {
2864 spin_lock(&cluster->lock);
2865 cluster->fragmented = 0;
2866 spin_unlock(&cluster->lock);
2867 }
2868
2869 spin_lock(&space_info->lock);
2870 spin_lock(&cache->lock);
2871 cache->pinned -= len;
David Brazdil0f672f62019-12-10 10:32:29 +00002872 btrfs_space_info_update_bytes_pinned(fs_info, space_info, -len);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002873 space_info->max_extent_size = 0;
2874 percpu_counter_add_batch(&space_info->total_bytes_pinned,
2875 -len, BTRFS_TOTAL_BYTES_PINNED_BATCH);
2876 if (cache->ro) {
2877 space_info->bytes_readonly += len;
2878 readonly = true;
2879 }
2880 spin_unlock(&cache->lock);
2881 if (!readonly && return_free_space &&
2882 global_rsv->space_info == space_info) {
2883 u64 to_add = len;
2884
2885 spin_lock(&global_rsv->lock);
2886 if (!global_rsv->full) {
2887 to_add = min(len, global_rsv->size -
2888 global_rsv->reserved);
2889 global_rsv->reserved += to_add;
David Brazdil0f672f62019-12-10 10:32:29 +00002890 btrfs_space_info_update_bytes_may_use(fs_info,
2891 space_info, to_add);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002892 if (global_rsv->reserved >= global_rsv->size)
2893 global_rsv->full = 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002894 len -= to_add;
2895 }
2896 spin_unlock(&global_rsv->lock);
2897 /* Add to any tickets we may have */
2898 if (len)
David Brazdil0f672f62019-12-10 10:32:29 +00002899 btrfs_try_granting_tickets(fs_info,
2900 space_info);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002901 }
2902 spin_unlock(&space_info->lock);
2903 }
2904
2905 if (cache)
2906 btrfs_put_block_group(cache);
2907 return 0;
2908}
2909
2910int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
2911{
2912 struct btrfs_fs_info *fs_info = trans->fs_info;
2913 struct btrfs_block_group_cache *block_group, *tmp;
2914 struct list_head *deleted_bgs;
2915 struct extent_io_tree *unpin;
2916 u64 start;
2917 u64 end;
2918 int ret;
2919
2920 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
2921 unpin = &fs_info->freed_extents[1];
2922 else
2923 unpin = &fs_info->freed_extents[0];
2924
Olivier Deprez0e641232021-09-23 10:07:05 +02002925 while (!TRANS_ABORTED(trans)) {
David Brazdil0f672f62019-12-10 10:32:29 +00002926 struct extent_state *cached_state = NULL;
2927
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002928 mutex_lock(&fs_info->unused_bg_unpin_mutex);
2929 ret = find_first_extent_bit(unpin, 0, &start, &end,
David Brazdil0f672f62019-12-10 10:32:29 +00002930 EXTENT_DIRTY, &cached_state);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002931 if (ret) {
2932 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2933 break;
2934 }
2935
2936 if (btrfs_test_opt(fs_info, DISCARD))
2937 ret = btrfs_discard_extent(fs_info, start,
2938 end + 1 - start, NULL);
2939
David Brazdil0f672f62019-12-10 10:32:29 +00002940 clear_extent_dirty(unpin, start, end, &cached_state);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002941 unpin_extent_range(fs_info, start, end, true);
2942 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
David Brazdil0f672f62019-12-10 10:32:29 +00002943 free_extent_state(cached_state);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002944 cond_resched();
2945 }
2946
2947 /*
2948 * Transaction is finished. We don't need the lock anymore. We
2949 * do need to clean up the block groups in case of a transaction
2950 * abort.
2951 */
2952 deleted_bgs = &trans->transaction->deleted_bgs;
2953 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
2954 u64 trimmed = 0;
2955
2956 ret = -EROFS;
Olivier Deprez0e641232021-09-23 10:07:05 +02002957 if (!TRANS_ABORTED(trans))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002958 ret = btrfs_discard_extent(fs_info,
2959 block_group->key.objectid,
2960 block_group->key.offset,
2961 &trimmed);
2962
2963 list_del_init(&block_group->bg_list);
2964 btrfs_put_block_group_trimming(block_group);
2965 btrfs_put_block_group(block_group);
2966
2967 if (ret) {
2968 const char *errstr = btrfs_decode_error(ret);
2969 btrfs_warn(fs_info,
2970 "discard failed while removing blockgroup: errno=%d %s",
2971 ret, errstr);
2972 }
2973 }
2974
2975 return 0;
2976}
2977
2978static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
2979 struct btrfs_delayed_ref_node *node, u64 parent,
2980 u64 root_objectid, u64 owner_objectid,
2981 u64 owner_offset, int refs_to_drop,
2982 struct btrfs_delayed_extent_op *extent_op)
2983{
2984 struct btrfs_fs_info *info = trans->fs_info;
2985 struct btrfs_key key;
2986 struct btrfs_path *path;
2987 struct btrfs_root *extent_root = info->extent_root;
2988 struct extent_buffer *leaf;
2989 struct btrfs_extent_item *ei;
2990 struct btrfs_extent_inline_ref *iref;
2991 int ret;
2992 int is_data;
2993 int extent_slot = 0;
2994 int found_extent = 0;
2995 int num_to_del = 1;
2996 u32 item_size;
2997 u64 refs;
2998 u64 bytenr = node->bytenr;
2999 u64 num_bytes = node->num_bytes;
3000 int last_ref = 0;
3001 bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
3002
3003 path = btrfs_alloc_path();
3004 if (!path)
3005 return -ENOMEM;
3006
3007 path->reada = READA_FORWARD;
3008 path->leave_spinning = 1;
3009
3010 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
3011 BUG_ON(!is_data && refs_to_drop != 1);
3012
3013 if (is_data)
3014 skinny_metadata = false;
3015
3016 ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
3017 parent, root_objectid, owner_objectid,
3018 owner_offset);
3019 if (ret == 0) {
3020 extent_slot = path->slots[0];
3021 while (extent_slot >= 0) {
3022 btrfs_item_key_to_cpu(path->nodes[0], &key,
3023 extent_slot);
3024 if (key.objectid != bytenr)
3025 break;
3026 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
3027 key.offset == num_bytes) {
3028 found_extent = 1;
3029 break;
3030 }
3031 if (key.type == BTRFS_METADATA_ITEM_KEY &&
3032 key.offset == owner_objectid) {
3033 found_extent = 1;
3034 break;
3035 }
3036 if (path->slots[0] - extent_slot > 5)
3037 break;
3038 extent_slot--;
3039 }
3040
3041 if (!found_extent) {
3042 BUG_ON(iref);
3043 ret = remove_extent_backref(trans, path, NULL,
3044 refs_to_drop,
3045 is_data, &last_ref);
3046 if (ret) {
3047 btrfs_abort_transaction(trans, ret);
3048 goto out;
3049 }
3050 btrfs_release_path(path);
3051 path->leave_spinning = 1;
3052
3053 key.objectid = bytenr;
3054 key.type = BTRFS_EXTENT_ITEM_KEY;
3055 key.offset = num_bytes;
3056
3057 if (!is_data && skinny_metadata) {
3058 key.type = BTRFS_METADATA_ITEM_KEY;
3059 key.offset = owner_objectid;
3060 }
3061
3062 ret = btrfs_search_slot(trans, extent_root,
3063 &key, path, -1, 1);
3064 if (ret > 0 && skinny_metadata && path->slots[0]) {
3065 /*
3066 * Couldn't find our skinny metadata item,
3067 * see if we have ye olde extent item.
3068 */
3069 path->slots[0]--;
3070 btrfs_item_key_to_cpu(path->nodes[0], &key,
3071 path->slots[0]);
3072 if (key.objectid == bytenr &&
3073 key.type == BTRFS_EXTENT_ITEM_KEY &&
3074 key.offset == num_bytes)
3075 ret = 0;
3076 }
3077
3078 if (ret > 0 && skinny_metadata) {
3079 skinny_metadata = false;
3080 key.objectid = bytenr;
3081 key.type = BTRFS_EXTENT_ITEM_KEY;
3082 key.offset = num_bytes;
3083 btrfs_release_path(path);
3084 ret = btrfs_search_slot(trans, extent_root,
3085 &key, path, -1, 1);
3086 }
3087
3088 if (ret) {
3089 btrfs_err(info,
3090 "umm, got %d back from search, was looking for %llu",
3091 ret, bytenr);
3092 if (ret > 0)
3093 btrfs_print_leaf(path->nodes[0]);
3094 }
3095 if (ret < 0) {
3096 btrfs_abort_transaction(trans, ret);
3097 goto out;
3098 }
3099 extent_slot = path->slots[0];
3100 }
3101 } else if (WARN_ON(ret == -ENOENT)) {
3102 btrfs_print_leaf(path->nodes[0]);
3103 btrfs_err(info,
3104 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
3105 bytenr, parent, root_objectid, owner_objectid,
3106 owner_offset);
3107 btrfs_abort_transaction(trans, ret);
3108 goto out;
3109 } else {
3110 btrfs_abort_transaction(trans, ret);
3111 goto out;
3112 }
3113
3114 leaf = path->nodes[0];
3115 item_size = btrfs_item_size_nr(leaf, extent_slot);
3116 if (unlikely(item_size < sizeof(*ei))) {
3117 ret = -EINVAL;
3118 btrfs_print_v0_err(info);
3119 btrfs_abort_transaction(trans, ret);
3120 goto out;
3121 }
3122 ei = btrfs_item_ptr(leaf, extent_slot,
3123 struct btrfs_extent_item);
3124 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
3125 key.type == BTRFS_EXTENT_ITEM_KEY) {
3126 struct btrfs_tree_block_info *bi;
3127 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
3128 bi = (struct btrfs_tree_block_info *)(ei + 1);
3129 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
3130 }
3131
3132 refs = btrfs_extent_refs(leaf, ei);
3133 if (refs < refs_to_drop) {
3134 btrfs_err(info,
3135 "trying to drop %d refs but we only have %Lu for bytenr %Lu",
3136 refs_to_drop, refs, bytenr);
3137 ret = -EINVAL;
3138 btrfs_abort_transaction(trans, ret);
3139 goto out;
3140 }
3141 refs -= refs_to_drop;
3142
3143 if (refs > 0) {
3144 if (extent_op)
3145 __run_delayed_extent_op(extent_op, leaf, ei);
3146 /*
3147 * In the case of inline back ref, reference count will
3148 * be updated by remove_extent_backref
3149 */
3150 if (iref) {
3151 BUG_ON(!found_extent);
3152 } else {
3153 btrfs_set_extent_refs(leaf, ei, refs);
3154 btrfs_mark_buffer_dirty(leaf);
3155 }
3156 if (found_extent) {
3157 ret = remove_extent_backref(trans, path, iref,
3158 refs_to_drop, is_data,
3159 &last_ref);
3160 if (ret) {
3161 btrfs_abort_transaction(trans, ret);
3162 goto out;
3163 }
3164 }
3165 } else {
3166 if (found_extent) {
3167 BUG_ON(is_data && refs_to_drop !=
3168 extent_data_ref_count(path, iref));
3169 if (iref) {
3170 BUG_ON(path->slots[0] != extent_slot);
3171 } else {
3172 BUG_ON(path->slots[0] != extent_slot + 1);
3173 path->slots[0] = extent_slot;
3174 num_to_del = 2;
3175 }
3176 }
3177
3178 last_ref = 1;
3179 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
3180 num_to_del);
3181 if (ret) {
3182 btrfs_abort_transaction(trans, ret);
3183 goto out;
3184 }
3185 btrfs_release_path(path);
3186
3187 if (is_data) {
Olivier Deprez0e641232021-09-23 10:07:05 +02003188 ret = btrfs_del_csums(trans, info->csum_root, bytenr,
3189 num_bytes);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003190 if (ret) {
3191 btrfs_abort_transaction(trans, ret);
3192 goto out;
3193 }
3194 }
3195
3196 ret = add_to_free_space_tree(trans, bytenr, num_bytes);
3197 if (ret) {
3198 btrfs_abort_transaction(trans, ret);
3199 goto out;
3200 }
3201
David Brazdil0f672f62019-12-10 10:32:29 +00003202 ret = btrfs_update_block_group(trans, bytenr, num_bytes, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003203 if (ret) {
3204 btrfs_abort_transaction(trans, ret);
3205 goto out;
3206 }
3207 }
3208 btrfs_release_path(path);
3209
3210out:
3211 btrfs_free_path(path);
3212 return ret;
3213}
3214
3215/*
3216 * when we free an block, it is possible (and likely) that we free the last
3217 * delayed ref for that extent as well. This searches the delayed ref tree for
3218 * a given extent, and if there are no other delayed refs to be processed, it
3219 * removes it from the tree.
3220 */
3221static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
3222 u64 bytenr)
3223{
3224 struct btrfs_delayed_ref_head *head;
3225 struct btrfs_delayed_ref_root *delayed_refs;
3226 int ret = 0;
3227
3228 delayed_refs = &trans->transaction->delayed_refs;
3229 spin_lock(&delayed_refs->lock);
3230 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
3231 if (!head)
3232 goto out_delayed_unlock;
3233
3234 spin_lock(&head->lock);
David Brazdil0f672f62019-12-10 10:32:29 +00003235 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003236 goto out;
3237
David Brazdil0f672f62019-12-10 10:32:29 +00003238 if (cleanup_extent_op(head) != NULL)
3239 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003240
3241 /*
3242 * waiting for the lock here would deadlock. If someone else has it
3243 * locked they are already in the process of dropping it anyway
3244 */
3245 if (!mutex_trylock(&head->mutex))
3246 goto out;
3247
David Brazdil0f672f62019-12-10 10:32:29 +00003248 btrfs_delete_ref_head(delayed_refs, head);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003249 head->processing = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00003250
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003251 spin_unlock(&head->lock);
3252 spin_unlock(&delayed_refs->lock);
3253
3254 BUG_ON(head->extent_op);
3255 if (head->must_insert_reserved)
3256 ret = 1;
3257
David Brazdil0f672f62019-12-10 10:32:29 +00003258 btrfs_cleanup_ref_head_accounting(trans->fs_info, delayed_refs, head);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003259 mutex_unlock(&head->mutex);
3260 btrfs_put_delayed_ref_head(head);
3261 return ret;
3262out:
3263 spin_unlock(&head->lock);
3264
3265out_delayed_unlock:
3266 spin_unlock(&delayed_refs->lock);
3267 return 0;
3268}
3269
3270void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
3271 struct btrfs_root *root,
3272 struct extent_buffer *buf,
3273 u64 parent, int last_ref)
3274{
3275 struct btrfs_fs_info *fs_info = root->fs_info;
David Brazdil0f672f62019-12-10 10:32:29 +00003276 struct btrfs_ref generic_ref = { 0 };
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003277 int pin = 1;
3278 int ret;
3279
David Brazdil0f672f62019-12-10 10:32:29 +00003280 btrfs_init_generic_ref(&generic_ref, BTRFS_DROP_DELAYED_REF,
3281 buf->start, buf->len, parent);
3282 btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf),
3283 root->root_key.objectid);
3284
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003285 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
3286 int old_ref_mod, new_ref_mod;
3287
David Brazdil0f672f62019-12-10 10:32:29 +00003288 btrfs_ref_tree_mod(fs_info, &generic_ref);
3289 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003290 &old_ref_mod, &new_ref_mod);
3291 BUG_ON(ret); /* -ENOMEM */
3292 pin = old_ref_mod >= 0 && new_ref_mod < 0;
3293 }
3294
3295 if (last_ref && btrfs_header_generation(buf) == trans->transid) {
3296 struct btrfs_block_group_cache *cache;
3297
3298 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
3299 ret = check_ref_cleanup(trans, buf->start);
3300 if (!ret)
3301 goto out;
3302 }
3303
3304 pin = 0;
3305 cache = btrfs_lookup_block_group(fs_info, buf->start);
3306
3307 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
David Brazdil0f672f62019-12-10 10:32:29 +00003308 pin_down_extent(cache, buf->start, buf->len, 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003309 btrfs_put_block_group(cache);
3310 goto out;
3311 }
3312
3313 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
3314
3315 btrfs_add_free_space(cache, buf->start, buf->len);
3316 btrfs_free_reserved_bytes(cache, buf->len, 0);
3317 btrfs_put_block_group(cache);
3318 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
3319 }
3320out:
3321 if (pin)
David Brazdil0f672f62019-12-10 10:32:29 +00003322 add_pinned_bytes(fs_info, &generic_ref);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003323
3324 if (last_ref) {
3325 /*
3326 * Deleting the buffer, clear the corrupt flag since it doesn't
3327 * matter anymore.
3328 */
3329 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
3330 }
3331}
3332
3333/* Can return -ENOMEM */
David Brazdil0f672f62019-12-10 10:32:29 +00003334int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003335{
David Brazdil0f672f62019-12-10 10:32:29 +00003336 struct btrfs_fs_info *fs_info = trans->fs_info;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003337 int old_ref_mod, new_ref_mod;
3338 int ret;
3339
3340 if (btrfs_is_testing(fs_info))
3341 return 0;
3342
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003343 /*
3344 * tree log blocks never actually go into the extent allocation
3345 * tree, just update pinning info and exit early.
3346 */
David Brazdil0f672f62019-12-10 10:32:29 +00003347 if ((ref->type == BTRFS_REF_METADATA &&
3348 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
3349 (ref->type == BTRFS_REF_DATA &&
3350 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003351 /* unlocks the pinned mutex */
David Brazdil0f672f62019-12-10 10:32:29 +00003352 btrfs_pin_extent(fs_info, ref->bytenr, ref->len, 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003353 old_ref_mod = new_ref_mod = 0;
3354 ret = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00003355 } else if (ref->type == BTRFS_REF_METADATA) {
3356 ret = btrfs_add_delayed_tree_ref(trans, ref, NULL,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003357 &old_ref_mod, &new_ref_mod);
3358 } else {
David Brazdil0f672f62019-12-10 10:32:29 +00003359 ret = btrfs_add_delayed_data_ref(trans, ref, 0,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003360 &old_ref_mod, &new_ref_mod);
3361 }
3362
David Brazdil0f672f62019-12-10 10:32:29 +00003363 if (!((ref->type == BTRFS_REF_METADATA &&
3364 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
3365 (ref->type == BTRFS_REF_DATA &&
3366 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)))
3367 btrfs_ref_tree_mod(fs_info, ref);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003368
David Brazdil0f672f62019-12-10 10:32:29 +00003369 if (ret == 0 && old_ref_mod >= 0 && new_ref_mod < 0)
3370 add_pinned_bytes(fs_info, ref);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003371
3372 return ret;
3373}
3374
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003375enum btrfs_loop_type {
David Brazdil0f672f62019-12-10 10:32:29 +00003376 LOOP_CACHING_NOWAIT,
3377 LOOP_CACHING_WAIT,
3378 LOOP_ALLOC_CHUNK,
3379 LOOP_NO_EMPTY_SIZE,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003380};
3381
3382static inline void
3383btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
3384 int delalloc)
3385{
3386 if (delalloc)
3387 down_read(&cache->data_rwsem);
3388}
3389
3390static inline void
3391btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
3392 int delalloc)
3393{
3394 btrfs_get_block_group(cache);
3395 if (delalloc)
3396 down_read(&cache->data_rwsem);
3397}
3398
3399static struct btrfs_block_group_cache *
3400btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
3401 struct btrfs_free_cluster *cluster,
3402 int delalloc)
3403{
3404 struct btrfs_block_group_cache *used_bg = NULL;
3405
3406 spin_lock(&cluster->refill_lock);
3407 while (1) {
3408 used_bg = cluster->block_group;
3409 if (!used_bg)
3410 return NULL;
3411
3412 if (used_bg == block_group)
3413 return used_bg;
3414
3415 btrfs_get_block_group(used_bg);
3416
3417 if (!delalloc)
3418 return used_bg;
3419
3420 if (down_read_trylock(&used_bg->data_rwsem))
3421 return used_bg;
3422
3423 spin_unlock(&cluster->refill_lock);
3424
3425 /* We should only have one-level nested. */
3426 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
3427
3428 spin_lock(&cluster->refill_lock);
3429 if (used_bg == cluster->block_group)
3430 return used_bg;
3431
3432 up_read(&used_bg->data_rwsem);
3433 btrfs_put_block_group(used_bg);
3434 }
3435}
3436
3437static inline void
3438btrfs_release_block_group(struct btrfs_block_group_cache *cache,
3439 int delalloc)
3440{
3441 if (delalloc)
3442 up_read(&cache->data_rwsem);
3443 btrfs_put_block_group(cache);
3444}
3445
3446/*
David Brazdil0f672f62019-12-10 10:32:29 +00003447 * Structure used internally for find_free_extent() function. Wraps needed
3448 * parameters.
3449 */
3450struct find_free_extent_ctl {
3451 /* Basic allocation info */
3452 u64 ram_bytes;
3453 u64 num_bytes;
3454 u64 empty_size;
3455 u64 flags;
3456 int delalloc;
3457
3458 /* Where to start the search inside the bg */
3459 u64 search_start;
3460
3461 /* For clustered allocation */
3462 u64 empty_cluster;
3463
3464 bool have_caching_bg;
3465 bool orig_have_caching_bg;
3466
3467 /* RAID index, converted from flags */
3468 int index;
3469
3470 /*
3471 * Current loop number, check find_free_extent_update_loop() for details
3472 */
3473 int loop;
3474
3475 /*
3476 * Whether we're refilling a cluster, if true we need to re-search
3477 * current block group but don't try to refill the cluster again.
3478 */
3479 bool retry_clustered;
3480
3481 /*
3482 * Whether we're updating free space cache, if true we need to re-search
3483 * current block group but don't try updating free space cache again.
3484 */
3485 bool retry_unclustered;
3486
3487 /* If current block group is cached */
3488 int cached;
3489
3490 /* Max contiguous hole found */
3491 u64 max_extent_size;
3492
3493 /* Total free space from free space cache, not always contiguous */
3494 u64 total_free_space;
3495
3496 /* Found result */
3497 u64 found_offset;
3498};
3499
3500
3501/*
3502 * Helper function for find_free_extent().
3503 *
3504 * Return -ENOENT to inform caller that we need fallback to unclustered mode.
3505 * Return -EAGAIN to inform caller that we need to re-search this block group
3506 * Return >0 to inform caller that we find nothing
3507 * Return 0 means we have found a location and set ffe_ctl->found_offset.
3508 */
3509static int find_free_extent_clustered(struct btrfs_block_group_cache *bg,
3510 struct btrfs_free_cluster *last_ptr,
3511 struct find_free_extent_ctl *ffe_ctl,
3512 struct btrfs_block_group_cache **cluster_bg_ret)
3513{
3514 struct btrfs_block_group_cache *cluster_bg;
3515 u64 aligned_cluster;
3516 u64 offset;
3517 int ret;
3518
3519 cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc);
3520 if (!cluster_bg)
3521 goto refill_cluster;
3522 if (cluster_bg != bg && (cluster_bg->ro ||
3523 !block_group_bits(cluster_bg, ffe_ctl->flags)))
3524 goto release_cluster;
3525
3526 offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
3527 ffe_ctl->num_bytes, cluster_bg->key.objectid,
3528 &ffe_ctl->max_extent_size);
3529 if (offset) {
3530 /* We have a block, we're done */
3531 spin_unlock(&last_ptr->refill_lock);
3532 trace_btrfs_reserve_extent_cluster(cluster_bg,
3533 ffe_ctl->search_start, ffe_ctl->num_bytes);
3534 *cluster_bg_ret = cluster_bg;
3535 ffe_ctl->found_offset = offset;
3536 return 0;
3537 }
3538 WARN_ON(last_ptr->block_group != cluster_bg);
3539
3540release_cluster:
3541 /*
3542 * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
3543 * lets just skip it and let the allocator find whatever block it can
3544 * find. If we reach this point, we will have tried the cluster
3545 * allocator plenty of times and not have found anything, so we are
3546 * likely way too fragmented for the clustering stuff to find anything.
3547 *
3548 * However, if the cluster is taken from the current block group,
3549 * release the cluster first, so that we stand a better chance of
3550 * succeeding in the unclustered allocation.
3551 */
3552 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
3553 spin_unlock(&last_ptr->refill_lock);
3554 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3555 return -ENOENT;
3556 }
3557
3558 /* This cluster didn't work out, free it and start over */
3559 btrfs_return_cluster_to_free_space(NULL, last_ptr);
3560
3561 if (cluster_bg != bg)
3562 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3563
3564refill_cluster:
3565 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
3566 spin_unlock(&last_ptr->refill_lock);
3567 return -ENOENT;
3568 }
3569
3570 aligned_cluster = max_t(u64,
3571 ffe_ctl->empty_cluster + ffe_ctl->empty_size,
3572 bg->full_stripe_len);
3573 ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
3574 ffe_ctl->num_bytes, aligned_cluster);
3575 if (ret == 0) {
3576 /* Now pull our allocation out of this cluster */
3577 offset = btrfs_alloc_from_cluster(bg, last_ptr,
3578 ffe_ctl->num_bytes, ffe_ctl->search_start,
3579 &ffe_ctl->max_extent_size);
3580 if (offset) {
3581 /* We found one, proceed */
3582 spin_unlock(&last_ptr->refill_lock);
3583 trace_btrfs_reserve_extent_cluster(bg,
3584 ffe_ctl->search_start,
3585 ffe_ctl->num_bytes);
3586 ffe_ctl->found_offset = offset;
3587 return 0;
3588 }
3589 } else if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
3590 !ffe_ctl->retry_clustered) {
3591 spin_unlock(&last_ptr->refill_lock);
3592
3593 ffe_ctl->retry_clustered = true;
3594 btrfs_wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
3595 ffe_ctl->empty_cluster + ffe_ctl->empty_size);
3596 return -EAGAIN;
3597 }
3598 /*
3599 * At this point we either didn't find a cluster or we weren't able to
3600 * allocate a block from our cluster. Free the cluster we've been
3601 * trying to use, and go to the next block group.
3602 */
3603 btrfs_return_cluster_to_free_space(NULL, last_ptr);
3604 spin_unlock(&last_ptr->refill_lock);
3605 return 1;
3606}
3607
3608/*
3609 * Return >0 to inform caller that we find nothing
3610 * Return 0 when we found an free extent and set ffe_ctrl->found_offset
3611 * Return -EAGAIN to inform caller that we need to re-search this block group
3612 */
3613static int find_free_extent_unclustered(struct btrfs_block_group_cache *bg,
3614 struct btrfs_free_cluster *last_ptr,
3615 struct find_free_extent_ctl *ffe_ctl)
3616{
3617 u64 offset;
3618
3619 /*
3620 * We are doing an unclustered allocation, set the fragmented flag so
3621 * we don't bother trying to setup a cluster again until we get more
3622 * space.
3623 */
3624 if (unlikely(last_ptr)) {
3625 spin_lock(&last_ptr->lock);
3626 last_ptr->fragmented = 1;
3627 spin_unlock(&last_ptr->lock);
3628 }
3629 if (ffe_ctl->cached) {
3630 struct btrfs_free_space_ctl *free_space_ctl;
3631
3632 free_space_ctl = bg->free_space_ctl;
3633 spin_lock(&free_space_ctl->tree_lock);
3634 if (free_space_ctl->free_space <
3635 ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
3636 ffe_ctl->empty_size) {
3637 ffe_ctl->total_free_space = max_t(u64,
3638 ffe_ctl->total_free_space,
3639 free_space_ctl->free_space);
3640 spin_unlock(&free_space_ctl->tree_lock);
3641 return 1;
3642 }
3643 spin_unlock(&free_space_ctl->tree_lock);
3644 }
3645
3646 offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
3647 ffe_ctl->num_bytes, ffe_ctl->empty_size,
3648 &ffe_ctl->max_extent_size);
3649
3650 /*
3651 * If we didn't find a chunk, and we haven't failed on this block group
3652 * before, and this block group is in the middle of caching and we are
3653 * ok with waiting, then go ahead and wait for progress to be made, and
3654 * set @retry_unclustered to true.
3655 *
3656 * If @retry_unclustered is true then we've already waited on this
3657 * block group once and should move on to the next block group.
3658 */
3659 if (!offset && !ffe_ctl->retry_unclustered && !ffe_ctl->cached &&
3660 ffe_ctl->loop > LOOP_CACHING_NOWAIT) {
3661 btrfs_wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
3662 ffe_ctl->empty_size);
3663 ffe_ctl->retry_unclustered = true;
3664 return -EAGAIN;
3665 } else if (!offset) {
3666 return 1;
3667 }
3668 ffe_ctl->found_offset = offset;
3669 return 0;
3670}
3671
3672/*
3673 * Return >0 means caller needs to re-search for free extent
3674 * Return 0 means we have the needed free extent.
3675 * Return <0 means we failed to locate any free extent.
3676 */
3677static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
3678 struct btrfs_free_cluster *last_ptr,
3679 struct btrfs_key *ins,
3680 struct find_free_extent_ctl *ffe_ctl,
3681 int full_search, bool use_cluster)
3682{
3683 struct btrfs_root *root = fs_info->extent_root;
3684 int ret;
3685
3686 if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
3687 ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
3688 ffe_ctl->orig_have_caching_bg = true;
3689
3690 if (!ins->objectid && ffe_ctl->loop >= LOOP_CACHING_WAIT &&
3691 ffe_ctl->have_caching_bg)
3692 return 1;
3693
3694 if (!ins->objectid && ++(ffe_ctl->index) < BTRFS_NR_RAID_TYPES)
3695 return 1;
3696
3697 if (ins->objectid) {
3698 if (!use_cluster && last_ptr) {
3699 spin_lock(&last_ptr->lock);
3700 last_ptr->window_start = ins->objectid;
3701 spin_unlock(&last_ptr->lock);
3702 }
3703 return 0;
3704 }
3705
3706 /*
3707 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
3708 * caching kthreads as we move along
3709 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
3710 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
3711 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
3712 * again
3713 */
3714 if (ffe_ctl->loop < LOOP_NO_EMPTY_SIZE) {
3715 ffe_ctl->index = 0;
3716 if (ffe_ctl->loop == LOOP_CACHING_NOWAIT) {
3717 /*
3718 * We want to skip the LOOP_CACHING_WAIT step if we
3719 * don't have any uncached bgs and we've already done a
3720 * full search through.
3721 */
3722 if (ffe_ctl->orig_have_caching_bg || !full_search)
3723 ffe_ctl->loop = LOOP_CACHING_WAIT;
3724 else
3725 ffe_ctl->loop = LOOP_ALLOC_CHUNK;
3726 } else {
3727 ffe_ctl->loop++;
3728 }
3729
3730 if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
3731 struct btrfs_trans_handle *trans;
3732 int exist = 0;
3733
3734 trans = current->journal_info;
3735 if (trans)
3736 exist = 1;
3737 else
3738 trans = btrfs_join_transaction(root);
3739
3740 if (IS_ERR(trans)) {
3741 ret = PTR_ERR(trans);
3742 return ret;
3743 }
3744
3745 ret = btrfs_chunk_alloc(trans, ffe_ctl->flags,
3746 CHUNK_ALLOC_FORCE);
3747
3748 /*
3749 * If we can't allocate a new chunk we've already looped
3750 * through at least once, move on to the NO_EMPTY_SIZE
3751 * case.
3752 */
3753 if (ret == -ENOSPC)
3754 ffe_ctl->loop = LOOP_NO_EMPTY_SIZE;
3755
3756 /* Do not bail out on ENOSPC since we can do more. */
3757 if (ret < 0 && ret != -ENOSPC)
3758 btrfs_abort_transaction(trans, ret);
3759 else
3760 ret = 0;
3761 if (!exist)
3762 btrfs_end_transaction(trans);
3763 if (ret)
3764 return ret;
3765 }
3766
3767 if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
3768 /*
3769 * Don't loop again if we already have no empty_size and
3770 * no empty_cluster.
3771 */
3772 if (ffe_ctl->empty_size == 0 &&
3773 ffe_ctl->empty_cluster == 0)
3774 return -ENOSPC;
3775 ffe_ctl->empty_size = 0;
3776 ffe_ctl->empty_cluster = 0;
3777 }
3778 return 1;
3779 }
3780 return -ENOSPC;
3781}
3782
3783/*
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003784 * walks the btree of allocated extents and find a hole of a given size.
3785 * The key ins is changed to record the hole:
3786 * ins->objectid == start position
3787 * ins->flags = BTRFS_EXTENT_ITEM_KEY
3788 * ins->offset == the size of the hole.
3789 * Any available blocks before search_start are skipped.
3790 *
3791 * If there is no suitable free space, we will record the max size of
3792 * the free space extent currently.
David Brazdil0f672f62019-12-10 10:32:29 +00003793 *
3794 * The overall logic and call chain:
3795 *
3796 * find_free_extent()
3797 * |- Iterate through all block groups
3798 * | |- Get a valid block group
3799 * | |- Try to do clustered allocation in that block group
3800 * | |- Try to do unclustered allocation in that block group
3801 * | |- Check if the result is valid
3802 * | | |- If valid, then exit
3803 * | |- Jump to next block group
3804 * |
3805 * |- Push harder to find free extents
3806 * |- If not found, re-iterate all block groups
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003807 */
Olivier Deprez0e641232021-09-23 10:07:05 +02003808static noinline int find_free_extent(struct btrfs_root *root,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003809 u64 ram_bytes, u64 num_bytes, u64 empty_size,
3810 u64 hint_byte, struct btrfs_key *ins,
3811 u64 flags, int delalloc)
3812{
Olivier Deprez0e641232021-09-23 10:07:05 +02003813 struct btrfs_fs_info *fs_info = root->fs_info;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003814 int ret = 0;
Olivier Deprez0e641232021-09-23 10:07:05 +02003815 int cache_block_group_error = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003816 struct btrfs_free_cluster *last_ptr = NULL;
3817 struct btrfs_block_group_cache *block_group = NULL;
David Brazdil0f672f62019-12-10 10:32:29 +00003818 struct find_free_extent_ctl ffe_ctl = {0};
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003819 struct btrfs_space_info *space_info;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003820 bool use_cluster = true;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003821 bool full_search = false;
3822
3823 WARN_ON(num_bytes < fs_info->sectorsize);
David Brazdil0f672f62019-12-10 10:32:29 +00003824
3825 ffe_ctl.ram_bytes = ram_bytes;
3826 ffe_ctl.num_bytes = num_bytes;
3827 ffe_ctl.empty_size = empty_size;
3828 ffe_ctl.flags = flags;
3829 ffe_ctl.search_start = 0;
3830 ffe_ctl.retry_clustered = false;
3831 ffe_ctl.retry_unclustered = false;
3832 ffe_ctl.delalloc = delalloc;
3833 ffe_ctl.index = btrfs_bg_flags_to_raid_index(flags);
3834 ffe_ctl.have_caching_bg = false;
3835 ffe_ctl.orig_have_caching_bg = false;
3836 ffe_ctl.found_offset = 0;
3837
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003838 ins->type = BTRFS_EXTENT_ITEM_KEY;
3839 ins->objectid = 0;
3840 ins->offset = 0;
3841
Olivier Deprez0e641232021-09-23 10:07:05 +02003842 trace_find_free_extent(root, num_bytes, empty_size, flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003843
David Brazdil0f672f62019-12-10 10:32:29 +00003844 space_info = btrfs_find_space_info(fs_info, flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003845 if (!space_info) {
3846 btrfs_err(fs_info, "No space info for %llu", flags);
3847 return -ENOSPC;
3848 }
3849
3850 /*
3851 * If our free space is heavily fragmented we may not be able to make
3852 * big contiguous allocations, so instead of doing the expensive search
3853 * for free space, simply return ENOSPC with our max_extent_size so we
3854 * can go ahead and search for a more manageable chunk.
3855 *
3856 * If our max_extent_size is large enough for our allocation simply
3857 * disable clustering since we will likely not be able to find enough
3858 * space to create a cluster and induce latency trying.
3859 */
3860 if (unlikely(space_info->max_extent_size)) {
3861 spin_lock(&space_info->lock);
3862 if (space_info->max_extent_size &&
3863 num_bytes > space_info->max_extent_size) {
3864 ins->offset = space_info->max_extent_size;
3865 spin_unlock(&space_info->lock);
3866 return -ENOSPC;
3867 } else if (space_info->max_extent_size) {
3868 use_cluster = false;
3869 }
3870 spin_unlock(&space_info->lock);
3871 }
3872
David Brazdil0f672f62019-12-10 10:32:29 +00003873 last_ptr = fetch_cluster_info(fs_info, space_info,
3874 &ffe_ctl.empty_cluster);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003875 if (last_ptr) {
3876 spin_lock(&last_ptr->lock);
3877 if (last_ptr->block_group)
3878 hint_byte = last_ptr->window_start;
3879 if (last_ptr->fragmented) {
3880 /*
3881 * We still set window_start so we can keep track of the
3882 * last place we found an allocation to try and save
3883 * some time.
3884 */
3885 hint_byte = last_ptr->window_start;
3886 use_cluster = false;
3887 }
3888 spin_unlock(&last_ptr->lock);
3889 }
3890
David Brazdil0f672f62019-12-10 10:32:29 +00003891 ffe_ctl.search_start = max(ffe_ctl.search_start,
3892 first_logical_byte(fs_info, 0));
3893 ffe_ctl.search_start = max(ffe_ctl.search_start, hint_byte);
3894 if (ffe_ctl.search_start == hint_byte) {
3895 block_group = btrfs_lookup_block_group(fs_info,
3896 ffe_ctl.search_start);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003897 /*
3898 * we don't want to use the block group if it doesn't match our
3899 * allocation bits, or if its not cached.
3900 *
3901 * However if we are re-searching with an ideal block group
3902 * picked out then we don't care that the block group is cached.
3903 */
3904 if (block_group && block_group_bits(block_group, flags) &&
3905 block_group->cached != BTRFS_CACHE_NO) {
3906 down_read(&space_info->groups_sem);
3907 if (list_empty(&block_group->list) ||
3908 block_group->ro) {
3909 /*
3910 * someone is removing this block group,
3911 * we can't jump into the have_block_group
3912 * target because our list pointers are not
3913 * valid
3914 */
3915 btrfs_put_block_group(block_group);
3916 up_read(&space_info->groups_sem);
3917 } else {
David Brazdil0f672f62019-12-10 10:32:29 +00003918 ffe_ctl.index = btrfs_bg_flags_to_raid_index(
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003919 block_group->flags);
3920 btrfs_lock_block_group(block_group, delalloc);
3921 goto have_block_group;
3922 }
3923 } else if (block_group) {
3924 btrfs_put_block_group(block_group);
3925 }
3926 }
3927search:
David Brazdil0f672f62019-12-10 10:32:29 +00003928 ffe_ctl.have_caching_bg = false;
3929 if (ffe_ctl.index == btrfs_bg_flags_to_raid_index(flags) ||
3930 ffe_ctl.index == 0)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003931 full_search = true;
3932 down_read(&space_info->groups_sem);
David Brazdil0f672f62019-12-10 10:32:29 +00003933 list_for_each_entry(block_group,
3934 &space_info->block_groups[ffe_ctl.index], list) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003935 /* If the block group is read-only, we can skip it entirely. */
3936 if (unlikely(block_group->ro))
3937 continue;
3938
3939 btrfs_grab_block_group(block_group, delalloc);
David Brazdil0f672f62019-12-10 10:32:29 +00003940 ffe_ctl.search_start = block_group->key.objectid;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003941
3942 /*
3943 * this can happen if we end up cycling through all the
3944 * raid types, but we want to make sure we only allocate
3945 * for the proper type.
3946 */
3947 if (!block_group_bits(block_group, flags)) {
3948 u64 extra = BTRFS_BLOCK_GROUP_DUP |
David Brazdil0f672f62019-12-10 10:32:29 +00003949 BTRFS_BLOCK_GROUP_RAID1_MASK |
3950 BTRFS_BLOCK_GROUP_RAID56_MASK |
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003951 BTRFS_BLOCK_GROUP_RAID10;
3952
3953 /*
3954 * if they asked for extra copies and this block group
3955 * doesn't provide them, bail. This does allow us to
3956 * fill raid0 from raid1.
3957 */
3958 if ((flags & extra) && !(block_group->flags & extra))
3959 goto loop;
David Brazdil0f672f62019-12-10 10:32:29 +00003960
3961 /*
3962 * This block group has different flags than we want.
3963 * It's possible that we have MIXED_GROUP flag but no
3964 * block group is mixed. Just skip such block group.
3965 */
3966 btrfs_release_block_group(block_group, delalloc);
3967 continue;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003968 }
3969
3970have_block_group:
David Brazdil0f672f62019-12-10 10:32:29 +00003971 ffe_ctl.cached = btrfs_block_group_cache_done(block_group);
3972 if (unlikely(!ffe_ctl.cached)) {
3973 ffe_ctl.have_caching_bg = true;
3974 ret = btrfs_cache_block_group(block_group, 0);
Olivier Deprez0e641232021-09-23 10:07:05 +02003975
3976 /*
3977 * If we get ENOMEM here or something else we want to
3978 * try other block groups, because it may not be fatal.
3979 * However if we can't find anything else we need to
3980 * save our return here so that we return the actual
3981 * error that caused problems, not ENOSPC.
3982 */
3983 if (ret < 0) {
3984 if (!cache_block_group_error)
3985 cache_block_group_error = ret;
3986 ret = 0;
3987 goto loop;
3988 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003989 ret = 0;
3990 }
3991
3992 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
3993 goto loop;
3994
3995 /*
3996 * Ok we want to try and use the cluster allocator, so
3997 * lets look there
3998 */
3999 if (last_ptr && use_cluster) {
David Brazdil0f672f62019-12-10 10:32:29 +00004000 struct btrfs_block_group_cache *cluster_bg = NULL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004001
David Brazdil0f672f62019-12-10 10:32:29 +00004002 ret = find_free_extent_clustered(block_group, last_ptr,
4003 &ffe_ctl, &cluster_bg);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004004
David Brazdil0f672f62019-12-10 10:32:29 +00004005 if (ret == 0) {
4006 if (cluster_bg && cluster_bg != block_group) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004007 btrfs_release_block_group(block_group,
4008 delalloc);
David Brazdil0f672f62019-12-10 10:32:29 +00004009 block_group = cluster_bg;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004010 }
4011 goto checks;
David Brazdil0f672f62019-12-10 10:32:29 +00004012 } else if (ret == -EAGAIN) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004013 goto have_block_group;
David Brazdil0f672f62019-12-10 10:32:29 +00004014 } else if (ret > 0) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004015 goto loop;
4016 }
David Brazdil0f672f62019-12-10 10:32:29 +00004017 /* ret == -ENOENT case falls through */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004018 }
4019
David Brazdil0f672f62019-12-10 10:32:29 +00004020 ret = find_free_extent_unclustered(block_group, last_ptr,
4021 &ffe_ctl);
4022 if (ret == -EAGAIN)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004023 goto have_block_group;
David Brazdil0f672f62019-12-10 10:32:29 +00004024 else if (ret > 0)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004025 goto loop;
David Brazdil0f672f62019-12-10 10:32:29 +00004026 /* ret == 0 case falls through */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004027checks:
David Brazdil0f672f62019-12-10 10:32:29 +00004028 ffe_ctl.search_start = round_up(ffe_ctl.found_offset,
4029 fs_info->stripesize);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004030
4031 /* move on to the next group */
David Brazdil0f672f62019-12-10 10:32:29 +00004032 if (ffe_ctl.search_start + num_bytes >
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004033 block_group->key.objectid + block_group->key.offset) {
David Brazdil0f672f62019-12-10 10:32:29 +00004034 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
4035 num_bytes);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004036 goto loop;
4037 }
4038
David Brazdil0f672f62019-12-10 10:32:29 +00004039 if (ffe_ctl.found_offset < ffe_ctl.search_start)
4040 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
4041 ffe_ctl.search_start - ffe_ctl.found_offset);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004042
4043 ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
4044 num_bytes, delalloc);
4045 if (ret == -EAGAIN) {
David Brazdil0f672f62019-12-10 10:32:29 +00004046 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
4047 num_bytes);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004048 goto loop;
4049 }
4050 btrfs_inc_block_group_reservations(block_group);
4051
4052 /* we are all good, lets return */
David Brazdil0f672f62019-12-10 10:32:29 +00004053 ins->objectid = ffe_ctl.search_start;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004054 ins->offset = num_bytes;
4055
David Brazdil0f672f62019-12-10 10:32:29 +00004056 trace_btrfs_reserve_extent(block_group, ffe_ctl.search_start,
4057 num_bytes);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004058 btrfs_release_block_group(block_group, delalloc);
4059 break;
4060loop:
David Brazdil0f672f62019-12-10 10:32:29 +00004061 ffe_ctl.retry_clustered = false;
4062 ffe_ctl.retry_unclustered = false;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004063 BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
David Brazdil0f672f62019-12-10 10:32:29 +00004064 ffe_ctl.index);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004065 btrfs_release_block_group(block_group, delalloc);
4066 cond_resched();
4067 }
4068 up_read(&space_info->groups_sem);
4069
David Brazdil0f672f62019-12-10 10:32:29 +00004070 ret = find_free_extent_update_loop(fs_info, last_ptr, ins, &ffe_ctl,
4071 full_search, use_cluster);
4072 if (ret > 0)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004073 goto search;
4074
Olivier Deprez0e641232021-09-23 10:07:05 +02004075 if (ret == -ENOSPC && !cache_block_group_error) {
David Brazdil0f672f62019-12-10 10:32:29 +00004076 /*
4077 * Use ffe_ctl->total_free_space as fallback if we can't find
4078 * any contiguous hole.
4079 */
4080 if (!ffe_ctl.max_extent_size)
4081 ffe_ctl.max_extent_size = ffe_ctl.total_free_space;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004082 spin_lock(&space_info->lock);
David Brazdil0f672f62019-12-10 10:32:29 +00004083 space_info->max_extent_size = ffe_ctl.max_extent_size;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004084 spin_unlock(&space_info->lock);
David Brazdil0f672f62019-12-10 10:32:29 +00004085 ins->offset = ffe_ctl.max_extent_size;
Olivier Deprez0e641232021-09-23 10:07:05 +02004086 } else if (ret == -ENOSPC) {
4087 ret = cache_block_group_error;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004088 }
4089 return ret;
4090}
4091
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004092/*
4093 * btrfs_reserve_extent - entry point to the extent allocator. Tries to find a
4094 * hole that is at least as big as @num_bytes.
4095 *
4096 * @root - The root that will contain this extent
4097 *
4098 * @ram_bytes - The amount of space in ram that @num_bytes take. This
4099 * is used for accounting purposes. This value differs
4100 * from @num_bytes only in the case of compressed extents.
4101 *
4102 * @num_bytes - Number of bytes to allocate on-disk.
4103 *
4104 * @min_alloc_size - Indicates the minimum amount of space that the
4105 * allocator should try to satisfy. In some cases
4106 * @num_bytes may be larger than what is required and if
4107 * the filesystem is fragmented then allocation fails.
4108 * However, the presence of @min_alloc_size gives a
4109 * chance to try and satisfy the smaller allocation.
4110 *
4111 * @empty_size - A hint that you plan on doing more COW. This is the
4112 * size in bytes the allocator should try to find free
4113 * next to the block it returns. This is just a hint and
4114 * may be ignored by the allocator.
4115 *
4116 * @hint_byte - Hint to the allocator to start searching above the byte
4117 * address passed. It might be ignored.
4118 *
4119 * @ins - This key is modified to record the found hole. It will
4120 * have the following values:
4121 * ins->objectid == start position
4122 * ins->flags = BTRFS_EXTENT_ITEM_KEY
4123 * ins->offset == the size of the hole.
4124 *
4125 * @is_data - Boolean flag indicating whether an extent is
4126 * allocated for data (true) or metadata (false)
4127 *
4128 * @delalloc - Boolean flag indicating whether this allocation is for
4129 * delalloc or not. If 'true' data_rwsem of block groups
4130 * is going to be acquired.
4131 *
4132 *
4133 * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
4134 * case -ENOSPC is returned then @ins->offset will contain the size of the
4135 * largest available hole the allocator managed to find.
4136 */
4137int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
4138 u64 num_bytes, u64 min_alloc_size,
4139 u64 empty_size, u64 hint_byte,
4140 struct btrfs_key *ins, int is_data, int delalloc)
4141{
4142 struct btrfs_fs_info *fs_info = root->fs_info;
4143 bool final_tried = num_bytes == min_alloc_size;
4144 u64 flags;
4145 int ret;
4146
4147 flags = get_alloc_profile_by_root(root, is_data);
4148again:
4149 WARN_ON(num_bytes < fs_info->sectorsize);
Olivier Deprez0e641232021-09-23 10:07:05 +02004150 ret = find_free_extent(root, ram_bytes, num_bytes, empty_size,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004151 hint_byte, ins, flags, delalloc);
4152 if (!ret && !is_data) {
4153 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
4154 } else if (ret == -ENOSPC) {
4155 if (!final_tried && ins->offset) {
4156 num_bytes = min(num_bytes >> 1, ins->offset);
4157 num_bytes = round_down(num_bytes,
4158 fs_info->sectorsize);
4159 num_bytes = max(num_bytes, min_alloc_size);
4160 ram_bytes = num_bytes;
4161 if (num_bytes == min_alloc_size)
4162 final_tried = true;
4163 goto again;
4164 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4165 struct btrfs_space_info *sinfo;
4166
David Brazdil0f672f62019-12-10 10:32:29 +00004167 sinfo = btrfs_find_space_info(fs_info, flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004168 btrfs_err(fs_info,
4169 "allocation failed flags %llu, wanted %llu",
4170 flags, num_bytes);
4171 if (sinfo)
David Brazdil0f672f62019-12-10 10:32:29 +00004172 btrfs_dump_space_info(fs_info, sinfo,
4173 num_bytes, 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004174 }
4175 }
4176
4177 return ret;
4178}
4179
4180static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
4181 u64 start, u64 len,
4182 int pin, int delalloc)
4183{
4184 struct btrfs_block_group_cache *cache;
4185 int ret = 0;
4186
4187 cache = btrfs_lookup_block_group(fs_info, start);
4188 if (!cache) {
4189 btrfs_err(fs_info, "Unable to find block group for %llu",
4190 start);
4191 return -ENOSPC;
4192 }
4193
4194 if (pin)
David Brazdil0f672f62019-12-10 10:32:29 +00004195 pin_down_extent(cache, start, len, 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004196 else {
4197 if (btrfs_test_opt(fs_info, DISCARD))
4198 ret = btrfs_discard_extent(fs_info, start, len, NULL);
4199 btrfs_add_free_space(cache, start, len);
4200 btrfs_free_reserved_bytes(cache, len, delalloc);
4201 trace_btrfs_reserved_extent_free(fs_info, start, len);
4202 }
4203
4204 btrfs_put_block_group(cache);
4205 return ret;
4206}
4207
4208int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
4209 u64 start, u64 len, int delalloc)
4210{
4211 return __btrfs_free_reserved_extent(fs_info, start, len, 0, delalloc);
4212}
4213
4214int btrfs_free_and_pin_reserved_extent(struct btrfs_fs_info *fs_info,
4215 u64 start, u64 len)
4216{
4217 return __btrfs_free_reserved_extent(fs_info, start, len, 1, 0);
4218}
4219
4220static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4221 u64 parent, u64 root_objectid,
4222 u64 flags, u64 owner, u64 offset,
4223 struct btrfs_key *ins, int ref_mod)
4224{
4225 struct btrfs_fs_info *fs_info = trans->fs_info;
4226 int ret;
4227 struct btrfs_extent_item *extent_item;
4228 struct btrfs_extent_inline_ref *iref;
4229 struct btrfs_path *path;
4230 struct extent_buffer *leaf;
4231 int type;
4232 u32 size;
4233
4234 if (parent > 0)
4235 type = BTRFS_SHARED_DATA_REF_KEY;
4236 else
4237 type = BTRFS_EXTENT_DATA_REF_KEY;
4238
4239 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
4240
4241 path = btrfs_alloc_path();
4242 if (!path)
4243 return -ENOMEM;
4244
4245 path->leave_spinning = 1;
4246 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
4247 ins, size);
4248 if (ret) {
4249 btrfs_free_path(path);
4250 return ret;
4251 }
4252
4253 leaf = path->nodes[0];
4254 extent_item = btrfs_item_ptr(leaf, path->slots[0],
4255 struct btrfs_extent_item);
4256 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
4257 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4258 btrfs_set_extent_flags(leaf, extent_item,
4259 flags | BTRFS_EXTENT_FLAG_DATA);
4260
4261 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4262 btrfs_set_extent_inline_ref_type(leaf, iref, type);
4263 if (parent > 0) {
4264 struct btrfs_shared_data_ref *ref;
4265 ref = (struct btrfs_shared_data_ref *)(iref + 1);
4266 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
4267 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
4268 } else {
4269 struct btrfs_extent_data_ref *ref;
4270 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
4271 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
4272 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
4273 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
4274 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
4275 }
4276
4277 btrfs_mark_buffer_dirty(path->nodes[0]);
4278 btrfs_free_path(path);
4279
4280 ret = remove_from_free_space_tree(trans, ins->objectid, ins->offset);
4281 if (ret)
4282 return ret;
4283
David Brazdil0f672f62019-12-10 10:32:29 +00004284 ret = btrfs_update_block_group(trans, ins->objectid, ins->offset, 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004285 if (ret) { /* -ENOENT, logic error */
4286 btrfs_err(fs_info, "update block group failed for %llu %llu",
4287 ins->objectid, ins->offset);
4288 BUG();
4289 }
4290 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
4291 return ret;
4292}
4293
4294static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
4295 struct btrfs_delayed_ref_node *node,
4296 struct btrfs_delayed_extent_op *extent_op)
4297{
4298 struct btrfs_fs_info *fs_info = trans->fs_info;
4299 int ret;
4300 struct btrfs_extent_item *extent_item;
4301 struct btrfs_key extent_key;
4302 struct btrfs_tree_block_info *block_info;
4303 struct btrfs_extent_inline_ref *iref;
4304 struct btrfs_path *path;
4305 struct extent_buffer *leaf;
4306 struct btrfs_delayed_tree_ref *ref;
4307 u32 size = sizeof(*extent_item) + sizeof(*iref);
4308 u64 num_bytes;
4309 u64 flags = extent_op->flags_to_set;
4310 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
4311
4312 ref = btrfs_delayed_node_to_tree_ref(node);
4313
4314 extent_key.objectid = node->bytenr;
4315 if (skinny_metadata) {
4316 extent_key.offset = ref->level;
4317 extent_key.type = BTRFS_METADATA_ITEM_KEY;
4318 num_bytes = fs_info->nodesize;
4319 } else {
4320 extent_key.offset = node->num_bytes;
4321 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
4322 size += sizeof(*block_info);
4323 num_bytes = node->num_bytes;
4324 }
4325
4326 path = btrfs_alloc_path();
4327 if (!path)
4328 return -ENOMEM;
4329
4330 path->leave_spinning = 1;
4331 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
4332 &extent_key, size);
4333 if (ret) {
4334 btrfs_free_path(path);
4335 return ret;
4336 }
4337
4338 leaf = path->nodes[0];
4339 extent_item = btrfs_item_ptr(leaf, path->slots[0],
4340 struct btrfs_extent_item);
4341 btrfs_set_extent_refs(leaf, extent_item, 1);
4342 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4343 btrfs_set_extent_flags(leaf, extent_item,
4344 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
4345
4346 if (skinny_metadata) {
4347 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4348 } else {
4349 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
4350 btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
4351 btrfs_set_tree_block_level(leaf, block_info, ref->level);
4352 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
4353 }
4354
4355 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
4356 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
4357 btrfs_set_extent_inline_ref_type(leaf, iref,
4358 BTRFS_SHARED_BLOCK_REF_KEY);
4359 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->parent);
4360 } else {
4361 btrfs_set_extent_inline_ref_type(leaf, iref,
4362 BTRFS_TREE_BLOCK_REF_KEY);
4363 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->root);
4364 }
4365
4366 btrfs_mark_buffer_dirty(leaf);
4367 btrfs_free_path(path);
4368
4369 ret = remove_from_free_space_tree(trans, extent_key.objectid,
4370 num_bytes);
4371 if (ret)
4372 return ret;
4373
David Brazdil0f672f62019-12-10 10:32:29 +00004374 ret = btrfs_update_block_group(trans, extent_key.objectid,
4375 fs_info->nodesize, 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004376 if (ret) { /* -ENOENT, logic error */
4377 btrfs_err(fs_info, "update block group failed for %llu %llu",
4378 extent_key.objectid, extent_key.offset);
4379 BUG();
4380 }
4381
4382 trace_btrfs_reserved_extent_alloc(fs_info, extent_key.objectid,
4383 fs_info->nodesize);
4384 return ret;
4385}
4386
4387int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4388 struct btrfs_root *root, u64 owner,
4389 u64 offset, u64 ram_bytes,
4390 struct btrfs_key *ins)
4391{
David Brazdil0f672f62019-12-10 10:32:29 +00004392 struct btrfs_ref generic_ref = { 0 };
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004393 int ret;
4394
4395 BUG_ON(root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
4396
David Brazdil0f672f62019-12-10 10:32:29 +00004397 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
4398 ins->objectid, ins->offset, 0);
4399 btrfs_init_data_ref(&generic_ref, root->root_key.objectid, owner, offset);
4400 btrfs_ref_tree_mod(root->fs_info, &generic_ref);
4401 ret = btrfs_add_delayed_data_ref(trans, &generic_ref,
4402 ram_bytes, NULL, NULL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004403 return ret;
4404}
4405
4406/*
4407 * this is used by the tree logging recovery code. It records that
4408 * an extent has been allocated and makes sure to clear the free
4409 * space cache bits as well
4410 */
4411int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
4412 u64 root_objectid, u64 owner, u64 offset,
4413 struct btrfs_key *ins)
4414{
4415 struct btrfs_fs_info *fs_info = trans->fs_info;
4416 int ret;
4417 struct btrfs_block_group_cache *block_group;
4418 struct btrfs_space_info *space_info;
4419
4420 /*
4421 * Mixed block groups will exclude before processing the log so we only
4422 * need to do the exclude dance if this fs isn't mixed.
4423 */
4424 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
4425 ret = __exclude_logged_extent(fs_info, ins->objectid,
4426 ins->offset);
4427 if (ret)
4428 return ret;
4429 }
4430
4431 block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
4432 if (!block_group)
4433 return -EINVAL;
4434
4435 space_info = block_group->space_info;
4436 spin_lock(&space_info->lock);
4437 spin_lock(&block_group->lock);
4438 space_info->bytes_reserved += ins->offset;
4439 block_group->reserved += ins->offset;
4440 spin_unlock(&block_group->lock);
4441 spin_unlock(&space_info->lock);
4442
4443 ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
4444 offset, ins, 1);
Olivier Deprez0e641232021-09-23 10:07:05 +02004445 if (ret)
4446 btrfs_pin_extent(fs_info, ins->objectid, ins->offset, 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004447 btrfs_put_block_group(block_group);
4448 return ret;
4449}
4450
4451static struct extent_buffer *
4452btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4453 u64 bytenr, int level, u64 owner)
4454{
4455 struct btrfs_fs_info *fs_info = root->fs_info;
4456 struct extent_buffer *buf;
4457
4458 buf = btrfs_find_create_tree_block(fs_info, bytenr);
4459 if (IS_ERR(buf))
4460 return buf;
4461
4462 /*
4463 * Extra safety check in case the extent tree is corrupted and extent
4464 * allocator chooses to use a tree block which is already used and
4465 * locked.
4466 */
4467 if (buf->lock_owner == current->pid) {
4468 btrfs_err_rl(fs_info,
4469"tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
4470 buf->start, btrfs_header_owner(buf), current->pid);
4471 free_extent_buffer(buf);
4472 return ERR_PTR(-EUCLEAN);
4473 }
4474
Olivier Deprez0e641232021-09-23 10:07:05 +02004475 btrfs_set_buffer_lockdep_class(owner, buf, level);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004476 btrfs_tree_lock(buf);
David Brazdil0f672f62019-12-10 10:32:29 +00004477 btrfs_clean_tree_block(buf);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004478 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
4479
David Brazdil0f672f62019-12-10 10:32:29 +00004480 btrfs_set_lock_blocking_write(buf);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004481 set_extent_buffer_uptodate(buf);
4482
4483 memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
4484 btrfs_set_header_level(buf, level);
4485 btrfs_set_header_bytenr(buf, buf->start);
4486 btrfs_set_header_generation(buf, trans->transid);
4487 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
4488 btrfs_set_header_owner(buf, owner);
David Brazdil0f672f62019-12-10 10:32:29 +00004489 write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004490 write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
4491 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
4492 buf->log_index = root->log_transid % 2;
4493 /*
4494 * we allow two log transactions at a time, use different
David Brazdil0f672f62019-12-10 10:32:29 +00004495 * EXTENT bit to differentiate dirty pages.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004496 */
4497 if (buf->log_index == 0)
4498 set_extent_dirty(&root->dirty_log_pages, buf->start,
4499 buf->start + buf->len - 1, GFP_NOFS);
4500 else
4501 set_extent_new(&root->dirty_log_pages, buf->start,
4502 buf->start + buf->len - 1);
4503 } else {
4504 buf->log_index = -1;
4505 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
4506 buf->start + buf->len - 1, GFP_NOFS);
4507 }
4508 trans->dirty = true;
4509 /* this returns a buffer locked for blocking */
4510 return buf;
4511}
4512
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004513/*
4514 * finds a free extent and does all the dirty work required for allocation
4515 * returns the tree buffer or an ERR_PTR on error.
4516 */
4517struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
4518 struct btrfs_root *root,
4519 u64 parent, u64 root_objectid,
4520 const struct btrfs_disk_key *key,
4521 int level, u64 hint,
4522 u64 empty_size)
4523{
4524 struct btrfs_fs_info *fs_info = root->fs_info;
4525 struct btrfs_key ins;
4526 struct btrfs_block_rsv *block_rsv;
4527 struct extent_buffer *buf;
4528 struct btrfs_delayed_extent_op *extent_op;
David Brazdil0f672f62019-12-10 10:32:29 +00004529 struct btrfs_ref generic_ref = { 0 };
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004530 u64 flags = 0;
4531 int ret;
4532 u32 blocksize = fs_info->nodesize;
4533 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
4534
4535#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4536 if (btrfs_is_testing(fs_info)) {
4537 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
4538 level, root_objectid);
4539 if (!IS_ERR(buf))
4540 root->alloc_bytenr += blocksize;
4541 return buf;
4542 }
4543#endif
4544
David Brazdil0f672f62019-12-10 10:32:29 +00004545 block_rsv = btrfs_use_block_rsv(trans, root, blocksize);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004546 if (IS_ERR(block_rsv))
4547 return ERR_CAST(block_rsv);
4548
4549 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
4550 empty_size, hint, &ins, 0, 0);
4551 if (ret)
4552 goto out_unuse;
4553
4554 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
4555 root_objectid);
4556 if (IS_ERR(buf)) {
4557 ret = PTR_ERR(buf);
4558 goto out_free_reserved;
4559 }
4560
4561 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
4562 if (parent == 0)
4563 parent = ins.objectid;
4564 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
4565 } else
4566 BUG_ON(parent > 0);
4567
4568 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
4569 extent_op = btrfs_alloc_delayed_extent_op();
4570 if (!extent_op) {
4571 ret = -ENOMEM;
4572 goto out_free_buf;
4573 }
4574 if (key)
4575 memcpy(&extent_op->key, key, sizeof(extent_op->key));
4576 else
4577 memset(&extent_op->key, 0, sizeof(extent_op->key));
4578 extent_op->flags_to_set = flags;
4579 extent_op->update_key = skinny_metadata ? false : true;
4580 extent_op->update_flags = true;
4581 extent_op->is_data = false;
4582 extent_op->level = level;
4583
David Brazdil0f672f62019-12-10 10:32:29 +00004584 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
4585 ins.objectid, ins.offset, parent);
4586 generic_ref.real_root = root->root_key.objectid;
4587 btrfs_init_tree_ref(&generic_ref, level, root_objectid);
4588 btrfs_ref_tree_mod(fs_info, &generic_ref);
4589 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004590 extent_op, NULL, NULL);
4591 if (ret)
4592 goto out_free_delayed;
4593 }
4594 return buf;
4595
4596out_free_delayed:
4597 btrfs_free_delayed_extent_op(extent_op);
4598out_free_buf:
4599 free_extent_buffer(buf);
4600out_free_reserved:
4601 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
4602out_unuse:
David Brazdil0f672f62019-12-10 10:32:29 +00004603 btrfs_unuse_block_rsv(fs_info, block_rsv, blocksize);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004604 return ERR_PTR(ret);
4605}
4606
4607struct walk_control {
4608 u64 refs[BTRFS_MAX_LEVEL];
4609 u64 flags[BTRFS_MAX_LEVEL];
4610 struct btrfs_key update_progress;
David Brazdil0f672f62019-12-10 10:32:29 +00004611 struct btrfs_key drop_progress;
4612 int drop_level;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004613 int stage;
4614 int level;
4615 int shared_level;
4616 int update_ref;
4617 int keep_locks;
4618 int reada_slot;
4619 int reada_count;
David Brazdil0f672f62019-12-10 10:32:29 +00004620 int restarted;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004621};
4622
4623#define DROP_REFERENCE 1
4624#define UPDATE_BACKREF 2
4625
4626static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
4627 struct btrfs_root *root,
4628 struct walk_control *wc,
4629 struct btrfs_path *path)
4630{
4631 struct btrfs_fs_info *fs_info = root->fs_info;
4632 u64 bytenr;
4633 u64 generation;
4634 u64 refs;
4635 u64 flags;
4636 u32 nritems;
4637 struct btrfs_key key;
4638 struct extent_buffer *eb;
4639 int ret;
4640 int slot;
4641 int nread = 0;
4642
4643 if (path->slots[wc->level] < wc->reada_slot) {
4644 wc->reada_count = wc->reada_count * 2 / 3;
4645 wc->reada_count = max(wc->reada_count, 2);
4646 } else {
4647 wc->reada_count = wc->reada_count * 3 / 2;
4648 wc->reada_count = min_t(int, wc->reada_count,
4649 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
4650 }
4651
4652 eb = path->nodes[wc->level];
4653 nritems = btrfs_header_nritems(eb);
4654
4655 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
4656 if (nread >= wc->reada_count)
4657 break;
4658
4659 cond_resched();
4660 bytenr = btrfs_node_blockptr(eb, slot);
4661 generation = btrfs_node_ptr_generation(eb, slot);
4662
4663 if (slot == path->slots[wc->level])
4664 goto reada;
4665
4666 if (wc->stage == UPDATE_BACKREF &&
4667 generation <= root->root_key.offset)
4668 continue;
4669
4670 /* We don't lock the tree block, it's OK to be racy here */
4671 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
4672 wc->level - 1, 1, &refs,
4673 &flags);
4674 /* We don't care about errors in readahead. */
4675 if (ret < 0)
4676 continue;
4677 BUG_ON(refs == 0);
4678
4679 if (wc->stage == DROP_REFERENCE) {
4680 if (refs == 1)
4681 goto reada;
4682
4683 if (wc->level == 1 &&
4684 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4685 continue;
4686 if (!wc->update_ref ||
4687 generation <= root->root_key.offset)
4688 continue;
4689 btrfs_node_key_to_cpu(eb, &key, slot);
4690 ret = btrfs_comp_cpu_keys(&key,
4691 &wc->update_progress);
4692 if (ret < 0)
4693 continue;
4694 } else {
4695 if (wc->level == 1 &&
4696 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4697 continue;
4698 }
4699reada:
4700 readahead_tree_block(fs_info, bytenr);
4701 nread++;
4702 }
4703 wc->reada_slot = slot;
4704}
4705
4706/*
4707 * helper to process tree block while walking down the tree.
4708 *
4709 * when wc->stage == UPDATE_BACKREF, this function updates
4710 * back refs for pointers in the block.
4711 *
4712 * NOTE: return value 1 means we should stop walking down.
4713 */
4714static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
4715 struct btrfs_root *root,
4716 struct btrfs_path *path,
4717 struct walk_control *wc, int lookup_info)
4718{
4719 struct btrfs_fs_info *fs_info = root->fs_info;
4720 int level = wc->level;
4721 struct extent_buffer *eb = path->nodes[level];
4722 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
4723 int ret;
4724
4725 if (wc->stage == UPDATE_BACKREF &&
4726 btrfs_header_owner(eb) != root->root_key.objectid)
4727 return 1;
4728
4729 /*
4730 * when reference count of tree block is 1, it won't increase
4731 * again. once full backref flag is set, we never clear it.
4732 */
4733 if (lookup_info &&
4734 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
4735 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
4736 BUG_ON(!path->locks[level]);
4737 ret = btrfs_lookup_extent_info(trans, fs_info,
4738 eb->start, level, 1,
4739 &wc->refs[level],
4740 &wc->flags[level]);
4741 BUG_ON(ret == -ENOMEM);
4742 if (ret)
4743 return ret;
4744 BUG_ON(wc->refs[level] == 0);
4745 }
4746
4747 if (wc->stage == DROP_REFERENCE) {
4748 if (wc->refs[level] > 1)
4749 return 1;
4750
4751 if (path->locks[level] && !wc->keep_locks) {
4752 btrfs_tree_unlock_rw(eb, path->locks[level]);
4753 path->locks[level] = 0;
4754 }
4755 return 0;
4756 }
4757
4758 /* wc->stage == UPDATE_BACKREF */
4759 if (!(wc->flags[level] & flag)) {
4760 BUG_ON(!path->locks[level]);
4761 ret = btrfs_inc_ref(trans, root, eb, 1);
4762 BUG_ON(ret); /* -ENOMEM */
4763 ret = btrfs_dec_ref(trans, root, eb, 0);
4764 BUG_ON(ret); /* -ENOMEM */
David Brazdil0f672f62019-12-10 10:32:29 +00004765 ret = btrfs_set_disk_extent_flags(trans, eb->start,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004766 eb->len, flag,
4767 btrfs_header_level(eb), 0);
4768 BUG_ON(ret); /* -ENOMEM */
4769 wc->flags[level] |= flag;
4770 }
4771
4772 /*
4773 * the block is shared by multiple trees, so it's not good to
4774 * keep the tree lock
4775 */
4776 if (path->locks[level] && level > 0) {
4777 btrfs_tree_unlock_rw(eb, path->locks[level]);
4778 path->locks[level] = 0;
4779 }
4780 return 0;
4781}
4782
4783/*
David Brazdil0f672f62019-12-10 10:32:29 +00004784 * This is used to verify a ref exists for this root to deal with a bug where we
4785 * would have a drop_progress key that hadn't been updated properly.
4786 */
4787static int check_ref_exists(struct btrfs_trans_handle *trans,
4788 struct btrfs_root *root, u64 bytenr, u64 parent,
4789 int level)
4790{
4791 struct btrfs_path *path;
4792 struct btrfs_extent_inline_ref *iref;
4793 int ret;
4794
4795 path = btrfs_alloc_path();
4796 if (!path)
4797 return -ENOMEM;
4798
4799 ret = lookup_extent_backref(trans, path, &iref, bytenr,
4800 root->fs_info->nodesize, parent,
4801 root->root_key.objectid, level, 0);
4802 btrfs_free_path(path);
4803 if (ret == -ENOENT)
4804 return 0;
4805 if (ret < 0)
4806 return ret;
4807 return 1;
4808}
4809
4810/*
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004811 * helper to process tree block pointer.
4812 *
4813 * when wc->stage == DROP_REFERENCE, this function checks
4814 * reference count of the block pointed to. if the block
4815 * is shared and we need update back refs for the subtree
4816 * rooted at the block, this function changes wc->stage to
4817 * UPDATE_BACKREF. if the block is shared and there is no
4818 * need to update back, this function drops the reference
4819 * to the block.
4820 *
4821 * NOTE: return value 1 means we should stop walking down.
4822 */
4823static noinline int do_walk_down(struct btrfs_trans_handle *trans,
4824 struct btrfs_root *root,
4825 struct btrfs_path *path,
4826 struct walk_control *wc, int *lookup_info)
4827{
4828 struct btrfs_fs_info *fs_info = root->fs_info;
4829 u64 bytenr;
4830 u64 generation;
4831 u64 parent;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004832 struct btrfs_key key;
4833 struct btrfs_key first_key;
David Brazdil0f672f62019-12-10 10:32:29 +00004834 struct btrfs_ref ref = { 0 };
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004835 struct extent_buffer *next;
4836 int level = wc->level;
4837 int reada = 0;
4838 int ret = 0;
4839 bool need_account = false;
4840
4841 generation = btrfs_node_ptr_generation(path->nodes[level],
4842 path->slots[level]);
4843 /*
4844 * if the lower level block was created before the snapshot
4845 * was created, we know there is no need to update back refs
4846 * for the subtree
4847 */
4848 if (wc->stage == UPDATE_BACKREF &&
4849 generation <= root->root_key.offset) {
4850 *lookup_info = 1;
4851 return 1;
4852 }
4853
4854 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
4855 btrfs_node_key_to_cpu(path->nodes[level], &first_key,
4856 path->slots[level]);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004857
4858 next = find_extent_buffer(fs_info, bytenr);
4859 if (!next) {
4860 next = btrfs_find_create_tree_block(fs_info, bytenr);
4861 if (IS_ERR(next))
4862 return PTR_ERR(next);
4863
4864 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
4865 level - 1);
4866 reada = 1;
4867 }
4868 btrfs_tree_lock(next);
David Brazdil0f672f62019-12-10 10:32:29 +00004869 btrfs_set_lock_blocking_write(next);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004870
4871 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
4872 &wc->refs[level - 1],
4873 &wc->flags[level - 1]);
4874 if (ret < 0)
4875 goto out_unlock;
4876
4877 if (unlikely(wc->refs[level - 1] == 0)) {
4878 btrfs_err(fs_info, "Missing references.");
4879 ret = -EIO;
4880 goto out_unlock;
4881 }
4882 *lookup_info = 0;
4883
4884 if (wc->stage == DROP_REFERENCE) {
4885 if (wc->refs[level - 1] > 1) {
4886 need_account = true;
4887 if (level == 1 &&
4888 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4889 goto skip;
4890
4891 if (!wc->update_ref ||
4892 generation <= root->root_key.offset)
4893 goto skip;
4894
4895 btrfs_node_key_to_cpu(path->nodes[level], &key,
4896 path->slots[level]);
4897 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
4898 if (ret < 0)
4899 goto skip;
4900
4901 wc->stage = UPDATE_BACKREF;
4902 wc->shared_level = level - 1;
4903 }
4904 } else {
4905 if (level == 1 &&
4906 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4907 goto skip;
4908 }
4909
4910 if (!btrfs_buffer_uptodate(next, generation, 0)) {
4911 btrfs_tree_unlock(next);
4912 free_extent_buffer(next);
4913 next = NULL;
4914 *lookup_info = 1;
4915 }
4916
4917 if (!next) {
4918 if (reada && level == 1)
4919 reada_walk_down(trans, root, wc, path);
4920 next = read_tree_block(fs_info, bytenr, generation, level - 1,
4921 &first_key);
4922 if (IS_ERR(next)) {
4923 return PTR_ERR(next);
4924 } else if (!extent_buffer_uptodate(next)) {
4925 free_extent_buffer(next);
4926 return -EIO;
4927 }
4928 btrfs_tree_lock(next);
David Brazdil0f672f62019-12-10 10:32:29 +00004929 btrfs_set_lock_blocking_write(next);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004930 }
4931
4932 level--;
4933 ASSERT(level == btrfs_header_level(next));
4934 if (level != btrfs_header_level(next)) {
4935 btrfs_err(root->fs_info, "mismatched level");
4936 ret = -EIO;
4937 goto out_unlock;
4938 }
4939 path->nodes[level] = next;
4940 path->slots[level] = 0;
4941 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
4942 wc->level = level;
4943 if (wc->level == 1)
4944 wc->reada_slot = 0;
4945 return 0;
4946skip:
4947 wc->refs[level - 1] = 0;
4948 wc->flags[level - 1] = 0;
4949 if (wc->stage == DROP_REFERENCE) {
4950 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
4951 parent = path->nodes[level]->start;
4952 } else {
4953 ASSERT(root->root_key.objectid ==
4954 btrfs_header_owner(path->nodes[level]));
4955 if (root->root_key.objectid !=
4956 btrfs_header_owner(path->nodes[level])) {
4957 btrfs_err(root->fs_info,
4958 "mismatched block owner");
4959 ret = -EIO;
4960 goto out_unlock;
4961 }
4962 parent = 0;
4963 }
4964
David Brazdil0f672f62019-12-10 10:32:29 +00004965 /*
4966 * If we had a drop_progress we need to verify the refs are set
4967 * as expected. If we find our ref then we know that from here
4968 * on out everything should be correct, and we can clear the
4969 * ->restarted flag.
4970 */
4971 if (wc->restarted) {
4972 ret = check_ref_exists(trans, root, bytenr, parent,
4973 level - 1);
4974 if (ret < 0)
4975 goto out_unlock;
4976 if (ret == 0)
4977 goto no_delete;
4978 ret = 0;
4979 wc->restarted = 0;
4980 }
4981
4982 /*
4983 * Reloc tree doesn't contribute to qgroup numbers, and we have
4984 * already accounted them at merge time (replace_path),
4985 * thus we could skip expensive subtree trace here.
4986 */
4987 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
4988 need_account) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004989 ret = btrfs_qgroup_trace_subtree(trans, next,
4990 generation, level - 1);
4991 if (ret) {
4992 btrfs_err_rl(fs_info,
4993 "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
4994 ret);
4995 }
4996 }
David Brazdil0f672f62019-12-10 10:32:29 +00004997
4998 /*
4999 * We need to update the next key in our walk control so we can
5000 * update the drop_progress key accordingly. We don't care if
5001 * find_next_key doesn't find a key because that means we're at
5002 * the end and are going to clean up now.
5003 */
5004 wc->drop_level = level;
5005 find_next_key(path, level, &wc->drop_progress);
5006
5007 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
5008 fs_info->nodesize, parent);
5009 btrfs_init_tree_ref(&ref, level - 1, root->root_key.objectid);
5010 ret = btrfs_free_extent(trans, &ref);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005011 if (ret)
5012 goto out_unlock;
5013 }
David Brazdil0f672f62019-12-10 10:32:29 +00005014no_delete:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005015 *lookup_info = 1;
5016 ret = 1;
5017
5018out_unlock:
5019 btrfs_tree_unlock(next);
5020 free_extent_buffer(next);
5021
5022 return ret;
5023}
5024
5025/*
5026 * helper to process tree block while walking up the tree.
5027 *
5028 * when wc->stage == DROP_REFERENCE, this function drops
5029 * reference count on the block.
5030 *
5031 * when wc->stage == UPDATE_BACKREF, this function changes
5032 * wc->stage back to DROP_REFERENCE if we changed wc->stage
5033 * to UPDATE_BACKREF previously while processing the block.
5034 *
5035 * NOTE: return value 1 means we should stop walking up.
5036 */
5037static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
5038 struct btrfs_root *root,
5039 struct btrfs_path *path,
5040 struct walk_control *wc)
5041{
5042 struct btrfs_fs_info *fs_info = root->fs_info;
5043 int ret;
5044 int level = wc->level;
5045 struct extent_buffer *eb = path->nodes[level];
5046 u64 parent = 0;
5047
5048 if (wc->stage == UPDATE_BACKREF) {
5049 BUG_ON(wc->shared_level < level);
5050 if (level < wc->shared_level)
5051 goto out;
5052
5053 ret = find_next_key(path, level + 1, &wc->update_progress);
5054 if (ret > 0)
5055 wc->update_ref = 0;
5056
5057 wc->stage = DROP_REFERENCE;
5058 wc->shared_level = -1;
5059 path->slots[level] = 0;
5060
5061 /*
5062 * check reference count again if the block isn't locked.
5063 * we should start walking down the tree again if reference
5064 * count is one.
5065 */
5066 if (!path->locks[level]) {
5067 BUG_ON(level == 0);
5068 btrfs_tree_lock(eb);
David Brazdil0f672f62019-12-10 10:32:29 +00005069 btrfs_set_lock_blocking_write(eb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005070 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
5071
5072 ret = btrfs_lookup_extent_info(trans, fs_info,
5073 eb->start, level, 1,
5074 &wc->refs[level],
5075 &wc->flags[level]);
5076 if (ret < 0) {
5077 btrfs_tree_unlock_rw(eb, path->locks[level]);
5078 path->locks[level] = 0;
5079 return ret;
5080 }
5081 BUG_ON(wc->refs[level] == 0);
5082 if (wc->refs[level] == 1) {
5083 btrfs_tree_unlock_rw(eb, path->locks[level]);
5084 path->locks[level] = 0;
5085 return 1;
5086 }
5087 }
5088 }
5089
5090 /* wc->stage == DROP_REFERENCE */
5091 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
5092
5093 if (wc->refs[level] == 1) {
5094 if (level == 0) {
5095 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5096 ret = btrfs_dec_ref(trans, root, eb, 1);
5097 else
5098 ret = btrfs_dec_ref(trans, root, eb, 0);
5099 BUG_ON(ret); /* -ENOMEM */
David Brazdil0f672f62019-12-10 10:32:29 +00005100 if (is_fstree(root->root_key.objectid)) {
5101 ret = btrfs_qgroup_trace_leaf_items(trans, eb);
5102 if (ret) {
5103 btrfs_err_rl(fs_info,
5104 "error %d accounting leaf items, quota is out of sync, rescan required",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005105 ret);
David Brazdil0f672f62019-12-10 10:32:29 +00005106 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005107 }
5108 }
David Brazdil0f672f62019-12-10 10:32:29 +00005109 /* make block locked assertion in btrfs_clean_tree_block happy */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005110 if (!path->locks[level] &&
5111 btrfs_header_generation(eb) == trans->transid) {
5112 btrfs_tree_lock(eb);
David Brazdil0f672f62019-12-10 10:32:29 +00005113 btrfs_set_lock_blocking_write(eb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005114 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
5115 }
David Brazdil0f672f62019-12-10 10:32:29 +00005116 btrfs_clean_tree_block(eb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005117 }
5118
5119 if (eb == root->node) {
5120 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5121 parent = eb->start;
5122 else if (root->root_key.objectid != btrfs_header_owner(eb))
5123 goto owner_mismatch;
5124 } else {
5125 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5126 parent = path->nodes[level + 1]->start;
5127 else if (root->root_key.objectid !=
5128 btrfs_header_owner(path->nodes[level + 1]))
5129 goto owner_mismatch;
5130 }
5131
5132 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
5133out:
5134 wc->refs[level] = 0;
5135 wc->flags[level] = 0;
5136 return 0;
5137
5138owner_mismatch:
5139 btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
5140 btrfs_header_owner(eb), root->root_key.objectid);
5141 return -EUCLEAN;
5142}
5143
5144static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
5145 struct btrfs_root *root,
5146 struct btrfs_path *path,
5147 struct walk_control *wc)
5148{
5149 int level = wc->level;
5150 int lookup_info = 1;
5151 int ret;
5152
5153 while (level >= 0) {
5154 ret = walk_down_proc(trans, root, path, wc, lookup_info);
5155 if (ret > 0)
5156 break;
5157
5158 if (level == 0)
5159 break;
5160
5161 if (path->slots[level] >=
5162 btrfs_header_nritems(path->nodes[level]))
5163 break;
5164
5165 ret = do_walk_down(trans, root, path, wc, &lookup_info);
5166 if (ret > 0) {
5167 path->slots[level]++;
5168 continue;
5169 } else if (ret < 0)
5170 return ret;
5171 level = wc->level;
5172 }
5173 return 0;
5174}
5175
5176static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
5177 struct btrfs_root *root,
5178 struct btrfs_path *path,
5179 struct walk_control *wc, int max_level)
5180{
5181 int level = wc->level;
5182 int ret;
5183
5184 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
5185 while (level < max_level && path->nodes[level]) {
5186 wc->level = level;
5187 if (path->slots[level] + 1 <
5188 btrfs_header_nritems(path->nodes[level])) {
5189 path->slots[level]++;
5190 return 0;
5191 } else {
5192 ret = walk_up_proc(trans, root, path, wc);
5193 if (ret > 0)
5194 return 0;
5195 if (ret < 0)
5196 return ret;
5197
5198 if (path->locks[level]) {
5199 btrfs_tree_unlock_rw(path->nodes[level],
5200 path->locks[level]);
5201 path->locks[level] = 0;
5202 }
5203 free_extent_buffer(path->nodes[level]);
5204 path->nodes[level] = NULL;
5205 level++;
5206 }
5207 }
5208 return 1;
5209}
5210
5211/*
5212 * drop a subvolume tree.
5213 *
5214 * this function traverses the tree freeing any blocks that only
5215 * referenced by the tree.
5216 *
5217 * when a shared tree block is found. this function decreases its
5218 * reference count by one. if update_ref is true, this function
5219 * also make sure backrefs for the shared block and all lower level
5220 * blocks are properly updated.
5221 *
5222 * If called with for_reloc == 0, may exit early with -EAGAIN
5223 */
5224int btrfs_drop_snapshot(struct btrfs_root *root,
5225 struct btrfs_block_rsv *block_rsv, int update_ref,
5226 int for_reloc)
5227{
5228 struct btrfs_fs_info *fs_info = root->fs_info;
5229 struct btrfs_path *path;
5230 struct btrfs_trans_handle *trans;
5231 struct btrfs_root *tree_root = fs_info->tree_root;
5232 struct btrfs_root_item *root_item = &root->root_item;
5233 struct walk_control *wc;
5234 struct btrfs_key key;
5235 int err = 0;
5236 int ret;
5237 int level;
5238 bool root_dropped = false;
5239
David Brazdil0f672f62019-12-10 10:32:29 +00005240 btrfs_debug(fs_info, "Drop subvolume %llu", root->root_key.objectid);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005241
5242 path = btrfs_alloc_path();
5243 if (!path) {
5244 err = -ENOMEM;
5245 goto out;
5246 }
5247
5248 wc = kzalloc(sizeof(*wc), GFP_NOFS);
5249 if (!wc) {
5250 btrfs_free_path(path);
5251 err = -ENOMEM;
5252 goto out;
5253 }
5254
Olivier Deprez0e641232021-09-23 10:07:05 +02005255 /*
5256 * Use join to avoid potential EINTR from transaction start. See
5257 * wait_reserve_ticket and the whole reservation callchain.
5258 */
5259 if (for_reloc)
5260 trans = btrfs_join_transaction(tree_root);
5261 else
5262 trans = btrfs_start_transaction(tree_root, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005263 if (IS_ERR(trans)) {
5264 err = PTR_ERR(trans);
5265 goto out_free;
5266 }
5267
David Brazdil0f672f62019-12-10 10:32:29 +00005268 err = btrfs_run_delayed_items(trans);
5269 if (err)
5270 goto out_end_trans;
5271
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005272 if (block_rsv)
5273 trans->block_rsv = block_rsv;
5274
David Brazdil0f672f62019-12-10 10:32:29 +00005275 /*
5276 * This will help us catch people modifying the fs tree while we're
5277 * dropping it. It is unsafe to mess with the fs tree while it's being
5278 * dropped as we unlock the root node and parent nodes as we walk down
5279 * the tree, assuming nothing will change. If something does change
5280 * then we'll have stale information and drop references to blocks we've
5281 * already dropped.
5282 */
5283 set_bit(BTRFS_ROOT_DELETING, &root->state);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005284 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
5285 level = btrfs_header_level(root->node);
5286 path->nodes[level] = btrfs_lock_root_node(root);
David Brazdil0f672f62019-12-10 10:32:29 +00005287 btrfs_set_lock_blocking_write(path->nodes[level]);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005288 path->slots[level] = 0;
5289 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
5290 memset(&wc->update_progress, 0,
5291 sizeof(wc->update_progress));
5292 } else {
5293 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
5294 memcpy(&wc->update_progress, &key,
5295 sizeof(wc->update_progress));
5296
5297 level = root_item->drop_level;
5298 BUG_ON(level == 0);
5299 path->lowest_level = level;
5300 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5301 path->lowest_level = 0;
5302 if (ret < 0) {
5303 err = ret;
5304 goto out_end_trans;
5305 }
5306 WARN_ON(ret > 0);
5307
5308 /*
5309 * unlock our path, this is safe because only this
5310 * function is allowed to delete this snapshot
5311 */
5312 btrfs_unlock_up_safe(path, 0);
5313
5314 level = btrfs_header_level(root->node);
5315 while (1) {
5316 btrfs_tree_lock(path->nodes[level]);
David Brazdil0f672f62019-12-10 10:32:29 +00005317 btrfs_set_lock_blocking_write(path->nodes[level]);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005318 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
5319
5320 ret = btrfs_lookup_extent_info(trans, fs_info,
5321 path->nodes[level]->start,
5322 level, 1, &wc->refs[level],
5323 &wc->flags[level]);
5324 if (ret < 0) {
5325 err = ret;
5326 goto out_end_trans;
5327 }
5328 BUG_ON(wc->refs[level] == 0);
5329
5330 if (level == root_item->drop_level)
5331 break;
5332
5333 btrfs_tree_unlock(path->nodes[level]);
5334 path->locks[level] = 0;
5335 WARN_ON(wc->refs[level] != 1);
5336 level--;
5337 }
5338 }
5339
David Brazdil0f672f62019-12-10 10:32:29 +00005340 wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005341 wc->level = level;
5342 wc->shared_level = -1;
5343 wc->stage = DROP_REFERENCE;
5344 wc->update_ref = update_ref;
5345 wc->keep_locks = 0;
5346 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
5347
5348 while (1) {
5349
5350 ret = walk_down_tree(trans, root, path, wc);
5351 if (ret < 0) {
5352 err = ret;
5353 break;
5354 }
5355
5356 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
5357 if (ret < 0) {
5358 err = ret;
5359 break;
5360 }
5361
5362 if (ret > 0) {
5363 BUG_ON(wc->stage != DROP_REFERENCE);
5364 break;
5365 }
5366
5367 if (wc->stage == DROP_REFERENCE) {
David Brazdil0f672f62019-12-10 10:32:29 +00005368 wc->drop_level = wc->level;
5369 btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
5370 &wc->drop_progress,
5371 path->slots[wc->drop_level]);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005372 }
David Brazdil0f672f62019-12-10 10:32:29 +00005373 btrfs_cpu_key_to_disk(&root_item->drop_progress,
5374 &wc->drop_progress);
5375 root_item->drop_level = wc->drop_level;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005376
5377 BUG_ON(wc->level == 0);
5378 if (btrfs_should_end_transaction(trans) ||
5379 (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
5380 ret = btrfs_update_root(trans, tree_root,
5381 &root->root_key,
5382 root_item);
5383 if (ret) {
5384 btrfs_abort_transaction(trans, ret);
5385 err = ret;
5386 goto out_end_trans;
5387 }
5388
5389 btrfs_end_transaction_throttle(trans);
5390 if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
5391 btrfs_debug(fs_info,
5392 "drop snapshot early exit");
5393 err = -EAGAIN;
5394 goto out_free;
5395 }
5396
Olivier Deprez0e641232021-09-23 10:07:05 +02005397 /*
5398 * Use join to avoid potential EINTR from transaction
5399 * start. See wait_reserve_ticket and the whole
5400 * reservation callchain.
5401 */
5402 if (for_reloc)
5403 trans = btrfs_join_transaction(tree_root);
5404 else
5405 trans = btrfs_start_transaction(tree_root, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005406 if (IS_ERR(trans)) {
5407 err = PTR_ERR(trans);
5408 goto out_free;
5409 }
5410 if (block_rsv)
5411 trans->block_rsv = block_rsv;
5412 }
5413 }
5414 btrfs_release_path(path);
5415 if (err)
5416 goto out_end_trans;
5417
5418 ret = btrfs_del_root(trans, &root->root_key);
5419 if (ret) {
5420 btrfs_abort_transaction(trans, ret);
5421 err = ret;
5422 goto out_end_trans;
5423 }
5424
5425 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
5426 ret = btrfs_find_root(tree_root, &root->root_key, path,
5427 NULL, NULL);
5428 if (ret < 0) {
5429 btrfs_abort_transaction(trans, ret);
5430 err = ret;
5431 goto out_end_trans;
5432 } else if (ret > 0) {
5433 /* if we fail to delete the orphan item this time
5434 * around, it'll get picked up the next time.
5435 *
5436 * The most common failure here is just -ENOENT.
5437 */
5438 btrfs_del_orphan_item(trans, tree_root,
5439 root->root_key.objectid);
5440 }
5441 }
5442
5443 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
5444 btrfs_add_dropped_root(trans, root);
5445 } else {
5446 free_extent_buffer(root->node);
5447 free_extent_buffer(root->commit_root);
5448 btrfs_put_fs_root(root);
5449 }
5450 root_dropped = true;
5451out_end_trans:
5452 btrfs_end_transaction_throttle(trans);
5453out_free:
5454 kfree(wc);
5455 btrfs_free_path(path);
5456out:
5457 /*
5458 * So if we need to stop dropping the snapshot for whatever reason we
5459 * need to make sure to add it back to the dead root list so that we
5460 * keep trying to do the work later. This also cleans up roots if we
5461 * don't have it in the radix (like when we recover after a power fail
5462 * or unmount) so we don't leak memory.
5463 */
5464 if (!for_reloc && !root_dropped)
5465 btrfs_add_dead_root(root);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005466 return err;
5467}
5468
5469/*
5470 * drop subtree rooted at tree block 'node'.
5471 *
5472 * NOTE: this function will unlock and release tree block 'node'
5473 * only used by relocation code
5474 */
5475int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
5476 struct btrfs_root *root,
5477 struct extent_buffer *node,
5478 struct extent_buffer *parent)
5479{
5480 struct btrfs_fs_info *fs_info = root->fs_info;
5481 struct btrfs_path *path;
5482 struct walk_control *wc;
5483 int level;
5484 int parent_level;
5485 int ret = 0;
5486 int wret;
5487
5488 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
5489
5490 path = btrfs_alloc_path();
5491 if (!path)
5492 return -ENOMEM;
5493
5494 wc = kzalloc(sizeof(*wc), GFP_NOFS);
5495 if (!wc) {
5496 btrfs_free_path(path);
5497 return -ENOMEM;
5498 }
5499
5500 btrfs_assert_tree_locked(parent);
5501 parent_level = btrfs_header_level(parent);
5502 extent_buffer_get(parent);
5503 path->nodes[parent_level] = parent;
5504 path->slots[parent_level] = btrfs_header_nritems(parent);
5505
5506 btrfs_assert_tree_locked(node);
5507 level = btrfs_header_level(node);
5508 path->nodes[level] = node;
5509 path->slots[level] = 0;
5510 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
5511
5512 wc->refs[parent_level] = 1;
5513 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5514 wc->level = level;
5515 wc->shared_level = -1;
5516 wc->stage = DROP_REFERENCE;
5517 wc->update_ref = 0;
5518 wc->keep_locks = 1;
5519 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
5520
5521 while (1) {
5522 wret = walk_down_tree(trans, root, path, wc);
5523 if (wret < 0) {
5524 ret = wret;
5525 break;
5526 }
5527
5528 wret = walk_up_tree(trans, root, path, wc, parent_level);
5529 if (wret < 0)
5530 ret = wret;
5531 if (wret != 0)
5532 break;
5533 }
5534
5535 kfree(wc);
5536 btrfs_free_path(path);
5537 return ret;
5538}
5539
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005540/*
5541 * helper to account the unused space of all the readonly block group in the
5542 * space_info. takes mirrors into account.
5543 */
5544u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
5545{
5546 struct btrfs_block_group_cache *block_group;
5547 u64 free_bytes = 0;
5548 int factor;
5549
5550 /* It's df, we don't care if it's racy */
5551 if (list_empty(&sinfo->ro_bgs))
5552 return 0;
5553
5554 spin_lock(&sinfo->lock);
5555 list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
5556 spin_lock(&block_group->lock);
5557
5558 if (!block_group->ro) {
5559 spin_unlock(&block_group->lock);
5560 continue;
5561 }
5562
5563 factor = btrfs_bg_type_to_factor(block_group->flags);
5564 free_bytes += (block_group->key.offset -
5565 btrfs_block_group_used(&block_group->item)) *
5566 factor;
5567
5568 spin_unlock(&block_group->lock);
5569 }
5570 spin_unlock(&sinfo->lock);
5571
5572 return free_bytes;
5573}
5574
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005575int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
5576 u64 start, u64 end)
5577{
5578 return unpin_extent_range(fs_info, start, end, false);
5579}
5580
5581/*
5582 * It used to be that old block groups would be left around forever.
5583 * Iterating over them would be enough to trim unused space. Since we
5584 * now automatically remove them, we also need to iterate over unallocated
5585 * space.
5586 *
5587 * We don't want a transaction for this since the discard may take a
5588 * substantial amount of time. We don't require that a transaction be
5589 * running, but we do need to take a running transaction into account
5590 * to ensure that we're not discarding chunks that were released or
5591 * allocated in the current transaction.
5592 *
5593 * Holding the chunks lock will prevent other threads from allocating
5594 * or releasing chunks, but it won't prevent a running transaction
5595 * from committing and releasing the memory that the pending chunks
5596 * list head uses. For that, we need to take a reference to the
5597 * transaction and hold the commit root sem. We only need to hold
5598 * it while performing the free space search since we have already
5599 * held back allocations.
5600 */
David Brazdil0f672f62019-12-10 10:32:29 +00005601static int btrfs_trim_free_extents(struct btrfs_device *device, u64 *trimmed)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005602{
David Brazdil0f672f62019-12-10 10:32:29 +00005603 u64 start = SZ_1M, len = 0, end = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005604 int ret;
5605
5606 *trimmed = 0;
5607
5608 /* Discard not supported = nothing to do. */
5609 if (!blk_queue_discard(bdev_get_queue(device->bdev)))
5610 return 0;
5611
David Brazdil0f672f62019-12-10 10:32:29 +00005612 /* Not writable = nothing to do. */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005613 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
5614 return 0;
5615
5616 /* No free space = nothing to do. */
5617 if (device->total_bytes <= device->bytes_used)
5618 return 0;
5619
5620 ret = 0;
5621
5622 while (1) {
5623 struct btrfs_fs_info *fs_info = device->fs_info;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005624 u64 bytes;
5625
5626 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
5627 if (ret)
5628 break;
5629
David Brazdil0f672f62019-12-10 10:32:29 +00005630 find_first_clear_extent_bit(&device->alloc_state, start,
5631 &start, &end,
5632 CHUNK_TRIMMED | CHUNK_ALLOCATED);
5633
Olivier Deprez0e641232021-09-23 10:07:05 +02005634 /* Check if there are any CHUNK_* bits left */
5635 if (start > device->total_bytes) {
5636 WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
5637 btrfs_warn_in_rcu(fs_info,
5638"ignoring attempt to trim beyond device size: offset %llu length %llu device %s device size %llu",
5639 start, end - start + 1,
5640 rcu_str_deref(device->name),
5641 device->total_bytes);
5642 mutex_unlock(&fs_info->chunk_mutex);
5643 ret = 0;
5644 break;
5645 }
5646
David Brazdil0f672f62019-12-10 10:32:29 +00005647 /* Ensure we skip the reserved area in the first 1M */
5648 start = max_t(u64, start, SZ_1M);
5649
5650 /*
5651 * If find_first_clear_extent_bit find a range that spans the
5652 * end of the device it will set end to -1, in this case it's up
5653 * to the caller to trim the value to the size of the device.
5654 */
5655 end = min(end, device->total_bytes - 1);
5656
5657 len = end - start + 1;
5658
5659 /* We didn't find any extents */
5660 if (!len) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005661 mutex_unlock(&fs_info->chunk_mutex);
David Brazdil0f672f62019-12-10 10:32:29 +00005662 ret = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005663 break;
5664 }
5665
David Brazdil0f672f62019-12-10 10:32:29 +00005666 ret = btrfs_issue_discard(device->bdev, start, len,
5667 &bytes);
5668 if (!ret)
5669 set_extent_bits(&device->alloc_state, start,
5670 start + bytes - 1,
5671 CHUNK_TRIMMED);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005672 mutex_unlock(&fs_info->chunk_mutex);
5673
5674 if (ret)
5675 break;
5676
5677 start += len;
5678 *trimmed += bytes;
5679
5680 if (fatal_signal_pending(current)) {
5681 ret = -ERESTARTSYS;
5682 break;
5683 }
5684
5685 cond_resched();
5686 }
5687
5688 return ret;
5689}
5690
5691/*
5692 * Trim the whole filesystem by:
5693 * 1) trimming the free space in each block group
5694 * 2) trimming the unallocated space on each device
5695 *
5696 * This will also continue trimming even if a block group or device encounters
5697 * an error. The return value will be the last error, or 0 if nothing bad
5698 * happens.
5699 */
5700int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
5701{
5702 struct btrfs_block_group_cache *cache = NULL;
5703 struct btrfs_device *device;
5704 struct list_head *devices;
5705 u64 group_trimmed;
David Brazdil0f672f62019-12-10 10:32:29 +00005706 u64 range_end = U64_MAX;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005707 u64 start;
5708 u64 end;
5709 u64 trimmed = 0;
5710 u64 bg_failed = 0;
5711 u64 dev_failed = 0;
5712 int bg_ret = 0;
5713 int dev_ret = 0;
5714 int ret = 0;
5715
David Brazdil0f672f62019-12-10 10:32:29 +00005716 /*
5717 * Check range overflow if range->len is set.
5718 * The default range->len is U64_MAX.
5719 */
5720 if (range->len != U64_MAX &&
5721 check_add_overflow(range->start, range->len, &range_end))
5722 return -EINVAL;
5723
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005724 cache = btrfs_lookup_first_block_group(fs_info, range->start);
David Brazdil0f672f62019-12-10 10:32:29 +00005725 for (; cache; cache = btrfs_next_block_group(cache)) {
5726 if (cache->key.objectid >= range_end) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005727 btrfs_put_block_group(cache);
5728 break;
5729 }
5730
5731 start = max(range->start, cache->key.objectid);
David Brazdil0f672f62019-12-10 10:32:29 +00005732 end = min(range_end, cache->key.objectid + cache->key.offset);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005733
5734 if (end - start >= range->minlen) {
David Brazdil0f672f62019-12-10 10:32:29 +00005735 if (!btrfs_block_group_cache_done(cache)) {
5736 ret = btrfs_cache_block_group(cache, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005737 if (ret) {
5738 bg_failed++;
5739 bg_ret = ret;
5740 continue;
5741 }
David Brazdil0f672f62019-12-10 10:32:29 +00005742 ret = btrfs_wait_block_group_cache_done(cache);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005743 if (ret) {
5744 bg_failed++;
5745 bg_ret = ret;
5746 continue;
5747 }
5748 }
5749 ret = btrfs_trim_block_group(cache,
5750 &group_trimmed,
5751 start,
5752 end,
5753 range->minlen);
5754
5755 trimmed += group_trimmed;
5756 if (ret) {
5757 bg_failed++;
5758 bg_ret = ret;
5759 continue;
5760 }
5761 }
5762 }
5763
5764 if (bg_failed)
5765 btrfs_warn(fs_info,
5766 "failed to trim %llu block group(s), last error %d",
5767 bg_failed, bg_ret);
5768 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5769 devices = &fs_info->fs_devices->devices;
5770 list_for_each_entry(device, devices, dev_list) {
Olivier Deprez0e641232021-09-23 10:07:05 +02005771 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
5772 continue;
5773
David Brazdil0f672f62019-12-10 10:32:29 +00005774 ret = btrfs_trim_free_extents(device, &group_trimmed);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005775 if (ret) {
5776 dev_failed++;
5777 dev_ret = ret;
5778 break;
5779 }
5780
5781 trimmed += group_trimmed;
5782 }
5783 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5784
5785 if (dev_failed)
5786 btrfs_warn(fs_info,
5787 "failed to trim %llu device(s), last error %d",
5788 dev_failed, dev_ret);
5789 range->len = trimmed;
5790 if (bg_ret)
5791 return bg_ret;
5792 return dev_ret;
5793}
5794
5795/*
5796 * btrfs_{start,end}_write_no_snapshotting() are similar to
5797 * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
5798 * data into the page cache through nocow before the subvolume is snapshoted,
5799 * but flush the data into disk after the snapshot creation, or to prevent
5800 * operations while snapshotting is ongoing and that cause the snapshot to be
5801 * inconsistent (writes followed by expanding truncates for example).
5802 */
5803void btrfs_end_write_no_snapshotting(struct btrfs_root *root)
5804{
5805 percpu_counter_dec(&root->subv_writers->counter);
5806 cond_wake_up(&root->subv_writers->wait);
5807}
5808
5809int btrfs_start_write_no_snapshotting(struct btrfs_root *root)
5810{
5811 if (atomic_read(&root->will_be_snapshotted))
5812 return 0;
5813
5814 percpu_counter_inc(&root->subv_writers->counter);
5815 /*
5816 * Make sure counter is updated before we check for snapshot creation.
5817 */
5818 smp_mb();
5819 if (atomic_read(&root->will_be_snapshotted)) {
5820 btrfs_end_write_no_snapshotting(root);
5821 return 0;
5822 }
5823 return 1;
5824}
5825
5826void btrfs_wait_for_snapshot_creation(struct btrfs_root *root)
5827{
5828 while (true) {
5829 int ret;
5830
5831 ret = btrfs_start_write_no_snapshotting(root);
5832 if (ret)
5833 break;
5834 wait_var_event(&root->will_be_snapshotted,
5835 !atomic_read(&root->will_be_snapshotted));
5836 }
5837}