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