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