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