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