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