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