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