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