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