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