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