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