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