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