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