clk: baikal-t1: Convert to platform device driver
[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         return ret;
1710 }
1711
1712 static inline struct btrfs_delayed_ref_node *
1713 select_delayed_ref(struct btrfs_delayed_ref_head *head)
1714 {
1715         struct btrfs_delayed_ref_node *ref;
1716
1717         if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
1718                 return NULL;
1719
1720         /*
1721          * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
1722          * This is to prevent a ref count from going down to zero, which deletes
1723          * the extent item from the extent tree, when there still are references
1724          * to add, which would fail because they would not find the extent item.
1725          */
1726         if (!list_empty(&head->ref_add_list))
1727                 return list_first_entry(&head->ref_add_list,
1728                                 struct btrfs_delayed_ref_node, add_list);
1729
1730         ref = rb_entry(rb_first_cached(&head->ref_tree),
1731                        struct btrfs_delayed_ref_node, ref_node);
1732         ASSERT(list_empty(&ref->add_list));
1733         return ref;
1734 }
1735
1736 static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
1737                                       struct btrfs_delayed_ref_head *head)
1738 {
1739         spin_lock(&delayed_refs->lock);
1740         head->processing = 0;
1741         delayed_refs->num_heads_ready++;
1742         spin_unlock(&delayed_refs->lock);
1743         btrfs_delayed_ref_unlock(head);
1744 }
1745
1746 static struct btrfs_delayed_extent_op *cleanup_extent_op(
1747                                 struct btrfs_delayed_ref_head *head)
1748 {
1749         struct btrfs_delayed_extent_op *extent_op = head->extent_op;
1750
1751         if (!extent_op)
1752                 return NULL;
1753
1754         if (head->must_insert_reserved) {
1755                 head->extent_op = NULL;
1756                 btrfs_free_delayed_extent_op(extent_op);
1757                 return NULL;
1758         }
1759         return extent_op;
1760 }
1761
1762 static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
1763                                      struct btrfs_delayed_ref_head *head)
1764 {
1765         struct btrfs_delayed_extent_op *extent_op;
1766         int ret;
1767
1768         extent_op = cleanup_extent_op(head);
1769         if (!extent_op)
1770                 return 0;
1771         head->extent_op = NULL;
1772         spin_unlock(&head->lock);
1773         ret = run_delayed_extent_op(trans, head, extent_op);
1774         btrfs_free_delayed_extent_op(extent_op);
1775         return ret ? ret : 1;
1776 }
1777
1778 void btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
1779                                   struct btrfs_delayed_ref_root *delayed_refs,
1780                                   struct btrfs_delayed_ref_head *head)
1781 {
1782         int nr_items = 1;       /* Dropping this ref head update. */
1783
1784         /*
1785          * We had csum deletions accounted for in our delayed refs rsv, we need
1786          * to drop the csum leaves for this update from our delayed_refs_rsv.
1787          */
1788         if (head->total_ref_mod < 0 && head->is_data) {
1789                 spin_lock(&delayed_refs->lock);
1790                 delayed_refs->pending_csums -= head->num_bytes;
1791                 spin_unlock(&delayed_refs->lock);
1792                 nr_items += btrfs_csum_bytes_to_leaves(fs_info, head->num_bytes);
1793         }
1794
1795         btrfs_delayed_refs_rsv_release(fs_info, nr_items);
1796 }
1797
1798 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
1799                             struct btrfs_delayed_ref_head *head)
1800 {
1801
1802         struct btrfs_fs_info *fs_info = trans->fs_info;
1803         struct btrfs_delayed_ref_root *delayed_refs;
1804         int ret;
1805
1806         delayed_refs = &trans->transaction->delayed_refs;
1807
1808         ret = run_and_cleanup_extent_op(trans, head);
1809         if (ret < 0) {
1810                 unselect_delayed_ref_head(delayed_refs, head);
1811                 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
1812                 return ret;
1813         } else if (ret) {
1814                 return ret;
1815         }
1816
1817         /*
1818          * Need to drop our head ref lock and re-acquire the delayed ref lock
1819          * and then re-check to make sure nobody got added.
1820          */
1821         spin_unlock(&head->lock);
1822         spin_lock(&delayed_refs->lock);
1823         spin_lock(&head->lock);
1824         if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
1825                 spin_unlock(&head->lock);
1826                 spin_unlock(&delayed_refs->lock);
1827                 return 1;
1828         }
1829         btrfs_delete_ref_head(delayed_refs, head);
1830         spin_unlock(&head->lock);
1831         spin_unlock(&delayed_refs->lock);
1832
1833         if (head->must_insert_reserved) {
1834                 btrfs_pin_extent(trans, head->bytenr, head->num_bytes, 1);
1835                 if (head->is_data) {
1836                         struct btrfs_root *csum_root;
1837
1838                         csum_root = btrfs_csum_root(fs_info, head->bytenr);
1839                         ret = btrfs_del_csums(trans, csum_root, head->bytenr,
1840                                               head->num_bytes);
1841                 }
1842         }
1843
1844         btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
1845
1846         trace_run_delayed_ref_head(fs_info, head, 0);
1847         btrfs_delayed_ref_unlock(head);
1848         btrfs_put_delayed_ref_head(head);
1849         return ret;
1850 }
1851
1852 static struct btrfs_delayed_ref_head *btrfs_obtain_ref_head(
1853                                         struct btrfs_trans_handle *trans)
1854 {
1855         struct btrfs_delayed_ref_root *delayed_refs =
1856                 &trans->transaction->delayed_refs;
1857         struct btrfs_delayed_ref_head *head = NULL;
1858         int ret;
1859
1860         spin_lock(&delayed_refs->lock);
1861         head = btrfs_select_ref_head(delayed_refs);
1862         if (!head) {
1863                 spin_unlock(&delayed_refs->lock);
1864                 return head;
1865         }
1866
1867         /*
1868          * Grab the lock that says we are going to process all the refs for
1869          * this head
1870          */
1871         ret = btrfs_delayed_ref_lock(delayed_refs, head);
1872         spin_unlock(&delayed_refs->lock);
1873
1874         /*
1875          * We may have dropped the spin lock to get the head mutex lock, and
1876          * that might have given someone else time to free the head.  If that's
1877          * true, it has been removed from our list and we can move on.
1878          */
1879         if (ret == -EAGAIN)
1880                 head = ERR_PTR(-EAGAIN);
1881
1882         return head;
1883 }
1884
1885 static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
1886                                     struct btrfs_delayed_ref_head *locked_ref,
1887                                     unsigned long *run_refs)
1888 {
1889         struct btrfs_fs_info *fs_info = trans->fs_info;
1890         struct btrfs_delayed_ref_root *delayed_refs;
1891         struct btrfs_delayed_extent_op *extent_op;
1892         struct btrfs_delayed_ref_node *ref;
1893         int must_insert_reserved = 0;
1894         int ret;
1895
1896         delayed_refs = &trans->transaction->delayed_refs;
1897
1898         lockdep_assert_held(&locked_ref->mutex);
1899         lockdep_assert_held(&locked_ref->lock);
1900
1901         while ((ref = select_delayed_ref(locked_ref))) {
1902                 if (ref->seq &&
1903                     btrfs_check_delayed_seq(fs_info, ref->seq)) {
1904                         spin_unlock(&locked_ref->lock);
1905                         unselect_delayed_ref_head(delayed_refs, locked_ref);
1906                         return -EAGAIN;
1907                 }
1908
1909                 (*run_refs)++;
1910                 ref->in_tree = 0;
1911                 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
1912                 RB_CLEAR_NODE(&ref->ref_node);
1913                 if (!list_empty(&ref->add_list))
1914                         list_del(&ref->add_list);
1915                 /*
1916                  * When we play the delayed ref, also correct the ref_mod on
1917                  * head
1918                  */
1919                 switch (ref->action) {
1920                 case BTRFS_ADD_DELAYED_REF:
1921                 case BTRFS_ADD_DELAYED_EXTENT:
1922                         locked_ref->ref_mod -= ref->ref_mod;
1923                         break;
1924                 case BTRFS_DROP_DELAYED_REF:
1925                         locked_ref->ref_mod += ref->ref_mod;
1926                         break;
1927                 default:
1928                         WARN_ON(1);
1929                 }
1930                 atomic_dec(&delayed_refs->num_entries);
1931
1932                 /*
1933                  * Record the must_insert_reserved flag before we drop the
1934                  * spin lock.
1935                  */
1936                 must_insert_reserved = locked_ref->must_insert_reserved;
1937                 locked_ref->must_insert_reserved = 0;
1938
1939                 extent_op = locked_ref->extent_op;
1940                 locked_ref->extent_op = NULL;
1941                 spin_unlock(&locked_ref->lock);
1942
1943                 ret = run_one_delayed_ref(trans, ref, extent_op,
1944                                           must_insert_reserved);
1945
1946                 btrfs_free_delayed_extent_op(extent_op);
1947                 if (ret) {
1948                         unselect_delayed_ref_head(delayed_refs, locked_ref);
1949                         btrfs_put_delayed_ref(ref);
1950                         btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
1951                                     ret);
1952                         return ret;
1953                 }
1954
1955                 btrfs_put_delayed_ref(ref);
1956                 cond_resched();
1957
1958                 spin_lock(&locked_ref->lock);
1959                 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
1960         }
1961
1962         return 0;
1963 }
1964
1965 /*
1966  * Returns 0 on success or if called with an already aborted transaction.
1967  * Returns -ENOMEM or -EIO on failure and will abort the transaction.
1968  */
1969 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
1970                                              unsigned long nr)
1971 {
1972         struct btrfs_fs_info *fs_info = trans->fs_info;
1973         struct btrfs_delayed_ref_root *delayed_refs;
1974         struct btrfs_delayed_ref_head *locked_ref = NULL;
1975         ktime_t start = ktime_get();
1976         int ret;
1977         unsigned long count = 0;
1978         unsigned long actual_count = 0;
1979
1980         delayed_refs = &trans->transaction->delayed_refs;
1981         do {
1982                 if (!locked_ref) {
1983                         locked_ref = btrfs_obtain_ref_head(trans);
1984                         if (IS_ERR_OR_NULL(locked_ref)) {
1985                                 if (PTR_ERR(locked_ref) == -EAGAIN) {
1986                                         continue;
1987                                 } else {
1988                                         break;
1989                                 }
1990                         }
1991                         count++;
1992                 }
1993                 /*
1994                  * We need to try and merge add/drops of the same ref since we
1995                  * can run into issues with relocate dropping the implicit ref
1996                  * and then it being added back again before the drop can
1997                  * finish.  If we merged anything we need to re-loop so we can
1998                  * get a good ref.
1999                  * Or we can get node references of the same type that weren't
2000                  * merged when created due to bumps in the tree mod seq, and
2001                  * we need to merge them to prevent adding an inline extent
2002                  * backref before dropping it (triggering a BUG_ON at
2003                  * insert_inline_extent_backref()).
2004                  */
2005                 spin_lock(&locked_ref->lock);
2006                 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2007
2008                 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref,
2009                                                       &actual_count);
2010                 if (ret < 0 && ret != -EAGAIN) {
2011                         /*
2012                          * Error, btrfs_run_delayed_refs_for_head already
2013                          * unlocked everything so just bail out
2014                          */
2015                         return ret;
2016                 } else if (!ret) {
2017                         /*
2018                          * Success, perform the usual cleanup of a processed
2019                          * head
2020                          */
2021                         ret = cleanup_ref_head(trans, locked_ref);
2022                         if (ret > 0 ) {
2023                                 /* We dropped our lock, we need to loop. */
2024                                 ret = 0;
2025                                 continue;
2026                         } else if (ret) {
2027                                 return ret;
2028                         }
2029                 }
2030
2031                 /*
2032                  * Either success case or btrfs_run_delayed_refs_for_head
2033                  * returned -EAGAIN, meaning we need to select another head
2034                  */
2035
2036                 locked_ref = NULL;
2037                 cond_resched();
2038         } while ((nr != -1 && count < nr) || locked_ref);
2039
2040         /*
2041          * We don't want to include ref heads since we can have empty ref heads
2042          * and those will drastically skew our runtime down since we just do
2043          * accounting, no actual extent tree updates.
2044          */
2045         if (actual_count > 0) {
2046                 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2047                 u64 avg;
2048
2049                 /*
2050                  * We weigh the current average higher than our current runtime
2051                  * to avoid large swings in the average.
2052                  */
2053                 spin_lock(&delayed_refs->lock);
2054                 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2055                 fs_info->avg_delayed_ref_runtime = avg >> 2;    /* div by 4 */
2056                 spin_unlock(&delayed_refs->lock);
2057         }
2058         return 0;
2059 }
2060
2061 #ifdef SCRAMBLE_DELAYED_REFS
2062 /*
2063  * Normally delayed refs get processed in ascending bytenr order. This
2064  * correlates in most cases to the order added. To expose dependencies on this
2065  * order, we start to process the tree in the middle instead of the beginning
2066  */
2067 static u64 find_middle(struct rb_root *root)
2068 {
2069         struct rb_node *n = root->rb_node;
2070         struct btrfs_delayed_ref_node *entry;
2071         int alt = 1;
2072         u64 middle;
2073         u64 first = 0, last = 0;
2074
2075         n = rb_first(root);
2076         if (n) {
2077                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2078                 first = entry->bytenr;
2079         }
2080         n = rb_last(root);
2081         if (n) {
2082                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2083                 last = entry->bytenr;
2084         }
2085         n = root->rb_node;
2086
2087         while (n) {
2088                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2089                 WARN_ON(!entry->in_tree);
2090
2091                 middle = entry->bytenr;
2092
2093                 if (alt)
2094                         n = n->rb_left;
2095                 else
2096                         n = n->rb_right;
2097
2098                 alt = 1 - alt;
2099         }
2100         return middle;
2101 }
2102 #endif
2103
2104 /*
2105  * this starts processing the delayed reference count updates and
2106  * extent insertions we have queued up so far.  count can be
2107  * 0, which means to process everything in the tree at the start
2108  * of the run (but not newly added entries), or it can be some target
2109  * number you'd like to process.
2110  *
2111  * Returns 0 on success or if called with an aborted transaction
2112  * Returns <0 on error and aborts the transaction
2113  */
2114 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2115                            unsigned long count)
2116 {
2117         struct btrfs_fs_info *fs_info = trans->fs_info;
2118         struct rb_node *node;
2119         struct btrfs_delayed_ref_root *delayed_refs;
2120         struct btrfs_delayed_ref_head *head;
2121         int ret;
2122         int run_all = count == (unsigned long)-1;
2123
2124         /* We'll clean this up in btrfs_cleanup_transaction */
2125         if (TRANS_ABORTED(trans))
2126                 return 0;
2127
2128         if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2129                 return 0;
2130
2131         delayed_refs = &trans->transaction->delayed_refs;
2132         if (count == 0)
2133                 count = delayed_refs->num_heads_ready;
2134
2135 again:
2136 #ifdef SCRAMBLE_DELAYED_REFS
2137         delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2138 #endif
2139         ret = __btrfs_run_delayed_refs(trans, count);
2140         if (ret < 0) {
2141                 btrfs_abort_transaction(trans, ret);
2142                 return ret;
2143         }
2144
2145         if (run_all) {
2146                 btrfs_create_pending_block_groups(trans);
2147
2148                 spin_lock(&delayed_refs->lock);
2149                 node = rb_first_cached(&delayed_refs->href_root);
2150                 if (!node) {
2151                         spin_unlock(&delayed_refs->lock);
2152                         goto out;
2153                 }
2154                 head = rb_entry(node, struct btrfs_delayed_ref_head,
2155                                 href_node);
2156                 refcount_inc(&head->refs);
2157                 spin_unlock(&delayed_refs->lock);
2158
2159                 /* Mutex was contended, block until it's released and retry. */
2160                 mutex_lock(&head->mutex);
2161                 mutex_unlock(&head->mutex);
2162
2163                 btrfs_put_delayed_ref_head(head);
2164                 cond_resched();
2165                 goto again;
2166         }
2167 out:
2168         return 0;
2169 }
2170
2171 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2172                                 struct extent_buffer *eb, u64 flags,
2173                                 int level)
2174 {
2175         struct btrfs_delayed_extent_op *extent_op;
2176         int ret;
2177
2178         extent_op = btrfs_alloc_delayed_extent_op();
2179         if (!extent_op)
2180                 return -ENOMEM;
2181
2182         extent_op->flags_to_set = flags;
2183         extent_op->update_flags = true;
2184         extent_op->update_key = false;
2185         extent_op->level = level;
2186
2187         ret = btrfs_add_delayed_extent_op(trans, eb->start, eb->len, extent_op);
2188         if (ret)
2189                 btrfs_free_delayed_extent_op(extent_op);
2190         return ret;
2191 }
2192
2193 static noinline int check_delayed_ref(struct btrfs_root *root,
2194                                       struct btrfs_path *path,
2195                                       u64 objectid, u64 offset, u64 bytenr)
2196 {
2197         struct btrfs_delayed_ref_head *head;
2198         struct btrfs_delayed_ref_node *ref;
2199         struct btrfs_delayed_data_ref *data_ref;
2200         struct btrfs_delayed_ref_root *delayed_refs;
2201         struct btrfs_transaction *cur_trans;
2202         struct rb_node *node;
2203         int ret = 0;
2204
2205         spin_lock(&root->fs_info->trans_lock);
2206         cur_trans = root->fs_info->running_transaction;
2207         if (cur_trans)
2208                 refcount_inc(&cur_trans->use_count);
2209         spin_unlock(&root->fs_info->trans_lock);
2210         if (!cur_trans)
2211                 return 0;
2212
2213         delayed_refs = &cur_trans->delayed_refs;
2214         spin_lock(&delayed_refs->lock);
2215         head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
2216         if (!head) {
2217                 spin_unlock(&delayed_refs->lock);
2218                 btrfs_put_transaction(cur_trans);
2219                 return 0;
2220         }
2221
2222         if (!mutex_trylock(&head->mutex)) {
2223                 refcount_inc(&head->refs);
2224                 spin_unlock(&delayed_refs->lock);
2225
2226                 btrfs_release_path(path);
2227
2228                 /*
2229                  * Mutex was contended, block until it's released and let
2230                  * caller try again
2231                  */
2232                 mutex_lock(&head->mutex);
2233                 mutex_unlock(&head->mutex);
2234                 btrfs_put_delayed_ref_head(head);
2235                 btrfs_put_transaction(cur_trans);
2236                 return -EAGAIN;
2237         }
2238         spin_unlock(&delayed_refs->lock);
2239
2240         spin_lock(&head->lock);
2241         /*
2242          * XXX: We should replace this with a proper search function in the
2243          * future.
2244          */
2245         for (node = rb_first_cached(&head->ref_tree); node;
2246              node = rb_next(node)) {
2247                 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
2248                 /* If it's a shared ref we know a cross reference exists */
2249                 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
2250                         ret = 1;
2251                         break;
2252                 }
2253
2254                 data_ref = btrfs_delayed_node_to_data_ref(ref);
2255
2256                 /*
2257                  * If our ref doesn't match the one we're currently looking at
2258                  * then we have a cross reference.
2259                  */
2260                 if (data_ref->root != root->root_key.objectid ||
2261                     data_ref->objectid != objectid ||
2262                     data_ref->offset != offset) {
2263                         ret = 1;
2264                         break;
2265                 }
2266         }
2267         spin_unlock(&head->lock);
2268         mutex_unlock(&head->mutex);
2269         btrfs_put_transaction(cur_trans);
2270         return ret;
2271 }
2272
2273 static noinline int check_committed_ref(struct btrfs_root *root,
2274                                         struct btrfs_path *path,
2275                                         u64 objectid, u64 offset, u64 bytenr,
2276                                         bool strict)
2277 {
2278         struct btrfs_fs_info *fs_info = root->fs_info;
2279         struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
2280         struct extent_buffer *leaf;
2281         struct btrfs_extent_data_ref *ref;
2282         struct btrfs_extent_inline_ref *iref;
2283         struct btrfs_extent_item *ei;
2284         struct btrfs_key key;
2285         u32 item_size;
2286         int type;
2287         int ret;
2288
2289         key.objectid = bytenr;
2290         key.offset = (u64)-1;
2291         key.type = BTRFS_EXTENT_ITEM_KEY;
2292
2293         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2294         if (ret < 0)
2295                 goto out;
2296         BUG_ON(ret == 0); /* Corruption */
2297
2298         ret = -ENOENT;
2299         if (path->slots[0] == 0)
2300                 goto out;
2301
2302         path->slots[0]--;
2303         leaf = path->nodes[0];
2304         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2305
2306         if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2307                 goto out;
2308
2309         ret = 1;
2310         item_size = btrfs_item_size(leaf, path->slots[0]);
2311         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2312
2313         /* If extent item has more than 1 inline ref then it's shared */
2314         if (item_size != sizeof(*ei) +
2315             btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2316                 goto out;
2317
2318         /*
2319          * If extent created before last snapshot => it's shared unless the
2320          * snapshot has been deleted. Use the heuristic if strict is false.
2321          */
2322         if (!strict &&
2323             (btrfs_extent_generation(leaf, ei) <=
2324              btrfs_root_last_snapshot(&root->root_item)))
2325                 goto out;
2326
2327         iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2328
2329         /* If this extent has SHARED_DATA_REF then it's shared */
2330         type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
2331         if (type != BTRFS_EXTENT_DATA_REF_KEY)
2332                 goto out;
2333
2334         ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2335         if (btrfs_extent_refs(leaf, ei) !=
2336             btrfs_extent_data_ref_count(leaf, ref) ||
2337             btrfs_extent_data_ref_root(leaf, ref) !=
2338             root->root_key.objectid ||
2339             btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2340             btrfs_extent_data_ref_offset(leaf, ref) != offset)
2341                 goto out;
2342
2343         ret = 0;
2344 out:
2345         return ret;
2346 }
2347
2348 int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
2349                           u64 bytenr, bool strict, struct btrfs_path *path)
2350 {
2351         int ret;
2352
2353         do {
2354                 ret = check_committed_ref(root, path, objectid,
2355                                           offset, bytenr, strict);
2356                 if (ret && ret != -ENOENT)
2357                         goto out;
2358
2359                 ret = check_delayed_ref(root, path, objectid, offset, bytenr);
2360         } while (ret == -EAGAIN);
2361
2362 out:
2363         btrfs_release_path(path);
2364         if (btrfs_is_data_reloc_root(root))
2365                 WARN_ON(ret > 0);
2366         return ret;
2367 }
2368
2369 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2370                            struct btrfs_root *root,
2371                            struct extent_buffer *buf,
2372                            int full_backref, int inc)
2373 {
2374         struct btrfs_fs_info *fs_info = root->fs_info;
2375         u64 bytenr;
2376         u64 num_bytes;
2377         u64 parent;
2378         u64 ref_root;
2379         u32 nritems;
2380         struct btrfs_key key;
2381         struct btrfs_file_extent_item *fi;
2382         struct btrfs_ref generic_ref = { 0 };
2383         bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC);
2384         int i;
2385         int action;
2386         int level;
2387         int ret = 0;
2388
2389         if (btrfs_is_testing(fs_info))
2390                 return 0;
2391
2392         ref_root = btrfs_header_owner(buf);
2393         nritems = btrfs_header_nritems(buf);
2394         level = btrfs_header_level(buf);
2395
2396         if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state) && level == 0)
2397                 return 0;
2398
2399         if (full_backref)
2400                 parent = buf->start;
2401         else
2402                 parent = 0;
2403         if (inc)
2404                 action = BTRFS_ADD_DELAYED_REF;
2405         else
2406                 action = BTRFS_DROP_DELAYED_REF;
2407
2408         for (i = 0; i < nritems; i++) {
2409                 if (level == 0) {
2410                         btrfs_item_key_to_cpu(buf, &key, i);
2411                         if (key.type != BTRFS_EXTENT_DATA_KEY)
2412                                 continue;
2413                         fi = btrfs_item_ptr(buf, i,
2414                                             struct btrfs_file_extent_item);
2415                         if (btrfs_file_extent_type(buf, fi) ==
2416                             BTRFS_FILE_EXTENT_INLINE)
2417                                 continue;
2418                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2419                         if (bytenr == 0)
2420                                 continue;
2421
2422                         num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2423                         key.offset -= btrfs_file_extent_offset(buf, fi);
2424                         btrfs_init_generic_ref(&generic_ref, action, bytenr,
2425                                                num_bytes, parent);
2426                         btrfs_init_data_ref(&generic_ref, ref_root, key.objectid,
2427                                             key.offset, root->root_key.objectid,
2428                                             for_reloc);
2429                         if (inc)
2430                                 ret = btrfs_inc_extent_ref(trans, &generic_ref);
2431                         else
2432                                 ret = btrfs_free_extent(trans, &generic_ref);
2433                         if (ret)
2434                                 goto fail;
2435                 } else {
2436                         bytenr = btrfs_node_blockptr(buf, i);
2437                         num_bytes = fs_info->nodesize;
2438                         btrfs_init_generic_ref(&generic_ref, action, bytenr,
2439                                                num_bytes, parent);
2440                         btrfs_init_tree_ref(&generic_ref, level - 1, ref_root,
2441                                             root->root_key.objectid, for_reloc);
2442                         if (inc)
2443                                 ret = btrfs_inc_extent_ref(trans, &generic_ref);
2444                         else
2445                                 ret = btrfs_free_extent(trans, &generic_ref);
2446                         if (ret)
2447                                 goto fail;
2448                 }
2449         }
2450         return 0;
2451 fail:
2452         return ret;
2453 }
2454
2455 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2456                   struct extent_buffer *buf, int full_backref)
2457 {
2458         return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
2459 }
2460
2461 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2462                   struct extent_buffer *buf, int full_backref)
2463 {
2464         return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
2465 }
2466
2467 static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
2468 {
2469         struct btrfs_fs_info *fs_info = root->fs_info;
2470         u64 flags;
2471         u64 ret;
2472
2473         if (data)
2474                 flags = BTRFS_BLOCK_GROUP_DATA;
2475         else if (root == fs_info->chunk_root)
2476                 flags = BTRFS_BLOCK_GROUP_SYSTEM;
2477         else
2478                 flags = BTRFS_BLOCK_GROUP_METADATA;
2479
2480         ret = btrfs_get_alloc_profile(fs_info, flags);
2481         return ret;
2482 }
2483
2484 static u64 first_logical_byte(struct btrfs_fs_info *fs_info)
2485 {
2486         struct rb_node *leftmost;
2487         u64 bytenr = 0;
2488
2489         read_lock(&fs_info->block_group_cache_lock);
2490         /* Get the block group with the lowest logical start address. */
2491         leftmost = rb_first_cached(&fs_info->block_group_cache_tree);
2492         if (leftmost) {
2493                 struct btrfs_block_group *bg;
2494
2495                 bg = rb_entry(leftmost, struct btrfs_block_group, cache_node);
2496                 bytenr = bg->start;
2497         }
2498         read_unlock(&fs_info->block_group_cache_lock);
2499
2500         return bytenr;
2501 }
2502
2503 static int pin_down_extent(struct btrfs_trans_handle *trans,
2504                            struct btrfs_block_group *cache,
2505                            u64 bytenr, u64 num_bytes, int reserved)
2506 {
2507         struct btrfs_fs_info *fs_info = cache->fs_info;
2508
2509         spin_lock(&cache->space_info->lock);
2510         spin_lock(&cache->lock);
2511         cache->pinned += num_bytes;
2512         btrfs_space_info_update_bytes_pinned(fs_info, cache->space_info,
2513                                              num_bytes);
2514         if (reserved) {
2515                 cache->reserved -= num_bytes;
2516                 cache->space_info->bytes_reserved -= num_bytes;
2517         }
2518         spin_unlock(&cache->lock);
2519         spin_unlock(&cache->space_info->lock);
2520
2521         set_extent_dirty(&trans->transaction->pinned_extents, bytenr,
2522                          bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
2523         return 0;
2524 }
2525
2526 int btrfs_pin_extent(struct btrfs_trans_handle *trans,
2527                      u64 bytenr, u64 num_bytes, int reserved)
2528 {
2529         struct btrfs_block_group *cache;
2530
2531         cache = btrfs_lookup_block_group(trans->fs_info, bytenr);
2532         BUG_ON(!cache); /* Logic error */
2533
2534         pin_down_extent(trans, cache, bytenr, num_bytes, reserved);
2535
2536         btrfs_put_block_group(cache);
2537         return 0;
2538 }
2539
2540 /*
2541  * this function must be called within transaction
2542  */
2543 int btrfs_pin_extent_for_log_replay(struct btrfs_trans_handle *trans,
2544                                     u64 bytenr, u64 num_bytes)
2545 {
2546         struct btrfs_block_group *cache;
2547         int ret;
2548
2549         cache = btrfs_lookup_block_group(trans->fs_info, bytenr);
2550         if (!cache)
2551                 return -EINVAL;
2552
2553         /*
2554          * pull in the free space cache (if any) so that our pin
2555          * removes the free space from the cache.  We have load_only set
2556          * to one because the slow code to read in the free extents does check
2557          * the pinned extents.
2558          */
2559         btrfs_cache_block_group(cache, 1);
2560         /*
2561          * Make sure we wait until the cache is completely built in case it is
2562          * missing or is invalid and therefore needs to be rebuilt.
2563          */
2564         ret = btrfs_wait_block_group_cache_done(cache);
2565         if (ret)
2566                 goto out;
2567
2568         pin_down_extent(trans, cache, bytenr, num_bytes, 0);
2569
2570         /* remove us from the free space cache (if we're there at all) */
2571         ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
2572 out:
2573         btrfs_put_block_group(cache);
2574         return ret;
2575 }
2576
2577 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
2578                                    u64 start, u64 num_bytes)
2579 {
2580         int ret;
2581         struct btrfs_block_group *block_group;
2582
2583         block_group = btrfs_lookup_block_group(fs_info, start);
2584         if (!block_group)
2585                 return -EINVAL;
2586
2587         btrfs_cache_block_group(block_group, 1);
2588         /*
2589          * Make sure we wait until the cache is completely built in case it is
2590          * missing or is invalid and therefore needs to be rebuilt.
2591          */
2592         ret = btrfs_wait_block_group_cache_done(block_group);
2593         if (ret)
2594                 goto out;
2595
2596         ret = btrfs_remove_free_space(block_group, start, num_bytes);
2597 out:
2598         btrfs_put_block_group(block_group);
2599         return ret;
2600 }
2601
2602 int btrfs_exclude_logged_extents(struct extent_buffer *eb)
2603 {
2604         struct btrfs_fs_info *fs_info = eb->fs_info;
2605         struct btrfs_file_extent_item *item;
2606         struct btrfs_key key;
2607         int found_type;
2608         int i;
2609         int ret = 0;
2610
2611         if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
2612                 return 0;
2613
2614         for (i = 0; i < btrfs_header_nritems(eb); i++) {
2615                 btrfs_item_key_to_cpu(eb, &key, i);
2616                 if (key.type != BTRFS_EXTENT_DATA_KEY)
2617                         continue;
2618                 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
2619                 found_type = btrfs_file_extent_type(eb, item);
2620                 if (found_type == BTRFS_FILE_EXTENT_INLINE)
2621                         continue;
2622                 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
2623                         continue;
2624                 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
2625                 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
2626                 ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
2627                 if (ret)
2628                         break;
2629         }
2630
2631         return ret;
2632 }
2633
2634 static void
2635 btrfs_inc_block_group_reservations(struct btrfs_block_group *bg)
2636 {
2637         atomic_inc(&bg->reservations);
2638 }
2639
2640 /*
2641  * Returns the free cluster for the given space info and sets empty_cluster to
2642  * what it should be based on the mount options.
2643  */
2644 static struct btrfs_free_cluster *
2645 fetch_cluster_info(struct btrfs_fs_info *fs_info,
2646                    struct btrfs_space_info *space_info, u64 *empty_cluster)
2647 {
2648         struct btrfs_free_cluster *ret = NULL;
2649
2650         *empty_cluster = 0;
2651         if (btrfs_mixed_space_info(space_info))
2652                 return ret;
2653
2654         if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
2655                 ret = &fs_info->meta_alloc_cluster;
2656                 if (btrfs_test_opt(fs_info, SSD))
2657                         *empty_cluster = SZ_2M;
2658                 else
2659                         *empty_cluster = SZ_64K;
2660         } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
2661                    btrfs_test_opt(fs_info, SSD_SPREAD)) {
2662                 *empty_cluster = SZ_2M;
2663                 ret = &fs_info->data_alloc_cluster;
2664         }
2665
2666         return ret;
2667 }
2668
2669 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
2670                               u64 start, u64 end,
2671                               const bool return_free_space)
2672 {
2673         struct btrfs_block_group *cache = NULL;
2674         struct btrfs_space_info *space_info;
2675         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
2676         struct btrfs_free_cluster *cluster = NULL;
2677         u64 len;
2678         u64 total_unpinned = 0;
2679         u64 empty_cluster = 0;
2680         bool readonly;
2681
2682         while (start <= end) {
2683                 readonly = false;
2684                 if (!cache ||
2685                     start >= cache->start + cache->length) {
2686                         if (cache)
2687                                 btrfs_put_block_group(cache);
2688                         total_unpinned = 0;
2689                         cache = btrfs_lookup_block_group(fs_info, start);
2690                         BUG_ON(!cache); /* Logic error */
2691
2692                         cluster = fetch_cluster_info(fs_info,
2693                                                      cache->space_info,
2694                                                      &empty_cluster);
2695                         empty_cluster <<= 1;
2696                 }
2697
2698                 len = cache->start + cache->length - start;
2699                 len = min(len, end + 1 - start);
2700
2701                 down_read(&fs_info->commit_root_sem);
2702                 if (start < cache->last_byte_to_unpin && return_free_space) {
2703                         u64 add_len = min(len, cache->last_byte_to_unpin - start);
2704
2705                         btrfs_add_free_space(cache, start, add_len);
2706                 }
2707                 up_read(&fs_info->commit_root_sem);
2708
2709                 start += len;
2710                 total_unpinned += len;
2711                 space_info = cache->space_info;
2712
2713                 /*
2714                  * If this space cluster has been marked as fragmented and we've
2715                  * unpinned enough in this block group to potentially allow a
2716                  * cluster to be created inside of it go ahead and clear the
2717                  * fragmented check.
2718                  */
2719                 if (cluster && cluster->fragmented &&
2720                     total_unpinned > empty_cluster) {
2721                         spin_lock(&cluster->lock);
2722                         cluster->fragmented = 0;
2723                         spin_unlock(&cluster->lock);
2724                 }
2725
2726                 spin_lock(&space_info->lock);
2727                 spin_lock(&cache->lock);
2728                 cache->pinned -= len;
2729                 btrfs_space_info_update_bytes_pinned(fs_info, space_info, -len);
2730                 space_info->max_extent_size = 0;
2731                 if (cache->ro) {
2732                         space_info->bytes_readonly += len;
2733                         readonly = true;
2734                 } else if (btrfs_is_zoned(fs_info)) {
2735                         /* Need reset before reusing in a zoned block group */
2736                         space_info->bytes_zone_unusable += len;
2737                         readonly = true;
2738                 }
2739                 spin_unlock(&cache->lock);
2740                 if (!readonly && return_free_space &&
2741                     global_rsv->space_info == space_info) {
2742                         spin_lock(&global_rsv->lock);
2743                         if (!global_rsv->full) {
2744                                 u64 to_add = min(len, global_rsv->size -
2745                                                       global_rsv->reserved);
2746
2747                                 global_rsv->reserved += to_add;
2748                                 btrfs_space_info_update_bytes_may_use(fs_info,
2749                                                 space_info, to_add);
2750                                 if (global_rsv->reserved >= global_rsv->size)
2751                                         global_rsv->full = 1;
2752                                 len -= to_add;
2753                         }
2754                         spin_unlock(&global_rsv->lock);
2755                 }
2756                 /* Add to any tickets we may have */
2757                 if (!readonly && return_free_space && len)
2758                         btrfs_try_granting_tickets(fs_info, space_info);
2759                 spin_unlock(&space_info->lock);
2760         }
2761
2762         if (cache)
2763                 btrfs_put_block_group(cache);
2764         return 0;
2765 }
2766
2767 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
2768 {
2769         struct btrfs_fs_info *fs_info = trans->fs_info;
2770         struct btrfs_block_group *block_group, *tmp;
2771         struct list_head *deleted_bgs;
2772         struct extent_io_tree *unpin;
2773         u64 start;
2774         u64 end;
2775         int ret;
2776
2777         unpin = &trans->transaction->pinned_extents;
2778
2779         while (!TRANS_ABORTED(trans)) {
2780                 struct extent_state *cached_state = NULL;
2781
2782                 mutex_lock(&fs_info->unused_bg_unpin_mutex);
2783                 ret = find_first_extent_bit(unpin, 0, &start, &end,
2784                                             EXTENT_DIRTY, &cached_state);
2785                 if (ret) {
2786                         mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2787                         break;
2788                 }
2789
2790                 if (btrfs_test_opt(fs_info, DISCARD_SYNC))
2791                         ret = btrfs_discard_extent(fs_info, start,
2792                                                    end + 1 - start, NULL);
2793
2794                 clear_extent_dirty(unpin, start, end, &cached_state);
2795                 unpin_extent_range(fs_info, start, end, true);
2796                 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
2797                 free_extent_state(cached_state);
2798                 cond_resched();
2799         }
2800
2801         if (btrfs_test_opt(fs_info, DISCARD_ASYNC)) {
2802                 btrfs_discard_calc_delay(&fs_info->discard_ctl);
2803                 btrfs_discard_schedule_work(&fs_info->discard_ctl, true);
2804         }
2805
2806         /*
2807          * Transaction is finished.  We don't need the lock anymore.  We
2808          * do need to clean up the block groups in case of a transaction
2809          * abort.
2810          */
2811         deleted_bgs = &trans->transaction->deleted_bgs;
2812         list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
2813                 u64 trimmed = 0;
2814
2815                 ret = -EROFS;
2816                 if (!TRANS_ABORTED(trans))
2817                         ret = btrfs_discard_extent(fs_info,
2818                                                    block_group->start,
2819                                                    block_group->length,
2820                                                    &trimmed);
2821
2822                 list_del_init(&block_group->bg_list);
2823                 btrfs_unfreeze_block_group(block_group);
2824                 btrfs_put_block_group(block_group);
2825
2826                 if (ret) {
2827                         const char *errstr = btrfs_decode_error(ret);
2828                         btrfs_warn(fs_info,
2829                            "discard failed while removing blockgroup: errno=%d %s",
2830                                    ret, errstr);
2831                 }
2832         }
2833
2834         return 0;
2835 }
2836
2837 static int do_free_extent_accounting(struct btrfs_trans_handle *trans,
2838                                      u64 bytenr, u64 num_bytes, bool is_data)
2839 {
2840         int ret;
2841
2842         if (is_data) {
2843                 struct btrfs_root *csum_root;
2844
2845                 csum_root = btrfs_csum_root(trans->fs_info, bytenr);
2846                 ret = btrfs_del_csums(trans, csum_root, bytenr, num_bytes);
2847                 if (ret) {
2848                         btrfs_abort_transaction(trans, ret);
2849                         return ret;
2850                 }
2851         }
2852
2853         ret = add_to_free_space_tree(trans, bytenr, num_bytes);
2854         if (ret) {
2855                 btrfs_abort_transaction(trans, ret);
2856                 return ret;
2857         }
2858
2859         ret = btrfs_update_block_group(trans, bytenr, num_bytes, false);
2860         if (ret)
2861                 btrfs_abort_transaction(trans, ret);
2862
2863         return ret;
2864 }
2865
2866 /*
2867  * Drop one or more refs of @node.
2868  *
2869  * 1. Locate the extent refs.
2870  *    It's either inline in EXTENT/METADATA_ITEM or in keyed SHARED_* item.
2871  *    Locate it, then reduce the refs number or remove the ref line completely.
2872  *
2873  * 2. Update the refs count in EXTENT/METADATA_ITEM
2874  *
2875  * Inline backref case:
2876  *
2877  * in extent tree we have:
2878  *
2879  *      item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
2880  *              refs 2 gen 6 flags DATA
2881  *              extent data backref root FS_TREE objectid 258 offset 0 count 1
2882  *              extent data backref root FS_TREE objectid 257 offset 0 count 1
2883  *
2884  * This function gets called with:
2885  *
2886  *    node->bytenr = 13631488
2887  *    node->num_bytes = 1048576
2888  *    root_objectid = FS_TREE
2889  *    owner_objectid = 257
2890  *    owner_offset = 0
2891  *    refs_to_drop = 1
2892  *
2893  * Then we should get some like:
2894  *
2895  *      item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
2896  *              refs 1 gen 6 flags DATA
2897  *              extent data backref root FS_TREE objectid 258 offset 0 count 1
2898  *
2899  * Keyed backref case:
2900  *
2901  * in extent tree we have:
2902  *
2903  *      item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
2904  *              refs 754 gen 6 flags DATA
2905  *      [...]
2906  *      item 2 key (13631488 EXTENT_DATA_REF <HASH>) itemoff 3915 itemsize 28
2907  *              extent data backref root FS_TREE objectid 866 offset 0 count 1
2908  *
2909  * This function get called with:
2910  *
2911  *    node->bytenr = 13631488
2912  *    node->num_bytes = 1048576
2913  *    root_objectid = FS_TREE
2914  *    owner_objectid = 866
2915  *    owner_offset = 0
2916  *    refs_to_drop = 1
2917  *
2918  * Then we should get some like:
2919  *
2920  *      item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
2921  *              refs 753 gen 6 flags DATA
2922  *
2923  * And that (13631488 EXTENT_DATA_REF <HASH>) gets removed.
2924  */
2925 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
2926                                struct btrfs_delayed_ref_node *node, u64 parent,
2927                                u64 root_objectid, u64 owner_objectid,
2928                                u64 owner_offset, int refs_to_drop,
2929                                struct btrfs_delayed_extent_op *extent_op)
2930 {
2931         struct btrfs_fs_info *info = trans->fs_info;
2932         struct btrfs_key key;
2933         struct btrfs_path *path;
2934         struct btrfs_root *extent_root;
2935         struct extent_buffer *leaf;
2936         struct btrfs_extent_item *ei;
2937         struct btrfs_extent_inline_ref *iref;
2938         int ret;
2939         int is_data;
2940         int extent_slot = 0;
2941         int found_extent = 0;
2942         int num_to_del = 1;
2943         u32 item_size;
2944         u64 refs;
2945         u64 bytenr = node->bytenr;
2946         u64 num_bytes = node->num_bytes;
2947         bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
2948
2949         extent_root = btrfs_extent_root(info, bytenr);
2950         ASSERT(extent_root);
2951
2952         path = btrfs_alloc_path();
2953         if (!path)
2954                 return -ENOMEM;
2955
2956         is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
2957
2958         if (!is_data && refs_to_drop != 1) {
2959                 btrfs_crit(info,
2960 "invalid refs_to_drop, dropping more than 1 refs for tree block %llu refs_to_drop %u",
2961                            node->bytenr, refs_to_drop);
2962                 ret = -EINVAL;
2963                 btrfs_abort_transaction(trans, ret);
2964                 goto out;
2965         }
2966
2967         if (is_data)
2968                 skinny_metadata = false;
2969
2970         ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
2971                                     parent, root_objectid, owner_objectid,
2972                                     owner_offset);
2973         if (ret == 0) {
2974                 /*
2975                  * Either the inline backref or the SHARED_DATA_REF/
2976                  * SHARED_BLOCK_REF is found
2977                  *
2978                  * Here is a quick path to locate EXTENT/METADATA_ITEM.
2979                  * It's possible the EXTENT/METADATA_ITEM is near current slot.
2980                  */
2981                 extent_slot = path->slots[0];
2982                 while (extent_slot >= 0) {
2983                         btrfs_item_key_to_cpu(path->nodes[0], &key,
2984                                               extent_slot);
2985                         if (key.objectid != bytenr)
2986                                 break;
2987                         if (key.type == BTRFS_EXTENT_ITEM_KEY &&
2988                             key.offset == num_bytes) {
2989                                 found_extent = 1;
2990                                 break;
2991                         }
2992                         if (key.type == BTRFS_METADATA_ITEM_KEY &&
2993                             key.offset == owner_objectid) {
2994                                 found_extent = 1;
2995                                 break;
2996                         }
2997
2998                         /* Quick path didn't find the EXTEMT/METADATA_ITEM */
2999                         if (path->slots[0] - extent_slot > 5)
3000                                 break;
3001                         extent_slot--;
3002                 }
3003
3004                 if (!found_extent) {
3005                         if (iref) {
3006                                 btrfs_crit(info,
3007 "invalid iref, no EXTENT/METADATA_ITEM found but has inline extent ref");
3008                                 btrfs_abort_transaction(trans, -EUCLEAN);
3009                                 goto err_dump;
3010                         }
3011                         /* Must be SHARED_* item, remove the backref first */
3012                         ret = remove_extent_backref(trans, extent_root, path,
3013                                                     NULL, refs_to_drop, is_data);
3014                         if (ret) {
3015                                 btrfs_abort_transaction(trans, ret);
3016                                 goto out;
3017                         }
3018                         btrfs_release_path(path);
3019
3020                         /* Slow path to locate EXTENT/METADATA_ITEM */
3021                         key.objectid = bytenr;
3022                         key.type = BTRFS_EXTENT_ITEM_KEY;
3023                         key.offset = num_bytes;
3024
3025                         if (!is_data && skinny_metadata) {
3026                                 key.type = BTRFS_METADATA_ITEM_KEY;
3027                                 key.offset = owner_objectid;
3028                         }
3029
3030                         ret = btrfs_search_slot(trans, extent_root,
3031                                                 &key, path, -1, 1);
3032                         if (ret > 0 && skinny_metadata && path->slots[0]) {
3033                                 /*
3034                                  * Couldn't find our skinny metadata item,
3035                                  * see if we have ye olde extent item.
3036                                  */
3037                                 path->slots[0]--;
3038                                 btrfs_item_key_to_cpu(path->nodes[0], &key,
3039                                                       path->slots[0]);
3040                                 if (key.objectid == bytenr &&
3041                                     key.type == BTRFS_EXTENT_ITEM_KEY &&
3042                                     key.offset == num_bytes)
3043                                         ret = 0;
3044                         }
3045
3046                         if (ret > 0 && skinny_metadata) {
3047                                 skinny_metadata = false;
3048                                 key.objectid = bytenr;
3049                                 key.type = BTRFS_EXTENT_ITEM_KEY;
3050                                 key.offset = num_bytes;
3051                                 btrfs_release_path(path);
3052                                 ret = btrfs_search_slot(trans, extent_root,
3053                                                         &key, path, -1, 1);
3054                         }
3055
3056                         if (ret) {
3057                                 btrfs_err(info,
3058                                           "umm, got %d back from search, was looking for %llu",
3059                                           ret, bytenr);
3060                                 if (ret > 0)
3061                                         btrfs_print_leaf(path->nodes[0]);
3062                         }
3063                         if (ret < 0) {
3064                                 btrfs_abort_transaction(trans, ret);
3065                                 goto out;
3066                         }
3067                         extent_slot = path->slots[0];
3068                 }
3069         } else if (WARN_ON(ret == -ENOENT)) {
3070                 btrfs_print_leaf(path->nodes[0]);
3071                 btrfs_err(info,
3072                         "unable to find ref byte nr %llu parent %llu root %llu  owner %llu offset %llu",
3073                         bytenr, parent, root_objectid, owner_objectid,
3074                         owner_offset);
3075                 btrfs_abort_transaction(trans, ret);
3076                 goto out;
3077         } else {
3078                 btrfs_abort_transaction(trans, ret);
3079                 goto out;
3080         }
3081
3082         leaf = path->nodes[0];
3083         item_size = btrfs_item_size(leaf, extent_slot);
3084         if (unlikely(item_size < sizeof(*ei))) {
3085                 ret = -EINVAL;
3086                 btrfs_print_v0_err(info);
3087                 btrfs_abort_transaction(trans, ret);
3088                 goto out;
3089         }
3090         ei = btrfs_item_ptr(leaf, extent_slot,
3091                             struct btrfs_extent_item);
3092         if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
3093             key.type == BTRFS_EXTENT_ITEM_KEY) {
3094                 struct btrfs_tree_block_info *bi;
3095                 if (item_size < sizeof(*ei) + sizeof(*bi)) {
3096                         btrfs_crit(info,
3097 "invalid extent item size for key (%llu, %u, %llu) owner %llu, has %u expect >= %zu",
3098                                    key.objectid, key.type, key.offset,
3099                                    owner_objectid, item_size,
3100                                    sizeof(*ei) + sizeof(*bi));
3101                         btrfs_abort_transaction(trans, -EUCLEAN);
3102                         goto err_dump;
3103                 }
3104                 bi = (struct btrfs_tree_block_info *)(ei + 1);
3105                 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
3106         }
3107
3108         refs = btrfs_extent_refs(leaf, ei);
3109         if (refs < refs_to_drop) {
3110                 btrfs_crit(info,
3111                 "trying to drop %d refs but we only have %llu for bytenr %llu",
3112                           refs_to_drop, refs, bytenr);
3113                 btrfs_abort_transaction(trans, -EUCLEAN);
3114                 goto err_dump;
3115         }
3116         refs -= refs_to_drop;
3117
3118         if (refs > 0) {
3119                 if (extent_op)
3120                         __run_delayed_extent_op(extent_op, leaf, ei);
3121                 /*
3122                  * In the case of inline back ref, reference count will
3123                  * be updated by remove_extent_backref
3124                  */
3125                 if (iref) {
3126                         if (!found_extent) {
3127                                 btrfs_crit(info,
3128 "invalid iref, got inlined extent ref but no EXTENT/METADATA_ITEM found");
3129                                 btrfs_abort_transaction(trans, -EUCLEAN);
3130                                 goto err_dump;
3131                         }
3132                 } else {
3133                         btrfs_set_extent_refs(leaf, ei, refs);
3134                         btrfs_mark_buffer_dirty(leaf);
3135                 }
3136                 if (found_extent) {
3137                         ret = remove_extent_backref(trans, extent_root, path,
3138                                                     iref, refs_to_drop, is_data);
3139                         if (ret) {
3140                                 btrfs_abort_transaction(trans, ret);
3141                                 goto out;
3142                         }
3143                 }
3144         } else {
3145                 /* In this branch refs == 1 */
3146                 if (found_extent) {
3147                         if (is_data && refs_to_drop !=
3148                             extent_data_ref_count(path, iref)) {
3149                                 btrfs_crit(info,
3150                 "invalid refs_to_drop, current refs %u refs_to_drop %u",
3151                                            extent_data_ref_count(path, iref),
3152                                            refs_to_drop);
3153                                 btrfs_abort_transaction(trans, -EUCLEAN);
3154                                 goto err_dump;
3155                         }
3156                         if (iref) {
3157                                 if (path->slots[0] != extent_slot) {
3158                                         btrfs_crit(info,
3159 "invalid iref, extent item key (%llu %u %llu) doesn't have wanted iref",
3160                                                    key.objectid, key.type,
3161                                                    key.offset);
3162                                         btrfs_abort_transaction(trans, -EUCLEAN);
3163                                         goto err_dump;
3164                                 }
3165                         } else {
3166                                 /*
3167                                  * No inline ref, we must be at SHARED_* item,
3168                                  * And it's single ref, it must be:
3169                                  * |    extent_slot       ||extent_slot + 1|
3170                                  * [ EXTENT/METADATA_ITEM ][ SHARED_* ITEM ]
3171                                  */
3172                                 if (path->slots[0] != extent_slot + 1) {
3173                                         btrfs_crit(info,
3174         "invalid SHARED_* item, previous item is not EXTENT/METADATA_ITEM");
3175                                         btrfs_abort_transaction(trans, -EUCLEAN);
3176                                         goto err_dump;
3177                                 }
3178                                 path->slots[0] = extent_slot;
3179                                 num_to_del = 2;
3180                         }
3181                 }
3182
3183                 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
3184                                       num_to_del);
3185                 if (ret) {
3186                         btrfs_abort_transaction(trans, ret);
3187                         goto out;
3188                 }
3189                 btrfs_release_path(path);
3190
3191                 ret = do_free_extent_accounting(trans, bytenr, num_bytes, is_data);
3192         }
3193         btrfs_release_path(path);
3194
3195 out:
3196         btrfs_free_path(path);
3197         return ret;
3198 err_dump:
3199         /*
3200          * Leaf dump can take up a lot of log buffer, so we only do full leaf
3201          * dump for debug build.
3202          */
3203         if (IS_ENABLED(CONFIG_BTRFS_DEBUG)) {
3204                 btrfs_crit(info, "path->slots[0]=%d extent_slot=%d",
3205                            path->slots[0], extent_slot);
3206                 btrfs_print_leaf(path->nodes[0]);
3207         }
3208
3209         btrfs_free_path(path);
3210         return -EUCLEAN;
3211 }
3212
3213 /*
3214  * when we free an block, it is possible (and likely) that we free the last
3215  * delayed ref for that extent as well.  This searches the delayed ref tree for
3216  * a given extent, and if there are no other delayed refs to be processed, it
3217  * removes it from the tree.
3218  */
3219 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
3220                                       u64 bytenr)
3221 {
3222         struct btrfs_delayed_ref_head *head;
3223         struct btrfs_delayed_ref_root *delayed_refs;
3224         int ret = 0;
3225
3226         delayed_refs = &trans->transaction->delayed_refs;
3227         spin_lock(&delayed_refs->lock);
3228         head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
3229         if (!head)
3230                 goto out_delayed_unlock;
3231
3232         spin_lock(&head->lock);
3233         if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
3234                 goto out;
3235
3236         if (cleanup_extent_op(head) != NULL)
3237                 goto out;
3238
3239         /*
3240          * waiting for the lock here would deadlock.  If someone else has it
3241          * locked they are already in the process of dropping it anyway
3242          */
3243         if (!mutex_trylock(&head->mutex))
3244                 goto out;
3245
3246         btrfs_delete_ref_head(delayed_refs, head);
3247         head->processing = 0;
3248
3249         spin_unlock(&head->lock);
3250         spin_unlock(&delayed_refs->lock);
3251
3252         BUG_ON(head->extent_op);
3253         if (head->must_insert_reserved)
3254                 ret = 1;
3255
3256         btrfs_cleanup_ref_head_accounting(trans->fs_info, delayed_refs, head);
3257         mutex_unlock(&head->mutex);
3258         btrfs_put_delayed_ref_head(head);
3259         return ret;
3260 out:
3261         spin_unlock(&head->lock);
3262
3263 out_delayed_unlock:
3264         spin_unlock(&delayed_refs->lock);
3265         return 0;
3266 }
3267
3268 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
3269                            u64 root_id,
3270                            struct extent_buffer *buf,
3271                            u64 parent, int last_ref)
3272 {
3273         struct btrfs_fs_info *fs_info = trans->fs_info;
3274         struct btrfs_ref generic_ref = { 0 };
3275         int ret;
3276
3277         btrfs_init_generic_ref(&generic_ref, BTRFS_DROP_DELAYED_REF,
3278                                buf->start, buf->len, parent);
3279         btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf),
3280                             root_id, 0, false);
3281
3282         if (root_id != BTRFS_TREE_LOG_OBJECTID) {
3283                 btrfs_ref_tree_mod(fs_info, &generic_ref);
3284                 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL);
3285                 BUG_ON(ret); /* -ENOMEM */
3286         }
3287
3288         if (last_ref && btrfs_header_generation(buf) == trans->transid) {
3289                 struct btrfs_block_group *cache;
3290                 bool must_pin = false;
3291
3292                 if (root_id != BTRFS_TREE_LOG_OBJECTID) {
3293                         ret = check_ref_cleanup(trans, buf->start);
3294                         if (!ret) {
3295                                 btrfs_redirty_list_add(trans->transaction, buf);
3296                                 goto out;
3297                         }
3298                 }
3299
3300                 cache = btrfs_lookup_block_group(fs_info, buf->start);
3301
3302                 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
3303                         pin_down_extent(trans, cache, buf->start, buf->len, 1);
3304                         btrfs_put_block_group(cache);
3305                         goto out;
3306                 }
3307
3308                 /*
3309                  * If this is a leaf and there are tree mod log users, we may
3310                  * have recorded mod log operations that point to this leaf.
3311                  * So we must make sure no one reuses this leaf's extent before
3312                  * mod log operations are applied to a node, otherwise after
3313                  * rewinding a node using the mod log operations we get an
3314                  * inconsistent btree, as the leaf's extent may now be used as
3315                  * a node or leaf for another different btree.
3316                  * We are safe from races here because at this point no other
3317                  * node or root points to this extent buffer, so if after this
3318                  * check a new tree mod log user joins, it will not be able to
3319                  * find a node pointing to this leaf and record operations that
3320                  * point to this leaf.
3321                  */
3322                 if (btrfs_header_level(buf) == 0 &&
3323                     test_bit(BTRFS_FS_TREE_MOD_LOG_USERS, &fs_info->flags))
3324                         must_pin = true;
3325
3326                 if (must_pin || btrfs_is_zoned(fs_info)) {
3327                         btrfs_redirty_list_add(trans->transaction, buf);
3328                         pin_down_extent(trans, cache, buf->start, buf->len, 1);
3329                         btrfs_put_block_group(cache);
3330                         goto out;
3331                 }
3332
3333                 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
3334
3335                 btrfs_add_free_space(cache, buf->start, buf->len);
3336                 btrfs_free_reserved_bytes(cache, buf->len, 0);
3337                 btrfs_put_block_group(cache);
3338                 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
3339         }
3340 out:
3341         if (last_ref) {
3342                 /*
3343                  * Deleting the buffer, clear the corrupt flag since it doesn't
3344                  * matter anymore.
3345                  */
3346                 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
3347         }
3348 }
3349
3350 /* Can return -ENOMEM */
3351 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
3352 {
3353         struct btrfs_fs_info *fs_info = trans->fs_info;
3354         int ret;
3355
3356         if (btrfs_is_testing(fs_info))
3357                 return 0;
3358
3359         /*
3360          * tree log blocks never actually go into the extent allocation
3361          * tree, just update pinning info and exit early.
3362          */
3363         if ((ref->type == BTRFS_REF_METADATA &&
3364              ref->tree_ref.owning_root == BTRFS_TREE_LOG_OBJECTID) ||
3365             (ref->type == BTRFS_REF_DATA &&
3366              ref->data_ref.owning_root == BTRFS_TREE_LOG_OBJECTID)) {
3367                 /* unlocks the pinned mutex */
3368                 btrfs_pin_extent(trans, ref->bytenr, ref->len, 1);
3369                 ret = 0;
3370         } else if (ref->type == BTRFS_REF_METADATA) {
3371                 ret = btrfs_add_delayed_tree_ref(trans, ref, NULL);
3372         } else {
3373                 ret = btrfs_add_delayed_data_ref(trans, ref, 0);
3374         }
3375
3376         if (!((ref->type == BTRFS_REF_METADATA &&
3377                ref->tree_ref.owning_root == BTRFS_TREE_LOG_OBJECTID) ||
3378               (ref->type == BTRFS_REF_DATA &&
3379                ref->data_ref.owning_root == BTRFS_TREE_LOG_OBJECTID)))
3380                 btrfs_ref_tree_mod(fs_info, ref);
3381
3382         return ret;
3383 }
3384
3385 enum btrfs_loop_type {
3386         LOOP_CACHING_NOWAIT,
3387         LOOP_CACHING_WAIT,
3388         LOOP_ALLOC_CHUNK,
3389         LOOP_NO_EMPTY_SIZE,
3390 };
3391
3392 static inline void
3393 btrfs_lock_block_group(struct btrfs_block_group *cache,
3394                        int delalloc)
3395 {
3396         if (delalloc)
3397                 down_read(&cache->data_rwsem);
3398 }
3399
3400 static inline void btrfs_grab_block_group(struct btrfs_block_group *cache,
3401                        int delalloc)
3402 {
3403         btrfs_get_block_group(cache);
3404         if (delalloc)
3405                 down_read(&cache->data_rwsem);
3406 }
3407
3408 static struct btrfs_block_group *btrfs_lock_cluster(
3409                    struct btrfs_block_group *block_group,
3410                    struct btrfs_free_cluster *cluster,
3411                    int delalloc)
3412         __acquires(&cluster->refill_lock)
3413 {
3414         struct btrfs_block_group *used_bg = NULL;
3415
3416         spin_lock(&cluster->refill_lock);
3417         while (1) {
3418                 used_bg = cluster->block_group;
3419                 if (!used_bg)
3420                         return NULL;
3421
3422                 if (used_bg == block_group)
3423                         return used_bg;
3424
3425                 btrfs_get_block_group(used_bg);
3426
3427                 if (!delalloc)
3428                         return used_bg;
3429
3430                 if (down_read_trylock(&used_bg->data_rwsem))
3431                         return used_bg;
3432
3433                 spin_unlock(&cluster->refill_lock);
3434
3435                 /* We should only have one-level nested. */
3436                 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
3437
3438                 spin_lock(&cluster->refill_lock);
3439                 if (used_bg == cluster->block_group)
3440                         return used_bg;
3441
3442                 up_read(&used_bg->data_rwsem);
3443                 btrfs_put_block_group(used_bg);
3444         }
3445 }
3446
3447 static inline void
3448 btrfs_release_block_group(struct btrfs_block_group *cache,
3449                          int delalloc)
3450 {
3451         if (delalloc)
3452                 up_read(&cache->data_rwsem);
3453         btrfs_put_block_group(cache);
3454 }
3455
3456 enum btrfs_extent_allocation_policy {
3457         BTRFS_EXTENT_ALLOC_CLUSTERED,
3458         BTRFS_EXTENT_ALLOC_ZONED,
3459 };
3460
3461 /*
3462  * Structure used internally for find_free_extent() function.  Wraps needed
3463  * parameters.
3464  */
3465 struct find_free_extent_ctl {
3466         /* Basic allocation info */
3467         u64 ram_bytes;
3468         u64 num_bytes;
3469         u64 min_alloc_size;
3470         u64 empty_size;
3471         u64 flags;
3472         int delalloc;
3473
3474         /* Where to start the search inside the bg */
3475         u64 search_start;
3476
3477         /* For clustered allocation */
3478         u64 empty_cluster;
3479         struct btrfs_free_cluster *last_ptr;
3480         bool use_cluster;
3481
3482         bool have_caching_bg;
3483         bool orig_have_caching_bg;
3484
3485         /* Allocation is called for tree-log */
3486         bool for_treelog;
3487
3488         /* Allocation is called for data relocation */
3489         bool for_data_reloc;
3490
3491         /* RAID index, converted from flags */
3492         int index;
3493
3494         /*
3495          * Current loop number, check find_free_extent_update_loop() for details
3496          */
3497         int loop;
3498
3499         /*
3500          * Whether we're refilling a cluster, if true we need to re-search
3501          * current block group but don't try to refill the cluster again.
3502          */
3503         bool retry_clustered;
3504
3505         /*
3506          * Whether we're updating free space cache, if true we need to re-search
3507          * current block group but don't try updating free space cache again.
3508          */
3509         bool retry_unclustered;
3510
3511         /* If current block group is cached */
3512         int cached;
3513
3514         /* Max contiguous hole found */
3515         u64 max_extent_size;
3516
3517         /* Total free space from free space cache, not always contiguous */
3518         u64 total_free_space;
3519
3520         /* Found result */
3521         u64 found_offset;
3522
3523         /* Hint where to start looking for an empty space */
3524         u64 hint_byte;
3525
3526         /* Allocation policy */
3527         enum btrfs_extent_allocation_policy policy;
3528 };
3529
3530
3531 /*
3532  * Helper function for find_free_extent().
3533  *
3534  * Return -ENOENT to inform caller that we need fallback to unclustered mode.
3535  * Return -EAGAIN to inform caller that we need to re-search this block group
3536  * Return >0 to inform caller that we find nothing
3537  * Return 0 means we have found a location and set ffe_ctl->found_offset.
3538  */
3539 static int find_free_extent_clustered(struct btrfs_block_group *bg,
3540                                       struct find_free_extent_ctl *ffe_ctl,
3541                                       struct btrfs_block_group **cluster_bg_ret)
3542 {
3543         struct btrfs_block_group *cluster_bg;
3544         struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3545         u64 aligned_cluster;
3546         u64 offset;
3547         int ret;
3548
3549         cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc);
3550         if (!cluster_bg)
3551                 goto refill_cluster;
3552         if (cluster_bg != bg && (cluster_bg->ro ||
3553             !block_group_bits(cluster_bg, ffe_ctl->flags)))
3554                 goto release_cluster;
3555
3556         offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
3557                         ffe_ctl->num_bytes, cluster_bg->start,
3558                         &ffe_ctl->max_extent_size);
3559         if (offset) {
3560                 /* We have a block, we're done */
3561                 spin_unlock(&last_ptr->refill_lock);
3562                 trace_btrfs_reserve_extent_cluster(cluster_bg,
3563                                 ffe_ctl->search_start, ffe_ctl->num_bytes);
3564                 *cluster_bg_ret = cluster_bg;
3565                 ffe_ctl->found_offset = offset;
3566                 return 0;
3567         }
3568         WARN_ON(last_ptr->block_group != cluster_bg);
3569
3570 release_cluster:
3571         /*
3572          * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
3573          * lets just skip it and let the allocator find whatever block it can
3574          * find. If we reach this point, we will have tried the cluster
3575          * allocator plenty of times and not have found anything, so we are
3576          * likely way too fragmented for the clustering stuff to find anything.
3577          *
3578          * However, if the cluster is taken from the current block group,
3579          * release the cluster first, so that we stand a better chance of
3580          * succeeding in the unclustered allocation.
3581          */
3582         if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
3583                 spin_unlock(&last_ptr->refill_lock);
3584                 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3585                 return -ENOENT;
3586         }
3587
3588         /* This cluster didn't work out, free it and start over */
3589         btrfs_return_cluster_to_free_space(NULL, last_ptr);
3590
3591         if (cluster_bg != bg)
3592                 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
3593
3594 refill_cluster:
3595         if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
3596                 spin_unlock(&last_ptr->refill_lock);
3597                 return -ENOENT;
3598         }
3599
3600         aligned_cluster = max_t(u64,
3601                         ffe_ctl->empty_cluster + ffe_ctl->empty_size,
3602                         bg->full_stripe_len);
3603         ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
3604                         ffe_ctl->num_bytes, aligned_cluster);
3605         if (ret == 0) {
3606                 /* Now pull our allocation out of this cluster */
3607                 offset = btrfs_alloc_from_cluster(bg, last_ptr,
3608                                 ffe_ctl->num_bytes, ffe_ctl->search_start,
3609                                 &ffe_ctl->max_extent_size);
3610                 if (offset) {
3611                         /* We found one, proceed */
3612                         spin_unlock(&last_ptr->refill_lock);
3613                         trace_btrfs_reserve_extent_cluster(bg,
3614                                         ffe_ctl->search_start,
3615                                         ffe_ctl->num_bytes);
3616                         ffe_ctl->found_offset = offset;
3617                         return 0;
3618                 }
3619         } else if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
3620                    !ffe_ctl->retry_clustered) {
3621                 spin_unlock(&last_ptr->refill_lock);
3622
3623                 ffe_ctl->retry_clustered = true;
3624                 btrfs_wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
3625                                 ffe_ctl->empty_cluster + ffe_ctl->empty_size);
3626                 return -EAGAIN;
3627         }
3628         /*
3629          * At this point we either didn't find a cluster or we weren't able to
3630          * allocate a block from our cluster.  Free the cluster we've been
3631          * trying to use, and go to the next block group.
3632          */
3633         btrfs_return_cluster_to_free_space(NULL, last_ptr);
3634         spin_unlock(&last_ptr->refill_lock);
3635         return 1;
3636 }
3637
3638 /*
3639  * Return >0 to inform caller that we find nothing
3640  * Return 0 when we found an free extent and set ffe_ctrl->found_offset
3641  * Return -EAGAIN to inform caller that we need to re-search this block group
3642  */
3643 static int find_free_extent_unclustered(struct btrfs_block_group *bg,
3644                                         struct find_free_extent_ctl *ffe_ctl)
3645 {
3646         struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3647         u64 offset;
3648
3649         /*
3650          * We are doing an unclustered allocation, set the fragmented flag so
3651          * we don't bother trying to setup a cluster again until we get more
3652          * space.
3653          */
3654         if (unlikely(last_ptr)) {
3655                 spin_lock(&last_ptr->lock);
3656                 last_ptr->fragmented = 1;
3657                 spin_unlock(&last_ptr->lock);
3658         }
3659         if (ffe_ctl->cached) {
3660                 struct btrfs_free_space_ctl *free_space_ctl;
3661
3662                 free_space_ctl = bg->free_space_ctl;
3663                 spin_lock(&free_space_ctl->tree_lock);
3664                 if (free_space_ctl->free_space <
3665                     ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
3666                     ffe_ctl->empty_size) {
3667                         ffe_ctl->total_free_space = max_t(u64,
3668                                         ffe_ctl->total_free_space,
3669                                         free_space_ctl->free_space);
3670                         spin_unlock(&free_space_ctl->tree_lock);
3671                         return 1;
3672                 }
3673                 spin_unlock(&free_space_ctl->tree_lock);
3674         }
3675
3676         offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
3677                         ffe_ctl->num_bytes, ffe_ctl->empty_size,
3678                         &ffe_ctl->max_extent_size);
3679
3680         /*
3681          * If we didn't find a chunk, and we haven't failed on this block group
3682          * before, and this block group is in the middle of caching and we are
3683          * ok with waiting, then go ahead and wait for progress to be made, and
3684          * set @retry_unclustered to true.
3685          *
3686          * If @retry_unclustered is true then we've already waited on this
3687          * block group once and should move on to the next block group.
3688          */
3689         if (!offset && !ffe_ctl->retry_unclustered && !ffe_ctl->cached &&
3690             ffe_ctl->loop > LOOP_CACHING_NOWAIT) {
3691                 btrfs_wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
3692                                                       ffe_ctl->empty_size);
3693                 ffe_ctl->retry_unclustered = true;
3694                 return -EAGAIN;
3695         } else if (!offset) {
3696                 return 1;
3697         }
3698         ffe_ctl->found_offset = offset;
3699         return 0;
3700 }
3701
3702 static int do_allocation_clustered(struct btrfs_block_group *block_group,
3703                                    struct find_free_extent_ctl *ffe_ctl,
3704                                    struct btrfs_block_group **bg_ret)
3705 {
3706         int ret;
3707
3708         /* We want to try and use the cluster allocator, so lets look there */
3709         if (ffe_ctl->last_ptr && ffe_ctl->use_cluster) {
3710                 ret = find_free_extent_clustered(block_group, ffe_ctl, bg_ret);
3711                 if (ret >= 0 || ret == -EAGAIN)
3712                         return ret;
3713                 /* ret == -ENOENT case falls through */
3714         }
3715
3716         return find_free_extent_unclustered(block_group, ffe_ctl);
3717 }
3718
3719 /*
3720  * Tree-log block group locking
3721  * ============================
3722  *
3723  * fs_info::treelog_bg_lock protects the fs_info::treelog_bg which
3724  * indicates the starting address of a block group, which is reserved only
3725  * for tree-log metadata.
3726  *
3727  * Lock nesting
3728  * ============
3729  *
3730  * space_info::lock
3731  *   block_group::lock
3732  *     fs_info::treelog_bg_lock
3733  */
3734
3735 /*
3736  * Simple allocator for sequential-only block group. It only allows sequential
3737  * allocation. No need to play with trees. This function also reserves the
3738  * bytes as in btrfs_add_reserved_bytes.
3739  */
3740 static int do_allocation_zoned(struct btrfs_block_group *block_group,
3741                                struct find_free_extent_ctl *ffe_ctl,
3742                                struct btrfs_block_group **bg_ret)
3743 {
3744         struct btrfs_fs_info *fs_info = block_group->fs_info;
3745         struct btrfs_space_info *space_info = block_group->space_info;
3746         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
3747         u64 start = block_group->start;
3748         u64 num_bytes = ffe_ctl->num_bytes;
3749         u64 avail;
3750         u64 bytenr = block_group->start;
3751         u64 log_bytenr;
3752         u64 data_reloc_bytenr;
3753         int ret = 0;
3754         bool skip = false;
3755
3756         ASSERT(btrfs_is_zoned(block_group->fs_info));
3757
3758         /*
3759          * Do not allow non-tree-log blocks in the dedicated tree-log block
3760          * group, and vice versa.
3761          */
3762         spin_lock(&fs_info->treelog_bg_lock);
3763         log_bytenr = fs_info->treelog_bg;
3764         if (log_bytenr && ((ffe_ctl->for_treelog && bytenr != log_bytenr) ||
3765                            (!ffe_ctl->for_treelog && bytenr == log_bytenr)))
3766                 skip = true;
3767         spin_unlock(&fs_info->treelog_bg_lock);
3768         if (skip)
3769                 return 1;
3770
3771         /*
3772          * Do not allow non-relocation blocks in the dedicated relocation block
3773          * group, and vice versa.
3774          */
3775         spin_lock(&fs_info->relocation_bg_lock);
3776         data_reloc_bytenr = fs_info->data_reloc_bg;
3777         if (data_reloc_bytenr &&
3778             ((ffe_ctl->for_data_reloc && bytenr != data_reloc_bytenr) ||
3779              (!ffe_ctl->for_data_reloc && bytenr == data_reloc_bytenr)))
3780                 skip = true;
3781         spin_unlock(&fs_info->relocation_bg_lock);
3782         if (skip)
3783                 return 1;
3784
3785         /* Check RO and no space case before trying to activate it */
3786         spin_lock(&block_group->lock);
3787         if (block_group->ro || btrfs_zoned_bg_is_full(block_group)) {
3788                 ret = 1;
3789                 /*
3790                  * May need to clear fs_info->{treelog,data_reloc}_bg.
3791                  * Return the error after taking the locks.
3792                  */
3793         }
3794         spin_unlock(&block_group->lock);
3795
3796         if (!ret && !btrfs_zone_activate(block_group)) {
3797                 ret = 1;
3798                 /*
3799                  * May need to clear fs_info->{treelog,data_reloc}_bg.
3800                  * Return the error after taking the locks.
3801                  */
3802         }
3803
3804         spin_lock(&space_info->lock);
3805         spin_lock(&block_group->lock);
3806         spin_lock(&fs_info->treelog_bg_lock);
3807         spin_lock(&fs_info->relocation_bg_lock);
3808
3809         if (ret)
3810                 goto out;
3811
3812         ASSERT(!ffe_ctl->for_treelog ||
3813                block_group->start == fs_info->treelog_bg ||
3814                fs_info->treelog_bg == 0);
3815         ASSERT(!ffe_ctl->for_data_reloc ||
3816                block_group->start == fs_info->data_reloc_bg ||
3817                fs_info->data_reloc_bg == 0);
3818
3819         if (block_group->ro || block_group->zoned_data_reloc_ongoing) {
3820                 ret = 1;
3821                 goto out;
3822         }
3823
3824         /*
3825          * Do not allow currently using block group to be tree-log dedicated
3826          * block group.
3827          */
3828         if (ffe_ctl->for_treelog && !fs_info->treelog_bg &&
3829             (block_group->used || block_group->reserved)) {
3830                 ret = 1;
3831                 goto out;
3832         }
3833
3834         /*
3835          * Do not allow currently used block group to be the data relocation
3836          * dedicated block group.
3837          */
3838         if (ffe_ctl->for_data_reloc && !fs_info->data_reloc_bg &&
3839             (block_group->used || block_group->reserved)) {
3840                 ret = 1;
3841                 goto out;
3842         }
3843
3844         WARN_ON_ONCE(block_group->alloc_offset > block_group->zone_capacity);
3845         avail = block_group->zone_capacity - block_group->alloc_offset;
3846         if (avail < num_bytes) {
3847                 if (ffe_ctl->max_extent_size < avail) {
3848                         /*
3849                          * With sequential allocator, free space is always
3850                          * contiguous
3851                          */
3852                         ffe_ctl->max_extent_size = avail;
3853                         ffe_ctl->total_free_space = avail;
3854                 }
3855                 ret = 1;
3856                 goto out;
3857         }
3858
3859         if (ffe_ctl->for_treelog && !fs_info->treelog_bg)
3860                 fs_info->treelog_bg = block_group->start;
3861
3862         if (ffe_ctl->for_data_reloc && !fs_info->data_reloc_bg)
3863                 fs_info->data_reloc_bg = block_group->start;
3864
3865         ffe_ctl->found_offset = start + block_group->alloc_offset;
3866         block_group->alloc_offset += num_bytes;
3867         spin_lock(&ctl->tree_lock);
3868         ctl->free_space -= num_bytes;
3869         spin_unlock(&ctl->tree_lock);
3870
3871         /*
3872          * We do not check if found_offset is aligned to stripesize. The
3873          * address is anyway rewritten when using zone append writing.
3874          */
3875
3876         ffe_ctl->search_start = ffe_ctl->found_offset;
3877
3878 out:
3879         if (ret && ffe_ctl->for_treelog)
3880                 fs_info->treelog_bg = 0;
3881         if (ret && ffe_ctl->for_data_reloc &&
3882             fs_info->data_reloc_bg == block_group->start) {
3883                 /*
3884                  * Do not allow further allocations from this block group.
3885                  * Compared to increasing the ->ro, setting the
3886                  * ->zoned_data_reloc_ongoing flag still allows nocow
3887                  *  writers to come in. See btrfs_inc_nocow_writers().
3888                  *
3889                  * We need to disable an allocation to avoid an allocation of
3890                  * regular (non-relocation data) extent. With mix of relocation
3891                  * extents and regular extents, we can dispatch WRITE commands
3892                  * (for relocation extents) and ZONE APPEND commands (for
3893                  * regular extents) at the same time to the same zone, which
3894                  * easily break the write pointer.
3895                  */
3896                 block_group->zoned_data_reloc_ongoing = 1;
3897                 fs_info->data_reloc_bg = 0;
3898         }
3899         spin_unlock(&fs_info->relocation_bg_lock);
3900         spin_unlock(&fs_info->treelog_bg_lock);
3901         spin_unlock(&block_group->lock);
3902         spin_unlock(&space_info->lock);
3903         return ret;
3904 }
3905
3906 static int do_allocation(struct btrfs_block_group *block_group,
3907                          struct find_free_extent_ctl *ffe_ctl,
3908                          struct btrfs_block_group **bg_ret)
3909 {
3910         switch (ffe_ctl->policy) {
3911         case BTRFS_EXTENT_ALLOC_CLUSTERED:
3912                 return do_allocation_clustered(block_group, ffe_ctl, bg_ret);
3913         case BTRFS_EXTENT_ALLOC_ZONED:
3914                 return do_allocation_zoned(block_group, ffe_ctl, bg_ret);
3915         default:
3916                 BUG();
3917         }
3918 }
3919
3920 static void release_block_group(struct btrfs_block_group *block_group,
3921                                 struct find_free_extent_ctl *ffe_ctl,
3922                                 int delalloc)
3923 {
3924         switch (ffe_ctl->policy) {
3925         case BTRFS_EXTENT_ALLOC_CLUSTERED:
3926                 ffe_ctl->retry_clustered = false;
3927                 ffe_ctl->retry_unclustered = false;
3928                 break;
3929         case BTRFS_EXTENT_ALLOC_ZONED:
3930                 /* Nothing to do */
3931                 break;
3932         default:
3933                 BUG();
3934         }
3935
3936         BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
3937                ffe_ctl->index);
3938         btrfs_release_block_group(block_group, delalloc);
3939 }
3940
3941 static void found_extent_clustered(struct find_free_extent_ctl *ffe_ctl,
3942                                    struct btrfs_key *ins)
3943 {
3944         struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
3945
3946         if (!ffe_ctl->use_cluster && last_ptr) {
3947                 spin_lock(&last_ptr->lock);
3948                 last_ptr->window_start = ins->objectid;
3949                 spin_unlock(&last_ptr->lock);
3950         }
3951 }
3952
3953 static void found_extent(struct find_free_extent_ctl *ffe_ctl,
3954                          struct btrfs_key *ins)
3955 {
3956         switch (ffe_ctl->policy) {
3957         case BTRFS_EXTENT_ALLOC_CLUSTERED:
3958                 found_extent_clustered(ffe_ctl, ins);
3959                 break;
3960         case BTRFS_EXTENT_ALLOC_ZONED:
3961                 /* Nothing to do */
3962                 break;
3963         default:
3964                 BUG();
3965         }
3966 }
3967
3968 static int can_allocate_chunk_zoned(struct btrfs_fs_info *fs_info,
3969                                     struct find_free_extent_ctl *ffe_ctl)
3970 {
3971         /* If we can activate new zone, just allocate a chunk and use it */
3972         if (btrfs_can_activate_zone(fs_info->fs_devices, ffe_ctl->flags))
3973                 return 0;
3974
3975         /*
3976          * We already reached the max active zones. Try to finish one block
3977          * group to make a room for a new block group. This is only possible
3978          * for a data block group because btrfs_zone_finish() may need to wait
3979          * for a running transaction which can cause a deadlock for metadata
3980          * allocation.
3981          */
3982         if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA) {
3983                 int ret = btrfs_zone_finish_one_bg(fs_info);
3984
3985                 if (ret == 1)
3986                         return 0;
3987                 else if (ret < 0)
3988                         return ret;
3989         }
3990
3991         /*
3992          * If we have enough free space left in an already active block group
3993          * and we can't activate any other zone now, do not allow allocating a
3994          * new chunk and let find_free_extent() retry with a smaller size.
3995          */
3996         if (ffe_ctl->max_extent_size >= ffe_ctl->min_alloc_size)
3997                 return -ENOSPC;
3998
3999         /*
4000          * Even min_alloc_size is not left in any block groups. Since we cannot
4001          * activate a new block group, allocating it may not help. Let's tell a
4002          * caller to try again and hope it progress something by writing some
4003          * parts of the region. That is only possible for data block groups,
4004          * where a part of the region can be written.
4005          */
4006         if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA)
4007                 return -EAGAIN;
4008
4009         /*
4010          * We cannot activate a new block group and no enough space left in any
4011          * block groups. So, allocating a new block group may not help. But,
4012          * there is nothing to do anyway, so let's go with it.
4013          */
4014         return 0;
4015 }
4016
4017 static int can_allocate_chunk(struct btrfs_fs_info *fs_info,
4018                               struct find_free_extent_ctl *ffe_ctl)
4019 {
4020         switch (ffe_ctl->policy) {
4021         case BTRFS_EXTENT_ALLOC_CLUSTERED:
4022                 return 0;
4023         case BTRFS_EXTENT_ALLOC_ZONED:
4024                 return can_allocate_chunk_zoned(fs_info, ffe_ctl);
4025         default:
4026                 BUG();
4027         }
4028 }
4029
4030 static int chunk_allocation_failed(struct find_free_extent_ctl *ffe_ctl)
4031 {
4032         switch (ffe_ctl->policy) {
4033         case BTRFS_EXTENT_ALLOC_CLUSTERED:
4034                 /*
4035                  * If we can't allocate a new chunk we've already looped through
4036                  * at least once, move on to the NO_EMPTY_SIZE case.
4037                  */
4038                 ffe_ctl->loop = LOOP_NO_EMPTY_SIZE;
4039                 return 0;
4040         case BTRFS_EXTENT_ALLOC_ZONED:
4041                 /* Give up here */
4042                 return -ENOSPC;
4043         default:
4044                 BUG();
4045         }
4046 }
4047
4048 /*
4049  * Return >0 means caller needs to re-search for free extent
4050  * Return 0 means we have the needed free extent.
4051  * Return <0 means we failed to locate any free extent.
4052  */
4053 static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
4054                                         struct btrfs_key *ins,
4055                                         struct find_free_extent_ctl *ffe_ctl,
4056                                         bool full_search)
4057 {
4058         struct btrfs_root *root = fs_info->chunk_root;
4059         int ret;
4060
4061         if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
4062             ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
4063                 ffe_ctl->orig_have_caching_bg = true;
4064
4065         if (ins->objectid) {
4066                 found_extent(ffe_ctl, ins);
4067                 return 0;
4068         }
4069
4070         if (ffe_ctl->loop >= LOOP_CACHING_WAIT && ffe_ctl->have_caching_bg)
4071                 return 1;
4072
4073         ffe_ctl->index++;
4074         if (ffe_ctl->index < BTRFS_NR_RAID_TYPES)
4075                 return 1;
4076
4077         /*
4078          * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
4079          *                      caching kthreads as we move along
4080          * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
4081          * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
4082          * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
4083          *                     again
4084          */
4085         if (ffe_ctl->loop < LOOP_NO_EMPTY_SIZE) {
4086                 ffe_ctl->index = 0;
4087                 if (ffe_ctl->loop == LOOP_CACHING_NOWAIT) {
4088                         /*
4089                          * We want to skip the LOOP_CACHING_WAIT step if we
4090                          * don't have any uncached bgs and we've already done a
4091                          * full search through.
4092                          */
4093                         if (ffe_ctl->orig_have_caching_bg || !full_search)
4094                                 ffe_ctl->loop = LOOP_CACHING_WAIT;
4095                         else
4096                                 ffe_ctl->loop = LOOP_ALLOC_CHUNK;
4097                 } else {
4098                         ffe_ctl->loop++;
4099                 }
4100
4101                 if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
4102                         struct btrfs_trans_handle *trans;
4103                         int exist = 0;
4104
4105                         /*Check if allocation policy allows to create a new chunk */
4106                         ret = can_allocate_chunk(fs_info, ffe_ctl);
4107                         if (ret)
4108                                 return ret;
4109
4110                         trans = current->journal_info;
4111                         if (trans)
4112                                 exist = 1;
4113                         else
4114                                 trans = btrfs_join_transaction(root);
4115
4116                         if (IS_ERR(trans)) {
4117                                 ret = PTR_ERR(trans);
4118                                 return ret;
4119                         }
4120
4121                         ret = btrfs_chunk_alloc(trans, ffe_ctl->flags,
4122                                                 CHUNK_ALLOC_FORCE_FOR_EXTENT);
4123
4124                         /* Do not bail out on ENOSPC since we can do more. */
4125                         if (ret == -ENOSPC)
4126                                 ret = chunk_allocation_failed(ffe_ctl);
4127                         else if (ret < 0)
4128                                 btrfs_abort_transaction(trans, ret);
4129                         else
4130                                 ret = 0;
4131                         if (!exist)
4132                                 btrfs_end_transaction(trans);
4133                         if (ret)
4134                                 return ret;
4135                 }
4136
4137                 if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
4138                         if (ffe_ctl->policy != BTRFS_EXTENT_ALLOC_CLUSTERED)
4139                                 return -ENOSPC;
4140
4141                         /*
4142                          * Don't loop again if we already have no empty_size and
4143                          * no empty_cluster.
4144                          */
4145                         if (ffe_ctl->empty_size == 0 &&
4146                             ffe_ctl->empty_cluster == 0)
4147                                 return -ENOSPC;
4148                         ffe_ctl->empty_size = 0;
4149                         ffe_ctl->empty_cluster = 0;
4150                 }
4151                 return 1;
4152         }
4153         return -ENOSPC;
4154 }
4155
4156 static int prepare_allocation_clustered(struct btrfs_fs_info *fs_info,
4157                                         struct find_free_extent_ctl *ffe_ctl,
4158                                         struct btrfs_space_info *space_info,
4159                                         struct btrfs_key *ins)
4160 {
4161         /*
4162          * If our free space is heavily fragmented we may not be able to make
4163          * big contiguous allocations, so instead of doing the expensive search
4164          * for free space, simply return ENOSPC with our max_extent_size so we
4165          * can go ahead and search for a more manageable chunk.
4166          *
4167          * If our max_extent_size is large enough for our allocation simply
4168          * disable clustering since we will likely not be able to find enough
4169          * space to create a cluster and induce latency trying.
4170          */
4171         if (space_info->max_extent_size) {
4172                 spin_lock(&space_info->lock);
4173                 if (space_info->max_extent_size &&
4174                     ffe_ctl->num_bytes > space_info->max_extent_size) {
4175                         ins->offset = space_info->max_extent_size;
4176                         spin_unlock(&space_info->lock);
4177                         return -ENOSPC;
4178                 } else if (space_info->max_extent_size) {
4179                         ffe_ctl->use_cluster = false;
4180                 }
4181                 spin_unlock(&space_info->lock);
4182         }
4183
4184         ffe_ctl->last_ptr = fetch_cluster_info(fs_info, space_info,
4185                                                &ffe_ctl->empty_cluster);
4186         if (ffe_ctl->last_ptr) {
4187                 struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
4188
4189                 spin_lock(&last_ptr->lock);
4190                 if (last_ptr->block_group)
4191                         ffe_ctl->hint_byte = last_ptr->window_start;
4192                 if (last_ptr->fragmented) {
4193                         /*
4194                          * We still set window_start so we can keep track of the
4195                          * last place we found an allocation to try and save
4196                          * some time.
4197                          */
4198                         ffe_ctl->hint_byte = last_ptr->window_start;
4199                         ffe_ctl->use_cluster = false;
4200                 }
4201                 spin_unlock(&last_ptr->lock);
4202         }
4203
4204         return 0;
4205 }
4206
4207 static int prepare_allocation(struct btrfs_fs_info *fs_info,
4208                               struct find_free_extent_ctl *ffe_ctl,
4209                               struct btrfs_space_info *space_info,
4210                               struct btrfs_key *ins)
4211 {
4212         switch (ffe_ctl->policy) {
4213         case BTRFS_EXTENT_ALLOC_CLUSTERED:
4214                 return prepare_allocation_clustered(fs_info, ffe_ctl,
4215                                                     space_info, ins);
4216         case BTRFS_EXTENT_ALLOC_ZONED:
4217                 if (ffe_ctl->for_treelog) {
4218                         spin_lock(&fs_info->treelog_bg_lock);
4219                         if (fs_info->treelog_bg)
4220                                 ffe_ctl->hint_byte = fs_info->treelog_bg;
4221                         spin_unlock(&fs_info->treelog_bg_lock);
4222                 }
4223                 if (ffe_ctl->for_data_reloc) {
4224                         spin_lock(&fs_info->relocation_bg_lock);
4225                         if (fs_info->data_reloc_bg)
4226                                 ffe_ctl->hint_byte = fs_info->data_reloc_bg;
4227                         spin_unlock(&fs_info->relocation_bg_lock);
4228                 }
4229                 return 0;
4230         default:
4231                 BUG();
4232         }
4233 }
4234
4235 /*
4236  * walks the btree of allocated extents and find a hole of a given size.
4237  * The key ins is changed to record the hole:
4238  * ins->objectid == start position
4239  * ins->flags = BTRFS_EXTENT_ITEM_KEY
4240  * ins->offset == the size of the hole.
4241  * Any available blocks before search_start are skipped.
4242  *
4243  * If there is no suitable free space, we will record the max size of
4244  * the free space extent currently.
4245  *
4246  * The overall logic and call chain:
4247  *
4248  * find_free_extent()
4249  * |- Iterate through all block groups
4250  * |  |- Get a valid block group
4251  * |  |- Try to do clustered allocation in that block group
4252  * |  |- Try to do unclustered allocation in that block group
4253  * |  |- Check if the result is valid
4254  * |  |  |- If valid, then exit
4255  * |  |- Jump to next block group
4256  * |
4257  * |- Push harder to find free extents
4258  *    |- If not found, re-iterate all block groups
4259  */
4260 static noinline int find_free_extent(struct btrfs_root *root,
4261                                      struct btrfs_key *ins,
4262                                      struct find_free_extent_ctl *ffe_ctl)
4263 {
4264         struct btrfs_fs_info *fs_info = root->fs_info;
4265         int ret = 0;
4266         int cache_block_group_error = 0;
4267         struct btrfs_block_group *block_group = NULL;
4268         struct btrfs_space_info *space_info;
4269         bool full_search = false;
4270
4271         WARN_ON(ffe_ctl->num_bytes < fs_info->sectorsize);
4272
4273         ffe_ctl->search_start = 0;
4274         /* For clustered allocation */
4275         ffe_ctl->empty_cluster = 0;
4276         ffe_ctl->last_ptr = NULL;
4277         ffe_ctl->use_cluster = true;
4278         ffe_ctl->have_caching_bg = false;
4279         ffe_ctl->orig_have_caching_bg = false;
4280         ffe_ctl->index = btrfs_bg_flags_to_raid_index(ffe_ctl->flags);
4281         ffe_ctl->loop = 0;
4282         /* For clustered allocation */
4283         ffe_ctl->retry_clustered = false;
4284         ffe_ctl->retry_unclustered = false;
4285         ffe_ctl->cached = 0;
4286         ffe_ctl->max_extent_size = 0;
4287         ffe_ctl->total_free_space = 0;
4288         ffe_ctl->found_offset = 0;
4289         ffe_ctl->policy = BTRFS_EXTENT_ALLOC_CLUSTERED;
4290
4291         if (btrfs_is_zoned(fs_info))
4292                 ffe_ctl->policy = BTRFS_EXTENT_ALLOC_ZONED;
4293
4294         ins->type = BTRFS_EXTENT_ITEM_KEY;
4295         ins->objectid = 0;
4296         ins->offset = 0;
4297
4298         trace_find_free_extent(root, ffe_ctl->num_bytes, ffe_ctl->empty_size,
4299                                ffe_ctl->flags);
4300
4301         space_info = btrfs_find_space_info(fs_info, ffe_ctl->flags);
4302         if (!space_info) {
4303                 btrfs_err(fs_info, "No space info for %llu", ffe_ctl->flags);
4304                 return -ENOSPC;
4305         }
4306
4307         ret = prepare_allocation(fs_info, ffe_ctl, space_info, ins);
4308         if (ret < 0)
4309                 return ret;
4310
4311         ffe_ctl->search_start = max(ffe_ctl->search_start,
4312                                     first_logical_byte(fs_info));
4313         ffe_ctl->search_start = max(ffe_ctl->search_start, ffe_ctl->hint_byte);
4314         if (ffe_ctl->search_start == ffe_ctl->hint_byte) {
4315                 block_group = btrfs_lookup_block_group(fs_info,
4316                                                        ffe_ctl->search_start);
4317                 /*
4318                  * we don't want to use the block group if it doesn't match our
4319                  * allocation bits, or if its not cached.
4320                  *
4321                  * However if we are re-searching with an ideal block group
4322                  * picked out then we don't care that the block group is cached.
4323                  */
4324                 if (block_group && block_group_bits(block_group, ffe_ctl->flags) &&
4325                     block_group->cached != BTRFS_CACHE_NO) {
4326                         down_read(&space_info->groups_sem);
4327                         if (list_empty(&block_group->list) ||
4328                             block_group->ro) {
4329                                 /*
4330                                  * someone is removing this block group,
4331                                  * we can't jump into the have_block_group
4332                                  * target because our list pointers are not
4333                                  * valid
4334                                  */
4335                                 btrfs_put_block_group(block_group);
4336                                 up_read(&space_info->groups_sem);
4337                         } else {
4338                                 ffe_ctl->index = btrfs_bg_flags_to_raid_index(
4339                                                         block_group->flags);
4340                                 btrfs_lock_block_group(block_group,
4341                                                        ffe_ctl->delalloc);
4342                                 goto have_block_group;
4343                         }
4344                 } else if (block_group) {
4345                         btrfs_put_block_group(block_group);
4346                 }
4347         }
4348 search:
4349         ffe_ctl->have_caching_bg = false;
4350         if (ffe_ctl->index == btrfs_bg_flags_to_raid_index(ffe_ctl->flags) ||
4351             ffe_ctl->index == 0)
4352                 full_search = true;
4353         down_read(&space_info->groups_sem);
4354         list_for_each_entry(block_group,
4355                             &space_info->block_groups[ffe_ctl->index], list) {
4356                 struct btrfs_block_group *bg_ret;
4357
4358                 /* If the block group is read-only, we can skip it entirely. */
4359                 if (unlikely(block_group->ro)) {
4360                         if (ffe_ctl->for_treelog)
4361                                 btrfs_clear_treelog_bg(block_group);
4362                         if (ffe_ctl->for_data_reloc)
4363                                 btrfs_clear_data_reloc_bg(block_group);
4364                         continue;
4365                 }
4366
4367                 btrfs_grab_block_group(block_group, ffe_ctl->delalloc);
4368                 ffe_ctl->search_start = block_group->start;
4369
4370                 /*
4371                  * this can happen if we end up cycling through all the
4372                  * raid types, but we want to make sure we only allocate
4373                  * for the proper type.
4374                  */
4375                 if (!block_group_bits(block_group, ffe_ctl->flags)) {
4376                         u64 extra = BTRFS_BLOCK_GROUP_DUP |
4377                                 BTRFS_BLOCK_GROUP_RAID1_MASK |
4378                                 BTRFS_BLOCK_GROUP_RAID56_MASK |
4379                                 BTRFS_BLOCK_GROUP_RAID10;
4380
4381                         /*
4382                          * if they asked for extra copies and this block group
4383                          * doesn't provide them, bail.  This does allow us to
4384                          * fill raid0 from raid1.
4385                          */
4386                         if ((ffe_ctl->flags & extra) && !(block_group->flags & extra))
4387                                 goto loop;
4388
4389                         /*
4390                          * This block group has different flags than we want.
4391                          * It's possible that we have MIXED_GROUP flag but no
4392                          * block group is mixed.  Just skip such block group.
4393                          */
4394                         btrfs_release_block_group(block_group, ffe_ctl->delalloc);
4395                         continue;
4396                 }
4397
4398 have_block_group:
4399                 ffe_ctl->cached = btrfs_block_group_done(block_group);
4400                 if (unlikely(!ffe_ctl->cached)) {
4401                         ffe_ctl->have_caching_bg = true;
4402                         ret = btrfs_cache_block_group(block_group, 0);
4403
4404                         /*
4405                          * If we get ENOMEM here or something else we want to
4406                          * try other block groups, because it may not be fatal.
4407                          * However if we can't find anything else we need to
4408                          * save our return here so that we return the actual
4409                          * error that caused problems, not ENOSPC.
4410                          */
4411                         if (ret < 0) {
4412                                 if (!cache_block_group_error)
4413                                         cache_block_group_error = ret;
4414                                 ret = 0;
4415                                 goto loop;
4416                         }
4417                         ret = 0;
4418                 }
4419
4420                 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
4421                         goto loop;
4422
4423                 bg_ret = NULL;
4424                 ret = do_allocation(block_group, ffe_ctl, &bg_ret);
4425                 if (ret == 0) {
4426                         if (bg_ret && bg_ret != block_group) {
4427                                 btrfs_release_block_group(block_group,
4428                                                           ffe_ctl->delalloc);
4429                                 block_group = bg_ret;
4430                         }
4431                 } else if (ret == -EAGAIN) {
4432                         goto have_block_group;
4433                 } else if (ret > 0) {
4434                         goto loop;
4435                 }
4436
4437                 /* Checks */
4438                 ffe_ctl->search_start = round_up(ffe_ctl->found_offset,
4439                                                  fs_info->stripesize);
4440
4441                 /* move on to the next group */
4442                 if (ffe_ctl->search_start + ffe_ctl->num_bytes >
4443                     block_group->start + block_group->length) {
4444                         btrfs_add_free_space_unused(block_group,
4445                                             ffe_ctl->found_offset,
4446                                             ffe_ctl->num_bytes);
4447                         goto loop;
4448                 }
4449
4450                 if (ffe_ctl->found_offset < ffe_ctl->search_start)
4451                         btrfs_add_free_space_unused(block_group,
4452                                         ffe_ctl->found_offset,
4453                                         ffe_ctl->search_start - ffe_ctl->found_offset);
4454
4455                 ret = btrfs_add_reserved_bytes(block_group, ffe_ctl->ram_bytes,
4456                                                ffe_ctl->num_bytes,
4457                                                ffe_ctl->delalloc);
4458                 if (ret == -EAGAIN) {
4459                         btrfs_add_free_space_unused(block_group,
4460                                         ffe_ctl->found_offset,
4461                                         ffe_ctl->num_bytes);
4462                         goto loop;
4463                 }
4464                 btrfs_inc_block_group_reservations(block_group);
4465
4466                 /* we are all good, lets return */
4467                 ins->objectid = ffe_ctl->search_start;
4468                 ins->offset = ffe_ctl->num_bytes;
4469
4470                 trace_btrfs_reserve_extent(block_group, ffe_ctl->search_start,
4471                                            ffe_ctl->num_bytes);
4472                 btrfs_release_block_group(block_group, ffe_ctl->delalloc);
4473                 break;
4474 loop:
4475                 release_block_group(block_group, ffe_ctl, ffe_ctl->delalloc);
4476                 cond_resched();
4477         }
4478         up_read(&space_info->groups_sem);
4479
4480         ret = find_free_extent_update_loop(fs_info, ins, ffe_ctl, full_search);
4481         if (ret > 0)
4482                 goto search;
4483
4484         if (ret == -ENOSPC && !cache_block_group_error) {
4485                 /*
4486                  * Use ffe_ctl->total_free_space as fallback if we can't find
4487                  * any contiguous hole.
4488                  */
4489                 if (!ffe_ctl->max_extent_size)
4490                         ffe_ctl->max_extent_size = ffe_ctl->total_free_space;
4491                 spin_lock(&space_info->lock);
4492                 space_info->max_extent_size = ffe_ctl->max_extent_size;
4493                 spin_unlock(&space_info->lock);
4494                 ins->offset = ffe_ctl->max_extent_size;
4495         } else if (ret == -ENOSPC) {
4496                 ret = cache_block_group_error;
4497         }
4498         return ret;
4499 }
4500
4501 /*
4502  * btrfs_reserve_extent - entry point to the extent allocator. Tries to find a
4503  *                        hole that is at least as big as @num_bytes.
4504  *
4505  * @root           -    The root that will contain this extent
4506  *
4507  * @ram_bytes      -    The amount of space in ram that @num_bytes take. This
4508  *                      is used for accounting purposes. This value differs
4509  *                      from @num_bytes only in the case of compressed extents.
4510  *
4511  * @num_bytes      -    Number of bytes to allocate on-disk.
4512  *
4513  * @min_alloc_size -    Indicates the minimum amount of space that the
4514  *                      allocator should try to satisfy. In some cases
4515  *                      @num_bytes may be larger than what is required and if
4516  *                      the filesystem is fragmented then allocation fails.
4517  *                      However, the presence of @min_alloc_size gives a
4518  *                      chance to try and satisfy the smaller allocation.
4519  *
4520  * @empty_size     -    A hint that you plan on doing more COW. This is the
4521  *                      size in bytes the allocator should try to find free
4522  *                      next to the block it returns.  This is just a hint and
4523  *                      may be ignored by the allocator.
4524  *
4525  * @hint_byte      -    Hint to the allocator to start searching above the byte
4526  *                      address passed. It might be ignored.
4527  *
4528  * @ins            -    This key is modified to record the found hole. It will
4529  *                      have the following values:
4530  *                      ins->objectid == start position
4531  *                      ins->flags = BTRFS_EXTENT_ITEM_KEY
4532  *                      ins->offset == the size of the hole.
4533  *
4534  * @is_data        -    Boolean flag indicating whether an extent is
4535  *                      allocated for data (true) or metadata (false)
4536  *
4537  * @delalloc       -    Boolean flag indicating whether this allocation is for
4538  *                      delalloc or not. If 'true' data_rwsem of block groups
4539  *                      is going to be acquired.
4540  *
4541  *
4542  * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
4543  * case -ENOSPC is returned then @ins->offset will contain the size of the
4544  * largest available hole the allocator managed to find.
4545  */
4546 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
4547                          u64 num_bytes, u64 min_alloc_size,
4548                          u64 empty_size, u64 hint_byte,
4549                          struct btrfs_key *ins, int is_data, int delalloc)
4550 {
4551         struct btrfs_fs_info *fs_info = root->fs_info;
4552         struct find_free_extent_ctl ffe_ctl = {};
4553         bool final_tried = num_bytes == min_alloc_size;
4554         u64 flags;
4555         int ret;
4556         bool for_treelog = (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
4557         bool for_data_reloc = (btrfs_is_data_reloc_root(root) && is_data);
4558
4559         flags = get_alloc_profile_by_root(root, is_data);
4560 again:
4561         WARN_ON(num_bytes < fs_info->sectorsize);
4562
4563         ffe_ctl.ram_bytes = ram_bytes;
4564         ffe_ctl.num_bytes = num_bytes;
4565         ffe_ctl.min_alloc_size = min_alloc_size;
4566         ffe_ctl.empty_size = empty_size;
4567         ffe_ctl.flags = flags;
4568         ffe_ctl.delalloc = delalloc;
4569         ffe_ctl.hint_byte = hint_byte;
4570         ffe_ctl.for_treelog = for_treelog;
4571         ffe_ctl.for_data_reloc = for_data_reloc;
4572
4573         ret = find_free_extent(root, ins, &ffe_ctl);
4574         if (!ret && !is_data) {
4575                 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
4576         } else if (ret == -ENOSPC) {
4577                 if (!final_tried && ins->offset) {
4578                         num_bytes = min(num_bytes >> 1, ins->offset);
4579                         num_bytes = round_down(num_bytes,
4580                                                fs_info->sectorsize);
4581                         num_bytes = max(num_bytes, min_alloc_size);
4582                         ram_bytes = num_bytes;
4583                         if (num_bytes == min_alloc_size)
4584                                 final_tried = true;
4585                         goto again;
4586                 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4587                         struct btrfs_space_info *sinfo;
4588
4589                         sinfo = btrfs_find_space_info(fs_info, flags);
4590                         btrfs_err(fs_info,
4591         "allocation failed flags %llu, wanted %llu tree-log %d, relocation: %d",
4592                                   flags, num_bytes, for_treelog, for_data_reloc);
4593                         if (sinfo)
4594                                 btrfs_dump_space_info(fs_info, sinfo,
4595                                                       num_bytes, 1);
4596                 }
4597         }
4598
4599         return ret;
4600 }
4601
4602 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
4603                                u64 start, u64 len, int delalloc)
4604 {
4605         struct btrfs_block_group *cache;
4606
4607         cache = btrfs_lookup_block_group(fs_info, start);
4608         if (!cache) {
4609                 btrfs_err(fs_info, "Unable to find block group for %llu",
4610                           start);
4611                 return -ENOSPC;
4612         }
4613
4614         btrfs_add_free_space(cache, start, len);
4615         btrfs_free_reserved_bytes(cache, len, delalloc);
4616         trace_btrfs_reserved_extent_free(fs_info, start, len);
4617
4618         btrfs_put_block_group(cache);
4619         return 0;
4620 }
4621
4622 int btrfs_pin_reserved_extent(struct btrfs_trans_handle *trans, u64 start,
4623                               u64 len)
4624 {
4625         struct btrfs_block_group *cache;
4626         int ret = 0;
4627
4628         cache = btrfs_lookup_block_group(trans->fs_info, start);
4629         if (!cache) {
4630                 btrfs_err(trans->fs_info, "unable to find block group for %llu",
4631                           start);
4632                 return -ENOSPC;
4633         }
4634
4635         ret = pin_down_extent(trans, cache, start, len, 1);
4636         btrfs_put_block_group(cache);
4637         return ret;
4638 }
4639
4640 static int alloc_reserved_extent(struct btrfs_trans_handle *trans, u64 bytenr,
4641                                  u64 num_bytes)
4642 {
4643         struct btrfs_fs_info *fs_info = trans->fs_info;
4644         int ret;
4645
4646         ret = remove_from_free_space_tree(trans, bytenr, num_bytes);
4647         if (ret)
4648                 return ret;
4649
4650         ret = btrfs_update_block_group(trans, bytenr, num_bytes, true);
4651         if (ret) {
4652                 ASSERT(!ret);
4653                 btrfs_err(fs_info, "update block group failed for %llu %llu",
4654                           bytenr, num_bytes);
4655                 return ret;
4656         }
4657
4658         trace_btrfs_reserved_extent_alloc(fs_info, bytenr, num_bytes);
4659         return 0;
4660 }
4661
4662 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4663                                       u64 parent, u64 root_objectid,
4664                                       u64 flags, u64 owner, u64 offset,
4665                                       struct btrfs_key *ins, int ref_mod)
4666 {
4667         struct btrfs_fs_info *fs_info = trans->fs_info;
4668         struct btrfs_root *extent_root;
4669         int ret;
4670         struct btrfs_extent_item *extent_item;
4671         struct btrfs_extent_inline_ref *iref;
4672         struct btrfs_path *path;
4673         struct extent_buffer *leaf;
4674         int type;
4675         u32 size;
4676
4677         if (parent > 0)
4678                 type = BTRFS_SHARED_DATA_REF_KEY;
4679         else
4680                 type = BTRFS_EXTENT_DATA_REF_KEY;
4681
4682         size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
4683
4684         path = btrfs_alloc_path();
4685         if (!path)
4686                 return -ENOMEM;
4687
4688         extent_root = btrfs_extent_root(fs_info, ins->objectid);
4689         ret = btrfs_insert_empty_item(trans, extent_root, path, ins, size);
4690         if (ret) {
4691                 btrfs_free_path(path);
4692                 return ret;
4693         }
4694
4695         leaf = path->nodes[0];
4696         extent_item = btrfs_item_ptr(leaf, path->slots[0],
4697                                      struct btrfs_extent_item);
4698         btrfs_set_extent_refs(leaf, extent_item, ref_mod);
4699         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4700         btrfs_set_extent_flags(leaf, extent_item,
4701                                flags | BTRFS_EXTENT_FLAG_DATA);
4702
4703         iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4704         btrfs_set_extent_inline_ref_type(leaf, iref, type);
4705         if (parent > 0) {
4706                 struct btrfs_shared_data_ref *ref;
4707                 ref = (struct btrfs_shared_data_ref *)(iref + 1);
4708                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
4709                 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
4710         } else {
4711                 struct btrfs_extent_data_ref *ref;
4712                 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
4713                 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
4714                 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
4715                 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
4716                 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
4717         }
4718
4719         btrfs_mark_buffer_dirty(path->nodes[0]);
4720         btrfs_free_path(path);
4721
4722         return alloc_reserved_extent(trans, ins->objectid, ins->offset);
4723 }
4724
4725 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
4726                                      struct btrfs_delayed_ref_node *node,
4727                                      struct btrfs_delayed_extent_op *extent_op)
4728 {
4729         struct btrfs_fs_info *fs_info = trans->fs_info;
4730         struct btrfs_root *extent_root;
4731         int ret;
4732         struct btrfs_extent_item *extent_item;
4733         struct btrfs_key extent_key;
4734         struct btrfs_tree_block_info *block_info;
4735         struct btrfs_extent_inline_ref *iref;
4736         struct btrfs_path *path;
4737         struct extent_buffer *leaf;
4738         struct btrfs_delayed_tree_ref *ref;
4739         u32 size = sizeof(*extent_item) + sizeof(*iref);
4740         u64 flags = extent_op->flags_to_set;
4741         bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
4742
4743         ref = btrfs_delayed_node_to_tree_ref(node);
4744
4745         extent_key.objectid = node->bytenr;
4746         if (skinny_metadata) {
4747                 extent_key.offset = ref->level;
4748                 extent_key.type = BTRFS_METADATA_ITEM_KEY;
4749         } else {
4750                 extent_key.offset = node->num_bytes;
4751                 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
4752                 size += sizeof(*block_info);
4753         }
4754
4755         path = btrfs_alloc_path();
4756         if (!path)
4757                 return -ENOMEM;
4758
4759         extent_root = btrfs_extent_root(fs_info, extent_key.objectid);
4760         ret = btrfs_insert_empty_item(trans, extent_root, path, &extent_key,
4761                                       size);
4762         if (ret) {
4763                 btrfs_free_path(path);
4764                 return ret;
4765         }
4766
4767         leaf = path->nodes[0];
4768         extent_item = btrfs_item_ptr(leaf, path->slots[0],
4769                                      struct btrfs_extent_item);
4770         btrfs_set_extent_refs(leaf, extent_item, 1);
4771         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4772         btrfs_set_extent_flags(leaf, extent_item,
4773                                flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
4774
4775         if (skinny_metadata) {
4776                 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4777         } else {
4778                 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
4779                 btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
4780                 btrfs_set_tree_block_level(leaf, block_info, ref->level);
4781                 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
4782         }
4783
4784         if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
4785                 btrfs_set_extent_inline_ref_type(leaf, iref,
4786                                                  BTRFS_SHARED_BLOCK_REF_KEY);
4787                 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->parent);
4788         } else {
4789                 btrfs_set_extent_inline_ref_type(leaf, iref,
4790                                                  BTRFS_TREE_BLOCK_REF_KEY);
4791                 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->root);
4792         }
4793
4794         btrfs_mark_buffer_dirty(leaf);
4795         btrfs_free_path(path);
4796
4797         return alloc_reserved_extent(trans, node->bytenr, fs_info->nodesize);
4798 }
4799
4800 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4801                                      struct btrfs_root *root, u64 owner,
4802                                      u64 offset, u64 ram_bytes,
4803                                      struct btrfs_key *ins)
4804 {
4805         struct btrfs_ref generic_ref = { 0 };
4806
4807         BUG_ON(root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
4808
4809         btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
4810                                ins->objectid, ins->offset, 0);
4811         btrfs_init_data_ref(&generic_ref, root->root_key.objectid, owner,
4812                             offset, 0, false);
4813         btrfs_ref_tree_mod(root->fs_info, &generic_ref);
4814
4815         return btrfs_add_delayed_data_ref(trans, &generic_ref, ram_bytes);
4816 }
4817
4818 /*
4819  * this is used by the tree logging recovery code.  It records that
4820  * an extent has been allocated and makes sure to clear the free
4821  * space cache bits as well
4822  */
4823 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
4824                                    u64 root_objectid, u64 owner, u64 offset,
4825                                    struct btrfs_key *ins)
4826 {
4827         struct btrfs_fs_info *fs_info = trans->fs_info;
4828         int ret;
4829         struct btrfs_block_group *block_group;
4830         struct btrfs_space_info *space_info;
4831
4832         /*
4833          * Mixed block groups will exclude before processing the log so we only
4834          * need to do the exclude dance if this fs isn't mixed.
4835          */
4836         if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
4837                 ret = __exclude_logged_extent(fs_info, ins->objectid,
4838                                               ins->offset);
4839                 if (ret)
4840                         return ret;
4841         }
4842
4843         block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
4844         if (!block_group)
4845                 return -EINVAL;
4846
4847         space_info = block_group->space_info;
4848         spin_lock(&space_info->lock);
4849         spin_lock(&block_group->lock);
4850         space_info->bytes_reserved += ins->offset;
4851         block_group->reserved += ins->offset;
4852         spin_unlock(&block_group->lock);
4853         spin_unlock(&space_info->lock);
4854
4855         ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
4856                                          offset, ins, 1);
4857         if (ret)
4858                 btrfs_pin_extent(trans, ins->objectid, ins->offset, 1);
4859         btrfs_put_block_group(block_group);
4860         return ret;
4861 }
4862
4863 static struct extent_buffer *
4864 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4865                       u64 bytenr, int level, u64 owner,
4866                       enum btrfs_lock_nesting nest)
4867 {
4868         struct btrfs_fs_info *fs_info = root->fs_info;
4869         struct extent_buffer *buf;
4870
4871         buf = btrfs_find_create_tree_block(fs_info, bytenr, owner, level);
4872         if (IS_ERR(buf))
4873                 return buf;
4874
4875         /*
4876          * Extra safety check in case the extent tree is corrupted and extent
4877          * allocator chooses to use a tree block which is already used and
4878          * locked.
4879          */
4880         if (buf->lock_owner == current->pid) {
4881                 btrfs_err_rl(fs_info,
4882 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
4883                         buf->start, btrfs_header_owner(buf), current->pid);
4884                 free_extent_buffer(buf);
4885                 return ERR_PTR(-EUCLEAN);
4886         }
4887
4888         /*
4889          * This needs to stay, because we could allocate a freed block from an
4890          * old tree into a new tree, so we need to make sure this new block is
4891          * set to the appropriate level and owner.
4892          */
4893         btrfs_set_buffer_lockdep_class(owner, buf, level);
4894         __btrfs_tree_lock(buf, nest);
4895         btrfs_clean_tree_block(buf);
4896         clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
4897         clear_bit(EXTENT_BUFFER_NO_CHECK, &buf->bflags);
4898
4899         set_extent_buffer_uptodate(buf);
4900
4901         memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
4902         btrfs_set_header_level(buf, level);
4903         btrfs_set_header_bytenr(buf, buf->start);
4904         btrfs_set_header_generation(buf, trans->transid);
4905         btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
4906         btrfs_set_header_owner(buf, owner);
4907         write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
4908         write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
4909         if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
4910                 buf->log_index = root->log_transid % 2;
4911                 /*
4912                  * we allow two log transactions at a time, use different
4913                  * EXTENT bit to differentiate dirty pages.
4914                  */
4915                 if (buf->log_index == 0)
4916                         set_extent_dirty(&root->dirty_log_pages, buf->start,
4917                                         buf->start + buf->len - 1, GFP_NOFS);
4918                 else
4919                         set_extent_new(&root->dirty_log_pages, buf->start,
4920                                         buf->start + buf->len - 1);
4921         } else {
4922                 buf->log_index = -1;
4923                 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
4924                          buf->start + buf->len - 1, GFP_NOFS);
4925         }
4926         /* this returns a buffer locked for blocking */
4927         return buf;
4928 }
4929
4930 /*
4931  * finds a free extent and does all the dirty work required for allocation
4932  * returns the tree buffer or an ERR_PTR on error.
4933  */
4934 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
4935                                              struct btrfs_root *root,
4936                                              u64 parent, u64 root_objectid,
4937                                              const struct btrfs_disk_key *key,
4938                                              int level, u64 hint,
4939                                              u64 empty_size,
4940                                              enum btrfs_lock_nesting nest)
4941 {
4942         struct btrfs_fs_info *fs_info = root->fs_info;
4943         struct btrfs_key ins;
4944         struct btrfs_block_rsv *block_rsv;
4945         struct extent_buffer *buf;
4946         struct btrfs_delayed_extent_op *extent_op;
4947         struct btrfs_ref generic_ref = { 0 };
4948         u64 flags = 0;
4949         int ret;
4950         u32 blocksize = fs_info->nodesize;
4951         bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
4952
4953 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4954         if (btrfs_is_testing(fs_info)) {
4955                 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
4956                                             level, root_objectid, nest);
4957                 if (!IS_ERR(buf))
4958                         root->alloc_bytenr += blocksize;
4959                 return buf;
4960         }
4961 #endif
4962
4963         block_rsv = btrfs_use_block_rsv(trans, root, blocksize);
4964         if (IS_ERR(block_rsv))
4965                 return ERR_CAST(block_rsv);
4966
4967         ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
4968                                    empty_size, hint, &ins, 0, 0);
4969         if (ret)
4970                 goto out_unuse;
4971
4972         buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
4973                                     root_objectid, nest);
4974         if (IS_ERR(buf)) {
4975                 ret = PTR_ERR(buf);
4976                 goto out_free_reserved;
4977         }
4978
4979         if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
4980                 if (parent == 0)
4981                         parent = ins.objectid;
4982                 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
4983         } else
4984                 BUG_ON(parent > 0);
4985
4986         if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
4987                 extent_op = btrfs_alloc_delayed_extent_op();
4988                 if (!extent_op) {
4989                         ret = -ENOMEM;
4990                         goto out_free_buf;
4991                 }
4992                 if (key)
4993                         memcpy(&extent_op->key, key, sizeof(extent_op->key));
4994                 else
4995                         memset(&extent_op->key, 0, sizeof(extent_op->key));
4996                 extent_op->flags_to_set = flags;
4997                 extent_op->update_key = skinny_metadata ? false : true;
4998                 extent_op->update_flags = true;
4999                 extent_op->level = level;
5000
5001                 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
5002                                        ins.objectid, ins.offset, parent);
5003                 btrfs_init_tree_ref(&generic_ref, level, root_objectid,
5004                                     root->root_key.objectid, false);
5005                 btrfs_ref_tree_mod(fs_info, &generic_ref);
5006                 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, extent_op);
5007                 if (ret)
5008                         goto out_free_delayed;
5009         }
5010         return buf;
5011
5012 out_free_delayed:
5013         btrfs_free_delayed_extent_op(extent_op);
5014 out_free_buf:
5015         btrfs_tree_unlock(buf);
5016         free_extent_buffer(buf);
5017 out_free_reserved:
5018         btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
5019 out_unuse:
5020         btrfs_unuse_block_rsv(fs_info, block_rsv, blocksize);
5021         return ERR_PTR(ret);
5022 }
5023
5024 struct walk_control {
5025         u64 refs[BTRFS_MAX_LEVEL];
5026         u64 flags[BTRFS_MAX_LEVEL];
5027         struct btrfs_key update_progress;
5028         struct btrfs_key drop_progress;
5029         int drop_level;
5030         int stage;
5031         int level;
5032         int shared_level;
5033         int update_ref;
5034         int keep_locks;
5035         int reada_slot;
5036         int reada_count;
5037         int restarted;
5038 };
5039
5040 #define DROP_REFERENCE  1
5041 #define UPDATE_BACKREF  2
5042
5043 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
5044                                      struct btrfs_root *root,
5045                                      struct walk_control *wc,
5046                                      struct btrfs_path *path)
5047 {
5048         struct btrfs_fs_info *fs_info = root->fs_info;
5049         u64 bytenr;
5050         u64 generation;
5051         u64 refs;
5052         u64 flags;
5053         u32 nritems;
5054         struct btrfs_key key;
5055         struct extent_buffer *eb;
5056         int ret;
5057         int slot;
5058         int nread = 0;
5059
5060         if (path->slots[wc->level] < wc->reada_slot) {
5061                 wc->reada_count = wc->reada_count * 2 / 3;
5062                 wc->reada_count = max(wc->reada_count, 2);
5063         } else {
5064                 wc->reada_count = wc->reada_count * 3 / 2;
5065                 wc->reada_count = min_t(int, wc->reada_count,
5066                                         BTRFS_NODEPTRS_PER_BLOCK(fs_info));
5067         }
5068
5069         eb = path->nodes[wc->level];
5070         nritems = btrfs_header_nritems(eb);
5071
5072         for (slot = path->slots[wc->level]; slot < nritems; slot++) {
5073                 if (nread >= wc->reada_count)
5074                         break;
5075
5076                 cond_resched();
5077                 bytenr = btrfs_node_blockptr(eb, slot);
5078                 generation = btrfs_node_ptr_generation(eb, slot);
5079
5080                 if (slot == path->slots[wc->level])
5081                         goto reada;
5082
5083                 if (wc->stage == UPDATE_BACKREF &&
5084                     generation <= root->root_key.offset)
5085                         continue;
5086
5087                 /* We don't lock the tree block, it's OK to be racy here */
5088                 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
5089                                                wc->level - 1, 1, &refs,
5090                                                &flags);
5091                 /* We don't care about errors in readahead. */
5092                 if (ret < 0)
5093                         continue;
5094                 BUG_ON(refs == 0);
5095
5096                 if (wc->stage == DROP_REFERENCE) {
5097                         if (refs == 1)
5098                                 goto reada;
5099
5100                         if (wc->level == 1 &&
5101                             (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5102                                 continue;
5103                         if (!wc->update_ref ||
5104                             generation <= root->root_key.offset)
5105                                 continue;
5106                         btrfs_node_key_to_cpu(eb, &key, slot);
5107                         ret = btrfs_comp_cpu_keys(&key,
5108                                                   &wc->update_progress);
5109                         if (ret < 0)
5110                                 continue;
5111                 } else {
5112                         if (wc->level == 1 &&
5113                             (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5114                                 continue;
5115                 }
5116 reada:
5117                 btrfs_readahead_node_child(eb, slot);
5118                 nread++;
5119         }
5120         wc->reada_slot = slot;
5121 }
5122
5123 /*
5124  * helper to process tree block while walking down the tree.
5125  *
5126  * when wc->stage == UPDATE_BACKREF, this function updates
5127  * back refs for pointers in the block.
5128  *
5129  * NOTE: return value 1 means we should stop walking down.
5130  */
5131 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
5132                                    struct btrfs_root *root,
5133                                    struct btrfs_path *path,
5134                                    struct walk_control *wc, int lookup_info)
5135 {
5136         struct btrfs_fs_info *fs_info = root->fs_info;
5137         int level = wc->level;
5138         struct extent_buffer *eb = path->nodes[level];
5139         u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5140         int ret;
5141
5142         if (wc->stage == UPDATE_BACKREF &&
5143             btrfs_header_owner(eb) != root->root_key.objectid)
5144                 return 1;
5145
5146         /*
5147          * when reference count of tree block is 1, it won't increase
5148          * again. once full backref flag is set, we never clear it.
5149          */
5150         if (lookup_info &&
5151             ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
5152              (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
5153                 BUG_ON(!path->locks[level]);
5154                 ret = btrfs_lookup_extent_info(trans, fs_info,
5155                                                eb->start, level, 1,
5156                                                &wc->refs[level],
5157                                                &wc->flags[level]);
5158                 BUG_ON(ret == -ENOMEM);
5159                 if (ret)
5160                         return ret;
5161                 BUG_ON(wc->refs[level] == 0);
5162         }
5163
5164         if (wc->stage == DROP_REFERENCE) {
5165                 if (wc->refs[level] > 1)
5166                         return 1;
5167
5168                 if (path->locks[level] && !wc->keep_locks) {
5169                         btrfs_tree_unlock_rw(eb, path->locks[level]);
5170                         path->locks[level] = 0;
5171                 }
5172                 return 0;
5173         }
5174
5175         /* wc->stage == UPDATE_BACKREF */
5176         if (!(wc->flags[level] & flag)) {
5177                 BUG_ON(!path->locks[level]);
5178                 ret = btrfs_inc_ref(trans, root, eb, 1);
5179                 BUG_ON(ret); /* -ENOMEM */
5180                 ret = btrfs_dec_ref(trans, root, eb, 0);
5181                 BUG_ON(ret); /* -ENOMEM */
5182                 ret = btrfs_set_disk_extent_flags(trans, eb, flag,
5183                                                   btrfs_header_level(eb));
5184                 BUG_ON(ret); /* -ENOMEM */
5185                 wc->flags[level] |= flag;
5186         }
5187
5188         /*
5189          * the block is shared by multiple trees, so it's not good to
5190          * keep the tree lock
5191          */
5192         if (path->locks[level] && level > 0) {
5193                 btrfs_tree_unlock_rw(eb, path->locks[level]);
5194                 path->locks[level] = 0;
5195         }
5196         return 0;
5197 }
5198
5199 /*
5200  * This is used to verify a ref exists for this root to deal with a bug where we
5201  * would have a drop_progress key that hadn't been updated properly.
5202  */
5203 static int check_ref_exists(struct btrfs_trans_handle *trans,
5204                             struct btrfs_root *root, u64 bytenr, u64 parent,
5205                             int level)
5206 {
5207         struct btrfs_path *path;
5208         struct btrfs_extent_inline_ref *iref;
5209         int ret;
5210
5211         path = btrfs_alloc_path();
5212         if (!path)
5213                 return -ENOMEM;
5214
5215         ret = lookup_extent_backref(trans, path, &iref, bytenr,
5216                                     root->fs_info->nodesize, parent,
5217                                     root->root_key.objectid, level, 0);
5218         btrfs_free_path(path);
5219         if (ret == -ENOENT)
5220                 return 0;
5221         if (ret < 0)
5222                 return ret;
5223         return 1;
5224 }
5225
5226 /*
5227  * helper to process tree block pointer.
5228  *
5229  * when wc->stage == DROP_REFERENCE, this function checks
5230  * reference count of the block pointed to. if the block
5231  * is shared and we need update back refs for the subtree
5232  * rooted at the block, this function changes wc->stage to
5233  * UPDATE_BACKREF. if the block is shared and there is no
5234  * need to update back, this function drops the reference
5235  * to the block.
5236  *
5237  * NOTE: return value 1 means we should stop walking down.
5238  */
5239 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
5240                                  struct btrfs_root *root,
5241                                  struct btrfs_path *path,
5242                                  struct walk_control *wc, int *lookup_info)
5243 {
5244         struct btrfs_fs_info *fs_info = root->fs_info;
5245         u64 bytenr;
5246         u64 generation;
5247         u64 parent;
5248         struct btrfs_key key;
5249         struct btrfs_key first_key;
5250         struct btrfs_ref ref = { 0 };
5251         struct extent_buffer *next;
5252         int level = wc->level;
5253         int reada = 0;
5254         int ret = 0;
5255         bool need_account = false;
5256
5257         generation = btrfs_node_ptr_generation(path->nodes[level],
5258                                                path->slots[level]);
5259         /*
5260          * if the lower level block was created before the snapshot
5261          * was created, we know there is no need to update back refs
5262          * for the subtree
5263          */
5264         if (wc->stage == UPDATE_BACKREF &&
5265             generation <= root->root_key.offset) {
5266                 *lookup_info = 1;
5267                 return 1;
5268         }
5269
5270         bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
5271         btrfs_node_key_to_cpu(path->nodes[level], &first_key,
5272                               path->slots[level]);
5273
5274         next = find_extent_buffer(fs_info, bytenr);
5275         if (!next) {
5276                 next = btrfs_find_create_tree_block(fs_info, bytenr,
5277                                 root->root_key.objectid, level - 1);
5278                 if (IS_ERR(next))
5279                         return PTR_ERR(next);
5280                 reada = 1;
5281         }
5282         btrfs_tree_lock(next);
5283
5284         ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
5285                                        &wc->refs[level - 1],
5286                                        &wc->flags[level - 1]);
5287         if (ret < 0)
5288                 goto out_unlock;
5289
5290         if (unlikely(wc->refs[level - 1] == 0)) {
5291                 btrfs_err(fs_info, "Missing references.");
5292                 ret = -EIO;
5293                 goto out_unlock;
5294         }
5295         *lookup_info = 0;
5296
5297         if (wc->stage == DROP_REFERENCE) {
5298                 if (wc->refs[level - 1] > 1) {
5299                         need_account = true;
5300                         if (level == 1 &&
5301                             (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5302                                 goto skip;
5303
5304                         if (!wc->update_ref ||
5305                             generation <= root->root_key.offset)
5306                                 goto skip;
5307
5308                         btrfs_node_key_to_cpu(path->nodes[level], &key,
5309                                               path->slots[level]);
5310                         ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
5311                         if (ret < 0)
5312                                 goto skip;
5313
5314                         wc->stage = UPDATE_BACKREF;
5315                         wc->shared_level = level - 1;
5316                 }
5317         } else {
5318                 if (level == 1 &&
5319                     (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5320                         goto skip;
5321         }
5322
5323         if (!btrfs_buffer_uptodate(next, generation, 0)) {
5324                 btrfs_tree_unlock(next);
5325                 free_extent_buffer(next);
5326                 next = NULL;
5327                 *lookup_info = 1;
5328         }
5329
5330         if (!next) {
5331                 if (reada && level == 1)
5332                         reada_walk_down(trans, root, wc, path);
5333                 next = read_tree_block(fs_info, bytenr, root->root_key.objectid,
5334                                        generation, level - 1, &first_key);
5335                 if (IS_ERR(next)) {
5336                         return PTR_ERR(next);
5337                 } else if (!extent_buffer_uptodate(next)) {
5338                         free_extent_buffer(next);
5339                         return -EIO;
5340                 }
5341                 btrfs_tree_lock(next);
5342         }
5343
5344         level--;
5345         ASSERT(level == btrfs_header_level(next));
5346         if (level != btrfs_header_level(next)) {
5347                 btrfs_err(root->fs_info, "mismatched level");
5348                 ret = -EIO;
5349                 goto out_unlock;
5350         }
5351         path->nodes[level] = next;
5352         path->slots[level] = 0;
5353         path->locks[level] = BTRFS_WRITE_LOCK;
5354         wc->level = level;
5355         if (wc->level == 1)
5356                 wc->reada_slot = 0;
5357         return 0;
5358 skip:
5359         wc->refs[level - 1] = 0;
5360         wc->flags[level - 1] = 0;
5361         if (wc->stage == DROP_REFERENCE) {
5362                 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5363                         parent = path->nodes[level]->start;
5364                 } else {
5365                         ASSERT(root->root_key.objectid ==
5366                                btrfs_header_owner(path->nodes[level]));
5367                         if (root->root_key.objectid !=
5368                             btrfs_header_owner(path->nodes[level])) {
5369                                 btrfs_err(root->fs_info,
5370                                                 "mismatched block owner");
5371                                 ret = -EIO;
5372                                 goto out_unlock;
5373                         }
5374                         parent = 0;
5375                 }
5376
5377                 /*
5378                  * If we had a drop_progress we need to verify the refs are set
5379                  * as expected.  If we find our ref then we know that from here
5380                  * on out everything should be correct, and we can clear the
5381                  * ->restarted flag.
5382                  */
5383                 if (wc->restarted) {
5384                         ret = check_ref_exists(trans, root, bytenr, parent,
5385                                                level - 1);
5386                         if (ret < 0)
5387                                 goto out_unlock;
5388                         if (ret == 0)
5389                                 goto no_delete;
5390                         ret = 0;
5391                         wc->restarted = 0;
5392                 }
5393
5394                 /*
5395                  * Reloc tree doesn't contribute to qgroup numbers, and we have
5396                  * already accounted them at merge time (replace_path),
5397                  * thus we could skip expensive subtree trace here.
5398                  */
5399                 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
5400                     need_account) {
5401                         ret = btrfs_qgroup_trace_subtree(trans, next,
5402                                                          generation, level - 1);
5403                         if (ret) {
5404                                 btrfs_err_rl(fs_info,
5405                                              "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
5406                                              ret);
5407                         }
5408                 }
5409
5410                 /*
5411                  * We need to update the next key in our walk control so we can
5412                  * update the drop_progress key accordingly.  We don't care if
5413                  * find_next_key doesn't find a key because that means we're at
5414                  * the end and are going to clean up now.
5415                  */
5416                 wc->drop_level = level;
5417                 find_next_key(path, level, &wc->drop_progress);
5418
5419                 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
5420                                        fs_info->nodesize, parent);
5421                 btrfs_init_tree_ref(&ref, level - 1, root->root_key.objectid,
5422                                     0, false);
5423                 ret = btrfs_free_extent(trans, &ref);
5424                 if (ret)
5425                         goto out_unlock;
5426         }
5427 no_delete:
5428         *lookup_info = 1;
5429         ret = 1;
5430
5431 out_unlock:
5432         btrfs_tree_unlock(next);
5433         free_extent_buffer(next);
5434
5435         return ret;
5436 }
5437
5438 /*
5439  * helper to process tree block while walking up the tree.
5440  *
5441  * when wc->stage == DROP_REFERENCE, this function drops
5442  * reference count on the block.
5443  *
5444  * when wc->stage == UPDATE_BACKREF, this function changes
5445  * wc->stage back to DROP_REFERENCE if we changed wc->stage
5446  * to UPDATE_BACKREF previously while processing the block.
5447  *
5448  * NOTE: return value 1 means we should stop walking up.
5449  */
5450 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
5451                                  struct btrfs_root *root,
5452                                  struct btrfs_path *path,
5453                                  struct walk_control *wc)
5454 {
5455         struct btrfs_fs_info *fs_info = root->fs_info;
5456         int ret;
5457         int level = wc->level;
5458         struct extent_buffer *eb = path->nodes[level];
5459         u64 parent = 0;
5460
5461         if (wc->stage == UPDATE_BACKREF) {
5462                 BUG_ON(wc->shared_level < level);
5463                 if (level < wc->shared_level)
5464                         goto out;
5465
5466                 ret = find_next_key(path, level + 1, &wc->update_progress);
5467                 if (ret > 0)
5468                         wc->update_ref = 0;
5469
5470                 wc->stage = DROP_REFERENCE;
5471                 wc->shared_level = -1;
5472                 path->slots[level] = 0;
5473
5474                 /*
5475                  * check reference count again if the block isn't locked.
5476                  * we should start walking down the tree again if reference
5477                  * count is one.
5478                  */
5479                 if (!path->locks[level]) {
5480                         BUG_ON(level == 0);
5481                         btrfs_tree_lock(eb);
5482                         path->locks[level] = BTRFS_WRITE_LOCK;
5483
5484                         ret = btrfs_lookup_extent_info(trans, fs_info,
5485                                                        eb->start, level, 1,
5486                                                        &wc->refs[level],
5487                                                        &wc->flags[level]);
5488                         if (ret < 0) {
5489                                 btrfs_tree_unlock_rw(eb, path->locks[level]);
5490                                 path->locks[level] = 0;
5491                                 return ret;
5492                         }
5493                         BUG_ON(wc->refs[level] == 0);
5494                         if (wc->refs[level] == 1) {
5495                                 btrfs_tree_unlock_rw(eb, path->locks[level]);
5496                                 path->locks[level] = 0;
5497                                 return 1;
5498                         }
5499                 }
5500         }
5501
5502         /* wc->stage == DROP_REFERENCE */
5503         BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
5504
5505         if (wc->refs[level] == 1) {
5506                 if (level == 0) {
5507                         if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5508                                 ret = btrfs_dec_ref(trans, root, eb, 1);
5509                         else
5510                                 ret = btrfs_dec_ref(trans, root, eb, 0);
5511                         BUG_ON(ret); /* -ENOMEM */
5512                         if (is_fstree(root->root_key.objectid)) {
5513                                 ret = btrfs_qgroup_trace_leaf_items(trans, eb);
5514                                 if (ret) {
5515                                         btrfs_err_rl(fs_info,
5516         "error %d accounting leaf items, quota is out of sync, rescan required",
5517                                              ret);
5518                                 }
5519                         }
5520                 }
5521                 /* make block locked assertion in btrfs_clean_tree_block happy */
5522                 if (!path->locks[level] &&
5523                     btrfs_header_generation(eb) == trans->transid) {
5524                         btrfs_tree_lock(eb);
5525                         path->locks[level] = BTRFS_WRITE_LOCK;
5526                 }
5527                 btrfs_clean_tree_block(eb);
5528         }
5529
5530         if (eb == root->node) {
5531                 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5532                         parent = eb->start;
5533                 else if (root->root_key.objectid != btrfs_header_owner(eb))
5534                         goto owner_mismatch;
5535         } else {
5536                 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5537                         parent = path->nodes[level + 1]->start;
5538                 else if (root->root_key.objectid !=
5539                          btrfs_header_owner(path->nodes[level + 1]))
5540                         goto owner_mismatch;
5541         }
5542
5543         btrfs_free_tree_block(trans, btrfs_root_id(root), eb, parent,
5544                               wc->refs[level] == 1);
5545 out:
5546         wc->refs[level] = 0;
5547         wc->flags[level] = 0;
5548         return 0;
5549
5550 owner_mismatch:
5551         btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
5552                      btrfs_header_owner(eb), root->root_key.objectid);
5553         return -EUCLEAN;
5554 }
5555
5556 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
5557                                    struct btrfs_root *root,
5558                                    struct btrfs_path *path,
5559                                    struct walk_control *wc)
5560 {
5561         int level = wc->level;
5562         int lookup_info = 1;
5563         int ret;
5564
5565         while (level >= 0) {
5566                 ret = walk_down_proc(trans, root, path, wc, lookup_info);
5567                 if (ret > 0)
5568                         break;
5569
5570                 if (level == 0)
5571                         break;
5572
5573                 if (path->slots[level] >=
5574                     btrfs_header_nritems(path->nodes[level]))
5575                         break;
5576
5577                 ret = do_walk_down(trans, root, path, wc, &lookup_info);
5578                 if (ret > 0) {
5579                         path->slots[level]++;
5580                         continue;
5581                 } else if (ret < 0)
5582                         return ret;
5583                 level = wc->level;
5584         }
5585         return 0;
5586 }
5587
5588 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
5589                                  struct btrfs_root *root,
5590                                  struct btrfs_path *path,
5591                                  struct walk_control *wc, int max_level)
5592 {
5593         int level = wc->level;
5594         int ret;
5595
5596         path->slots[level] = btrfs_header_nritems(path->nodes[level]);
5597         while (level < max_level && path->nodes[level]) {
5598                 wc->level = level;
5599                 if (path->slots[level] + 1 <
5600                     btrfs_header_nritems(path->nodes[level])) {
5601                         path->slots[level]++;
5602                         return 0;
5603                 } else {
5604                         ret = walk_up_proc(trans, root, path, wc);
5605                         if (ret > 0)
5606                                 return 0;
5607                         if (ret < 0)
5608                                 return ret;
5609
5610                         if (path->locks[level]) {
5611                                 btrfs_tree_unlock_rw(path->nodes[level],
5612                                                      path->locks[level]);
5613                                 path->locks[level] = 0;
5614                         }
5615                         free_extent_buffer(path->nodes[level]);
5616                         path->nodes[level] = NULL;
5617                         level++;
5618                 }
5619         }
5620         return 1;
5621 }
5622
5623 /*
5624  * drop a subvolume tree.
5625  *
5626  * this function traverses the tree freeing any blocks that only
5627  * referenced by the tree.
5628  *
5629  * when a shared tree block is found. this function decreases its
5630  * reference count by one. if update_ref is true, this function
5631  * also make sure backrefs for the shared block and all lower level
5632  * blocks are properly updated.
5633  *
5634  * If called with for_reloc == 0, may exit early with -EAGAIN
5635  */
5636 int btrfs_drop_snapshot(struct btrfs_root *root, int update_ref, int for_reloc)
5637 {
5638         struct btrfs_fs_info *fs_info = root->fs_info;
5639         struct btrfs_path *path;
5640         struct btrfs_trans_handle *trans;
5641         struct btrfs_root *tree_root = fs_info->tree_root;
5642         struct btrfs_root_item *root_item = &root->root_item;
5643         struct walk_control *wc;
5644         struct btrfs_key key;
5645         int err = 0;
5646         int ret;
5647         int level;
5648         bool root_dropped = false;
5649         bool unfinished_drop = false;
5650
5651         btrfs_debug(fs_info, "Drop subvolume %llu", root->root_key.objectid);
5652
5653         path = btrfs_alloc_path();
5654         if (!path) {
5655                 err = -ENOMEM;
5656                 goto out;
5657         }
5658
5659         wc = kzalloc(sizeof(*wc), GFP_NOFS);
5660         if (!wc) {
5661                 btrfs_free_path(path);
5662                 err = -ENOMEM;
5663                 goto out;
5664         }
5665
5666         /*
5667          * Use join to avoid potential EINTR from transaction start. See
5668          * wait_reserve_ticket and the whole reservation callchain.
5669          */
5670         if (for_reloc)
5671                 trans = btrfs_join_transaction(tree_root);
5672         else
5673                 trans = btrfs_start_transaction(tree_root, 0);
5674         if (IS_ERR(trans)) {
5675                 err = PTR_ERR(trans);
5676                 goto out_free;
5677         }
5678
5679         err = btrfs_run_delayed_items(trans);
5680         if (err)
5681                 goto out_end_trans;
5682
5683         /*
5684          * This will help us catch people modifying the fs tree while we're
5685          * dropping it.  It is unsafe to mess with the fs tree while it's being
5686          * dropped as we unlock the root node and parent nodes as we walk down
5687          * the tree, assuming nothing will change.  If something does change
5688          * then we'll have stale information and drop references to blocks we've
5689          * already dropped.
5690          */
5691         set_bit(BTRFS_ROOT_DELETING, &root->state);
5692         unfinished_drop = test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state);
5693
5694         if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
5695                 level = btrfs_header_level(root->node);
5696                 path->nodes[level] = btrfs_lock_root_node(root);
5697                 path->slots[level] = 0;
5698                 path->locks[level] = BTRFS_WRITE_LOCK;
5699                 memset(&wc->update_progress, 0,
5700                        sizeof(wc->update_progress));
5701         } else {
5702                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
5703                 memcpy(&wc->update_progress, &key,
5704                        sizeof(wc->update_progress));
5705
5706                 level = btrfs_root_drop_level(root_item);
5707                 BUG_ON(level == 0);
5708                 path->lowest_level = level;
5709                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5710                 path->lowest_level = 0;
5711                 if (ret < 0) {
5712                         err = ret;
5713                         goto out_end_trans;
5714                 }
5715                 WARN_ON(ret > 0);
5716
5717                 /*
5718                  * unlock our path, this is safe because only this
5719                  * function is allowed to delete this snapshot
5720                  */
5721                 btrfs_unlock_up_safe(path, 0);
5722
5723                 level = btrfs_header_level(root->node);
5724                 while (1) {
5725                         btrfs_tree_lock(path->nodes[level]);
5726                         path->locks[level] = BTRFS_WRITE_LOCK;
5727
5728                         ret = btrfs_lookup_extent_info(trans, fs_info,
5729                                                 path->nodes[level]->start,
5730                                                 level, 1, &wc->refs[level],
5731                                                 &wc->flags[level]);
5732                         if (ret < 0) {
5733                                 err = ret;
5734                                 goto out_end_trans;
5735                         }
5736                         BUG_ON(wc->refs[level] == 0);
5737
5738                         if (level == btrfs_root_drop_level(root_item))
5739                                 break;
5740
5741                         btrfs_tree_unlock(path->nodes[level]);
5742                         path->locks[level] = 0;
5743                         WARN_ON(wc->refs[level] != 1);
5744                         level--;
5745                 }
5746         }
5747
5748         wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
5749         wc->level = level;
5750         wc->shared_level = -1;
5751         wc->stage = DROP_REFERENCE;
5752         wc->update_ref = update_ref;
5753         wc->keep_locks = 0;
5754         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
5755
5756         while (1) {
5757
5758                 ret = walk_down_tree(trans, root, path, wc);
5759                 if (ret < 0) {
5760                         err = ret;
5761                         break;
5762                 }
5763
5764                 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
5765                 if (ret < 0) {
5766                         err = ret;
5767                         break;
5768                 }
5769
5770                 if (ret > 0) {
5771                         BUG_ON(wc->stage != DROP_REFERENCE);
5772                         break;
5773                 }
5774
5775                 if (wc->stage == DROP_REFERENCE) {
5776                         wc->drop_level = wc->level;
5777                         btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
5778                                               &wc->drop_progress,
5779                                               path->slots[wc->drop_level]);
5780                 }
5781                 btrfs_cpu_key_to_disk(&root_item->drop_progress,
5782                                       &wc->drop_progress);
5783                 btrfs_set_root_drop_level(root_item, wc->drop_level);
5784
5785                 BUG_ON(wc->level == 0);
5786                 if (btrfs_should_end_transaction(trans) ||
5787                     (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
5788                         ret = btrfs_update_root(trans, tree_root,
5789                                                 &root->root_key,
5790                                                 root_item);
5791                         if (ret) {
5792                                 btrfs_abort_transaction(trans, ret);
5793                                 err = ret;
5794                                 goto out_end_trans;
5795                         }
5796
5797                         btrfs_end_transaction_throttle(trans);
5798                         if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
5799                                 btrfs_debug(fs_info,
5800                                             "drop snapshot early exit");
5801                                 err = -EAGAIN;
5802                                 goto out_free;
5803                         }
5804
5805                        /*
5806                         * Use join to avoid potential EINTR from transaction
5807                         * start. See wait_reserve_ticket and the whole
5808                         * reservation callchain.
5809                         */
5810                         if (for_reloc)
5811                                 trans = btrfs_join_transaction(tree_root);
5812                         else
5813                                 trans = btrfs_start_transaction(tree_root, 0);
5814                         if (IS_ERR(trans)) {
5815                                 err = PTR_ERR(trans);
5816                                 goto out_free;
5817                         }
5818                 }
5819         }
5820         btrfs_release_path(path);
5821         if (err)
5822                 goto out_end_trans;
5823
5824         ret = btrfs_del_root(trans, &root->root_key);
5825         if (ret) {
5826                 btrfs_abort_transaction(trans, ret);
5827                 err = ret;
5828                 goto out_end_trans;
5829         }
5830
5831         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
5832                 ret = btrfs_find_root(tree_root, &root->root_key, path,
5833                                       NULL, NULL);
5834                 if (ret < 0) {
5835                         btrfs_abort_transaction(trans, ret);
5836                         err = ret;
5837                         goto out_end_trans;
5838                 } else if (ret > 0) {
5839                         /* if we fail to delete the orphan item this time
5840                          * around, it'll get picked up the next time.
5841                          *
5842                          * The most common failure here is just -ENOENT.
5843                          */
5844                         btrfs_del_orphan_item(trans, tree_root,
5845                                               root->root_key.objectid);
5846                 }
5847         }
5848
5849         /*
5850          * This subvolume is going to be completely dropped, and won't be
5851          * recorded as dirty roots, thus pertrans meta rsv will not be freed at
5852          * commit transaction time.  So free it here manually.
5853          */
5854         btrfs_qgroup_convert_reserved_meta(root, INT_MAX);
5855         btrfs_qgroup_free_meta_all_pertrans(root);
5856
5857         if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state))
5858                 btrfs_add_dropped_root(trans, root);
5859         else
5860                 btrfs_put_root(root);
5861         root_dropped = true;
5862 out_end_trans:
5863         btrfs_end_transaction_throttle(trans);
5864 out_free:
5865         kfree(wc);
5866         btrfs_free_path(path);
5867 out:
5868         /*
5869          * We were an unfinished drop root, check to see if there are any
5870          * pending, and if not clear and wake up any waiters.
5871          */
5872         if (!err && unfinished_drop)
5873                 btrfs_maybe_wake_unfinished_drop(fs_info);
5874
5875         /*
5876          * So if we need to stop dropping the snapshot for whatever reason we
5877          * need to make sure to add it back to the dead root list so that we
5878          * keep trying to do the work later.  This also cleans up roots if we
5879          * don't have it in the radix (like when we recover after a power fail
5880          * or unmount) so we don't leak memory.
5881          */
5882         if (!for_reloc && !root_dropped)
5883                 btrfs_add_dead_root(root);
5884         return err;
5885 }
5886
5887 /*
5888  * drop subtree rooted at tree block 'node'.
5889  *
5890  * NOTE: this function will unlock and release tree block 'node'
5891  * only used by relocation code
5892  */
5893 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
5894                         struct btrfs_root *root,
5895                         struct extent_buffer *node,
5896                         struct extent_buffer *parent)
5897 {
5898         struct btrfs_fs_info *fs_info = root->fs_info;
5899         struct btrfs_path *path;
5900         struct walk_control *wc;
5901         int level;
5902         int parent_level;
5903         int ret = 0;
5904         int wret;
5905
5906         BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
5907
5908         path = btrfs_alloc_path();
5909         if (!path)
5910                 return -ENOMEM;
5911
5912         wc = kzalloc(sizeof(*wc), GFP_NOFS);
5913         if (!wc) {
5914                 btrfs_free_path(path);
5915                 return -ENOMEM;
5916         }
5917
5918         btrfs_assert_tree_write_locked(parent);
5919         parent_level = btrfs_header_level(parent);
5920         atomic_inc(&parent->refs);
5921         path->nodes[parent_level] = parent;
5922         path->slots[parent_level] = btrfs_header_nritems(parent);
5923
5924         btrfs_assert_tree_write_locked(node);
5925         level = btrfs_header_level(node);
5926         path->nodes[level] = node;
5927         path->slots[level] = 0;
5928         path->locks[level] = BTRFS_WRITE_LOCK;
5929
5930         wc->refs[parent_level] = 1;
5931         wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5932         wc->level = level;
5933         wc->shared_level = -1;
5934         wc->stage = DROP_REFERENCE;
5935         wc->update_ref = 0;
5936         wc->keep_locks = 1;
5937         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
5938
5939         while (1) {
5940                 wret = walk_down_tree(trans, root, path, wc);
5941                 if (wret < 0) {
5942                         ret = wret;
5943                         break;
5944                 }
5945
5946                 wret = walk_up_tree(trans, root, path, wc, parent_level);
5947                 if (wret < 0)
5948                         ret = wret;
5949                 if (wret != 0)
5950                         break;
5951         }
5952
5953         kfree(wc);
5954         btrfs_free_path(path);
5955         return ret;
5956 }
5957
5958 /*
5959  * helper to account the unused space of all the readonly block group in the
5960  * space_info. takes mirrors into account.
5961  */
5962 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
5963 {
5964         struct btrfs_block_group *block_group;
5965         u64 free_bytes = 0;
5966         int factor;
5967
5968         /* It's df, we don't care if it's racy */
5969         if (list_empty(&sinfo->ro_bgs))
5970                 return 0;
5971
5972         spin_lock(&sinfo->lock);
5973         list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
5974                 spin_lock(&block_group->lock);
5975
5976                 if (!block_group->ro) {
5977                         spin_unlock(&block_group->lock);
5978                         continue;
5979                 }
5980
5981                 factor = btrfs_bg_type_to_factor(block_group->flags);
5982                 free_bytes += (block_group->length -
5983                                block_group->used) * factor;
5984
5985                 spin_unlock(&block_group->lock);
5986         }
5987         spin_unlock(&sinfo->lock);
5988
5989         return free_bytes;
5990 }
5991
5992 int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
5993                                    u64 start, u64 end)
5994 {
5995         return unpin_extent_range(fs_info, start, end, false);
5996 }
5997
5998 /*
5999  * It used to be that old block groups would be left around forever.
6000  * Iterating over them would be enough to trim unused space.  Since we
6001  * now automatically remove them, we also need to iterate over unallocated
6002  * space.
6003  *
6004  * We don't want a transaction for this since the discard may take a
6005  * substantial amount of time.  We don't require that a transaction be
6006  * running, but we do need to take a running transaction into account
6007  * to ensure that we're not discarding chunks that were released or
6008  * allocated in the current transaction.
6009  *
6010  * Holding the chunks lock will prevent other threads from allocating
6011  * or releasing chunks, but it won't prevent a running transaction
6012  * from committing and releasing the memory that the pending chunks
6013  * list head uses.  For that, we need to take a reference to the
6014  * transaction and hold the commit root sem.  We only need to hold
6015  * it while performing the free space search since we have already
6016  * held back allocations.
6017  */
6018 static int btrfs_trim_free_extents(struct btrfs_device *device, u64 *trimmed)
6019 {
6020         u64 start = BTRFS_DEVICE_RANGE_RESERVED, len = 0, end = 0;
6021         int ret;
6022
6023         *trimmed = 0;
6024
6025         /* Discard not supported = nothing to do. */
6026         if (!bdev_max_discard_sectors(device->bdev))
6027                 return 0;
6028
6029         /* Not writable = nothing to do. */
6030         if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
6031                 return 0;
6032
6033         /* No free space = nothing to do. */
6034         if (device->total_bytes <= device->bytes_used)
6035                 return 0;
6036
6037         ret = 0;
6038
6039         while (1) {
6040                 struct btrfs_fs_info *fs_info = device->fs_info;
6041                 u64 bytes;
6042
6043                 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
6044                 if (ret)
6045                         break;
6046
6047                 find_first_clear_extent_bit(&device->alloc_state, start,
6048                                             &start, &end,
6049                                             CHUNK_TRIMMED | CHUNK_ALLOCATED);
6050
6051                 /* Check if there are any CHUNK_* bits left */
6052                 if (start > device->total_bytes) {
6053                         WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
6054                         btrfs_warn_in_rcu(fs_info,
6055 "ignoring attempt to trim beyond device size: offset %llu length %llu device %s device size %llu",
6056                                           start, end - start + 1,
6057                                           rcu_str_deref(device->name),
6058                                           device->total_bytes);
6059                         mutex_unlock(&fs_info->chunk_mutex);
6060                         ret = 0;
6061                         break;
6062                 }
6063
6064                 /* Ensure we skip the reserved space on each device. */
6065                 start = max_t(u64, start, BTRFS_DEVICE_RANGE_RESERVED);
6066
6067                 /*
6068                  * If find_first_clear_extent_bit find a range that spans the
6069                  * end of the device it will set end to -1, in this case it's up
6070                  * to the caller to trim the value to the size of the device.
6071                  */
6072                 end = min(end, device->total_bytes - 1);
6073
6074                 len = end - start + 1;
6075
6076                 /* We didn't find any extents */
6077                 if (!len) {
6078                         mutex_unlock(&fs_info->chunk_mutex);
6079                         ret = 0;
6080                         break;
6081                 }
6082
6083                 ret = btrfs_issue_discard(device->bdev, start, len,
6084                                           &bytes);
6085                 if (!ret)
6086                         set_extent_bits(&device->alloc_state, start,
6087                                         start + bytes - 1,
6088                                         CHUNK_TRIMMED);
6089                 mutex_unlock(&fs_info->chunk_mutex);
6090
6091                 if (ret)
6092                         break;
6093
6094                 start += len;
6095                 *trimmed += bytes;
6096
6097                 if (fatal_signal_pending(current)) {
6098                         ret = -ERESTARTSYS;
6099                         break;
6100                 }
6101
6102                 cond_resched();
6103         }
6104
6105         return ret;
6106 }
6107
6108 /*
6109  * Trim the whole filesystem by:
6110  * 1) trimming the free space in each block group
6111  * 2) trimming the unallocated space on each device
6112  *
6113  * This will also continue trimming even if a block group or device encounters
6114  * an error.  The return value will be the last error, or 0 if nothing bad
6115  * happens.
6116  */
6117 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
6118 {
6119         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6120         struct btrfs_block_group *cache = NULL;
6121         struct btrfs_device *device;
6122         u64 group_trimmed;
6123         u64 range_end = U64_MAX;
6124         u64 start;
6125         u64 end;
6126         u64 trimmed = 0;
6127         u64 bg_failed = 0;
6128         u64 dev_failed = 0;
6129         int bg_ret = 0;
6130         int dev_ret = 0;
6131         int ret = 0;
6132
6133         if (range->start == U64_MAX)
6134                 return -EINVAL;
6135
6136         /*
6137          * Check range overflow if range->len is set.
6138          * The default range->len is U64_MAX.
6139          */
6140         if (range->len != U64_MAX &&
6141             check_add_overflow(range->start, range->len, &range_end))
6142                 return -EINVAL;
6143
6144         cache = btrfs_lookup_first_block_group(fs_info, range->start);
6145         for (; cache; cache = btrfs_next_block_group(cache)) {
6146                 if (cache->start >= range_end) {
6147                         btrfs_put_block_group(cache);
6148                         break;
6149                 }
6150
6151                 start = max(range->start, cache->start);
6152                 end = min(range_end, cache->start + cache->length);
6153
6154                 if (end - start >= range->minlen) {
6155                         if (!btrfs_block_group_done(cache)) {
6156                                 ret = btrfs_cache_block_group(cache, 0);
6157                                 if (ret) {
6158                                         bg_failed++;
6159                                         bg_ret = ret;
6160                                         continue;
6161                                 }
6162                                 ret = btrfs_wait_block_group_cache_done(cache);
6163                                 if (ret) {
6164                                         bg_failed++;
6165                                         bg_ret = ret;
6166                                         continue;
6167                                 }
6168                         }
6169                         ret = btrfs_trim_block_group(cache,
6170                                                      &group_trimmed,
6171                                                      start,
6172                                                      end,
6173                                                      range->minlen);
6174
6175                         trimmed += group_trimmed;
6176                         if (ret) {
6177                                 bg_failed++;
6178                                 bg_ret = ret;
6179                                 continue;
6180                         }
6181                 }
6182         }
6183
6184         if (bg_failed)
6185                 btrfs_warn(fs_info,
6186                         "failed to trim %llu block group(s), last error %d",
6187                         bg_failed, bg_ret);
6188
6189         mutex_lock(&fs_devices->device_list_mutex);
6190         list_for_each_entry(device, &fs_devices->devices, dev_list) {
6191                 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
6192                         continue;
6193
6194                 ret = btrfs_trim_free_extents(device, &group_trimmed);
6195                 if (ret) {
6196                         dev_failed++;
6197                         dev_ret = ret;
6198                         break;
6199                 }
6200
6201                 trimmed += group_trimmed;
6202         }
6203         mutex_unlock(&fs_devices->device_list_mutex);
6204
6205         if (dev_failed)
6206                 btrfs_warn(fs_info,
6207                         "failed to trim %llu device(s), last error %d",
6208                         dev_failed, dev_ret);
6209         range->len = trimmed;
6210         if (bg_ret)
6211                 return bg_ret;
6212         return dev_ret;
6213 }