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