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