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