btrfs: factor out devs_max setting in __btrfs_alloc_chunk
[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 u64 generic_ref_to_space_flags(struct btrfs_ref *ref)
760 {
761         if (ref->type == BTRFS_REF_METADATA) {
762                 if (ref->tree_ref.root == BTRFS_CHUNK_TREE_OBJECTID)
763                         return BTRFS_BLOCK_GROUP_SYSTEM;
764                 else
765                         return BTRFS_BLOCK_GROUP_METADATA;
766         }
767         return BTRFS_BLOCK_GROUP_DATA;
768 }
769
770 static void add_pinned_bytes(struct btrfs_fs_info *fs_info,
771                              struct btrfs_ref *ref)
772 {
773         struct btrfs_space_info *space_info;
774         u64 flags = generic_ref_to_space_flags(ref);
775
776         space_info = __find_space_info(fs_info, flags);
777         ASSERT(space_info);
778         percpu_counter_add_batch(&space_info->total_bytes_pinned, ref->len,
779                     BTRFS_TOTAL_BYTES_PINNED_BATCH);
780 }
781
782 static void sub_pinned_bytes(struct btrfs_fs_info *fs_info,
783                              struct btrfs_ref *ref)
784 {
785         struct btrfs_space_info *space_info;
786         u64 flags = generic_ref_to_space_flags(ref);
787
788         space_info = __find_space_info(fs_info, flags);
789         ASSERT(space_info);
790         percpu_counter_add_batch(&space_info->total_bytes_pinned, -ref->len,
791                     BTRFS_TOTAL_BYTES_PINNED_BATCH);
792 }
793
794 /*
795  * after adding space to the filesystem, we need to clear the full flags
796  * on all the space infos.
797  */
798 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
799 {
800         struct list_head *head = &info->space_info;
801         struct btrfs_space_info *found;
802
803         rcu_read_lock();
804         list_for_each_entry_rcu(found, head, list)
805                 found->full = 0;
806         rcu_read_unlock();
807 }
808
809 /* simple helper to search for an existing data extent at a given offset */
810 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
811 {
812         int ret;
813         struct btrfs_key key;
814         struct btrfs_path *path;
815
816         path = btrfs_alloc_path();
817         if (!path)
818                 return -ENOMEM;
819
820         key.objectid = start;
821         key.offset = len;
822         key.type = BTRFS_EXTENT_ITEM_KEY;
823         ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
824         btrfs_free_path(path);
825         return ret;
826 }
827
828 /*
829  * helper function to lookup reference count and flags of a tree block.
830  *
831  * the head node for delayed ref is used to store the sum of all the
832  * reference count modifications queued up in the rbtree. the head
833  * node may also store the extent flags to set. This way you can check
834  * to see what the reference count and extent flags would be if all of
835  * the delayed refs are not processed.
836  */
837 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
838                              struct btrfs_fs_info *fs_info, u64 bytenr,
839                              u64 offset, int metadata, u64 *refs, u64 *flags)
840 {
841         struct btrfs_delayed_ref_head *head;
842         struct btrfs_delayed_ref_root *delayed_refs;
843         struct btrfs_path *path;
844         struct btrfs_extent_item *ei;
845         struct extent_buffer *leaf;
846         struct btrfs_key key;
847         u32 item_size;
848         u64 num_refs;
849         u64 extent_flags;
850         int ret;
851
852         /*
853          * If we don't have skinny metadata, don't bother doing anything
854          * different
855          */
856         if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
857                 offset = fs_info->nodesize;
858                 metadata = 0;
859         }
860
861         path = btrfs_alloc_path();
862         if (!path)
863                 return -ENOMEM;
864
865         if (!trans) {
866                 path->skip_locking = 1;
867                 path->search_commit_root = 1;
868         }
869
870 search_again:
871         key.objectid = bytenr;
872         key.offset = offset;
873         if (metadata)
874                 key.type = BTRFS_METADATA_ITEM_KEY;
875         else
876                 key.type = BTRFS_EXTENT_ITEM_KEY;
877
878         ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
879         if (ret < 0)
880                 goto out_free;
881
882         if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
883                 if (path->slots[0]) {
884                         path->slots[0]--;
885                         btrfs_item_key_to_cpu(path->nodes[0], &key,
886                                               path->slots[0]);
887                         if (key.objectid == bytenr &&
888                             key.type == BTRFS_EXTENT_ITEM_KEY &&
889                             key.offset == fs_info->nodesize)
890                                 ret = 0;
891                 }
892         }
893
894         if (ret == 0) {
895                 leaf = path->nodes[0];
896                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
897                 if (item_size >= sizeof(*ei)) {
898                         ei = btrfs_item_ptr(leaf, path->slots[0],
899                                             struct btrfs_extent_item);
900                         num_refs = btrfs_extent_refs(leaf, ei);
901                         extent_flags = btrfs_extent_flags(leaf, ei);
902                 } else {
903                         ret = -EINVAL;
904                         btrfs_print_v0_err(fs_info);
905                         if (trans)
906                                 btrfs_abort_transaction(trans, ret);
907                         else
908                                 btrfs_handle_fs_error(fs_info, ret, NULL);
909
910                         goto out_free;
911                 }
912
913                 BUG_ON(num_refs == 0);
914         } else {
915                 num_refs = 0;
916                 extent_flags = 0;
917                 ret = 0;
918         }
919
920         if (!trans)
921                 goto out;
922
923         delayed_refs = &trans->transaction->delayed_refs;
924         spin_lock(&delayed_refs->lock);
925         head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
926         if (head) {
927                 if (!mutex_trylock(&head->mutex)) {
928                         refcount_inc(&head->refs);
929                         spin_unlock(&delayed_refs->lock);
930
931                         btrfs_release_path(path);
932
933                         /*
934                          * Mutex was contended, block until it's released and try
935                          * again
936                          */
937                         mutex_lock(&head->mutex);
938                         mutex_unlock(&head->mutex);
939                         btrfs_put_delayed_ref_head(head);
940                         goto search_again;
941                 }
942                 spin_lock(&head->lock);
943                 if (head->extent_op && head->extent_op->update_flags)
944                         extent_flags |= head->extent_op->flags_to_set;
945                 else
946                         BUG_ON(num_refs == 0);
947
948                 num_refs += head->ref_mod;
949                 spin_unlock(&head->lock);
950                 mutex_unlock(&head->mutex);
951         }
952         spin_unlock(&delayed_refs->lock);
953 out:
954         WARN_ON(num_refs == 0);
955         if (refs)
956                 *refs = num_refs;
957         if (flags)
958                 *flags = extent_flags;
959 out_free:
960         btrfs_free_path(path);
961         return ret;
962 }
963
964 /*
965  * Back reference rules.  Back refs have three main goals:
966  *
967  * 1) differentiate between all holders of references to an extent so that
968  *    when a reference is dropped we can make sure it was a valid reference
969  *    before freeing the extent.
970  *
971  * 2) Provide enough information to quickly find the holders of an extent
972  *    if we notice a given block is corrupted or bad.
973  *
974  * 3) Make it easy to migrate blocks for FS shrinking or storage pool
975  *    maintenance.  This is actually the same as #2, but with a slightly
976  *    different use case.
977  *
978  * There are two kinds of back refs. The implicit back refs is optimized
979  * for pointers in non-shared tree blocks. For a given pointer in a block,
980  * back refs of this kind provide information about the block's owner tree
981  * and the pointer's key. These information allow us to find the block by
982  * b-tree searching. The full back refs is for pointers in tree blocks not
983  * referenced by their owner trees. The location of tree block is recorded
984  * in the back refs. Actually the full back refs is generic, and can be
985  * used in all cases the implicit back refs is used. The major shortcoming
986  * of the full back refs is its overhead. Every time a tree block gets
987  * COWed, we have to update back refs entry for all pointers in it.
988  *
989  * For a newly allocated tree block, we use implicit back refs for
990  * pointers in it. This means most tree related operations only involve
991  * implicit back refs. For a tree block created in old transaction, the
992  * only way to drop a reference to it is COW it. So we can detect the
993  * event that tree block loses its owner tree's reference and do the
994  * back refs conversion.
995  *
996  * When a tree block is COWed through a tree, there are four cases:
997  *
998  * The reference count of the block is one and the tree is the block's
999  * owner tree. Nothing to do in this case.
1000  *
1001  * The reference count of the block is one and the tree is not the
1002  * block's owner tree. In this case, full back refs is used for pointers
1003  * in the block. Remove these full back refs, add implicit back refs for
1004  * every pointers in the new block.
1005  *
1006  * The reference count of the block is greater than one and the tree is
1007  * the block's owner tree. In this case, implicit back refs is used for
1008  * pointers in the block. Add full back refs for every pointers in the
1009  * block, increase lower level extents' reference counts. The original
1010  * implicit back refs are entailed to the new block.
1011  *
1012  * The reference count of the block is greater than one and the tree is
1013  * not the block's owner tree. Add implicit back refs for every pointer in
1014  * the new block, increase lower level extents' reference count.
1015  *
1016  * Back Reference Key composing:
1017  *
1018  * The key objectid corresponds to the first byte in the extent,
1019  * The key type is used to differentiate between types of back refs.
1020  * There are different meanings of the key offset for different types
1021  * of back refs.
1022  *
1023  * File extents can be referenced by:
1024  *
1025  * - multiple snapshots, subvolumes, or different generations in one subvol
1026  * - different files inside a single subvolume
1027  * - different offsets inside a file (bookend extents in file.c)
1028  *
1029  * The extent ref structure for the implicit back refs has fields for:
1030  *
1031  * - Objectid of the subvolume root
1032  * - objectid of the file holding the reference
1033  * - original offset in the file
1034  * - how many bookend extents
1035  *
1036  * The key offset for the implicit back refs is hash of the first
1037  * three fields.
1038  *
1039  * The extent ref structure for the full back refs has field for:
1040  *
1041  * - number of pointers in the tree leaf
1042  *
1043  * The key offset for the implicit back refs is the first byte of
1044  * the tree leaf
1045  *
1046  * When a file extent is allocated, The implicit back refs is used.
1047  * the fields are filled in:
1048  *
1049  *     (root_key.objectid, inode objectid, offset in file, 1)
1050  *
1051  * When a file extent is removed file truncation, we find the
1052  * corresponding implicit back refs and check the following fields:
1053  *
1054  *     (btrfs_header_owner(leaf), inode objectid, offset in file)
1055  *
1056  * Btree extents can be referenced by:
1057  *
1058  * - Different subvolumes
1059  *
1060  * Both the implicit back refs and the full back refs for tree blocks
1061  * only consist of key. The key offset for the implicit back refs is
1062  * objectid of block's owner tree. The key offset for the full back refs
1063  * is the first byte of parent block.
1064  *
1065  * When implicit back refs is used, information about the lowest key and
1066  * level of the tree block are required. These information are stored in
1067  * tree block info structure.
1068  */
1069
1070 /*
1071  * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
1072  * is_data == BTRFS_REF_TYPE_DATA, data type is requiried,
1073  * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
1074  */
1075 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
1076                                      struct btrfs_extent_inline_ref *iref,
1077                                      enum btrfs_inline_ref_type is_data)
1078 {
1079         int type = btrfs_extent_inline_ref_type(eb, iref);
1080         u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
1081
1082         if (type == BTRFS_TREE_BLOCK_REF_KEY ||
1083             type == BTRFS_SHARED_BLOCK_REF_KEY ||
1084             type == BTRFS_SHARED_DATA_REF_KEY ||
1085             type == BTRFS_EXTENT_DATA_REF_KEY) {
1086                 if (is_data == BTRFS_REF_TYPE_BLOCK) {
1087                         if (type == BTRFS_TREE_BLOCK_REF_KEY)
1088                                 return type;
1089                         if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1090                                 ASSERT(eb->fs_info);
1091                                 /*
1092                                  * Every shared one has parent tree
1093                                  * block, which must be aligned to
1094                                  * nodesize.
1095                                  */
1096                                 if (offset &&
1097                                     IS_ALIGNED(offset, eb->fs_info->nodesize))
1098                                         return type;
1099                         }
1100                 } else if (is_data == BTRFS_REF_TYPE_DATA) {
1101                         if (type == BTRFS_EXTENT_DATA_REF_KEY)
1102                                 return type;
1103                         if (type == BTRFS_SHARED_DATA_REF_KEY) {
1104                                 ASSERT(eb->fs_info);
1105                                 /*
1106                                  * Every shared one has parent tree
1107                                  * block, which must be aligned to
1108                                  * nodesize.
1109                                  */
1110                                 if (offset &&
1111                                     IS_ALIGNED(offset, eb->fs_info->nodesize))
1112                                         return type;
1113                         }
1114                 } else {
1115                         ASSERT(is_data == BTRFS_REF_TYPE_ANY);
1116                         return type;
1117                 }
1118         }
1119
1120         btrfs_print_leaf((struct extent_buffer *)eb);
1121         btrfs_err(eb->fs_info, "eb %llu invalid extent inline ref type %d",
1122                   eb->start, type);
1123         WARN_ON(1);
1124
1125         return BTRFS_REF_TYPE_INVALID;
1126 }
1127
1128 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1129 {
1130         u32 high_crc = ~(u32)0;
1131         u32 low_crc = ~(u32)0;
1132         __le64 lenum;
1133
1134         lenum = cpu_to_le64(root_objectid);
1135         high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
1136         lenum = cpu_to_le64(owner);
1137         low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
1138         lenum = cpu_to_le64(offset);
1139         low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
1140
1141         return ((u64)high_crc << 31) ^ (u64)low_crc;
1142 }
1143
1144 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1145                                      struct btrfs_extent_data_ref *ref)
1146 {
1147         return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1148                                     btrfs_extent_data_ref_objectid(leaf, ref),
1149                                     btrfs_extent_data_ref_offset(leaf, ref));
1150 }
1151
1152 static int match_extent_data_ref(struct extent_buffer *leaf,
1153                                  struct btrfs_extent_data_ref *ref,
1154                                  u64 root_objectid, u64 owner, u64 offset)
1155 {
1156         if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1157             btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1158             btrfs_extent_data_ref_offset(leaf, ref) != offset)
1159                 return 0;
1160         return 1;
1161 }
1162
1163 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1164                                            struct btrfs_path *path,
1165                                            u64 bytenr, u64 parent,
1166                                            u64 root_objectid,
1167                                            u64 owner, u64 offset)
1168 {
1169         struct btrfs_root *root = trans->fs_info->extent_root;
1170         struct btrfs_key key;
1171         struct btrfs_extent_data_ref *ref;
1172         struct extent_buffer *leaf;
1173         u32 nritems;
1174         int ret;
1175         int recow;
1176         int err = -ENOENT;
1177
1178         key.objectid = bytenr;
1179         if (parent) {
1180                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1181                 key.offset = parent;
1182         } else {
1183                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1184                 key.offset = hash_extent_data_ref(root_objectid,
1185                                                   owner, offset);
1186         }
1187 again:
1188         recow = 0;
1189         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1190         if (ret < 0) {
1191                 err = ret;
1192                 goto fail;
1193         }
1194
1195         if (parent) {
1196                 if (!ret)
1197                         return 0;
1198                 goto fail;
1199         }
1200
1201         leaf = path->nodes[0];
1202         nritems = btrfs_header_nritems(leaf);
1203         while (1) {
1204                 if (path->slots[0] >= nritems) {
1205                         ret = btrfs_next_leaf(root, path);
1206                         if (ret < 0)
1207                                 err = ret;
1208                         if (ret)
1209                                 goto fail;
1210
1211                         leaf = path->nodes[0];
1212                         nritems = btrfs_header_nritems(leaf);
1213                         recow = 1;
1214                 }
1215
1216                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1217                 if (key.objectid != bytenr ||
1218                     key.type != BTRFS_EXTENT_DATA_REF_KEY)
1219                         goto fail;
1220
1221                 ref = btrfs_item_ptr(leaf, path->slots[0],
1222                                      struct btrfs_extent_data_ref);
1223
1224                 if (match_extent_data_ref(leaf, ref, root_objectid,
1225                                           owner, offset)) {
1226                         if (recow) {
1227                                 btrfs_release_path(path);
1228                                 goto again;
1229                         }
1230                         err = 0;
1231                         break;
1232                 }
1233                 path->slots[0]++;
1234         }
1235 fail:
1236         return err;
1237 }
1238
1239 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1240                                            struct btrfs_path *path,
1241                                            u64 bytenr, u64 parent,
1242                                            u64 root_objectid, u64 owner,
1243                                            u64 offset, int refs_to_add)
1244 {
1245         struct btrfs_root *root = trans->fs_info->extent_root;
1246         struct btrfs_key key;
1247         struct extent_buffer *leaf;
1248         u32 size;
1249         u32 num_refs;
1250         int ret;
1251
1252         key.objectid = bytenr;
1253         if (parent) {
1254                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1255                 key.offset = parent;
1256                 size = sizeof(struct btrfs_shared_data_ref);
1257         } else {
1258                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1259                 key.offset = hash_extent_data_ref(root_objectid,
1260                                                   owner, offset);
1261                 size = sizeof(struct btrfs_extent_data_ref);
1262         }
1263
1264         ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1265         if (ret && ret != -EEXIST)
1266                 goto fail;
1267
1268         leaf = path->nodes[0];
1269         if (parent) {
1270                 struct btrfs_shared_data_ref *ref;
1271                 ref = btrfs_item_ptr(leaf, path->slots[0],
1272                                      struct btrfs_shared_data_ref);
1273                 if (ret == 0) {
1274                         btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1275                 } else {
1276                         num_refs = btrfs_shared_data_ref_count(leaf, ref);
1277                         num_refs += refs_to_add;
1278                         btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1279                 }
1280         } else {
1281                 struct btrfs_extent_data_ref *ref;
1282                 while (ret == -EEXIST) {
1283                         ref = btrfs_item_ptr(leaf, path->slots[0],
1284                                              struct btrfs_extent_data_ref);
1285                         if (match_extent_data_ref(leaf, ref, root_objectid,
1286                                                   owner, offset))
1287                                 break;
1288                         btrfs_release_path(path);
1289                         key.offset++;
1290                         ret = btrfs_insert_empty_item(trans, root, path, &key,
1291                                                       size);
1292                         if (ret && ret != -EEXIST)
1293                                 goto fail;
1294
1295                         leaf = path->nodes[0];
1296                 }
1297                 ref = btrfs_item_ptr(leaf, path->slots[0],
1298                                      struct btrfs_extent_data_ref);
1299                 if (ret == 0) {
1300                         btrfs_set_extent_data_ref_root(leaf, ref,
1301                                                        root_objectid);
1302                         btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1303                         btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1304                         btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1305                 } else {
1306                         num_refs = btrfs_extent_data_ref_count(leaf, ref);
1307                         num_refs += refs_to_add;
1308                         btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1309                 }
1310         }
1311         btrfs_mark_buffer_dirty(leaf);
1312         ret = 0;
1313 fail:
1314         btrfs_release_path(path);
1315         return ret;
1316 }
1317
1318 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1319                                            struct btrfs_path *path,
1320                                            int refs_to_drop, int *last_ref)
1321 {
1322         struct btrfs_key key;
1323         struct btrfs_extent_data_ref *ref1 = NULL;
1324         struct btrfs_shared_data_ref *ref2 = NULL;
1325         struct extent_buffer *leaf;
1326         u32 num_refs = 0;
1327         int ret = 0;
1328
1329         leaf = path->nodes[0];
1330         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1331
1332         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1333                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1334                                       struct btrfs_extent_data_ref);
1335                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1336         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1337                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1338                                       struct btrfs_shared_data_ref);
1339                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1340         } else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
1341                 btrfs_print_v0_err(trans->fs_info);
1342                 btrfs_abort_transaction(trans, -EINVAL);
1343                 return -EINVAL;
1344         } else {
1345                 BUG();
1346         }
1347
1348         BUG_ON(num_refs < refs_to_drop);
1349         num_refs -= refs_to_drop;
1350
1351         if (num_refs == 0) {
1352                 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1353                 *last_ref = 1;
1354         } else {
1355                 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1356                         btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1357                 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1358                         btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1359                 btrfs_mark_buffer_dirty(leaf);
1360         }
1361         return ret;
1362 }
1363
1364 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
1365                                           struct btrfs_extent_inline_ref *iref)
1366 {
1367         struct btrfs_key key;
1368         struct extent_buffer *leaf;
1369         struct btrfs_extent_data_ref *ref1;
1370         struct btrfs_shared_data_ref *ref2;
1371         u32 num_refs = 0;
1372         int type;
1373
1374         leaf = path->nodes[0];
1375         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1376
1377         BUG_ON(key.type == BTRFS_EXTENT_REF_V0_KEY);
1378         if (iref) {
1379                 /*
1380                  * If type is invalid, we should have bailed out earlier than
1381                  * this call.
1382                  */
1383                 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
1384                 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1385                 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1386                         ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1387                         num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1388                 } else {
1389                         ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1390                         num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1391                 }
1392         } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1393                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1394                                       struct btrfs_extent_data_ref);
1395                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1396         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1397                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1398                                       struct btrfs_shared_data_ref);
1399                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1400         } else {
1401                 WARN_ON(1);
1402         }
1403         return num_refs;
1404 }
1405
1406 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1407                                           struct btrfs_path *path,
1408                                           u64 bytenr, u64 parent,
1409                                           u64 root_objectid)
1410 {
1411         struct btrfs_root *root = trans->fs_info->extent_root;
1412         struct btrfs_key key;
1413         int ret;
1414
1415         key.objectid = bytenr;
1416         if (parent) {
1417                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1418                 key.offset = parent;
1419         } else {
1420                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1421                 key.offset = root_objectid;
1422         }
1423
1424         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1425         if (ret > 0)
1426                 ret = -ENOENT;
1427         return ret;
1428 }
1429
1430 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1431                                           struct btrfs_path *path,
1432                                           u64 bytenr, u64 parent,
1433                                           u64 root_objectid)
1434 {
1435         struct btrfs_key key;
1436         int ret;
1437
1438         key.objectid = bytenr;
1439         if (parent) {
1440                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1441                 key.offset = parent;
1442         } else {
1443                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1444                 key.offset = root_objectid;
1445         }
1446
1447         ret = btrfs_insert_empty_item(trans, trans->fs_info->extent_root,
1448                                       path, &key, 0);
1449         btrfs_release_path(path);
1450         return ret;
1451 }
1452
1453 static inline int extent_ref_type(u64 parent, u64 owner)
1454 {
1455         int type;
1456         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1457                 if (parent > 0)
1458                         type = BTRFS_SHARED_BLOCK_REF_KEY;
1459                 else
1460                         type = BTRFS_TREE_BLOCK_REF_KEY;
1461         } else {
1462                 if (parent > 0)
1463                         type = BTRFS_SHARED_DATA_REF_KEY;
1464                 else
1465                         type = BTRFS_EXTENT_DATA_REF_KEY;
1466         }
1467         return type;
1468 }
1469
1470 static int find_next_key(struct btrfs_path *path, int level,
1471                          struct btrfs_key *key)
1472
1473 {
1474         for (; level < BTRFS_MAX_LEVEL; level++) {
1475                 if (!path->nodes[level])
1476                         break;
1477                 if (path->slots[level] + 1 >=
1478                     btrfs_header_nritems(path->nodes[level]))
1479                         continue;
1480                 if (level == 0)
1481                         btrfs_item_key_to_cpu(path->nodes[level], key,
1482                                               path->slots[level] + 1);
1483                 else
1484                         btrfs_node_key_to_cpu(path->nodes[level], key,
1485                                               path->slots[level] + 1);
1486                 return 0;
1487         }
1488         return 1;
1489 }
1490
1491 /*
1492  * look for inline back ref. if back ref is found, *ref_ret is set
1493  * to the address of inline back ref, and 0 is returned.
1494  *
1495  * if back ref isn't found, *ref_ret is set to the address where it
1496  * should be inserted, and -ENOENT is returned.
1497  *
1498  * if insert is true and there are too many inline back refs, the path
1499  * points to the extent item, and -EAGAIN is returned.
1500  *
1501  * NOTE: inline back refs are ordered in the same way that back ref
1502  *       items in the tree are ordered.
1503  */
1504 static noinline_for_stack
1505 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1506                                  struct btrfs_path *path,
1507                                  struct btrfs_extent_inline_ref **ref_ret,
1508                                  u64 bytenr, u64 num_bytes,
1509                                  u64 parent, u64 root_objectid,
1510                                  u64 owner, u64 offset, int insert)
1511 {
1512         struct btrfs_fs_info *fs_info = trans->fs_info;
1513         struct btrfs_root *root = fs_info->extent_root;
1514         struct btrfs_key key;
1515         struct extent_buffer *leaf;
1516         struct btrfs_extent_item *ei;
1517         struct btrfs_extent_inline_ref *iref;
1518         u64 flags;
1519         u64 item_size;
1520         unsigned long ptr;
1521         unsigned long end;
1522         int extra_size;
1523         int type;
1524         int want;
1525         int ret;
1526         int err = 0;
1527         bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
1528         int needed;
1529
1530         key.objectid = bytenr;
1531         key.type = BTRFS_EXTENT_ITEM_KEY;
1532         key.offset = num_bytes;
1533
1534         want = extent_ref_type(parent, owner);
1535         if (insert) {
1536                 extra_size = btrfs_extent_inline_ref_size(want);
1537                 path->keep_locks = 1;
1538         } else
1539                 extra_size = -1;
1540
1541         /*
1542          * Owner is our level, so we can just add one to get the level for the
1543          * block we are interested in.
1544          */
1545         if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1546                 key.type = BTRFS_METADATA_ITEM_KEY;
1547                 key.offset = owner;
1548         }
1549
1550 again:
1551         ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1552         if (ret < 0) {
1553                 err = ret;
1554                 goto out;
1555         }
1556
1557         /*
1558          * We may be a newly converted file system which still has the old fat
1559          * extent entries for metadata, so try and see if we have one of those.
1560          */
1561         if (ret > 0 && skinny_metadata) {
1562                 skinny_metadata = false;
1563                 if (path->slots[0]) {
1564                         path->slots[0]--;
1565                         btrfs_item_key_to_cpu(path->nodes[0], &key,
1566                                               path->slots[0]);
1567                         if (key.objectid == bytenr &&
1568                             key.type == BTRFS_EXTENT_ITEM_KEY &&
1569                             key.offset == num_bytes)
1570                                 ret = 0;
1571                 }
1572                 if (ret) {
1573                         key.objectid = bytenr;
1574                         key.type = BTRFS_EXTENT_ITEM_KEY;
1575                         key.offset = num_bytes;
1576                         btrfs_release_path(path);
1577                         goto again;
1578                 }
1579         }
1580
1581         if (ret && !insert) {
1582                 err = -ENOENT;
1583                 goto out;
1584         } else if (WARN_ON(ret)) {
1585                 err = -EIO;
1586                 goto out;
1587         }
1588
1589         leaf = path->nodes[0];
1590         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1591         if (unlikely(item_size < sizeof(*ei))) {
1592                 err = -EINVAL;
1593                 btrfs_print_v0_err(fs_info);
1594                 btrfs_abort_transaction(trans, err);
1595                 goto out;
1596         }
1597
1598         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1599         flags = btrfs_extent_flags(leaf, ei);
1600
1601         ptr = (unsigned long)(ei + 1);
1602         end = (unsigned long)ei + item_size;
1603
1604         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
1605                 ptr += sizeof(struct btrfs_tree_block_info);
1606                 BUG_ON(ptr > end);
1607         }
1608
1609         if (owner >= BTRFS_FIRST_FREE_OBJECTID)
1610                 needed = BTRFS_REF_TYPE_DATA;
1611         else
1612                 needed = BTRFS_REF_TYPE_BLOCK;
1613
1614         err = -ENOENT;
1615         while (1) {
1616                 if (ptr >= end) {
1617                         WARN_ON(ptr > end);
1618                         break;
1619                 }
1620                 iref = (struct btrfs_extent_inline_ref *)ptr;
1621                 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
1622                 if (type == BTRFS_REF_TYPE_INVALID) {
1623                         err = -EUCLEAN;
1624                         goto out;
1625                 }
1626
1627                 if (want < type)
1628                         break;
1629                 if (want > type) {
1630                         ptr += btrfs_extent_inline_ref_size(type);
1631                         continue;
1632                 }
1633
1634                 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1635                         struct btrfs_extent_data_ref *dref;
1636                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1637                         if (match_extent_data_ref(leaf, dref, root_objectid,
1638                                                   owner, offset)) {
1639                                 err = 0;
1640                                 break;
1641                         }
1642                         if (hash_extent_data_ref_item(leaf, dref) <
1643                             hash_extent_data_ref(root_objectid, owner, offset))
1644                                 break;
1645                 } else {
1646                         u64 ref_offset;
1647                         ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1648                         if (parent > 0) {
1649                                 if (parent == ref_offset) {
1650                                         err = 0;
1651                                         break;
1652                                 }
1653                                 if (ref_offset < parent)
1654                                         break;
1655                         } else {
1656                                 if (root_objectid == ref_offset) {
1657                                         err = 0;
1658                                         break;
1659                                 }
1660                                 if (ref_offset < root_objectid)
1661                                         break;
1662                         }
1663                 }
1664                 ptr += btrfs_extent_inline_ref_size(type);
1665         }
1666         if (err == -ENOENT && insert) {
1667                 if (item_size + extra_size >=
1668                     BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1669                         err = -EAGAIN;
1670                         goto out;
1671                 }
1672                 /*
1673                  * To add new inline back ref, we have to make sure
1674                  * there is no corresponding back ref item.
1675                  * For simplicity, we just do not add new inline back
1676                  * ref if there is any kind of item for this block
1677                  */
1678                 if (find_next_key(path, 0, &key) == 0 &&
1679                     key.objectid == bytenr &&
1680                     key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1681                         err = -EAGAIN;
1682                         goto out;
1683                 }
1684         }
1685         *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1686 out:
1687         if (insert) {
1688                 path->keep_locks = 0;
1689                 btrfs_unlock_up_safe(path, 1);
1690         }
1691         return err;
1692 }
1693
1694 /*
1695  * helper to add new inline back ref
1696  */
1697 static noinline_for_stack
1698 void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
1699                                  struct btrfs_path *path,
1700                                  struct btrfs_extent_inline_ref *iref,
1701                                  u64 parent, u64 root_objectid,
1702                                  u64 owner, u64 offset, int refs_to_add,
1703                                  struct btrfs_delayed_extent_op *extent_op)
1704 {
1705         struct extent_buffer *leaf;
1706         struct btrfs_extent_item *ei;
1707         unsigned long ptr;
1708         unsigned long end;
1709         unsigned long item_offset;
1710         u64 refs;
1711         int size;
1712         int type;
1713
1714         leaf = path->nodes[0];
1715         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1716         item_offset = (unsigned long)iref - (unsigned long)ei;
1717
1718         type = extent_ref_type(parent, owner);
1719         size = btrfs_extent_inline_ref_size(type);
1720
1721         btrfs_extend_item(path, size);
1722
1723         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1724         refs = btrfs_extent_refs(leaf, ei);
1725         refs += refs_to_add;
1726         btrfs_set_extent_refs(leaf, ei, refs);
1727         if (extent_op)
1728                 __run_delayed_extent_op(extent_op, leaf, ei);
1729
1730         ptr = (unsigned long)ei + item_offset;
1731         end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1732         if (ptr < end - size)
1733                 memmove_extent_buffer(leaf, ptr + size, ptr,
1734                                       end - size - ptr);
1735
1736         iref = (struct btrfs_extent_inline_ref *)ptr;
1737         btrfs_set_extent_inline_ref_type(leaf, iref, type);
1738         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1739                 struct btrfs_extent_data_ref *dref;
1740                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1741                 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1742                 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1743                 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1744                 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1745         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1746                 struct btrfs_shared_data_ref *sref;
1747                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1748                 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1749                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1750         } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1751                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1752         } else {
1753                 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1754         }
1755         btrfs_mark_buffer_dirty(leaf);
1756 }
1757
1758 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1759                                  struct btrfs_path *path,
1760                                  struct btrfs_extent_inline_ref **ref_ret,
1761                                  u64 bytenr, u64 num_bytes, u64 parent,
1762                                  u64 root_objectid, u64 owner, u64 offset)
1763 {
1764         int ret;
1765
1766         ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1767                                            num_bytes, parent, root_objectid,
1768                                            owner, offset, 0);
1769         if (ret != -ENOENT)
1770                 return ret;
1771
1772         btrfs_release_path(path);
1773         *ref_ret = NULL;
1774
1775         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1776                 ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1777                                             root_objectid);
1778         } else {
1779                 ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1780                                              root_objectid, owner, offset);
1781         }
1782         return ret;
1783 }
1784
1785 /*
1786  * helper to update/remove inline back ref
1787  */
1788 static noinline_for_stack
1789 void update_inline_extent_backref(struct btrfs_path *path,
1790                                   struct btrfs_extent_inline_ref *iref,
1791                                   int refs_to_mod,
1792                                   struct btrfs_delayed_extent_op *extent_op,
1793                                   int *last_ref)
1794 {
1795         struct extent_buffer *leaf = path->nodes[0];
1796         struct btrfs_extent_item *ei;
1797         struct btrfs_extent_data_ref *dref = NULL;
1798         struct btrfs_shared_data_ref *sref = NULL;
1799         unsigned long ptr;
1800         unsigned long end;
1801         u32 item_size;
1802         int size;
1803         int type;
1804         u64 refs;
1805
1806         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1807         refs = btrfs_extent_refs(leaf, ei);
1808         WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1809         refs += refs_to_mod;
1810         btrfs_set_extent_refs(leaf, ei, refs);
1811         if (extent_op)
1812                 __run_delayed_extent_op(extent_op, leaf, ei);
1813
1814         /*
1815          * If type is invalid, we should have bailed out after
1816          * lookup_inline_extent_backref().
1817          */
1818         type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1819         ASSERT(type != BTRFS_REF_TYPE_INVALID);
1820
1821         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1822                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1823                 refs = btrfs_extent_data_ref_count(leaf, dref);
1824         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1825                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1826                 refs = btrfs_shared_data_ref_count(leaf, sref);
1827         } else {
1828                 refs = 1;
1829                 BUG_ON(refs_to_mod != -1);
1830         }
1831
1832         BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1833         refs += refs_to_mod;
1834
1835         if (refs > 0) {
1836                 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1837                         btrfs_set_extent_data_ref_count(leaf, dref, refs);
1838                 else
1839                         btrfs_set_shared_data_ref_count(leaf, sref, refs);
1840         } else {
1841                 *last_ref = 1;
1842                 size =  btrfs_extent_inline_ref_size(type);
1843                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1844                 ptr = (unsigned long)iref;
1845                 end = (unsigned long)ei + item_size;
1846                 if (ptr + size < end)
1847                         memmove_extent_buffer(leaf, ptr, ptr + size,
1848                                               end - ptr - size);
1849                 item_size -= size;
1850                 btrfs_truncate_item(path, item_size, 1);
1851         }
1852         btrfs_mark_buffer_dirty(leaf);
1853 }
1854
1855 static noinline_for_stack
1856 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1857                                  struct btrfs_path *path,
1858                                  u64 bytenr, u64 num_bytes, u64 parent,
1859                                  u64 root_objectid, u64 owner,
1860                                  u64 offset, int refs_to_add,
1861                                  struct btrfs_delayed_extent_op *extent_op)
1862 {
1863         struct btrfs_extent_inline_ref *iref;
1864         int ret;
1865
1866         ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1867                                            num_bytes, parent, root_objectid,
1868                                            owner, offset, 1);
1869         if (ret == 0) {
1870                 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1871                 update_inline_extent_backref(path, iref, refs_to_add,
1872                                              extent_op, NULL);
1873         } else if (ret == -ENOENT) {
1874                 setup_inline_extent_backref(trans->fs_info, path, iref, parent,
1875                                             root_objectid, owner, offset,
1876                                             refs_to_add, extent_op);
1877                 ret = 0;
1878         }
1879         return ret;
1880 }
1881
1882 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1883                                  struct btrfs_path *path,
1884                                  u64 bytenr, u64 parent, u64 root_objectid,
1885                                  u64 owner, u64 offset, int refs_to_add)
1886 {
1887         int ret;
1888         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1889                 BUG_ON(refs_to_add != 1);
1890                 ret = insert_tree_block_ref(trans, path, bytenr, parent,
1891                                             root_objectid);
1892         } else {
1893                 ret = insert_extent_data_ref(trans, path, bytenr, parent,
1894                                              root_objectid, owner, offset,
1895                                              refs_to_add);
1896         }
1897         return ret;
1898 }
1899
1900 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1901                                  struct btrfs_path *path,
1902                                  struct btrfs_extent_inline_ref *iref,
1903                                  int refs_to_drop, int is_data, int *last_ref)
1904 {
1905         int ret = 0;
1906
1907         BUG_ON(!is_data && refs_to_drop != 1);
1908         if (iref) {
1909                 update_inline_extent_backref(path, iref, -refs_to_drop, NULL,
1910                                              last_ref);
1911         } else if (is_data) {
1912                 ret = remove_extent_data_ref(trans, path, refs_to_drop,
1913                                              last_ref);
1914         } else {
1915                 *last_ref = 1;
1916                 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1917         }
1918         return ret;
1919 }
1920
1921 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1922                                u64 *discarded_bytes)
1923 {
1924         int j, ret = 0;
1925         u64 bytes_left, end;
1926         u64 aligned_start = ALIGN(start, 1 << 9);
1927
1928         if (WARN_ON(start != aligned_start)) {
1929                 len -= aligned_start - start;
1930                 len = round_down(len, 1 << 9);
1931                 start = aligned_start;
1932         }
1933
1934         *discarded_bytes = 0;
1935
1936         if (!len)
1937                 return 0;
1938
1939         end = start + len;
1940         bytes_left = len;
1941
1942         /* Skip any superblocks on this device. */
1943         for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1944                 u64 sb_start = btrfs_sb_offset(j);
1945                 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1946                 u64 size = sb_start - start;
1947
1948                 if (!in_range(sb_start, start, bytes_left) &&
1949                     !in_range(sb_end, start, bytes_left) &&
1950                     !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1951                         continue;
1952
1953                 /*
1954                  * Superblock spans beginning of range.  Adjust start and
1955                  * try again.
1956                  */
1957                 if (sb_start <= start) {
1958                         start += sb_end - start;
1959                         if (start > end) {
1960                                 bytes_left = 0;
1961                                 break;
1962                         }
1963                         bytes_left = end - start;
1964                         continue;
1965                 }
1966
1967                 if (size) {
1968                         ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1969                                                    GFP_NOFS, 0);
1970                         if (!ret)
1971                                 *discarded_bytes += size;
1972                         else if (ret != -EOPNOTSUPP)
1973                                 return ret;
1974                 }
1975
1976                 start = sb_end;
1977                 if (start > end) {
1978                         bytes_left = 0;
1979                         break;
1980                 }
1981                 bytes_left = end - start;
1982         }
1983
1984         if (bytes_left) {
1985                 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
1986                                            GFP_NOFS, 0);
1987                 if (!ret)
1988                         *discarded_bytes += bytes_left;
1989         }
1990         return ret;
1991 }
1992
1993 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1994                          u64 num_bytes, u64 *actual_bytes)
1995 {
1996         int ret;
1997         u64 discarded_bytes = 0;
1998         struct btrfs_bio *bbio = NULL;
1999
2000
2001         /*
2002          * Avoid races with device replace and make sure our bbio has devices
2003          * associated to its stripes that don't go away while we are discarding.
2004          */
2005         btrfs_bio_counter_inc_blocked(fs_info);
2006         /* Tell the block device(s) that the sectors can be discarded */
2007         ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, bytenr, &num_bytes,
2008                               &bbio, 0);
2009         /* Error condition is -ENOMEM */
2010         if (!ret) {
2011                 struct btrfs_bio_stripe *stripe = bbio->stripes;
2012                 int i;
2013
2014
2015                 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
2016                         u64 bytes;
2017                         struct request_queue *req_q;
2018
2019                         if (!stripe->dev->bdev) {
2020                                 ASSERT(btrfs_test_opt(fs_info, DEGRADED));
2021                                 continue;
2022                         }
2023                         req_q = bdev_get_queue(stripe->dev->bdev);
2024                         if (!blk_queue_discard(req_q))
2025                                 continue;
2026
2027                         ret = btrfs_issue_discard(stripe->dev->bdev,
2028                                                   stripe->physical,
2029                                                   stripe->length,
2030                                                   &bytes);
2031                         if (!ret)
2032                                 discarded_bytes += bytes;
2033                         else if (ret != -EOPNOTSUPP)
2034                                 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
2035
2036                         /*
2037                          * Just in case we get back EOPNOTSUPP for some reason,
2038                          * just ignore the return value so we don't screw up
2039                          * people calling discard_extent.
2040                          */
2041                         ret = 0;
2042                 }
2043                 btrfs_put_bbio(bbio);
2044         }
2045         btrfs_bio_counter_dec(fs_info);
2046
2047         if (actual_bytes)
2048                 *actual_bytes = discarded_bytes;
2049
2050
2051         if (ret == -EOPNOTSUPP)
2052                 ret = 0;
2053         return ret;
2054 }
2055
2056 /* Can return -ENOMEM */
2057 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2058                          struct btrfs_ref *generic_ref)
2059 {
2060         struct btrfs_fs_info *fs_info = trans->fs_info;
2061         int old_ref_mod, new_ref_mod;
2062         int ret;
2063
2064         ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
2065                generic_ref->action);
2066         BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
2067                generic_ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID);
2068
2069         if (generic_ref->type == BTRFS_REF_METADATA)
2070                 ret = btrfs_add_delayed_tree_ref(trans, generic_ref,
2071                                 NULL, &old_ref_mod, &new_ref_mod);
2072         else
2073                 ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0,
2074                                                  &old_ref_mod, &new_ref_mod);
2075
2076         btrfs_ref_tree_mod(fs_info, generic_ref);
2077
2078         if (ret == 0 && old_ref_mod < 0 && new_ref_mod >= 0)
2079                 sub_pinned_bytes(fs_info, generic_ref);
2080
2081         return ret;
2082 }
2083
2084 /*
2085  * __btrfs_inc_extent_ref - insert backreference for a given extent
2086  *
2087  * @trans:          Handle of transaction
2088  *
2089  * @node:           The delayed ref node used to get the bytenr/length for
2090  *                  extent whose references are incremented.
2091  *
2092  * @parent:         If this is a shared extent (BTRFS_SHARED_DATA_REF_KEY/
2093  *                  BTRFS_SHARED_BLOCK_REF_KEY) then it holds the logical
2094  *                  bytenr of the parent block. Since new extents are always
2095  *                  created with indirect references, this will only be the case
2096  *                  when relocating a shared extent. In that case, root_objectid
2097  *                  will be BTRFS_TREE_RELOC_OBJECTID. Otheriwse, parent must
2098  *                  be 0
2099  *
2100  * @root_objectid:  The id of the root where this modification has originated,
2101  *                  this can be either one of the well-known metadata trees or
2102  *                  the subvolume id which references this extent.
2103  *
2104  * @owner:          For data extents it is the inode number of the owning file.
2105  *                  For metadata extents this parameter holds the level in the
2106  *                  tree of the extent.
2107  *
2108  * @offset:         For metadata extents the offset is ignored and is currently
2109  *                  always passed as 0. For data extents it is the fileoffset
2110  *                  this extent belongs to.
2111  *
2112  * @refs_to_add     Number of references to add
2113  *
2114  * @extent_op       Pointer to a structure, holding information necessary when
2115  *                  updating a tree block's flags
2116  *
2117  */
2118 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2119                                   struct btrfs_delayed_ref_node *node,
2120                                   u64 parent, u64 root_objectid,
2121                                   u64 owner, u64 offset, int refs_to_add,
2122                                   struct btrfs_delayed_extent_op *extent_op)
2123 {
2124         struct btrfs_path *path;
2125         struct extent_buffer *leaf;
2126         struct btrfs_extent_item *item;
2127         struct btrfs_key key;
2128         u64 bytenr = node->bytenr;
2129         u64 num_bytes = node->num_bytes;
2130         u64 refs;
2131         int ret;
2132
2133         path = btrfs_alloc_path();
2134         if (!path)
2135                 return -ENOMEM;
2136
2137         path->reada = READA_FORWARD;
2138         path->leave_spinning = 1;
2139         /* this will setup the path even if it fails to insert the back ref */
2140         ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
2141                                            parent, root_objectid, owner,
2142                                            offset, refs_to_add, extent_op);
2143         if ((ret < 0 && ret != -EAGAIN) || !ret)
2144                 goto out;
2145
2146         /*
2147          * Ok we had -EAGAIN which means we didn't have space to insert and
2148          * inline extent ref, so just update the reference count and add a
2149          * normal backref.
2150          */
2151         leaf = path->nodes[0];
2152         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2153         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2154         refs = btrfs_extent_refs(leaf, item);
2155         btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2156         if (extent_op)
2157                 __run_delayed_extent_op(extent_op, leaf, item);
2158
2159         btrfs_mark_buffer_dirty(leaf);
2160         btrfs_release_path(path);
2161
2162         path->reada = READA_FORWARD;
2163         path->leave_spinning = 1;
2164         /* now insert the actual backref */
2165         ret = insert_extent_backref(trans, path, bytenr, parent, root_objectid,
2166                                     owner, offset, refs_to_add);
2167         if (ret)
2168                 btrfs_abort_transaction(trans, ret);
2169 out:
2170         btrfs_free_path(path);
2171         return ret;
2172 }
2173
2174 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2175                                 struct btrfs_delayed_ref_node *node,
2176                                 struct btrfs_delayed_extent_op *extent_op,
2177                                 int insert_reserved)
2178 {
2179         int ret = 0;
2180         struct btrfs_delayed_data_ref *ref;
2181         struct btrfs_key ins;
2182         u64 parent = 0;
2183         u64 ref_root = 0;
2184         u64 flags = 0;
2185
2186         ins.objectid = node->bytenr;
2187         ins.offset = node->num_bytes;
2188         ins.type = BTRFS_EXTENT_ITEM_KEY;
2189
2190         ref = btrfs_delayed_node_to_data_ref(node);
2191         trace_run_delayed_data_ref(trans->fs_info, node, ref, node->action);
2192
2193         if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2194                 parent = ref->parent;
2195         ref_root = ref->root;
2196
2197         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2198                 if (extent_op)
2199                         flags |= extent_op->flags_to_set;
2200                 ret = alloc_reserved_file_extent(trans, parent, ref_root,
2201                                                  flags, ref->objectid,
2202                                                  ref->offset, &ins,
2203                                                  node->ref_mod);
2204         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2205                 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2206                                              ref->objectid, ref->offset,
2207                                              node->ref_mod, extent_op);
2208         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2209                 ret = __btrfs_free_extent(trans, node, parent,
2210                                           ref_root, ref->objectid,
2211                                           ref->offset, node->ref_mod,
2212                                           extent_op);
2213         } else {
2214                 BUG();
2215         }
2216         return ret;
2217 }
2218
2219 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2220                                     struct extent_buffer *leaf,
2221                                     struct btrfs_extent_item *ei)
2222 {
2223         u64 flags = btrfs_extent_flags(leaf, ei);
2224         if (extent_op->update_flags) {
2225                 flags |= extent_op->flags_to_set;
2226                 btrfs_set_extent_flags(leaf, ei, flags);
2227         }
2228
2229         if (extent_op->update_key) {
2230                 struct btrfs_tree_block_info *bi;
2231                 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2232                 bi = (struct btrfs_tree_block_info *)(ei + 1);
2233                 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2234         }
2235 }
2236
2237 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2238                                  struct btrfs_delayed_ref_head *head,
2239                                  struct btrfs_delayed_extent_op *extent_op)
2240 {
2241         struct btrfs_fs_info *fs_info = trans->fs_info;
2242         struct btrfs_key key;
2243         struct btrfs_path *path;
2244         struct btrfs_extent_item *ei;
2245         struct extent_buffer *leaf;
2246         u32 item_size;
2247         int ret;
2248         int err = 0;
2249         int metadata = !extent_op->is_data;
2250
2251         if (trans->aborted)
2252                 return 0;
2253
2254         if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2255                 metadata = 0;
2256
2257         path = btrfs_alloc_path();
2258         if (!path)
2259                 return -ENOMEM;
2260
2261         key.objectid = head->bytenr;
2262
2263         if (metadata) {
2264                 key.type = BTRFS_METADATA_ITEM_KEY;
2265                 key.offset = extent_op->level;
2266         } else {
2267                 key.type = BTRFS_EXTENT_ITEM_KEY;
2268                 key.offset = head->num_bytes;
2269         }
2270
2271 again:
2272         path->reada = READA_FORWARD;
2273         path->leave_spinning = 1;
2274         ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
2275         if (ret < 0) {
2276                 err = ret;
2277                 goto out;
2278         }
2279         if (ret > 0) {
2280                 if (metadata) {
2281                         if (path->slots[0] > 0) {
2282                                 path->slots[0]--;
2283                                 btrfs_item_key_to_cpu(path->nodes[0], &key,
2284                                                       path->slots[0]);
2285                                 if (key.objectid == head->bytenr &&
2286                                     key.type == BTRFS_EXTENT_ITEM_KEY &&
2287                                     key.offset == head->num_bytes)
2288                                         ret = 0;
2289                         }
2290                         if (ret > 0) {
2291                                 btrfs_release_path(path);
2292                                 metadata = 0;
2293
2294                                 key.objectid = head->bytenr;
2295                                 key.offset = head->num_bytes;
2296                                 key.type = BTRFS_EXTENT_ITEM_KEY;
2297                                 goto again;
2298                         }
2299                 } else {
2300                         err = -EIO;
2301                         goto out;
2302                 }
2303         }
2304
2305         leaf = path->nodes[0];
2306         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2307
2308         if (unlikely(item_size < sizeof(*ei))) {
2309                 err = -EINVAL;
2310                 btrfs_print_v0_err(fs_info);
2311                 btrfs_abort_transaction(trans, err);
2312                 goto out;
2313         }
2314
2315         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2316         __run_delayed_extent_op(extent_op, leaf, ei);
2317
2318         btrfs_mark_buffer_dirty(leaf);
2319 out:
2320         btrfs_free_path(path);
2321         return err;
2322 }
2323
2324 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2325                                 struct btrfs_delayed_ref_node *node,
2326                                 struct btrfs_delayed_extent_op *extent_op,
2327                                 int insert_reserved)
2328 {
2329         int ret = 0;
2330         struct btrfs_delayed_tree_ref *ref;
2331         u64 parent = 0;
2332         u64 ref_root = 0;
2333
2334         ref = btrfs_delayed_node_to_tree_ref(node);
2335         trace_run_delayed_tree_ref(trans->fs_info, node, ref, node->action);
2336
2337         if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2338                 parent = ref->parent;
2339         ref_root = ref->root;
2340
2341         if (node->ref_mod != 1) {
2342                 btrfs_err(trans->fs_info,
2343         "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
2344                           node->bytenr, node->ref_mod, node->action, ref_root,
2345                           parent);
2346                 return -EIO;
2347         }
2348         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2349                 BUG_ON(!extent_op || !extent_op->update_flags);
2350                 ret = alloc_reserved_tree_block(trans, node, extent_op);
2351         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2352                 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2353                                              ref->level, 0, 1, extent_op);
2354         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2355                 ret = __btrfs_free_extent(trans, node, parent, ref_root,
2356                                           ref->level, 0, 1, extent_op);
2357         } else {
2358                 BUG();
2359         }
2360         return ret;
2361 }
2362
2363 /* helper function to actually process a single delayed ref entry */
2364 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2365                                struct btrfs_delayed_ref_node *node,
2366                                struct btrfs_delayed_extent_op *extent_op,
2367                                int insert_reserved)
2368 {
2369         int ret = 0;
2370
2371         if (trans->aborted) {
2372                 if (insert_reserved)
2373                         btrfs_pin_extent(trans->fs_info, node->bytenr,
2374                                          node->num_bytes, 1);
2375                 return 0;
2376         }
2377
2378         if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2379             node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2380                 ret = run_delayed_tree_ref(trans, node, extent_op,
2381                                            insert_reserved);
2382         else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2383                  node->type == BTRFS_SHARED_DATA_REF_KEY)
2384                 ret = run_delayed_data_ref(trans, node, extent_op,
2385                                            insert_reserved);
2386         else
2387                 BUG();
2388         if (ret && insert_reserved)
2389                 btrfs_pin_extent(trans->fs_info, node->bytenr,
2390                                  node->num_bytes, 1);
2391         return ret;
2392 }
2393
2394 static inline struct btrfs_delayed_ref_node *
2395 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2396 {
2397         struct btrfs_delayed_ref_node *ref;
2398
2399         if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
2400                 return NULL;
2401
2402         /*
2403          * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
2404          * This is to prevent a ref count from going down to zero, which deletes
2405          * the extent item from the extent tree, when there still are references
2406          * to add, which would fail because they would not find the extent item.
2407          */
2408         if (!list_empty(&head->ref_add_list))
2409                 return list_first_entry(&head->ref_add_list,
2410                                 struct btrfs_delayed_ref_node, add_list);
2411
2412         ref = rb_entry(rb_first_cached(&head->ref_tree),
2413                        struct btrfs_delayed_ref_node, ref_node);
2414         ASSERT(list_empty(&ref->add_list));
2415         return ref;
2416 }
2417
2418 static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
2419                                       struct btrfs_delayed_ref_head *head)
2420 {
2421         spin_lock(&delayed_refs->lock);
2422         head->processing = 0;
2423         delayed_refs->num_heads_ready++;
2424         spin_unlock(&delayed_refs->lock);
2425         btrfs_delayed_ref_unlock(head);
2426 }
2427
2428 static struct btrfs_delayed_extent_op *cleanup_extent_op(
2429                                 struct btrfs_delayed_ref_head *head)
2430 {
2431         struct btrfs_delayed_extent_op *extent_op = head->extent_op;
2432
2433         if (!extent_op)
2434                 return NULL;
2435
2436         if (head->must_insert_reserved) {
2437                 head->extent_op = NULL;
2438                 btrfs_free_delayed_extent_op(extent_op);
2439                 return NULL;
2440         }
2441         return extent_op;
2442 }
2443
2444 static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
2445                                      struct btrfs_delayed_ref_head *head)
2446 {
2447         struct btrfs_delayed_extent_op *extent_op;
2448         int ret;
2449
2450         extent_op = cleanup_extent_op(head);
2451         if (!extent_op)
2452                 return 0;
2453         head->extent_op = NULL;
2454         spin_unlock(&head->lock);
2455         ret = run_delayed_extent_op(trans, head, extent_op);
2456         btrfs_free_delayed_extent_op(extent_op);
2457         return ret ? ret : 1;
2458 }
2459
2460 void btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
2461                                   struct btrfs_delayed_ref_root *delayed_refs,
2462                                   struct btrfs_delayed_ref_head *head)
2463 {
2464         int nr_items = 1;       /* Dropping this ref head update. */
2465
2466         if (head->total_ref_mod < 0) {
2467                 struct btrfs_space_info *space_info;
2468                 u64 flags;
2469
2470                 if (head->is_data)
2471                         flags = BTRFS_BLOCK_GROUP_DATA;
2472                 else if (head->is_system)
2473                         flags = BTRFS_BLOCK_GROUP_SYSTEM;
2474                 else
2475                         flags = BTRFS_BLOCK_GROUP_METADATA;
2476                 space_info = __find_space_info(fs_info, flags);
2477                 ASSERT(space_info);
2478                 percpu_counter_add_batch(&space_info->total_bytes_pinned,
2479                                    -head->num_bytes,
2480                                    BTRFS_TOTAL_BYTES_PINNED_BATCH);
2481
2482                 /*
2483                  * We had csum deletions accounted for in our delayed refs rsv,
2484                  * we need to drop the csum leaves for this update from our
2485                  * delayed_refs_rsv.
2486                  */
2487                 if (head->is_data) {
2488                         spin_lock(&delayed_refs->lock);
2489                         delayed_refs->pending_csums -= head->num_bytes;
2490                         spin_unlock(&delayed_refs->lock);
2491                         nr_items += btrfs_csum_bytes_to_leaves(fs_info,
2492                                 head->num_bytes);
2493                 }
2494         }
2495
2496         btrfs_delayed_refs_rsv_release(fs_info, nr_items);
2497 }
2498
2499 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
2500                             struct btrfs_delayed_ref_head *head)
2501 {
2502
2503         struct btrfs_fs_info *fs_info = trans->fs_info;
2504         struct btrfs_delayed_ref_root *delayed_refs;
2505         int ret;
2506
2507         delayed_refs = &trans->transaction->delayed_refs;
2508
2509         ret = run_and_cleanup_extent_op(trans, head);
2510         if (ret < 0) {
2511                 unselect_delayed_ref_head(delayed_refs, head);
2512                 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
2513                 return ret;
2514         } else if (ret) {
2515                 return ret;
2516         }
2517
2518         /*
2519          * Need to drop our head ref lock and re-acquire the delayed ref lock
2520          * and then re-check to make sure nobody got added.
2521          */
2522         spin_unlock(&head->lock);
2523         spin_lock(&delayed_refs->lock);
2524         spin_lock(&head->lock);
2525         if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
2526                 spin_unlock(&head->lock);
2527                 spin_unlock(&delayed_refs->lock);
2528                 return 1;
2529         }
2530         btrfs_delete_ref_head(delayed_refs, head);
2531         spin_unlock(&head->lock);
2532         spin_unlock(&delayed_refs->lock);
2533
2534         if (head->must_insert_reserved) {
2535                 btrfs_pin_extent(fs_info, head->bytenr,
2536                                  head->num_bytes, 1);
2537                 if (head->is_data) {
2538                         ret = btrfs_del_csums(trans, fs_info, head->bytenr,
2539                                               head->num_bytes);
2540                 }
2541         }
2542
2543         btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
2544
2545         trace_run_delayed_ref_head(fs_info, head, 0);
2546         btrfs_delayed_ref_unlock(head);
2547         btrfs_put_delayed_ref_head(head);
2548         return 0;
2549 }
2550
2551 static struct btrfs_delayed_ref_head *btrfs_obtain_ref_head(
2552                                         struct btrfs_trans_handle *trans)
2553 {
2554         struct btrfs_delayed_ref_root *delayed_refs =
2555                 &trans->transaction->delayed_refs;
2556         struct btrfs_delayed_ref_head *head = NULL;
2557         int ret;
2558
2559         spin_lock(&delayed_refs->lock);
2560         head = btrfs_select_ref_head(delayed_refs);
2561         if (!head) {
2562                 spin_unlock(&delayed_refs->lock);
2563                 return head;
2564         }
2565
2566         /*
2567          * Grab the lock that says we are going to process all the refs for
2568          * this head
2569          */
2570         ret = btrfs_delayed_ref_lock(delayed_refs, head);
2571         spin_unlock(&delayed_refs->lock);
2572
2573         /*
2574          * We may have dropped the spin lock to get the head mutex lock, and
2575          * that might have given someone else time to free the head.  If that's
2576          * true, it has been removed from our list and we can move on.
2577          */
2578         if (ret == -EAGAIN)
2579                 head = ERR_PTR(-EAGAIN);
2580
2581         return head;
2582 }
2583
2584 static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
2585                                     struct btrfs_delayed_ref_head *locked_ref,
2586                                     unsigned long *run_refs)
2587 {
2588         struct btrfs_fs_info *fs_info = trans->fs_info;
2589         struct btrfs_delayed_ref_root *delayed_refs;
2590         struct btrfs_delayed_extent_op *extent_op;
2591         struct btrfs_delayed_ref_node *ref;
2592         int must_insert_reserved = 0;
2593         int ret;
2594
2595         delayed_refs = &trans->transaction->delayed_refs;
2596
2597         lockdep_assert_held(&locked_ref->mutex);
2598         lockdep_assert_held(&locked_ref->lock);
2599
2600         while ((ref = select_delayed_ref(locked_ref))) {
2601                 if (ref->seq &&
2602                     btrfs_check_delayed_seq(fs_info, ref->seq)) {
2603                         spin_unlock(&locked_ref->lock);
2604                         unselect_delayed_ref_head(delayed_refs, locked_ref);
2605                         return -EAGAIN;
2606                 }
2607
2608                 (*run_refs)++;
2609                 ref->in_tree = 0;
2610                 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
2611                 RB_CLEAR_NODE(&ref->ref_node);
2612                 if (!list_empty(&ref->add_list))
2613                         list_del(&ref->add_list);
2614                 /*
2615                  * When we play the delayed ref, also correct the ref_mod on
2616                  * head
2617                  */
2618                 switch (ref->action) {
2619                 case BTRFS_ADD_DELAYED_REF:
2620                 case BTRFS_ADD_DELAYED_EXTENT:
2621                         locked_ref->ref_mod -= ref->ref_mod;
2622                         break;
2623                 case BTRFS_DROP_DELAYED_REF:
2624                         locked_ref->ref_mod += ref->ref_mod;
2625                         break;
2626                 default:
2627                         WARN_ON(1);
2628                 }
2629                 atomic_dec(&delayed_refs->num_entries);
2630
2631                 /*
2632                  * Record the must_insert_reserved flag before we drop the
2633                  * spin lock.
2634                  */
2635                 must_insert_reserved = locked_ref->must_insert_reserved;
2636                 locked_ref->must_insert_reserved = 0;
2637
2638                 extent_op = locked_ref->extent_op;
2639                 locked_ref->extent_op = NULL;
2640                 spin_unlock(&locked_ref->lock);
2641
2642                 ret = run_one_delayed_ref(trans, ref, extent_op,
2643                                           must_insert_reserved);
2644
2645                 btrfs_free_delayed_extent_op(extent_op);
2646                 if (ret) {
2647                         unselect_delayed_ref_head(delayed_refs, locked_ref);
2648                         btrfs_put_delayed_ref(ref);
2649                         btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
2650                                     ret);
2651                         return ret;
2652                 }
2653
2654                 btrfs_put_delayed_ref(ref);
2655                 cond_resched();
2656
2657                 spin_lock(&locked_ref->lock);
2658                 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2659         }
2660
2661         return 0;
2662 }
2663
2664 /*
2665  * Returns 0 on success or if called with an already aborted transaction.
2666  * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2667  */
2668 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2669                                              unsigned long nr)
2670 {
2671         struct btrfs_fs_info *fs_info = trans->fs_info;
2672         struct btrfs_delayed_ref_root *delayed_refs;
2673         struct btrfs_delayed_ref_head *locked_ref = NULL;
2674         ktime_t start = ktime_get();
2675         int ret;
2676         unsigned long count = 0;
2677         unsigned long actual_count = 0;
2678
2679         delayed_refs = &trans->transaction->delayed_refs;
2680         do {
2681                 if (!locked_ref) {
2682                         locked_ref = btrfs_obtain_ref_head(trans);
2683                         if (IS_ERR_OR_NULL(locked_ref)) {
2684                                 if (PTR_ERR(locked_ref) == -EAGAIN) {
2685                                         continue;
2686                                 } else {
2687                                         break;
2688                                 }
2689                         }
2690                         count++;
2691                 }
2692                 /*
2693                  * We need to try and merge add/drops of the same ref since we
2694                  * can run into issues with relocate dropping the implicit ref
2695                  * and then it being added back again before the drop can
2696                  * finish.  If we merged anything we need to re-loop so we can
2697                  * get a good ref.
2698                  * Or we can get node references of the same type that weren't
2699                  * merged when created due to bumps in the tree mod seq, and
2700                  * we need to merge them to prevent adding an inline extent
2701                  * backref before dropping it (triggering a BUG_ON at
2702                  * insert_inline_extent_backref()).
2703                  */
2704                 spin_lock(&locked_ref->lock);
2705                 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2706
2707                 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref,
2708                                                       &actual_count);
2709                 if (ret < 0 && ret != -EAGAIN) {
2710                         /*
2711                          * Error, btrfs_run_delayed_refs_for_head already
2712                          * unlocked everything so just bail out
2713                          */
2714                         return ret;
2715                 } else if (!ret) {
2716                         /*
2717                          * Success, perform the usual cleanup of a processed
2718                          * head
2719                          */
2720                         ret = cleanup_ref_head(trans, locked_ref);
2721                         if (ret > 0 ) {
2722                                 /* We dropped our lock, we need to loop. */
2723                                 ret = 0;
2724                                 continue;
2725                         } else if (ret) {
2726                                 return ret;
2727                         }
2728                 }
2729
2730                 /*
2731                  * Either success case or btrfs_run_delayed_refs_for_head
2732                  * returned -EAGAIN, meaning we need to select another head
2733                  */
2734
2735                 locked_ref = NULL;
2736                 cond_resched();
2737         } while ((nr != -1 && count < nr) || locked_ref);
2738
2739         /*
2740          * We don't want to include ref heads since we can have empty ref heads
2741          * and those will drastically skew our runtime down since we just do
2742          * accounting, no actual extent tree updates.
2743          */
2744         if (actual_count > 0) {
2745                 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2746                 u64 avg;
2747
2748                 /*
2749                  * We weigh the current average higher than our current runtime
2750                  * to avoid large swings in the average.
2751                  */
2752                 spin_lock(&delayed_refs->lock);
2753                 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2754                 fs_info->avg_delayed_ref_runtime = avg >> 2;    /* div by 4 */
2755                 spin_unlock(&delayed_refs->lock);
2756         }
2757         return 0;
2758 }
2759
2760 #ifdef SCRAMBLE_DELAYED_REFS
2761 /*
2762  * Normally delayed refs get processed in ascending bytenr order. This
2763  * correlates in most cases to the order added. To expose dependencies on this
2764  * order, we start to process the tree in the middle instead of the beginning
2765  */
2766 static u64 find_middle(struct rb_root *root)
2767 {
2768         struct rb_node *n = root->rb_node;
2769         struct btrfs_delayed_ref_node *entry;
2770         int alt = 1;
2771         u64 middle;
2772         u64 first = 0, last = 0;
2773
2774         n = rb_first(root);
2775         if (n) {
2776                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2777                 first = entry->bytenr;
2778         }
2779         n = rb_last(root);
2780         if (n) {
2781                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2782                 last = entry->bytenr;
2783         }
2784         n = root->rb_node;
2785
2786         while (n) {
2787                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2788                 WARN_ON(!entry->in_tree);
2789
2790                 middle = entry->bytenr;
2791
2792                 if (alt)
2793                         n = n->rb_left;
2794                 else
2795                         n = n->rb_right;
2796
2797                 alt = 1 - alt;
2798         }
2799         return middle;
2800 }
2801 #endif
2802
2803 static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
2804 {
2805         u64 num_bytes;
2806
2807         num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2808                              sizeof(struct btrfs_extent_inline_ref));
2809         if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2810                 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2811
2812         /*
2813          * We don't ever fill up leaves all the way so multiply by 2 just to be
2814          * closer to what we're really going to want to use.
2815          */
2816         return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
2817 }
2818
2819 /*
2820  * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2821  * would require to store the csums for that many bytes.
2822  */
2823 u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
2824 {
2825         u64 csum_size;
2826         u64 num_csums_per_leaf;
2827         u64 num_csums;
2828
2829         csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
2830         num_csums_per_leaf = div64_u64(csum_size,
2831                         (u64)btrfs_super_csum_size(fs_info->super_copy));
2832         num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
2833         num_csums += num_csums_per_leaf - 1;
2834         num_csums = div64_u64(num_csums, num_csums_per_leaf);
2835         return num_csums;
2836 }
2837
2838 bool btrfs_check_space_for_delayed_refs(struct btrfs_fs_info *fs_info)
2839 {
2840         struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
2841         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
2842         bool ret = false;
2843         u64 reserved;
2844
2845         spin_lock(&global_rsv->lock);
2846         reserved = global_rsv->reserved;
2847         spin_unlock(&global_rsv->lock);
2848
2849         /*
2850          * Since the global reserve is just kind of magic we don't really want
2851          * to rely on it to save our bacon, so if our size is more than the
2852          * delayed_refs_rsv and the global rsv then it's time to think about
2853          * bailing.
2854          */
2855         spin_lock(&delayed_refs_rsv->lock);
2856         reserved += delayed_refs_rsv->reserved;
2857         if (delayed_refs_rsv->size >= reserved)
2858                 ret = true;
2859         spin_unlock(&delayed_refs_rsv->lock);
2860         return ret;
2861 }
2862
2863 int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans)
2864 {
2865         u64 num_entries =
2866                 atomic_read(&trans->transaction->delayed_refs.num_entries);
2867         u64 avg_runtime;
2868         u64 val;
2869
2870         smp_mb();
2871         avg_runtime = trans->fs_info->avg_delayed_ref_runtime;
2872         val = num_entries * avg_runtime;
2873         if (val >= NSEC_PER_SEC)
2874                 return 1;
2875         if (val >= NSEC_PER_SEC / 2)
2876                 return 2;
2877
2878         return btrfs_check_space_for_delayed_refs(trans->fs_info);
2879 }
2880
2881 /*
2882  * this starts processing the delayed reference count updates and
2883  * extent insertions we have queued up so far.  count can be
2884  * 0, which means to process everything in the tree at the start
2885  * of the run (but not newly added entries), or it can be some target
2886  * number you'd like to process.
2887  *
2888  * Returns 0 on success or if called with an aborted transaction
2889  * Returns <0 on error and aborts the transaction
2890  */
2891 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2892                            unsigned long count)
2893 {
2894         struct btrfs_fs_info *fs_info = trans->fs_info;
2895         struct rb_node *node;
2896         struct btrfs_delayed_ref_root *delayed_refs;
2897         struct btrfs_delayed_ref_head *head;
2898         int ret;
2899         int run_all = count == (unsigned long)-1;
2900
2901         /* We'll clean this up in btrfs_cleanup_transaction */
2902         if (trans->aborted)
2903                 return 0;
2904
2905         if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2906                 return 0;
2907
2908         delayed_refs = &trans->transaction->delayed_refs;
2909         if (count == 0)
2910                 count = atomic_read(&delayed_refs->num_entries) * 2;
2911
2912 again:
2913 #ifdef SCRAMBLE_DELAYED_REFS
2914         delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2915 #endif
2916         ret = __btrfs_run_delayed_refs(trans, count);
2917         if (ret < 0) {
2918                 btrfs_abort_transaction(trans, ret);
2919                 return ret;
2920         }
2921
2922         if (run_all) {
2923                 btrfs_create_pending_block_groups(trans);
2924
2925                 spin_lock(&delayed_refs->lock);
2926                 node = rb_first_cached(&delayed_refs->href_root);
2927                 if (!node) {
2928                         spin_unlock(&delayed_refs->lock);
2929                         goto out;
2930                 }
2931                 head = rb_entry(node, struct btrfs_delayed_ref_head,
2932                                 href_node);
2933                 refcount_inc(&head->refs);
2934                 spin_unlock(&delayed_refs->lock);
2935
2936                 /* Mutex was contended, block until it's released and retry. */
2937                 mutex_lock(&head->mutex);
2938                 mutex_unlock(&head->mutex);
2939
2940                 btrfs_put_delayed_ref_head(head);
2941                 cond_resched();
2942                 goto again;
2943         }
2944 out:
2945         return 0;
2946 }
2947
2948 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2949                                 u64 bytenr, u64 num_bytes, u64 flags,
2950                                 int level, int is_data)
2951 {
2952         struct btrfs_delayed_extent_op *extent_op;
2953         int ret;
2954
2955         extent_op = btrfs_alloc_delayed_extent_op();
2956         if (!extent_op)
2957                 return -ENOMEM;
2958
2959         extent_op->flags_to_set = flags;
2960         extent_op->update_flags = true;
2961         extent_op->update_key = false;
2962         extent_op->is_data = is_data ? true : false;
2963         extent_op->level = level;
2964
2965         ret = btrfs_add_delayed_extent_op(trans, bytenr, num_bytes, extent_op);
2966         if (ret)
2967                 btrfs_free_delayed_extent_op(extent_op);
2968         return ret;
2969 }
2970
2971 static noinline int check_delayed_ref(struct btrfs_root *root,
2972                                       struct btrfs_path *path,
2973                                       u64 objectid, u64 offset, u64 bytenr)
2974 {
2975         struct btrfs_delayed_ref_head *head;
2976         struct btrfs_delayed_ref_node *ref;
2977         struct btrfs_delayed_data_ref *data_ref;
2978         struct btrfs_delayed_ref_root *delayed_refs;
2979         struct btrfs_transaction *cur_trans;
2980         struct rb_node *node;
2981         int ret = 0;
2982
2983         spin_lock(&root->fs_info->trans_lock);
2984         cur_trans = root->fs_info->running_transaction;
2985         if (cur_trans)
2986                 refcount_inc(&cur_trans->use_count);
2987         spin_unlock(&root->fs_info->trans_lock);
2988         if (!cur_trans)
2989                 return 0;
2990
2991         delayed_refs = &cur_trans->delayed_refs;
2992         spin_lock(&delayed_refs->lock);
2993         head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
2994         if (!head) {
2995                 spin_unlock(&delayed_refs->lock);
2996                 btrfs_put_transaction(cur_trans);
2997                 return 0;
2998         }
2999
3000         if (!mutex_trylock(&head->mutex)) {
3001                 refcount_inc(&head->refs);
3002                 spin_unlock(&delayed_refs->lock);
3003
3004                 btrfs_release_path(path);
3005
3006                 /*
3007                  * Mutex was contended, block until it's released and let
3008                  * caller try again
3009                  */
3010                 mutex_lock(&head->mutex);
3011                 mutex_unlock(&head->mutex);
3012                 btrfs_put_delayed_ref_head(head);
3013                 btrfs_put_transaction(cur_trans);
3014                 return -EAGAIN;
3015         }
3016         spin_unlock(&delayed_refs->lock);
3017
3018         spin_lock(&head->lock);
3019         /*
3020          * XXX: We should replace this with a proper search function in the
3021          * future.
3022          */
3023         for (node = rb_first_cached(&head->ref_tree); node;
3024              node = rb_next(node)) {
3025                 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
3026                 /* If it's a shared ref we know a cross reference exists */
3027                 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
3028                         ret = 1;
3029                         break;
3030                 }
3031
3032                 data_ref = btrfs_delayed_node_to_data_ref(ref);
3033
3034                 /*
3035                  * If our ref doesn't match the one we're currently looking at
3036                  * then we have a cross reference.
3037                  */
3038                 if (data_ref->root != root->root_key.objectid ||
3039                     data_ref->objectid != objectid ||
3040                     data_ref->offset != offset) {
3041                         ret = 1;
3042                         break;
3043                 }
3044         }
3045         spin_unlock(&head->lock);
3046         mutex_unlock(&head->mutex);
3047         btrfs_put_transaction(cur_trans);
3048         return ret;
3049 }
3050
3051 static noinline int check_committed_ref(struct btrfs_root *root,
3052                                         struct btrfs_path *path,
3053                                         u64 objectid, u64 offset, u64 bytenr)
3054 {
3055         struct btrfs_fs_info *fs_info = root->fs_info;
3056         struct btrfs_root *extent_root = fs_info->extent_root;
3057         struct extent_buffer *leaf;
3058         struct btrfs_extent_data_ref *ref;
3059         struct btrfs_extent_inline_ref *iref;
3060         struct btrfs_extent_item *ei;
3061         struct btrfs_key key;
3062         u32 item_size;
3063         int type;
3064         int ret;
3065
3066         key.objectid = bytenr;
3067         key.offset = (u64)-1;
3068         key.type = BTRFS_EXTENT_ITEM_KEY;
3069
3070         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
3071         if (ret < 0)
3072                 goto out;
3073         BUG_ON(ret == 0); /* Corruption */
3074
3075         ret = -ENOENT;
3076         if (path->slots[0] == 0)
3077                 goto out;
3078
3079         path->slots[0]--;
3080         leaf = path->nodes[0];
3081         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3082
3083         if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
3084                 goto out;
3085
3086         ret = 1;
3087         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3088         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
3089