btrfs: remove unused parameter fs_info from btrfs_truncate_item
[sfrench/cifs-2.6.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 "tree-log.h"
20 #include "disk-io.h"
21 #include "print-tree.h"
22 #include "volumes.h"
23 #include "raid56.h"
24 #include "locking.h"
25 #include "free-space-cache.h"
26 #include "free-space-tree.h"
27 #include "math.h"
28 #include "sysfs.h"
29 #include "qgroup.h"
30 #include "ref-verify.h"
31
32 #undef SCRAMBLE_DELAYED_REFS
33
34 /*
35  * control flags for do_chunk_alloc's force field
36  * CHUNK_ALLOC_NO_FORCE means to only allocate a chunk
37  * if we really need one.
38  *
39  * CHUNK_ALLOC_LIMITED means to only try and allocate one
40  * if we have very few chunks already allocated.  This is
41  * used as part of the clustering code to help make sure
42  * we have a good pool of storage to cluster in, without
43  * filling the FS with empty chunks
44  *
45  * CHUNK_ALLOC_FORCE means it must try to allocate one
46  *
47  */
48 enum {
49         CHUNK_ALLOC_NO_FORCE = 0,
50         CHUNK_ALLOC_LIMITED = 1,
51         CHUNK_ALLOC_FORCE = 2,
52 };
53
54 /*
55  * Declare a helper function to detect underflow of various space info members
56  */
57 #define DECLARE_SPACE_INFO_UPDATE(name)                                 \
58 static inline void update_##name(struct btrfs_space_info *sinfo,        \
59                                  s64 bytes)                             \
60 {                                                                       \
61         if (bytes < 0 && sinfo->name < -bytes) {                        \
62                 WARN_ON(1);                                             \
63                 sinfo->name = 0;                                        \
64                 return;                                                 \
65         }                                                               \
66         sinfo->name += bytes;                                           \
67 }
68
69 DECLARE_SPACE_INFO_UPDATE(bytes_may_use);
70 DECLARE_SPACE_INFO_UPDATE(bytes_pinned);
71
72 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
73                                struct btrfs_delayed_ref_node *node, u64 parent,
74                                u64 root_objectid, u64 owner_objectid,
75                                u64 owner_offset, int refs_to_drop,
76                                struct btrfs_delayed_extent_op *extra_op);
77 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
78                                     struct extent_buffer *leaf,
79                                     struct btrfs_extent_item *ei);
80 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
81                                       u64 parent, u64 root_objectid,
82                                       u64 flags, u64 owner, u64 offset,
83                                       struct btrfs_key *ins, int ref_mod);
84 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
85                                      struct btrfs_delayed_ref_node *node,
86                                      struct btrfs_delayed_extent_op *extent_op);
87 static int do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
88                           int force);
89 static int find_next_key(struct btrfs_path *path, int level,
90                          struct btrfs_key *key);
91 static void dump_space_info(struct btrfs_fs_info *fs_info,
92                             struct btrfs_space_info *info, u64 bytes,
93                             int dump_block_groups);
94 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
95                                u64 num_bytes);
96 static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
97                                      struct btrfs_space_info *space_info,
98                                      u64 num_bytes);
99 static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
100                                      struct btrfs_space_info *space_info,
101                                      u64 num_bytes);
102
103 static noinline int
104 block_group_cache_done(struct btrfs_block_group_cache *cache)
105 {
106         smp_mb();
107         return cache->cached == BTRFS_CACHE_FINISHED ||
108                 cache->cached == BTRFS_CACHE_ERROR;
109 }
110
111 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
112 {
113         return (cache->flags & bits) == bits;
114 }
115
116 void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
117 {
118         atomic_inc(&cache->count);
119 }
120
121 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
122 {
123         if (atomic_dec_and_test(&cache->count)) {
124                 WARN_ON(cache->pinned > 0);
125                 WARN_ON(cache->reserved > 0);
126
127                 /*
128                  * If not empty, someone is still holding mutex of
129                  * full_stripe_lock, which can only be released by caller.
130                  * And it will definitely cause use-after-free when caller
131                  * tries to release full stripe lock.
132                  *
133                  * No better way to resolve, but only to warn.
134                  */
135                 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
136                 kfree(cache->free_space_ctl);
137                 kfree(cache);
138         }
139 }
140
141 /*
142  * this adds the block group to the fs_info rb tree for the block group
143  * cache
144  */
145 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
146                                 struct btrfs_block_group_cache *block_group)
147 {
148         struct rb_node **p;
149         struct rb_node *parent = NULL;
150         struct btrfs_block_group_cache *cache;
151
152         spin_lock(&info->block_group_cache_lock);
153         p = &info->block_group_cache_tree.rb_node;
154
155         while (*p) {
156                 parent = *p;
157                 cache = rb_entry(parent, struct btrfs_block_group_cache,
158                                  cache_node);
159                 if (block_group->key.objectid < cache->key.objectid) {
160                         p = &(*p)->rb_left;
161                 } else if (block_group->key.objectid > cache->key.objectid) {
162                         p = &(*p)->rb_right;
163                 } else {
164                         spin_unlock(&info->block_group_cache_lock);
165                         return -EEXIST;
166                 }
167         }
168
169         rb_link_node(&block_group->cache_node, parent, p);
170         rb_insert_color(&block_group->cache_node,
171                         &info->block_group_cache_tree);
172
173         if (info->first_logical_byte > block_group->key.objectid)
174                 info->first_logical_byte = block_group->key.objectid;
175
176         spin_unlock(&info->block_group_cache_lock);
177
178         return 0;
179 }
180
181 /*
182  * This will return the block group at or after bytenr if contains is 0, else
183  * it will return the block group that contains the bytenr
184  */
185 static struct btrfs_block_group_cache *
186 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
187                               int contains)
188 {
189         struct btrfs_block_group_cache *cache, *ret = NULL;
190         struct rb_node *n;
191         u64 end, start;
192
193         spin_lock(&info->block_group_cache_lock);
194         n = info->block_group_cache_tree.rb_node;
195
196         while (n) {
197                 cache = rb_entry(n, struct btrfs_block_group_cache,
198                                  cache_node);
199                 end = cache->key.objectid + cache->key.offset - 1;
200                 start = cache->key.objectid;
201
202                 if (bytenr < start) {
203                         if (!contains && (!ret || start < ret->key.objectid))
204                                 ret = cache;
205                         n = n->rb_left;
206                 } else if (bytenr > start) {
207                         if (contains && bytenr <= end) {
208                                 ret = cache;
209                                 break;
210                         }
211                         n = n->rb_right;
212                 } else {
213                         ret = cache;
214                         break;
215                 }
216         }
217         if (ret) {
218                 btrfs_get_block_group(ret);
219                 if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
220                         info->first_logical_byte = ret->key.objectid;
221         }
222         spin_unlock(&info->block_group_cache_lock);
223
224         return ret;
225 }
226
227 static int add_excluded_extent(struct btrfs_fs_info *fs_info,
228                                u64 start, u64 num_bytes)
229 {
230         u64 end = start + num_bytes - 1;
231         set_extent_bits(&fs_info->freed_extents[0],
232                         start, end, EXTENT_UPTODATE);
233         set_extent_bits(&fs_info->freed_extents[1],
234                         start, end, EXTENT_UPTODATE);
235         return 0;
236 }
237
238 static void free_excluded_extents(struct btrfs_block_group_cache *cache)
239 {
240         struct btrfs_fs_info *fs_info = cache->fs_info;
241         u64 start, end;
242
243         start = cache->key.objectid;
244         end = start + cache->key.offset - 1;
245
246         clear_extent_bits(&fs_info->freed_extents[0],
247                           start, end, EXTENT_UPTODATE);
248         clear_extent_bits(&fs_info->freed_extents[1],
249                           start, end, EXTENT_UPTODATE);
250 }
251
252 static int exclude_super_stripes(struct btrfs_block_group_cache *cache)
253 {
254         struct btrfs_fs_info *fs_info = cache->fs_info;
255         u64 bytenr;
256         u64 *logical;
257         int stripe_len;
258         int i, nr, ret;
259
260         if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
261                 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
262                 cache->bytes_super += stripe_len;
263                 ret = add_excluded_extent(fs_info, cache->key.objectid,
264                                           stripe_len);
265                 if (ret)
266                         return ret;
267         }
268
269         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
270                 bytenr = btrfs_sb_offset(i);
271                 ret = btrfs_rmap_block(fs_info, cache->key.objectid,
272                                        bytenr, &logical, &nr, &stripe_len);
273                 if (ret)
274                         return ret;
275
276                 while (nr--) {
277                         u64 start, len;
278
279                         if (logical[nr] > cache->key.objectid +
280                             cache->key.offset)
281                                 continue;
282
283                         if (logical[nr] + stripe_len <= cache->key.objectid)
284                                 continue;
285
286                         start = logical[nr];
287                         if (start < cache->key.objectid) {
288                                 start = cache->key.objectid;
289                                 len = (logical[nr] + stripe_len) - start;
290                         } else {
291                                 len = min_t(u64, stripe_len,
292                                             cache->key.objectid +
293                                             cache->key.offset - start);
294                         }
295
296                         cache->bytes_super += len;
297                         ret = add_excluded_extent(fs_info, start, len);
298                         if (ret) {
299                                 kfree(logical);
300                                 return ret;
301                         }
302                 }
303
304                 kfree(logical);
305         }
306         return 0;
307 }
308
309 static struct btrfs_caching_control *
310 get_caching_control(struct btrfs_block_group_cache *cache)
311 {
312         struct btrfs_caching_control *ctl;
313
314         spin_lock(&cache->lock);
315         if (!cache->caching_ctl) {
316                 spin_unlock(&cache->lock);
317                 return NULL;
318         }
319
320         ctl = cache->caching_ctl;
321         refcount_inc(&ctl->count);
322         spin_unlock(&cache->lock);
323         return ctl;
324 }
325
326 static void put_caching_control(struct btrfs_caching_control *ctl)
327 {
328         if (refcount_dec_and_test(&ctl->count))
329                 kfree(ctl);
330 }
331
332 #ifdef CONFIG_BTRFS_DEBUG
333 static void fragment_free_space(struct btrfs_block_group_cache *block_group)
334 {
335         struct btrfs_fs_info *fs_info = block_group->fs_info;
336         u64 start = block_group->key.objectid;
337         u64 len = block_group->key.offset;
338         u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
339                 fs_info->nodesize : fs_info->sectorsize;
340         u64 step = chunk << 1;
341
342         while (len > chunk) {
343                 btrfs_remove_free_space(block_group, start, chunk);
344                 start += step;
345                 if (len < step)
346                         len = 0;
347                 else
348                         len -= step;
349         }
350 }
351 #endif
352
353 /*
354  * this is only called by cache_block_group, since we could have freed extents
355  * we need to check the pinned_extents for any extents that can't be used yet
356  * since their free space will be released as soon as the transaction commits.
357  */
358 u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
359                        u64 start, u64 end)
360 {
361         struct btrfs_fs_info *info = block_group->fs_info;
362         u64 extent_start, extent_end, size, total_added = 0;
363         int ret;
364
365         while (start < end) {
366                 ret = find_first_extent_bit(info->pinned_extents, start,
367                                             &extent_start, &extent_end,
368                                             EXTENT_DIRTY | EXTENT_UPTODATE,
369                                             NULL);
370                 if (ret)
371                         break;
372
373                 if (extent_start <= start) {
374                         start = extent_end + 1;
375                 } else if (extent_start > start && extent_start < end) {
376                         size = extent_start - start;
377                         total_added += size;
378                         ret = btrfs_add_free_space(block_group, start,
379                                                    size);
380                         BUG_ON(ret); /* -ENOMEM or logic error */
381                         start = extent_end + 1;
382                 } else {
383                         break;
384                 }
385         }
386
387         if (start < end) {
388                 size = end - start;
389                 total_added += size;
390                 ret = btrfs_add_free_space(block_group, start, size);
391                 BUG_ON(ret); /* -ENOMEM or logic error */
392         }
393
394         return total_added;
395 }
396
397 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
398 {
399         struct btrfs_block_group_cache *block_group = caching_ctl->block_group;
400         struct btrfs_fs_info *fs_info = block_group->fs_info;
401         struct btrfs_root *extent_root = fs_info->extent_root;
402         struct btrfs_path *path;
403         struct extent_buffer *leaf;
404         struct btrfs_key key;
405         u64 total_found = 0;
406         u64 last = 0;
407         u32 nritems;
408         int ret;
409         bool wakeup = true;
410
411         path = btrfs_alloc_path();
412         if (!path)
413                 return -ENOMEM;
414
415         last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
416
417 #ifdef CONFIG_BTRFS_DEBUG
418         /*
419          * If we're fragmenting we don't want to make anybody think we can
420          * allocate from this block group until we've had a chance to fragment
421          * the free space.
422          */
423         if (btrfs_should_fragment_free_space(block_group))
424                 wakeup = false;
425 #endif
426         /*
427          * We don't want to deadlock with somebody trying to allocate a new
428          * extent for the extent root while also trying to search the extent
429          * root to add free space.  So we skip locking and search the commit
430          * root, since its read-only
431          */
432         path->skip_locking = 1;
433         path->search_commit_root = 1;
434         path->reada = READA_FORWARD;
435
436         key.objectid = last;
437         key.offset = 0;
438         key.type = BTRFS_EXTENT_ITEM_KEY;
439
440 next:
441         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
442         if (ret < 0)
443                 goto out;
444
445         leaf = path->nodes[0];
446         nritems = btrfs_header_nritems(leaf);
447
448         while (1) {
449                 if (btrfs_fs_closing(fs_info) > 1) {
450                         last = (u64)-1;
451                         break;
452                 }
453
454                 if (path->slots[0] < nritems) {
455                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
456                 } else {
457                         ret = find_next_key(path, 0, &key);
458                         if (ret)
459                                 break;
460
461                         if (need_resched() ||
462                             rwsem_is_contended(&fs_info->commit_root_sem)) {
463                                 if (wakeup)
464                                         caching_ctl->progress = last;
465                                 btrfs_release_path(path);
466                                 up_read(&fs_info->commit_root_sem);
467                                 mutex_unlock(&caching_ctl->mutex);
468                                 cond_resched();
469                                 mutex_lock(&caching_ctl->mutex);
470                                 down_read(&fs_info->commit_root_sem);
471                                 goto next;
472                         }
473
474                         ret = btrfs_next_leaf(extent_root, path);
475                         if (ret < 0)
476                                 goto out;
477                         if (ret)
478                                 break;
479                         leaf = path->nodes[0];
480                         nritems = btrfs_header_nritems(leaf);
481                         continue;
482                 }
483
484                 if (key.objectid < last) {
485                         key.objectid = last;
486                         key.offset = 0;
487                         key.type = BTRFS_EXTENT_ITEM_KEY;
488
489                         if (wakeup)
490                                 caching_ctl->progress = last;
491                         btrfs_release_path(path);
492                         goto next;
493                 }
494
495                 if (key.objectid < block_group->key.objectid) {
496                         path->slots[0]++;
497                         continue;
498                 }
499
500                 if (key.objectid >= block_group->key.objectid +
501                     block_group->key.offset)
502                         break;
503
504                 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
505                     key.type == BTRFS_METADATA_ITEM_KEY) {
506                         total_found += add_new_free_space(block_group, last,
507                                                           key.objectid);
508                         if (key.type == BTRFS_METADATA_ITEM_KEY)
509                                 last = key.objectid +
510                                         fs_info->nodesize;
511                         else
512                                 last = key.objectid + key.offset;
513
514                         if (total_found > CACHING_CTL_WAKE_UP) {
515                                 total_found = 0;
516                                 if (wakeup)
517                                         wake_up(&caching_ctl->wait);
518                         }
519                 }
520                 path->slots[0]++;
521         }
522         ret = 0;
523
524         total_found += add_new_free_space(block_group, last,
525                                           block_group->key.objectid +
526                                           block_group->key.offset);
527         caching_ctl->progress = (u64)-1;
528
529 out:
530         btrfs_free_path(path);
531         return ret;
532 }
533
534 static noinline void caching_thread(struct btrfs_work *work)
535 {
536         struct btrfs_block_group_cache *block_group;
537         struct btrfs_fs_info *fs_info;
538         struct btrfs_caching_control *caching_ctl;
539         int ret;
540
541         caching_ctl = container_of(work, struct btrfs_caching_control, work);
542         block_group = caching_ctl->block_group;
543         fs_info = block_group->fs_info;
544
545         mutex_lock(&caching_ctl->mutex);
546         down_read(&fs_info->commit_root_sem);
547
548         if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
549                 ret = load_free_space_tree(caching_ctl);
550         else
551                 ret = load_extent_tree_free(caching_ctl);
552
553         spin_lock(&block_group->lock);
554         block_group->caching_ctl = NULL;
555         block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
556         spin_unlock(&block_group->lock);
557
558 #ifdef CONFIG_BTRFS_DEBUG
559         if (btrfs_should_fragment_free_space(block_group)) {
560                 u64 bytes_used;
561
562                 spin_lock(&block_group->space_info->lock);
563                 spin_lock(&block_group->lock);
564                 bytes_used = block_group->key.offset -
565                         btrfs_block_group_used(&block_group->item);
566                 block_group->space_info->bytes_used += bytes_used >> 1;
567                 spin_unlock(&block_group->lock);
568                 spin_unlock(&block_group->space_info->lock);
569                 fragment_free_space(block_group);
570         }
571 #endif
572
573         caching_ctl->progress = (u64)-1;
574
575         up_read(&fs_info->commit_root_sem);
576         free_excluded_extents(block_group);
577         mutex_unlock(&caching_ctl->mutex);
578
579         wake_up(&caching_ctl->wait);
580
581         put_caching_control(caching_ctl);
582         btrfs_put_block_group(block_group);
583 }
584
585 static int cache_block_group(struct btrfs_block_group_cache *cache,
586                              int load_cache_only)
587 {
588         DEFINE_WAIT(wait);
589         struct btrfs_fs_info *fs_info = cache->fs_info;
590         struct btrfs_caching_control *caching_ctl;
591         int ret = 0;
592
593         caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
594         if (!caching_ctl)
595                 return -ENOMEM;
596
597         INIT_LIST_HEAD(&caching_ctl->list);
598         mutex_init(&caching_ctl->mutex);
599         init_waitqueue_head(&caching_ctl->wait);
600         caching_ctl->block_group = cache;
601         caching_ctl->progress = cache->key.objectid;
602         refcount_set(&caching_ctl->count, 1);
603         btrfs_init_work(&caching_ctl->work, btrfs_cache_helper,
604                         caching_thread, NULL, NULL);
605
606         spin_lock(&cache->lock);
607         /*
608          * This should be a rare occasion, but this could happen I think in the
609          * case where one thread starts to load the space cache info, and then
610          * some other thread starts a transaction commit which tries to do an
611          * allocation while the other thread is still loading the space cache
612          * info.  The previous loop should have kept us from choosing this block
613          * group, but if we've moved to the state where we will wait on caching
614          * block groups we need to first check if we're doing a fast load here,
615          * so we can wait for it to finish, otherwise we could end up allocating
616          * from a block group who's cache gets evicted for one reason or
617          * another.
618          */
619         while (cache->cached == BTRFS_CACHE_FAST) {
620                 struct btrfs_caching_control *ctl;
621
622                 ctl = cache->caching_ctl;
623                 refcount_inc(&ctl->count);
624                 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
625                 spin_unlock(&cache->lock);
626
627                 schedule();
628
629                 finish_wait(&ctl->wait, &wait);
630                 put_caching_control(ctl);
631                 spin_lock(&cache->lock);
632         }
633
634         if (cache->cached != BTRFS_CACHE_NO) {
635                 spin_unlock(&cache->lock);
636                 kfree(caching_ctl);
637                 return 0;
638         }
639         WARN_ON(cache->caching_ctl);
640         cache->caching_ctl = caching_ctl;
641         cache->cached = BTRFS_CACHE_FAST;
642         spin_unlock(&cache->lock);
643
644         if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
645                 mutex_lock(&caching_ctl->mutex);
646                 ret = load_free_space_cache(cache);
647
648                 spin_lock(&cache->lock);
649                 if (ret == 1) {
650                         cache->caching_ctl = NULL;
651                         cache->cached = BTRFS_CACHE_FINISHED;
652                         cache->last_byte_to_unpin = (u64)-1;
653                         caching_ctl->progress = (u64)-1;
654                 } else {
655                         if (load_cache_only) {
656                                 cache->caching_ctl = NULL;
657                                 cache->cached = BTRFS_CACHE_NO;
658                         } else {
659                                 cache->cached = BTRFS_CACHE_STARTED;
660                                 cache->has_caching_ctl = 1;
661                         }
662                 }
663                 spin_unlock(&cache->lock);
664 #ifdef CONFIG_BTRFS_DEBUG
665                 if (ret == 1 &&
666                     btrfs_should_fragment_free_space(cache)) {
667                         u64 bytes_used;
668
669                         spin_lock(&cache->space_info->lock);
670                         spin_lock(&cache->lock);
671                         bytes_used = cache->key.offset -
672                                 btrfs_block_group_used(&cache->item);
673                         cache->space_info->bytes_used += bytes_used >> 1;
674                         spin_unlock(&cache->lock);
675                         spin_unlock(&cache->space_info->lock);
676                         fragment_free_space(cache);
677                 }
678 #endif
679                 mutex_unlock(&caching_ctl->mutex);
680
681                 wake_up(&caching_ctl->wait);
682                 if (ret == 1) {
683                         put_caching_control(caching_ctl);
684                         free_excluded_extents(cache);
685                         return 0;
686                 }
687         } else {
688                 /*
689                  * We're either using the free space tree or no caching at all.
690                  * Set cached to the appropriate value and wakeup any waiters.
691                  */
692                 spin_lock(&cache->lock);
693                 if (load_cache_only) {
694                         cache->caching_ctl = NULL;
695                         cache->cached = BTRFS_CACHE_NO;
696                 } else {
697                         cache->cached = BTRFS_CACHE_STARTED;
698                         cache->has_caching_ctl = 1;
699                 }
700                 spin_unlock(&cache->lock);
701                 wake_up(&caching_ctl->wait);
702         }
703
704         if (load_cache_only) {
705                 put_caching_control(caching_ctl);
706                 return 0;
707         }
708
709         down_write(&fs_info->commit_root_sem);
710         refcount_inc(&caching_ctl->count);
711         list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
712         up_write(&fs_info->commit_root_sem);
713
714         btrfs_get_block_group(cache);
715
716         btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
717
718         return ret;
719 }
720
721 /*
722  * return the block group that starts at or after bytenr
723  */
724 static struct btrfs_block_group_cache *
725 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
726 {
727         return block_group_cache_tree_search(info, bytenr, 0);
728 }
729
730 /*
731  * return the block group that contains the given bytenr
732  */
733 struct btrfs_block_group_cache *btrfs_lookup_block_group(
734                                                  struct btrfs_fs_info *info,
735                                                  u64 bytenr)
736 {
737         return block_group_cache_tree_search(info, bytenr, 1);
738 }
739
740 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
741                                                   u64 flags)
742 {
743         struct list_head *head = &info->space_info;
744         struct btrfs_space_info *found;
745
746         flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
747
748         rcu_read_lock();
749         list_for_each_entry_rcu(found, head, list) {
750                 if (found->flags & flags) {
751                         rcu_read_unlock();
752                         return found;
753                 }
754         }
755         rcu_read_unlock();
756         return NULL;
757 }
758
759 static void add_pinned_bytes(struct btrfs_fs_info *fs_info,
760                              struct btrfs_ref *ref)
761 {
762         struct btrfs_space_info *space_info;
763         s64 num_bytes = -ref->len;
764         u64 flags;
765
766         if (ref->type == BTRFS_REF_METADATA) {
767                 if (ref->tree_ref.root == BTRFS_CHUNK_TREE_OBJECTID)
768                         flags = BTRFS_BLOCK_GROUP_SYSTEM;
769                 else
770                         flags = BTRFS_BLOCK_GROUP_METADATA;
771         } else {
772                 flags = BTRFS_BLOCK_GROUP_DATA;
773         }
774
775         space_info = __find_space_info(fs_info, flags);
776         ASSERT(space_info);
777         percpu_counter_add_batch(&space_info->total_bytes_pinned, num_bytes,
778                     BTRFS_TOTAL_BYTES_PINNED_BATCH);
779 }
780
781 /*
782  * after adding space to the filesystem, we need to clear the full flags
783  * on all the space infos.
784  */
785 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
786 {
787         struct list_head *head = &info->space_info;
788         struct btrfs_space_info *found;
789
790         rcu_read_lock();
791         list_for_each_entry_rcu(found, head, list)
792                 found->full = 0;
793         rcu_read_unlock();
794 }
795
796 /* simple helper to search for an existing data extent at a given offset */
797 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
798 {
799         int ret;
800         struct btrfs_key key;
801         struct btrfs_path *path;
802
803         path = btrfs_alloc_path();
804         if (!path)
805                 return -ENOMEM;
806
807         key.objectid = start;
808         key.offset = len;
809         key.type = BTRFS_EXTENT_ITEM_KEY;
810         ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
811         btrfs_free_path(path);
812         return ret;
813 }
814
815 /*
816  * helper function to lookup reference count and flags of a tree block.
817  *
818  * the head node for delayed ref is used to store the sum of all the
819  * reference count modifications queued up in the rbtree. the head
820  * node may also store the extent flags to set. This way you can check
821  * to see what the reference count and extent flags would be if all of
822  * the delayed refs are not processed.
823  */
824 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
825                              struct btrfs_fs_info *fs_info, u64 bytenr,
826                              u64 offset, int metadata, u64 *refs, u64 *flags)
827 {
828         struct btrfs_delayed_ref_head *head;
829         struct btrfs_delayed_ref_root *delayed_refs;
830         struct btrfs_path *path;
831         struct btrfs_extent_item *ei;
832         struct extent_buffer *leaf;
833         struct btrfs_key key;
834         u32 item_size;
835         u64 num_refs;
836         u64 extent_flags;
837         int ret;
838
839         /*
840          * If we don't have skinny metadata, don't bother doing anything
841          * different
842          */
843         if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
844                 offset = fs_info->nodesize;
845                 metadata = 0;
846         }
847
848         path = btrfs_alloc_path();
849         if (!path)
850                 return -ENOMEM;
851
852         if (!trans) {
853                 path->skip_locking = 1;
854                 path->search_commit_root = 1;
855         }
856
857 search_again:
858         key.objectid = bytenr;
859         key.offset = offset;
860         if (metadata)
861                 key.type = BTRFS_METADATA_ITEM_KEY;
862         else
863                 key.type = BTRFS_EXTENT_ITEM_KEY;
864
865         ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
866         if (ret < 0)
867                 goto out_free;
868
869         if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
870                 if (path->slots[0]) {
871                         path->slots[0]--;
872                         btrfs_item_key_to_cpu(path->nodes[0], &key,
873                                               path->slots[0]);
874                         if (key.objectid == bytenr &&
875                             key.type == BTRFS_EXTENT_ITEM_KEY &&
876                             key.offset == fs_info->nodesize)
877                                 ret = 0;
878                 }
879         }
880
881         if (ret == 0) {
882                 leaf = path->nodes[0];
883                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
884                 if (item_size >= sizeof(*ei)) {
885                         ei = btrfs_item_ptr(leaf, path->slots[0],
886                                             struct btrfs_extent_item);
887                         num_refs = btrfs_extent_refs(leaf, ei);
888                         extent_flags = btrfs_extent_flags(leaf, ei);
889                 } else {
890                         ret = -EINVAL;
891                         btrfs_print_v0_err(fs_info);
892                         if (trans)
893                                 btrfs_abort_transaction(trans, ret);
894                         else
895                                 btrfs_handle_fs_error(fs_info, ret, NULL);
896
897                         goto out_free;
898                 }
899
900                 BUG_ON(num_refs == 0);
901         } else {
902                 num_refs = 0;
903                 extent_flags = 0;
904                 ret = 0;
905         }
906
907         if (!trans)
908                 goto out;
909
910         delayed_refs = &trans->transaction->delayed_refs;
911         spin_lock(&delayed_refs->lock);
912         head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
913         if (head) {
914                 if (!mutex_trylock(&head->mutex)) {
915                         refcount_inc(&head->refs);
916                         spin_unlock(&delayed_refs->lock);
917
918                         btrfs_release_path(path);
919
920                         /*
921                          * Mutex was contended, block until it's released and try
922                          * again
923                          */
924                         mutex_lock(&head->mutex);
925                         mutex_unlock(&head->mutex);
926                         btrfs_put_delayed_ref_head(head);
927                         goto search_again;
928                 }
929                 spin_lock(&head->lock);
930                 if (head->extent_op && head->extent_op->update_flags)
931                         extent_flags |= head->extent_op->flags_to_set;
932                 else
933                         BUG_ON(num_refs == 0);
934
935                 num_refs += head->ref_mod;
936                 spin_unlock(&head->lock);
937                 mutex_unlock(&head->mutex);
938         }
939         spin_unlock(&delayed_refs->lock);
940 out:
941         WARN_ON(num_refs == 0);
942         if (refs)
943                 *refs = num_refs;
944         if (flags)
945                 *flags = extent_flags;
946 out_free:
947         btrfs_free_path(path);
948         return ret;
949 }
950
951 /*
952  * Back reference rules.  Back refs have three main goals:
953  *
954  * 1) differentiate between all holders of references to an extent so that
955  *    when a reference is dropped we can make sure it was a valid reference
956  *    before freeing the extent.
957  *
958  * 2) Provide enough information to quickly find the holders of an extent
959  *    if we notice a given block is corrupted or bad.
960  *
961  * 3) Make it easy to migrate blocks for FS shrinking or storage pool
962  *    maintenance.  This is actually the same as #2, but with a slightly
963  *    different use case.
964  *
965  * There are two kinds of back refs. The implicit back refs is optimized
966  * for pointers in non-shared tree blocks. For a given pointer in a block,
967  * back refs of this kind provide information about the block's owner tree
968  * and the pointer's key. These information allow us to find the block by
969  * b-tree searching. The full back refs is for pointers in tree blocks not
970  * referenced by their owner trees. The location of tree block is recorded
971  * in the back refs. Actually the full back refs is generic, and can be
972  * used in all cases the implicit back refs is used. The major shortcoming
973  * of the full back refs is its overhead. Every time a tree block gets
974  * COWed, we have to update back refs entry for all pointers in it.
975  *
976  * For a newly allocated tree block, we use implicit back refs for
977  * pointers in it. This means most tree related operations only involve
978  * implicit back refs. For a tree block created in old transaction, the
979  * only way to drop a reference to it is COW it. So we can detect the
980  * event that tree block loses its owner tree's reference and do the
981  * back refs conversion.
982  *
983  * When a tree block is COWed through a tree, there are four cases:
984  *
985  * The reference count of the block is one and the tree is the block's
986  * owner tree. Nothing to do in this case.
987  *
988  * The reference count of the block is one and the tree is not the
989  * block's owner tree. In this case, full back refs is used for pointers
990  * in the block. Remove these full back refs, add implicit back refs for
991  * every pointers in the new block.
992  *
993  * The reference count of the block is greater than one and the tree is
994  * the block's owner tree. In this case, implicit back refs is used for
995  * pointers in the block. Add full back refs for every pointers in the
996  * block, increase lower level extents' reference counts. The original
997  * implicit back refs are entailed to the new block.
998  *
999  * The reference count of the block is greater than one and the tree is
1000  * not the block's owner tree. Add implicit back refs for every pointer in
1001  * the new block, increase lower level extents' reference count.
1002  *
1003  * Back Reference Key composing:
1004  *
1005  * The key objectid corresponds to the first byte in the extent,
1006  * The key type is used to differentiate between types of back refs.
1007  * There are different meanings of the key offset for different types
1008  * of back refs.
1009  *
1010  * File extents can be referenced by:
1011  *
1012  * - multiple snapshots, subvolumes, or different generations in one subvol
1013  * - different files inside a single subvolume
1014  * - different offsets inside a file (bookend extents in file.c)
1015  *
1016  * The extent ref structure for the implicit back refs has fields for:
1017  *
1018  * - Objectid of the subvolume root
1019  * - objectid of the file holding the reference
1020  * - original offset in the file
1021  * - how many bookend extents
1022  *
1023  * The key offset for the implicit back refs is hash of the first
1024  * three fields.
1025  *
1026  * The extent ref structure for the full back refs has field for:
1027  *
1028  * - number of pointers in the tree leaf
1029  *
1030  * The key offset for the implicit back refs is the first byte of
1031  * the tree leaf
1032  *
1033  * When a file extent is allocated, The implicit back refs is used.
1034  * the fields are filled in:
1035  *
1036  *     (root_key.objectid, inode objectid, offset in file, 1)
1037  *
1038  * When a file extent is removed file truncation, we find the
1039  * corresponding implicit back refs and check the following fields:
1040  *
1041  *     (btrfs_header_owner(leaf), inode objectid, offset in file)
1042  *
1043  * Btree extents can be referenced by:
1044  *
1045  * - Different subvolumes
1046  *
1047  * Both the implicit back refs and the full back refs for tree blocks
1048  * only consist of key. The key offset for the implicit back refs is
1049  * objectid of block's owner tree. The key offset for the full back refs
1050  * is the first byte of parent block.
1051  *
1052  * When implicit back refs is used, information about the lowest key and
1053  * level of the tree block are required. These information are stored in
1054  * tree block info structure.
1055  */
1056
1057 /*
1058  * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
1059  * is_data == BTRFS_REF_TYPE_DATA, data type is requiried,
1060  * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
1061  */
1062 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
1063                                      struct btrfs_extent_inline_ref *iref,
1064                                      enum btrfs_inline_ref_type is_data)
1065 {
1066         int type = btrfs_extent_inline_ref_type(eb, iref);
1067         u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
1068
1069         if (type == BTRFS_TREE_BLOCK_REF_KEY ||
1070             type == BTRFS_SHARED_BLOCK_REF_KEY ||
1071             type == BTRFS_SHARED_DATA_REF_KEY ||
1072             type == BTRFS_EXTENT_DATA_REF_KEY) {
1073                 if (is_data == BTRFS_REF_TYPE_BLOCK) {
1074                         if (type == BTRFS_TREE_BLOCK_REF_KEY)
1075                                 return type;
1076                         if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1077                                 ASSERT(eb->fs_info);
1078                                 /*
1079                                  * Every shared one has parent tree
1080                                  * block, which must be aligned to
1081                                  * nodesize.
1082                                  */
1083                                 if (offset &&
1084                                     IS_ALIGNED(offset, eb->fs_info->nodesize))
1085                                         return type;
1086                         }
1087                 } else if (is_data == BTRFS_REF_TYPE_DATA) {
1088                         if (type == BTRFS_EXTENT_DATA_REF_KEY)
1089                                 return type;
1090                         if (type == BTRFS_SHARED_DATA_REF_KEY) {
1091                                 ASSERT(eb->fs_info);
1092                                 /*
1093                                  * Every shared one has parent tree
1094                                  * block, which must be aligned to
1095                                  * nodesize.
1096                                  */
1097                                 if (offset &&
1098                                     IS_ALIGNED(offset, eb->fs_info->nodesize))
1099                                         return type;
1100                         }
1101                 } else {
1102                         ASSERT(is_data == BTRFS_REF_TYPE_ANY);
1103                         return type;
1104                 }
1105         }
1106
1107         btrfs_print_leaf((struct extent_buffer *)eb);
1108         btrfs_err(eb->fs_info, "eb %llu invalid extent inline ref type %d",
1109                   eb->start, type);
1110         WARN_ON(1);
1111
1112         return BTRFS_REF_TYPE_INVALID;
1113 }
1114
1115 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1116 {
1117         u32 high_crc = ~(u32)0;
1118         u32 low_crc = ~(u32)0;
1119         __le64 lenum;
1120
1121         lenum = cpu_to_le64(root_objectid);
1122         high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
1123         lenum = cpu_to_le64(owner);
1124         low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
1125         lenum = cpu_to_le64(offset);
1126         low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
1127
1128         return ((u64)high_crc << 31) ^ (u64)low_crc;
1129 }
1130
1131 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1132                                      struct btrfs_extent_data_ref *ref)
1133 {
1134         return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1135                                     btrfs_extent_data_ref_objectid(leaf, ref),
1136                                     btrfs_extent_data_ref_offset(leaf, ref));
1137 }
1138
1139 static int match_extent_data_ref(struct extent_buffer *leaf,
1140                                  struct btrfs_extent_data_ref *ref,
1141                                  u64 root_objectid, u64 owner, u64 offset)
1142 {
1143         if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1144             btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1145             btrfs_extent_data_ref_offset(leaf, ref) != offset)
1146                 return 0;
1147         return 1;
1148 }
1149
1150 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1151                                            struct btrfs_path *path,
1152                                            u64 bytenr, u64 parent,
1153                                            u64 root_objectid,
1154                                            u64 owner, u64 offset)
1155 {
1156         struct btrfs_root *root = trans->fs_info->extent_root;
1157         struct btrfs_key key;
1158         struct btrfs_extent_data_ref *ref;
1159         struct extent_buffer *leaf;
1160         u32 nritems;
1161         int ret;
1162         int recow;
1163         int err = -ENOENT;
1164
1165         key.objectid = bytenr;
1166         if (parent) {
1167                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1168                 key.offset = parent;
1169         } else {
1170                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1171                 key.offset = hash_extent_data_ref(root_objectid,
1172                                                   owner, offset);
1173         }
1174 again:
1175         recow = 0;
1176         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1177         if (ret < 0) {
1178                 err = ret;
1179                 goto fail;
1180         }
1181
1182         if (parent) {
1183                 if (!ret)
1184                         return 0;
1185                 goto fail;
1186         }
1187
1188         leaf = path->nodes[0];
1189         nritems = btrfs_header_nritems(leaf);
1190         while (1) {
1191                 if (path->slots[0] >= nritems) {
1192                         ret = btrfs_next_leaf(root, path);
1193                         if (ret < 0)
1194                                 err = ret;
1195                         if (ret)
1196                                 goto fail;
1197
1198                         leaf = path->nodes[0];
1199                         nritems = btrfs_header_nritems(leaf);
1200                         recow = 1;
1201                 }
1202
1203                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1204                 if (key.objectid != bytenr ||
1205                     key.type != BTRFS_EXTENT_DATA_REF_KEY)
1206                         goto fail;
1207
1208                 ref = btrfs_item_ptr(leaf, path->slots[0],
1209                                      struct btrfs_extent_data_ref);
1210
1211                 if (match_extent_data_ref(leaf, ref, root_objectid,
1212                                           owner, offset)) {
1213                         if (recow) {
1214                                 btrfs_release_path(path);
1215                                 goto again;
1216                         }
1217                         err = 0;
1218                         break;
1219                 }
1220                 path->slots[0]++;
1221         }
1222 fail:
1223         return err;
1224 }
1225
1226 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1227                                            struct btrfs_path *path,
1228                                            u64 bytenr, u64 parent,
1229                                            u64 root_objectid, u64 owner,
1230                                            u64 offset, int refs_to_add)
1231 {
1232         struct btrfs_root *root = trans->fs_info->extent_root;
1233         struct btrfs_key key;
1234         struct extent_buffer *leaf;
1235         u32 size;
1236         u32 num_refs;
1237         int ret;
1238
1239         key.objectid = bytenr;
1240         if (parent) {
1241                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1242                 key.offset = parent;
1243                 size = sizeof(struct btrfs_shared_data_ref);
1244         } else {
1245                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1246                 key.offset = hash_extent_data_ref(root_objectid,
1247                                                   owner, offset);
1248                 size = sizeof(struct btrfs_extent_data_ref);
1249         }
1250
1251         ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1252         if (ret && ret != -EEXIST)
1253                 goto fail;
1254
1255         leaf = path->nodes[0];
1256         if (parent) {
1257                 struct btrfs_shared_data_ref *ref;
1258                 ref = btrfs_item_ptr(leaf, path->slots[0],
1259                                      struct btrfs_shared_data_ref);
1260                 if (ret == 0) {
1261                         btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1262                 } else {
1263                         num_refs = btrfs_shared_data_ref_count(leaf, ref);
1264                         num_refs += refs_to_add;
1265                         btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1266                 }
1267         } else {
1268                 struct btrfs_extent_data_ref *ref;
1269                 while (ret == -EEXIST) {
1270                         ref = btrfs_item_ptr(leaf, path->slots[0],
1271                                              struct btrfs_extent_data_ref);
1272                         if (match_extent_data_ref(leaf, ref, root_objectid,
1273                                                   owner, offset))
1274                                 break;
1275                         btrfs_release_path(path);
1276                         key.offset++;
1277                         ret = btrfs_insert_empty_item(trans, root, path, &key,
1278                                                       size);
1279                         if (ret && ret != -EEXIST)
1280                                 goto fail;
1281
1282                         leaf = path->nodes[0];
1283                 }
1284                 ref = btrfs_item_ptr(leaf, path->slots[0],
1285                                      struct btrfs_extent_data_ref);
1286                 if (ret == 0) {
1287                         btrfs_set_extent_data_ref_root(leaf, ref,
1288                                                        root_objectid);
1289                         btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1290                         btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1291                         btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1292                 } else {
1293                         num_refs = btrfs_extent_data_ref_count(leaf, ref);
1294                         num_refs += refs_to_add;
1295                         btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1296                 }
1297         }
1298         btrfs_mark_buffer_dirty(leaf);
1299         ret = 0;
1300 fail:
1301         btrfs_release_path(path);
1302         return ret;
1303 }
1304
1305 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1306                                            struct btrfs_path *path,
1307                                            int refs_to_drop, int *last_ref)
1308 {
1309         struct btrfs_key key;
1310         struct btrfs_extent_data_ref *ref1 = NULL;
1311         struct btrfs_shared_data_ref *ref2 = NULL;
1312         struct extent_buffer *leaf;
1313         u32 num_refs = 0;
1314         int ret = 0;
1315
1316         leaf = path->nodes[0];
1317         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1318
1319         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1320                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1321                                       struct btrfs_extent_data_ref);
1322                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1323         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1324                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1325                                       struct btrfs_shared_data_ref);
1326                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1327         } else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
1328                 btrfs_print_v0_err(trans->fs_info);
1329                 btrfs_abort_transaction(trans, -EINVAL);
1330                 return -EINVAL;
1331         } else {
1332                 BUG();
1333         }
1334
1335         BUG_ON(num_refs < refs_to_drop);
1336         num_refs -= refs_to_drop;
1337
1338         if (num_refs == 0) {
1339                 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1340                 *last_ref = 1;
1341         } else {
1342                 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1343                         btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1344                 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1345                         btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1346                 btrfs_mark_buffer_dirty(leaf);
1347         }
1348         return ret;
1349 }
1350
1351 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
1352                                           struct btrfs_extent_inline_ref *iref)
1353 {
1354         struct btrfs_key key;
1355         struct extent_buffer *leaf;
1356         struct btrfs_extent_data_ref *ref1;
1357         struct btrfs_shared_data_ref *ref2;
1358         u32 num_refs = 0;
1359         int type;
1360
1361         leaf = path->nodes[0];
1362         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1363
1364         BUG_ON(key.type == BTRFS_EXTENT_REF_V0_KEY);
1365         if (iref) {
1366                 /*
1367                  * If type is invalid, we should have bailed out earlier than
1368                  * this call.
1369                  */
1370                 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
1371                 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1372                 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1373                         ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1374                         num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1375                 } else {
1376                         ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1377                         num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1378                 }
1379         } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1380                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1381                                       struct btrfs_extent_data_ref);
1382                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1383         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1384                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1385                                       struct btrfs_shared_data_ref);
1386                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1387         } else {
1388                 WARN_ON(1);
1389         }
1390         return num_refs;
1391 }
1392
1393 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1394                                           struct btrfs_path *path,
1395                                           u64 bytenr, u64 parent,
1396                                           u64 root_objectid)
1397 {
1398         struct btrfs_root *root = trans->fs_info->extent_root;
1399         struct btrfs_key key;
1400         int ret;
1401
1402         key.objectid = bytenr;
1403         if (parent) {
1404                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1405                 key.offset = parent;
1406         } else {
1407                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1408                 key.offset = root_objectid;
1409         }
1410
1411         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1412         if (ret > 0)
1413                 ret = -ENOENT;
1414         return ret;
1415 }
1416
1417 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1418                                           struct btrfs_path *path,
1419                                           u64 bytenr, u64 parent,
1420                                           u64 root_objectid)
1421 {
1422         struct btrfs_key key;
1423         int ret;
1424
1425         key.objectid = bytenr;
1426         if (parent) {
1427                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1428                 key.offset = parent;
1429         } else {
1430                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1431                 key.offset = root_objectid;
1432         }
1433
1434         ret = btrfs_insert_empty_item(trans, trans->fs_info->extent_root,
1435                                       path, &key, 0);
1436         btrfs_release_path(path);
1437         return ret;
1438 }
1439
1440 static inline int extent_ref_type(u64 parent, u64 owner)
1441 {
1442         int type;
1443         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1444                 if (parent > 0)
1445                         type = BTRFS_SHARED_BLOCK_REF_KEY;
1446                 else
1447                         type = BTRFS_TREE_BLOCK_REF_KEY;
1448         } else {
1449                 if (parent > 0)
1450                         type = BTRFS_SHARED_DATA_REF_KEY;
1451                 else
1452                         type = BTRFS_EXTENT_DATA_REF_KEY;
1453         }
1454         return type;
1455 }
1456
1457 static int find_next_key(struct btrfs_path *path, int level,
1458                          struct btrfs_key *key)
1459
1460 {
1461         for (; level < BTRFS_MAX_LEVEL; level++) {
1462                 if (!path->nodes[level])
1463                         break;
1464                 if (path->slots[level] + 1 >=
1465                     btrfs_header_nritems(path->nodes[level]))
1466                         continue;
1467                 if (level == 0)
1468                         btrfs_item_key_to_cpu(path->nodes[level], key,
1469                                               path->slots[level] + 1);
1470                 else
1471                         btrfs_node_key_to_cpu(path->nodes[level], key,
1472                                               path->slots[level] + 1);
1473                 return 0;
1474         }
1475         return 1;
1476 }
1477
1478 /*
1479  * look for inline back ref. if back ref is found, *ref_ret is set
1480  * to the address of inline back ref, and 0 is returned.
1481  *
1482  * if back ref isn't found, *ref_ret is set to the address where it
1483  * should be inserted, and -ENOENT is returned.
1484  *
1485  * if insert is true and there are too many inline back refs, the path
1486  * points to the extent item, and -EAGAIN is returned.
1487  *
1488  * NOTE: inline back refs are ordered in the same way that back ref
1489  *       items in the tree are ordered.
1490  */
1491 static noinline_for_stack
1492 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1493                                  struct btrfs_path *path,
1494                                  struct btrfs_extent_inline_ref **ref_ret,
1495                                  u64 bytenr, u64 num_bytes,
1496                                  u64 parent, u64 root_objectid,
1497                                  u64 owner, u64 offset, int insert)
1498 {
1499         struct btrfs_fs_info *fs_info = trans->fs_info;
1500         struct btrfs_root *root = fs_info->extent_root;
1501         struct btrfs_key key;
1502         struct extent_buffer *leaf;
1503         struct btrfs_extent_item *ei;
1504         struct btrfs_extent_inline_ref *iref;
1505         u64 flags;
1506         u64 item_size;
1507         unsigned long ptr;
1508         unsigned long end;
1509         int extra_size;
1510         int type;
1511         int want;
1512         int ret;
1513         int err = 0;
1514         bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
1515         int needed;
1516
1517         key.objectid = bytenr;
1518         key.type = BTRFS_EXTENT_ITEM_KEY;
1519         key.offset = num_bytes;
1520
1521         want = extent_ref_type(parent, owner);
1522         if (insert) {
1523                 extra_size = btrfs_extent_inline_ref_size(want);
1524                 path->keep_locks = 1;
1525         } else
1526                 extra_size = -1;
1527
1528         /*
1529          * Owner is our level, so we can just add one to get the level for the
1530          * block we are interested in.
1531          */
1532         if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1533                 key.type = BTRFS_METADATA_ITEM_KEY;
1534                 key.offset = owner;
1535         }
1536
1537 again:
1538         ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1539         if (ret < 0) {
1540                 err = ret;
1541                 goto out;
1542         }
1543
1544         /*
1545          * We may be a newly converted file system which still has the old fat
1546          * extent entries for metadata, so try and see if we have one of those.
1547          */
1548         if (ret > 0 && skinny_metadata) {
1549                 skinny_metadata = false;
1550                 if (path->slots[0]) {
1551                         path->slots[0]--;
1552                         btrfs_item_key_to_cpu(path->nodes[0], &key,
1553                                               path->slots[0]);
1554                         if (key.objectid == bytenr &&
1555                             key.type == BTRFS_EXTENT_ITEM_KEY &&
1556                             key.offset == num_bytes)
1557                                 ret = 0;
1558                 }
1559                 if (ret) {
1560                         key.objectid = bytenr;
1561                         key.type = BTRFS_EXTENT_ITEM_KEY;
1562                         key.offset = num_bytes;
1563                         btrfs_release_path(path);
1564                         goto again;
1565                 }
1566         }
1567
1568         if (ret && !insert) {
1569                 err = -ENOENT;
1570                 goto out;
1571         } else if (WARN_ON(ret)) {
1572                 err = -EIO;
1573                 goto out;
1574         }
1575
1576         leaf = path->nodes[0];
1577         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1578         if (unlikely(item_size < sizeof(*ei))) {
1579                 err = -EINVAL;
1580                 btrfs_print_v0_err(fs_info);
1581                 btrfs_abort_transaction(trans, err);
1582                 goto out;
1583         }
1584
1585         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1586         flags = btrfs_extent_flags(leaf, ei);
1587
1588         ptr = (unsigned long)(ei + 1);
1589         end = (unsigned long)ei + item_size;
1590
1591         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
1592                 ptr += sizeof(struct btrfs_tree_block_info);
1593                 BUG_ON(ptr > end);
1594         }
1595
1596         if (owner >= BTRFS_FIRST_FREE_OBJECTID)
1597                 needed = BTRFS_REF_TYPE_DATA;
1598         else
1599                 needed = BTRFS_REF_TYPE_BLOCK;
1600
1601         err = -ENOENT;
1602         while (1) {
1603                 if (ptr >= end) {
1604                         WARN_ON(ptr > end);
1605                         break;
1606                 }
1607                 iref = (struct btrfs_extent_inline_ref *)ptr;
1608                 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
1609                 if (type == BTRFS_REF_TYPE_INVALID) {
1610                         err = -EUCLEAN;
1611                         goto out;
1612                 }
1613
1614                 if (want < type)
1615                         break;
1616                 if (want > type) {
1617                         ptr += btrfs_extent_inline_ref_size(type);
1618                         continue;
1619                 }
1620
1621                 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1622                         struct btrfs_extent_data_ref *dref;
1623                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1624                         if (match_extent_data_ref(leaf, dref, root_objectid,
1625                                                   owner, offset)) {
1626                                 err = 0;
1627                                 break;
1628                         }
1629                         if (hash_extent_data_ref_item(leaf, dref) <
1630                             hash_extent_data_ref(root_objectid, owner, offset))
1631                                 break;
1632                 } else {
1633                         u64 ref_offset;
1634                         ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1635                         if (parent > 0) {
1636                                 if (parent == ref_offset) {
1637                                         err = 0;
1638                                         break;
1639                                 }
1640                                 if (ref_offset < parent)
1641                                         break;
1642                         } else {
1643                                 if (root_objectid == ref_offset) {
1644                                         err = 0;
1645                                         break;
1646                                 }
1647                                 if (ref_offset < root_objectid)
1648                                         break;
1649                         }
1650                 }
1651                 ptr += btrfs_extent_inline_ref_size(type);
1652         }
1653         if (err == -ENOENT && insert) {
1654                 if (item_size + extra_size >=
1655                     BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1656                         err = -EAGAIN;
1657                         goto out;
1658                 }
1659                 /*
1660                  * To add new inline back ref, we have to make sure
1661                  * there is no corresponding back ref item.
1662                  * For simplicity, we just do not add new inline back
1663                  * ref if there is any kind of item for this block
1664                  */
1665                 if (find_next_key(path, 0, &key) == 0 &&
1666                     key.objectid == bytenr &&
1667                     key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1668                         err = -EAGAIN;
1669                         goto out;
1670                 }
1671         }
1672         *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1673 out:
1674         if (insert) {
1675                 path->keep_locks = 0;
1676                 btrfs_unlock_up_safe(path, 1);
1677         }
1678         return err;
1679 }
1680
1681 /*
1682  * helper to add new inline back ref
1683  */
1684 static noinline_for_stack
1685 void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
1686                                  struct btrfs_path *path,
1687                                  struct btrfs_extent_inline_ref *iref,
1688                                  u64 parent, u64 root_objectid,
1689                                  u64 owner, u64 offset, int refs_to_add,
1690                                  struct btrfs_delayed_extent_op *extent_op)
1691 {
1692         struct extent_buffer *leaf;
1693         struct btrfs_extent_item *ei;
1694         unsigned long ptr;
1695         unsigned long end;
1696         unsigned long item_offset;
1697         u64 refs;
1698         int size;
1699         int type;
1700
1701         leaf = path->nodes[0];
1702         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1703         item_offset = (unsigned long)iref - (unsigned long)ei;
1704
1705         type = extent_ref_type(parent, owner);
1706         size = btrfs_extent_inline_ref_size(type);
1707
1708         btrfs_extend_item(fs_info, path, size);
1709
1710         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1711         refs = btrfs_extent_refs(leaf, ei);
1712         refs += refs_to_add;
1713         btrfs_set_extent_refs(leaf, ei, refs);
1714         if (extent_op)
1715                 __run_delayed_extent_op(extent_op, leaf, ei);
1716
1717         ptr = (unsigned long)ei + item_offset;
1718         end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1719         if (ptr < end - size)
1720                 memmove_extent_buffer(leaf, ptr + size, ptr,
1721                                       end - size - ptr);
1722
1723         iref = (struct btrfs_extent_inline_ref *)ptr;
1724         btrfs_set_extent_inline_ref_type(leaf, iref, type);
1725         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1726                 struct btrfs_extent_data_ref *dref;
1727                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1728                 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1729                 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1730                 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1731                 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1732         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1733                 struct btrfs_shared_data_ref *sref;
1734                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1735                 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1736                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1737         } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1738                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1739         } else {
1740                 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1741         }
1742         btrfs_mark_buffer_dirty(leaf);
1743 }
1744
1745 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1746                                  struct btrfs_path *path,
1747                                  struct btrfs_extent_inline_ref **ref_ret,
1748                                  u64 bytenr, u64 num_bytes, u64 parent,
1749                                  u64 root_objectid, u64 owner, u64 offset)
1750 {
1751         int ret;
1752
1753         ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1754                                            num_bytes, parent, root_objectid,
1755                                            owner, offset, 0);
1756         if (ret != -ENOENT)
1757                 return ret;
1758
1759         btrfs_release_path(path);
1760         *ref_ret = NULL;
1761
1762         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1763                 ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1764                                             root_objectid);
1765         } else {
1766                 ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1767                                              root_objectid, owner, offset);
1768         }
1769         return ret;
1770 }
1771
1772 /*
1773  * helper to update/remove inline back ref
1774  */
1775 static noinline_for_stack
1776 void update_inline_extent_backref(struct btrfs_path *path,
1777                                   struct btrfs_extent_inline_ref *iref,
1778                                   int refs_to_mod,
1779                                   struct btrfs_delayed_extent_op *extent_op,
1780                                   int *last_ref)
1781 {
1782         struct extent_buffer *leaf = path->nodes[0];
1783         struct btrfs_extent_item *ei;
1784         struct btrfs_extent_data_ref *dref = NULL;
1785         struct btrfs_shared_data_ref *sref = NULL;
1786         unsigned long ptr;
1787         unsigned long end;
1788         u32 item_size;
1789         int size;
1790         int type;
1791         u64 refs;
1792
1793         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1794         refs = btrfs_extent_refs(leaf, ei);
1795         WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1796         refs += refs_to_mod;
1797         btrfs_set_extent_refs(leaf, ei, refs);
1798         if (extent_op)
1799                 __run_delayed_extent_op(extent_op, leaf, ei);
1800
1801         /*
1802          * If type is invalid, we should have bailed out after
1803          * lookup_inline_extent_backref().
1804          */
1805         type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1806         ASSERT(type != BTRFS_REF_TYPE_INVALID);
1807
1808         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1809                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1810                 refs = btrfs_extent_data_ref_count(leaf, dref);
1811         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1812                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1813                 refs = btrfs_shared_data_ref_count(leaf, sref);
1814         } else {
1815                 refs = 1;
1816                 BUG_ON(refs_to_mod != -1);
1817         }
1818
1819         BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1820         refs += refs_to_mod;
1821
1822         if (refs > 0) {
1823                 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1824                         btrfs_set_extent_data_ref_count(leaf, dref, refs);
1825                 else
1826                         btrfs_set_shared_data_ref_count(leaf, sref, refs);
1827         } else {
1828                 *last_ref = 1;
1829                 size =  btrfs_extent_inline_ref_size(type);
1830                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1831                 ptr = (unsigned long)iref;
1832                 end = (unsigned long)ei + item_size;
1833                 if (ptr + size < end)
1834                         memmove_extent_buffer(leaf, ptr, ptr + size,
1835                                               end - ptr - size);
1836                 item_size -= size;
1837                 btrfs_truncate_item(path, item_size, 1);
1838         }
1839         btrfs_mark_buffer_dirty(leaf);
1840 }
1841
1842 static noinline_for_stack
1843 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1844                                  struct btrfs_path *path,
1845                                  u64 bytenr, u64 num_bytes, u64 parent,
1846                                  u64 root_objectid, u64 owner,
1847                                  u64 offset, int refs_to_add,
1848                                  struct btrfs_delayed_extent_op *extent_op)
1849 {
1850         struct btrfs_extent_inline_ref *iref;
1851         int ret;
1852
1853         ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1854                                            num_bytes, parent, root_objectid,
1855                                            owner, offset, 1);
1856         if (ret == 0) {
1857                 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1858                 update_inline_extent_backref(path, iref, refs_to_add,
1859                                              extent_op, NULL);
1860         } else if (ret == -ENOENT) {
1861                 setup_inline_extent_backref(trans->fs_info, path, iref, parent,
1862                                             root_objectid, owner, offset,
1863                                             refs_to_add, extent_op);
1864                 ret = 0;
1865         }
1866         return ret;
1867 }
1868
1869 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1870                                  struct btrfs_path *path,
1871                                  u64 bytenr, u64 parent, u64 root_objectid,
1872                                  u64 owner, u64 offset, int refs_to_add)
1873 {
1874         int ret;
1875         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1876                 BUG_ON(refs_to_add != 1);
1877                 ret = insert_tree_block_ref(trans, path, bytenr, parent,
1878                                             root_objectid);
1879         } else {
1880                 ret = insert_extent_data_ref(trans, path, bytenr, parent,
1881                                              root_objectid, owner, offset,
1882                                              refs_to_add);
1883         }
1884         return ret;
1885 }
1886
1887 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1888                                  struct btrfs_path *path,
1889                                  struct btrfs_extent_inline_ref *iref,
1890                                  int refs_to_drop, int is_data, int *last_ref)
1891 {
1892         int ret = 0;
1893
1894         BUG_ON(!is_data && refs_to_drop != 1);
1895         if (iref) {
1896                 update_inline_extent_backref(path, iref, -refs_to_drop, NULL,
1897                                              last_ref);
1898         } else if (is_data) {
1899                 ret = remove_extent_data_ref(trans, path, refs_to_drop,
1900                                              last_ref);
1901         } else {
1902                 *last_ref = 1;
1903                 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1904         }
1905         return ret;
1906 }
1907
1908 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1909                                u64 *discarded_bytes)
1910 {
1911         int j, ret = 0;
1912         u64 bytes_left, end;
1913         u64 aligned_start = ALIGN(start, 1 << 9);
1914
1915         if (WARN_ON(start != aligned_start)) {
1916                 len -= aligned_start - start;
1917                 len = round_down(len, 1 << 9);
1918                 start = aligned_start;
1919         }
1920
1921         *discarded_bytes = 0;
1922
1923         if (!len)
1924                 return 0;
1925
1926         end = start + len;
1927         bytes_left = len;
1928
1929         /* Skip any superblocks on this device. */
1930         for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1931                 u64 sb_start = btrfs_sb_offset(j);
1932                 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1933                 u64 size = sb_start - start;
1934
1935                 if (!in_range(sb_start, start, bytes_left) &&
1936                     !in_range(sb_end, start, bytes_left) &&
1937                     !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1938                         continue;
1939
1940                 /*
1941                  * Superblock spans beginning of range.  Adjust start and
1942                  * try again.
1943                  */
1944                 if (sb_start <= start) {
1945                         start += sb_end - start;
1946                         if (start > end) {
1947                                 bytes_left = 0;
1948                                 break;
1949                         }
1950                         bytes_left = end - start;
1951                         continue;
1952                 }
1953
1954                 if (size) {
1955                         ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1956                                                    GFP_NOFS, 0);
1957                         if (!ret)
1958                                 *discarded_bytes += size;
1959                         else if (ret != -EOPNOTSUPP)
1960                                 return ret;
1961                 }
1962
1963                 start = sb_end;
1964                 if (start > end) {
1965                         bytes_left = 0;
1966                         break;
1967                 }
1968                 bytes_left = end - start;
1969         }
1970
1971         if (bytes_left) {
1972                 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
1973                                            GFP_NOFS, 0);
1974                 if (!ret)
1975                         *discarded_bytes += bytes_left;
1976         }
1977         return ret;
1978 }
1979
1980 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1981                          u64 num_bytes, u64 *actual_bytes)
1982 {
1983         int ret;
1984         u64 discarded_bytes = 0;
1985         struct btrfs_bio *bbio = NULL;
1986
1987
1988         /*
1989          * Avoid races with device replace and make sure our bbio has devices
1990          * associated to its stripes that don't go away while we are discarding.
1991          */
1992         btrfs_bio_counter_inc_blocked(fs_info);
1993         /* Tell the block device(s) that the sectors can be discarded */
1994         ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, bytenr, &num_bytes,
1995                               &bbio, 0);
1996         /* Error condition is -ENOMEM */
1997         if (!ret) {
1998                 struct btrfs_bio_stripe *stripe = bbio->stripes;
1999                 int i;
2000
2001
2002                 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
2003                         u64 bytes;
2004                         struct request_queue *req_q;
2005
2006                         if (!stripe->dev->bdev) {
2007                                 ASSERT(btrfs_test_opt(fs_info, DEGRADED));
2008                                 continue;
2009                         }
2010                         req_q = bdev_get_queue(stripe->dev->bdev);
2011                         if (!blk_queue_discard(req_q))
2012                                 continue;
2013
2014                         ret = btrfs_issue_discard(stripe->dev->bdev,
2015                                                   stripe->physical,
2016                                                   stripe->length,
2017                                                   &bytes);
2018                         if (!ret)
2019                                 discarded_bytes += bytes;
2020                         else if (ret != -EOPNOTSUPP)
2021                                 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
2022
2023                         /*
2024                          * Just in case we get back EOPNOTSUPP for some reason,
2025                          * just ignore the return value so we don't screw up
2026                          * people calling discard_extent.
2027                          */
2028                         ret = 0;
2029                 }
2030                 btrfs_put_bbio(bbio);
2031         }
2032         btrfs_bio_counter_dec(fs_info);
2033
2034         if (actual_bytes)
2035                 *actual_bytes = discarded_bytes;
2036
2037
2038         if (ret == -EOPNOTSUPP)
2039                 ret = 0;
2040         return ret;
2041 }
2042
2043 /* Can return -ENOMEM */
2044 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2045                          struct btrfs_ref *generic_ref)
2046 {
2047         struct btrfs_fs_info *fs_info = trans->fs_info;
2048         int old_ref_mod, new_ref_mod;
2049         int ret;
2050
2051         ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
2052                generic_ref->action);
2053         BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
2054                generic_ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID);
2055
2056         if (generic_ref->type == BTRFS_REF_METADATA)
2057                 ret = btrfs_add_delayed_tree_ref(trans, generic_ref,
2058                                 NULL, &old_ref_mod, &new_ref_mod);
2059         else
2060                 ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0,
2061                                                  &old_ref_mod, &new_ref_mod);
2062
2063         btrfs_ref_tree_mod(fs_info, generic_ref);
2064
2065         if (ret == 0 && old_ref_mod < 0 && new_ref_mod >= 0)
2066                 add_pinned_bytes(fs_info, generic_ref);
2067
2068         return ret;
2069 }
2070
2071 /*
2072  * __btrfs_inc_extent_ref - insert backreference for a given extent
2073  *
2074  * @trans:          Handle of transaction
2075  *
2076  * @node:           The delayed ref node used to get the bytenr/length for
2077  *                  extent whose references are incremented.
2078  *
2079  * @parent:         If this is a shared extent (BTRFS_SHARED_DATA_REF_KEY/
2080  *                  BTRFS_SHARED_BLOCK_REF_KEY) then it holds the logical
2081  *                  bytenr of the parent block. Since new extents are always
2082  *                  created with indirect references, this will only be the case
2083  *                  when relocating a shared extent. In that case, root_objectid
2084  *                  will be BTRFS_TREE_RELOC_OBJECTID. Otheriwse, parent must
2085  *                  be 0
2086  *
2087  * @root_objectid:  The id of the root where this modification has originated,
2088  *                  this can be either one of the well-known metadata trees or
2089  *                  the subvolume id which references this extent.
2090  *
2091  * @owner:          For data extents it is the inode number of the owning file.
2092  *                  For metadata extents this parameter holds the level in the
2093  *                  tree of the extent.
2094  *
2095  * @offset:         For metadata extents the offset is ignored and is currently
2096  *                  always passed as 0. For data extents it is the fileoffset
2097  *                  this extent belongs to.
2098  *
2099  * @refs_to_add     Number of references to add
2100  *
2101  * @extent_op       Pointer to a structure, holding information necessary when
2102  *                  updating a tree block's flags
2103  *
2104  */
2105 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2106                                   struct btrfs_delayed_ref_node *node,
2107                                   u64 parent, u64 root_objectid,
2108                                   u64 owner, u64 offset, int refs_to_add,
2109                                   struct btrfs_delayed_extent_op *extent_op)
2110 {
2111         struct btrfs_path *path;
2112         struct extent_buffer *leaf;
2113         struct btrfs_extent_item *item;
2114         struct btrfs_key key;
2115         u64 bytenr = node->bytenr;
2116         u64 num_bytes = node->num_bytes;
2117         u64 refs;
2118         int ret;
2119
2120         path = btrfs_alloc_path();
2121         if (!path)
2122                 return -ENOMEM;
2123
2124         path->reada = READA_FORWARD;
2125         path->leave_spinning = 1;
2126         /* this will setup the path even if it fails to insert the back ref */
2127         ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
2128                                            parent, root_objectid, owner,
2129                                            offset, refs_to_add, extent_op);
2130         if ((ret < 0 && ret != -EAGAIN) || !ret)
2131                 goto out;
2132
2133         /*
2134          * Ok we had -EAGAIN which means we didn't have space to insert and
2135          * inline extent ref, so just update the reference count and add a
2136          * normal backref.
2137          */
2138         leaf = path->nodes[0];
2139         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2140         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2141         refs = btrfs_extent_refs(leaf, item);
2142         btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2143         if (extent_op)
2144                 __run_delayed_extent_op(extent_op, leaf, item);
2145
2146         btrfs_mark_buffer_dirty(leaf);
2147         btrfs_release_path(path);
2148
2149         path->reada = READA_FORWARD;
2150         path->leave_spinning = 1;
2151         /* now insert the actual backref */
2152         ret = insert_extent_backref(trans, path, bytenr, parent, root_objectid,
2153                                     owner, offset, refs_to_add);
2154         if (ret)
2155                 btrfs_abort_transaction(trans, ret);
2156 out:
2157         btrfs_free_path(path);
2158         return ret;
2159 }
2160
2161 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2162                                 struct btrfs_delayed_ref_node *node,
2163                                 struct btrfs_delayed_extent_op *extent_op,
2164                                 int insert_reserved)
2165 {
2166         int ret = 0;
2167         struct btrfs_delayed_data_ref *ref;
2168         struct btrfs_key ins;
2169         u64 parent = 0;
2170         u64 ref_root = 0;
2171         u64 flags = 0;
2172
2173         ins.objectid = node->bytenr;
2174         ins.offset = node->num_bytes;
2175         ins.type = BTRFS_EXTENT_ITEM_KEY;
2176
2177         ref = btrfs_delayed_node_to_data_ref(node);
2178         trace_run_delayed_data_ref(trans->fs_info, node, ref, node->action);
2179
2180         if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2181                 parent = ref->parent;
2182         ref_root = ref->root;
2183
2184         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2185                 if (extent_op)
2186                         flags |= extent_op->flags_to_set;
2187                 ret = alloc_reserved_file_extent(trans, parent, ref_root,
2188                                                  flags, ref->objectid,
2189                                                  ref->offset, &ins,
2190                                                  node->ref_mod);
2191         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2192                 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2193                                              ref->objectid, ref->offset,
2194                                              node->ref_mod, extent_op);
2195         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2196                 ret = __btrfs_free_extent(trans, node, parent,
2197                                           ref_root, ref->objectid,
2198                                           ref->offset, node->ref_mod,
2199                                           extent_op);
2200         } else {
2201                 BUG();
2202         }
2203         return ret;
2204 }
2205
2206 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2207                                     struct extent_buffer *leaf,
2208                                     struct btrfs_extent_item *ei)
2209 {
2210         u64 flags = btrfs_extent_flags(leaf, ei);
2211         if (extent_op->update_flags) {
2212                 flags |= extent_op->flags_to_set;
2213                 btrfs_set_extent_flags(leaf, ei, flags);
2214         }
2215
2216         if (extent_op->update_key) {
2217                 struct btrfs_tree_block_info *bi;
2218                 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2219                 bi = (struct btrfs_tree_block_info *)(ei + 1);
2220                 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2221         }
2222 }
2223
2224 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2225                                  struct btrfs_delayed_ref_head *head,
2226                                  struct btrfs_delayed_extent_op *extent_op)
2227 {
2228         struct btrfs_fs_info *fs_info = trans->fs_info;
2229         struct btrfs_key key;
2230         struct btrfs_path *path;
2231         struct btrfs_extent_item *ei;
2232         struct extent_buffer *leaf;
2233         u32 item_size;
2234         int ret;
2235         int err = 0;
2236         int metadata = !extent_op->is_data;
2237
2238         if (trans->aborted)
2239                 return 0;
2240
2241         if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2242                 metadata = 0;
2243
2244         path = btrfs_alloc_path();
2245         if (!path)
2246                 return -ENOMEM;
2247
2248         key.objectid = head->bytenr;
2249
2250         if (metadata) {
2251                 key.type = BTRFS_METADATA_ITEM_KEY;
2252                 key.offset = extent_op->level;
2253         } else {
2254                 key.type = BTRFS_EXTENT_ITEM_KEY;
2255                 key.offset = head->num_bytes;
2256         }
2257
2258 again:
2259         path->reada = READA_FORWARD;
2260         path->leave_spinning = 1;
2261         ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
2262         if (ret < 0) {
2263                 err = ret;
2264                 goto out;
2265         }
2266         if (ret > 0) {
2267                 if (metadata) {
2268                         if (path->slots[0] > 0) {
2269                                 path->slots[0]--;
2270                                 btrfs_item_key_to_cpu(path->nodes[0], &key,
2271                                                       path->slots[0]);
2272                                 if (key.objectid == head->bytenr &&
2273                                     key.type == BTRFS_EXTENT_ITEM_KEY &&
2274                                     key.offset == head->num_bytes)
2275                                         ret = 0;
2276                         }
2277                         if (ret > 0) {
2278                                 btrfs_release_path(path);
2279                                 metadata = 0;
2280
2281                                 key.objectid = head->bytenr;
2282                                 key.offset = head->num_bytes;
2283                                 key.type = BTRFS_EXTENT_ITEM_KEY;
2284                                 goto again;
2285                         }
2286                 } else {
2287                         err = -EIO;
2288                         goto out;
2289                 }
2290         }
2291
2292         leaf = path->nodes[0];
2293         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2294
2295         if (unlikely(item_size < sizeof(*ei))) {
2296                 err = -EINVAL;
2297                 btrfs_print_v0_err(fs_info);
2298                 btrfs_abort_transaction(trans, err);
2299                 goto out;
2300         }
2301
2302         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2303         __run_delayed_extent_op(extent_op, leaf, ei);
2304
2305         btrfs_mark_buffer_dirty(leaf);
2306 out:
2307         btrfs_free_path(path);
2308         return err;
2309 }
2310
2311 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2312                                 struct btrfs_delayed_ref_node *node,
2313                                 struct btrfs_delayed_extent_op *extent_op,
2314                                 int insert_reserved)
2315 {
2316         int ret = 0;
2317         struct btrfs_delayed_tree_ref *ref;
2318         u64 parent = 0;
2319         u64 ref_root = 0;
2320
2321         ref = btrfs_delayed_node_to_tree_ref(node);
2322         trace_run_delayed_tree_ref(trans->fs_info, node, ref, node->action);
2323
2324         if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2325                 parent = ref->parent;
2326         ref_root = ref->root;
2327
2328         if (node->ref_mod != 1) {
2329                 btrfs_err(trans->fs_info,
2330         "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
2331                           node->bytenr, node->ref_mod, node->action, ref_root,
2332                           parent);
2333                 return -EIO;
2334         }
2335         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2336                 BUG_ON(!extent_op || !extent_op->update_flags);
2337                 ret = alloc_reserved_tree_block(trans, node, extent_op);
2338         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2339                 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2340                                              ref->level, 0, 1, extent_op);
2341         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2342                 ret = __btrfs_free_extent(trans, node, parent, ref_root,
2343                                           ref->level, 0, 1, extent_op);
2344         } else {
2345                 BUG();
2346         }
2347         return ret;
2348 }
2349
2350 /* helper function to actually process a single delayed ref entry */
2351 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2352                                struct btrfs_delayed_ref_node *node,
2353                                struct btrfs_delayed_extent_op *extent_op,
2354                                int insert_reserved)
2355 {
2356         int ret = 0;
2357
2358         if (trans->aborted) {
2359                 if (insert_reserved)
2360                         btrfs_pin_extent(trans->fs_info, node->bytenr,
2361                                          node->num_bytes, 1);
2362                 return 0;
2363         }
2364
2365         if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2366             node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2367                 ret = run_delayed_tree_ref(trans, node, extent_op,
2368                                            insert_reserved);
2369         else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2370                  node->type == BTRFS_SHARED_DATA_REF_KEY)
2371                 ret = run_delayed_data_ref(trans, node, extent_op,
2372                                            insert_reserved);
2373         else
2374                 BUG();
2375         if (ret && insert_reserved)
2376                 btrfs_pin_extent(trans->fs_info, node->bytenr,
2377                                  node->num_bytes, 1);
2378         return ret;
2379 }
2380
2381 static inline struct btrfs_delayed_ref_node *
2382 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2383 {
2384         struct btrfs_delayed_ref_node *ref;
2385
2386         if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
2387                 return NULL;
2388
2389         /*
2390          * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
2391          * This is to prevent a ref count from going down to zero, which deletes
2392          * the extent item from the extent tree, when there still are references
2393          * to add, which would fail because they would not find the extent item.
2394          */
2395         if (!list_empty(&head->ref_add_list))
2396                 return list_first_entry(&head->ref_add_list,
2397                                 struct btrfs_delayed_ref_node, add_list);
2398
2399         ref = rb_entry(rb_first_cached(&head->ref_tree),
2400                        struct btrfs_delayed_ref_node, ref_node);
2401         ASSERT(list_empty(&ref->add_list));
2402         return ref;
2403 }
2404
2405 static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
2406                                       struct btrfs_delayed_ref_head *head)
2407 {
2408         spin_lock(&delayed_refs->lock);
2409         head->processing = 0;
2410         delayed_refs->num_heads_ready++;
2411         spin_unlock(&delayed_refs->lock);
2412         btrfs_delayed_ref_unlock(head);
2413 }
2414
2415 static struct btrfs_delayed_extent_op *cleanup_extent_op(
2416                                 struct btrfs_delayed_ref_head *head)
2417 {
2418         struct btrfs_delayed_extent_op *extent_op = head->extent_op;
2419
2420         if (!extent_op)
2421                 return NULL;
2422
2423         if (head->must_insert_reserved) {
2424                 head->extent_op = NULL;
2425                 btrfs_free_delayed_extent_op(extent_op);
2426                 return NULL;
2427         }
2428         return extent_op;
2429 }
2430
2431 static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
2432                                      struct btrfs_delayed_ref_head *head)
2433 {
2434         struct btrfs_delayed_extent_op *extent_op;
2435         int ret;
2436
2437         extent_op = cleanup_extent_op(head);
2438         if (!extent_op)
2439                 return 0;
2440         head->extent_op = NULL;
2441         spin_unlock(&head->lock);
2442         ret = run_delayed_extent_op(trans, head, extent_op);
2443         btrfs_free_delayed_extent_op(extent_op);
2444         return ret ? ret : 1;
2445 }
2446
2447 void btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
2448                                   struct btrfs_delayed_ref_root *delayed_refs,
2449                                   struct btrfs_delayed_ref_head *head)
2450 {
2451         int nr_items = 1;       /* Dropping this ref head update. */
2452
2453         if (head->total_ref_mod < 0) {
2454                 struct btrfs_space_info *space_info;
2455                 u64 flags;
2456
2457                 if (head->is_data)
2458                         flags = BTRFS_BLOCK_GROUP_DATA;
2459                 else if (head->is_system)
2460                         flags = BTRFS_BLOCK_GROUP_SYSTEM;
2461                 else
2462                         flags = BTRFS_BLOCK_GROUP_METADATA;
2463                 space_info = __find_space_info(fs_info, flags);
2464                 ASSERT(space_info);
2465                 percpu_counter_add_batch(&space_info->total_bytes_pinned,
2466                                    -head->num_bytes,
2467                                    BTRFS_TOTAL_BYTES_PINNED_BATCH);
2468
2469                 /*
2470                  * We had csum deletions accounted for in our delayed refs rsv,
2471                  * we need to drop the csum leaves for this update from our
2472                  * delayed_refs_rsv.
2473                  */
2474                 if (head->is_data) {
2475                         spin_lock(&delayed_refs->lock);
2476                         delayed_refs->pending_csums -= head->num_bytes;
2477                         spin_unlock(&delayed_refs->lock);
2478                         nr_items += btrfs_csum_bytes_to_leaves(fs_info,
2479                                 head->num_bytes);
2480                 }
2481         }
2482
2483         btrfs_delayed_refs_rsv_release(fs_info, nr_items);
2484 }
2485
2486 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
2487                             struct btrfs_delayed_ref_head *head)
2488 {
2489
2490         struct btrfs_fs_info *fs_info = trans->fs_info;
2491         struct btrfs_delayed_ref_root *delayed_refs;
2492         int ret;
2493
2494         delayed_refs = &trans->transaction->delayed_refs;
2495
2496         ret = run_and_cleanup_extent_op(trans, head);
2497         if (ret < 0) {
2498                 unselect_delayed_ref_head(delayed_refs, head);
2499                 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
2500                 return ret;
2501         } else if (ret) {
2502                 return ret;
2503         }
2504
2505         /*
2506          * Need to drop our head ref lock and re-acquire the delayed ref lock
2507          * and then re-check to make sure nobody got added.
2508          */
2509         spin_unlock(&head->lock);
2510         spin_lock(&delayed_refs->lock);
2511         spin_lock(&head->lock);
2512         if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
2513                 spin_unlock(&head->lock);
2514                 spin_unlock(&delayed_refs->lock);
2515                 return 1;
2516         }
2517         btrfs_delete_ref_head(delayed_refs, head);
2518         spin_unlock(&head->lock);
2519         spin_unlock(&delayed_refs->lock);
2520
2521         if (head->must_insert_reserved) {
2522                 btrfs_pin_extent(fs_info, head->bytenr,
2523                                  head->num_bytes, 1);
2524                 if (head->is_data) {
2525                         ret = btrfs_del_csums(trans, fs_info, head->bytenr,
2526                                               head->num_bytes);
2527                 }
2528         }
2529
2530         btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
2531
2532         trace_run_delayed_ref_head(fs_info, head, 0);
2533         btrfs_delayed_ref_unlock(head);
2534         btrfs_put_delayed_ref_head(head);
2535         return 0;
2536 }
2537
2538 static struct btrfs_delayed_ref_head *btrfs_obtain_ref_head(
2539                                         struct btrfs_trans_handle *trans)
2540 {
2541         struct btrfs_delayed_ref_root *delayed_refs =
2542                 &trans->transaction->delayed_refs;
2543         struct btrfs_delayed_ref_head *head = NULL;
2544         int ret;
2545
2546         spin_lock(&delayed_refs->lock);
2547         head = btrfs_select_ref_head(delayed_refs);
2548         if (!head) {
2549                 spin_unlock(&delayed_refs->lock);
2550                 return head;
2551         }
2552
2553         /*
2554          * Grab the lock that says we are going to process all the refs for
2555          * this head
2556          */
2557         ret = btrfs_delayed_ref_lock(delayed_refs, head);
2558         spin_unlock(&delayed_refs->lock);
2559
2560         /*
2561          * We may have dropped the spin lock to get the head mutex lock, and
2562          * that might have given someone else time to free the head.  If that's
2563          * true, it has been removed from our list and we can move on.
2564          */
2565         if (ret == -EAGAIN)
2566                 head = ERR_PTR(-EAGAIN);
2567
2568         return head;
2569 }
2570
2571 static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
2572                                     struct btrfs_delayed_ref_head *locked_ref,
2573                                     unsigned long *run_refs)
2574 {
2575         struct btrfs_fs_info *fs_info = trans->fs_info;
2576         struct btrfs_delayed_ref_root *delayed_refs;
2577         struct btrfs_delayed_extent_op *extent_op;
2578         struct btrfs_delayed_ref_node *ref;
2579         int must_insert_reserved = 0;
2580         int ret;
2581
2582         delayed_refs = &trans->transaction->delayed_refs;
2583
2584         lockdep_assert_held(&locked_ref->mutex);
2585         lockdep_assert_held(&locked_ref->lock);
2586
2587         while ((ref = select_delayed_ref(locked_ref))) {
2588                 if (ref->seq &&
2589                     btrfs_check_delayed_seq(fs_info, ref->seq)) {
2590                         spin_unlock(&locked_ref->lock);
2591                         unselect_delayed_ref_head(delayed_refs, locked_ref);
2592                         return -EAGAIN;
2593                 }
2594
2595                 (*run_refs)++;
2596                 ref->in_tree = 0;
2597                 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
2598                 RB_CLEAR_NODE(&ref->ref_node);
2599                 if (!list_empty(&ref->add_list))
2600                         list_del(&ref->add_list);
2601                 /*
2602                  * When we play the delayed ref, also correct the ref_mod on
2603                  * head
2604                  */
2605                 switch (ref->action) {
2606                 case BTRFS_ADD_DELAYED_REF:
2607                 case BTRFS_ADD_DELAYED_EXTENT:
2608                         locked_ref->ref_mod -= ref->ref_mod;
2609                         break;
2610                 case BTRFS_DROP_DELAYED_REF:
2611                         locked_ref->ref_mod += ref->ref_mod;
2612                         break;
2613                 default:
2614                         WARN_ON(1);
2615                 }
2616                 atomic_dec(&delayed_refs->num_entries);
2617
2618                 /*
2619                  * Record the must_insert_reserved flag before we drop the
2620                  * spin lock.
2621                  */
2622                 must_insert_reserved = locked_ref->must_insert_reserved;
2623                 locked_ref->must_insert_reserved = 0;
2624
2625                 extent_op = locked_ref->extent_op;
2626                 locked_ref->extent_op = NULL;
2627                 spin_unlock(&locked_ref->lock);
2628
2629                 ret = run_one_delayed_ref(trans, ref, extent_op,
2630                                           must_insert_reserved);
2631
2632                 btrfs_free_delayed_extent_op(extent_op);
2633                 if (ret) {
2634                         unselect_delayed_ref_head(delayed_refs, locked_ref);
2635                         btrfs_put_delayed_ref(ref);
2636                         btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
2637                                     ret);
2638                         return ret;
2639                 }
2640
2641                 btrfs_put_delayed_ref(ref);
2642                 cond_resched();
2643
2644                 spin_lock(&locked_ref->lock);
2645                 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2646         }
2647
2648         return 0;
2649 }
2650
2651 /*
2652  * Returns 0 on success or if called with an already aborted transaction.
2653  * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2654  */
2655 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2656                                              unsigned long nr)
2657 {
2658         struct btrfs_fs_info *fs_info = trans->fs_info;
2659         struct btrfs_delayed_ref_root *delayed_refs;
2660         struct btrfs_delayed_ref_head *locked_ref = NULL;
2661         ktime_t start = ktime_get();
2662         int ret;
2663         unsigned long count = 0;
2664         unsigned long actual_count = 0;
2665
2666         delayed_refs = &trans->transaction->delayed_refs;
2667         do {
2668                 if (!locked_ref) {
2669                         locked_ref = btrfs_obtain_ref_head(trans);
2670                         if (IS_ERR_OR_NULL(locked_ref)) {
2671                                 if (PTR_ERR(locked_ref) == -EAGAIN) {
2672                                         continue;
2673                                 } else {
2674                                         break;
2675                                 }
2676                         }
2677                         count++;
2678                 }
2679                 /*
2680                  * We need to try and merge add/drops of the same ref since we
2681                  * can run into issues with relocate dropping the implicit ref
2682                  * and then it being added back again before the drop can
2683                  * finish.  If we merged anything we need to re-loop so we can
2684                  * get a good ref.
2685                  * Or we can get node references of the same type that weren't
2686                  * merged when created due to bumps in the tree mod seq, and
2687                  * we need to merge them to prevent adding an inline extent
2688                  * backref before dropping it (triggering a BUG_ON at
2689                  * insert_inline_extent_backref()).
2690                  */
2691                 spin_lock(&locked_ref->lock);
2692                 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2693
2694                 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref,
2695                                                       &actual_count);
2696                 if (ret < 0 && ret != -EAGAIN) {
2697                         /*
2698                          * Error, btrfs_run_delayed_refs_for_head already
2699                          * unlocked everything so just bail out
2700                          */
2701                         return ret;
2702                 } else if (!ret) {
2703                         /*
2704                          * Success, perform the usual cleanup of a processed
2705                          * head
2706                          */
2707                         ret = cleanup_ref_head(trans, locked_ref);
2708                         if (ret > 0 ) {
2709                                 /* We dropped our lock, we need to loop. */
2710                                 ret = 0;
2711                                 continue;
2712                         } else if (ret) {
2713                                 return ret;
2714                         }
2715                 }
2716
2717                 /*
2718                  * Either success case or btrfs_run_delayed_refs_for_head
2719                  * returned -EAGAIN, meaning we need to select another head
2720                  */
2721
2722                 locked_ref = NULL;
2723                 cond_resched();
2724         } while ((nr != -1 && count < nr) || locked_ref);
2725
2726         /*
2727          * We don't want to include ref heads since we can have empty ref heads
2728          * and those will drastically skew our runtime down since we just do
2729          * accounting, no actual extent tree updates.
2730          */
2731         if (actual_count > 0) {
2732                 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2733                 u64 avg;
2734
2735                 /*
2736                  * We weigh the current average higher than our current runtime
2737                  * to avoid large swings in the average.
2738                  */
2739                 spin_lock(&delayed_refs->lock);
2740                 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2741                 fs_info->avg_delayed_ref_runtime = avg >> 2;    /* div by 4 */
2742                 spin_unlock(&delayed_refs->lock);
2743         }
2744         return 0;
2745 }
2746
2747 #ifdef SCRAMBLE_DELAYED_REFS
2748 /*
2749  * Normally delayed refs get processed in ascending bytenr order. This
2750  * correlates in most cases to the order added. To expose dependencies on this
2751  * order, we start to process the tree in the middle instead of the beginning
2752  */
2753 static u64 find_middle(struct rb_root *root)
2754 {
2755         struct rb_node *n = root->rb_node;
2756         struct btrfs_delayed_ref_node *entry;
2757         int alt = 1;
2758         u64 middle;
2759         u64 first = 0, last = 0;
2760
2761         n = rb_first(root);
2762         if (n) {
2763                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2764                 first = entry->bytenr;
2765         }
2766         n = rb_last(root);
2767         if (n) {
2768                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2769                 last = entry->bytenr;
2770         }
2771         n = root->rb_node;
2772
2773         while (n) {
2774                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2775                 WARN_ON(!entry->in_tree);
2776
2777                 middle = entry->bytenr;
2778
2779                 if (alt)
2780                         n = n->rb_left;
2781                 else
2782                         n = n->rb_right;
2783
2784                 alt = 1 - alt;
2785         }
2786         return middle;
2787 }
2788 #endif
2789
2790 static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
2791 {
2792         u64 num_bytes;
2793
2794         num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2795                              sizeof(struct btrfs_extent_inline_ref));
2796         if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2797                 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2798
2799         /*
2800          * We don't ever fill up leaves all the way so multiply by 2 just to be
2801          * closer to what we're really going to want to use.
2802          */
2803         return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
2804 }
2805
2806 /*
2807  * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2808  * would require to store the csums for that many bytes.
2809  */
2810 u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
2811 {
2812         u64 csum_size;
2813         u64 num_csums_per_leaf;
2814         u64 num_csums;
2815
2816         csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
2817         num_csums_per_leaf = div64_u64(csum_size,
2818                         (u64)btrfs_super_csum_size(fs_info->super_copy));
2819         num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
2820         num_csums += num_csums_per_leaf - 1;
2821         num_csums = div64_u64(num_csums, num_csums_per_leaf);
2822         return num_csums;
2823 }
2824
2825 bool btrfs_check_space_for_delayed_refs(struct btrfs_fs_info *fs_info)
2826 {
2827         struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
2828         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
2829         bool ret = false;
2830         u64 reserved;
2831
2832         spin_lock(&global_rsv->lock);
2833         reserved = global_rsv->reserved;
2834         spin_unlock(&global_rsv->lock);
2835
2836         /*
2837          * Since the global reserve is just kind of magic we don't really want
2838          * to rely on it to save our bacon, so if our size is more than the
2839          * delayed_refs_rsv and the global rsv then it's time to think about
2840          * bailing.
2841          */
2842         spin_lock(&delayed_refs_rsv->lock);
2843         reserved += delayed_refs_rsv->reserved;
2844         if (delayed_refs_rsv->size >= reserved)
2845                 ret = true;
2846         spin_unlock(&delayed_refs_rsv->lock);
2847         return ret;
2848 }
2849
2850 int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans)
2851 {
2852         u64 num_entries =
2853                 atomic_read(&trans->transaction->delayed_refs.num_entries);
2854         u64 avg_runtime;
2855         u64 val;
2856
2857         smp_mb();
2858         avg_runtime = trans->fs_info->avg_delayed_ref_runtime;
2859         val = num_entries * avg_runtime;
2860         if (val >= NSEC_PER_SEC)
2861                 return 1;
2862         if (val >= NSEC_PER_SEC / 2)
2863                 return 2;
2864
2865         return btrfs_check_space_for_delayed_refs(trans->fs_info);
2866 }
2867
2868 /*
2869  * this starts processing the delayed reference count updates and
2870  * extent insertions we have queued up so far.  count can be
2871  * 0, which means to process everything in the tree at the start
2872  * of the run (but not newly added entries), or it can be some target
2873  * number you'd like to process.
2874  *
2875  * Returns 0 on success or if called with an aborted transaction
2876  * Returns <0 on error and aborts the transaction
2877  */
2878 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2879                            unsigned long count)
2880 {
2881         struct btrfs_fs_info *fs_info = trans->fs_info;
2882         struct rb_node *node;
2883         struct btrfs_delayed_ref_root *delayed_refs;
2884         struct btrfs_delayed_ref_head *head;
2885         int ret;
2886         int run_all = count == (unsigned long)-1;
2887
2888         /* We'll clean this up in btrfs_cleanup_transaction */
2889         if (trans->aborted)
2890                 return 0;
2891
2892         if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2893                 return 0;
2894
2895         delayed_refs = &trans->transaction->delayed_refs;
2896         if (count == 0)
2897                 count = atomic_read(&delayed_refs->num_entries) * 2;
2898
2899 again:
2900 #ifdef SCRAMBLE_DELAYED_REFS
2901         delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2902 #endif
2903         ret = __btrfs_run_delayed_refs(trans, count);
2904         if (ret < 0) {
2905                 btrfs_abort_transaction(trans, ret);
2906                 return ret;
2907         }
2908
2909         if (run_all) {
2910                 btrfs_create_pending_block_groups(trans);
2911
2912                 spin_lock(&delayed_refs->lock);
2913                 node = rb_first_cached(&delayed_refs->href_root);
2914                 if (!node) {
2915                         spin_unlock(&delayed_refs->lock);
2916                         goto out;
2917                 }
2918                 head = rb_entry(node, struct btrfs_delayed_ref_head,
2919                                 href_node);
2920                 refcount_inc(&head->refs);
2921                 spin_unlock(&delayed_refs->lock);
2922
2923                 /* Mutex was contended, block until it's released and retry. */
2924                 mutex_lock(&head->mutex);
2925                 mutex_unlock(&head->mutex);
2926
2927                 btrfs_put_delayed_ref_head(head);
2928                 cond_resched();
2929                 goto again;
2930         }
2931 out:
2932         return 0;
2933 }
2934
2935 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2936                                 struct btrfs_fs_info *fs_info,
2937                                 u64 bytenr, u64 num_bytes, u64 flags,
2938                                 int level, int is_data)
2939 {
2940         struct btrfs_delayed_extent_op *extent_op;
2941         int ret;
2942
2943         extent_op = btrfs_alloc_delayed_extent_op();
2944         if (!extent_op)
2945                 return -ENOMEM;
2946
2947         extent_op->flags_to_set = flags;
2948         extent_op->update_flags = true;
2949         extent_op->update_key = false;
2950         extent_op->is_data = is_data ? true : false;
2951         extent_op->level = level;
2952
2953         ret = btrfs_add_delayed_extent_op(fs_info, trans, bytenr,
2954                                           num_bytes, extent_op);
2955         if (ret)
2956                 btrfs_free_delayed_extent_op(extent_op);
2957         return ret;
2958 }
2959
2960 static noinline int check_delayed_ref(struct btrfs_root *root,
2961                                       struct btrfs_path *path,
2962                                       u64 objectid, u64 offset, u64 bytenr)
2963 {
2964         struct btrfs_delayed_ref_head *head;
2965         struct btrfs_delayed_ref_node *ref;
2966         struct btrfs_delayed_data_ref *data_ref;
2967         struct btrfs_delayed_ref_root *delayed_refs;
2968         struct btrfs_transaction *cur_trans;
2969         struct rb_node *node;
2970         int ret = 0;
2971
2972         spin_lock(&root->fs_info->trans_lock);
2973         cur_trans = root->fs_info->running_transaction;
2974         if (cur_trans)
2975                 refcount_inc(&cur_trans->use_count);
2976         spin_unlock(&root->fs_info->trans_lock);
2977         if (!cur_trans)
2978                 return 0;
2979
2980         delayed_refs = &cur_trans->delayed_refs;
2981         spin_lock(&delayed_refs->lock);
2982         head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
2983         if (!head) {
2984                 spin_unlock(&delayed_refs->lock);
2985                 btrfs_put_transaction(cur_trans);
2986                 return 0;
2987         }
2988
2989         if (!mutex_trylock(&head->mutex)) {
2990                 refcount_inc(&head->refs);
2991                 spin_unlock(&delayed_refs->lock);
2992
2993                 btrfs_release_path(path);
2994
2995                 /*
2996                  * Mutex was contended, block until it's released and let
2997                  * caller try again
2998                  */
2999                 mutex_lock(&head->mutex);
3000                 mutex_unlock(&head->mutex);
3001                 btrfs_put_delayed_ref_head(head);
3002                 btrfs_put_transaction(cur_trans);
3003                 return -EAGAIN;
3004         }
3005         spin_unlock(&delayed_refs->lock);
3006
3007         spin_lock(&head->lock);
3008         /*
3009          * XXX: We should replace this with a proper search function in the
3010          * future.
3011          */
3012         for (node = rb_first_cached(&head->ref_tree); node;
3013              node = rb_next(node)) {
3014                 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
3015                 /* If it's a shared ref we know a cross reference exists */
3016                 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
3017                         ret = 1;
3018                         break;
3019                 }
3020
3021                 data_ref = btrfs_delayed_node_to_data_ref(ref);
3022
3023                 /*
3024                  * If our ref doesn't match the one we're currently looking at
3025                  * then we have a cross reference.
3026                  */
3027                 if (data_ref->root != root->root_key.objectid ||
3028                     data_ref->objectid != objectid ||
3029                     data_ref->offset != offset) {
3030                         ret = 1;
3031                         break;
3032                 }
3033         }
3034         spin_unlock(&head->lock);
3035         mutex_unlock(&head->mutex);
3036         btrfs_put_transaction(cur_trans);
3037         return ret;
3038 }
3039
3040 static noinline int check_committed_ref(struct btrfs_root *root,
3041                                         struct btrfs_path *path,
3042                                         u64 objectid, u64 offset, u64 bytenr)
3043 {
3044         struct btrfs_fs_info *fs_info = root->fs_info;
3045         struct btrfs_root *extent_root = fs_info->extent_root;
3046         struct extent_buffer *leaf;
3047         struct btrfs_extent_data_ref *ref;
3048         struct btrfs_extent_inline_ref *iref;
3049         struct btrfs_extent_item *ei;
3050         struct btrfs_key key;
3051         u32 item_size;
3052         int type;
3053         int ret;
3054
3055         key.objectid = bytenr;
3056         key.offset = (u64)-1;
3057         key.type = BTRFS_EXTENT_ITEM_KEY;
3058
3059         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
3060         if (ret < 0)
3061                 goto out;
3062         BUG_ON(ret == 0); /* Corruption */
3063
3064         ret = -ENOENT;
3065         if (path->slots[0] == 0)
3066                 goto out;
3067
3068         path->slots[0]--;
3069         leaf = path->nodes[0];
3070         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3071
3072         if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
3073                 goto out;
3074
3075         ret = 1;
3076         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3077         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
3078
3079         if (item_size != sizeof(*ei) +
3080             btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
3081                 goto out;
3082
3083         if (btrfs_extent_generation(leaf, ei) <=
3084             btrfs_root_last_snapshot(&root->root_item))
3085                 goto out;
3086
3087         iref = (struct btrfs_extent_inline_ref *)(ei + 1);
3088
3089         type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
3090         if (type != BTRFS_EXTENT_DATA_REF_KEY)
3091                 goto out;
3092
3093         ref = (struct btrfs_extent_data_ref *)(&iref->offset);
3094         if (btrfs_extent_refs(leaf, ei) !=
3095             btrfs_extent_data_ref_count(leaf, ref) ||
3096             btrfs_extent_data_ref_root(leaf, ref) !=
3097             root->root_key.objectid ||
3098             btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
3099             btrfs_extent_data_ref_offset(leaf, ref) != offset)
3100                 goto out;
3101
3102         ret = 0;
3103 out:
3104         return ret;
3105 }
3106
3107 int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
3108                           u64 bytenr)
3109 {
3110         struct btrfs_path *path;
3111         int ret;
3112
3113         path = btrfs_alloc_path();
3114         if (!path)
3115                 return -ENOMEM;
3116
3117         do {
3118                 ret = check_committed_ref(root, path, objectid,
3119                                           offset, bytenr);
3120                 if (ret && ret != -ENOENT)
3121                         goto out;
3122
3123                 ret = check_delayed_ref(root, path, objectid, offset, bytenr);
3124         } while (ret == -EAGAIN);
3125
3126 out:
3127         btrfs_free_path(path);
3128         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3129                 WARN_ON(ret > 0);
3130         return ret;
3131 }
3132
3133 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
3134                            struct btrfs_root *root,
3135                            struct extent_buffer *buf,
3136                            int full_backref, int inc)
3137 {
3138         struct btrfs_fs_info *fs_info = root->fs_info;
3139         u64 bytenr;
3140         u64 num_bytes;
3141         u64 parent;
3142         u64 ref_root;
3143         u32 nritems;
3144         struct btrfs_key key;
3145         struct btrfs_file_extent_item *fi;
3146         struct btrfs_ref generic_ref = { 0 };
3147         bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC);
3148         int i;
3149         int action;
3150         int level;
3151         int ret = 0;
3152
3153         if (btrfs_is_testing(fs_info))
3154                 return 0;
3155
3156         ref_root = btrfs_header_owner(buf);
3157         nritems = btrfs_header_nritems(buf);
3158         level = btrfs_header_level(buf);
3159
3160         if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
3161                 return 0;
3162
3163         if (full_backref)
3164                 parent = buf->start;
3165         else
3166                 parent = 0;
3167         if (inc)
3168                 action = BTRFS_ADD_DELAYED_REF;
3169         else
3170                 action = BTRFS_DROP_DELAYED_REF;
3171
3172         for (i = 0; i < nritems; i++) {
3173                 if (level == 0) {
3174                         btrfs_item_key_to_cpu(buf, &key, i);
3175                         if (key.type != BTRFS_EXTENT_DATA_KEY)
3176                                 continue;
3177                         fi = btrfs_item_ptr(buf, i,
3178                                             struct btrfs_file_extent_item);
3179                         if (btrfs_file_extent_type(buf, fi) ==
3180                             BTRFS_FILE_EXTENT_INLINE)
3181                                 continue;
3182                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
3183                         if (bytenr == 0)
3184                                 continue;
3185
3186                         num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
3187                         key.offset -= btrfs_file_extent_offset(buf, fi);
3188                         btrfs_init_generic_ref(&generic_ref, action, bytenr,
3189                                                num_bytes, parent);
3190                         generic_ref.real_root = root->root_key.objectid;
3191                         btrfs_init_data_ref(&generic_ref, ref_root, key.objectid,
3192                                             key.offset);
3193                         generic_ref.skip_qgroup = for_reloc;
3194                         if (inc)
3195                                 ret = btrfs_inc_extent_ref(trans, &generic_ref);
3196                         else
3197                                 ret = btrfs_free_extent(trans, &generic_ref);
3198                         if (ret)
3199                                 goto fail;
3200                 } else {
3201                         bytenr = btrfs_node_blockptr(buf, i);
3202                         num_bytes = fs_info->nodesize;
3203                         btrfs_init_generic_ref(&generic_ref, action, bytenr,
3204                                                num_bytes, parent);
3205                         generic_ref.real_root = root->root_key.objectid;
3206                         btrfs_init_tree_ref(&generic_ref, level - 1, ref_root);
3207                         generic_ref.skip_qgroup = for_reloc;
3208                         if (inc)
3209                                 ret = btrfs_inc_extent_ref(trans, &generic_ref);
3210                         else
3211                                 ret = btrfs_free_extent(trans, &generic_ref);
3212                         if (ret)
3213                                 goto fail;
3214                 }
3215         }
3216         return 0;
3217 fail:
3218         return ret;
3219 }
3220
3221 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3222                   struct extent_buffer *buf, int full_backref)
3223 {
3224         return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
3225 }
3226
3227 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3228                   struct extent_buffer *buf, int full_backref)
3229 {
3230         return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
3231 }
3232
3233 static int write_one_cache_group(struct btrfs_trans_handle *trans,
3234                                  struct btrfs_path *path,
3235                                  struct btrfs_block_group_cache *cache)
3236 {
3237         struct btrfs_fs_info *fs_info = trans->fs_info;
3238         int ret;
3239         struct btrfs_root *extent_root = fs_info->extent_root;
3240         unsigned long bi;
3241         struct extent_buffer *leaf;
3242
3243         ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
3244         if (ret) {
3245                 if (ret > 0)
3246                         ret = -ENOENT;
3247                 goto fail;
3248         }
3249
3250         leaf = path->nodes[0];
3251         bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3252         write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
3253         btrfs_mark_buffer_dirty(leaf);
3254 fail:
3255         btrfs_release_path(path);
3256         return ret;
3257
3258 }
3259
3260 static struct btrfs_block_group_cache *next_block_group(
3261                 struct btrfs_block_group_cache *cache)
3262 {
3263         struct btrfs_fs_info *fs_info = cache->fs_info;
3264         struct rb_node *node;
3265
3266         spin_lock(&fs_info->block_group_cache_lock);
3267
3268         /* If our block group was removed, we need a full search. */
3269         if (RB_EMPTY_NODE(&cache->cache_node)) {
3270                 const u64 next_bytenr = cache->key.objectid + cache->key.offset;
3271
3272                 spin_unlock(&fs_info->block_group_cache_lock);
3273                 btrfs_put_block_group(cache);
3274                 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
3275         }
3276         node = rb_next(&cache->cache_node);
3277         btrfs_put_block_group(cache);
3278         if (node) {
3279                 cache = rb_entry(node, struct btrfs_block_group_cache,
3280                                  cache_node);
3281                 btrfs_get_block_group(cache);
3282         } else
3283                 cache = NULL;
3284         spin_unlock(&fs_info->block_group_cache_lock);
3285         return cache;
3286 }
3287
3288 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
3289                             struct btrfs_trans_handle *trans,
3290                             struct btrfs_path *path)
3291 {
3292         struct btrfs_fs_info *fs_info = block_group->fs_info;
3293         struct btrfs_root *root = fs_info->tree_root;
3294         struct inode *inode = NULL;
3295         struct extent_changeset *data_reserved = NULL;
3296         u64 alloc_hint = 0;
3297         int dcs = BTRFS_DC_ERROR;
3298         u64 num_pages = 0;
3299         int retries = 0;
3300         int ret = 0;
3301
3302         /*
3303          * If this block group is smaller than 100 megs don't bother caching the
3304          * block group.
3305          */
3306         if (block_group->key.offset < (100 * SZ_1M)) {
3307                 spin_lock(&block_group->lock);
3308                 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3309                 spin_unlock(&block_group->lock);
3310                 return 0;
3311         }
3312
3313         if (trans->aborted)
3314                 return 0;
3315 again:
3316         inode = lookup_free_space_inode(block_group, path);
3317         if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3318                 ret = PTR_ERR(inode);
3319                 btrfs_release_path(path);
3320                 goto out;
3321         }
3322
3323         if (IS_ERR(inode)) {
3324                 BUG_ON(retries);
3325                 retries++;
3326
3327                 if (block_group->ro)
3328                         goto out_free;
3329
3330                 ret = create_free_space_inode(trans, block_group, path);
3331                 if (ret)
3332                         goto out_free;
3333                 goto again;
3334         }
3335
3336         /*
3337          * We want to set the generation to 0, that way if anything goes wrong
3338          * from here on out we know not to trust this cache when we load up next
3339          * time.
3340          */
3341         BTRFS_I(inode)->generation = 0;
3342         ret = btrfs_update_inode(trans, root, inode);
3343         if (ret) {
3344                 /*
3345                  * So theoretically we could recover from this, simply set the
3346                  * super cache generation to 0 so we know to invalidate the
3347                  * cache, but then we'd have to keep track of the block groups
3348                  * that fail this way so we know we _have_ to reset this cache
3349                  * before the next commit or risk reading stale cache.  So to
3350                  * limit our exposure to horrible edge cases lets just abort the
3351                  * transaction, this only happens in really bad situations
3352                  * anyway.
3353                  */
3354                 btrfs_abort_transaction(trans, ret);
3355                 goto out_put;
3356         }
3357         WARN_ON(ret);
3358
3359         /* We've already setup this transaction, go ahead and exit */
3360         if (block_group->cache_generation == trans->transid &&
3361             i_size_read(inode)) {
3362                 dcs = BTRFS_DC_SETUP;
3363                 goto out_put;
3364         }
3365
3366         if (i_size_read(inode) > 0) {
3367                 ret = btrfs_check_trunc_cache_free_space(fs_info,
3368                                         &fs_info->global_block_rsv);
3369                 if (ret)
3370                         goto out_put;
3371
3372                 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
3373                 if (ret)
3374                         goto out_put;
3375         }
3376
3377         spin_lock(&block_group->lock);
3378         if (block_group->cached != BTRFS_CACHE_FINISHED ||
3379             !btrfs_test_opt(fs_info, SPACE_CACHE)) {
3380                 /*
3381                  * don't bother trying to write stuff out _if_
3382                  * a) we're not cached,
3383                  * b) we're with nospace_cache mount option,
3384                  * c) we're with v2 space_cache (FREE_SPACE_TREE).
3385                  */
3386                 dcs = BTRFS_DC_WRITTEN;
3387                 spin_unlock(&block_group->lock);
3388                 goto out_put;
3389         }
3390         spin_unlock(&block_group->lock);
3391
3392         /*
3393          * We hit an ENOSPC when setting up the cache in this transaction, just
3394          * skip doing the setup, we've already cleared the cache so we're safe.
3395          */
3396         if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
3397                 ret = -ENOSPC;
3398                 goto out_put;
3399         }
3400
3401         /*
3402          * Try to preallocate enough space based on how big the block group is.
3403          * Keep in mind this has to include any pinned space which could end up
3404          * taking up quite a bit since it's not folded into the other space
3405          * cache.
3406          */
3407         num_pages = div_u64(block_group->key.offset, SZ_256M);
3408         if (!num_pages)
3409                 num_pages = 1;
3410
3411         num_pages *= 16;
3412         num_pages *= PAGE_SIZE;
3413
3414         ret = btrfs_check_data_free_space(inode, &data_reserved, 0, num_pages);
3415         if (ret)
3416                 goto out_put;
3417
3418         ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3419                                               num_pages, num_pages,
3420                                               &alloc_hint);
3421         /*
3422          * Our cache requires contiguous chunks so that we don't modify a bunch
3423          * of metadata or split extents when writing the cache out, which means
3424          * we can enospc if we are heavily fragmented in addition to just normal
3425          * out of space conditions.  So if we hit this just skip setting up any
3426          * other block groups for this transaction, maybe we'll unpin enough
3427          * space the next time around.
3428          */
3429         if (!ret)
3430                 dcs = BTRFS_DC_SETUP;
3431         else if (ret == -ENOSPC)
3432                 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
3433
3434 out_put:
3435         iput(inode);
3436 out_free:
3437         btrfs_release_path(path);
3438 out:
3439         spin_lock(&block_group->lock);
3440         if (!ret && dcs == BTRFS_DC_SETUP)
3441                 block_group->cache_generation = trans->transid;
3442         block_group->disk_cache_state = dcs;
3443         spin_unlock(&block_group->lock);
3444
3445         extent_changeset_free(data_reserved);
3446         return ret;
3447 }
3448
3449 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
3450 {
3451         struct btrfs_fs_info *fs_info = trans->fs_info;
3452         struct btrfs_block_group_cache *cache, *tmp;
3453         struct btrfs_transaction *cur_trans = trans->transaction;
3454         struct btrfs_path *path;
3455
3456         if (list_empty(&cur_trans->dirty_bgs) ||
3457             !btrfs_test_opt(fs_info, SPACE_CACHE))
3458                 return 0;
3459
3460         path = btrfs_alloc_path();
3461         if (!path)
3462                 return -ENOMEM;
3463
3464         /* Could add new block groups, use _safe just in case */
3465         list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
3466                                  dirty_list) {
3467                 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3468                         cache_save_setup(cache, trans, path);
3469         }
3470
3471         btrfs_free_path(path);
3472         return 0;
3473 }
3474
3475 /*
3476  * transaction commit does final block group cache writeback during a
3477  * critical section where nothing is allowed to change the FS.  This is
3478  * required in order for the cache to actually match the block group,
3479  * but can introduce a lot of latency into the commit.
3480  *
3481  * So, btrfs_start_dirty_block_groups is here to kick off block group
3482  * cache IO.  There's a chance we'll have to redo some of it if the
3483  * block group changes again during the commit, but it greatly reduces
3484  * the commit latency by getting rid of the easy block groups while
3485  * we're still allowing others to join the commit.
3486  */
3487 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
3488 {
3489         struct btrfs_fs_info *fs_info = trans->fs_info;
3490         struct btrfs_block_group_cache *cache;
3491         struct btrfs_transaction *cur_trans = trans->transaction;
3492         int ret = 0;
3493         int should_put;
3494         struct btrfs_path *path = NULL;
3495         LIST_HEAD(dirty);
3496         struct list_head *io = &cur_trans->io_bgs;
3497         int num_started = 0;
3498         int loops = 0;
3499
3500         spin_lock(&cur_trans->dirty_bgs_lock);
3501         if (list_empty(&cur_trans->dirty_bgs)) {
3502                 spin_unlock(&cur_trans->dirty_bgs_lock);
3503                 return 0;
3504         }
3505         list_splice_init(&cur_trans->dirty_bgs, &dirty);
3506         spin_unlock(&cur_trans->dirty_bgs_lock);
3507
3508 again:
3509         /*
3510          * make sure all the block groups on our dirty list actually
3511          * exist
3512          */
3513         btrfs_create_pending_block_groups(trans);
3514
3515         if (!path) {
3516                 path = btrfs_alloc_path();
3517                 if (!path)
3518                         return -ENOMEM;
3519         }
3520
3521         /*
3522          * cache_write_mutex is here only to save us from balance or automatic
3523          * removal of empty block groups deleting this block group while we are
3524          * writing out the cache
3525          */
3526         mutex_lock(&trans->transaction->cache_write_mutex);
3527         while (!list_empty(&dirty)) {
3528                 bool drop_reserve = true;
3529
3530                 cache = list_first_entry(&dirty,
3531                                          struct btrfs_block_group_cache,
3532                                          dirty_list);
3533                 /*
3534                  * this can happen if something re-dirties a block
3535                  * group that is already under IO.  Just wait for it to
3536                  * finish and then do it all again
3537                  */
3538                 if (!list_empty(&cache->io_list)) {
3539                         list_del_init(&cache->io_list);
3540                         btrfs_wait_cache_io(trans, cache, path);
3541                         btrfs_put_block_group(cache);
3542                 }
3543
3544
3545                 /*
3546                  * btrfs_wait_cache_io uses the cache->dirty_list to decide
3547                  * if it should update the cache_state.  Don't delete
3548                  * until after we wait.
3549                  *
3550                  * Since we're not running in the commit critical section
3551                  * we need the dirty_bgs_lock to protect from update_block_group
3552                  */
3553                 spin_lock(&cur_trans->dirty_bgs_lock);
3554                 list_del_init(&cache->dirty_list);
3555                 spin_unlock(&cur_trans->dirty_bgs_lock);
3556
3557                 should_put = 1;
3558
3559                 cache_save_setup(cache, trans, path);
3560
3561                 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3562                         cache->io_ctl.inode = NULL;
3563                         ret = btrfs_write_out_cache(trans, cache, path);
3564                         if (ret == 0 && cache->io_ctl.inode) {
3565                                 num_started++;
3566                                 should_put = 0;
3567
3568                                 /*
3569                                  * The cache_write_mutex is protecting the
3570                                  * io_list, also refer to the definition of
3571                                  * btrfs_transaction::io_bgs for more details
3572                                  */
3573                                 list_add_tail(&cache->io_list, io);
3574                         } else {
3575                                 /*
3576                                  * if we failed to write the cache, the
3577                                  * generation will be bad and life goes on
3578                                  */
3579                                 ret = 0;
3580                         }
3581                 }
3582                 if (!ret) {
3583                         ret = write_one_cache_group(trans, path, cache);
3584                         /*
3585                          * Our block group might still be attached to the list
3586                          * of new block groups in the transaction handle of some
3587                          * other task (struct btrfs_trans_handle->new_bgs). This
3588                          * means its block group item isn't yet in the extent
3589                          * tree. If this happens ignore the error, as we will
3590                          * try again later in the critical section of the
3591                          * transaction commit.
3592                          */
3593                         if (ret == -ENOENT) {
3594                                 ret = 0;
3595                                 spin_lock(&cur_trans->dirty_bgs_lock);
3596                                 if (list_empty(&cache->dirty_list)) {
3597                                         list_add_tail(&cache->dirty_list,
3598                                                       &cur_trans->dirty_bgs);
3599                                         btrfs_get_block_group(cache);
3600                                         drop_reserve = false;
3601                                 }
3602                                 spin_unlock(&cur_trans->dirty_bgs_lock);
3603                         } else if (ret) {
3604                                 btrfs_abort_transaction(trans, ret);
3605                         }
3606                 }
3607
3608                 /* if it's not on the io list, we need to put the block group */
3609                 if (should_put)
3610                         btrfs_put_block_group(cache);
3611                 if (drop_reserve)
3612                         btrfs_delayed_refs_rsv_release(fs_info, 1);
3613
3614                 if (ret)
3615                         break;
3616
3617                 /*
3618                  * Avoid blocking other tasks for too long. It might even save
3619                  * us from writing caches for block groups that are going to be
3620                  * removed.
3621                  */
3622                 mutex_unlock(&trans->transaction->cache_write_mutex);
3623                 mutex_lock(&trans->transaction->cache_write_mutex);
3624         }
3625         mutex_unlock(&trans->transaction->cache_write_mutex);
3626
3627         /*
3628          * go through delayed refs for all the stuff we've just kicked off
3629          * and then loop back (just once)
3630          */
3631         ret = btrfs_run_delayed_refs(trans, 0);
3632         if (!ret && loops == 0) {
3633                 loops++;
3634                 spin_lock(&cur_trans->dirty_bgs_lock);
3635                 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3636                 /*
3637                  * dirty_bgs_lock protects us from concurrent block group
3638                  * deletes too (not just cache_write_mutex).
3639                  */
3640                 if (!list_empty(&dirty)) {
3641                         spin_unlock(&cur_trans->dirty_bgs_lock);
3642                         goto again;
3643                 }
3644                 spin_unlock(&cur_trans->dirty_bgs_lock);
3645         } else if (ret < 0) {
3646                 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
3647         }
3648
3649         btrfs_free_path(path);
3650         return ret;
3651 }
3652
3653 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
3654 {
3655         struct btrfs_fs_info *fs_info = trans->fs_info;
3656         struct btrfs_block_group_cache *cache;
3657         struct btrfs_transaction *cur_trans = trans->transaction;
3658         int ret = 0;
3659         int should_put;
3660         struct btrfs_path *path;
3661         struct list_head *io = &cur_trans->io_bgs;
3662         int num_started = 0;
3663
3664         path = btrfs_alloc_path();
3665         if (!path)
3666                 return -ENOMEM;
3667
3668         /*
3669          * Even though we are in the critical section of the transaction commit,
3670          * we can still have concurrent tasks adding elements to this
3671          * transaction's list of dirty block groups. These tasks correspond to
3672          * endio free space workers started when writeback finishes for a
3673          * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3674          * allocate new block groups as a result of COWing nodes of the root
3675          * tree when updating the free space inode. The writeback for the space
3676          * caches is triggered by an earlier call to
3677          * btrfs_start_dirty_block_groups() and iterations of the following
3678          * loop.
3679          * Also we want to do the cache_save_setup first and then run the
3680          * delayed refs to make sure we have the best chance at doing this all
3681          * in one shot.
3682          */
3683         spin_lock(&cur_trans->dirty_bgs_lock);
3684         while (!list_empty(&cur_trans->dirty_bgs)) {
3685                 cache = list_first_entry(&cur_trans->dirty_bgs,
3686                                          struct btrfs_block_group_cache,
3687                                          dirty_list);
3688
3689                 /*
3690                  * this can happen if cache_save_setup re-dirties a block
3691                  * group that is already under IO.  Just wait for it to
3692                  * finish and then do it all again
3693                  */
3694                 if (!list_empty(&cache->io_list)) {
3695                         spin_unlock(&cur_trans->dirty_bgs_lock);
3696                         list_del_init(&cache->io_list);
3697                         btrfs_wait_cache_io(trans, cache, path);
3698                         btrfs_put_block_group(cache);
3699                         spin_lock(&cur_trans->dirty_bgs_lock);
3700                 }
3701
3702                 /*
3703                  * don't remove from the dirty list until after we've waited
3704                  * on any pending IO
3705                  */
3706                 list_del_init(&cache->dirty_list);
3707                 spin_unlock(&cur_trans->dirty_bgs_lock);
3708                 should_put = 1;
3709
3710                 cache_save_setup(cache, trans, path);
3711
3712                 if (!ret)
3713                         ret = btrfs_run_delayed_refs(trans,
3714                                                      (unsigned long) -1);
3715
3716                 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3717                         cache->io_ctl.inode = NULL;
3718                         ret = btrfs_write_out_cache(trans, cache, path);
3719                         if (ret == 0 && cache->io_ctl.inode) {
3720                                 num_started++;
3721                                 should_put = 0;
3722                                 list_add_tail(&cache->io_list, io);
3723                         } else {
3724                                 /*
3725                                  * if we failed to write the cache, the
3726                                  * generation will be bad and life goes on
3727                                  */
3728                                 ret = 0;
3729                         }
3730                 }
3731                 if (!ret) {
3732                         ret = write_one_cache_group(trans, path, cache);
3733                         /*
3734                          * One of the free space endio workers might have
3735                          * created a new block group while updating a free space
3736                          * cache's inode (at inode.c:btrfs_finish_ordered_io())
3737                          * and hasn't released its transaction handle yet, in
3738                          * which case the new block group is still attached to
3739                          * its transaction handle and its creation has not
3740                          * finished yet (no block group item in the extent tree
3741                          * yet, etc). If this is the case, wait for all free
3742                          * space endio workers to finish and retry. This is a
3743                          * a very rare case so no need for a more efficient and
3744                          * complex approach.
3745                          */
3746                         if (ret == -ENOENT) {
3747                                 wait_event(cur_trans->writer_wait,
3748                                    atomic_read(&cur_trans->num_writers) == 1);
3749                                 ret = write_one_cache_group(trans, path, cache);
3750                         }
3751                         if (ret)
3752                                 btrfs_abort_transaction(trans, ret);
3753                 }
3754
3755                 /* if its not on the io list, we need to put the block group */
3756                 if (should_put)
3757                         btrfs_put_block_group(cache);
3758                 btrfs_delayed_refs_rsv_release(fs_info, 1);
3759                 spin_lock(&cur_trans->dirty_bgs_lock);
3760         }
3761         spin_unlock(&cur_trans->dirty_bgs_lock);
3762
3763         /*
3764          * Refer to the definition of io_bgs member for details why it's safe
3765          * to use it without any locking
3766          */
3767         while (!list_empty(io)) {
3768                 cache = list_first_entry(io, struct btrfs_block_group_cache,
3769                                          io_list);
3770                 list_del_init(&cache->io_list);
3771                 btrfs_wait_cache_io(trans, cache, path);
3772                 btrfs_put_block_group(cache);
3773         }
3774
3775         btrfs_free_path(path);
3776         return ret;
3777 }
3778
3779 int btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
3780 {
3781         struct btrfs_block_group_cache *block_group;
3782         int readonly = 0;
3783
3784         block_group = btrfs_lookup_block_group(fs_info, bytenr);
3785         if (!block_group || block_group->ro)
3786                 readonly = 1;
3787         if (block_group)
3788                 btrfs_put_block_group(block_group);
3789         return readonly;
3790 }
3791
3792 bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3793 {
3794         struct btrfs_block_group_cache *bg;
3795         bool ret = true;
3796
3797         bg = btrfs_lookup_block_group(fs_info, bytenr);
3798         if (!bg)
3799                 return false;
3800
3801         spin_lock(&bg->lock);
3802         if (bg->ro)
3803                 ret = false;
3804         else
3805                 atomic_inc(&bg->nocow_writers);
3806         spin_unlock(&bg->lock);
3807
3808         /* no put on block group, done by btrfs_dec_nocow_writers */
3809         if (!ret)
3810                 btrfs_put_block_group(bg);
3811
3812         return ret;
3813
3814 }
3815
3816 void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3817 {
3818         struct btrfs_block_group_cache *bg;
3819
3820         bg = btrfs_lookup_block_group(fs_info, bytenr);
3821         ASSERT(bg);
3822         if (atomic_dec_and_test(&bg->nocow_writers))
3823                 wake_up_var(&bg->nocow_writers);
3824         /*
3825          * Once for our lookup and once for the lookup done by a previous call
3826          * to btrfs_inc_nocow_writers()
3827          */
3828         btrfs_put_block_group(bg);
3829         btrfs_put_block_group(bg);
3830 }
3831
3832 void btrfs_wait_nocow_writers(struct btrfs_block_group_cache *bg)
3833 {
3834         wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
3835 }
3836
3837 static const char *alloc_name(u64 flags)
3838 {
3839         switch (flags) {
3840         case BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA:
3841                 return "mixed";
3842         case BTRFS_BLOCK_GROUP_METADATA:
3843                 return "metadata";
3844         case BTRFS_BLOCK_GROUP_DATA:
3845                 return "data";
3846         case BTRFS_BLOCK_GROUP_SYSTEM:
3847                 return "system";
3848         default:
3849                 WARN_ON(1);
3850                 return "invalid-combination";
3851         };
3852 }
3853
3854 static int create_space_info(struct btrfs_fs_info *info, u64 flags)
3855 {
3856
3857         struct btrfs_space_info *space_info;
3858         int i;
3859         int ret;
3860
3861         space_info = kzalloc(sizeof(*space_info), GFP_NOFS);
3862         if (!space_info)
3863                 return -ENOMEM;
3864
3865         ret = percpu_counter_init(&space_info->total_bytes_pinned, 0,
3866                                  GFP_KERNEL);
3867         if (ret) {
3868                 kfree(space_info);
3869                 return ret;
3870         }
3871
3872         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
3873                 INIT_LIST_HEAD(&space_info->block_groups[i]);
3874         init_rwsem(&space_info->groups_sem);
3875         spin_lock_init(&space_info->lock);
3876         space_info->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
3877         space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3878         init_waitqueue_head(&space_info->wait);
3879         INIT_LIST_HEAD(&space_info->ro_bgs);
3880         INIT_LIST_HEAD(&space_info->tickets);
3881         INIT_LIST_HEAD(&space_info->priority_tickets);
3882
3883         ret = kobject_init_and_add(&space_info->kobj, &space_info_ktype,
3884                                     info->space_info_kobj, "%s",
3885                                     alloc_name(space_info->flags));
3886         if (ret) {
3887                 percpu_counter_destroy(&space_info->total_bytes_pinned);
3888                 kfree(space_info);
3889                 return ret;
3890         }
3891
3892         list_add_rcu(&space_info->list, &info->space_info);
3893         if (flags & BTRFS_BLOCK_GROUP_DATA)
3894                 info->data_sinfo = space_info;
3895
3896         return ret;
3897 }
3898
3899 static void update_space_info(struct btrfs_fs_info *info, u64 flags,
3900                              u64 total_bytes, u64 bytes_used,
3901                              u64 bytes_readonly,
3902                              struct btrfs_space_info **space_info)
3903 {
3904         struct btrfs_space_info *found;
3905         int factor;
3906
3907         factor = btrfs_bg_type_to_factor(flags);
3908
3909         found = __find_space_info(info, flags);
3910         ASSERT(found);
3911         spin_lock(&found->lock);
3912         found->total_bytes += total_bytes;
3913         found->disk_total += total_bytes * factor;
3914         found->bytes_used += bytes_used;
3915         found->disk_used += bytes_used * factor;
3916         found->bytes_readonly += bytes_readonly;
3917         if (total_bytes > 0)
3918                 found->full = 0;
3919         space_info_add_new_bytes(info, found, total_bytes -
3920                                  bytes_used - bytes_readonly);
3921         spin_unlock(&found->lock);
3922         *space_info = found;
3923 }
3924
3925 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3926 {
3927         u64 extra_flags = chunk_to_extended(flags) &
3928                                 BTRFS_EXTENDED_PROFILE_MASK;
3929
3930         write_seqlock(&fs_info->profiles_lock);
3931         if (flags & BTRFS_BLOCK_GROUP_DATA)
3932                 fs_info->avail_data_alloc_bits |= extra_flags;
3933         if (flags & BTRFS_BLOCK_GROUP_METADATA)
3934                 fs_info->avail_metadata_alloc_bits |= extra_flags;
3935         if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3936                 fs_info->avail_system_alloc_bits |= extra_flags;
3937         write_sequnlock(&fs_info->profiles_lock);
3938 }
3939
3940 /*
3941  * returns target flags in extended format or 0 if restripe for this
3942  * chunk_type is not in progress
3943  *
3944  * should be called with balance_lock held
3945  */
3946 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
3947 {
3948         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3949         u64 target = 0;
3950
3951         if (!bctl)
3952                 return 0;
3953
3954         if (flags & BTRFS_BLOCK_GROUP_DATA &&
3955             bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3956                 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
3957         } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
3958                    bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3959                 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
3960         } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
3961                    bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3962                 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
3963         }
3964
3965         return target;
3966 }
3967
3968 /*
3969  * @flags: available profiles in extended format (see ctree.h)
3970  *
3971  * Returns reduced profile in chunk format.  If profile changing is in
3972  * progress (either running or paused) picks the target profile (if it's
3973  * already available), otherwise falls back to plain reducing.
3974  */
3975 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
3976 {
3977         u64 num_devices = fs_info->fs_devices->rw_devices;
3978         u64 target;
3979         u64 raid_type;
3980         u64 allowed = 0;
3981
3982         /*
3983          * see if restripe for this chunk_type is in progress, if so
3984          * try to reduce to the target profile
3985          */
3986         spin_lock(&fs_info->balance_lock);
3987         target = get_restripe_target(fs_info, flags);
3988         if (target) {
3989                 /* pick target profile only if it's already available */
3990                 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
3991                         spin_unlock(&fs_info->balance_lock);
3992                         return extended_to_chunk(target);
3993                 }
3994         }
3995         spin_unlock(&fs_info->balance_lock);
3996
3997         /* First, mask out the RAID levels which aren't possible */
3998         for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
3999                 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
4000                         allowed |= btrfs_raid_array[raid_type].bg_flag;
4001         }
4002         allowed &= flags;
4003
4004         if (allowed & BTRFS_BLOCK_GROUP_RAID6)
4005                 allowed = BTRFS_BLOCK_GROUP_RAID6;
4006         else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
4007                 allowed = BTRFS_BLOCK_GROUP_RAID5;
4008         else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
4009                 allowed = BTRFS_BLOCK_GROUP_RAID10;
4010         else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
4011                 allowed = BTRFS_BLOCK_GROUP_RAID1;
4012         else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
4013                 allowed = BTRFS_BLOCK_GROUP_RAID0;
4014
4015         flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
4016
4017         return extended_to_chunk(flags | allowed);
4018 }
4019
4020 static u64 get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
4021 {
4022         unsigned seq;
4023         u64 flags;
4024
4025         do {
4026                 flags = orig_flags;
4027                 seq = read_seqbegin(&fs_info->profiles_lock);
4028
4029                 if (flags & BTRFS_BLOCK_GROUP_DATA)
4030                         flags |= fs_info->avail_data_alloc_bits;
4031                 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
4032                         flags |= fs_info->avail_system_alloc_bits;
4033                 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
4034                         flags |= fs_info->avail_metadata_alloc_bits;
4035         } while (read_seqretry(&fs_info->profiles_lock, seq));
4036
4037         return btrfs_reduce_alloc_profile(fs_info, flags);
4038 }
4039
4040 static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
4041 {
4042         struct btrfs_fs_info *fs_info = root->fs_info;
4043         u64 flags;
4044         u64 ret;
4045
4046         if (data)
4047                 flags = BTRFS_BLOCK_GROUP_DATA;
4048         else if (root == fs_info->chunk_root)
4049                 flags = BTRFS_BLOCK_GROUP_SYSTEM;
4050         else
4051                 flags = BTRFS_BLOCK_GROUP_METADATA;
4052
4053         ret = get_alloc_profile(fs_info, flags);
4054         return ret;
4055 }
4056
4057 u64 btrfs_data_alloc_profile(struct btrfs_fs_info *fs_info)
4058 {
4059         return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_DATA);
4060 }
4061
4062 u64 btrfs_metadata_alloc_profile(struct btrfs_fs_info *fs_info)
4063 {
4064         return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4065 }
4066
4067 u64 btrfs_system_alloc_profile(struct btrfs_fs_info *fs_info)
4068 {
4069         return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4070 }
4071
4072 static u64 btrfs_space_info_used(struct btrfs_space_info *s_info,
4073                                  bool may_use_included)
4074 {
4075         ASSERT(s_info);
4076         return s_info->bytes_used + s_info->bytes_reserved +
4077                 s_info->bytes_pinned + s_info->bytes_readonly +
4078                 (may_use_included ? s_info->bytes_may_use : 0);
4079 }
4080
4081 int btrfs_alloc_data_chunk_ondemand(struct btrfs_inode *inode, u64 bytes)
4082 {
4083         struct btrfs_root *root = inode->root;
4084         struct btrfs_fs_info *fs_info = root->fs_info;
4085         struct btrfs_space_info *data_sinfo = fs_info->data_sinfo;
4086         u64 used;
4087         int ret = 0;
4088         int need_commit = 2;
4089         int have_pinned_space;
4090
4091         /* make sure bytes are sectorsize aligned */
4092         bytes = ALIGN(bytes, fs_info->sectorsize);
4093
4094         if (btrfs_is_free_space_inode(inode)) {
4095                 need_commit = 0;
4096                 ASSERT(current->journal_info);
4097         }
4098
4099 again:
4100         /* make sure we have enough space to handle the data first */
4101         spin_lock(&data_sinfo->lock);
4102         used = btrfs_space_info_used(data_sinfo, true);
4103
4104         if (used + bytes > data_sinfo->total_bytes) {
4105                 struct btrfs_trans_handle *trans;
4106
4107                 /*
4108                  * if we don't have enough free bytes in this space then we need
4109                  * to alloc a new chunk.
4110                  */
4111                 if (!data_sinfo->full) {
4112                         u64 alloc_target;
4113
4114                         data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
4115                         spin_unlock(&data_sinfo->lock);
4116
4117                         alloc_target = btrfs_data_alloc_profile(fs_info);
4118                         /*
4119                          * It is ugly that we don't call nolock join
4120                          * transaction for the free space inode case here.
4121                          * But it is safe because we only do the data space
4122                          * reservation for the free space cache in the
4123                          * transaction context, the common join transaction
4124                          * just increase the counter of the current transaction
4125                          * handler, doesn't try to acquire the trans_lock of
4126                          * the fs.
4127                          */
4128                         trans = btrfs_join_transaction(root);
4129                         if (IS_ERR(trans))
4130                                 return PTR_ERR(trans);
4131
4132                         ret = do_chunk_alloc(trans, alloc_target,
4133                                              CHUNK_ALLOC_NO_FORCE);
4134                         btrfs_end_transaction(trans);
4135                         if (ret < 0) {
4136                                 if (ret != -ENOSPC)
4137                                         return ret;
4138                                 else {
4139                                         have_pinned_space = 1;
4140                                         goto commit_trans;
4141                                 }
4142                         }
4143
4144                         goto again;
4145                 }
4146
4147                 /*
4148                  * If we don't have enough pinned space to deal with this
4149                  * allocation, and no removed chunk in current transaction,
4150                  * don't bother committing the transaction.
4151                  */
4152                 have_pinned_space = __percpu_counter_compare(
4153                         &data_sinfo->total_bytes_pinned,
4154                         used + bytes - data_sinfo->total_bytes,
4155                         BTRFS_TOTAL_BYTES_PINNED_BATCH);
4156                 spin_unlock(&data_sinfo->lock);
4157
4158                 /* commit the current transaction and try again */
4159 commit_trans:
4160                 if (need_commit) {
4161                         need_commit--;
4162
4163                         if (need_commit > 0) {
4164                                 btrfs_start_delalloc_roots(fs_info, -1);
4165                                 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0,
4166                                                          (u64)-1);
4167                         }
4168
4169                         trans = btrfs_join_transaction(root);
4170                         if (IS_ERR(trans))
4171                                 return PTR_ERR(trans);
4172                         if (have_pinned_space >= 0 ||
4173                             test_bit(BTRFS_TRANS_HAVE_FREE_BGS,
4174                                      &trans->transaction->flags) ||
4175                             need_commit > 0) {
4176                                 ret = btrfs_commit_transaction(trans);
4177                                 if (ret)
4178                                         return ret;
4179                                 /*
4180                                  * The cleaner kthread might still be doing iput
4181                                  * operations. Wait for it to finish so that
4182                                  * more space is released.  We don't need to
4183                                  * explicitly run the delayed iputs here because
4184                                  * the commit_transaction would have woken up
4185                                  * the cleaner.
4186                                  */
4187                                 ret = btrfs_wait_on_delayed_iputs(fs_info);
4188                                 if (ret)
4189                                         return ret;
4190                                 goto again;
4191                         } else {
4192                                 btrfs_end_transaction(trans);
4193                         }
4194                 }
4195
4196                 trace_btrfs_space_reservation(fs_info,
4197                                               "space_info:enospc",
4198                                               data_sinfo->flags, bytes, 1);
4199                 return -ENOSPC;
4200         }
4201         update_bytes_may_use(data_sinfo, bytes);
4202         trace_btrfs_space_reservation(fs_info, "space_info",
4203                                       data_sinfo->flags, bytes, 1);
4204         spin_unlock(&data_sinfo->lock);
4205
4206         return 0;
4207 }
4208
4209 int btrfs_check_data_free_space(struct inode *inode,
4210                         struct extent_changeset **reserved, u64 start, u64 len)
4211 {
4212         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4213         int ret;
4214
4215         /* align the range */
4216         len = round_up(start + len, fs_info->sectorsize) -
4217               round_down(start, fs_info->sectorsize);
4218         start = round_down(start, fs_info->sectorsize);
4219
4220         ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode), len);
4221         if (ret < 0)
4222                 return ret;
4223
4224         /* Use new btrfs_qgroup_reserve_data to reserve precious data space. */
4225         ret = btrfs_qgroup_reserve_data(inode, reserved, start, len);
4226         if (ret < 0)
4227                 btrfs_free_reserved_data_space_noquota(inode, start, len);
4228         else
4229                 ret = 0;
4230         return ret;
4231 }
4232
4233 /*
4234  * Called if we need to clear a data reservation for this inode
4235  * Normally in a error case.
4236  *
4237  * This one will *NOT* use accurate qgroup reserved space API, just for case
4238  * which we can't sleep and is sure it won't affect qgroup reserved space.
4239  * Like clear_bit_hook().
4240  */
4241 void btrfs_free_reserved_data_space_noquota(struct inode *inode, u64 start,
4242                                             u64 len)
4243 {
4244         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4245         struct btrfs_space_info *data_sinfo;
4246
4247         /* Make sure the range is aligned to sectorsize */
4248         len = round_up(start + len, fs_info->sectorsize) -
4249               round_down(start, fs_info->sectorsize);
4250         start = round_down(start, fs_info->sectorsize);
4251
4252         data_sinfo = fs_info->data_sinfo;
4253         spin_lock(&data_sinfo->lock);
4254         update_bytes_may_use(data_sinfo, -len);
4255         trace_btrfs_space_reservation(fs_info, "space_info",
4256                                       data_sinfo->flags, len, 0);
4257         spin_unlock(&data_sinfo->lock);
4258 }
4259
4260 /*
4261  * Called if we need to clear a data reservation for this inode
4262  * Normally in a error case.
4263  *
4264  * This one will handle the per-inode data rsv map for accurate reserved
4265  * space framework.
4266  */
4267 void btrfs_free_reserved_data_space(struct inode *inode,
4268                         struct extent_changeset *reserved, u64 start, u64 len)
4269 {
4270         struct btrfs_root *root = BTRFS_I(inode)->root;
4271
4272         /* Make sure the range is aligned to sectorsize */
4273         len = round_up(start + len, root->fs_info->sectorsize) -
4274               round_down(start, root->fs_info->sectorsize);
4275         start = round_down(start, root->fs_info->sectorsize);
4276
4277         btrfs_free_reserved_data_space_noquota(inode, start, len);
4278         btrfs_qgroup_free_data(inode, reserved, start, len);
4279 }
4280
4281 static void force_metadata_allocation(struct btrfs_fs_info *info)
4282 {
4283         struct list_head *head = &info->space_info;
4284         struct btrfs_space_info *found;
4285
4286         rcu_read_lock();
4287         list_for_each_entry_rcu(found, head, list) {
4288                 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
4289                         found->force_alloc = CHUNK_ALLOC_FORCE;
4290         }
4291         rcu_read_unlock();
4292 }
4293
4294 static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
4295 {
4296         return (global->size << 1);
4297 }
4298
4299 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
4300                               struct btrfs_space_info *sinfo, int force)
4301 {
4302         u64 bytes_used = btrfs_space_info_used(sinfo, false);
4303         u64 thresh;
4304
4305         if (force == CHUNK_ALLOC_FORCE)
4306                 return 1;
4307
4308         /*
4309          * in limited mode, we want to have some free space up to
4310          * about 1% of the FS size.
4311          */
4312         if (force == CHUNK_ALLOC_LIMITED) {
4313                 thresh = btrfs_super_total_bytes(fs_info->super_copy);
4314                 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
4315
4316                 if (sinfo->total_bytes - bytes_used < thresh)
4317                         return 1;
4318         }
4319
4320         if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
4321                 return 0;
4322         return 1;
4323 }
4324
4325 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
4326 {
4327         u64 num_dev;
4328
4329         if (type & (BTRFS_BLOCK_GROUP_RAID10 |
4330                     BTRFS_BLOCK_GROUP_RAID0 |
4331                     BTRFS_BLOCK_GROUP_RAID5 |
4332                     BTRFS_BLOCK_GROUP_RAID6))
4333                 num_dev = fs_info->fs_devices->rw_devices;
4334         else if (type & BTRFS_BLOCK_GROUP_RAID1)
4335                 num_dev = 2;
4336         else
4337                 num_dev = 1;    /* DUP or single */
4338
4339         return num_dev;
4340 }
4341
4342 /*
4343  * If @is_allocation is true, reserve space in the system space info necessary
4344  * for allocating a chunk, otherwise if it's false, reserve space necessary for
4345  * removing a chunk.
4346  */
4347 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
4348 {
4349         struct btrfs_fs_info *fs_info = trans->fs_info;
4350         struct btrfs_space_info *info;
4351         u64 left;
4352         u64 thresh;
4353         int ret = 0;
4354         u64 num_devs;
4355
4356         /*
4357          * Needed because we can end up allocating a system chunk and for an
4358          * atomic and race free space reservation in the chunk block reserve.
4359          */
4360         lockdep_assert_held(&fs_info->chunk_mutex);
4361
4362         info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4363         spin_lock(&info->lock);
4364         left = info->total_bytes - btrfs_space_info_used(info, true);
4365         spin_unlock(&info->lock);
4366
4367         num_devs = get_profile_num_devs(fs_info, type);
4368
4369         /* num_devs device items to update and 1 chunk item to add or remove */
4370         thresh = btrfs_calc_trunc_metadata_size(fs_info, num_devs) +
4371                 btrfs_calc_trans_metadata_size(fs_info, 1);
4372
4373         if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4374                 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
4375                            left, thresh, type);
4376                 dump_space_info(fs_info, info, 0, 0);
4377         }
4378
4379         if (left < thresh) {
4380                 u64 flags = btrfs_system_alloc_profile(fs_info);
4381
4382                 /*
4383                  * Ignore failure to create system chunk. We might end up not
4384                  * needing it, as we might not need to COW all nodes/leafs from
4385                  * the paths we visit in the chunk tree (they were already COWed
4386                  * or created in the current transaction for example).
4387                  */
4388                 ret = btrfs_alloc_chunk(trans, flags);
4389         }
4390
4391         if (!ret) {
4392                 ret = btrfs_block_rsv_add(fs_info->chunk_root,
4393                                           &fs_info->chunk_block_rsv,
4394                                           thresh, BTRFS_RESERVE_NO_FLUSH);
4395                 if (!ret)
4396                         trans->chunk_bytes_reserved += thresh;
4397         }
4398 }
4399
4400 /*
4401  * If force is CHUNK_ALLOC_FORCE:
4402  *    - return 1 if it successfully allocates a chunk,
4403  *    - return errors including -ENOSPC otherwise.
4404  * If force is NOT CHUNK_ALLOC_FORCE:
4405  *    - return 0 if it doesn't need to allocate a new chunk,
4406  *    - return 1 if it successfully allocates a chunk,
4407  *    - return errors including -ENOSPC otherwise.
4408  */
4409 static int do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
4410                           int force)
4411 {
4412         struct btrfs_fs_info *fs_info = trans->fs_info;
4413         struct btrfs_space_info *space_info;
4414         bool wait_for_alloc = false;
4415         bool should_alloc = false;
4416         int ret = 0;
4417
4418         /* Don't re-enter if we're already allocating a chunk */
4419         if (trans->allocating_chunk)
4420                 return -ENOSPC;
4421
4422         space_info = __find_space_info(fs_info, flags);
4423         ASSERT(space_info);
4424
4425         do {
4426                 spin_lock(&space_info->lock);
4427                 if (force < space_info->force_alloc)
4428                         force = space_info->force_alloc;
4429                 should_alloc = should_alloc_chunk(fs_info, space_info, force);
4430                 if (space_info->full) {
4431                         /* No more free physical space */
4432                         if (should_alloc)
4433                                 ret = -ENOSPC;
4434                         else
4435                                 ret = 0;
4436                         spin_unlock(&space_info->lock);
4437                         return ret;
4438                 } else if (!should_alloc) {
4439                         spin_unlock(&space_info->lock);
4440                         return 0;
4441                 } else if (space_info->chunk_alloc) {
4442                         /*
4443                          * Someone is already allocating, so we need to block
4444                          * until this someone is finished and then loop to
4445                          * recheck if we should continue with our allocation
4446                          * attempt.
4447                          */
4448                         wait_for_alloc = true;
4449                         spin_unlock(&space_info->lock);
4450                         mutex_lock(&fs_info->chunk_mutex);
4451                         mutex_unlock(&fs_info->chunk_mutex);
4452                 } else {
4453                         /* Proceed with allocation */
4454                         space_info->chunk_alloc = 1;
4455                         wait_for_alloc = false;
4456                         spin_unlock(&space_info->lock);
4457                 }
4458
4459                 cond_resched();
4460         } while (wait_for_alloc);
4461
4462         mutex_lock(&fs_info->chunk_mutex);
4463         trans->allocating_chunk = true;
4464
4465         /*
4466          * If we have mixed data/metadata chunks we want to make sure we keep
4467          * allocating mixed chunks instead of individual chunks.
4468          */
4469         if (btrfs_mixed_space_info(space_info))
4470                 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
4471
4472         /*
4473          * if we're doing a data chunk, go ahead and make sure that
4474          * we keep a reasonable number of metadata chunks allocated in the
4475          * FS as well.
4476          */
4477         if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
4478                 fs_info->data_chunk_allocations++;
4479                 if (!(fs_info->data_chunk_allocations %
4480                       fs_info->metadata_ratio))
4481                         force_metadata_allocation(fs_info);
4482         }
4483
4484         /*
4485          * Check if we have enough space in SYSTEM chunk because we may need
4486          * to update devices.
4487          */
4488         check_system_chunk(trans, flags);
4489
4490         ret = btrfs_alloc_chunk(trans, flags);
4491         trans->allocating_chunk = false;
4492
4493         spin_lock(&space_info->lock);
4494         if (ret < 0) {
4495                 if (ret == -ENOSPC)
4496                         space_info->full = 1;
4497                 else
4498                         goto out;
4499         } else {
4500                 ret = 1;
4501                 space_info->max_extent_size = 0;
4502         }
4503
4504         space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
4505 out:
4506         space_info->chunk_alloc = 0;
4507         spin_unlock(&space_info->lock);
4508         mutex_unlock(&fs_info->chunk_mutex);
4509         /*
4510          * When we allocate a new chunk we reserve space in the chunk block
4511          * reserve to make sure we can COW nodes/leafs in the chunk tree or
4512          * add new nodes/leafs to it if we end up needing to do it when
4513          * inserting the chunk item and updating device items as part of the
4514          * second phase of chunk allocation, performed by
4515          * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
4516          * large number of new block groups to create in our transaction
4517          * handle's new_bgs list to avoid exhausting the chunk block reserve
4518          * in extreme cases - like having a single transaction create many new
4519          * block groups when starting to write out the free space caches of all
4520          * the block groups that were made dirty during the lifetime of the
4521          * transaction.
4522          */
4523         if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
4524                 btrfs_create_pending_block_groups(trans);
4525
4526         return ret;
4527 }
4528
4529 static int can_overcommit(struct btrfs_fs_info *fs_info,
4530                           struct btrfs_space_info *space_info, u64 bytes,
4531                           enum btrfs_reserve_flush_enum flush,
4532                           bool system_chunk)
4533 {
4534         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4535         u64 profile;
4536         u64 space_size;
4537         u64 avail;
4538         u64 used;
4539         int factor;
4540
4541         /* Don't overcommit when in mixed mode. */
4542         if (space_info->flags & BTRFS_BLOCK_GROUP_DATA)
4543                 return 0;
4544
4545         if (system_chunk)
4546                 profile = btrfs_system_alloc_profile(fs_info);
4547         else
4548                 profile = btrfs_metadata_alloc_profile(fs_info);
4549
4550         used = btrfs_space_info_used(space_info, false);
4551
4552         /*
4553          * We only want to allow over committing if we have lots of actual space
4554          * free, but if we don't have enough space to handle the global reserve
4555          * space then we could end up having a real enospc problem when trying
4556          * to allocate a chunk or some other such important allocation.
4557          */
4558         spin_lock(&global_rsv->lock);
4559         space_size = calc_global_rsv_need_space(global_rsv);
4560         spin_unlock(&global_rsv->lock);
4561         if (used + space_size >= space_info->total_bytes)
4562                 return 0;
4563
4564         used += space_info->bytes_may_use;
4565
4566         avail = atomic64_read(&fs_info->free_chunk_space);
4567
4568         /*
4569          * If we have dup, raid1 or raid10 then only half of the free
4570          * space is actually usable.  For raid56, the space info used
4571          * doesn't include the parity drive, so we don't have to
4572          * change the math
4573          */
4574         factor = btrfs_bg_type_to_factor(profile);
4575         avail = div_u64(avail, factor);
4576
4577         /*
4578          * If we aren't flushing all things, let us overcommit up to
4579          * 1/2th of the space. If we can flush, don't let us overcommit
4580          * too much, let it overcommit up to 1/8 of the space.
4581          */
4582         if (flush == BTRFS_RESERVE_FLUSH_ALL)
4583                 avail >>= 3;
4584         else
4585                 avail >>= 1;
4586
4587         if (used + bytes < space_info->total_bytes + avail)
4588                 return 1;
4589         return 0;
4590 }
4591
4592 static void btrfs_writeback_inodes_sb_nr(struct btrfs_fs_info *fs_info,
4593                                          unsigned long nr_pages, int nr_items)
4594 {
4595         struct super_block *sb = fs_info->sb;
4596
4597         if (down_read_trylock(&sb->s_umount)) {
4598                 writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
4599                 up_read(&sb->s_umount);
4600         } else {
4601                 /*
4602                  * We needn't worry the filesystem going from r/w to r/o though
4603                  * we don't acquire ->s_umount mutex, because the filesystem
4604                  * should guarantee the delalloc inodes list be empty after
4605                  * the filesystem is readonly(all dirty pages are written to
4606                  * the disk).
4607                  */
4608                 btrfs_start_delalloc_roots(fs_info, nr_items);
4609                 if (!current->journal_info)
4610                         btrfs_wait_ordered_roots(fs_info, nr_items, 0, (u64)-1);
4611         }
4612 }
4613
4614 static inline u64 calc_reclaim_items_nr(struct btrfs_fs_info *fs_info,
4615                                         u64 to_reclaim)
4616 {
4617         u64 bytes;
4618         u64 nr;
4619
4620         bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
4621         nr = div64_u64(to_reclaim, bytes);
4622         if (!nr)
4623                 nr = 1;
4624         return nr;
4625 }
4626
4627 #define EXTENT_SIZE_PER_ITEM    SZ_256K
4628
4629 /*
4630  * shrink metadata reservation for delalloc
4631  */
4632 static void shrink_delalloc(struct btrfs_fs_info *fs_info, u64 to_reclaim,
4633                             u64 orig, bool wait_ordered)
4634 {
4635         struct btrfs_space_info *space_info;
4636         struct btrfs_trans_handle *trans;
4637         u64 delalloc_bytes;
4638         u64 async_pages;
4639         u64 items;
4640         long time_left;
4641         unsigned long nr_pages;
4642         int loops;
4643
4644         /* Calc the number of the pages we need flush for space reservation */
4645         items = calc_reclaim_items_nr(fs_info, to_reclaim);
4646         to_reclaim = items * EXTENT_SIZE_PER_ITEM;
4647
4648         trans = (struct btrfs_trans_handle *)current->journal_info;
4649         space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4650
4651         delalloc_bytes = percpu_counter_sum_positive(
4652                                                 &fs_info->delalloc_bytes);
4653         if (delalloc_bytes == 0) {
4654                 if (trans)
4655                         return;
4656                 if (wait_ordered)
4657                         btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
4658                 return;
4659         }
4660
4661         loops = 0;
4662         while (delalloc_bytes && loops < 3) {
4663                 nr_pages = min(delalloc_bytes, to_reclaim) >> PAGE_SHIFT;
4664
4665                 /*
4666                  * Triggers inode writeback for up to nr_pages. This will invoke
4667                  * ->writepages callback and trigger delalloc filling
4668                  *  (btrfs_run_delalloc_range()).
4669                  */
4670                 btrfs_writeback_inodes_sb_nr(fs_info, nr_pages, items);
4671
4672                 /*
4673                  * We need to wait for the compressed pages to start before
4674                  * we continue.
4675                  */
4676                 async_pages = atomic_read(&fs_info->async_delalloc_pages);
4677                 if (!async_pages)
4678                         goto skip_async;
4679
4680                 /*
4681                  * Calculate how many compressed pages we want to be written
4682                  * before we continue. I.e if there are more async pages than we
4683                  * require wait_event will wait until nr_pages are written.
4684                  */
4685                 if (async_pages <= nr_pages)
4686                         async_pages = 0;
4687                 else
4688                         async_pages -= nr_pages;
4689
4690                 wait_event(fs_info->async_submit_wait,
4691                            atomic_read(&fs_info->async_delalloc_pages) <=
4692                            (int)async_pages);
4693 skip_async:
4694                 spin_lock(&space_info->lock);
4695                 if (list_empty(&space_info->tickets) &&
4696                     list_empty(&space_info->priority_tickets)) {
4697                         spin_unlock(&space_info->lock);
4698                         break;
4699                 }
4700                 spin_unlock(&space_info->lock);
4701
4702                 loops++;
4703                 if (wait_ordered && !trans) {
4704                         btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
4705                 } else {
4706                         time_left = schedule_timeout_killable(1);
4707                         if (time_left)
4708                                 break;
4709                 }
4710                 delalloc_bytes = percpu_counter_sum_positive(
4711                                                 &fs_info->delalloc_bytes);
4712         }
4713 }
4714
4715 struct reserve_ticket {
4716         u64 orig_bytes;
4717         u64 bytes;
4718         int error;
4719         struct list_head list;
4720         wait_queue_head_t wait;
4721 };
4722
4723 /**
4724  * maybe_commit_transaction - possibly commit the transaction if its ok to
4725  * @root - the root we're allocating for
4726  * @bytes - the number of bytes we want to reserve
4727  * @force - force the commit
4728  *
4729  * This will check to make sure that committing the transaction will actually
4730  * get us somewhere and then commit the transaction if it does.  Otherwise it
4731  * will return -ENOSPC.
4732  */
4733 static int may_commit_transaction(struct btrfs_fs_info *fs_info,
4734                                   struct btrfs_space_info *space_info)
4735 {
4736         struct reserve_ticket *ticket = NULL;
4737         struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_block_rsv;
4738         struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
4739         struct btrfs_trans_handle *trans;
4740         u64 bytes_needed;
4741         u64 reclaim_bytes = 0;
4742
4743         trans = (struct btrfs_trans_handle *)current->journal_info;
4744         if (trans)
4745                 return -EAGAIN;
4746
4747         spin_lock(&space_info->lock);
4748         if (!list_empty(&space_info->priority_tickets))
4749                 ticket = list_first_entry(&space_info->priority_tickets,
4750                                           struct reserve_ticket, list);
4751         else if (!list_empty(&space_info->tickets))
4752                 ticket = list_first_entry(&space_info->tickets,
4753                                           struct reserve_ticket, list);
4754         bytes_needed = (ticket) ? ticket->bytes : 0;
4755         spin_unlock(&space_info->lock);
4756
4757         if (!bytes_needed)
4758                 return 0;
4759
4760         trans = btrfs_join_transaction(fs_info->extent_root);
4761         if (IS_ERR(trans))
4762                 return PTR_ERR(trans);
4763
4764         /*
4765          * See if there is enough pinned space to make this reservation, or if
4766          * we have block groups that are going to be freed, allowing us to
4767          * possibly do a chunk allocation the next loop through.
4768          */
4769         if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags) ||
4770             __percpu_counter_compare(&space_info->total_bytes_pinned,
4771                                      bytes_needed,
4772                                      BTRFS_TOTAL_BYTES_PINNED_BATCH) >= 0)
4773                 goto commit;
4774
4775         /*
4776          * See if there is some space in the delayed insertion reservation for
4777          * this reservation.
4778          */
4779         if (space_info != delayed_rsv->space_info)
4780                 goto enospc;
4781
4782         spin_lock(&delayed_rsv->lock);
4783         reclaim_bytes += delayed_rsv->reserved;
4784         spin_unlock(&delayed_rsv->lock);
4785
4786         spin_lock(&delayed_refs_rsv->lock);
4787         reclaim_bytes += delayed_refs_rsv->reserved;
4788         spin_unlock(&delayed_refs_rsv->lock);
4789         if (reclaim_bytes >= bytes_needed)
4790                 goto commit;
4791         bytes_needed -= reclaim_bytes;
4792
4793         if (__percpu_counter_compare(&space_info->total_bytes_pinned,
4794                                    bytes_needed,
4795                                    BTRFS_TOTAL_BYTES_PINNED_BATCH) < 0)
4796                 goto enospc;
4797
4798 commit:
4799         return btrfs_commit_transaction(trans);
4800 enospc:
4801         btrfs_end_transaction(trans);
4802         return -ENOSPC;
4803 }
4804
4805 /*
4806  * Try to flush some data based on policy set by @state. This is only advisory
4807  * and may fail for various reasons. The caller is supposed to examine the
4808  * state of @space_info to detect the outcome.
4809  */
4810 static void flush_space(struct btrfs_fs_info *fs_info,
4811                        struct btrfs_space_info *space_info, u64 num_bytes,
4812                        int state)
4813 {
4814         struct btrfs_root *root = fs_info->extent_root;
4815         struct btrfs_trans_handle *trans;
4816         int nr;
4817         int ret = 0;
4818
4819         switch (state) {
4820         case FLUSH_DELAYED_ITEMS_NR:
4821         case FLUSH_DELAYED_ITEMS:
4822                 if (state == FLUSH_DELAYED_ITEMS_NR)
4823                         nr = calc_reclaim_items_nr(fs_info, num_bytes) * 2;
4824                 else
4825                         nr = -1;
4826
4827                 trans = btrfs_join_transaction(root);
4828                 if (IS_ERR(trans)) {
4829                         ret = PTR_ERR(trans);
4830                         break;
4831                 }
4832                 ret = btrfs_run_delayed_items_nr(trans, nr);
4833                 btrfs_end_transaction(trans);
4834                 break;
4835         case FLUSH_DELALLOC:
4836         case FLUSH_DELALLOC_WAIT:
4837                 shrink_delalloc(fs_info, num_bytes * 2, num_bytes,
4838                                 state == FLUSH_DELALLOC_WAIT);
4839                 break;
4840         case FLUSH_DELAYED_REFS_NR:
4841         case FLUSH_DELAYED_REFS:
4842                 trans = btrfs_join_transaction(root);
4843                 if (IS_ERR(trans)) {
4844                         ret = PTR_ERR(trans);
4845                         break;
4846                 }
4847                 if (state == FLUSH_DELAYED_REFS_NR)
4848                         nr = calc_reclaim_items_nr(fs_info, num_bytes);
4849                 else
4850                         nr = 0;
4851                 btrfs_run_delayed_refs(trans, nr);
4852                 btrfs_end_transaction(trans);
4853                 break;
4854         case ALLOC_CHUNK:
4855         case ALLOC_CHUNK_FORCE:
4856                 trans = btrfs_join_transaction(root);
4857                 if (IS_ERR(trans)) {
4858                         ret = PTR_ERR(trans);
4859                         break;
4860                 }
4861                 ret = do_chunk_alloc(trans,
4862                                      btrfs_metadata_alloc_profile(fs_info),
4863                                      (state == ALLOC_CHUNK) ?
4864                                       CHUNK_ALLOC_NO_FORCE : CHUNK_ALLOC_FORCE);
4865                 btrfs_end_transaction(trans);
4866                 if (ret > 0 || ret == -ENOSPC)
4867                         ret = 0;
4868                 break;
4869         case COMMIT_TRANS:
4870                 /*
4871                  * If we have pending delayed iputs then we could free up a
4872                  * bunch of pinned space, so make sure we run the iputs before
4873                  * we do our pinned bytes check below.
4874                  */
4875                 btrfs_run_delayed_iputs(fs_info);
4876                 btrfs_wait_on_delayed_iputs(fs_info);
4877
4878                 ret = may_commit_transaction(fs_info, space_info);
4879                 break;
4880         default:
4881                 ret = -ENOSPC;
4882                 break;
4883         }
4884
4885         trace_btrfs_flush_space(fs_info, space_info->flags, num_bytes, state,
4886                                 ret);
4887         return;
4888 }
4889
4890 static inline u64
4891 btrfs_calc_reclaim_metadata_size(struct btrfs_fs_info *fs_info,
4892                                  struct btrfs_space_info *space_info,
4893                                  bool system_chunk)
4894 {
4895         struct reserve_ticket *ticket;
4896         u64 used;
4897         u64 expected;
4898         u64 to_reclaim = 0;
4899
4900         list_for_each_entry(ticket, &space_info->tickets, list)
4901                 to_reclaim += ticket->bytes;
4902         list_for_each_entry(ticket, &space_info->priority_tickets, list)
4903                 to_reclaim += ticket->bytes;
4904         if (to_reclaim)
4905                 return to_reclaim;
4906
4907         to_reclaim = min_t(u64, num_online_cpus() * SZ_1M, SZ_16M);
4908         if (can_overcommit(fs_info, space_info, to_reclaim,
4909                            BTRFS_RESERVE_FLUSH_ALL, system_chunk))
4910                 return 0;
4911
4912         used = btrfs_space_info_used(space_info, true);
4913
4914         if (can_overcommit(fs_info, space_info, SZ_1M,
4915                            BTRFS_RESERVE_FLUSH_ALL, system_chunk))
4916                 expected = div_factor_fine(space_info->total_bytes, 95);
4917         else
4918                 expected = div_factor_fine(space_info->total_bytes, 90);
4919
4920         if (used > expected)
4921                 to_reclaim = used - expected;
4922         else
4923                 to_reclaim = 0;
4924         to_reclaim = min(to_reclaim, space_info->bytes_may_use +
4925                                      space_info->bytes_reserved);
4926         return to_reclaim;
4927 }
4928
4929 static inline int need_do_async_reclaim(struct btrfs_fs_info *fs_info,
4930                                         struct btrfs_space_info *space_info,
4931                                         u64 used, bool system_chunk)
4932 {
4933         u64 thresh = div_factor_fine(space_info->total_bytes, 98);
4934
4935         /* If we're just plain full then async reclaim just slows us down. */
4936         if ((space_info->bytes_used + space_info->bytes_reserved) >= thresh)
4937                 return 0;
4938
4939         if (!btrfs_calc_reclaim_metadata_size(fs_info, space_info,
4940                                               system_chunk))
4941                 return 0;
4942
4943         return (used >= thresh && !btrfs_fs_closing(fs_info) &&
4944                 !test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
4945 }
4946
4947 static bool wake_all_tickets(struct list_head *head)
4948 {
4949         struct reserve_ticket *ticket;
4950
4951         while (!list_empty(head)) {
4952                 ticket = list_first_entry(head, struct reserve_ticket, list);
4953                 list_del_init(&ticket->list);
4954                 ticket->error = -ENOSPC;
4955                 wake_up(&ticket->wait);
4956                 if (ticket->bytes != ticket->orig_bytes)
4957                         return true;
4958         }
4959         return false;
4960 }
4961
4962 /*
4963  * This is for normal flushers, we can wait all goddamned day if we want to.  We
4964  * will loop and continuously try to flush as long as we are making progress.
4965  * We count progress as clearing off tickets each time we have to loop.
4966  */
4967 static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
4968 {
4969         struct btrfs_fs_info *fs_info;
4970         struct btrfs_space_info *space_info;
4971         u64 to_reclaim;
4972         int flush_state;
4973         int commit_cycles = 0;
4974         u64 last_tickets_id;
4975
4976         fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
4977         space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4978
4979         spin_lock(&space_info->lock);
4980         to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info,
4981                                                       false);
4982         if (!to_reclaim) {
4983                 space_info->flush = 0;
4984                 spin_unlock(&space_info->lock);
4985                 return;
4986         }
4987         last_tickets_id = space_info->tickets_id;
4988         spin_unlock(&space_info->lock);
4989
4990         flush_state = FLUSH_DELAYED_ITEMS_NR;
4991         do {
4992                 flush_space(fs_info, space_info, to_reclaim, flush_state);
4993                 spin_lock(&space_info->lock);
4994                 if (list_empty(&space_info->tickets)) {
4995                         space_info->flush = 0;
4996                         spin_unlock(&space_info->lock);
4997                         return;
4998                 }
4999                 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info,
5000                                                               space_info,
5001                                                               false);
5002                 if (last_tickets_id == space_info->tickets_id) {
5003                         flush_state++;
5004                 } else {
5005                         last_tickets_id = space_info->tickets_id;
5006                         flush_state = FLUSH_DELAYED_ITEMS_NR;
5007                         if (commit_cycles)
5008                                 commit_cycles--;
5009                 }
5010
5011                 /*
5012                  * We don't want to force a chunk allocation until we've tried
5013                  * pretty hard to reclaim space.  Think of the case where we
5014                  * freed up a bunch of space and so have a lot of pinned space
5015                  * to reclaim.  We would rather use that than possibly create a
5016                  * underutilized metadata chunk.  So if this is our first run
5017                  * through the flushing state machine skip ALLOC_CHUNK_FORCE and
5018                  * commit the transaction.  If nothing has changed the next go
5019                  * around then we can force a chunk allocation.
5020                  */
5021                 if (flush_state == ALLOC_CHUNK_FORCE && !commit_cycles)
5022                         flush_state++;
5023
5024                 if (flush_state > COMMIT_TRANS) {
5025                         commit_cycles++;
5026                         if (commit_cycles > 2) {
5027                                 if (wake_all_tickets(&space_info->tickets)) {
5028                                         flush_state = FLUSH_DELAYED_ITEMS_NR;
5029                                         commit_cycles--;
5030                                 } else {
5031                                         space_info->flush = 0;
5032                                 }
5033                         } else {
5034                                 flush_state = FLUSH_DELAYED_ITEMS_NR;
5035                         }
5036                 }
5037                 spin_unlock(&space_info->lock);
5038         } while (flush_state <= COMMIT_TRANS);
5039 }
5040
5041 void btrfs_init_async_reclaim_work(struct work_struct *work)
5042 {
5043         INIT_WORK(work, btrfs_async_reclaim_metadata_space);
5044 }
5045
5046 static const enum btrfs_flush_state priority_flush_states[] = {
5047         FLUSH_DELAYED_ITEMS_NR,
5048         FLUSH_DELAYED_ITEMS,
5049         ALLOC_CHUNK,
5050 };
5051
5052 static void priority_reclaim_metadata_space(struct btrfs_fs_info *fs_info,
5053                                             struct btrfs_space_info *space_info,
5054                                             struct reserve_ticket *ticket)
5055 {
5056         u64 to_reclaim;
5057         int flush_state;
5058
5059         spin_lock(&space_info->lock);
5060         to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info,
5061                                                       false);
5062         if (!to_reclaim) {
5063                 spin_unlock(&space_info->lock);
5064                 return;
5065         }
5066         spin_unlock(&space_info->lock);
5067
5068         flush_state = 0;
5069         do {
5070                 flush_space(fs_info, space_info, to_reclaim,
5071                             priority_flush_states[flush_state]);
5072                 flush_state++;
5073                 spin_lock(&space_info->lock);
5074                 if (ticket->bytes == 0) {
5075                         spin_unlock(&space_info->lock);
5076                         return;
5077                 }
5078                 spin_unlock(&space_info->lock);
5079         } while (flush_state < ARRAY_SIZE(priority_flush_states));
5080 }
5081
5082 static int wait_reserve_ticket(struct btrfs_fs_info *fs_info,
5083                                struct btrfs_space_info *space_info,
5084                                struct reserve_ticket *ticket)
5085
5086 {
5087         DEFINE_WAIT(wait);
5088         u64 reclaim_bytes = 0;
5089         int ret = 0;
5090
5091         spin_lock(&space_info->lock);
5092         while (ticket->bytes > 0 && ticket->error == 0) {
5093                 ret = prepare_to_wait_event(&ticket->wait, &wait, TASK_KILLABLE);
5094                 if (ret) {
5095                         ret = -EINTR;
5096                         break;
5097                 }
5098                 spin_unlock(&space_info->lock);
5099
5100                 schedule();
5101
5102                 finish_wait(&ticket->wait, &wait);
5103                 spin_lock(&space_info->lock);
5104         }
5105         if (!ret)
5106                 ret = ticket->error;
5107         if (!list_empty(&ticket->list))
5108                 list_del_init(&ticket->list);
5109         if (ticket->bytes && ticket->bytes < ticket->orig_bytes)
5110                 reclaim_bytes = ticket->orig_bytes - ticket->bytes;
5111         spin_unlock(&space_info->lock);
5112
5113         if (reclaim_bytes)
5114                 space_info_add_old_bytes(fs_info, space_info, reclaim_bytes);
5115         return ret;
5116 }
5117
5118 /**
5119  * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5120  * @root - the root we're allocating for
5121  * @space_info - the space info we want to allocate from
5122  * @orig_bytes - the number of bytes we want
5123  * @flush - whether or not we can flush to make our reservation
5124  *
5125  * This will reserve orig_bytes number of bytes from the space info associated
5126  * with the block_rsv.  If there is not enough space it will make an attempt to
5127  * flush out space to make room.  It will do this by flushing delalloc if
5128  * possible or committing the transaction.  If flush is 0 then no attempts to
5129  * regain reservations will be made and this will fail if there is not enough
5130  * space already.
5131  */
5132 static int __reserve_metadata_bytes(struct btrfs_fs_info *fs_info,
5133                                     struct btrfs_space_info *space_info,
5134                                     u64 orig_bytes,
5135                                     enum btrfs_reserve_flush_enum flush,
5136                                     bool system_chunk)
5137 {
5138         struct reserve_ticket ticket;
5139         u64 used;
5140         u64 reclaim_bytes = 0;
5141         int ret = 0;
5142
5143         ASSERT(orig_bytes);
5144         ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_ALL);
5145
5146         spin_lock(&space_info->lock);
5147         ret = -ENOSPC;
5148         used = btrfs_space_info_used(space_info, true);
5149
5150         /*
5151          * If we have enough space then hooray, make our reservation and carry
5152          * on.  If not see if we can overcommit, and if we can, hooray carry on.
5153          * If not things get more complicated.
5154          */
5155         if (used + orig_bytes <= space_info->total_bytes) {
5156                 update_bytes_may_use(space_info, orig_bytes);
5157                 trace_btrfs_space_reservation(fs_info, "space_info",
5158                                               space_info->flags, orig_bytes, 1);
5159                 ret = 0;
5160         } else if (can_overcommit(fs_info, space_info, orig_bytes, flush,
5161                                   system_chunk)) {
5162                 update_bytes_may_use(space_info, orig_bytes);
5163                 trace_btrfs_space_reservation(fs_info, "space_info",
5164                                               space_info->flags, orig_bytes, 1);
5165                 ret = 0;
5166         }
5167
5168         /*
5169          * If we couldn't make a reservation then setup our reservation ticket
5170          * and kick the async worker if it's not already running.
5171          *
5172          * If we are a priority flusher then we just need to add our ticket to
5173          * the list and we will do our own flushing further down.
5174          */
5175         if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
5176                 ticket.orig_bytes = orig_bytes;
5177                 ticket.bytes = orig_bytes;
5178                 ticket.error = 0;
5179                 init_waitqueue_head(&ticket.wait);
5180                 if (flush == BTRFS_RESERVE_FLUSH_ALL) {
5181                         list_add_tail(&ticket.list, &space_info->tickets);
5182                         if (!space_info->flush) {
5183                                 space_info->flush = 1;
5184                                 trace_btrfs_trigger_flush(fs_info,
5185                                                           space_info->flags,
5186                                                           orig_bytes, flush,
5187                                                           "enospc");
5188                                 queue_work(system_unbound_wq,
5189                                            &fs_info->async_reclaim_work);
5190                         }
5191                 } else {
5192                         list_add_tail(&ticket.list,
5193                                       &space_info->priority_tickets);
5194                 }
5195         } else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
5196                 used += orig_bytes;
5197                 /*
5198                  * We will do the space reservation dance during log replay,
5199                  * which means we won't have fs_info->fs_root set, so don't do
5200                  * the async reclaim as we will panic.
5201                  */
5202                 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags) &&
5203                     need_do_async_reclaim(fs_info, space_info,
5204                                           used, system_chunk) &&
5205                     !work_busy(&fs_info->async_reclaim_work)) {
5206                         trace_btrfs_trigger_flush(fs_info, space_info->flags,
5207                                                   orig_bytes, flush, "preempt");
5208                         queue_work(system_unbound_wq,
5209                                    &fs_info->async_reclaim_work);
5210                 }
5211         }
5212         spin_unlock(&space_info->lock);
5213         if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
5214                 return ret;
5215
5216         if (flush == BTRFS_RESERVE_FLUSH_ALL)
5217                 return wait_reserve_ticket(fs_info, space_info, &ticket);
5218
5219         ret = 0;
5220         priority_reclaim_metadata_space(fs_info, space_info, &ticket);
5221         spin_lock(&space_info->lock);
5222         if (ticket.bytes) {
5223                 if (ticket.bytes < orig_bytes)
5224                         reclaim_bytes = orig_bytes - ticket.bytes;
5225                 list_del_init(&ticket.list);
5226                 ret = -ENOSPC;
5227         }
5228         spin_unlock(&space_info->lock);
5229
5230         if (reclaim_bytes)
5231                 space_info_add_old_bytes(fs_info, space_info, reclaim_bytes);
5232         ASSERT(list_empty(&ticket.list));
5233         return ret;
5234 }
5235
5236 /**
5237  * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5238  * @root - the root we're allocating for
5239  * @block_rsv - the block_rsv we're allocating for
5240  * @orig_bytes - the number of bytes we want
5241  * @flush - whether or not we can flush to make our reservation
5242  *
5243  * This will reserve orig_bytes number of bytes from the space info associated
5244  * with the block_rsv.  If there is not enough space it will make an attempt to
5245  * flush out space to make room.  It will do this by flushing delalloc if
5246  * possible or committing the transaction.  If flush is 0 then no attempts to
5247  * regain reservations will be made and this will fail if there is not enough
5248  * space already.
5249  */
5250 static int reserve_metadata_bytes(struct btrfs_root *root,
5251                                   struct btrfs_block_rsv *block_rsv,
5252                                   u64 orig_bytes,
5253                                   enum btrfs_reserve_flush_enum flush)
5254 {
5255         struct btrfs_fs_info *fs_info = root->fs_info;
5256         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5257         int ret;
5258         bool system_chunk = (root == fs_info->chunk_root);
5259
5260         ret = __reserve_metadata_bytes(fs_info, block_rsv->space_info,
5261                                        orig_bytes, flush, system_chunk);
5262         if (ret == -ENOSPC &&
5263             unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
5264                 if (block_rsv != global_rsv &&
5265                     !block_rsv_use_bytes(global_rsv, orig_bytes))
5266                         ret = 0;
5267         }
5268         if (ret == -ENOSPC) {
5269                 trace_btrfs_space_reservation(fs_info, "space_info:enospc",
5270                                               block_rsv->space_info->flags,
5271                                               orig_bytes, 1);
5272
5273                 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG))
5274                         dump_space_info(fs_info, block_rsv->space_info,
5275                                         orig_bytes, 0);
5276         }
5277         return ret;
5278 }
5279
5280 static struct btrfs_block_rsv *get_block_rsv(
5281                                         const struct btrfs_trans_handle *trans,
5282                                         const struct btrfs_root *root)
5283 {
5284         struct btrfs_fs_info *fs_info = root->fs_info;
5285         struct btrfs_block_rsv *block_rsv = NULL;
5286
5287         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
5288             (root == fs_info->csum_root && trans->adding_csums) ||
5289             (root == fs_info->uuid_root))
5290                 block_rsv = trans->block_rsv;
5291
5292         if (!block_rsv)
5293                 block_rsv = root->block_rsv;
5294
5295         if (!block_rsv)
5296                 block_rsv = &fs_info->empty_block_rsv;
5297
5298         return block_rsv;
5299 }
5300
5301 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
5302                                u64 num_bytes)
5303 {
5304         int ret = -ENOSPC;
5305         spin_lock(&block_rsv->lock);
5306         if (block_rsv->reserved >= num_bytes) {
5307                 block_rsv->reserved -= num_bytes;
5308                 if (block_rsv->reserved < block_rsv->size)
5309                         block_rsv->full = 0;
5310                 ret = 0;
5311         }
5312         spin_unlock(&block_rsv->lock);
5313         return ret;
5314 }
5315
5316 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
5317                                 u64 num_bytes, bool update_size)
5318 {
5319         spin_lock(&block_rsv->lock);
5320         block_rsv->reserved += num_bytes;
5321         if (update_size)
5322                 block_rsv->size += num_bytes;
5323         else if (block_rsv->reserved >= block_rsv->size)
5324                 block_rsv->full = 1;
5325         spin_unlock(&block_rsv->lock);
5326 }
5327
5328 int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
5329                              struct btrfs_block_rsv *dest, u64 num_bytes,
5330                              int min_factor)
5331 {
5332         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5333         u64 min_bytes;
5334
5335         if (global_rsv->space_info != dest->space_info)
5336                 return -ENOSPC;
5337
5338         spin_lock(&global_rsv->lock);
5339         min_bytes = div_factor(global_rsv->size, min_factor);
5340         if (global_rsv->reserved < min_bytes + num_bytes) {
5341                 spin_unlock(&global_rsv->lock);
5342                 return -ENOSPC;
5343         }
5344         global_rsv->reserved -= num_bytes;
5345         if (global_rsv->reserved < global_rsv->size)
5346                 global_rsv->full = 0;
5347         spin_unlock(&global_rsv->lock);
5348
5349         block_rsv_add_bytes(dest, num_bytes, true);
5350         return 0;
5351 }
5352
5353 /**
5354  * btrfs_migrate_to_delayed_refs_rsv - transfer bytes to our delayed refs rsv.
5355  * @fs_info - the fs info for our fs.
5356  * @src - the source block rsv to transfer from.
5357  * @num_bytes - the number of bytes to transfer.
5358  *
5359  * This transfers up to the num_bytes amount from the src rsv to the
5360  * delayed_refs_rsv.  Any extra bytes are returned to the space info.
5361  */
5362 void btrfs_migrate_to_delayed_refs_rsv(struct btrfs_fs_info *fs_info,
5363                                        struct btrfs_block_rsv *src,
5364                                        u64 num_bytes)
5365 {
5366         struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
5367         u64 to_free = 0;
5368
5369         spin_lock(&src->lock);
5370         src->reserved -= num_bytes;
5371         src->size -= num_bytes;
5372         spin_unlock(&src->lock);
5373
5374         spin_lock(&delayed_refs_rsv->lock);
5375         if (delayed_refs_rsv->size > delayed_refs_rsv->reserved) {
5376                 u64 delta = delayed_refs_rsv->size -
5377                         delayed_refs_rsv->reserved;
5378                 if (num_bytes > delta) {
5379                         to_free = num_bytes - delta;
5380                         num_bytes = delta;
5381                 }
5382         } else {
5383                 to_free = num_bytes;
5384                 num_bytes = 0;
5385         }
5386
5387         if (num_bytes)
5388                 delayed_refs_rsv->reserved += num_bytes;
5389         if (delayed_refs_rsv->reserved >= delayed_refs_rsv->size)
5390                 delayed_refs_rsv->full = 1;
5391         spin_unlock(&delayed_refs_rsv->lock);
5392
5393         if (num_bytes)
5394                 trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
5395                                               0, num_bytes, 1);
5396         if (to_free)
5397                 space_info_add_old_bytes(fs_info, delayed_refs_rsv->space_info,
5398                                          to_free);
5399 }
5400
5401 /**
5402  * btrfs_delayed_refs_rsv_refill - refill based on our delayed refs usage.
5403  * @fs_info - the fs_info for our fs.
5404  * @flush - control how we can flush for this reservation.
5405  *
5406  * This will refill the delayed block_rsv up to 1 items size worth of space and
5407  * will return -ENOSPC if we can't make the reservation.
5408  */
5409 int btrfs_delayed_refs_rsv_refill(struct btrfs_fs_info *fs_info,
5410                                   enum btrfs_reserve_flush_enum flush)
5411 {
5412         struct btrfs_block_rsv *block_rsv = &fs_info->delayed_refs_rsv;
5413         u64 limit = btrfs_calc_trans_metadata_size(fs_info, 1);
5414         u64 num_bytes = 0;
5415         int ret = -ENOSPC;
5416
5417         spin_lock(&block_rsv->lock);
5418         if (block_rsv->reserved < block_rsv->size) {
5419                 num_bytes = block_rsv->size - block_rsv->reserved;
5420                 num_bytes = min(num_bytes, limit);
5421         }
5422         spin_unlock(&block_rsv->lock);
5423
5424         if (!num_bytes)
5425                 return 0;
5426
5427         ret = reserve_metadata_bytes(fs_info->extent_root, block_rsv,
5428                                      num_bytes, flush);
5429         if (ret)
5430                 return ret;
5431         block_rsv_add_bytes(block_rsv, num_bytes, 0);
5432         trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
5433                                       0, num_bytes, 1);
5434         return 0;
5435 }
5436
5437 /*
5438  * This is for space we already have accounted in space_info->bytes_may_use, so
5439  * basically when we're returning space from block_rsv's.
5440  */
5441 static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
5442                                      struct btrfs_space_info *space_info,
5443                                      u64 num_bytes)
5444 {
5445         struct reserve_ticket *ticket;
5446         struct list_head *head;
5447         u64 used;
5448         enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_NO_FLUSH;
5449         bool check_overcommit = false;
5450
5451         spin_lock(&space_info->lock);
5452         head = &space_info->priority_tickets;
5453
5454         /*
5455          * If we are over our limit then we need to check and see if we can
5456          * overcommit, and if we can't then we just need to free up our space
5457          * and not satisfy any requests.
5458          */
5459         used = btrfs_space_info_used(space_info, true);
5460         if (used - num_bytes >= space_info->total_bytes)
5461                 check_overcommit = true;
5462 again:
5463         while (!list_empty(head) && num_bytes) {
5464                 ticket = list_first_entry(head, struct reserve_ticket,
5465                                           list);
5466                 /*
5467                  * We use 0 bytes because this space is already reserved, so
5468                  * adding the ticket space would be a double count.
5469                  */
5470                 if (check_overcommit &&
5471                     !can_overcommit(fs_info, space_info, 0, flush, false))
5472                         break;
5473                 if (num_bytes >= ticket->bytes) {
5474                         list_del_init(&ticket->list);
5475                         num_bytes -= ticket->bytes;
5476                         ticket->bytes = 0;
5477                         space_info->tickets_id++;
5478                         wake_up(&ticket->wait);
5479                 } else {
5480                         ticket->bytes -= num_bytes;
5481                         num_bytes = 0;
5482                 }
5483         }
5484
5485         if (num_bytes && head == &space_info->priority_tickets) {
5486                 head = &space_info->tickets;
5487                 flush = BTRFS_RESERVE_FLUSH_ALL;
5488                 goto again;
5489         }
5490         update_bytes_may_use(space_info, -num_bytes);
5491         trace_btrfs_space_reservation(fs_info, "space_info",
5492                                       space_info->flags, num_bytes, 0);
5493         spin_unlock(&space_info->lock);
5494 }
5495
5496 /*
5497  * This is for newly allocated space that isn't accounted in
5498  * space_info->bytes_may_use yet.  So if we allocate a chunk or unpin an extent
5499  * we use this helper.
5500  */
5501 static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
5502                                      struct btrfs_space_info *space_info,
5503                                      u64 num_bytes)
5504 {
5505         struct reserve_ticket *ticket;
5506         struct list_head *head = &space_info->priority_tickets;
5507
5508 again:
5509         while (!list_empty(head) && num_bytes) {
5510                 ticket = list_first_entry(head, struct reserve_ticket,
5511                                           list);
5512                 if (num_bytes >= ticket->bytes) {
5513                         trace_btrfs_space_reservation(fs_info, "space_info",
5514                                                       space_info->flags,
5515                                                       ticket->bytes, 1);
5516                         list_del_init(&ticket->list);
5517                         num_bytes -= ticket->bytes;
5518                         update_bytes_may_use(space_info, ticket->bytes);
5519                         ticket->bytes = 0;
5520                         space_info->tickets_id++;
5521                         wake_up(&ticket->wait);
5522                 } else {
5523                         trace_btrfs_space_reservation(fs_info, "space_info",
5524                                                       space_info->flags,
5525                                                       num_bytes, 1);
5526                         update_bytes_may_use(space_info, num_bytes);
5527                         ticket->bytes -= num_bytes;
5528                         num_bytes = 0;
5529                 }
5530         }
5531
5532         if (num_bytes && head == &space_info->priority_tickets) {
5533                 head = &space_info->tickets;
5534                 goto again;
5535         }
5536 }
5537
5538 static u64 block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
5539                                     struct btrfs_block_rsv *block_rsv,
5540                                     struct btrfs_block_rsv *dest, u64 num_bytes,
5541                                     u64 *qgroup_to_release_ret)
5542 {
5543         struct btrfs_space_info *space_info = block_rsv->space_info;
5544         u64 qgroup_to_release = 0;
5545         u64 ret;
5546
5547         spin_lock(&block_rsv->lock);
5548         if (num_bytes == (u64)-1) {
5549                 num_bytes = block_rsv->size;
5550                 qgroup_to_release = block_rsv->qgroup_rsv_size;
5551         }
5552         block_rsv->size -= num_bytes;
5553         if (block_rsv->reserved >= block_rsv->size) {
5554                 num_bytes = block_rsv->reserved - block_rsv->size;
5555                 block_rsv->reserved = block_rsv->size;
5556                 block_rsv->full = 1;
5557         } else {
5558                 num_bytes = 0;
5559         }
5560         if (block_rsv->qgroup_rsv_reserved >= block_rsv->qgroup_rsv_size) {
5561                 qgroup_to_release = block_rsv->qgroup_rsv_reserved -
5562                                     block_rsv->qgroup_rsv_size;
5563                 block_rsv->qgroup_rsv_reserved = block_rsv->qgroup_rsv_size;
5564         } else {
5565                 qgroup_to_release = 0;
5566         }
5567         spin_unlock(&block_rsv->lock);
5568
5569         ret = num_bytes;
5570         if (num_bytes > 0) {
5571                 if (dest) {
5572                         spin_lock(&dest->lock);
5573                         if (!dest->full) {
5574                                 u64 bytes_to_add;
5575
5576                                 bytes_to_add = dest->size - dest->reserved;
5577                                 bytes_to_add = min(num_bytes, bytes_to_add);
5578                                 dest->reserved += bytes_to_add;
5579                                 if (dest->reserved >= dest->size)
5580                                         dest->full = 1;
5581                                 num_bytes -= bytes_to_add;
5582                         }
5583                         spin_unlock(&dest->lock);
5584                 }
5585                 if (num_bytes)
5586                         space_info_add_old_bytes(fs_info, space_info,
5587                                                  num_bytes);
5588         }
5589         if (qgroup_to_release_ret)
5590                 *qgroup_to_release_ret = qgroup_to_release;
5591         return ret;
5592 }
5593
5594 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src,
5595                             struct btrfs_block_rsv *dst, u64 num_bytes,
5596                             bool update_size)
5597 {
5598         int ret;
5599
5600         ret = block_rsv_use_bytes(src, num_bytes);
5601         if (ret)
5602                 return ret;
5603
5604         block_rsv_add_bytes(dst, num_bytes, update_size);
5605         return 0;
5606 }
5607
5608 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
5609 {
5610         memset(rsv, 0, sizeof(*rsv));
5611         spin_lock_init(&rsv->lock);
5612         rsv->type = type;
5613 }
5614
5615 void btrfs_init_metadata_block_rsv(struct btrfs_fs_info *fs_info,
5616                                    struct btrfs_block_rsv *rsv,
5617                                    unsigned short type)
5618 {
5619         btrfs_init_block_rsv(rsv, type);
5620         rsv->space_info = __find_space_info(fs_info,
5621                                             BTRFS_BLOCK_GROUP_METADATA);
5622 }
5623
5624 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_fs_info *fs_info,
5625                                               unsigned short type)
5626 {
5627         struct btrfs_block_rsv *block_rsv;
5628
5629         block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
5630         if (!block_rsv)
5631                 return NULL;
5632
5633         btrfs_init_metadata_block_rsv(fs_info, block_rsv, type);
5634         return block_rsv;
5635 }
5636
5637 void btrfs_free_block_rsv(struct btrfs_fs_info *fs_info,
5638                           struct btrfs_block_rsv *rsv)
5639 {
5640         if (!rsv)
5641                 return;
5642         btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
5643         kfree(rsv);
5644 }
5645
5646 int btrfs_block_rsv_add(struct btrfs_root *root,
5647                         struct btrfs_block_rsv *block_rsv, u64 num_bytes,
5648                         enum btrfs_reserve_flush_enum flush)
5649 {
5650         int ret;
5651
5652         if (num_bytes == 0)
5653                 return 0;
5654
5655         ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5656         if (!ret)
5657                 block_rsv_add_bytes(block_rsv, num_bytes, true);
5658
5659         return ret;
5660 }
5661
5662 int btrfs_block_rsv_check(struct btrfs_block_rsv *block_rsv, int min_factor)
5663 {
5664         u64 num_bytes = 0;
5665         int ret = -ENOSPC;
5666
5667         if (!block_rsv)
5668                 return 0;
5669
5670         spin_lock(&block_rsv->lock);
5671         num_bytes = div_factor(block_rsv->size, min_factor);
5672         if (block_rsv->reserved >= num_bytes)
5673                 ret = 0;
5674         spin_unlock(&block_rsv->lock);
5675
5676         return ret;
5677 }
5678
5679 int btrfs_block_rsv_refill(struct btrfs_root *root,
5680                            struct btrfs_block_rsv *block_rsv, u64 min_reserved,
5681                            enum btrfs_reserve_flush_enum flush)
5682 {
5683         u64 num_bytes = 0;
5684         int ret = -ENOSPC;
5685
5686         if (!block_rsv)
5687                 return 0;
5688
5689         spin_lock(&block_rsv->lock);
5690         num_bytes = min_reserved;
5691         if (block_rsv->reserved >= num_bytes)
5692                 ret = 0;
5693         else
5694                 num_bytes -= block_rsv->reserved;
5695         spin_unlock(&block_rsv->lock);
5696
5697         if (!ret)
5698                 return 0;
5699
5700         ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5701         if (!ret) {
5702                 block_rsv_add_bytes(block_rsv, num_bytes, false);
5703                 return 0;
5704         }
5705
5706         return ret;
5707 }
5708
5709 static void calc_refill_bytes(struct btrfs_block_rsv *block_rsv,
5710                                 u64 *metadata_bytes, u64 *qgroup_bytes)
5711 {
5712         *metadata_bytes = 0;
5713         *qgroup_bytes = 0;
5714
5715         spin_lock(&block_rsv->lock);
5716         if (block_rsv->reserved < block_rsv->size)
5717                 *metadata_bytes = block_rsv->size - block_rsv->reserved;
5718         if (block_rsv->qgroup_rsv_reserved < block_rsv->qgroup_rsv_size)
5719                 *qgroup_bytes = block_rsv->qgroup_rsv_size -
5720                         block_rsv->qgroup_rsv_reserved;
5721         spin_unlock(&block_rsv->lock);
5722 }
5723
5724 /**
5725  * btrfs_inode_rsv_refill - refill the inode block rsv.
5726  * @inode - the inode we are refilling.
5727  * @flush - the flushing restriction.
5728  *
5729  * Essentially the same as btrfs_block_rsv_refill, except it uses the
5730  * block_rsv->size as the minimum size.  We'll either refill the missing amount
5731  * or return if we already have enough space.  This will also handle the reserve
5732  * tracepoint for the reserved amount.
5733  */
5734 static int btrfs_inode_rsv_refill(struct btrfs_inode *inode,
5735                                   enum btrfs_reserve_flush_enum flush)
5736 {
5737         struct btrfs_root *root = inode->root;
5738         struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
5739         u64 num_bytes, last = 0;
5740         u64 qgroup_num_bytes;
5741         int ret = -ENOSPC;
5742
5743         calc_refill_bytes(block_rsv, &num_bytes, &qgroup_num_bytes);
5744         if (num_bytes == 0)
5745                 return 0;
5746
5747         do {
5748                 ret = btrfs_qgroup_reserve_meta_prealloc(root, qgroup_num_bytes,
5749                                                          true);
5750                 if (ret)
5751                         return ret;
5752                 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5753                 if (ret) {
5754                         btrfs_qgroup_free_meta_prealloc(root, qgroup_num_bytes);
5755                         last = num_bytes;
5756                         /*
5757                          * If we are fragmented we can end up with a lot of
5758                          * outstanding extents which will make our size be much
5759                          * larger than our reserved amount.
5760                          *
5761                          * If the reservation happens here, it might be very
5762                          * big though not needed in the end, if the delalloc
5763                          * flushing happens.
5764                          *
5765                          * If this is the case try and do the reserve again.
5766                          */
5767                         if (flush == BTRFS_RESERVE_FLUSH_ALL)
5768                                 calc_refill_bytes(block_rsv, &num_bytes,
5769                                                    &qgroup_num_bytes);
5770                         if (num_bytes == 0)
5771                                 return 0;
5772                 }
5773         } while (ret && last != num_bytes);
5774
5775         if (!ret) {
5776                 block_rsv_add_bytes(block_rsv, num_bytes, false);
5777                 trace_btrfs_space_reservation(root->fs_info, "delalloc",
5778                                               btrfs_ino(inode), num_bytes, 1);
5779
5780                 /* Don't forget to increase qgroup_rsv_reserved */
5781                 spin_lock(&block_rsv->lock);
5782                 block_rsv->qgroup_rsv_reserved += qgroup_num_bytes;
5783                 spin_unlock(&block_rsv->lock);
5784         }
5785         return ret;
5786 }
5787
5788 static u64 __btrfs_block_rsv_release(struct btrfs_fs_info *fs_info,
5789                                      struct btrfs_block_rsv *block_rsv,
5790                                      u64 num_bytes, u64 *qgroup_to_release)
5791 {
5792         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5793         struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_refs_rsv;
5794         struct btrfs_block_rsv *target = delayed_rsv;
5795
5796         if (target->full || target == block_rsv)
5797                 target = global_rsv;
5798
5799         if (block_rsv->space_info != target->space_info)
5800                 target = NULL;
5801
5802         return block_rsv_release_bytes(fs_info, block_rsv, target, num_bytes,
5803                                        qgroup_to_release);
5804 }
5805
5806 void btrfs_block_rsv_release(struct btrfs_fs_info *fs_info,
5807                              struct btrfs_block_rsv *block_rsv,
5808                              u64 num_bytes)
5809 {
5810         __btrfs_block_rsv_release(fs_info, block_rsv, num_bytes, NULL);
5811 }
5812
5813 /**
5814  * btrfs_inode_rsv_release - release any excessive reservation.
5815  * @inode - the inode we need to release from.
5816  * @qgroup_free - free or convert qgroup meta.
5817  *   Unlike normal operation, qgroup meta reservation needs to know if we are
5818  *   freeing qgroup reservation or just converting it into per-trans.  Normally
5819  *   @qgroup_free is true for error handling, and false for normal release.
5820  *
5821  * This is the same as btrfs_block_rsv_release, except that it handles the
5822  * tracepoint for the reservation.
5823  */
5824 static void btrfs_inode_rsv_release(struct btrfs_inode *inode, bool qgroup_free)
5825 {
5826         struct btrfs_fs_info *fs_info = inode->root->fs_info;
5827         struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
5828         u64 released = 0;
5829         u64 qgroup_to_release = 0;
5830
5831         /*
5832          * Since we statically set the block_rsv->size we just want to say we
5833          * are releasing 0 bytes, and then we'll just get the reservation over
5834          * the size free'd.
5835          */
5836         released = __btrfs_block_rsv_release(fs_info, block_rsv, 0,
5837                                              &qgroup_to_release);
5838         if (released > 0)
5839                 trace_btrfs_space_reservation(fs_info, "delalloc",
5840                                               btrfs_ino(inode), released, 0);
5841         if (qgroup_free)
5842                 btrfs_qgroup_free_meta_prealloc(inode->root, qgroup_to_release);
5843         else
5844                 btrfs_qgroup_convert_reserved_meta(inode->root,
5845                                                    qgroup_to_release);
5846 }
5847
5848 /**
5849  * btrfs_delayed_refs_rsv_release - release a ref head's reservation.
5850  * @fs_info - the fs_info for our fs.
5851  * @nr - the number of items to drop.
5852  *
5853  * This drops the delayed ref head's count from the delayed refs rsv and frees
5854  * any excess reservation we had.
5855  */
5856 void btrfs_delayed_refs_rsv_release(struct btrfs_fs_info *fs_info, int nr)
5857 {
5858         struct btrfs_block_rsv *block_rsv = &fs_info->delayed_refs_rsv;
5859         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5860         u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, nr);
5861         u64 released = 0;
5862
5863         released = block_rsv_release_bytes(fs_info, block_rsv, global_rsv,
5864                                            num_bytes, NULL);
5865         if (released)
5866                 trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
5867                                               0, released, 0);
5868 }
5869
5870 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
5871 {
5872         struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
5873         struct btrfs_space_info *sinfo = block_rsv->space_info;
5874         u64 num_bytes;
5875
5876         /*
5877          * The global block rsv is based on the size of the extent tree, the
5878          * checksum tree and the root tree.  If the fs is empty we want to set
5879          * it to a minimal amount for safety.
5880          */
5881         num_bytes = btrfs_root_used(&fs_info->extent_root->root_item) +
5882                 btrfs_root_used(&fs_info->csum_root->root_item) +
5883                 btrfs_root_used(&fs_info->tree_root->root_item);
5884         num_bytes = max_t(u64, num_bytes, SZ_16M);
5885
5886         spin_lock(&sinfo->lock);
5887         spin_lock(&block_rsv->lock);
5888
5889         block_rsv->size = min_t(u64, num_bytes, SZ_512M);
5890
5891         if (block_rsv->reserved < block_rsv->size) {
5892                 num_bytes = btrfs_space_info_used(sinfo, true);
5893                 if (sinfo->total_bytes > num_bytes) {
5894                         num_bytes = sinfo->total_bytes - num_bytes;
5895                         num_bytes = min(num_bytes,
5896                                         block_rsv->size - block_rsv->reserved);
5897                         block_rsv->reserved += num_bytes;
5898                         update_bytes_may_use(sinfo, num_bytes);
5899                         trace_btrfs_space_reservation(fs_info, "space_info",
5900                                                       sinfo->flags, num_bytes,
5901                                                       1);
5902                 }
5903         } else if (block_rsv->reserved > block_rsv->size) {
5904                 num_bytes = block_rsv->reserved - block_rsv->size;
5905                 update_bytes_may_use(sinfo, -num_bytes);
5906                 trace_btrfs_space_reservation(fs_info, "space_info",
5907                                       sinfo->flags, num_bytes, 0);
5908                 block_rsv->reserved = block_rsv->size;
5909         }
5910
5911         if (block_rsv->reserved == block_rsv->size)
5912                 block_rsv->full = 1;
5913         else
5914                 block_rsv->full = 0;
5915
5916         spin_unlock(&block_rsv->lock);
5917         spin_unlock(&sinfo->lock);
5918 }
5919
5920 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
5921 {
5922         struct btrfs_space_info *space_info;
5923
5924         space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
5925         fs_info->chunk_block_rsv.space_info = space_info;
5926
5927         space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
5928         fs_info->global_block_rsv.space_info = space_info;
5929         fs_info->trans_block_rsv.space_info = space_info;
5930         fs_info->empty_block_rsv.space_info = space_info;
5931         fs_info->delayed_block_rsv.space_info = space_info;
5932         fs_info->delayed_refs_rsv.space_info = space_info;
5933
5934         fs_info->extent_root->block_rsv = &fs_info->delayed_refs_rsv;
5935         fs_info->csum_root->block_rsv = &fs_info->delayed_refs_rsv;
5936         fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
5937         fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
5938         if (fs_info->quota_root)
5939                 fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
5940         fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
5941
5942         update_global_block_rsv(fs_info);
5943 }
5944
5945 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
5946 {
5947         block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
5948                                 (u64)-1, NULL);
5949         WARN_ON(fs_info->trans_block_rsv.size > 0);
5950         WARN_ON(fs_info->trans_block_rsv.reserved > 0);
5951         WARN_ON(fs_info->chunk_block_rsv.size > 0);
5952         WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
5953         WARN_ON(fs_info->delayed_block_rsv.size > 0);
5954         WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
5955         WARN_ON(fs_info->delayed_refs_rsv.reserved > 0);
5956         WARN_ON(fs_info->delayed_refs_rsv.size > 0);
5957 }
5958
5959 /*
5960  * btrfs_update_delayed_refs_rsv - adjust the size of the delayed refs rsv
5961  * @trans - the trans that may have generated delayed refs
5962  *
5963  * This is to be called anytime we may have adjusted trans->delayed_ref_updates,
5964  * it'll calculate the additional size and add it to the delayed_refs_rsv.
5965  */
5966 void btrfs_update_delayed_refs_rsv(struct btrfs_trans_handle *trans)
5967 {
5968         struct btrfs_fs_info *fs_info = trans->fs_info;
5969         struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_refs_rsv;
5970         u64 num_bytes;
5971
5972         if (!trans->delayed_ref_updates)
5973                 return;
5974
5975         num_bytes = btrfs_calc_trans_metadata_size(fs_info,
5976                                                    trans->delayed_ref_updates);
5977         spin_lock(&delayed_rsv->lock);
5978         delayed_rsv->size += num_bytes;
5979         delayed_rsv->full = 0;
5980         spin_unlock(&delayed_rsv->lock);
5981         trans->delayed_ref_updates = 0;
5982 }
5983
5984 /*
5985  * To be called after all the new block groups attached to the transaction
5986  * handle have been created (btrfs_create_pending_block_groups()).
5987  */
5988 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
5989 {
5990         struct btrfs_fs_info *fs_info = trans->fs_info;
5991
5992         if (!trans->chunk_bytes_reserved)
5993                 return;
5994
5995         WARN_ON_ONCE(!list_empty(&trans->new_bgs));
5996
5997         block_rsv_release_bytes(fs_info, &fs_info->chunk_block_rsv, NULL,
5998                                 trans->chunk_bytes_reserved, NULL);
5999         trans->chunk_bytes_reserved = 0;
6000 }
6001
6002 /*
6003  * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
6004  * root: the root of the parent directory
6005  * rsv: block reservation
6006  * items: the number of items that we need do reservation
6007  * use_global_rsv: allow fallback to the global block reservation
6008  *
6009  * This function is used to reserve the space for snapshot/subvolume
6010  * creation and deletion. Those operations are different with the
6011  * common file/directory operations, they change two fs/file trees
6012  * and root tree, the number of items that the qgroup reserves is
6013  * different with the free space reservation. So we can not use
6014  * the space reservation mechanism in start_transaction().
6015  */
6016 int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
6017                                      struct btrfs_block_rsv *rsv, int items,
6018                                      bool use_global_rsv)
6019 {
6020         u64 qgroup_num_bytes = 0;
6021         u64 num_bytes;
6022         int ret;
6023         struct btrfs_fs_info *fs_info = root->fs_info;
6024         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
6025
6026         if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
6027                 /* One for parent inode, two for dir entries */
6028                 qgroup_num_bytes = 3 * fs_info->nodesize;
6029                 ret = btrfs_qgroup_reserve_meta_prealloc(root,
6030                                 qgroup_num_bytes, true);
6031                 if (ret)
6032                         return ret;
6033         }
6034
6035         num_bytes = btrfs_calc_trans_metadata_size(fs_info, items);
6036         rsv->space_info = __find_space_info(fs_info,
6037                                             BTRFS_BLOCK_GROUP_METADATA);
6038         ret = btrfs_block_rsv_add(root, rsv, num_bytes,
6039                                   BTRFS_RESERVE_FLUSH_ALL);
6040
6041         if (ret == -ENOSPC && use_global_rsv)
6042                 ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes, true);
6043
6044         if (ret && qgroup_num_bytes)
6045                 btrfs_qgroup_free_meta_prealloc(root, qgroup_num_bytes);
6046
6047         return ret;
6048 }
6049
6050 void btrfs_subvolume_release_metadata(struct btrfs_fs_info *fs_info,
6051                                       struct btrfs_block_rsv *rsv)
6052 {
6053         btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
6054 }
6055
6056 static void btrfs_calculate_inode_block_rsv_size(struct btrfs_fs_info *fs_info,
6057                                                  struct btrfs_inode *inode)
6058 {
6059         struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
6060         u64 reserve_size = 0;
6061         u64 qgroup_rsv_size = 0;
6062         u64 csum_leaves;
6063         unsigned outstanding_extents;
6064
6065         lockdep_assert_held(&inode->lock);
6066         outstanding_extents = inode->outstanding_extents;
6067         if (outstanding_extents)
6068                 reserve_size = btrfs_calc_trans_metadata_size(fs_info,
6069                                                 outstanding_extents + 1);
6070         csum_leaves = btrfs_csum_bytes_to_leaves(fs_info,
6071                                                  inode->csum_bytes);
6072         reserve_size += btrfs_calc_trans_metadata_size(fs_info,
6073                                                        csum_leaves);
6074         /*
6075          * For qgroup rsv, the calculation is very simple:
6076          * account one nodesize for each outstanding extent
6077          *
6078          * This is overestimating in most cases.
6079          */
6080         qgroup_rsv_size = (u64)outstanding_extents * fs_info->nodesize;
6081
6082         spin_lock(&block_rsv->lock);
6083         block_rsv->size = reserve_size;
6084         block_rsv->qgroup_rsv_size = qgroup_rsv_size;
6085         spin_unlock(&block_rsv->lock);
6086 }
6087
6088 int btrfs_delalloc_reserve_metadata(struct btrfs_inode *inode, u64 num_bytes)
6089 {
6090         struct btrfs_fs_info *fs_info = inode->root->fs_info;
6091         unsigned nr_extents;
6092         enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
6093         int ret = 0;
6094         bool delalloc_lock = true;
6095
6096         /* If we are a free space inode we need to not flush since we will be in
6097          * the middle of a transaction commit.  We also don't need the delalloc
6098          * mutex since we won't race with anybody.  We need this mostly to make
6099          * lockdep shut its filthy mouth.
6100          *
6101          * If we have a transaction open (can happen if we call truncate_block
6102          * from truncate), then we need FLUSH_LIMIT so we don't deadlock.
6103          */
6104         if (btrfs_is_free_space_inode(inode)) {
6105                 flush = BTRFS_RESERVE_NO_FLUSH;
6106                 delalloc_lock = false;
6107         } else {
6108                 if (current->journal_info)
6109                         flush = BTRFS_RESERVE_FLUSH_LIMIT;
6110
6111                 if (btrfs_transaction_in_commit(fs_info))
6112                         schedule_timeout(1);
6113         }
6114
6115         if (delalloc_lock)
6116                 mutex_lock(&inode->delalloc_mutex);
6117
6118         num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
6119
6120         /* Add our new extents and calculate the new rsv size. */
6121         spin_lock(&inode->lock);
6122         nr_extents = count_max_extents(num_bytes);
6123         btrfs_mod_outstanding_extents(inode, nr_extents);
6124         inode->csum_bytes += num_bytes;
6125         btrfs_calculate_inode_block_rsv_size(fs_info, inode);
6126         spin_unlock(&inode->lock);
6127
6128         ret = btrfs_inode_rsv_refill(inode, flush);
6129         if (unlikely(ret))
6130                 goto out_fail;
6131
6132         if (delalloc_lock)
6133                 mutex_unlock(&inode->delalloc_mutex);
6134         return 0;
6135
6136 out_fail:
6137         spin_lock(&inode->lock);
6138         nr_extents = count_max_extents(num_bytes);
6139         btrfs_mod_outstanding_extents(inode, -nr_extents);
6140         inode->csum_bytes -= num_bytes;
6141         btrfs_calculate_inode_block_rsv_size(fs_info, inode);
6142         spin_unlock(&inode->lock);
6143
6144         btrfs_inode_rsv_release(inode, true);
6145         if (delalloc_lock)
6146                 mutex_unlock(&inode->delalloc_mutex);
6147         return ret;
6148 }
6149
6150 /**
6151  * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
6152  * @inode: the inode to release the reservation for.
6153  * @num_bytes: the number of bytes we are releasing.
6154  * @qgroup_free: free qgroup reservation or convert it to per-trans reservation
6155  *
6156  * This will release the metadata reservation for an inode.  This can be called
6157  * once we complete IO for a given set of bytes to release their metadata
6158  * reservations, or on error for the same reason.
6159  */
6160 void btrfs_delalloc_release_metadata(struct btrfs_inode *inode, u64 num_bytes,
6161                                      bool qgroup_free)
6162 {
6163         struct btrfs_fs_info *fs_info = inode->root->fs_info;
6164
6165         num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
6166         spin_lock(&inode->lock);
6167         inode->csum_bytes -= num_bytes;
6168         btrfs_calculate_inode_block_rsv_size(fs_info, inode);
6169         spin_unlock(&inode->lock);
6170
6171         if (btrfs_is_testing(fs_info))
6172                 return;
6173
6174         btrfs_inode_rsv_release(inode, qgroup_free);
6175 }
6176
6177 /**
6178  * btrfs_delalloc_release_extents - release our outstanding_extents
6179  * @inode: the inode to balance the reservation for.
6180  * @num_bytes: the number of bytes we originally reserved with
6181  * @qgroup_free: do we need to free qgroup meta reservation or convert them.
6182  *
6183  * When we reserve space we increase outstanding_extents for the extents we may
6184  * add.  Once we've set the range as delalloc or created our ordered extents we
6185  * have outstanding_extents to track the real usage, so we use this to free our
6186  * temporarily tracked outstanding_extents.  This _must_ be used in conjunction
6187  * with btrfs_delalloc_reserve_metadata.
6188  */
6189 void btrfs_delalloc_release_extents(struct btrfs_inode *inode, u64 num_bytes,
6190                                     bool qgroup_free)
6191 {
6192         struct btrfs_fs_info *fs_info = inode->root->fs_info;
6193         unsigned num_extents;
6194
6195         spin_lock(&inode->lock);
6196         num_extents = count_max_extents(num_bytes);
6197         btrfs_mod_outstanding_extents(inode, -num_extents);
6198         btrfs_calculate_inode_block_rsv_size(fs_info, inode);
6199         spin_unlock(&inode->lock);
6200
6201         if (btrfs_is_testing(fs_info))
6202                 return;
6203
6204         btrfs_inode_rsv_release(inode, qgroup_free);
6205 }
6206
6207 /**
6208  * btrfs_delalloc_reserve_space - reserve data and metadata space for
6209  * delalloc
6210  * @inode: inode we're writing to
6211  * @start: start range we are writing to
6212  * @len: how long the range we are writing to
6213  * @reserved: mandatory parameter, record actually reserved qgroup ranges of
6214  *            current reservation.
6215  *
6216  * This will do the following things
6217  *
6218  * o reserve space in data space info for num bytes
6219  *   and reserve precious corresponding qgroup space
6220  *   (Done in check_data_free_space)
6221  *
6222  * o reserve space for metadata space, based on the number of outstanding
6223  *   extents and how much csums will be needed
6224  *   also reserve metadata space in a per root over-reserve method.
6225  * o add to the inodes->delalloc_bytes
6226  * o add it to the fs_info's delalloc inodes list.
6227  *   (Above 3 all done in delalloc_reserve_metadata)
6228  *
6229  * Return 0 for success
6230  * Return <0 for error(-ENOSPC or -EQUOT)
6231  */
6232 int btrfs_delalloc_reserve_space(struct inode *inode,
6233                         struct extent_changeset **reserved, u64 start, u64 len)
6234 {
6235         int ret;
6236
6237         ret = btrfs_check_data_free_space(inode, reserved, start, len);
6238         if (ret < 0)
6239                 return ret;
6240         ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len);
6241         if (ret < 0)
6242                 btrfs_free_reserved_data_space(inode, *reserved, start, len);
6243         return ret;
6244 }
6245
6246 /**
6247  * btrfs_delalloc_release_space - release data and metadata space for delalloc
6248  * @inode: inode we're releasing space for
6249  * @start: start position of the space already reserved
6250  * @len: the len of the space already reserved
6251  * @release_bytes: the len of the space we consumed or didn't use
6252  *
6253  * This function will release the metadata space that was not used and will
6254  * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
6255  * list if there are no delalloc bytes left.
6256  * Also it will handle the qgroup reserved space.
6257  */
6258 void btrfs_delalloc_release_space(struct inode *inode,
6259                                   struct extent_changeset *reserved,
6260                                   u64 start, u64 len, bool qgroup_free)
6261 {
6262         btrfs_delalloc_release_metadata(BTRFS_I(inode), len, qgroup_free);
6263         btrfs_free_reserved_data_space(inode, reserved, start, len);
6264 }
6265
6266 static int update_block_group(struct btrfs_trans_handle *trans,
6267                               u64 bytenr, u64 num_bytes, int alloc)
6268 {
6269         struct btrfs_fs_info *info = trans->fs_info;
6270         struct btrfs_block_group_cache *cache = NULL;
6271         u64 total = num_bytes;
6272         u64 old_val;
6273         u64 byte_in_group;
6274         int factor;
6275         int ret = 0;
6276
6277         /* block accounting for super block */
6278         spin_lock(&info->delalloc_root_lock);
6279         old_val = btrfs_super_bytes_used(info->super_copy);
6280         if (alloc)
6281                 old_val += num_bytes;
6282         else
6283                 old_val -= num_bytes;
6284         btrfs_set_super_bytes_used(info->super_copy, old_val);
6285         spin_unlock(&info->delalloc_root_lock);
6286
6287         while (total) {
6288                 cache = btrfs_lookup_block_group(info, bytenr);
6289                 if (!cache) {
6290                         ret = -ENOENT;
6291                         break;
6292                 }
6293                 factor = btrfs_bg_type_to_factor(cache->flags);
6294
6295                 /*
6296                  * If this block group has free space cache written out, we
6297                  * need to make sure to load it if we are removing space.  This
6298                  * is because we need the unpinning stage to actually add the
6299                  * space back to the block group, otherwise we will leak space.
6300                  */
6301                 if (!alloc && cache->cached == BTRFS_CACHE_NO)
6302                         cache_block_group(cache, 1);
6303
6304                 byte_in_group = bytenr - cache->key.objectid;
6305                 WARN_ON(byte_in_group > cache->key.offset);
6306
6307                 spin_lock(&cache->space_info->lock);
6308                 spin_lock(&cache->lock);
6309
6310                 if (btrfs_test_opt(info, SPACE_CACHE) &&
6311                     cache->disk_cache_state < BTRFS_DC_CLEAR)
6312                         cache->disk_cache_state = BTRFS_DC_CLEAR;
6313
6314                 old_val = btrfs_block_group_used(&cache->item);
6315                 num_bytes = min(total, cache->key.offset - byte_in_group);
6316                 if (alloc) {
6317                         old_val += num_bytes;
6318                         btrfs_set_block_group_used(&cache->item, old_val);
6319                         cache->reserved -= num_bytes;
6320                         cache->space_info->bytes_reserved -= num_bytes;
6321                         cache->space_info->bytes_used += num_bytes;
6322                         cache->space_info->disk_used += num_bytes * factor;
6323                         spin_unlock(&cache->lock);
6324                         spin_unlock(&cache->space_info->lock);
6325                 } else {
6326                         old_val -= num_bytes;
6327                         btrfs_set_block_group_used(&cache->item, old_val);
6328                         cache->pinned += num_bytes;
6329                         update_bytes_pinned(cache->space_info, num_bytes);
6330                         cache->space_info->bytes_used -= num_bytes;
6331                         cache->space_info->disk_used -= num_bytes * factor;
6332                         spin_unlock(&cache->lock);
6333                         spin_unlock(&cache->space_info->lock);
6334
6335                         trace_btrfs_space_reservation(info, "pinned",
6336                                                       cache->space_info->flags,
6337                                                       num_bytes, 1);
6338                         percpu_counter_add_batch(&cache->space_info->total_bytes_pinned,
6339                                            num_bytes,
6340                                            BTRFS_TOTAL_BYTES_PINNED_BATCH);
6341                         set_extent_dirty(info->pinned_extents,
6342                                          bytenr, bytenr + num_bytes - 1,
6343                                          GFP_NOFS | __GFP_NOFAIL);
6344                 }
6345
6346                 spin_lock(&trans->transaction->dirty_bgs_lock);
6347                 if (list_empty(&cache->dirty_list)) {
6348                         list_add_tail(&cache->dirty_list,
6349                                       &trans->transaction->dirty_bgs);
6350                         trans->delayed_ref_updates++;
6351                         btrfs_get_block_group(cache);
6352                 }
6353                 spin_unlock(&trans->transaction->dirty_bgs_lock);
6354
6355                 /*
6356                  * No longer have used bytes in this block group, queue it for
6357                  * deletion. We do this after adding the block group to the
6358                  * dirty list to avoid races between cleaner kthread and space
6359                  * cache writeout.
6360                  */
6361                 if (!alloc && old_val == 0)
6362                         btrfs_mark_bg_unused(cache);
6363
6364                 btrfs_put_block_group(cache);
6365                 total -= num_bytes;
6366                 bytenr += num_bytes;
6367         }
6368
6369         /* Modified block groups are accounted for in the delayed_refs_rsv. */
6370         btrfs_update_delayed_refs_rsv(trans);
6371         return ret;
6372 }
6373
6374 static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
6375 {
6376         struct btrfs_block_group_cache *cache;
6377         u64 bytenr;
6378
6379         spin_lock(&fs_info->block_group_cache_lock);
6380         bytenr = fs_info->first_logical_byte;
6381         spin_unlock(&fs_info->block_group_cache_lock);
6382
6383         if (bytenr < (u64)-1)
6384                 return bytenr;
6385
6386         cache = btrfs_lookup_first_block_group(fs_info, search_start);
6387         if (!cache)
6388                 return 0;
6389
6390         bytenr = cache->key.objectid;
6391         btrfs_put_block_group(cache);
6392
6393         return bytenr;
6394 }
6395
6396 static int pin_down_extent(struct btrfs_block_group_cache *cache,
6397                            u64 bytenr, u64 num_bytes, int reserved)
6398 {
6399         struct btrfs_fs_info *fs_info = cache->fs_info;
6400
6401         spin_lock(&cache->space_info->lock);
6402         spin_lock(&cache->lock);
6403         cache->pinned += num_bytes;
6404         update_bytes_pinned(cache->space_info, num_bytes);
6405         if (reserved) {
6406                 cache->reserved -= num_bytes;
6407                 cache->space_info->bytes_reserved -= num_bytes;
6408         }
6409         spin_unlock(&cache->lock);
6410         spin_unlock(&cache->space_info->lock);
6411
6412         trace_btrfs_space_reservation(fs_info, "pinned",
6413                                       cache->space_info->flags, num_bytes, 1);
6414         percpu_counter_add_batch(&cache->space_info->total_bytes_pinned,
6415                     num_bytes, BTRFS_TOTAL_BYTES_PINNED_BATCH);
6416         set_extent_dirty(fs_info->pinned_extents, bytenr,
6417                          bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
6418         return 0;
6419 }
6420
6421 /*
6422  * this function must be called within transaction
6423  */
6424 int btrfs_pin_extent(struct btrfs_fs_info *fs_info,
6425                      u64 bytenr, u64 num_bytes, int reserved)
6426 {
6427         struct btrfs_block_group_cache *cache;
6428
6429         cache = btrfs_lookup_block_group(fs_info, bytenr);
6430         BUG_ON(!cache); /* Logic error */
6431
6432         pin_down_extent(cache, bytenr, num_bytes, reserved);
6433
6434         btrfs_put_block_group(cache);
6435         return 0;
6436 }
6437
6438 /*
6439  * this function must be called within transaction
6440  */
6441 int btrfs_pin_extent_for_log_replay(struct btrfs_fs_info *fs_info,
6442                                     u64 bytenr, u64 num_bytes)
6443 {
6444         struct btrfs_block_group_cache *cache;
6445         int ret;
6446
6447         cache = btrfs_lookup_block_group(fs_info, bytenr);
6448         if (!cache)
6449                 return -EINVAL;
6450
6451         /*
6452          * pull in the free space cache (if any) so that our pin
6453          * removes the free space from the cache.  We have load_only set
6454          * to one because the slow code to read in the free extents does check
6455          * the pinned extents.
6456          */
6457         cache_block_group(cache, 1);
6458
6459         pin_down_extent(cache, bytenr, num_bytes, 0);
6460
6461         /* remove us from the free space cache (if we're there at all) */
6462         ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
6463         btrfs_put_block_group(cache);
6464         return ret;
6465 }
6466
6467 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
6468                                    u64 start, u64 num_bytes)
6469 {
6470         int ret;
6471         struct btrfs_block_group_cache *block_group;
6472         struct btrfs_caching_control *caching_ctl;
6473
6474         block_group = btrfs_lookup_block_group(fs_info, start);
6475         if (!block_group)
6476                 return -EINVAL;
6477
6478         cache_block_group(block_group, 0);
6479         caching_ctl = get_caching_control(block_group);
6480
6481         if (!caching_ctl) {
6482                 /* Logic error */
6483                 BUG_ON(!block_group_cache_done(block_group));
6484                 ret = btrfs_remove_free_space(block_group, start, num_bytes);
6485         } else {
6486                 mutex_lock(&caching_ctl->mutex);
6487
6488                 if (start >= caching_ctl->progress) {
6489                         ret = add_excluded_extent(fs_info, start, num_bytes);
6490                 } else if (start + num_bytes <= caching_ctl->progress) {
6491                         ret = btrfs_remove_free_space(block_group,
6492                                                       start, num_bytes);
6493                 } else {
6494                         num_bytes = caching_ctl->progress - start;
6495                         ret = btrfs_remove_free_space(block_group,
6496                                                       start, num_bytes);
6497                         if (ret)
6498                                 goto out_lock;
6499
6500                         num_bytes = (start + num_bytes) -
6501                                 caching_ctl->progress;
6502                         start = caching_ctl->progress;
6503                         ret = add_excluded_extent(fs_info, start, num_bytes);
6504                 }
6505 out_lock:
6506                 mutex_unlock(&caching_ctl->mutex);
6507                 put_caching_control(caching_ctl);
6508         }
6509         btrfs_put_block_group(block_group);
6510         return ret;
6511 }
6512
6513 int btrfs_exclude_logged_extents(struct extent_buffer *eb)
6514 {
6515         struct btrfs_fs_info *fs_info = eb->fs_info;
6516         struct btrfs_file_extent_item *item;
6517         struct btrfs_key key;
6518         int found_type;
6519         int i;
6520         int ret = 0;
6521
6522         if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
6523                 return 0;
6524
6525         for (i = 0; i < btrfs_header_nritems(eb); i++) {
6526                 btrfs_item_key_to_cpu(eb, &key, i);
6527                 if (key.type != BTRFS_EXTENT_DATA_KEY)
6528                         continue;
6529                 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
6530                 found_type = btrfs_file_extent_type(eb, item);
6531                 if (found_type == BTRFS_FILE_EXTENT_INLINE)
6532                         continue;
6533                 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
6534                         continue;
6535                 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
6536                 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
6537                 ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
6538                 if (ret)
6539                         break;
6540         }
6541
6542         return ret;
6543 }
6544
6545 static void
6546 btrfs_inc_block_group_reservations(struct btrfs_block_group_cache *bg)
6547 {
6548         atomic_inc(&bg->reservations);
6549 }
6550
6551 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
6552                                         const u64 start)
6553 {
6554         struct btrfs_block_group_cache *bg;
6555
6556         bg = btrfs_lookup_block_group(fs_info, start);
6557         ASSERT(bg);
6558         if (atomic_dec_and_test(&bg->reservations))
6559                 wake_up_var(&bg->reservations);
6560         btrfs_put_block_group(bg);
6561 }
6562
6563 void btrfs_wait_block_group_reservations(struct btrfs_block_group_cache *bg)
6564 {
6565         struct btrfs_space_info *space_info = bg->space_info;
6566
6567         ASSERT(bg->ro);
6568
6569         if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
6570                 return;
6571
6572         /*
6573          * Our block group is read only but before we set it to read only,
6574          * some task might have had allocated an extent from it already, but it
6575          * has not yet created a respective ordered extent (and added it to a
6576          * root's list of ordered extents).
6577          * Therefore wait for any task currently allocating extents, since the
6578          * block group's reservations counter is incremented while a read lock
6579          * on the groups' semaphore is held and decremented after releasing
6580          * the read access on that semaphore and creating the ordered extent.
6581          */
6582         down_write(&space_info->groups_sem);
6583         up_write(&space_info->groups_sem);
6584
6585         wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
6586 }
6587
6588 /**
6589  * btrfs_add_reserved_bytes - update the block_group and space info counters
6590  * @cache:      The cache we are manipulating
6591  * @ram_bytes:  The number of bytes of file content, and will be same to
6592  *              @num_bytes except for the compress path.
6593  * @num_bytes:  The number of bytes in question
6594  * @delalloc:   The blocks are allocated for the delalloc write
6595  *
6596  * This is called by the allocator when it reserves space. If this is a
6597  * reservation and the block group has become read only we cannot make the
6598  * reservation and return -EAGAIN, otherwise this function always succeeds.
6599  */
6600 static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
6601                                     u64 ram_bytes, u64 num_bytes, int delalloc)
6602 {
6603         struct btrfs_space_info *space_info = cache->space_info;
6604         int ret = 0;
6605
6606         spin_lock(&space_info->lock);
6607         spin_lock(&cache->lock);
6608         if (cache->ro) {
6609                 ret = -EAGAIN;
6610         } else {
6611                 cache->reserved += num_bytes;
6612                 space_info->bytes_reserved += num_bytes;
6613                 update_bytes_may_use(space_info, -ram_bytes);
6614                 if (delalloc)
6615                         cache->delalloc_bytes += num_bytes;
6616         }
6617         spin_unlock(&cache->lock);
6618         spin_unlock(&space_info->lock);
6619         return ret;
6620 }
6621
6622 /**
6623  * btrfs_free_reserved_bytes - update the block_group and space info counters
6624  * @cache:      The cache we are manipulating
6625  * @num_bytes:  The number of bytes in question
6626  * @delalloc:   The blocks are allocated for the delalloc write
6627  *
6628  * This is called by somebody who is freeing space that was never actually used
6629  * on disk.  For example if you reserve some space for a new leaf in transaction
6630  * A and before transaction A commits you free that leaf, you call this with
6631  * reserve set to 0 in order to clear the reservation.
6632  */
6633
6634 static void btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
6635                                       u64 num_bytes, int delalloc)
6636 {
6637         struct btrfs_space_info *space_info = cache->space_info;
6638
6639         spin_lock(&space_info->lock);
6640         spin_lock(&cache->lock);
6641         if (cache->ro)
6642                 space_info->bytes_readonly += num_bytes;
6643         cache->reserved -= num_bytes;
6644         space_info->bytes_reserved -= num_bytes;
6645         space_info->max_extent_size = 0;
6646
6647         if (delalloc)
6648                 cache->delalloc_bytes -= num_bytes;
6649         spin_unlock(&cache->lock);
6650         spin_unlock(&space_info->lock);
6651 }
6652 void btrfs_prepare_extent_commit(struct btrfs_fs_info *fs_info)
6653 {
6654         struct btrfs_caching_control *next;
6655         struct btrfs_caching_control *caching_ctl;
6656         struct btrfs_block_group_cache *cache;
6657
6658         down_write(&fs_info->commit_root_sem);
6659
6660         list_for_each_entry_safe(caching_ctl, next,
6661                                  &fs_info->caching_block_groups, list) {
6662                 cache = caching_ctl->block_group;
6663                 if (block_group_cache_done(cache)) {
6664                         cache->last_byte_to_unpin = (u64)-1;
6665                         list_del_init(&caching_ctl->list);
6666                         put_caching_control(caching_ctl);
6667                 } else {
6668                         cache->last_byte_to_unpin = caching_ctl->progress;
6669                 }
6670         }
6671
6672         if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6673                 fs_info->pinned_extents = &fs_info->freed_extents[1];
6674         else
6675                 fs_info->pinned_extents = &fs_info->freed_extents[0];
6676
6677         up_write(&fs_info->commit_root_sem);
6678
6679         update_global_block_rsv(fs_info);
6680 }
6681
6682 /*
6683  * Returns the free cluster for the given space info and sets empty_cluster to
6684  * what it should be based on the mount options.
6685  */
6686 static struct btrfs_free_cluster *
6687 fetch_cluster_info(struct btrfs_fs_info *fs_info,
6688                    struct btrfs_space_info *space_info, u64 *empty_cluster)
6689 {
6690         struct btrfs_free_cluster *ret = NULL;
6691
6692         *empty_cluster = 0;
6693         if (btrfs_mixed_space_info(space_info))
6694                 return ret;
6695
6696         if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
6697                 ret = &fs_info->meta_alloc_cluster;
6698                 if (btrfs_test_opt(fs_info, SSD))
6699                         *empty_cluster = SZ_2M;
6700                 else
6701                         *empty_cluster = SZ_64K;
6702         } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
6703                    btrfs_test_opt(fs_info, SSD_SPREAD)) {
6704                 *empty_cluster = SZ_2M;
6705                 ret = &fs_info->data_alloc_cluster;
6706         }
6707
6708         return ret;
6709 }
6710
6711 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
6712                               u64 start, u64 end,
6713                               const bool return_free_space)
6714 {
6715         struct btrfs_block_group_cache *cache = NULL;
6716         struct btrfs_space_info *space_info;
6717         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
6718         struct btrfs_free_cluster *cluster = NULL;
6719         u64 len;
6720         u64 total_unpinned = 0;
6721         u64 empty_cluster = 0;
6722         bool readonly;
6723
6724         while (start <= end) {
6725                 readonly = false;
6726                 if (!cache ||
6727                     start >= cache->key.objectid + cache->key.offset) {
6728                         if (cache)
6729                                 btrfs_put_block_group(cache);
6730                         total_unpinned = 0;
6731                         cache = btrfs_lookup_block_group(fs_info, start);
6732                         BUG_ON(!cache); /* Logic error */
6733
6734                         cluster = fetch_cluster_info(fs_info,
6735                                                      cache->space_info,
6736                                                      &empty_cluster);
6737                         empty_cluster <<= 1;
6738                 }
6739
6740                 len = cache->key.objectid + cache->key.offset - start;
6741                 len = min(len, end + 1 - start);
6742
6743                 if (start < cache->last_byte_to_unpin) {
6744                         len = min(len, cache->last_byte_to_unpin - start);
6745                         if (return_free_space)
6746                                 btrfs_add_free_space(cache, start, len);
6747                 }
6748
6749                 start += len;
6750                 total_unpinned += len;
6751                 space_info = cache->space_info;
6752
6753                 /*
6754                  * If this space cluster has been marked as fragmented and we've
6755                  * unpinned enough in this block group to potentially allow a
6756                  * cluster to be created inside of it go ahead and clear the
6757                  * fragmented check.
6758                  */
6759                 if (cluster && cluster->fragmented &&
6760                     total_unpinned > empty_cluster) {
6761                         spin_lock(&cluster->lock);
6762                         cluster->fragmented = 0;
6763                         spin_unlock(&cluster->lock);
6764                 }
6765
6766                 spin_lock(&space_info->lock);
6767                 spin_lock(&cache->lock);
6768                 cache->pinned -= len;
6769                 update_bytes_pinned(space_info, -len);
6770
6771                 trace_btrfs_space_reservation(fs_info, "pinned",
6772                                               space_info->flags, len, 0);
6773                 space_info->max_extent_size = 0;
6774                 percpu_counter_add_batch(&space_info->total_bytes_pinned,
6775                             -len, BTRFS_TOTAL_BYTES_PINNED_BATCH);
6776                 if (cache->ro) {
6777                         space_info->bytes_readonly += len;
6778                         readonly = true;
6779                 }
6780                 spin_unlock(&cache->lock);
6781                 if (!readonly && return_free_space &&
6782                     global_rsv->space_info == space_info) {
6783                         u64 to_add = len;
6784
6785                         spin_lock(&global_rsv->lock);
6786                         if (!global_rsv->full) {
6787                                 to_add = min(len, global_rsv->size -
6788                                              global_rsv->reserved);
6789                                 global_rsv->reserved += to_add;
6790                                 update_bytes_may_use(space_info, to_add);
6791                                 if (global_rsv->reserved >= global_rsv->size)
6792                                         global_rsv->full = 1;
6793                                 trace_btrfs_space_reservation(fs_info,
6794                                                               "space_info",
6795                                                               space_info->flags,
6796                                                               to_add, 1);
6797                                 len -= to_add;
6798                         }
6799                         spin_unlock(&global_rsv->lock);
6800                         /* Add to any tickets we may have */
6801                         if (len)
6802                                 space_info_add_new_bytes(fs_info, space_info,
6803                                                          len);
6804                 }
6805                 spin_unlock(&space_info->lock);
6806         }
6807
6808         if (cache)
6809                 btrfs_put_block_group(cache);
6810         return 0;
6811 }
6812
6813 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
6814 {
6815         struct btrfs_fs_info *fs_info = trans->fs_info;
6816         struct btrfs_block_group_cache *block_group, *tmp;
6817         struct list_head *deleted_bgs;
6818         struct extent_io_tree *unpin;
6819         u64 start;
6820         u64 end;
6821         int ret;
6822
6823         if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6824                 unpin = &fs_info->freed_extents[1];
6825         else
6826                 unpin = &fs_info->freed_extents[0];
6827
6828         while (!trans->aborted) {
6829                 struct extent_state *cached_state = NULL;
6830
6831                 mutex_lock(&fs_info->unused_bg_unpin_mutex);
6832                 ret = find_first_extent_bit(unpin, 0, &start, &end,
6833                                             EXTENT_DIRTY, &cached_state);
6834                 if (ret) {
6835                         mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6836                         break;
6837                 }
6838
6839                 if (btrfs_test_opt(fs_info, DISCARD))
6840                         ret = btrfs_discard_extent(fs_info, start,
6841                                                    end + 1 - start, NULL);
6842
6843                 clear_extent_dirty(unpin, start, end, &cached_state);
6844                 unpin_extent_range(fs_info, start, end, true);
6845                 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6846                 free_extent_state(cached_state);
6847                 cond_resched();
6848         }
6849
6850         /*
6851          * Transaction is finished.  We don't need the lock anymore.  We
6852          * do need to clean up the block groups in case of a transaction
6853          * abort.
6854          */
6855         deleted_bgs = &trans->transaction->deleted_bgs;
6856         list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
6857                 u64 trimmed = 0;
6858
6859                 ret = -EROFS;
6860                 if (!trans->aborted)
6861                         ret = btrfs_discard_extent(fs_info,
6862                                                    block_group->key.objectid,
6863                                                    block_group->key.offset,
6864                                                    &trimmed);
6865
6866                 list_del_init(&block_group->bg_list);
6867                 btrfs_put_block_group_trimming(block_group);
6868                 btrfs_put_block_group(block_group);
6869
6870                 if (ret) {
6871                         const char *errstr = btrfs_decode_error(ret);
6872                         btrfs_warn(fs_info,
6873                            "discard failed while removing blockgroup: errno=%d %s",
6874                                    ret, errstr);
6875                 }
6876         }
6877
6878         return 0;
6879 }
6880
6881 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
6882                                struct btrfs_delayed_ref_node *node, u64 parent,
6883                                u64 root_objectid, u64 owner_objectid,
6884                                u64 owner_offset, int refs_to_drop,
6885                                struct btrfs_delayed_extent_op *extent_op)
6886 {
6887         struct btrfs_fs_info *info = trans->fs_info;
6888         struct btrfs_key key;
6889         struct btrfs_path *path;
6890         struct btrfs_root *extent_root = info->extent_root;
6891         struct extent_buffer *leaf;
6892         struct btrfs_extent_item *ei;
6893         struct btrfs_extent_inline_ref *iref;
6894         int ret;
6895         int is_data;
6896         int extent_slot = 0;
6897         int found_extent = 0;
6898         int num_to_del = 1;
6899         u32 item_size;
6900         u64 refs;
6901         u64 bytenr = node->bytenr;
6902         u64 num_bytes = node->num_bytes;
6903         int last_ref = 0;
6904         bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
6905
6906         path = btrfs_alloc_path();
6907         if (!path)
6908                 return -ENOMEM;
6909
6910         path->reada = READA_FORWARD;
6911         path->leave_spinning = 1;
6912
6913         is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
6914         BUG_ON(!is_data && refs_to_drop != 1);
6915
6916         if (is_data)
6917                 skinny_metadata = false;
6918
6919         ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
6920                                     parent, root_objectid, owner_objectid,
6921                                     owner_offset);
6922         if (ret == 0) {
6923                 extent_slot = path->slots[0];
6924                 while (extent_slot >= 0) {
6925                         btrfs_item_key_to_cpu(path->nodes[0], &key,
6926                                               extent_slot);
6927                         if (key.objectid != bytenr)
6928                                 break;
6929                         if (key.type == BTRFS_EXTENT_ITEM_KEY &&
6930                             key.offset == num_bytes) {
6931                                 found_extent = 1;
6932                                 break;
6933                         }
6934                         if (key.type == BTRFS_METADATA_ITEM_KEY &&
6935                             key.offset == owner_objectid) {
6936                                 found_extent = 1;
6937                                 break;
6938                         }
6939                         if (path->slots[0] - extent_slot > 5)
6940                                 break;
6941                         extent_slot--;
6942                 }
6943
6944                 if (!found_extent) {
6945                         BUG_ON(iref);
6946                         ret = remove_extent_backref(trans, path, NULL,
6947                                                     refs_to_drop,
6948                                                     is_data, &last_ref);
6949                         if (ret) {
6950                                 btrfs_abort_transaction(trans, ret);
6951                                 goto out;
6952                         }
6953                         btrfs_release_path(path);
6954                         path->leave_spinning = 1;
6955
6956                         key.objectid = bytenr;
6957                         key.type = BTRFS_EXTENT_ITEM_KEY;
6958                         key.offset = num_bytes;
6959
6960                         if (!is_data && skinny_metadata) {
6961                                 key.type = BTRFS_METADATA_ITEM_KEY;
6962                                 key.offset = owner_objectid;
6963                         }
6964
6965                         ret = btrfs_search_slot(trans, extent_root,
6966                                                 &key, path, -1, 1);
6967                         if (ret > 0 && skinny_metadata && path->slots[0]) {
6968                                 /*
6969                                  * Couldn't find our skinny metadata item,
6970                                  * see if we have ye olde extent item.
6971                                  */
6972                                 path->slots[0]--;
6973                                 btrfs_item_key_to_cpu(path->nodes[0], &key,
6974                                                       path->slots[0]);
6975                                 if (key.objectid == bytenr &&
6976                                     key.type == BTRFS_EXTENT_ITEM_KEY &&
6977                                     key.offset == num_bytes)
6978                                         ret = 0;
6979                         }
6980
6981                         if (ret > 0 && skinny_metadata) {
6982                                 skinny_metadata = false;
6983                                 key.objectid = bytenr;
6984                                 key.type = BTRFS_EXTENT_ITEM_KEY;
6985                                 key.offset = num_bytes;
6986                                 btrfs_release_path(path);
6987                                 ret = btrfs_search_slot(trans, extent_root,
6988                                                         &key, path, -1, 1);
6989                         }
6990
6991                         if (ret) {
6992                                 btrfs_err(info,
6993                                           "umm, got %d back from search, was looking for %llu",
6994                                           ret, bytenr);
6995                                 if (ret > 0)
6996                                         btrfs_print_leaf(path->nodes[0]);
6997                         }
6998                         if (ret < 0) {
6999                                 btrfs_abort_transaction(trans, ret);
7000                                 goto out;
7001                         }
7002                         extent_slot = path->slots[0];
7003                 }
7004         } else if (WARN_ON(ret == -ENOENT)) {
7005                 btrfs_print_leaf(path->nodes[0]);
7006                 btrfs_err(info,
7007                         "unable to find ref byte nr %llu parent %llu root %llu  owner %llu offset %llu",
7008                         bytenr, parent, root_objectid, owner_objectid,
7009                         owner_offset);
7010                 btrfs_abort_transaction(trans, ret);
7011                 goto out;
7012         } else {
7013                 btrfs_abort_transaction(trans, ret);
7014                 goto out;
7015         }
7016
7017         leaf = path->nodes[0];
7018         item_size = btrfs_item_size_nr(leaf, extent_slot);
7019         if (unlikely(item_size < sizeof(*ei))) {
7020                 ret = -EINVAL;
7021                 btrfs_print_v0_err(info);
7022                 btrfs_abort_transaction(trans, ret);
7023                 goto out;
7024         }
7025         ei = btrfs_item_ptr(leaf, extent_slot,
7026                             struct btrfs_extent_item);
7027         if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
7028             key.type == BTRFS_EXTENT_ITEM_KEY) {
7029                 struct btrfs_tree_block_info *bi;
7030                 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
7031                 bi = (struct btrfs_tree_block_info *)(ei + 1);
7032                 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
7033         }
7034
7035         refs = btrfs_extent_refs(leaf, ei);
7036         if (refs < refs_to_drop) {
7037                 btrfs_err(info,
7038                           "trying to drop %d refs but we only have %Lu for bytenr %Lu",
7039                           refs_to_drop, refs, bytenr);
7040                 ret = -EINVAL;
7041                 btrfs_abort_transaction(trans, ret);
7042                 goto out;
7043         }
7044         refs -= refs_to_drop;
7045
7046         if (refs > 0) {
7047                 if (extent_op)
7048                         __run_delayed_extent_op(extent_op, leaf, ei);
7049                 /*
7050                  * In the case of inline back ref, reference count will
7051                  * be updated by remove_extent_backref
7052                  */
7053                 if (iref) {
7054                         BUG_ON(!found_extent);
7055                 } else {
7056                         btrfs_set_extent_refs(leaf, ei, refs);
7057                         btrfs_mark_buffer_dirty(leaf);
7058                 }
7059                 if (found_extent) {
7060                         ret = remove_extent_backref(trans, path, iref,
7061                                                     refs_to_drop, is_data,
7062                                                     &last_ref);
7063                         if (ret) {
7064                                 btrfs_abort_transaction(trans, ret);
7065                                 goto out;
7066                         }
7067                 }
7068         } else {
7069                 if (found_extent) {
7070                         BUG_ON(is_data && refs_to_drop !=
7071                                extent_data_ref_count(path, iref));
7072                         if (iref) {
7073                                 BUG_ON(path->slots[0] != extent_slot);
7074                         } else {
7075                                 BUG_ON(path->slots[0] != extent_slot + 1);
7076                                 path->slots[0] = extent_slot;
7077                                 num_to_del = 2;
7078                         }
7079                 }
7080
7081                 last_ref = 1;
7082                 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
7083                                       num_to_del);
7084                 if (ret) {
7085                         btrfs_abort_transaction(trans, ret);
7086                         goto out;
7087                 }
7088                 btrfs_release_path(path);
7089
7090                 if (is_data) {
7091                         ret = btrfs_del_csums(trans, info, bytenr, num_bytes);
7092                         if (ret) {
7093                                 btrfs_abort_transaction(trans, ret);
7094                                 goto out;
7095                         }
7096                 }
7097
7098                 ret = add_to_free_space_tree(trans, bytenr, num_bytes);
7099                 if (ret) {
7100                         btrfs_abort_transaction(trans, ret);
7101                         goto out;
7102                 }
7103
7104                 ret = update_block_group(trans, bytenr, num_bytes, 0);
7105                 if (ret) {
7106                         btrfs_abort_transaction(trans, ret);
7107                         goto out;
7108                 }
7109         }
7110         btrfs_release_path(path);
7111
7112 out:
7113         btrfs_free_path(path);
7114         return ret;
7115 }
7116
7117 /*
7118  * when we free an block, it is possible (and likely) that we free the last
7119  * delayed ref for that extent as well.  This searches the delayed ref tree for
7120  * a given extent, and if there are no other delayed refs to be processed, it
7121  * removes it from the tree.
7122  */
7123 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
7124                                       u64 bytenr)
7125 {
7126         struct btrfs_delayed_ref_head *head;
7127         struct btrfs_delayed_ref_root *delayed_refs;
7128         int ret = 0;
7129
7130         delayed_refs = &trans->transaction->delayed_refs;
7131         spin_lock(&delayed_refs->lock);
7132         head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
7133         if (!head)
7134                 goto out_delayed_unlock;
7135
7136         spin_lock(&head->lock);
7137         if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
7138                 goto out;
7139
7140         if (cleanup_extent_op(head) != NULL)
7141                 goto out;
7142
7143         /*
7144          * waiting for the lock here would deadlock.  If someone else has it
7145          * locked they are already in the process of dropping it anyway
7146          */
7147         if (!mutex_trylock(&head->mutex))
7148                 goto out;
7149
7150         btrfs_delete_ref_head(delayed_refs, head);
7151         head->processing = 0;
7152
7153         spin_unlock(&head->lock);
7154         spin_unlock(&delayed_refs->lock);
7155
7156         BUG_ON(head->extent_op);
7157         if (head->must_insert_reserved)
7158                 ret = 1;
7159
7160         btrfs_cleanup_ref_head_accounting(trans->fs_info, delayed_refs, head);
7161         mutex_unlock(&head->mutex);
7162         btrfs_put_delayed_ref_head(head);
7163         return ret;
7164 out:
7165         spin_unlock(&head->lock);
7166
7167 out_delayed_unlock:
7168         spin_unlock(&delayed_refs->lock);
7169         return 0;
7170 }
7171
7172 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
7173                            struct btrfs_root *root,
7174                            struct extent_buffer *buf,
7175                            u64 parent, int last_ref)
7176 {
7177         struct btrfs_fs_info *fs_info = root->fs_info;
7178         struct btrfs_ref generic_ref = { 0 };
7179         int pin = 1;
7180         int ret;
7181
7182         btrfs_init_generic_ref(&generic_ref, BTRFS_DROP_DELAYED_REF,
7183                                buf->start, buf->len, parent);
7184         btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf),
7185                             root->root_key.objectid);
7186
7187         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
7188                 int old_ref_mod, new_ref_mod;
7189
7190                 btrfs_ref_tree_mod(fs_info, &generic_ref);
7191                 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL,
7192                                                  &old_ref_mod, &new_ref_mod);
7193                 BUG_ON(ret); /* -ENOMEM */
7194                 pin = old_ref_mod >= 0 && new_ref_mod < 0;
7195         }
7196
7197         if (last_ref && btrfs_header_generation(buf) == trans->transid) {
7198                 struct btrfs_block_group_cache *cache;
7199
7200                 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
7201                         ret = check_ref_cleanup(trans, buf->start);
7202                         if (!ret)
7203                                 goto out;
7204                 }
7205
7206                 pin = 0;
7207                 cache = btrfs_lookup_block_group(fs_info, buf->start);
7208
7209                 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
7210                         pin_down_extent(cache, buf->start, buf->len, 1);
7211                         btrfs_put_block_group(cache);
7212                         goto out;
7213                 }
7214
7215                 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
7216
7217                 btrfs_add_free_space(cache, buf->start, buf->len);
7218                 btrfs_free_reserved_bytes(cache, buf->len, 0);
7219                 btrfs_put_block_group(cache);
7220                 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
7221         }
7222 out:
7223         if (pin)
7224                 add_pinned_bytes(fs_info, &generic_ref);
7225
7226         if (last_ref) {
7227                 /*
7228                  * Deleting the buffer, clear the corrupt flag since it doesn't
7229                  * matter anymore.
7230                  */
7231                 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
7232         }
7233 }
7234
7235 /* Can return -ENOMEM */
7236 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
7237 {
7238         struct btrfs_fs_info *fs_info = trans->fs_info;
7239         int old_ref_mod, new_ref_mod;
7240         int ret;
7241
7242         if (btrfs_is_testing(fs_info))
7243                 return 0;
7244
7245         /*
7246          * tree log blocks never actually go into the extent allocation
7247          * tree, just update pinning info and exit early.
7248          */
7249         if ((ref->type == BTRFS_REF_METADATA &&
7250              ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
7251             (ref->type == BTRFS_REF_DATA &&
7252              ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)) {
7253                 /* unlocks the pinned mutex */
7254                 btrfs_pin_extent(fs_info, ref->bytenr, ref->len, 1);
7255                 old_ref_mod = new_ref_mod = 0;
7256                 ret = 0;
7257         } else if (ref->type == BTRFS_REF_METADATA) {
7258                 ret = btrfs_add_delayed_tree_ref(trans, ref, NULL,
7259                                                  &old_ref_mod, &new_ref_mod);
7260         } else {
7261                 ret = btrfs_add_delayed_data_ref(trans, ref, 0,
7262                                                  &old_ref_mod, &new_ref_mod);
7263         }
7264
7265         if (!((ref->type == BTRFS_REF_METADATA &&
7266                ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
7267               (ref->type == BTRFS_REF_DATA &&
7268                ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)))
7269                 btrfs_ref_tree_mod(fs_info, ref);
7270
7271         if (ret == 0 && old_ref_mod >= 0 && new_ref_mod < 0)
7272                 add_pinned_bytes(fs_info, ref);
7273
7274         return ret;
7275 }
7276
7277 /*
7278  * when we wait for progress in the block group caching, its because
7279  * our allocation attempt failed at least once.  So, we must sleep
7280  * and let some progress happen before we try again.
7281  *
7282  * This function will sleep at least once waiting for new free space to
7283  * show up, and then it will check the block group free space numbers
7284  * for our min num_bytes.  Another option is to have it go ahead
7285  * and look in the rbtree for a free extent of a given size, but this
7286  * is a good start.
7287  *
7288  * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
7289  * any of the information in this block group.
7290  */
7291 static noinline void
7292 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
7293                                 u64 num_bytes)
7294 {
7295         struct btrfs_caching_control *caching_ctl;
7296
7297         caching_ctl = get_caching_control(cache);
7298         if (!caching_ctl)
7299                 return;
7300
7301         wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
7302                    (cache->free_space_ctl->free_space >= num_bytes));
7303
7304         put_caching_control(caching_ctl);
7305 }
7306
7307 static noinline int
7308 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
7309 {
7310         struct btrfs_caching_control *caching_ctl;
7311         int ret = 0;
7312
7313         caching_ctl = get_caching_control(cache);
7314         if (!caching_ctl)
7315                 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
7316
7317         wait_event(caching_ctl->wait, block_group_cache_done(cache));
7318         if (cache->cached == BTRFS_CACHE_ERROR)
7319                 ret = -EIO;
7320         put_caching_control(caching_ctl);
7321         return ret;
7322 }
7323
7324 enum btrfs_loop_type {
7325         LOOP_CACHING_NOWAIT = 0,
7326         LOOP_CACHING_WAIT = 1,
7327         LOOP_ALLOC_CHUNK = 2,
7328         LOOP_NO_EMPTY_SIZE = 3,
7329 };
7330
7331 static inline void
7332 btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
7333                        int delalloc)
7334 {
7335         if (delalloc)
7336                 down_read(&cache->data_rwsem);
7337 }
7338
7339 static inline void
7340 btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
7341                        int delalloc)
7342 {
7343         btrfs_get_block_group(cache);
7344         if (delalloc)
7345                 down_read(&cache->data_rwsem);
7346 }
7347
7348 static struct btrfs_block_group_cache *
7349 btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
7350                    struct btrfs_free_cluster *cluster,
7351                    int delalloc)
7352 {
7353         struct btrfs_block_group_cache *used_bg = NULL;
7354
7355         spin_lock(&cluster->refill_lock);
7356         while (1) {
7357                 used_bg = cluster->block_group;
7358                 if (!used_bg)
7359                         return NULL;
7360
7361                 if (used_bg == block_group)
7362                         return used_bg;
7363
7364                 btrfs_get_block_group(used_bg);
7365
7366                 if (!delalloc)
7367                         return used_bg;
7368
7369                 if (down_read_trylock(&used_bg->data_rwsem))
7370                         return used_bg;
7371
7372                 spin_unlock(&cluster->refill_lock);
7373
7374                 /* We should only have one-level nested. */
7375                 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
7376
7377                 spin_lock(&cluster->refill_lock);
7378                 if (used_bg == cluster->block_group)
7379                         return used_bg;
7380
7381                 up_read(&used_bg->data_rwsem);
7382                 btrfs_put_block_group(used_bg);
7383         }
7384 }
7385
7386 static inline void
7387 btrfs_release_block_group(struct btrfs_block_group_cache *cache,
7388                          int delalloc)
7389 {
7390         if (delalloc)
7391                 up_read(&cache->data_rwsem);
7392         btrfs_put_block_group(cache);
7393 }
7394
7395 /*
7396  * Structure used internally for find_free_extent() function.  Wraps needed
7397  * parameters.
7398  */
7399 struct find_free_extent_ctl {
7400         /* Basic allocation info */
7401         u64 ram_bytes;
7402         u64 num_bytes;
7403         u64 empty_size;
7404         u64 flags;
7405         int delalloc;
7406
7407         /* Where to start the search inside the bg */
7408         u64 search_start;
7409
7410         /* For clustered allocation */
7411         u64 empty_cluster;
7412
7413         bool have_caching_bg;
7414         bool orig_have_caching_bg;
7415
7416         /* RAID index, converted from flags */
7417         int index;
7418
7419         /*
7420          * Current loop number, check find_free_extent_update_loop() for details
7421          */
7422         int loop;
7423
7424         /*
7425          * Whether we're refilling a cluster, if true we need to re-search
7426          * current block group but don't try to refill the cluster again.
7427          */
7428         bool retry_clustered;
7429
7430         /*
7431          * Whether we're updating free space cache, if true we need to re-search
7432          * current block group but don't try updating free space cache again.
7433          */
7434         bool retry_unclustered;
7435
7436         /* If current block group is cached */
7437         int cached;
7438
7439         /* Max contiguous hole found */
7440         u64 max_extent_size;
7441
7442         /* Total free space from free space cache, not always contiguous */
7443         u64 total_free_space;
7444
7445         /* Found result */
7446         u64 found_offset;
7447 };
7448
7449
7450 /*
7451  * Helper function for find_free_extent().
7452  *
7453  * Return -ENOENT to inform caller that we need fallback to unclustered mode.
7454  * Return -EAGAIN to inform caller that we need to re-search this block group
7455  * Return >0 to inform caller that we find nothing
7456  * Return 0 means we have found a location and set ffe_ctl->found_offset.
7457  */
7458 static int find_free_extent_clustered(struct btrfs_block_group_cache *bg,
7459                 struct btrfs_free_cluster *last_ptr,
7460                 struct find_free_extent_ctl *ffe_ctl,
7461                 struct btrfs_block_group_cache **cluster_bg_ret)
7462 {
7463         struct btrfs_block_group_cache *cluster_bg;
7464         u64 aligned_cluster;
7465         u64 offset;
7466         int ret;
7467
7468         cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc);
7469         if (!cluster_bg)
7470                 goto refill_cluster;
7471         if (cluster_bg != bg && (cluster_bg->ro ||
7472             !block_group_bits(cluster_bg, ffe_ctl->flags)))
7473                 goto release_cluster;
7474
7475         offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
7476                         ffe_ctl->num_bytes, cluster_bg->key.objectid,
7477                         &ffe_ctl->max_extent_size);
7478         if (offset) {
7479                 /* We have a block, we're done */
7480                 spin_unlock(&last_ptr->refill_lock);
7481                 trace_btrfs_reserve_extent_cluster(cluster_bg,
7482                                 ffe_ctl->search_start, ffe_ctl->num_bytes);
7483                 *cluster_bg_ret = cluster_bg;
7484                 ffe_ctl->found_offset = offset;
7485                 return 0;
7486         }
7487         WARN_ON(last_ptr->block_group != cluster_bg);
7488
7489 release_cluster:
7490         /*
7491          * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
7492          * lets just skip it and let the allocator find whatever block it can
7493          * find. If we reach this point, we will have tried the cluster
7494          * allocator plenty of times and not have found anything, so we are
7495          * likely way too fragmented for the clustering stuff to find anything.
7496          *
7497          * However, if the cluster is taken from the current block group,
7498          * release the cluster first, so that we stand a better chance of
7499          * succeeding in the unclustered allocation.
7500          */
7501         if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
7502                 spin_unlock(&last_ptr->refill_lock);
7503                 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
7504                 return -ENOENT;
7505         }
7506
7507         /* This cluster didn't work out, free it and start over */
7508         btrfs_return_cluster_to_free_space(NULL, last_ptr);
7509
7510         if (cluster_bg != bg)
7511                 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
7512
7513 refill_cluster:
7514         if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
7515                 spin_unlock(&last_ptr->refill_lock);
7516                 return -ENOENT;
7517         }
7518
7519         aligned_cluster = max_t(u64,
7520                         ffe_ctl->empty_cluster + ffe_ctl->empty_size,
7521                         bg->full_stripe_len);
7522         ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
7523                         ffe_ctl->num_bytes, aligned_cluster);
7524         if (ret == 0) {
7525                 /* Now pull our allocation out of this cluster */
7526                 offset = btrfs_alloc_from_cluster(bg, last_ptr,
7527                                 ffe_ctl->num_bytes, ffe_ctl->search_start,
7528                                 &ffe_ctl->max_extent_size);
7529                 if (offset) {
7530                         /* We found one, proceed */
7531                         spin_unlock(&last_ptr->refill_lock);
7532                         trace_btrfs_reserve_extent_cluster(bg,
7533                                         ffe_ctl->search_start,
7534                                         ffe_ctl->num_bytes);
7535                         ffe_ctl->found_offset = offset;
7536                         return 0;
7537                 }
7538         } else if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
7539                    !ffe_ctl->retry_clustered) {
7540                 spin_unlock(&last_ptr->refill_lock);
7541
7542                 ffe_ctl->retry_clustered = true;
7543                 wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
7544                                 ffe_ctl->empty_cluster + ffe_ctl->empty_size);
7545                 return -EAGAIN;
7546         }
7547         /*
7548          * At this point we either didn't find a cluster or we weren't able to
7549          * allocate a block from our cluster.  Free the cluster we've been
7550          * trying to use, and go to the next block group.
7551          */
7552         btrfs_return_cluster_to_free_space(NULL, last_ptr);
7553         spin_unlock(&last_ptr->refill_lock);
7554         return 1;
7555 }
7556
7557 /*
7558  * Return >0 to inform caller that we find nothing
7559  * Return 0 when we found an free extent and set ffe_ctrl->found_offset
7560  * Return -EAGAIN to inform caller that we need to re-search this block group
7561  */
7562 static int find_free_extent_unclustered(struct btrfs_block_group_cache *bg,
7563                 struct btrfs_free_cluster *last_ptr,
7564                 struct find_free_extent_ctl *ffe_ctl)
7565 {
7566         u64 offset;
7567
7568         /*
7569          * We are doing an unclustered allocation, set the fragmented flag so
7570          * we don't bother trying to setup a cluster again until we get more
7571          * space.
7572          */
7573         if (unlikely(last_ptr)) {
7574                 spin_lock(&last_ptr->lock);
7575                 last_ptr->fragmented = 1;
7576                 spin_unlock(&last_ptr->lock);
7577         }
7578         if (ffe_ctl->cached) {
7579                 struct btrfs_free_space_ctl *free_space_ctl;
7580
7581                 free_space_ctl = bg->free_space_ctl;
7582                 spin_lock(&free_space_ctl->tree_lock);
7583                 if (free_space_ctl->free_space <
7584                     ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
7585                     ffe_ctl->empty_size) {
7586                         ffe_ctl->total_free_space = max_t(u64,
7587                                         ffe_ctl->total_free_space,
7588                                         free_space_ctl->free_space);
7589                         spin_unlock(&free_space_ctl->tree_lock);
7590                         return 1;
7591                 }
7592                 spin_unlock(&free_space_ctl->tree_lock);
7593         }
7594
7595         offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
7596                         ffe_ctl->num_bytes, ffe_ctl->empty_size,
7597                         &ffe_ctl->max_extent_size);
7598
7599         /*
7600          * If we didn't find a chunk, and we haven't failed on this block group
7601          * before, and this block group is in the middle of caching and we are
7602          * ok with waiting, then go ahead and wait for progress to be made, and
7603          * set @retry_unclustered to true.
7604          *
7605          * If @retry_unclustered is true then we've already waited on this
7606          * block group once and should move on to the next block group.
7607          */
7608         if (!offset && !ffe_ctl->retry_unclustered && !ffe_ctl->cached &&
7609             ffe_ctl->loop > LOOP_CACHING_NOWAIT) {
7610                 wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
7611                                                 ffe_ctl->empty_size);
7612                 ffe_ctl->retry_unclustered = true;
7613                 return -EAGAIN;
7614         } else if (!offset) {
7615                 return 1;
7616         }
7617         ffe_ctl->found_offset = offset;
7618         return 0;
7619 }
7620
7621 /*
7622  * Return >0 means caller needs to re-search for free extent
7623  * Return 0 means we have the needed free extent.
7624  * Return <0 means we failed to locate any free extent.
7625  */
7626 static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
7627                                         struct btrfs_free_cluster *last_ptr,
7628                                         struct btrfs_key *ins,
7629                                         struct find_free_extent_ctl *ffe_ctl,
7630                                         int full_search, bool use_cluster)
7631 {
7632         struct btrfs_root *root = fs_info->extent_root;
7633         int ret;
7634
7635         if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
7636             ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
7637                 ffe_ctl->orig_have_caching_bg = true;
7638
7639         if (!ins->objectid && ffe_ctl->loop >= LOOP_CACHING_WAIT &&
7640             ffe_ctl->have_caching_bg)
7641                 return 1;
7642
7643         if (!ins->objectid && ++(ffe_ctl->index) < BTRFS_NR_RAID_TYPES)
7644                 return 1;
7645
7646         if (ins->objectid) {
7647                 if (!use_cluster && last_ptr) {
7648                         spin_lock(&last_ptr->lock);
7649                         last_ptr->window_start = ins->objectid;
7650                         spin_unlock(&last_ptr->lock);
7651                 }
7652                 return 0;
7653         }
7654
7655         /*
7656          * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
7657          *                      caching kthreads as we move along
7658          * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
7659          * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
7660          * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
7661          *                     again
7662          */
7663         if (ffe_ctl->loop < LOOP_NO_EMPTY_SIZE) {
7664                 ffe_ctl->index = 0;
7665                 if (ffe_ctl->loop == LOOP_CACHING_NOWAIT) {
7666                         /*
7667                          * We want to skip the LOOP_CACHING_WAIT step if we
7668                          * don't have any uncached bgs and we've already done a
7669                          * full search through.
7670                          */
7671                         if (ffe_ctl->orig_have_caching_bg || !full_search)
7672                                 ffe_ctl->loop = LOOP_CACHING_WAIT;
7673                         else
7674                                 ffe_ctl->loop = LOOP_ALLOC_CHUNK;
7675                 } else {
7676                         ffe_ctl->loop++;
7677                 }
7678
7679                 if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
7680                         struct btrfs_trans_handle *trans;
7681                         int exist = 0;
7682
7683                         trans = current->journal_info;
7684                         if (trans)
7685                                 exist = 1;
7686                         else
7687                                 trans = btrfs_join_transaction(root);
7688
7689                         if (IS_ERR(trans)) {
7690                                 ret = PTR_ERR(trans);
7691                                 return ret;
7692                         }
7693
7694                         ret = do_chunk_alloc(trans, ffe_ctl->flags,
7695                                              CHUNK_ALLOC_FORCE);
7696
7697                         /*
7698                          * If we can't allocate a new chunk we've already looped
7699                          * through at least once, move on to the NO_EMPTY_SIZE
7700                          * case.
7701                          */
7702                         if (ret == -ENOSPC)
7703                                 ffe_ctl->loop = LOOP_NO_EMPTY_SIZE;
7704
7705                         /* Do not bail out on ENOSPC since we can do more. */
7706                         if (ret < 0 && ret != -ENOSPC)
7707                                 btrfs_abort_transaction(trans, ret);
7708                         else
7709                                 ret = 0;
7710                         if (!exist)
7711                                 btrfs_end_transaction(trans);
7712                         if (ret)
7713                                 return ret;
7714                 }
7715
7716                 if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
7717                         /*
7718                          * Don't loop again if we already have no empty_size and
7719                          * no empty_cluster.
7720                          */
7721                         if (ffe_ctl->empty_size == 0 &&
7722                             ffe_ctl->empty_cluster == 0)
7723                                 return -ENOSPC;
7724                         ffe_ctl->empty_size = 0;
7725                         ffe_ctl->empty_cluster = 0;
7726                 }
7727                 return 1;
7728         }
7729         return -ENOSPC;
7730 }
7731
7732 /*
7733  * walks the btree of allocated extents and find a hole of a given size.
7734  * The key ins is changed to record the hole:
7735  * ins->objectid == start position
7736  * ins->flags = BTRFS_EXTENT_ITEM_KEY
7737  * ins->offset == the size of the hole.
7738  * Any available blocks before search_start are skipped.
7739  *
7740  * If there is no suitable free space, we will record the max size of
7741  * the free space extent currently.
7742  *
7743  * The overall logic and call chain:
7744  *
7745  * find_free_extent()
7746  * |- Iterate through all block groups
7747  * |  |- Get a valid block group
7748  * |  |- Try to do clustered allocation in that block group
7749  * |  |- Try to do unclustered allocation in that block group
7750  * |  |- Check if the result is valid
7751  * |  |  |- If valid, then exit
7752  * |  |- Jump to next block group
7753  * |
7754  * |- Push harder to find free extents
7755  *    |- If not found, re-iterate all block groups
7756  */
7757 static noinline int find_free_extent(struct btrfs_fs_info *fs_info,
7758                                 u64 ram_bytes, u64 num_bytes, u64 empty_size,
7759                                 u64 hint_byte, struct btrfs_key *ins,
7760                                 u64 flags, int delalloc)
7761 {
7762         int ret = 0;
7763         struct btrfs_free_cluster *last_ptr = NULL;
7764         struct btrfs_block_group_cache *block_group = NULL;
7765         struct find_free_extent_ctl ffe_ctl = {0};
7766         struct btrfs_space_info *space_info;
7767         bool use_cluster = true;
7768         bool full_search = false;
7769
7770         WARN_ON(num_bytes < fs_info->sectorsize);
7771
7772         ffe_ctl.ram_bytes = ram_bytes;
7773         ffe_ctl.num_bytes = num_bytes;
7774         ffe_ctl.empty_size = empty_size;
7775         ffe_ctl.flags = flags;
7776         ffe_ctl.search_start = 0;
7777         ffe_ctl.retry_clustered = false;
7778         ffe_ctl.retry_unclustered = false;
7779         ffe_ctl.delalloc = delalloc;
7780         ffe_ctl.index = btrfs_bg_flags_to_raid_index(flags);
7781         ffe_ctl.have_caching_bg = false;
7782         ffe_ctl.orig_have_caching_bg = false;
7783         ffe_ctl.found_offset = 0;
7784
7785         ins->type = BTRFS_EXTENT_ITEM_KEY;
7786         ins->objectid = 0;
7787         ins->offset = 0;
7788
7789         trace_find_free_extent(fs_info, num_bytes, empty_size, flags);
7790
7791         space_info = __find_space_info(fs_info, flags);
7792         if (!space_info) {
7793                 btrfs_err(fs_info, "No space info for %llu", flags);
7794                 return -ENOSPC;
7795         }
7796
7797         /*
7798          * If our free space is heavily fragmented we may not be able to make
7799          * big contiguous allocations, so instead of doing the expensive search
7800          * for free space, simply return ENOSPC with our max_extent_size so we
7801          * can go ahead and search for a more manageable chunk.
7802          *
7803          * If our max_extent_size is large enough for our allocation simply
7804          * disable clustering since we will likely not be able to find enough
7805          * space to create a cluster and induce latency trying.
7806          */
7807         if (unlikely(space_info->max_extent_size)) {
7808                 spin_lock(&space_info->lock);
7809                 if (space_info->max_extent_size &&
7810                     num_bytes > space_info->max_extent_size) {
7811                         ins->offset = space_info->max_extent_size;
7812                         spin_unlock(&space_info->lock);
7813                         return -ENOSPC;
7814                 } else if (space_info->max_extent_size) {
7815                         use_cluster = false;
7816                 }
7817                 spin_unlock(&space_info->lock);
7818         }
7819
7820         last_ptr = fetch_cluster_info(fs_info, space_info,
7821                                       &ffe_ctl.empty_cluster);
7822         if (last_ptr) {
7823                 spin_lock(&last_ptr->lock);
7824                 if (last_ptr->block_group)
7825                         hint_byte = last_ptr->window_start;
7826                 if (last_ptr->fragmented) {
7827                         /*
7828                          * We still set window_start so we can keep track of the
7829                          * last place we found an allocation to try and save
7830                          * some time.
7831                          */
7832                         hint_byte = last_ptr->window_start;
7833                         use_cluster = false;
7834                 }
7835                 spin_unlock(&last_ptr->lock);
7836         }
7837
7838         ffe_ctl.search_start = max(ffe_ctl.search_start,
7839                                    first_logical_byte(fs_info, 0));
7840         ffe_ctl.search_start = max(ffe_ctl.search_start, hint_byte);
7841         if (ffe_ctl.search_start == hint_byte) {
7842                 block_group = btrfs_lookup_block_group(fs_info,
7843                                                        ffe_ctl.search_start);
7844                 /*
7845                  * we don't want to use the block group if it doesn't match our
7846                  * allocation bits, or if its not cached.
7847                  *
7848                  * However if we are re-searching with an ideal block group
7849                  * picked out then we don't care that the block group is cached.
7850                  */
7851                 if (block_group && block_group_bits(block_group, flags) &&
7852                     block_group->cached != BTRFS_CACHE_NO) {
7853                         down_read(&space_info->groups_sem);
7854                         if (list_empty(&block_group->list) ||
7855                             block_group->ro) {
7856                                 /*
7857                                  * someone is removing this block group,
7858                                  * we can't jump into the have_block_group
7859                                  * target because our list pointers are not
7860                                  * valid
7861                                  */
7862                                 btrfs_put_block_group(block_group);
7863                                 up_read(&space_info->groups_sem);
7864                         } else {
7865                                 ffe_ctl.index = btrfs_bg_flags_to_raid_index(
7866                                                 block_group->flags);
7867                                 btrfs_lock_block_group(block_group, delalloc);
7868                                 goto have_block_group;
7869                         }
7870                 } else if (block_group) {
7871                         btrfs_put_block_group(block_group);
7872                 }
7873         }
7874 search:
7875         ffe_ctl.have_caching_bg = false;
7876         if (ffe_ctl.index == btrfs_bg_flags_to_raid_index(flags) ||
7877             ffe_ctl.index == 0)
7878                 full_search = true;
7879         down_read(&space_info->groups_sem);
7880         list_for_each_entry(block_group,
7881                             &space_info->block_groups[ffe_ctl.index], list) {
7882                 /* If the block group is read-only, we can skip it entirely. */
7883                 if (unlikely(block_group->ro))
7884                         continue;
7885
7886                 btrfs_grab_block_group(block_group, delalloc);
7887                 ffe_ctl.search_start = block_group->key.objectid;
7888
7889                 /*
7890                  * this can happen if we end up cycling through all the
7891                  * raid types, but we want to make sure we only allocate
7892                  * for the proper type.
7893                  */
7894                 if (!block_group_bits(block_group, flags)) {
7895                         u64 extra = BTRFS_BLOCK_GROUP_DUP |
7896                                 BTRFS_BLOCK_GROUP_RAID1 |
7897                                 BTRFS_BLOCK_GROUP_RAID5 |
7898                                 BTRFS_BLOCK_GROUP_RAID6 |
7899                                 BTRFS_BLOCK_GROUP_RAID10;
7900
7901                         /*
7902                          * if they asked for extra copies and this block group
7903                          * doesn't provide them, bail.  This does allow us to
7904                          * fill raid0 from raid1.
7905                          */
7906                         if ((flags & extra) && !(block_group->flags & extra))
7907                                 goto loop;
7908                 }
7909
7910 have_block_group:
7911                 ffe_ctl.cached = block_group_cache_done(block_group);
7912                 if (unlikely(!ffe_ctl.cached)) {
7913                         ffe_ctl.have_caching_bg = true;
7914                         ret = cache_block_group(block_group, 0);
7915                         BUG_ON(ret < 0);
7916                         ret = 0;
7917                 }
7918
7919                 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
7920                         goto loop;
7921
7922                 /*
7923                  * Ok we want to try and use the cluster allocator, so
7924                  * lets look there
7925                  */
7926                 if (last_ptr && use_cluster) {
7927                         struct btrfs_block_group_cache *cluster_bg = NULL;
7928
7929                         ret = find_free_extent_clustered(block_group, last_ptr,
7930                                                          &ffe_ctl, &cluster_bg);
7931
7932                         if (ret == 0) {
7933                                 if (cluster_bg && cluster_bg != block_group) {
7934                                         btrfs_release_block_group(block_group,
7935                                                                   delalloc);
7936                                         block_group = cluster_bg;
7937                                 }
7938                                 goto checks;
7939                         } else if (ret == -EAGAIN) {
7940                                 goto have_block_group;
7941                         } else if (ret > 0) {
7942                                 goto loop;
7943                         }
7944                         /* ret == -ENOENT case falls through */
7945                 }
7946
7947                 ret = find_free_extent_unclustered(block_group, last_ptr,
7948                                                    &ffe_ctl);
7949                 if (ret == -EAGAIN)
7950                         goto have_block_group;
7951                 else if (ret > 0)
7952                         goto loop;
7953                 /* ret == 0 case falls through */
7954 checks:
7955                 ffe_ctl.search_start = round_up(ffe_ctl.found_offset,
7956                                              fs_info->stripesize);
7957
7958                 /* move on to the next group */
7959                 if (ffe_ctl.search_start + num_bytes >
7960                     block_group->key.objectid + block_group->key.offset) {
7961                         btrfs_add_free_space(block_group, ffe_ctl.found_offset,
7962                                              num_bytes);
7963                         goto loop;
7964                 }
7965
7966                 if (ffe_ctl.found_offset < ffe_ctl.search_start)
7967                         btrfs_add_free_space(block_group, ffe_ctl.found_offset,
7968                                 ffe_ctl.search_start - ffe_ctl.found_offset);
7969
7970                 ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
7971                                 num_bytes, delalloc);
7972                 if (ret == -EAGAIN) {
7973                         btrfs_add_free_space(block_group, ffe_ctl.found_offset,
7974                                              num_bytes);
7975                         goto loop;
7976                 }
7977                 btrfs_inc_block_group_reservations(block_group);
7978
7979                 /* we are all good, lets return */
7980                 ins->objectid = ffe_ctl.search_start;
7981                 ins->offset = num_bytes;
7982
7983                 trace_btrfs_reserve_extent(block_group, ffe_ctl.search_start,
7984                                            num_bytes);
7985                 btrfs_release_block_group(block_group, delalloc);
7986                 break;
7987 loop:
7988                 ffe_ctl.retry_clustered = false;
7989                 ffe_ctl.retry_unclustered = false;
7990                 BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
7991                        ffe_ctl.index);
7992                 btrfs_release_block_group(block_group, delalloc);
7993                 cond_resched();
7994         }
7995         up_read(&space_info->groups_sem);
7996
7997         ret = find_free_extent_update_loop(fs_info, last_ptr, ins, &ffe_ctl,
7998                                            full_search, use_cluster);
7999         if (ret > 0)
8000                 goto search;
8001
8002         if (ret == -ENOSPC) {
8003                 /*
8004                  * Use ffe_ctl->total_free_space as fallback if we can't find
8005                  * any contiguous hole.
8006                  */
8007                 if (!ffe_ctl.max_extent_size)
8008                         ffe_ctl.max_extent_size = ffe_ctl.total_free_space;
8009                 spin_lock(&space_info->lock);
8010                 space_info->max_extent_size = ffe_ctl.max_extent_size;
8011                 spin_unlock(&space_info->lock);
8012                 ins->offset = ffe_ctl.max_extent_size;
8013         }
8014         return ret;
8015 }
8016
8017 #define DUMP_BLOCK_RSV(fs_info, rsv_name)                               \
8018 do {                                                                    \
8019         struct btrfs_block_rsv *__rsv = &(fs_info)->rsv_name;           \
8020         spin_lock(&__rsv->lock);                                        \
8021         btrfs_info(fs_info, #rsv_name ": size %llu reserved %llu",      \
8022                    __rsv->size, __rsv->reserved);                       \
8023         spin_unlock(&__rsv->lock);                                      \
8024 } while (0)
8025
8026 static void dump_space_info(struct btrfs_fs_info *fs_info,
8027                             struct btrfs_space_info *info, u64 bytes,
8028                             int dump_block_groups)
8029 {
8030         struct btrfs_block_group_cache *cache;
8031         int index = 0;
8032
8033         spin_lock(&info->lock);
8034         btrfs_info(fs_info, "space_info %llu has %llu free, is %sfull",
8035                    info->flags,
8036                    info->total_bytes - btrfs_space_info_used(info, true),
8037                    info->full ? "" : "not ");
8038         btrfs_info(fs_info,
8039                 "space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu",
8040                 info->total_bytes, info->bytes_used, info->bytes_pinned,
8041                 info->bytes_reserved, info->bytes_may_use,
8042                 info->bytes_readonly);
8043         spin_unlock(&info->lock);
8044
8045         DUMP_BLOCK_RSV(fs_info, global_block_rsv);
8046         DUMP_BLOCK_RSV(fs_info, trans_block_rsv);
8047         DUMP_BLOCK_RSV(fs_info, chunk_block_rsv);
8048         DUMP_BLOCK_RSV(fs_info, delayed_block_rsv);
8049         DUMP_BLOCK_RSV(fs_info, delayed_refs_rsv);
8050
8051         if (!dump_block_groups)
8052                 return;
8053
8054         down_read(&info->groups_sem);
8055 again:
8056         list_for_each_entry(cache, &info->block_groups[index], list) {
8057                 spin_lock(&cache->lock);
8058                 btrfs_info(fs_info,
8059                         "block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %s",
8060                         cache->key.objectid, cache->key.offset,
8061                         btrfs_block_group_used(&cache->item), cache->pinned,
8062                         cache->reserved, cache->ro ? "[readonly]" : "");
8063                 btrfs_dump_free_space(cache, bytes);
8064                 spin_unlock(&cache->lock);
8065         }
8066         if (++index < BTRFS_NR_RAID_TYPES)
8067                 goto again;
8068         up_read(&info->groups_sem);
8069 }
8070
8071 /*
8072  * btrfs_reserve_extent - entry point to the extent allocator. Tries to find a
8073  *                        hole that is at least as big as @num_bytes.
8074  *
8075  * @root           -    The root that will contain this extent
8076  *
8077  * @ram_bytes      -    The amount of space in ram that @num_bytes take. This
8078  *                      is used for accounting purposes. This value differs
8079  *                      from @num_bytes only in the case of compressed extents.
8080  *
8081  * @num_bytes      -    Number of bytes to allocate on-disk.
8082  *
8083  * @min_alloc_size -    Indicates the minimum amount of space that the
8084  *                      allocator should try to satisfy. In some cases
8085  *                      @num_bytes may be larger than what is required and if
8086  *                      the filesystem is fragmented then allocation fails.
8087  *                      However, the presence of @min_alloc_size gives a
8088  *                      chance to try and satisfy the smaller allocation.
8089  *
8090  * @empty_size     -    A hint that you plan on doing more COW. This is the
8091  *                      size in bytes the allocator should try to find free
8092  *                      next to the block it returns.  This is just a hint and
8093  *                      may be ignored by the allocator.
8094  *
8095  * @hint_byte      -    Hint to the allocator to start searching above the byte
8096  *                      address passed. It might be ignored.
8097  *
8098  * @ins            -    This key is modified to record the found hole. It will
8099  *                      have the following values:
8100  *                      ins->objectid == start position
8101  *                      ins->flags = BTRFS_EXTENT_ITEM_KEY
8102  *                      ins->offset == the size of the hole.
8103  *
8104  * @is_data        -    Boolean flag indicating whether an extent is
8105  *                      allocated for data (true) or metadata (false)
8106  *
8107  * @delalloc       -    Boolean flag indicating whether this allocation is for
8108  *                      delalloc or not. If 'true' data_rwsem of block groups
8109  *                      is going to be acquired.
8110  *
8111  *
8112  * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
8113  * case -ENOSPC is returned then @ins->offset will contain the size of the
8114  * largest available hole the allocator managed to find.
8115  */
8116 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
8117                          u64 num_bytes, u64 min_alloc_size,
8118                          u64 empty_size, u64 hint_byte,
8119                          struct btrfs_key *ins, int is_data, int delalloc)
8120 {
8121         struct btrfs_fs_info *fs_info = root->fs_info;
8122         bool final_tried = num_bytes == min_alloc_size;
8123         u64 flags;
8124         int ret;
8125
8126         flags = get_alloc_profile_by_root(root, is_data);
8127 again:
8128         WARN_ON(num_bytes < fs_info->sectorsize);
8129         ret = find_free_extent(fs_info, ram_bytes, num_bytes, empty_size,
8130                                hint_byte, ins, flags, delalloc);
8131         if (!ret && !is_data) {
8132                 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
8133         } else if (ret == -ENOSPC) {
8134                 if (!final_tried && ins->offset) {
8135                         num_bytes = min(num_bytes >> 1, ins->offset);
8136                         num_bytes = round_down(num_bytes,
8137                                                fs_info->sectorsize);
8138                         num_bytes = max(num_bytes, min_alloc_size);
8139                         ram_bytes = num_bytes;
8140                         if (num_bytes == min_alloc_size)
8141                                 final_tried = true;
8142                         goto again;
8143                 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
8144                         struct btrfs_space_info *sinfo;
8145
8146                         sinfo = __find_space_info(fs_info, flags);
8147                         btrfs_err(fs_info,
8148                                   "allocation failed flags %llu, wanted %llu",
8149                                   flags, num_bytes);
8150                         if (sinfo)
8151                                 dump_space_info(fs_info, sinfo, num_bytes, 1);
8152                 }
8153         }
8154
8155         return ret;
8156 }
8157
8158 static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
8159                                         u64 start, u64 len,
8160                                         int pin, int delalloc)
8161 {
8162         struct btrfs_block_group_cache *cache;
8163         int ret = 0;
8164
8165         cache = btrfs_lookup_block_group(fs_info, start);
8166         if (!cache) {
8167                 btrfs_err(fs_info, "Unable to find block group for %llu",
8168                           start);
8169                 return -ENOSPC;
8170         }
8171
8172         if (pin)
8173                 pin_down_extent(cache, start, len, 1);
8174         else {
8175                 if (btrfs_test_opt(fs_info, DISCARD))
8176                         ret = btrfs_discard_extent(fs_info, start, len, NULL);
8177                 btrfs_add_free_space(cache, start, len);
8178                 btrfs_free_reserved_bytes(cache, len, delalloc);
8179                 trace_btrfs_reserved_extent_free(fs_info, start, len);
8180         }
8181
8182         btrfs_put_block_group(cache);
8183         return ret;
8184 }
8185
8186 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
8187                                u64 start, u64 len, int delalloc)
8188 {
8189         return __btrfs_free_reserved_extent(fs_info, start, len, 0, delalloc);
8190 }
8191
8192 int btrfs_free_and_pin_reserved_extent(struct btrfs_fs_info *fs_info,
8193                                        u64 start, u64 len)
8194 {
8195         return __btrfs_free_reserved_extent(fs_info, start, len, 1, 0);
8196 }
8197
8198 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
8199                                       u64 parent, u64 root_objectid,
8200                                       u64 flags, u64 owner, u64 offset,
8201                                       struct btrfs_key *ins, int ref_mod)
8202 {
8203         struct btrfs_fs_info *fs_info = trans->fs_info;
8204         int ret;
8205         struct btrfs_extent_item *extent_item;
8206         struct btrfs_extent_inline_ref *iref;
8207         struct btrfs_path *path;
8208         struct extent_buffer *leaf;
8209         int type;
8210         u32 size;
8211
8212         if (parent > 0)
8213                 type = BTRFS_SHARED_DATA_REF_KEY;
8214         else
8215                 type = BTRFS_EXTENT_DATA_REF_KEY;
8216
8217         size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
8218
8219         path = btrfs_alloc_path();
8220         if (!path)
8221                 return -ENOMEM;
8222
8223         path->leave_spinning = 1;
8224         ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
8225                                       ins, size);
8226         if (ret) {
8227                 btrfs_free_path(path);
8228                 return ret;
8229         }
8230
8231         leaf = path->nodes[0];
8232         extent_item = btrfs_item_ptr(leaf, path->slots[0],
8233                                      struct btrfs_extent_item);
8234         btrfs_set_extent_refs(leaf, extent_item, ref_mod);
8235         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
8236         btrfs_set_extent_flags(leaf, extent_item,
8237                                flags | BTRFS_EXTENT_FLAG_DATA);
8238
8239         iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
8240         btrfs_set_extent_inline_ref_type(leaf, iref, type);
8241         if (parent > 0) {
8242                 struct btrfs_shared_data_ref *ref;
8243                 ref = (struct btrfs_shared_data_ref *)(iref + 1);
8244                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
8245                 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
8246         } else {
8247                 struct btrfs_extent_data_ref *ref;
8248                 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
8249                 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
8250                 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
8251                 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
8252                 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
8253         }
8254
8255         btrfs_mark_buffer_dirty(path->nodes[0]);
8256         btrfs_free_path(path);
8257
8258         ret = remove_from_free_space_tree(trans, ins->objectid, ins->offset);
8259         if (ret)
8260                 return ret;
8261
8262         ret = update_block_group(trans, ins->objectid, ins->offset, 1);
8263         if (ret) { /* -ENOENT, logic error */
8264                 btrfs_err(fs_info, "update block group failed for %llu %llu",
8265                         ins->objectid, ins->offset);
8266                 BUG();
8267         }
8268         trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
8269         return ret;
8270 }
8271
8272 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
8273                                      struct btrfs_delayed_ref_node *node,
8274                                      struct btrfs_delayed_extent_op *extent_op)
8275 {
8276         struct btrfs_fs_info *fs_info = trans->fs_info;
8277         int ret;
8278         struct btrfs_extent_item *extent_item;
8279         struct btrfs_key extent_key;
8280         struct btrfs_tree_block_info *block_info;
8281         struct btrfs_extent_inline_ref *iref;
8282         struct btrfs_path *path;
8283         struct extent_buffer *leaf;
8284         struct btrfs_delayed_tree_ref *ref;
8285         u32 size = sizeof(*extent_item) + sizeof(*iref);
8286         u64 num_bytes;
8287         u64 flags = extent_op->flags_to_set;
8288         bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
8289
8290         ref = btrfs_delayed_node_to_tree_ref(node);
8291
8292         extent_key.objectid = node->bytenr;
8293         if (skinny_metadata) {
8294                 extent_key.offset = ref->level;
8295                 extent_key.type = BTRFS_METADATA_ITEM_KEY;
8296                 num_bytes = fs_info->nodesize;
8297         } else {
8298                 extent_key.offset = node->num_bytes;
8299                 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
8300                 size += sizeof(*block_info);
8301                 num_bytes = node->num_bytes;
8302         }
8303
8304         path = btrfs_alloc_path();
8305         if (!path)
8306                 return -ENOMEM;
8307
8308         path->leave_spinning = 1;
8309         ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
8310                                       &extent_key, size);
8311         if (ret) {
8312                 btrfs_free_path(path);
8313                 return ret;
8314         }
8315
8316         leaf = path->nodes[0];
8317         extent_item = btrfs_item_ptr(leaf, path->slots[0],
8318                                      struct btrfs_extent_item);
8319         btrfs_set_extent_refs(leaf, extent_item, 1);
8320         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
8321         btrfs_set_extent_flags(leaf, extent_item,
8322                                flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
8323
8324         if (skinny_metadata) {
8325                 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
8326         } else {
8327                 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
8328                 btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
8329                 btrfs_set_tree_block_level(leaf, block_info, ref->level);
8330                 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
8331         }
8332
8333         if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
8334                 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8335                 btrfs_set_extent_inline_ref_type(leaf, iref,
8336                                                  BTRFS_SHARED_BLOCK_REF_KEY);
8337                 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->parent);
8338         } else {
8339                 btrfs_set_extent_inline_ref_type(leaf, iref,
8340                                                  BTRFS_TREE_BLOCK_REF_KEY);
8341                 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->root);
8342         }
8343
8344         btrfs_mark_buffer_dirty(leaf);
8345         btrfs_free_path(path);
8346
8347         ret = remove_from_free_space_tree(trans, extent_key.objectid,
8348                                           num_bytes);
8349         if (ret)
8350                 return ret;
8351
8352         ret = update_block_group(trans, extent_key.objectid,
8353                                  fs_info->nodesize, 1);
8354         if (ret) { /* -ENOENT, logic error */
8355                 btrfs_err(fs_info, "update block group failed for %llu %llu",
8356                         extent_key.objectid, extent_key.offset);
8357                 BUG();
8358         }
8359
8360         trace_btrfs_reserved_extent_alloc(fs_info, extent_key.objectid,
8361                                           fs_info->nodesize);
8362         return ret;
8363 }
8364
8365 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
8366                                      struct btrfs_root *root, u64 owner,
8367                                      u64 offset, u64 ram_bytes,
8368                                      struct btrfs_key *ins)
8369 {
8370         struct btrfs_ref generic_ref = { 0 };
8371         int ret;
8372
8373         BUG_ON(root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
8374
8375         btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
8376                                ins->objectid, ins->offset, 0);
8377         btrfs_init_data_ref(&generic_ref, root->root_key.objectid, owner, offset);
8378         btrfs_ref_tree_mod(root->fs_info, &generic_ref);
8379         ret = btrfs_add_delayed_data_ref(trans, &generic_ref,
8380                                          ram_bytes, NULL, NULL);
8381         return ret;
8382 }
8383
8384 /*
8385  * this is used by the tree logging recovery code.  It records that
8386  * an extent has been allocated and makes sure to clear the free
8387  * space cache bits as well
8388  */
8389 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
8390                                    u64 root_objectid, u64 owner, u64 offset,
8391                                    struct btrfs_key *ins)
8392 {
8393         struct btrfs_fs_info *fs_info = trans->fs_info;
8394         int ret;
8395         struct btrfs_block_group_cache *block_group;
8396         struct btrfs_space_info *space_info;
8397
8398         /*
8399          * Mixed block groups will exclude before processing the log so we only
8400          * need to do the exclude dance if this fs isn't mixed.
8401          */
8402         if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
8403                 ret = __exclude_logged_extent(fs_info, ins->objectid,
8404                                               ins->offset);
8405                 if (ret)
8406                         return ret;
8407         }
8408
8409         block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
8410         if (!block_group)
8411                 return -EINVAL;
8412
8413         space_info = block_group->space_info;
8414         spin_lock(&space_info->lock);
8415         spin_lock(&block_group->lock);
8416         space_info->bytes_reserved += ins->offset;
8417         block_group->reserved += ins->offset;
8418         spin_unlock(&block_group->lock);
8419         spin_unlock(&space_info->lock);
8420
8421         ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
8422                                          offset, ins, 1);
8423         btrfs_put_block_group(block_group);
8424         return ret;
8425 }
8426
8427 static struct extent_buffer *
8428 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
8429                       u64 bytenr, int level, u64 owner)
8430 {
8431         struct btrfs_fs_info *fs_info = root->fs_info;
8432         struct extent_buffer *buf;
8433
8434         buf = btrfs_find_create_tree_block(fs_info, bytenr);
8435         if (IS_ERR(buf))
8436                 return buf;
8437
8438         /*
8439          * Extra safety check in case the extent tree is corrupted and extent
8440          * allocator chooses to use a tree block which is already used and
8441          * locked.
8442          */
8443         if (buf->lock_owner == current->pid) {
8444                 btrfs_err_rl(fs_info,
8445 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
8446                         buf->start, btrfs_header_owner(buf), current->pid);
8447                 free_extent_buffer(buf);
8448                 return ERR_PTR(-EUCLEAN);
8449         }
8450
8451         btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
8452         btrfs_tree_lock(buf);
8453         btrfs_clean_tree_block(buf);
8454         clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
8455
8456         btrfs_set_lock_blocking_write(buf);
8457         set_extent_buffer_uptodate(buf);
8458
8459         memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
8460         btrfs_set_header_level(buf, level);
8461         btrfs_set_header_bytenr(buf, buf->start);
8462         btrfs_set_header_generation(buf, trans->transid);
8463         btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
8464         btrfs_set_header_owner(buf, owner);
8465         write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
8466         write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
8467         if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
8468                 buf->log_index = root->log_transid % 2;
8469                 /*
8470                  * we allow two log transactions at a time, use different
8471                  * EXTENT bit to differentiate dirty pages.
8472                  */
8473                 if (buf->log_index == 0)
8474                         set_extent_dirty(&root->dirty_log_pages, buf->start,
8475                                         buf->start + buf->len - 1, GFP_NOFS);
8476                 else
8477                         set_extent_new(&root->dirty_log_pages, buf->start,
8478                                         buf->start + buf->len - 1);
8479         } else {
8480                 buf->log_index = -1;
8481                 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
8482                          buf->start + buf->len - 1, GFP_NOFS);
8483         }
8484         trans->dirty = true;
8485         /* this returns a buffer locked for blocking */
8486         return buf;
8487 }
8488
8489 static struct btrfs_block_rsv *
8490 use_block_rsv(struct btrfs_trans_handle *trans,
8491               struct btrfs_root *root, u32 blocksize)
8492 {
8493         struct btrfs_fs_info *fs_info = root->fs_info;
8494         struct btrfs_block_rsv *block_rsv;
8495         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
8496         int ret;
8497         bool global_updated = false;
8498
8499         block_rsv = get_block_rsv(trans, root);
8500
8501         if (unlikely(block_rsv->size == 0))
8502                 goto try_reserve;
8503 again:
8504         ret = block_rsv_use_bytes(block_rsv, blocksize);
8505         if (!ret)
8506                 return block_rsv;
8507
8508         if (block_rsv->failfast)
8509                 return ERR_PTR(ret);
8510
8511         if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
8512                 global_updated = true;
8513                 update_global_block_rsv(fs_info);
8514                 goto again;
8515         }
8516
8517         /*
8518          * The global reserve still exists to save us from ourselves, so don't
8519          * warn_on if we are short on our delayed refs reserve.
8520          */
8521         if (block_rsv->type != BTRFS_BLOCK_RSV_DELREFS &&
8522             btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
8523                 static DEFINE_RATELIMIT_STATE(_rs,
8524                                 DEFAULT_RATELIMIT_INTERVAL * 10,
8525                                 /*DEFAULT_RATELIMIT_BURST*/ 1);
8526                 if (__ratelimit(&_rs))
8527                         WARN(1, KERN_DEBUG
8528                                 "BTRFS: block rsv returned %d\n", ret);
8529         }
8530 try_reserve:
8531         ret = reserve_metadata_bytes(root, block_rsv, blocksize,
8532                                      BTRFS_RESERVE_NO_FLUSH);
8533         if (!ret)
8534                 return block_rsv;
8535         /*
8536          * If we couldn't reserve metadata bytes try and use some from
8537          * the global reserve if its space type is the same as the global
8538          * reservation.
8539          */
8540         if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
8541             block_rsv->space_info == global_rsv->space_info) {
8542                 ret = block_rsv_use_bytes(global_rsv, blocksize);
8543                 if (!ret)
8544                         return global_rsv;
8545         }
8546         return ERR_PTR(ret);
8547 }
8548
8549 static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
8550                             struct btrfs_block_rsv *block_rsv, u32 blocksize)
8551 {
8552         block_rsv_add_bytes(block_rsv, blocksize, false);
8553         block_rsv_release_bytes(fs_info, block_rsv, NULL, 0, NULL);
8554 }
8555
8556 /*
8557  * finds a free extent and does all the dirty work required for allocation
8558  * returns the tree buffer or an ERR_PTR on error.
8559  */
8560 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
8561                                              struct btrfs_root *root,
8562                                              u64 parent, u64 root_objectid,
8563                                              const struct btrfs_disk_key *key,
8564                                              int level, u64 hint,
8565                                              u64 empty_size)
8566 {
8567         struct btrfs_fs_info *fs_info = root->fs_info;
8568         struct btrfs_key ins;
8569         struct btrfs_block_rsv *block_rsv;
8570         struct extent_buffer *buf;
8571         struct btrfs_delayed_extent_op *extent_op;
8572         struct btrfs_ref generic_ref = { 0 };
8573         u64 flags = 0;
8574         int ret;
8575         u32 blocksize = fs_info->nodesize;
8576         bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
8577
8578 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8579         if (btrfs_is_testing(fs_info)) {
8580                 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
8581                                             level, root_objectid);
8582                 if (!IS_ERR(buf))
8583                         root->alloc_bytenr += blocksize;
8584                 return buf;
8585         }
8586 #endif
8587
8588         block_rsv = use_block_rsv(trans, root, blocksize);
8589         if (IS_ERR(block_rsv))
8590                 return ERR_CAST(block_rsv);
8591
8592         ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
8593                                    empty_size, hint, &ins, 0, 0);
8594         if (ret)
8595                 goto out_unuse;
8596
8597         buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
8598                                     root_objectid);
8599         if (IS_ERR(buf)) {
8600                 ret = PTR_ERR(buf);
8601                 goto out_free_reserved;
8602         }
8603
8604         if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
8605                 if (parent == 0)
8606                         parent = ins.objectid;
8607                 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
8608         } else
8609                 BUG_ON(parent > 0);
8610
8611         if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
8612                 extent_op = btrfs_alloc_delayed_extent_op();
8613                 if (!extent_op) {
8614                         ret = -ENOMEM;
8615                         goto out_free_buf;
8616                 }
8617                 if (key)
8618                         memcpy(&extent_op->key, key, sizeof(extent_op->key));
8619                 else
8620                         memset(&extent_op->key, 0, sizeof(extent_op->key));
8621                 extent_op->flags_to_set = flags;
8622                 extent_op->update_key = skinny_metadata ? false : true;
8623                 extent_op->update_flags = true;
8624                 extent_op->is_data = false;
8625                 extent_op->level = level;
8626
8627                 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
8628                                        ins.objectid, ins.offset, parent);
8629                 generic_ref.real_root = root->root_key.objectid;
8630                 btrfs_init_tree_ref(&generic_ref, level, root_objectid);
8631                 btrfs_ref_tree_mod(fs_info, &generic_ref);
8632                 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref,
8633                                                  extent_op, NULL, NULL);
8634                 if (ret)
8635                         goto out_free_delayed;
8636         }
8637         return buf;
8638
8639 out_free_delayed:
8640         btrfs_free_delayed_extent_op(extent_op);
8641 out_free_buf:
8642         free_extent_buffer(buf);
8643 out_free_reserved:
8644         btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
8645 out_unuse:
8646         unuse_block_rsv(fs_info, block_rsv, blocksize);
8647         return ERR_PTR(ret);
8648 }
8649
8650 struct walk_control {
8651         u64 refs[BTRFS_MAX_LEVEL];
8652         u64 flags[BTRFS_MAX_LEVEL];
8653         struct btrfs_key update_progress;
8654         struct btrfs_key drop_progress;
8655         int drop_level;
8656         int stage;
8657         int level;
8658         int shared_level;
8659         int update_ref;
8660         int keep_locks;
8661         int reada_slot;
8662         int reada_count;
8663         int restarted;
8664 };
8665
8666 #define DROP_REFERENCE  1
8667 #define UPDATE_BACKREF  2
8668
8669 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
8670                                      struct btrfs_root *root,
8671                                      struct walk_control *wc,
8672                                      struct btrfs_path *path)
8673 {
8674         struct btrfs_fs_info *fs_info = root->fs_info;
8675         u64 bytenr;
8676         u64 generation;
8677         u64 refs;
8678         u64 flags;
8679         u32 nritems;
8680         struct btrfs_key key;
8681         struct extent_buffer *eb;
8682         int ret;
8683         int slot;
8684         int nread = 0;
8685
8686         if (path->slots[wc->level] < wc->reada_slot) {
8687                 wc->reada_count = wc->reada_count * 2 / 3;
8688                 wc->reada_count = max(wc->reada_count, 2);
8689         } else {
8690                 wc->reada_count = wc->reada_count * 3 / 2;
8691                 wc->reada_count = min_t(int, wc->reada_count,
8692                                         BTRFS_NODEPTRS_PER_BLOCK(fs_info));
8693         }
8694
8695         eb = path->nodes[wc->level];
8696         nritems = btrfs_header_nritems(eb);
8697
8698         for (slot = path->slots[wc->level]; slot < nritems; slot++) {
8699                 if (nread >= wc->reada_count)
8700                         break;
8701
8702                 cond_resched();
8703                 bytenr = btrfs_node_blockptr(eb, slot);
8704                 generation = btrfs_node_ptr_generation(eb, slot);
8705
8706                 if (slot == path->slots[wc->level])
8707                         goto reada;
8708
8709                 if (wc->stage == UPDATE_BACKREF &&
8710                     generation <= root->root_key.offset)
8711                         continue;
8712
8713                 /* We don't lock the tree block, it's OK to be racy here */
8714                 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
8715                                                wc->level - 1, 1, &refs,
8716                                                &flags);
8717                 /* We don't care about errors in readahead. */
8718                 if (ret < 0)
8719                         continue;
8720                 BUG_ON(refs == 0);
8721
8722                 if (wc->stage == DROP_REFERENCE) {
8723                         if (refs == 1)
8724                                 goto reada;
8725
8726                         if (wc->level == 1 &&
8727                             (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8728                                 continue;
8729                         if (!wc->update_ref ||
8730                             generation <= root->root_key.offset)
8731                                 continue;
8732                         btrfs_node_key_to_cpu(eb, &key, slot);
8733                         ret = btrfs_comp_cpu_keys(&key,
8734                                                   &wc->update_progress);
8735                         if (ret < 0)
8736                                 continue;
8737                 } else {
8738                         if (wc->level == 1 &&
8739                             (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8740                                 continue;
8741                 }
8742 reada:
8743                 readahead_tree_block(fs_info, bytenr);
8744                 nread++;
8745         }
8746         wc->reada_slot = slot;
8747 }
8748
8749 /*
8750  * helper to process tree block while walking down the tree.
8751  *
8752  * when wc->stage == UPDATE_BACKREF, this function updates
8753  * back refs for pointers in the block.
8754  *
8755  * NOTE: return value 1 means we should stop walking down.
8756  */
8757 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
8758                                    struct btrfs_root *root,
8759                                    struct btrfs_path *path,
8760                                    struct walk_control *wc, int lookup_info)
8761 {
8762         struct btrfs_fs_info *fs_info = root->fs_info;
8763         int level = wc->level;
8764         struct extent_buffer *eb = path->nodes[level];
8765         u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8766         int ret;
8767
8768         if (wc->stage == UPDATE_BACKREF &&
8769             btrfs_header_owner(eb) != root->root_key.objectid)
8770                 return 1;
8771
8772         /*
8773          * when reference count of tree block is 1, it won't increase
8774          * again. once full backref flag is set, we never clear it.
8775          */
8776         if (lookup_info &&
8777             ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
8778              (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
8779                 BUG_ON(!path->locks[level]);
8780                 ret = btrfs_lookup_extent_info(trans, fs_info,
8781                                                eb->start, level, 1,
8782                                                &wc->refs[level],
8783                                                &wc->flags[level]);
8784                 BUG_ON(ret == -ENOMEM);
8785                 if (ret)
8786                         return ret;
8787                 BUG_ON(wc->refs[level] == 0);
8788         }
8789
8790         if (wc->stage == DROP_REFERENCE) {
8791                 if (wc->refs[level] > 1)
8792                         return 1;
8793
8794                 if (path->locks[level] && !wc->keep_locks) {
8795                         btrfs_tree_unlock_rw(eb, path->locks[level]);
8796                         path->locks[level] = 0;
8797                 }
8798                 return 0;
8799         }
8800
8801         /* wc->stage == UPDATE_BACKREF */
8802         if (!(wc->flags[level] & flag)) {
8803                 BUG_ON(!path->locks[level]);
8804                 ret = btrfs_inc_ref(trans, root, eb, 1);
8805                 BUG_ON(ret); /* -ENOMEM */
8806                 ret = btrfs_dec_ref(trans, root, eb, 0);
8807                 BUG_ON(ret); /* -ENOMEM */
8808                 ret = btrfs_set_disk_extent_flags(trans, fs_info, eb->start,
8809                                                   eb->len, flag,
8810                                                   btrfs_header_level(eb), 0);
8811                 BUG_ON(ret); /* -ENOMEM */
8812                 wc->flags[level] |= flag;
8813         }
8814
8815         /*
8816          * the block is shared by multiple trees, so it's not good to
8817          * keep the tree lock
8818          */
8819         if (path->locks[level] && level > 0) {
8820                 btrfs_tree_unlock_rw(eb, path->locks[level]);
8821                 path->locks[level] = 0;
8822         }
8823         return 0;
8824 }
8825
8826 /*
8827  * This is used to verify a ref exists for this root to deal with a bug where we
8828  * would have a drop_progress key that hadn't been updated properly.
8829  */
8830 static int check_ref_exists(struct btrfs_trans_handle *trans,
8831                             struct btrfs_root *root, u64 bytenr, u64 parent,
8832                             int level)
8833 {
8834         struct btrfs_path *path;
8835         struct btrfs_extent_inline_ref *iref;
8836         int ret;
8837
8838         path = btrfs_alloc_path();
8839         if (!path)
8840                 return -ENOMEM;
8841
8842         ret = lookup_extent_backref(trans, path, &iref, bytenr,
8843                                     root->fs_info->nodesize, parent,
8844                                     root->root_key.objectid, level, 0);
8845         btrfs_free_path(path);
8846         if (ret == -ENOENT)
8847                 return 0;
8848         if (ret < 0)
8849                 return ret;
8850         return 1;
8851 }
8852
8853 /*
8854  * helper to process tree block pointer.
8855  *
8856  * when wc->stage == DROP_REFERENCE, this function checks
8857  * reference count of the block pointed to. if the block
8858  * is shared and we need update back refs for the subtree
8859  * rooted at the block, this function changes wc->stage to
8860  * UPDATE_BACKREF. if the block is shared and there is no
8861  * need to update back, this function drops the reference
8862  * to the block.
8863  *
8864  * NOTE: return value 1 means we should stop walking down.
8865  */
8866 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
8867                                  struct btrfs_root *root,
8868                                  struct btrfs_path *path,
8869                                  struct walk_control *wc, int *lookup_info)
8870 {
8871         struct btrfs_fs_info *fs_info = root->fs_info;
8872         u64 bytenr;
8873         u64 generation;
8874         u64 parent;
8875         struct btrfs_key key;
8876         struct btrfs_key first_key;
8877         struct btrfs_ref ref = { 0 };
8878         struct extent_buffer *next;
8879         int level = wc->level;
8880         int reada = 0;
8881         int ret = 0;
8882         bool need_account = false;
8883
8884         generation = btrfs_node_ptr_generation(path->nodes[level],
8885                                                path->slots[level]);
8886         /*
8887          * if the lower level block was created before the snapshot
8888          * was created, we know there is no need to update back refs
8889          * for the subtree
8890          */
8891         if (wc->stage == UPDATE_BACKREF &&
8892             generation <= root->root_key.offset) {
8893                 *lookup_info = 1;
8894                 return 1;
8895         }
8896
8897         bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
8898         btrfs_node_key_to_cpu(path->nodes[level], &first_key,
8899                               path->slots[level]);
8900
8901         next = find_extent_buffer(fs_info, bytenr);
8902         if (!next) {
8903                 next = btrfs_find_create_tree_block(fs_info, bytenr);
8904                 if (IS_ERR(next))
8905                         return PTR_ERR(next);
8906
8907                 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
8908                                                level - 1);
8909                 reada = 1;
8910         }
8911         btrfs_tree_lock(next);
8912         btrfs_set_lock_blocking_write(next);
8913
8914         ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
8915                                        &wc->refs[level - 1],
8916                                        &wc->flags[level - 1]);
8917         if (ret < 0)
8918                 goto out_unlock;
8919
8920         if (unlikely(wc->refs[level - 1] == 0)) {
8921                 btrfs_err(fs_info, "Missing references.");
8922                 ret = -EIO;
8923                 goto out_unlock;
8924         }
8925         *lookup_info = 0;
8926
8927         if (wc->stage == DROP_REFERENCE) {
8928                 if (wc->refs[level - 1] > 1) {
8929                         need_account = true;
8930                         if (level == 1 &&
8931                             (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8932                                 goto skip;
8933
8934                         if (!wc->update_ref ||
8935                             generation <= root->root_key.offset)
8936                                 goto skip;
8937
8938                         btrfs_node_key_to_cpu(path->nodes[level], &key,
8939                                               path->slots[level]);
8940                         ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
8941                         if (ret < 0)
8942                                 goto skip;
8943
8944                         wc->stage = UPDATE_BACKREF;
8945                         wc->shared_level = level - 1;
8946                 }
8947         } else {
8948                 if (level == 1 &&
8949                     (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8950                         goto skip;
8951         }
8952
8953         if (!btrfs_buffer_uptodate(next, generation, 0)) {
8954                 btrfs_tree_unlock(next);
8955                 free_extent_buffer(next);
8956                 next = NULL;
8957                 *lookup_info = 1;
8958         }
8959
8960         if (!next) {
8961                 if (reada && level == 1)
8962                         reada_walk_down(trans, root, wc, path);
8963                 next = read_tree_block(fs_info, bytenr, generation, level - 1,
8964                                        &first_key);
8965                 if (IS_ERR(next)) {
8966                         return PTR_ERR(next);
8967                 } else if (!extent_buffer_uptodate(next)) {
8968                         free_extent_buffer(next);
8969                         return -EIO;
8970                 }
8971                 btrfs_tree_lock(next);
8972                 btrfs_set_lock_blocking_write(next);
8973         }
8974
8975         level--;
8976         ASSERT(level == btrfs_header_level(next));
8977         if (level != btrfs_header_level(next)) {
8978                 btrfs_err(root->fs_info, "mismatched level");
8979                 ret = -EIO;
8980                 goto out_unlock;
8981         }
8982         path->nodes[level] = next;
8983         path->slots[level] = 0;
8984         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8985         wc->level = level;
8986         if (wc->level == 1)
8987                 wc->reada_slot = 0;
8988         return 0;
8989 skip:
8990         wc->refs[level - 1] = 0;
8991         wc->flags[level - 1] = 0;
8992         if (wc->stage == DROP_REFERENCE) {
8993                 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
8994                         parent = path->nodes[level]->start;
8995                 } else {
8996                         ASSERT(root->root_key.objectid ==
8997                                btrfs_header_owner(path->nodes[level]));
8998                         if (root->root_key.objectid !=
8999                             btrfs_header_owner(path->nodes[level])) {
9000                                 btrfs_err(root->fs_info,
9001                                                 "mismatched block owner");
9002                                 ret = -EIO;
9003                                 goto out_unlock;
9004                         }
9005                         parent = 0;
9006                 }
9007
9008                 /*
9009                  * If we had a drop_progress we need to verify the refs are set
9010                  * as expected.  If we find our ref then we know that from here
9011                  * on out everything should be correct, and we can clear the
9012                  * ->restarted flag.
9013                  */
9014                 if (wc->restarted) {
9015                         ret = check_ref_exists(trans, root, bytenr, parent,
9016                                                level - 1);
9017                         if (ret < 0)
9018                                 goto out_unlock;
9019                         if (ret == 0)
9020                                 goto no_delete;
9021                         ret = 0;
9022                         wc->restarted = 0;
9023                 }
9024
9025                 /*
9026                  * Reloc tree doesn't contribute to qgroup numbers, and we have
9027                  * already accounted them at merge time (replace_path),
9028                  * thus we could skip expensive subtree trace here.
9029                  */
9030                 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
9031                     need_account) {
9032                         ret = btrfs_qgroup_trace_subtree(trans, next,
9033                                                          generation, level - 1);
9034                         if (ret) {
9035                                 btrfs_err_rl(fs_info,
9036                                              "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
9037                                              ret);
9038                         }
9039                 }
9040
9041                 /*
9042                  * We need to update the next key in our walk control so we can
9043                  * update the drop_progress key accordingly.  We don't care if
9044                  * find_next_key doesn't find a key because that means we're at
9045                  * the end and are going to clean up now.
9046                  */
9047                 wc->drop_level = level;
9048                 find_next_key(path, level, &wc->drop_progress);
9049
9050                 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
9051                                        fs_info->nodesize, parent);
9052                 btrfs_init_tree_ref(&ref, level - 1, root->root_key.objectid);
9053                 ret = btrfs_free_extent(trans, &ref);
9054                 if (ret)
9055                         goto out_unlock;
9056         }
9057 no_delete:
9058         *lookup_info = 1;
9059         ret = 1;
9060
9061 out_unlock:
9062         btrfs_tree_unlock(next);
9063         free_extent_buffer(next);
9064
9065         return ret;
9066 }
9067
9068 /*
9069  * helper to process tree block while walking up the tree.
9070  *
9071  * when wc->stage == DROP_REFERENCE, this function drops
9072  * reference count on the block.
9073  *
9074  * when wc->stage == UPDATE_BACKREF, this function changes
9075  * wc->stage back to DROP_REFERENCE if we changed wc->stage
9076  * to UPDATE_BACKREF previously while processing the block.
9077  *
9078  * NOTE: return value 1 means we should stop walking up.
9079  */
9080 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
9081                                  struct btrfs_root *root,
9082                                  struct btrfs_path *path,
9083                                  struct walk_control *wc)
9084 {
9085         struct btrfs_fs_info *fs_info = root->fs_info;
9086         int ret;
9087         int level = wc->level;
9088         struct extent_buffer *eb = path->nodes[level];
9089         u64 parent = 0;
9090
9091         if (wc->stage == UPDATE_BACKREF) {
9092                 BUG_ON(wc->shared_level < level);
9093                 if (level < wc->shared_level)
9094                         goto out;
9095
9096                 ret = find_next_key(path, level + 1, &wc->update_progress);
9097                 if (ret > 0)
9098                         wc->update_ref = 0;
9099
9100                 wc->stage = DROP_REFERENCE;
9101                 wc->shared_level = -1;
9102                 path->slots[level] = 0;
9103
9104                 /*
9105                  * check reference count again if the block isn't locked.
9106                  * we should start walking down the tree again if reference
9107                  * count is one.
9108                  */
9109                 if (!path->locks[level]) {
9110                         BUG_ON(level == 0);
9111                         btrfs_tree_lock(eb);
9112                         btrfs_set_lock_blocking_write(eb);
9113                         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9114
9115                         ret = btrfs_lookup_extent_info(trans, fs_info,
9116                                                        eb->start, level, 1,
9117                                                        &wc->refs[level],
9118                                                        &wc->flags[level]);
9119                         if (ret < 0) {
9120                                 btrfs_tree_unlock_rw(eb, path->locks[level]);
9121                                 path->locks[level] = 0;
9122                                 return ret;
9123                         }
9124                         BUG_ON(wc->refs[level] == 0);
9125                         if (wc->refs[level] == 1) {
9126                                 btrfs_tree_unlock_rw(eb, path->locks[level]);
9127                                 path->locks[level] = 0;
9128                                 return 1;
9129                         }
9130                 }
9131         }
9132
9133         /* wc->stage == DROP_REFERENCE */
9134         BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
9135
9136         if (wc->refs[level] == 1) {
9137                 if (level == 0) {
9138                         if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
9139                                 ret = btrfs_dec_ref(trans, root, eb, 1);
9140                         else
9141                                 ret = btrfs_dec_ref(trans, root, eb, 0);
9142                         BUG_ON(ret); /* -ENOMEM */
9143                         if (is_fstree(root->root_key.objectid)) {
9144                                 ret = btrfs_qgroup_trace_leaf_items(trans, eb);
9145                                 if (ret) {
9146                                         btrfs_err_rl(fs_info,
9147         "error %d accounting leaf items, quota is out of sync, rescan required",
9148                                              ret);
9149                                 }
9150                         }
9151                 }
9152                 /* make block locked assertion in btrfs_clean_tree_block happy */
9153                 if (!path->locks[level] &&
9154                     btrfs_header_generation(eb) == trans->transid) {
9155                         btrfs_tree_lock(eb);
9156                         btrfs_set_lock_blocking_write(eb);
9157                         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9158                 }
9159                 btrfs_clean_tree_block(eb);
9160         }
9161
9162         if (eb == root->node) {
9163                 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
9164                         parent = eb->start;
9165                 else if (root->root_key.objectid != btrfs_header_owner(eb))
9166                         goto owner_mismatch;
9167         } else {
9168                 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
9169                         parent = path->nodes[level + 1]->start;
9170                 else if (root->root_key.objectid !=
9171                          btrfs_header_owner(path->nodes[level + 1]))
9172                         goto owner_mismatch;
9173         }
9174
9175         btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
9176 out:
9177         wc->refs[level] = 0;
9178         wc->flags[level] = 0;
9179         return 0;
9180
9181 owner_mismatch:
9182         btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
9183                      btrfs_header_owner(eb), root->root_key.objectid);
9184         return -EUCLEAN;
9185 }
9186
9187 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
9188                                    struct btrfs_root *root,
9189                                    struct btrfs_path *path,
9190                                    struct walk_control *wc)
9191 {
9192         int level = wc->level;
9193         int lookup_info = 1;
9194         int ret;
9195
9196         while (level >= 0) {
9197                 ret = walk_down_proc(trans, root, path, wc, lookup_info);
9198                 if (ret > 0)
9199                         break;
9200
9201                 if (level == 0)
9202                         break;
9203
9204                 if (path->slots[level] >=
9205                     btrfs_header_nritems(path->nodes[level]))
9206                         break;
9207
9208                 ret = do_walk_down(trans, root, path, wc, &lookup_info);
9209                 if (ret > 0) {
9210                         path->slots[level]++;
9211                         continue;
9212                 } else if (ret < 0)
9213                         return ret;
9214                 level = wc->level;
9215         }
9216         return 0;
9217 }
9218
9219 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
9220                                  struct btrfs_root *root,
9221                                  struct btrfs_path *path,
9222                                  struct walk_control *wc, int max_level)
9223 {
9224         int level = wc->level;
9225         int ret;
9226
9227         path->slots[level] = btrfs_header_nritems(path->nodes[level]);
9228         while (level < max_level && path->nodes[level]) {
9229                 wc->level = level;
9230                 if (path->slots[level] + 1 <
9231                     btrfs_header_nritems(path->nodes[level])) {
9232                         path->slots[level]++;
9233                         return 0;
9234                 } else {
9235                         ret = walk_up_proc(trans, root, path, wc);
9236                         if (ret > 0)
9237                                 return 0;
9238                         if (ret < 0)
9239                                 return ret;
9240
9241                         if (path->locks[level]) {
9242                                 btrfs_tree_unlock_rw(path->nodes[level],
9243                                                      path->locks[level]);
9244                                 path->locks[level] = 0;
9245                         }
9246                         free_extent_buffer(path->nodes[level]);
9247                         path->nodes[level] = NULL;
9248                         level++;
9249                 }
9250         }
9251         return 1;
9252 }
9253
9254 /*
9255  * drop a subvolume tree.
9256  *
9257  * this function traverses the tree freeing any blocks that only
9258  * referenced by the tree.
9259  *
9260  * when a shared tree block is found. this function decreases its
9261  * reference count by one. if update_ref is true, this function
9262  * also make sure backrefs for the shared block and all lower level
9263  * blocks are properly updated.
9264  *
9265  * If called with for_reloc == 0, may exit early with -EAGAIN
9266  */
9267 int btrfs_drop_snapshot(struct btrfs_root *root,
9268                          struct btrfs_block_rsv *block_rsv, int update_ref,
9269                          int for_reloc)
9270 {
9271         struct btrfs_fs_info *fs_info = root->fs_info;
9272         struct btrfs_path *path;
9273         struct btrfs_trans_handle *trans;
9274         struct btrfs_root *tree_root = fs_info->tree_root;
9275         struct btrfs_root_item *root_item = &root->root_item;
9276         struct walk_control *wc;
9277         struct btrfs_key key;
9278         int err = 0;
9279         int ret;
9280         int level;
9281         bool root_dropped = false;
9282
9283         btrfs_debug(fs_info, "Drop subvolume %llu", root->root_key.objectid);
9284
9285         path = btrfs_alloc_path();
9286         if (!path) {
9287                 err = -ENOMEM;
9288                 goto out;
9289         }
9290
9291         wc = kzalloc(sizeof(*wc), GFP_NOFS);
9292         if (!wc) {
9293                 btrfs_free_path(path);
9294                 err = -ENOMEM;
9295                 goto out;
9296         }
9297
9298         trans = btrfs_start_transaction(tree_root, 0);
9299         if (IS_ERR(trans)) {
9300                 err = PTR_ERR(trans);
9301                 goto out_free;
9302         }
9303
9304         err = btrfs_run_delayed_items(trans);
9305         if (err)
9306                 goto out_end_trans;
9307
9308         if (block_rsv)
9309                 trans->block_rsv = block_rsv;
9310
9311         /*
9312          * This will help us catch people modifying the fs tree while we're
9313          * dropping it.  It is unsafe to mess with the fs tree while it's being
9314          * dropped as we unlock the root node and parent nodes as we walk down
9315          * the tree, assuming nothing will change.  If something does change
9316          * then we'll have stale information and drop references to blocks we've
9317          * already dropped.
9318          */
9319         set_bit(BTRFS_ROOT_DELETING, &root->state);
9320         if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
9321                 level = btrfs_header_level(root->node);
9322                 path->nodes[level] = btrfs_lock_root_node(root);
9323                 btrfs_set_lock_blocking_write(path->nodes[level]);
9324                 path->slots[level] = 0;
9325                 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9326                 memset(&wc->update_progress, 0,
9327                        sizeof(wc->update_progress));
9328         } else {
9329                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
9330                 memcpy(&wc->update_progress, &key,
9331                        sizeof(wc->update_progress));
9332
9333                 level = root_item->drop_level;
9334                 BUG_ON(level == 0);
9335                 path->lowest_level = level;
9336                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
9337                 path->lowest_level = 0;
9338                 if (ret < 0) {
9339                         err = ret;
9340                         goto out_end_trans;
9341                 }
9342                 WARN_ON(ret > 0);
9343
9344                 /*
9345                  * unlock our path, this is safe because only this
9346                  * function is allowed to delete this snapshot
9347                  */
9348                 btrfs_unlock_up_safe(path, 0);
9349
9350                 level = btrfs_header_level(root->node);
9351                 while (1) {
9352                         btrfs_tree_lock(path->nodes[level]);
9353                         btrfs_set_lock_blocking_write(path->nodes[level]);
9354                         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9355
9356                         ret = btrfs_lookup_extent_info(trans, fs_info,
9357                                                 path->nodes[level]->start,
9358                                                 level, 1, &wc->refs[level],
9359                                                 &wc->flags[level]);
9360                         if (ret < 0) {
9361                                 err = ret;
9362                                 goto out_end_trans;
9363                         }
9364                         BUG_ON(wc->refs[level] == 0);
9365
9366                         if (level == root_item->drop_level)
9367                                 break;
9368
9369                         btrfs_tree_unlock(path->nodes[level]);
9370                         path->locks[level] = 0;
9371                         WARN_ON(wc->refs[level] != 1);
9372                         level--;
9373                 }
9374         }
9375
9376         wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
9377         wc->level = level;
9378         wc->shared_level = -1;
9379         wc->stage = DROP_REFERENCE;
9380         wc->update_ref = update_ref;
9381         wc->keep_locks = 0;
9382         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
9383
9384         while (1) {
9385
9386                 ret = walk_down_tree(trans, root, path, wc);
9387                 if (ret < 0) {
9388                         err = ret;
9389                         break;
9390                 }
9391
9392                 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
9393                 if (ret < 0) {
9394                         err = ret;
9395                         break;
9396                 }
9397
9398                 if (ret > 0) {
9399                         BUG_ON(wc->stage != DROP_REFERENCE);
9400                         break;
9401                 }
9402
9403                 if (wc->stage == DROP_REFERENCE) {
9404                         wc->drop_level = wc->level;
9405                         btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
9406                                               &wc->drop_progress,
9407                                               path->slots[wc->drop_level]);
9408                 }
9409                 btrfs_cpu_key_to_disk(&root_item->drop_progress,
9410                                       &wc->drop_progress);
9411                 root_item->drop_level = wc->drop_level;
9412
9413                 BUG_ON(wc->level == 0);
9414                 if (btrfs_should_end_transaction(trans) ||
9415                     (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
9416                         ret = btrfs_update_root(trans, tree_root,
9417                                                 &root->root_key,
9418                                                 root_item);
9419                         if (ret) {
9420                                 btrfs_abort_transaction(trans, ret);
9421                                 err = ret;
9422                                 goto out_end_trans;
9423                         }
9424
9425                         btrfs_end_transaction_throttle(trans);
9426                         if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
9427                                 btrfs_debug(fs_info,
9428                                             "drop snapshot early exit");
9429                                 err = -EAGAIN;
9430                                 goto out_free;
9431                         }
9432
9433                         trans = btrfs_start_transaction(tree_root, 0);
9434                         if (IS_ERR(trans)) {
9435                                 err = PTR_ERR(trans);
9436                                 goto out_free;
9437                         }
9438                         if (block_rsv)
9439                                 trans->block_rsv = block_rsv;
9440                 }
9441         }
9442         btrfs_release_path(path);
9443         if (err)
9444                 goto out_end_trans;
9445
9446         ret = btrfs_del_root(trans, &root->root_key);
9447         if (ret) {
9448                 btrfs_abort_transaction(trans, ret);
9449                 err = ret;
9450                 goto out_end_trans;
9451         }
9452
9453         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
9454                 ret = btrfs_find_root(tree_root, &root->root_key, path,
9455                                       NULL, NULL);
9456                 if (ret < 0) {
9457                         btrfs_abort_transaction(trans, ret);
9458                         err = ret;
9459                         goto out_end_trans;
9460                 } else if (ret > 0) {
9461                         /* if we fail to delete the orphan item this time
9462                          * around, it'll get picked up the next time.
9463                          *
9464                          * The most common failure here is just -ENOENT.
9465                          */
9466                         btrfs_del_orphan_item(trans, tree_root,
9467                                               root->root_key.objectid);
9468                 }
9469         }
9470
9471         if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
9472                 btrfs_add_dropped_root(trans, root);
9473         } else {
9474                 free_extent_buffer(root->node);
9475                 free_extent_buffer(root->commit_root);
9476                 btrfs_put_fs_root(root);
9477         }
9478         root_dropped = true;
9479 out_end_trans:
9480         btrfs_end_transaction_throttle(trans);
9481 out_free:
9482         kfree(wc);
9483         btrfs_free_path(path);
9484 out:
9485         /*
9486          * So if we need to stop dropping the snapshot for whatever reason we
9487          * need to make sure to add it back to the dead root list so that we
9488          * keep trying to do the work later.  This also cleans up roots if we
9489          * don't have it in the radix (like when we recover after a power fail
9490          * or unmount) so we don't leak memory.
9491          */
9492         if (!for_reloc && !root_dropped)
9493                 btrfs_add_dead_root(root);
9494         if (err && err != -EAGAIN)
9495                 btrfs_handle_fs_error(fs_info, err, NULL);
9496         return err;
9497 }
9498
9499 /*
9500  * drop subtree rooted at tree block 'node'.
9501  *
9502  * NOTE: this function will unlock and release tree block 'node'
9503  * only used by relocation code
9504  */
9505 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
9506                         struct btrfs_root *root,
9507                         struct extent_buffer *node,
9508                         struct extent_buffer *parent)
9509 {
9510         struct btrfs_fs_info *fs_info = root->fs_info;
9511         struct btrfs_path *path;
9512         struct walk_control *wc;
9513         int level;
9514         int parent_level;
9515         int ret = 0;
9516         int wret;
9517
9518         BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
9519
9520         path = btrfs_alloc_path();
9521         if (!path)
9522                 return -ENOMEM;
9523
9524         wc = kzalloc(sizeof(*wc), GFP_NOFS);
9525         if (!wc) {
9526                 btrfs_free_path(path);
9527                 return -ENOMEM;
9528         }
9529
9530         btrfs_assert_tree_locked(parent);
9531         parent_level = btrfs_header_level(parent);
9532         extent_buffer_get(parent);
9533         path->nodes[parent_level] = parent;
9534         path->slots[parent_level] = btrfs_header_nritems(parent);
9535
9536         btrfs_assert_tree_locked(node);
9537         level = btrfs_header_level(node);
9538         path->nodes[level] = node;
9539         path->slots[level] = 0;
9540         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9541
9542         wc->refs[parent_level] = 1;
9543         wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
9544         wc->level = level;
9545         wc->shared_level = -1;
9546         wc->stage = DROP_REFERENCE;
9547         wc->update_ref = 0;
9548         wc->keep_locks = 1;
9549         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
9550
9551         while (1) {
9552                 wret = walk_down_tree(trans, root, path, wc);
9553                 if (wret < 0) {
9554                         ret = wret;
9555                         break;
9556                 }
9557
9558                 wret = walk_up_tree(trans, root, path, wc, parent_level);
9559                 if (wret < 0)
9560                         ret = wret;
9561                 if (wret != 0)
9562                         break;
9563         }
9564
9565         kfree(wc);
9566         btrfs_free_path(path);
9567         return ret;
9568 }
9569
9570 static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
9571 {
9572         u64 num_devices;
9573         u64 stripped;
9574
9575         /*
9576          * if restripe for this chunk_type is on pick target profile and
9577          * return, otherwise do the usual balance
9578          */
9579         stripped = get_restripe_target(fs_info, flags);
9580         if (stripped)
9581                 return extended_to_chunk(stripped);
9582
9583         num_devices = fs_info->fs_devices->rw_devices;
9584
9585         stripped = BTRFS_BLOCK_GROUP_RAID0 |
9586                 BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
9587                 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
9588
9589         if (num_devices == 1) {
9590                 stripped |= BTRFS_BLOCK_GROUP_DUP;
9591                 stripped = flags & ~stripped;
9592
9593                 /* turn raid0 into single device chunks */
9594                 if (flags & BTRFS_BLOCK_GROUP_RAID0)
9595                         return stripped;
9596
9597                 /* turn mirroring into duplication */
9598                 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
9599                              BTRFS_BLOCK_GROUP_RAID10))
9600                         return stripped | BTRFS_BLOCK_GROUP_DUP;
9601         } else {
9602                 /* they already had raid on here, just return */
9603                 if (flags & stripped)
9604                         return flags;
9605
9606                 stripped |= BTRFS_BLOCK_GROUP_DUP;
9607                 stripped = flags & ~stripped;
9608
9609                 /* switch duplicated blocks with raid1 */
9610                 if (flags & BTRFS_BLOCK_GROUP_DUP)
9611                         return stripped | BTRFS_BLOCK_GROUP_RAID1;
9612
9613                 /* this is drive concat, leave it alone */
9614         }
9615
9616         return flags;
9617 }
9618
9619 static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
9620 {
9621         struct btrfs_space_info *sinfo = cache->space_info;
9622         u64 num_bytes;
9623         u64 sinfo_used;
9624         u64 min_allocable_bytes;
9625         int ret = -ENOSPC;
9626
9627         /*
9628          * We need some metadata space and system metadata space for
9629          * allocating chunks in some corner cases until we force to set
9630          * it to be readonly.
9631          */
9632         if ((sinfo->flags &
9633              (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
9634             !force)
9635                 min_allocable_bytes = SZ_1M;
9636         else
9637                 min_allocable_bytes = 0;
9638
9639         spin_lock(&sinfo->lock);
9640         spin_lock(&cache->lock);
9641
9642         if (cache->ro) {
9643                 cache->ro++;
9644                 ret = 0;
9645                 goto out;
9646         }
9647
9648         num_bytes = cache->key.offset - cache->reserved - cache->pinned -
9649                     cache->bytes_super - btrfs_block_group_used(&cache->item);
9650         sinfo_used = btrfs_space_info_used(sinfo, true);
9651
9652         if (sinfo_used + num_bytes + min_allocable_bytes <=
9653             sinfo->total_bytes) {
9654                 sinfo->bytes_readonly += num_bytes;
9655                 cache->ro++;
9656                 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
9657                 ret = 0;
9658         }
9659 out:
9660         spin_unlock(&cache->lock);
9661         spin_unlock(&sinfo->lock);
9662         if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
9663                 btrfs_info(cache->fs_info,
9664                         "unable to make block group %llu ro",
9665                         cache->key.objectid);
9666                 btrfs_info(cache->fs_info,
9667                         "sinfo_used=%llu bg_num_bytes=%llu min_allocable=%llu",
9668                         sinfo_used, num_bytes, min_allocable_bytes);
9669                 dump_space_info(cache->fs_info, cache->space_info, 0, 0);
9670         }
9671         return ret;
9672 }
9673
9674 int btrfs_inc_block_group_ro(struct btrfs_block_group_cache *cache)
9675
9676 {
9677         struct btrfs_fs_info *fs_info = cache->fs_info;
9678         struct btrfs_trans_handle *trans;
9679         u64 alloc_flags;
9680         int ret;
9681
9682 again:
9683         trans = btrfs_join_transaction(fs_info->extent_root);
9684         if (IS_ERR(trans))
9685                 return PTR_ERR(trans);
9686
9687         /*
9688          * we're not allowed to set block groups readonly after the dirty
9689          * block groups cache has started writing.  If it already started,
9690          * back off and let this transaction commit
9691          */
9692         mutex_lock(&fs_info->ro_block_group_mutex);
9693         if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
9694                 u64 transid = trans->transid;
9695
9696                 mutex_unlock(&fs_info->ro_block_group_mutex);
9697                 btrfs_end_transaction(trans);
9698
9699                 ret = btrfs_wait_for_commit(fs_info, transid);
9700                 if (ret)
9701                         return ret;
9702                 goto again;
9703         }
9704
9705         /*
9706          * if we are changing raid levels, try to allocate a corresponding
9707          * block group with the new raid level.
9708          */
9709         alloc_flags = update_block_group_flags(fs_info, cache->flags);
9710         if (alloc_flags != cache->flags) {
9711                 ret = do_chunk_alloc(trans, alloc_flags,
9712                                      CHUNK_ALLOC_FORCE);
9713                 /*
9714                  * ENOSPC is allowed here, we may have enough space
9715                  * already allocated at the new raid level to
9716                  * carry on
9717                  */
9718                 if (ret == -ENOSPC)
9719                         ret = 0;
9720                 if (ret < 0)
9721                         goto out;
9722         }
9723
9724         ret = inc_block_group_ro(cache, 0);
9725         if (!ret)
9726                 goto out;
9727         alloc_flags = get_alloc_profile(fs_info, cache->space_info->flags);
9728         ret = do_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
9729         if (ret < 0)
9730                 goto out;
9731         ret = inc_block_group_ro(cache, 0);
9732 out:
9733         if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
9734                 alloc_flags = update_block_group_flags(fs_info, cache->flags);
9735                 mutex_lock(&fs_info->chunk_mutex);
9736                 check_system_chunk(trans, alloc_flags);
9737                 mutex_unlock(&fs_info->chunk_mutex);
9738         }
9739         mutex_unlock(&fs_info->ro_block_group_mutex);
9740
9741         btrfs_end_transaction(trans);
9742         return ret;
9743 }
9744
9745 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
9746 {
9747         u64 alloc_flags = get_alloc_profile(trans->fs_info, type);
9748
9749         return do_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
9750 }
9751
9752 /*
9753  * helper to account the unused space of all the readonly block group in the
9754  * space_info. takes mirrors into account.
9755  */
9756 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
9757 {
9758         struct btrfs_block_group_cache *block_group;
9759         u64 free_bytes = 0;
9760         int factor;
9761
9762         /* It's df, we don't care if it's racy */
9763         if (list_empty(&sinfo->ro_bgs))
9764                 return 0;
9765
9766         spin_lock(&sinfo->lock);
9767         list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
9768                 spin_lock(&block_group->lock);
9769
9770                 if (!block_group->ro) {
9771                         spin_unlock(&block_group->lock);
9772                         continue;
9773                 }
9774
9775                 factor = btrfs_bg_type_to_factor(block_group->flags);
9776                 free_bytes += (block_group->key.offset -
9777                                btrfs_block_group_used(&block_group->item)) *
9778                                factor;
9779
9780                 spin_unlock(&block_group->lock);
9781         }
9782         spin_unlock(&sinfo->lock);
9783
9784         return free_bytes;
9785 }
9786
9787 void btrfs_dec_block_group_ro(struct btrfs_block_group_cache *cache)
9788 {
9789         struct btrfs_space_info *sinfo = cache->space_info;
9790         u64 num_bytes;
9791
9792         BUG_ON(!cache->ro);
9793
9794         spin_lock(&sinfo->lock);
9795         spin_lock(&cache->lock);
9796         if (!--cache->ro) {
9797                 num_bytes = cache->key.offset - cache->reserved -
9798                             cache->pinned - cache->bytes_super -
9799                             btrfs_block_group_used(&cache->item);
9800                 sinfo->bytes_readonly -= num_bytes;
9801                 list_del_init(&cache->ro_list);
9802         }
9803         spin_unlock(&cache->lock);
9804         spin_unlock(&sinfo->lock);
9805 }
9806
9807 /*
9808  * Checks to see if it's even possible to relocate this block group.
9809  *
9810  * @return - -1 if it's not a good idea to relocate this block group, 0 if its
9811  * ok to go ahead and try.
9812  */
9813 int btrfs_can_relocate(struct btrfs_fs_info *fs_info, u64 bytenr)
9814 {
9815         struct btrfs_block_group_cache *block_group;
9816         struct btrfs_space_info *space_info;
9817         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
9818         struct btrfs_device *device;
9819         u64 min_free;
9820         u64 dev_min = 1;
9821         u64 dev_nr = 0;
9822         u64 target;
9823         int debug;
9824         int index;
9825         int full = 0;
9826         int ret = 0;
9827
9828         debug = btrfs_test_opt(fs_info, ENOSPC_DEBUG);
9829
9830         block_group = btrfs_lookup_block_group(fs_info, bytenr);
9831
9832         /* odd, couldn't find the block group, leave it alone */
9833         if (!block_group) {
9834                 if (debug)
9835                         btrfs_warn(fs_info,
9836                                    "can't find block group for bytenr %llu",
9837                                    bytenr);
9838                 return -1;
9839         }
9840
9841         min_free = btrfs_block_group_used(&block_group->item);
9842
9843         /* no bytes used, we're good */
9844         if (!min_free)
9845                 goto out;
9846
9847         space_info = block_group->space_info;
9848         spin_lock(&space_info->lock);
9849
9850         full = space_info->full;
9851
9852         /*
9853          * if this is the last block group we have in this space, we can't
9854          * relocate it unless we're able to allocate a new chunk below.
9855          *
9856          * Otherwise, we need to make sure we have room in the space to handle
9857          * all of the extents from this block group.  If we can, we're good
9858          */
9859         if ((space_info->total_bytes != block_group->key.offset) &&
9860             (btrfs_space_info_used(space_info, false) + min_free <
9861              space_info->total_bytes)) {
9862                 spin_unlock(&space_info->lock);
9863                 goto out;
9864         }
9865         spin_unlock(&space_info->lock);
9866
9867         /*
9868          * ok we don't have enough space, but maybe we have free space on our
9869          * devices to allocate new chunks for relocation, so loop through our
9870          * alloc devices and guess if we have enough space.  if this block
9871          * group is going to be restriped, run checks against the target
9872          * profile instead of the current one.
9873          */
9874         ret = -1;
9875
9876         /*
9877          * index:
9878          *      0: raid10
9879          *      1: raid1
9880          *      2: dup
9881          *      3: raid0
9882          *      4: single
9883          */
9884         target = get_restripe_target(fs_info, block_group->flags);
9885         if (target) {
9886                 index = btrfs_bg_flags_to_raid_index(extended_to_chunk(target));
9887         } else {
9888                 /*
9889                  * this is just a balance, so if we were marked as full
9890                  * we know there is no space for a new chunk
9891                  */
9892                 if (full) {
9893                         if (debug)
9894                                 btrfs_warn(fs_info,
9895                                            "no space to alloc new chunk for block group %llu",
9896                                            block_group->key.objectid);
9897                         goto out;
9898                 }
9899
9900                 index = btrfs_bg_flags_to_raid_index(block_group->flags);
9901         }
9902
9903         if (index == BTRFS_RAID_RAID10) {
9904                 dev_min = 4;
9905                 /* Divide by 2 */
9906                 min_free >>= 1;
9907         } else if (index == BTRFS_RAID_RAID1) {
9908                 dev_min = 2;
9909         } else if (index == BTRFS_RAID_DUP) {
9910                 /* Multiply by 2 */
9911                 min_free <<= 1;
9912         } else if (index == BTRFS_RAID_RAID0) {
9913                 dev_min = fs_devices->rw_devices;
9914                 min_free = div64_u64(min_free, dev_min);
9915         }
9916
9917         mutex_lock(&fs_info->chunk_mutex);
9918         list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
9919                 u64 dev_offset;
9920
9921                 /*
9922                  * check to make sure we can actually find a chunk with enough
9923                  * space to fit our block group in.
9924                  */
9925                 if (device->total_bytes > device->bytes_used + min_free &&
9926                     !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
9927                         ret = find_free_dev_extent(device, min_free,
9928                                                    &dev_offset, NULL);
9929                         if (!ret)
9930                                 dev_nr++;
9931
9932                         if (dev_nr >= dev_min)
9933                                 break;
9934
9935                         ret = -1;
9936                 }
9937         }
9938         if (debug && ret == -1)
9939                 btrfs_warn(fs_info,
9940                            "no space to allocate a new chunk for block group %llu",
9941                            block_group->key.objectid);
9942         mutex_unlock(&fs_info->chunk_mutex);
9943 out:
9944         btrfs_put_block_group(block_group);
9945         return ret;
9946 }
9947
9948 static int find_first_block_group(struct btrfs_fs_info *fs_info,
9949                                   struct btrfs_path *path,
9950                                   struct btrfs_key *key)
9951 {
9952         struct btrfs_root *root = fs_info->extent_root;
9953         int ret = 0;
9954         struct btrfs_key found_key;
9955         struct extent_buffer *leaf;
9956         struct btrfs_block_group_item bg;
9957         u64 flags;
9958         int slot;
9959
9960         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
9961         if (ret < 0)
9962                 goto out;
9963
9964         while (1) {
9965                 slot = path->slots[0];
9966                 leaf = path->nodes[0];
9967                 if (slot >= btrfs_header_nritems(leaf)) {
9968                         ret = btrfs_next_leaf(root, path);
9969                         if (ret == 0)
9970                                 continue;
9971                         if (ret < 0)
9972                                 goto out;
9973                         break;
9974                 }
9975                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
9976
9977                 if (found_key.objectid >= key->objectid &&
9978                     found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
9979                         struct extent_map_tree *em_tree;
9980                         struct extent_map *em;
9981
9982                         em_tree = &root->fs_info->mapping_tree.map_tree;
9983                         read_lock(&em_tree->lock);
9984                         em = lookup_extent_mapping(em_tree, found_key.objectid,
9985                                                    found_key.offset);
9986                         read_unlock(&em_tree->lock);
9987                         if (!em) {
9988                                 btrfs_err(fs_info,
9989                         "logical %llu len %llu found bg but no related chunk",
9990                                           found_key.objectid, found_key.offset);
9991                                 ret = -ENOENT;
9992                         } else if (em->start != found_key.objectid ||
9993                                    em->len != found_key.offset) {
9994                                 btrfs_err(fs_info,
9995                 "block group %llu len %llu mismatch with chunk %llu len %llu",
9996                                           found_key.objectid, found_key.offset,
9997                                           em->start, em->len);
9998                                 ret = -EUCLEAN;
9999                         } else {
10000                                 read_extent_buffer(leaf, &bg,
10001                                         btrfs_item_ptr_offset(leaf, slot),
10002                                         sizeof(bg));
10003                                 flags = btrfs_block_group_flags(&bg) &
10004                                         BTRFS_BLOCK_GROUP_TYPE_MASK;
10005
10006                                 if (flags != (em->map_lookup->type &
10007                                               BTRFS_BLOCK_GROUP_TYPE_MASK)) {
10008                                         btrfs_err(fs_info,
10009 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
10010                                                 found_key.objectid,
10011                                                 found_key.offset, flags,
10012                                                 (BTRFS_BLOCK_GROUP_TYPE_MASK &
10013                                                  em->map_lookup->type));
10014                                         ret = -EUCLEAN;
10015                                 } else {
10016                                         ret = 0;
10017                                 }
10018                         }
10019                         free_extent_map(em);
10020                         goto out;
10021                 }
10022                 path->slots[0]++;
10023         }
10024 out:
10025         return ret;
10026 }
10027
10028 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
10029 {
10030         struct btrfs_block_group_cache *block_group;
10031         u64 last = 0;
10032
10033         while (1) {
10034                 struct inode *inode;
10035
10036                 block_group = btrfs_lookup_first_block_group(info, last);
10037                 while (block_group) {
10038                         wait_block_group_cache_done(block_group);
10039                         spin_lock(&block_group->lock);
10040                         if (block_group->iref)
10041                                 break;
10042                         spin_unlock(&block_group->lock);
10043                         block_group = next_block_group(block_group);
10044                 }
10045                 if (!block_group) {
10046                         if (last == 0)
10047                                 break;
10048                         last = 0;
10049                         continue;
10050                 }
10051
10052                 inode = block_group->inode;
10053                 block_group->iref = 0;
10054                 block_group->inode = NULL;
10055                 spin_unlock(&block_group->lock);
10056                 ASSERT(block_group->io_ctl.inode == NULL);
10057                 iput(inode);
10058                 last = block_group->key.objectid + block_group->key.offset;
10059                 btrfs_put_block_group(block_group);
10060         }
10061 }
10062
10063 /*
10064  * Must be called only after stopping all workers, since we could have block
10065  * group caching kthreads running, and therefore they could race with us if we
10066  * freed the block groups before stopping them.
10067  */
10068 int btrfs_free_block_groups(struct btrfs_fs_info *info)
10069 {
10070         struct btrfs_block_group_cache *block_group;
10071         struct btrfs_space_info *space_info;
10072         struct btrfs_caching_control *caching_ctl;
10073         struct rb_node *n;
10074
10075         down_write(&info->commit_root_sem);
10076         while (!list_empty(&info->caching_block_groups)) {
10077                 caching_ctl = list_entry(info->caching_block_groups.next,
10078                                          struct btrfs_caching_control, list);
10079                 list_del(&caching_ctl->list);
10080                 put_caching_control(caching_ctl);
10081         }
10082         up_write(&info->commit_root_sem);
10083
10084         spin_lock(&info->unused_bgs_lock);
10085         while (!list_empty(&info->unused_bgs)) {
10086                 block_group = list_first_entry(&info->unused_bgs,
10087                                                struct btrfs_block_group_cache,
10088                                                bg_list);
10089                 list_del_init(&block_group->bg_list);
10090                 btrfs_put_block_group(block_group);
10091         }
10092         spin_unlock(&info->unused_bgs_lock);
10093
10094         spin_lock(&info->block_group_cache_lock);
10095         while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
10096                 block_group = rb_entry(n, struct btrfs_block_group_cache,
10097                                        cache_node);
10098                 rb_erase(&block_group->cache_node,
10099                          &info->block_group_cache_tree);
10100                 RB_CLEAR_NODE(&block_group->cache_node);
10101                 spin_unlock(&info->block_group_cache_lock);
10102
10103                 down_write(&block_group->space_info->groups_sem);
10104                 list_del(&block_group->list);
10105                 up_write(&block_group->space_info->groups_sem);
10106
10107                 /*
10108                  * We haven't cached this block group, which means we could
10109                  * possibly have excluded extents on this block group.
10110                  */
10111                 if (block_group->cached == BTRFS_CACHE_NO ||
10112                     block_group->cached == BTRFS_CACHE_ERROR)
10113                         free_excluded_extents(block_group);
10114
10115                 btrfs_remove_free_space_cache(block_group);
10116                 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
10117                 ASSERT(list_empty(&block_group->dirty_list));
10118                 ASSERT(list_empty(&block_group->io_list));
10119                 ASSERT(list_empty(&block_group->bg_list));
10120                 ASSERT(atomic_read(&block_group->count) == 1);
10121                 btrfs_put_block_group(block_group);
10122
10123                 spin_lock(&info->block_group_cache_lock);
10124         }
10125         spin_unlock(&info->block_group_cache_lock);
10126
10127         /* now that all the block groups are freed, go through and
10128          * free all the space_info structs.  This is only called during
10129          * the final stages of unmount, and so we know nobody is
10130          * using them.  We call synchronize_rcu() once before we start,
10131          * just to be on the safe side.
10132          */
10133         synchronize_rcu();
10134
10135         release_global_block_rsv(info);
10136
10137         while (!list_empty(&info->space_info)) {
10138                 int i;
10139
10140                 space_info = list_entry(info->space_info.next,
10141                                         struct btrfs_space_info,
10142                                         list);
10143
10144                 /*
10145                  * Do not hide this behind enospc_debug, this is actually
10146                  * important and indicates a real bug if this happens.
10147                  */
10148                 if (WARN_ON(space_info->bytes_pinned > 0 ||
10149                             space_info->bytes_reserved > 0 ||
10150                             space_info->bytes_may_use > 0))
10151                         dump_space_info(info, space_info, 0, 0);
10152                 list_del(&space_info->list);
10153                 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
10154                         struct kobject *kobj;
10155                         kobj = space_info->block_group_kobjs[i];
10156                         space_info->block_group_kobjs[i] = NULL;
10157                         if (kobj) {
10158                                 kobject_del(kobj);
10159                                 kobject_put(kobj);
10160                         }
10161                 }
10162                 kobject_del(&space_info->kobj);
10163                 kobject_put(&space_info->kobj);
10164         }
10165         return 0;
10166 }
10167
10168 /* link_block_group will queue up kobjects to add when we're reclaim-safe */
10169 void btrfs_add_raid_kobjects(struct btrfs_fs_info *fs_info)
10170 {
10171         struct btrfs_space_info *space_info;
10172         struct raid_kobject *rkobj;
10173         LIST_HEAD(list);
10174         int index;
10175         int ret = 0;
10176
10177         spin_lock(&fs_info->pending_raid_kobjs_lock);
10178         list_splice_init(&fs_info->pending_raid_kobjs, &list);
10179         spin_unlock(&fs_info->pending_raid_kobjs_lock);
10180
10181         list_for_each_entry(rkobj, &list, list) {
10182                 space_info = __find_space_info(fs_info, rkobj->flags);
10183                 index = btrfs_bg_flags_to_raid_index(rkobj->flags);
10184
10185                 ret = kobject_add(&rkobj->kobj, &space_info->kobj,
10186                                   "%s", get_raid_name(index));
10187                 if (ret) {
10188                         kobject_put(&rkobj->kobj);
10189                         break;
10190                 }
10191         }
10192         if (ret)
10193                 btrfs_warn(fs_info,
10194                            "failed to add kobject for block cache, ignoring");
10195 }
10196
10197 static void link_block_group(struct btrfs_block_group_cache *cache)
10198 {
10199         struct btrfs_space_info *space_info = cache->space_info;
10200         struct btrfs_fs_info *fs_info = cache->fs_info;
10201         int index = btrfs_bg_flags_to_raid_index(cache->flags);
10202         bool first = false;
10203
10204         down_write(&space_info->groups_sem);
10205         if (list_empty(&space_info->block_groups[index]))
10206                 first = true;
10207         list_add_tail(&cache->list, &space_info->block_groups[index]);
10208         up_write(&space_info->groups_sem);
10209
10210         if (first) {
10211                 struct raid_kobject *rkobj = kzalloc(sizeof(*rkobj), GFP_NOFS);
10212                 if (!rkobj) {
10213                         btrfs_warn(cache->fs_info,
10214                                 "couldn't alloc memory for raid level kobject");
10215                         return;
10216                 }
10217                 rkobj->flags = cache->flags;
10218                 kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
10219
10220                 spin_lock(&fs_info->pending_raid_kobjs_lock);
10221                 list_add_tail(&rkobj->list, &fs_info->pending_raid_kobjs);
10222                 spin_unlock(&fs_info->pending_raid_kobjs_lock);
10223                 space_info->block_group_kobjs[index] = &rkobj->kobj;
10224         }
10225 }
10226
10227 static struct btrfs_block_group_cache *
10228 btrfs_create_block_group_cache(struct btrfs_fs_info *fs_info,
10229                                u64 start, u64 size)
10230 {
10231         struct btrfs_block_group_cache *cache;
10232
10233         cache = kzalloc(sizeof(*cache), GFP_NOFS);
10234         if (!cache)
10235                 return NULL;
10236
10237         cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
10238                                         GFP_NOFS);
10239         if (!cache->free_space_ctl) {
10240                 kfree(cache);
10241                 return NULL;
10242         }
10243
10244         cache->key.objectid = start;
10245         cache->key.offset = size;
10246         cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
10247
10248         cache->fs_info = fs_info;
10249         cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
10250         set_free_space_tree_thresholds(cache);
10251
10252         atomic_set(&cache->count, 1);
10253         spin_lock_init(&cache->lock);
10254         init_rwsem(&cache->data_rwsem);
10255         INIT_LIST_HEAD(&cache->list);
10256         INIT_LIST_HEAD(&cache->cluster_list);
10257         INIT_LIST_HEAD(&cache->bg_list);
10258         INIT_LIST_HEAD(&cache->ro_list);
10259         INIT_LIST_HEAD(&cache->dirty_list);
10260         INIT_LIST_HEAD(&cache->io_list);
10261         btrfs_init_free_space_ctl(cache);
10262         atomic_set(&cache->trimming, 0);
10263         mutex_init(&cache->free_space_lock);
10264         btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
10265
10266         return cache;
10267 }
10268
10269
10270 /*
10271  * Iterate all chunks and verify that each of them has the corresponding block
10272  * group
10273  */
10274 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
10275 {
10276         struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
10277         struct extent_map *em;
10278         struct btrfs_block_group_cache *bg;
10279         u64 start = 0;
10280         int ret = 0;
10281
10282         while (1) {
10283                 read_lock(&map_tree->map_tree.lock);
10284                 /*
10285                  * lookup_extent_mapping will return the first extent map
10286                  * intersecting the range, so setting @len to 1 is enough to
10287                  * get the first chunk.
10288                  */
10289                 em = lookup_extent_mapping(&map_tree->map_tree, start, 1);
10290                 read_unlock(&map_tree->map_tree.lock);
10291                 if (!em)
10292                         break;
10293
10294                 bg = btrfs_lookup_block_group(fs_info, em->start);
10295                 if (!bg) {
10296                         btrfs_err(fs_info,
10297         "chunk start=%llu len=%llu doesn't have corresponding block group",
10298                                      em->start, em->len);
10299                         ret = -EUCLEAN;
10300                         free_extent_map(em);
10301                         break;
10302                 }
10303                 if (bg->key.objectid != em->start ||
10304                     bg->key.offset != em->len ||
10305                     (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
10306                     (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
10307                         btrfs_err(fs_info,
10308 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
10309                                 em->start, em->len,
10310                                 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
10311                                 bg->key.objectid, bg->key.offset,
10312                                 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
10313                         ret = -EUCLEAN;
10314                         free_extent_map(em);
10315                         btrfs_put_block_group(bg);
10316                         break;
10317                 }
10318                 start = em->start + em->len;
10319                 free_extent_map(em);
10320                 btrfs_put_block_group(bg);
10321         }
10322         return ret;
10323 }
10324
10325 int btrfs_read_block_groups(struct btrfs_fs_info *info)
10326 {
10327         struct btrfs_path *path;
10328         int ret;
10329         struct btrfs_block_group_cache *cache;
10330         struct btrfs_space_info *space_info;
10331         struct btrfs_key key;
10332         struct btrfs_key found_key;
10333         struct extent_buffer *leaf;
10334         int need_clear = 0;
10335         u64 cache_gen;
10336         u64 feature;
10337         int mixed;
10338
10339         feature = btrfs_super_incompat_flags(info->super_copy);
10340         mixed = !!(feature & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS);
10341
10342         key.objectid = 0;
10343         key.offset = 0;
10344         key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
10345         path = btrfs_alloc_path();
10346         if (!path)
10347                 return -ENOMEM;
10348         path->reada = READA_FORWARD;
10349
10350         cache_gen = btrfs_super_cache_generation(info->super_copy);
10351         if (btrfs_test_opt(info, SPACE_CACHE) &&
10352             btrfs_super_generation(info->super_copy) != cache_gen)
10353                 need_clear = 1;
10354         if (btrfs_test_opt(info, CLEAR_CACHE))
10355                 need_clear = 1;
10356
10357         while (1) {
10358                 ret = find_first_block_group(info, path, &key);
10359                 if (ret > 0)
10360                         break;
10361                 if (ret != 0)
10362                         goto error;
10363
10364                 leaf = path->nodes[0];
10365                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
10366
10367                 cache = btrfs_create_block_group_cache(info, found_key.objectid,
10368                                                        found_key.offset);
10369                 if (!cache) {
10370                         ret = -ENOMEM;
10371                         goto error;
10372                 }
10373
10374                 if (need_clear) {
10375                         /*
10376                          * When we mount with old space cache, we need to
10377                          * set BTRFS_DC_CLEAR and set dirty flag.
10378                          *
10379                          * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
10380                          *    truncate the old free space cache inode and
10381                          *    setup a new one.
10382                          * b) Setting 'dirty flag' makes sure that we flush
10383                          *    the new space cache info onto disk.
10384                          */
10385                         if (btrfs_test_opt(info, SPACE_CACHE))
10386                                 cache->disk_cache_state = BTRFS_DC_CLEAR;
10387                 }
10388
10389                 read_extent_buffer(leaf, &cache->item,
10390                                    btrfs_item_ptr_offset(leaf, path->slots[0]),
10391                                    sizeof(cache->item));
10392                 cache->flags = btrfs_block_group_flags(&cache->item);
10393                 if (!mixed &&
10394                     ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
10395                     (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
10396                         btrfs_err(info,
10397 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
10398                                   cache->key.objectid);
10399                         ret = -EINVAL;
10400                         goto error;
10401                 }
10402
10403                 key.objectid = found_key.objectid + found_key.offset;
10404                 btrfs_release_path(path);
10405
10406                 /*
10407                  * We need to exclude the super stripes now so that the space
10408                  * info has super bytes accounted for, otherwise we'll think
10409                  * we have more space than we actually do.
10410                  */
10411                 ret = exclude_super_stripes(cache);
10412                 if (ret) {
10413                         /*
10414                          * We may have excluded something, so call this just in
10415                          * case.
10416                          */
10417                         free_excluded_extents(cache);
10418                         btrfs_put_block_group(cache);
10419                         goto error;
10420                 }
10421
10422                 /*
10423                  * check for two cases, either we are full, and therefore
10424                  * don't need to bother with the caching work since we won't
10425                  * find any space, or we are empty, and we can just add all
10426                  * the space in and be done with it.  This saves us _a_lot_ of
10427                  * time, particularly in the full case.
10428                  */
10429                 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
10430                         cache->last_byte_to_unpin = (u64)-1;
10431                         cache->cached = BTRFS_CACHE_FINISHED;
10432                         free_excluded_extents(cache);
10433                 } else if (btrfs_block_group_used(&cache->item) == 0) {
10434                         cache->last_byte_to_unpin = (u64)-1;
10435                         cache->cached = BTRFS_CACHE_FINISHED;
10436                         add_new_free_space(cache, found_key.objectid,
10437                                            found_key.objectid +
10438                                            found_key.offset);
10439                         free_excluded_extents(cache);
10440                 }
10441
10442                 ret = btrfs_add_block_group_cache(info, cache);
10443                 if (ret) {
10444                         btrfs_remove_free_space_cache(cache);
10445                         btrfs_put_block_group(cache);
10446                         goto error;
10447                 }
10448
10449                 trace_btrfs_add_block_group(info, cache, 0);
10450                 update_space_info(info, cache->flags, found_key.offset,
10451                                   btrfs_block_group_used(&cache->item),
10452                                   cache->bytes_super, &space_info);
10453
10454                 cache->space_info = space_info;
10455
10456                 link_block_group(cache);
10457
10458                 set_avail_alloc_bits(info, cache->flags);
10459                 if (btrfs_chunk_readonly(info, cache->key.objectid)) {
10460                         inc_block_group_ro(cache, 1);
10461                 } else if (btrfs_block_group_used(&cache->item) == 0) {
10462                         ASSERT(list_empty(&cache->bg_list));
10463                         btrfs_mark_bg_unused(cache);
10464                 }
10465         }
10466
10467         list_for_each_entry_rcu(space_info, &info->space_info, list) {
10468                 if (!(get_alloc_profile(info, space_info->flags) &
10469                       (BTRFS_BLOCK_GROUP_RAID10 |
10470                        BTRFS_BLOCK_GROUP_RAID1 |
10471                        BTRFS_BLOCK_GROUP_RAID5 |
10472                        BTRFS_BLOCK_GROUP_RAID6 |
10473                        BTRFS_BLOCK_GROUP_DUP)))
10474                         continue;
10475                 /*
10476                  * avoid allocating from un-mirrored block group if there are
10477                  * mirrored block groups.
10478                  */
10479                 list_for_each_entry(cache,
10480                                 &space_info->block_groups[BTRFS_RAID_RAID0],
10481                                 list)
10482                         inc_block_group_ro(cache, 1);
10483                 list_for_each_entry(cache,
10484                                 &space_info->block_groups[BTRFS_RAID_SINGLE],
10485                                 list)
10486                         inc_block_group_ro(cache, 1);
10487         }
10488
10489         btrfs_add_raid_kobjects(info);
10490         init_global_block_rsv(info);
10491         ret = check_chunk_block_group_mappings(info);
10492 error:
10493         btrfs_free_path(path);
10494         return ret;
10495 }
10496
10497 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
10498 {
10499         struct btrfs_fs_info *fs_info = trans->fs_info;
10500         struct btrfs_block_group_cache *block_group;
10501         struct btrfs_root *extent_root = fs_info->extent_root;
10502         struct btrfs_block_group_item item;
10503         struct btrfs_key key;
10504         int ret = 0;
10505
10506         if (!trans->can_flush_pending_bgs)
10507                 return;
10508
10509         while (!list_empty(&trans->new_bgs)) {
10510                 block_group = list_first_entry(&trans->new_bgs,
10511                                                struct btrfs_block_group_cache,
10512                                                bg_list);
10513                 if (ret)
10514                         goto next;
10515
10516                 spin_lock(&block_group->lock);
10517                 memcpy(&item, &block_group->item, sizeof(item));
10518                 memcpy(&key, &block_group->key, sizeof(key));
10519                 spin_unlock(&block_group->lock);
10520
10521                 ret = btrfs_insert_item(trans, extent_root, &key, &item,
10522                                         sizeof(item));
10523                 if (ret)
10524                         btrfs_abort_transaction(trans, ret);
10525                 ret = btrfs_finish_chunk_alloc(trans, key.objectid, key.offset);
10526                 if (ret)
10527                         btrfs_abort_transaction(trans, ret);
10528                 add_block_group_free_space(trans, block_group);
10529                 /* already aborted the transaction if it failed. */
10530 next:
10531                 btrfs_delayed_refs_rsv_release(fs_info, 1);
10532                 list_del_init(&block_group->bg_list);
10533         }
10534         btrfs_trans_release_chunk_metadata(trans);
10535 }
10536
10537 int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
10538                            u64 type, u64 chunk_offset, u64 size)
10539 {
10540         struct btrfs_fs_info *fs_info = trans->fs_info;
10541         struct btrfs_block_group_cache *cache;
10542         int ret;
10543
10544         btrfs_set_log_full_commit(trans);
10545
10546         cache = btrfs_create_block_group_cache(fs_info, chunk_offset, size);
10547         if (!cache)
10548                 return -ENOMEM;
10549
10550         btrfs_set_block_group_used(&cache->item, bytes_used);
10551         btrfs_set_block_group_chunk_objectid(&cache->item,
10552                                              BTRFS_FIRST_CHUNK_TREE_OBJECTID);
10553         btrfs_set_block_group_flags(&cache->item, type);
10554
10555         cache->flags = type;
10556         cache->last_byte_to_unpin = (u64)-1;
10557         cache->cached = BTRFS_CACHE_FINISHED;
10558         cache->needs_free_space = 1;
10559         ret = exclude_super_stripes(cache);
10560         if (ret) {
10561                 /*
10562                  * We may have excluded something, so call this just in
10563                  * case.
10564                  */
10565                 free_excluded_extents(cache);
10566                 btrfs_put_block_group(cache);
10567                 return ret;
10568         }
10569
10570         add_new_free_space(cache, chunk_offset, chunk_offset + size);
10571
10572         free_excluded_extents(cache);
10573
10574 #ifdef CONFIG_BTRFS_DEBUG
10575         if (btrfs_should_fragment_free_space(cache)) {
10576                 u64 new_bytes_used = size - bytes_used;
10577
10578                 bytes_used += new_bytes_used >> 1;
10579                 fragment_free_space(cache);
10580         }
10581 #endif
10582         /*
10583          * Ensure the corresponding space_info object is created and
10584          * assigned to our block group. We want our bg to be added to the rbtree
10585          * with its ->space_info set.
10586          */
10587         cache->space_info = __find_space_info(fs_info, cache->flags);
10588         ASSERT(cache->space_info);
10589
10590         ret = btrfs_add_block_group_cache(fs_info, cache);
10591         if (ret) {
10592                 btrfs_remove_free_space_cache(cache);
10593                 btrfs_put_block_group(cache);
10594                 return ret;
10595         }
10596
10597         /*
10598          * Now that our block group has its ->space_info set and is inserted in
10599          * the rbtree, update the space info's counters.
10600          */
10601         trace_btrfs_add_block_group(fs_info, cache, 1);
10602         update_space_info(fs_info, cache->flags, size, bytes_used,
10603                                 cache->bytes_super, &cache->space_info);
10604         update_global_block_rsv(fs_info);
10605
10606         link_block_group(cache);
10607
10608         list_add_tail(&cache->bg_list, &trans->new_bgs);
10609         trans->delayed_ref_updates++;
10610         btrfs_update_delayed_refs_rsv(trans);
10611
10612         set_avail_alloc_bits(fs_info, type);
10613         return 0;
10614 }
10615
10616 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
10617 {
10618         u64 extra_flags = chunk_to_extended(flags) &
10619                                 BTRFS_EXTENDED_PROFILE_MASK;
10620
10621         write_seqlock(&fs_info->profiles_lock);
10622         if (flags & BTRFS_BLOCK_GROUP_DATA)
10623                 fs_info->avail_data_alloc_bits &= ~extra_flags;
10624         if (flags & BTRFS_BLOCK_GROUP_METADATA)
10625                 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
10626         if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
10627                 fs_info->avail_system_alloc_bits &= ~extra_flags;
10628         write_sequnlock(&fs_info->profiles_lock);
10629 }
10630
10631 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
10632                              u64 group_start, struct extent_map *em)
10633 {
10634         struct btrfs_fs_info *fs_info = trans->fs_info;
10635         struct btrfs_root *root = fs_info->extent_root;
10636         struct btrfs_path *path;
10637         struct btrfs_block_group_cache *block_group;
10638         struct btrfs_free_cluster *cluster;
10639         struct btrfs_root *tree_root = fs_info->tree_root;
10640         struct btrfs_key key;
10641         struct inode *inode;
10642         struct kobject *kobj = NULL;
10643         int ret;
10644         int index;
10645         int factor;
10646         struct btrfs_caching_control *caching_ctl = NULL;
10647         bool remove_em;
10648         bool remove_rsv = false;
10649
10650         block_group = btrfs_lookup_block_group(fs_info, group_start);
10651         BUG_ON(!block_group);
10652         BUG_ON(!block_group->ro);
10653
10654         trace_btrfs_remove_block_group(block_group);
10655         /*
10656          * Free the reserved super bytes from this block group before
10657          * remove it.
10658          */
10659         free_excluded_extents(block_group);
10660         btrfs_free_ref_tree_range(fs_info, block_group->key.objectid,
10661                                   block_group->key.offset);
10662
10663         memcpy(&key, &block_group->key, sizeof(key));
10664         index = btrfs_bg_flags_to_raid_index(block_group->flags);
10665         factor = btrfs_bg_type_to_factor(block_group->flags);
10666
10667         /* make sure this block group isn't part of an allocation cluster */
10668         cluster = &fs_info->data_alloc_cluster;
10669         spin_lock(&cluster->refill_lock);
10670         btrfs_return_cluster_to_free_space(block_group, cluster);
10671         spin_unlock(&cluster->refill_lock);
10672
10673         /*
10674          * make sure this block group isn't part of a metadata
10675          * allocation cluster
10676          */
10677         cluster = &fs_info->meta_alloc_cluster;
10678         spin_lock(&cluster->refill_lock);
10679         btrfs_return_cluster_to_free_space(block_group, cluster);
10680         spin_unlock(&cluster->refill_lock);
10681
10682         path = btrfs_alloc_path();
10683         if (!path) {
10684                 ret = -ENOMEM;
10685                 goto out;
10686         }
10687
10688         /*
10689          * get the inode first so any iput calls done for the io_list
10690          * aren't the final iput (no unlinks allowed now)
10691          */
10692         inode = lookup_free_space_inode(block_group, path);
10693
10694         mutex_lock(&trans->transaction->cache_write_mutex);
10695         /*
10696          * Make sure our free space cache IO is done before removing the
10697          * free space inode
10698          */
10699         spin_lock(&trans->transaction->dirty_bgs_lock);
10700         if (!list_empty(&block_group->io_list)) {
10701                 list_del_init(&block_group->io_list);
10702
10703                 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
10704
10705                 spin_unlock(&trans->transaction->dirty_bgs_lock);
10706                 btrfs_wait_cache_io(trans, block_group, path);
10707                 btrfs_put_block_group(block_group);
10708                 spin_lock(&trans->transaction->dirty_bgs_lock);
10709         }
10710
10711         if (!list_empty(&block_group->dirty_list)) {
10712                 list_del_init(&block_group->dirty_list);
10713                 remove_rsv = true;
10714                 btrfs_put_block_group(block_group);
10715         }
10716         spin_unlock(&trans->transaction->dirty_bgs_lock);
10717         mutex_unlock(&trans->transaction->cache_write_mutex);
10718
10719         if (!IS_ERR(inode)) {
10720                 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10721                 if (ret) {
10722                         btrfs_add_delayed_iput(inode);
10723                         goto out;
10724                 }
10725                 clear_nlink(inode);
10726                 /* One for the block groups ref */
10727                 spin_lock(&block_group->lock);
10728                 if (block_group->iref) {
10729                         block_group->iref = 0;
10730                         block_group->inode = NULL;
10731                         spin_unlock(&block_group->lock);
10732                         iput(inode);
10733                 } else {
10734                         spin_unlock(&block_group->lock);
10735                 }
10736                 /* One for our lookup ref */
10737                 btrfs_add_delayed_iput(inode);
10738         }
10739
10740         key.objectid = BTRFS_FREE_SPACE_OBJECTID;
10741         key.offset = block_group->key.objectid;
10742         key.type = 0;
10743
10744         ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
10745         if (ret < 0)
10746                 goto out;
10747         if (ret > 0)
10748                 btrfs_release_path(path);
10749         if (ret == 0) {
10750                 ret = btrfs_del_item(trans, tree_root, path);
10751                 if (ret)
10752                         goto out;
10753                 btrfs_release_path(path);
10754         }
10755
10756         spin_lock(&fs_info->block_group_cache_lock);
10757         rb_erase(&block_group->cache_node,
10758                  &fs_info->block_group_cache_tree);
10759         RB_CLEAR_NODE(&block_group->cache_node);
10760
10761         if (fs_info->first_logical_byte == block_group->key.objectid)
10762                 fs_info->first_logical_byte = (u64)-1;
10763         spin_unlock(&fs_info->block_group_cache_lock);
10764
10765         down_write(&block_group->space_info->groups_sem);
10766         /*
10767          * we must use list_del_init so people can check to see if they
10768          * are still on the list after taking the semaphore
10769          */
10770         list_del_init(&block_group->list);
10771         if (list_empty(&block_group->space_info->block_groups[index])) {
10772                 kobj = block_group->space_info->block_group_kobjs[index];
10773                 block_group->space_info->block_group_kobjs[index] = NULL;
10774                 clear_avail_alloc_bits(fs_info, block_group->flags);
10775         }
10776         up_write(&block_group->space_info->groups_sem);
10777         if (kobj) {
10778                 kobject_del(kobj);
10779                 kobject_put(kobj);
10780         }
10781
10782         if (block_group->has_caching_ctl)
10783                 caching_ctl = get_caching_control(block_group);
10784         if (block_group->cached == BTRFS_CACHE_STARTED)
10785                 wait_block_group_cache_done(block_group);
10786         if (block_group->has_caching_ctl) {
10787                 down_write(&fs_info->commit_root_sem);
10788                 if (!caching_ctl) {
10789                         struct btrfs_caching_control *ctl;
10790
10791                         list_for_each_entry(ctl,
10792                                     &fs_info->caching_block_groups, list)
10793                                 if (ctl->block_group == block_group) {
10794                                         caching_ctl = ctl;
10795                                         refcount_inc(&caching_ctl->count);
10796                                         break;
10797                                 }
10798                 }
10799                 if (caching_ctl)
10800                         list_del_init(&caching_ctl->list);
10801                 up_write(&fs_info->commit_root_sem);
10802                 if (caching_ctl) {
10803                         /* Once for the caching bgs list and once for us. */
10804                         put_caching_control(caching_ctl);
10805                         put_caching_control(caching_ctl);
10806                 }
10807         }
10808
10809         spin_lock(&trans->transaction->dirty_bgs_lock);
10810         WARN_ON(!list_empty(&block_group->dirty_list));
10811         WARN_ON(!list_empty(&block_group->io_list));
10812         spin_unlock(&trans->transaction->dirty_bgs_lock);
10813
10814         btrfs_remove_free_space_cache(block_group);
10815
10816         spin_lock(&block_group->space_info->lock);
10817         list_del_init(&block_group->ro_list);
10818
10819         if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
10820                 WARN_ON(block_group->space_info->total_bytes
10821                         < block_group->key.offset);
10822                 WARN_ON(block_group->space_info->bytes_readonly
10823                         < block_group->key.offset);
10824                 WARN_ON(block_group->space_info->disk_total
10825                         < block_group->key.offset * factor);
10826         }
10827         block_group->space_info->total_bytes -= block_group->key.offset;
10828         block_group->space_info->bytes_readonly -= block_group->key.offset;
10829         block_group->space_info->disk_total -= block_group->key.offset * factor;
10830
10831         spin_unlock(&block_group->space_info->lock);
10832
10833         memcpy(&key, &block_group->key, sizeof(key));
10834
10835         mutex_lock(&fs_info->chunk_mutex);
10836         spin_lock(&block_group->lock);
10837         block_group->removed = 1;
10838         /*
10839          * At this point trimming can't start on this block group, because we
10840          * removed the block group from the tree fs_info->block_group_cache_tree
10841          * so no one can't find it anymore and even if someone already got this
10842          * block group before we removed it from the rbtree, they have already
10843          * incremented block_group->trimming - if they didn't, they won't find
10844          * any free space entries because we already removed them all when we
10845          * called btrfs_remove_free_space_cache().
10846          *
10847          * And we must not remove the extent map from the fs_info->mapping_tree
10848          * to prevent the same logical address range and physical device space
10849          * ranges from being reused for a new block group. This is because our
10850          * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
10851          * completely transactionless, so while it is trimming a range the
10852          * currently running transaction might finish and a new one start,
10853          * allowing for new block groups to be created that can reuse the same
10854          * physical device locations unless we take this special care.
10855          *
10856          * There may also be an implicit trim operation if the file system
10857          * is mounted with -odiscard. The same protections must remain
10858          * in place until the extents have been discarded completely when
10859          * the transaction commit has completed.
10860          */
10861         remove_em = (atomic_read(&block_group->trimming) == 0);
10862         spin_unlock(&block_group->lock);
10863
10864         if (remove_em) {
10865                 struct extent_map_tree *em_tree;
10866
10867                 em_tree = &fs_info->mapping_tree.map_tree;
10868                 write_lock(&em_tree->lock);
10869                 remove_extent_mapping(em_tree, em);
10870                 write_unlock(&em_tree->lock);
10871                 /* once for the tree */
10872                 free_extent_map(em);
10873         }
10874
10875         mutex_unlock(&fs_info->chunk_mutex);
10876
10877         ret = remove_block_group_free_space(trans, block_group);
10878         if (ret)
10879                 goto out;
10880
10881         btrfs_put_block_group(block_group);
10882         btrfs_put_block_group(block_group);
10883
10884         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
10885         if (ret > 0)
10886                 ret = -EIO;
10887         if (ret < 0)
10888                 goto out;
10889
10890         ret = btrfs_del_item(trans, root, path);
10891 out:
10892         if (remove_rsv)
10893                 btrfs_delayed_refs_rsv_release(fs_info, 1);
10894         btrfs_free_path(path);
10895         return ret;
10896 }
10897
10898 struct btrfs_trans_handle *
10899 btrfs_start_trans_remove_block_group(struct btrfs_fs_info *fs_info,
10900                                      const u64 chunk_offset)
10901 {
10902         struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
10903         struct extent_map *em;
10904         struct map_lookup *map;
10905         unsigned int num_items;
10906
10907         read_lock(&em_tree->lock);
10908         em = lookup_extent_mapping(em_tree, chunk_offset, 1);
10909         read_unlock(&em_tree->lock);
10910         ASSERT(em && em->start == chunk_offset);
10911
10912         /*
10913          * We need to reserve 3 + N units from the metadata space info in order
10914          * to remove a block group (done at btrfs_remove_chunk() and at
10915          * btrfs_remove_block_group()), which are used for:
10916          *
10917          * 1 unit for adding the free space inode's orphan (located in the tree
10918          * of tree roots).
10919          * 1 unit for deleting the block group item (located in the extent
10920          * tree).
10921          * 1 unit for deleting the free space item (located in tree of tree
10922          * roots).
10923          * N units for deleting N device extent items corresponding to each
10924          * stripe (located in the device tree).
10925          *
10926          * In order to remove a block group we also need to reserve units in the
10927          * system space info in order to update the chunk tree (update one or
10928          * more device items and remove one chunk item), but this is done at
10929          * btrfs_remove_chunk() through a call to check_system_chunk().
10930          */
10931         map = em->map_lookup;
10932         num_items = 3 + map->num_stripes;
10933         free_extent_map(em);
10934
10935         return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
10936                                                            num_items, 1);
10937 }
10938
10939 /*
10940  * Process the unused_bgs list and remove any that don't have any allocated
10941  * space inside of them.
10942  */
10943 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
10944 {
10945         struct btrfs_block_group_cache *block_group;
10946         struct btrfs_space_info *space_info;
10947         struct btrfs_trans_handle *trans;
10948         int ret = 0;
10949
10950         if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
10951                 return;
10952
10953         spin_lock(&fs_info->unused_bgs_lock);
10954         while (!list_empty(&fs_info->unused_bgs)) {
10955                 u64 start, end;
10956                 int trimming;
10957
10958                 block_group = list_first_entry(&fs_info->unused_bgs,
10959                                                struct btrfs_block_group_cache,
10960                                                bg_list);
10961                 list_del_init(&block_group->bg_list);
10962
10963                 space_info = block_group->space_info;
10964
10965                 if (ret || btrfs_mixed_space_info(space_info)) {
10966                         btrfs_put_block_group(block_group);
10967                         continue;
10968                 }
10969                 spin_unlock(&fs_info->unused_bgs_lock);
10970
10971                 mutex_lock(&fs_info->delete_unused_bgs_mutex);
10972
10973                 /* Don't want to race with allocators so take the groups_sem */
10974                 down_write(&space_info->groups_sem);
10975                 spin_lock(&block_group->lock);
10976                 if (block_group->reserved || block_group->pinned ||
10977                     btrfs_block_group_used(&block_group->item) ||
10978                     block_group->ro ||
10979                     list_is_singular(&block_group->list)) {
10980                         /*
10981                          * We want to bail if we made new allocations or have
10982                          * outstanding allocations in this block group.  We do
10983                          * the ro check in case balance is currently acting on
10984                          * this block group.
10985                          */
10986                         trace_btrfs_skip_unused_block_group(block_group);
10987                         spin_unlock(&block_group->lock);
10988                         up_write(&space_info->groups_sem);
10989                         goto next;
10990                 }
10991                 spin_unlock(&block_group->lock);
10992
10993                 /* We don't want to force the issue, only flip if it's ok. */
10994                 ret = inc_block_group_ro(block_group, 0);
10995                 up_write(&space_info->groups_sem);
10996                 if (ret < 0) {
10997                         ret = 0;
10998                         goto next;
10999                 }
11000
11001                 /*
11002                  * Want to do this before we do anything else so we can recover
11003                  * properly if we fail to join the transaction.
11004                  */
11005                 trans = btrfs_start_trans_remove_block_group(fs_info,
11006                                                      block_group->key.objectid);
11007                 if (IS_ERR(trans)) {
11008                         btrfs_dec_block_group_ro(block_group);
11009                         ret = PTR_ERR(trans);
11010                         goto next;
11011                 }
11012
11013                 /*
11014                  * We could have pending pinned extents for this block group,
11015                  * just delete them, we don't care about them anymore.
11016                  */
11017                 start = block_group->key.objectid;
11018                 end = start + block_group->key.offset - 1;
11019                 /*
11020                  * Hold the unused_bg_unpin_mutex lock to avoid racing with
11021                  * btrfs_finish_extent_commit(). If we are at transaction N,
11022                  * another task might be running finish_extent_commit() for the
11023                  * previous transaction N - 1, and have seen a range belonging
11024                  * to the block group in freed_extents[] before we were able to
11025                  * clear the whole block group range from freed_extents[]. This
11026                  * means that task can lookup for the block group after we
11027                  * unpinned it from freed_extents[] and removed it, leading to
11028                  * a BUG_ON() at btrfs_unpin_extent_range().
11029                  */
11030                 mutex_lock(&fs_info->unused_bg_unpin_mutex);
11031                 ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
11032                                   EXTENT_DIRTY);
11033                 if (ret) {
11034                         mutex_unlock(&fs_info->unused_bg_unpin_mutex);
11035                         btrfs_dec_block_group_ro(block_group);
11036                         goto end_trans;
11037                 }
11038                 ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
11039                                   EXTENT_DIRTY);
11040                 if (ret) {
11041                         mutex_unlock(&fs_info->unused_bg_unpin_mutex);
11042                         btrfs_dec_block_group_ro(block_group);
11043                         goto end_trans;
11044                 }
11045                 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
11046
11047                 /* Reset pinned so btrfs_put_block_group doesn't complain */
11048                 spin_lock(&space_info->lock);
11049                 spin_lock(&block_group->lock);
11050
11051                 update_bytes_pinned(space_info, -block_group->pinned);
11052                 space_info->bytes_readonly += block_group->pinned;
11053                 percpu_counter_add_batch(&space_info->total_bytes_pinned,
11054                                    -block_group->pinned,
11055                                    BTRFS_TOTAL_BYTES_PINNED_BATCH);
11056                 block_group->pinned = 0;
11057
11058                 spin_unlock(&block_group->lock);
11059                 spin_unlock(&space_info->lock);
11060
11061                 /* DISCARD can flip during remount */
11062                 trimming = btrfs_test_opt(fs_info, DISCARD);
11063
11064                 /* Implicit trim during transaction commit. */
11065                 if (trimming)
11066                         btrfs_get_block_group_trimming(block_group);
11067
11068                 /*
11069                  * Btrfs_remove_chunk will abort the transaction if things go
11070                  * horribly wrong.
11071                  */
11072                 ret = btrfs_remove_chunk(trans, block_group->key.objectid);
11073
11074                 if (ret) {
11075                         if (trimming)
11076                                 btrfs_put_block_group_trimming(block_group);
11077                         goto end_trans;
11078                 }
11079
11080                 /*
11081                  * If we're not mounted with -odiscard, we can just forget
11082                  * about this block group. Otherwise we'll need to wait
11083                  * until transaction commit to do the actual discard.
11084                  */
11085                 if (trimming) {
11086                         spin_lock(&fs_info->unused_bgs_lock);
11087                         /*
11088                          * A concurrent scrub might have added us to the list
11089                          * fs_info->unused_bgs, so use a list_move operation
11090                          * to add the block group to the deleted_bgs list.
11091                          */
11092                         list_move(&block_group->bg_list,
11093                                   &trans->transaction->deleted_bgs);
11094                         spin_unlock(&fs_info->unused_bgs_lock);
11095                         btrfs_get_block_group(block_group);
11096                 }
11097 end_trans:
11098                 btrfs_end_transaction(trans);
11099 next:
11100                 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
11101                 btrfs_put_block_group(block_group);
11102                 spin_lock(&fs_info->unused_bgs_lock);
11103         }
11104         spin_unlock(&fs_info->unused_bgs_lock);
11105 }
11106
11107 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
11108 {
11109         struct btrfs_super_block *disk_super;
11110         u64 features;
11111         u64 flags;
11112         int mixed = 0;
11113         int ret;
11114
11115         disk_super = fs_info->super_copy;
11116         if (!btrfs_super_root(disk_super))
11117                 return -EINVAL;
11118
11119         features = btrfs_super_incompat_flags(disk_super);
11120         if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
11121                 mixed = 1;
11122
11123         flags = BTRFS_BLOCK_GROUP_SYSTEM;
11124         ret = create_space_info(fs_info, flags);
11125         if (ret)
11126                 goto out;
11127
11128         if (mixed) {
11129                 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
11130                 ret = create_space_info(fs_info, flags);
11131         } else {
11132                 flags = BTRFS_BLOCK_GROUP_METADATA;
11133                 ret = create_space_info(fs_info, flags);
11134                 if (ret)
11135                         goto out;
11136
11137                 flags = BTRFS_BLOCK_GROUP_DATA;
11138                 ret = create_space_info(fs_info, flags);
11139         }
11140 out:
11141         return ret;
11142 }
11143
11144 int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
11145                                    u64 start, u64 end)
11146 {
11147         return unpin_extent_range(fs_info, start, end, false);
11148 }
11149
11150 /*
11151  * It used to be that old block groups would be left around forever.
11152  * Iterating over them would be enough to trim unused space.  Since we
11153  * now automatically remove them, we also need to iterate over unallocated
11154  * space.
11155  *
11156  * We don't want a transaction for this since the discard may take a
11157  * substantial amount of time.  We don't require that a transaction be
11158  * running, but we do need to take a running transaction into account
11159  * to ensure that we're not discarding chunks that were released or
11160  * allocated in the current transaction.
11161  *
11162  * Holding the chunks lock will prevent other threads from allocating
11163  * or releasing chunks, but it won't prevent a running transaction
11164  * from committing and releasing the memory that the pending chunks
11165  * list head uses.  For that, we need to take a reference to the
11166  * transaction and hold the commit root sem.  We only need to hold
11167  * it while performing the free space search since we have already
11168  * held back allocations.
11169  */
11170 static int btrfs_trim_free_extents(struct btrfs_device *device,
11171                                    struct fstrim_range *range, u64 *trimmed)
11172 {
11173         u64 start, len = 0, end = 0;
11174         int ret;
11175
11176         start = max_t(u64, range->start, SZ_1M);
11177         *trimmed = 0;
11178
11179         /* Discard not supported = nothing to do. */
11180         if (!blk_queue_discard(bdev_get_queue(device->bdev)))
11181                 return 0;
11182
11183         /* Not writable = nothing to do. */
11184         if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
11185                 return 0;
11186
11187         /* No free space = nothing to do. */
11188         if (device->total_bytes <= device->bytes_used)
11189                 return 0;
11190
11191         ret = 0;
11192
11193         while (1) {
11194                 struct btrfs_fs_info *fs_info = device->fs_info;
11195                 u64 bytes;
11196
11197                 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
11198                 if (ret)
11199                         break;
11200
11201                 find_first_clear_extent_bit(&device->alloc_state, start,
11202                                             &start, &end,
11203                                             CHUNK_TRIMMED | CHUNK_ALLOCATED);
11204                 /*
11205                  * If find_first_clear_extent_bit find a range that spans the
11206                  * end of the device it will set end to -1, in this case it's up
11207                  * to the caller to trim the value to the size of the device.
11208                  */
11209                 end = min(end, device->total_bytes - 1);
11210                 len = end - start + 1;
11211
11212                 /* We didn't find any extents */
11213                 if (!len) {
11214                         mutex_unlock(&fs_info->chunk_mutex);
11215                         ret = 0;
11216                         break;
11217                 }
11218
11219                 /* Keep going until we satisfy minlen or reach end of space */
11220                 if (len < range->minlen) {
11221                         mutex_unlock(&fs_info->chunk_mutex);
11222                         start += len;
11223                         continue;
11224                 }
11225
11226                 /* If we are out of the passed range break */
11227                 if (start > range->start + range->len - 1) {
11228                         mutex_unlock(&fs_info->chunk_mutex);
11229                         break;
11230                 }
11231
11232                 start = max(range->start, start);
11233                 len = min(range->len, len);
11234
11235                 ret = btrfs_issue_discard(device->bdev, start, len,
11236                                           &bytes);
11237                 if (!ret)
11238                         set_extent_bits(&device->alloc_state, start,
11239                                         start + bytes - 1,
11240                                         CHUNK_TRIMMED);
11241                 mutex_unlock(&fs_info->chunk_mutex);
11242
11243                 if (ret)
11244                         break;
11245
11246                 start += len;
11247                 *trimmed += bytes;
11248
11249                 /* We've trimmed enough */
11250                 if (*trimmed >= range->len)
11251                         break;
11252
11253                 if (fatal_signal_pending(current)) {
11254                         ret = -ERESTARTSYS;
11255                         break;
11256                 }
11257
11258                 cond_resched();
11259         }
11260
11261         return ret;
11262 }
11263
11264 /*
11265  * Trim the whole filesystem by:
11266  * 1) trimming the free space in each block group
11267  * 2) trimming the unallocated space on each device
11268  *
11269  * This will also continue trimming even if a block group or device encounters
11270  * an error.  The return value will be the last error, or 0 if nothing bad
11271  * happens.
11272  */
11273 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
11274 {
11275         struct btrfs_block_group_cache *cache = NULL;
11276         struct btrfs_device *device;
11277         struct list_head *devices;
11278         u64 group_trimmed;
11279         u64 start;
11280         u64 end;
11281         u64 trimmed = 0;
11282         u64 bg_failed = 0;
11283         u64 dev_failed = 0;
11284         int bg_ret = 0;
11285         int dev_ret = 0;
11286         int ret = 0;
11287
11288         cache = btrfs_lookup_first_block_group(fs_info, range->start);
11289         for (; cache; cache = next_block_group(cache)) {
11290                 if (cache->key.objectid >= (range->start + range->len)) {
11291                         btrfs_put_block_group(cache);
11292                         break;
11293                 }
11294
11295                 start = max(range->start, cache->key.objectid);
11296                 end = min(range->start + range->len,
11297                                 cache->key.objectid + cache->key.offset);
11298
11299                 if (end - start >= range->minlen) {
11300                         if (!block_group_cache_done(cache)) {
11301                                 ret = cache_block_group(cache, 0);
11302                                 if (ret) {
11303                                         bg_failed++;
11304                                         bg_ret = ret;
11305                                         continue;
11306                                 }
11307                                 ret = wait_block_group_cache_done(cache);
11308                                 if (ret) {
11309                                         bg_failed++;
11310                                         bg_ret = ret;
11311                                         continue;
11312                                 }
11313                         }
11314                         ret = btrfs_trim_block_group(cache,
11315                                                      &group_trimmed,
11316                                                      start,
11317                                                      end,
11318                                                      range->minlen);
11319
11320                         trimmed += group_trimmed;
11321                         if (ret) {
11322                                 bg_failed++;
11323                                 bg_ret = ret;
11324                                 continue;
11325                         }
11326                 }
11327         }
11328
11329         if (bg_failed)
11330                 btrfs_warn(fs_info,
11331                         "failed to trim %llu block group(s), last error %d",
11332                         bg_failed, bg_ret);
11333         mutex_lock(&fs_info->fs_devices->device_list_mutex);
11334         devices = &fs_info->fs_devices->devices;
11335         list_for_each_entry(device, devices, dev_list) {
11336                 ret = btrfs_trim_free_extents(device, range, &group_trimmed);
11337                 if (ret) {
11338                         dev_failed++;
11339                         dev_ret = ret;
11340                         break;
11341                 }
11342
11343                 trimmed += group_trimmed;
11344         }
11345         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
11346
11347         if (dev_failed)
11348                 btrfs_warn(fs_info,
11349                         "failed to trim %llu device(s), last error %d",
11350                         dev_failed, dev_ret);
11351         range->len = trimmed;
11352         if (bg_ret)
11353                 return bg_ret;
11354         return dev_ret;
11355 }
11356
11357 /*
11358  * btrfs_{start,end}_write_no_snapshotting() are similar to
11359  * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
11360  * data into the page cache through nocow before the subvolume is snapshoted,
11361  * but flush the data into disk after the snapshot creation, or to prevent
11362  * operations while snapshotting is ongoing and that cause the snapshot to be
11363  * inconsistent (writes followed by expanding truncates for example).
11364  */
11365 void btrfs_end_write_no_snapshotting(struct btrfs_root *root)
11366 {
11367         percpu_counter_dec(&root->subv_writers->counter);
11368         cond_wake_up(&root->subv_writers->wait);
11369 }
11370
11371 int btrfs_start_write_no_snapshotting(struct btrfs_root *root)
11372 {
11373         if (atomic_read(&root->will_be_snapshotted))
11374                 return 0;
11375
11376         percpu_counter_inc(&root->subv_writers->counter);
11377         /*
11378          * Make sure counter is updated before we check for snapshot creation.
11379          */
11380         smp_mb();
11381         if (atomic_read(&root->will_be_snapshotted)) {
11382                 btrfs_end_write_no_snapshotting(root);
11383                 return 0;
11384         }
11385         return 1;
11386 }
11387
11388 void btrfs_wait_for_snapshot_creation(struct btrfs_root *root)
11389 {
11390         while (true) {
11391                 int ret;
11392
11393                 ret = btrfs_start_write_no_snapshotting(root);
11394                 if (ret)
11395                         break;
11396                 wait_var_event(&root->will_be_snapshotted,
11397                                !atomic_read(&root->will_be_snapshotted));
11398         }
11399 }
11400
11401 void btrfs_mark_bg_unused(struct btrfs_block_group_cache *bg)
11402 {
11403         struct btrfs_fs_info *fs_info = bg->fs_info;
11404
11405         spin_lock(&fs_info->unused_bgs_lock);
11406         if (list_empty(&bg->bg_list)) {
11407                 btrfs_get_block_group(bg);
11408                 trace_btrfs_add_unused_block_group(bg);
11409                 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
11410         }
11411         spin_unlock(&fs_info->unused_bgs_lock);
11412 }