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