btrfs: Remove fs_info from __btrfs_free_extent
[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 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
55                                struct btrfs_delayed_ref_node *node, u64 parent,
56                                u64 root_objectid, u64 owner_objectid,
57                                u64 owner_offset, int refs_to_drop,
58                                struct btrfs_delayed_extent_op *extra_op);
59 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
60                                     struct extent_buffer *leaf,
61                                     struct btrfs_extent_item *ei);
62 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
63                                       struct btrfs_fs_info *fs_info,
64                                       u64 parent, u64 root_objectid,
65                                       u64 flags, u64 owner, u64 offset,
66                                       struct btrfs_key *ins, int ref_mod);
67 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
68                                      struct btrfs_delayed_ref_node *node,
69                                      struct btrfs_delayed_extent_op *extent_op);
70 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
71                           struct btrfs_fs_info *fs_info, u64 flags,
72                           int force);
73 static int find_next_key(struct btrfs_path *path, int level,
74                          struct btrfs_key *key);
75 static void dump_space_info(struct btrfs_fs_info *fs_info,
76                             struct btrfs_space_info *info, u64 bytes,
77                             int dump_block_groups);
78 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
79                                u64 num_bytes);
80 static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
81                                      struct btrfs_space_info *space_info,
82                                      u64 num_bytes);
83 static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
84                                      struct btrfs_space_info *space_info,
85                                      u64 num_bytes);
86
87 static noinline int
88 block_group_cache_done(struct btrfs_block_group_cache *cache)
89 {
90         smp_mb();
91         return cache->cached == BTRFS_CACHE_FINISHED ||
92                 cache->cached == BTRFS_CACHE_ERROR;
93 }
94
95 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
96 {
97         return (cache->flags & bits) == bits;
98 }
99
100 void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
101 {
102         atomic_inc(&cache->count);
103 }
104
105 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
106 {
107         if (atomic_dec_and_test(&cache->count)) {
108                 WARN_ON(cache->pinned > 0);
109                 WARN_ON(cache->reserved > 0);
110
111                 /*
112                  * If not empty, someone is still holding mutex of
113                  * full_stripe_lock, which can only be released by caller.
114                  * And it will definitely cause use-after-free when caller
115                  * tries to release full stripe lock.
116                  *
117                  * No better way to resolve, but only to warn.
118                  */
119                 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
120                 kfree(cache->free_space_ctl);
121                 kfree(cache);
122         }
123 }
124
125 /*
126  * this adds the block group to the fs_info rb tree for the block group
127  * cache
128  */
129 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
130                                 struct btrfs_block_group_cache *block_group)
131 {
132         struct rb_node **p;
133         struct rb_node *parent = NULL;
134         struct btrfs_block_group_cache *cache;
135
136         spin_lock(&info->block_group_cache_lock);
137         p = &info->block_group_cache_tree.rb_node;
138
139         while (*p) {
140                 parent = *p;
141                 cache = rb_entry(parent, struct btrfs_block_group_cache,
142                                  cache_node);
143                 if (block_group->key.objectid < cache->key.objectid) {
144                         p = &(*p)->rb_left;
145                 } else if (block_group->key.objectid > cache->key.objectid) {
146                         p = &(*p)->rb_right;
147                 } else {
148                         spin_unlock(&info->block_group_cache_lock);
149                         return -EEXIST;
150                 }
151         }
152
153         rb_link_node(&block_group->cache_node, parent, p);
154         rb_insert_color(&block_group->cache_node,
155                         &info->block_group_cache_tree);
156
157         if (info->first_logical_byte > block_group->key.objectid)
158                 info->first_logical_byte = block_group->key.objectid;
159
160         spin_unlock(&info->block_group_cache_lock);
161
162         return 0;
163 }
164
165 /*
166  * This will return the block group at or after bytenr if contains is 0, else
167  * it will return the block group that contains the bytenr
168  */
169 static struct btrfs_block_group_cache *
170 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
171                               int contains)
172 {
173         struct btrfs_block_group_cache *cache, *ret = NULL;
174         struct rb_node *n;
175         u64 end, start;
176
177         spin_lock(&info->block_group_cache_lock);
178         n = info->block_group_cache_tree.rb_node;
179
180         while (n) {
181                 cache = rb_entry(n, struct btrfs_block_group_cache,
182                                  cache_node);
183                 end = cache->key.objectid + cache->key.offset - 1;
184                 start = cache->key.objectid;
185
186                 if (bytenr < start) {
187                         if (!contains && (!ret || start < ret->key.objectid))
188                                 ret = cache;
189                         n = n->rb_left;
190                 } else if (bytenr > start) {
191                         if (contains && bytenr <= end) {
192                                 ret = cache;
193                                 break;
194                         }
195                         n = n->rb_right;
196                 } else {
197                         ret = cache;
198                         break;
199                 }
200         }
201         if (ret) {
202                 btrfs_get_block_group(ret);
203                 if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
204                         info->first_logical_byte = ret->key.objectid;
205         }
206         spin_unlock(&info->block_group_cache_lock);
207
208         return ret;
209 }
210
211 static int add_excluded_extent(struct btrfs_fs_info *fs_info,
212                                u64 start, u64 num_bytes)
213 {
214         u64 end = start + num_bytes - 1;
215         set_extent_bits(&fs_info->freed_extents[0],
216                         start, end, EXTENT_UPTODATE);
217         set_extent_bits(&fs_info->freed_extents[1],
218                         start, end, EXTENT_UPTODATE);
219         return 0;
220 }
221
222 static void free_excluded_extents(struct btrfs_fs_info *fs_info,
223                                   struct btrfs_block_group_cache *cache)
224 {
225         u64 start, end;
226
227         start = cache->key.objectid;
228         end = start + cache->key.offset - 1;
229
230         clear_extent_bits(&fs_info->freed_extents[0],
231                           start, end, EXTENT_UPTODATE);
232         clear_extent_bits(&fs_info->freed_extents[1],
233                           start, end, EXTENT_UPTODATE);
234 }
235
236 static int exclude_super_stripes(struct btrfs_fs_info *fs_info,
237                                  struct btrfs_block_group_cache *cache)
238 {
239         u64 bytenr;
240         u64 *logical;
241         int stripe_len;
242         int i, nr, ret;
243
244         if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
245                 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
246                 cache->bytes_super += stripe_len;
247                 ret = add_excluded_extent(fs_info, cache->key.objectid,
248                                           stripe_len);
249                 if (ret)
250                         return ret;
251         }
252
253         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
254                 bytenr = btrfs_sb_offset(i);
255                 ret = btrfs_rmap_block(fs_info, cache->key.objectid,
256                                        bytenr, &logical, &nr, &stripe_len);
257                 if (ret)
258                         return ret;
259
260                 while (nr--) {
261                         u64 start, len;
262
263                         if (logical[nr] > cache->key.objectid +
264                             cache->key.offset)
265                                 continue;
266
267                         if (logical[nr] + stripe_len <= cache->key.objectid)
268                                 continue;
269
270                         start = logical[nr];
271                         if (start < cache->key.objectid) {
272                                 start = cache->key.objectid;
273                                 len = (logical[nr] + stripe_len) - start;
274                         } else {
275                                 len = min_t(u64, stripe_len,
276                                             cache->key.objectid +
277                                             cache->key.offset - start);
278                         }
279
280                         cache->bytes_super += len;
281                         ret = add_excluded_extent(fs_info, start, len);
282                         if (ret) {
283                                 kfree(logical);
284                                 return ret;
285                         }
286                 }
287
288                 kfree(logical);
289         }
290         return 0;
291 }
292
293 static struct btrfs_caching_control *
294 get_caching_control(struct btrfs_block_group_cache *cache)
295 {
296         struct btrfs_caching_control *ctl;
297
298         spin_lock(&cache->lock);
299         if (!cache->caching_ctl) {
300                 spin_unlock(&cache->lock);
301                 return NULL;
302         }
303
304         ctl = cache->caching_ctl;
305         refcount_inc(&ctl->count);
306         spin_unlock(&cache->lock);
307         return ctl;
308 }
309
310 static void put_caching_control(struct btrfs_caching_control *ctl)
311 {
312         if (refcount_dec_and_test(&ctl->count))
313                 kfree(ctl);
314 }
315
316 #ifdef CONFIG_BTRFS_DEBUG
317 static void fragment_free_space(struct btrfs_block_group_cache *block_group)
318 {
319         struct btrfs_fs_info *fs_info = block_group->fs_info;
320         u64 start = block_group->key.objectid;
321         u64 len = block_group->key.offset;
322         u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
323                 fs_info->nodesize : fs_info->sectorsize;
324         u64 step = chunk << 1;
325
326         while (len > chunk) {
327                 btrfs_remove_free_space(block_group, start, chunk);
328                 start += step;
329                 if (len < step)
330                         len = 0;
331                 else
332                         len -= step;
333         }
334 }
335 #endif
336
337 /*
338  * this is only called by cache_block_group, since we could have freed extents
339  * we need to check the pinned_extents for any extents that can't be used yet
340  * since their free space will be released as soon as the transaction commits.
341  */
342 u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
343                        u64 start, u64 end)
344 {
345         struct btrfs_fs_info *info = block_group->fs_info;
346         u64 extent_start, extent_end, size, total_added = 0;
347         int ret;
348
349         while (start < end) {
350                 ret = find_first_extent_bit(info->pinned_extents, start,
351                                             &extent_start, &extent_end,
352                                             EXTENT_DIRTY | EXTENT_UPTODATE,
353                                             NULL);
354                 if (ret)
355                         break;
356
357                 if (extent_start <= start) {
358                         start = extent_end + 1;
359                 } else if (extent_start > start && extent_start < end) {
360                         size = extent_start - start;
361                         total_added += size;
362                         ret = btrfs_add_free_space(block_group, start,
363                                                    size);
364                         BUG_ON(ret); /* -ENOMEM or logic error */
365                         start = extent_end + 1;
366                 } else {
367                         break;
368                 }
369         }
370
371         if (start < end) {
372                 size = end - start;
373                 total_added += size;
374                 ret = btrfs_add_free_space(block_group, start, size);
375                 BUG_ON(ret); /* -ENOMEM or logic error */
376         }
377
378         return total_added;
379 }
380
381 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
382 {
383         struct btrfs_block_group_cache *block_group = caching_ctl->block_group;
384         struct btrfs_fs_info *fs_info = block_group->fs_info;
385         struct btrfs_root *extent_root = fs_info->extent_root;
386         struct btrfs_path *path;
387         struct extent_buffer *leaf;
388         struct btrfs_key key;
389         u64 total_found = 0;
390         u64 last = 0;
391         u32 nritems;
392         int ret;
393         bool wakeup = true;
394
395         path = btrfs_alloc_path();
396         if (!path)
397                 return -ENOMEM;
398
399         last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
400
401 #ifdef CONFIG_BTRFS_DEBUG
402         /*
403          * If we're fragmenting we don't want to make anybody think we can
404          * allocate from this block group until we've had a chance to fragment
405          * the free space.
406          */
407         if (btrfs_should_fragment_free_space(block_group))
408                 wakeup = false;
409 #endif
410         /*
411          * We don't want to deadlock with somebody trying to allocate a new
412          * extent for the extent root while also trying to search the extent
413          * root to add free space.  So we skip locking and search the commit
414          * root, since its read-only
415          */
416         path->skip_locking = 1;
417         path->search_commit_root = 1;
418         path->reada = READA_FORWARD;
419
420         key.objectid = last;
421         key.offset = 0;
422         key.type = BTRFS_EXTENT_ITEM_KEY;
423
424 next:
425         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
426         if (ret < 0)
427                 goto out;
428
429         leaf = path->nodes[0];
430         nritems = btrfs_header_nritems(leaf);
431
432         while (1) {
433                 if (btrfs_fs_closing(fs_info) > 1) {
434                         last = (u64)-1;
435                         break;
436                 }
437
438                 if (path->slots[0] < nritems) {
439                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
440                 } else {
441                         ret = find_next_key(path, 0, &key);
442                         if (ret)
443                                 break;
444
445                         if (need_resched() ||
446                             rwsem_is_contended(&fs_info->commit_root_sem)) {
447                                 if (wakeup)
448                                         caching_ctl->progress = last;
449                                 btrfs_release_path(path);
450                                 up_read(&fs_info->commit_root_sem);
451                                 mutex_unlock(&caching_ctl->mutex);
452                                 cond_resched();
453                                 mutex_lock(&caching_ctl->mutex);
454                                 down_read(&fs_info->commit_root_sem);
455                                 goto next;
456                         }
457
458                         ret = btrfs_next_leaf(extent_root, path);
459                         if (ret < 0)
460                                 goto out;
461                         if (ret)
462                                 break;
463                         leaf = path->nodes[0];
464                         nritems = btrfs_header_nritems(leaf);
465                         continue;
466                 }
467
468                 if (key.objectid < last) {
469                         key.objectid = last;
470                         key.offset = 0;
471                         key.type = BTRFS_EXTENT_ITEM_KEY;
472
473                         if (wakeup)
474                                 caching_ctl->progress = last;
475                         btrfs_release_path(path);
476                         goto next;
477                 }
478
479                 if (key.objectid < block_group->key.objectid) {
480                         path->slots[0]++;
481                         continue;
482                 }
483
484                 if (key.objectid >= block_group->key.objectid +
485                     block_group->key.offset)
486                         break;
487
488                 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
489                     key.type == BTRFS_METADATA_ITEM_KEY) {
490                         total_found += add_new_free_space(block_group, last,
491                                                           key.objectid);
492                         if (key.type == BTRFS_METADATA_ITEM_KEY)
493                                 last = key.objectid +
494                                         fs_info->nodesize;
495                         else
496                                 last = key.objectid + key.offset;
497
498                         if (total_found > CACHING_CTL_WAKE_UP) {
499                                 total_found = 0;
500                                 if (wakeup)
501                                         wake_up(&caching_ctl->wait);
502                         }
503                 }
504                 path->slots[0]++;
505         }
506         ret = 0;
507
508         total_found += add_new_free_space(block_group, last,
509                                           block_group->key.objectid +
510                                           block_group->key.offset);
511         caching_ctl->progress = (u64)-1;
512
513 out:
514         btrfs_free_path(path);
515         return ret;
516 }
517
518 static noinline void caching_thread(struct btrfs_work *work)
519 {
520         struct btrfs_block_group_cache *block_group;
521         struct btrfs_fs_info *fs_info;
522         struct btrfs_caching_control *caching_ctl;
523         int ret;
524
525         caching_ctl = container_of(work, struct btrfs_caching_control, work);
526         block_group = caching_ctl->block_group;
527         fs_info = block_group->fs_info;
528
529         mutex_lock(&caching_ctl->mutex);
530         down_read(&fs_info->commit_root_sem);
531
532         if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
533                 ret = load_free_space_tree(caching_ctl);
534         else
535                 ret = load_extent_tree_free(caching_ctl);
536
537         spin_lock(&block_group->lock);
538         block_group->caching_ctl = NULL;
539         block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
540         spin_unlock(&block_group->lock);
541
542 #ifdef CONFIG_BTRFS_DEBUG
543         if (btrfs_should_fragment_free_space(block_group)) {
544                 u64 bytes_used;
545
546                 spin_lock(&block_group->space_info->lock);
547                 spin_lock(&block_group->lock);
548                 bytes_used = block_group->key.offset -
549                         btrfs_block_group_used(&block_group->item);
550                 block_group->space_info->bytes_used += bytes_used >> 1;
551                 spin_unlock(&block_group->lock);
552                 spin_unlock(&block_group->space_info->lock);
553                 fragment_free_space(block_group);
554         }
555 #endif
556
557         caching_ctl->progress = (u64)-1;
558
559         up_read(&fs_info->commit_root_sem);
560         free_excluded_extents(fs_info, block_group);
561         mutex_unlock(&caching_ctl->mutex);
562
563         wake_up(&caching_ctl->wait);
564
565         put_caching_control(caching_ctl);
566         btrfs_put_block_group(block_group);
567 }
568
569 static int cache_block_group(struct btrfs_block_group_cache *cache,
570                              int load_cache_only)
571 {
572         DEFINE_WAIT(wait);
573         struct btrfs_fs_info *fs_info = cache->fs_info;
574         struct btrfs_caching_control *caching_ctl;
575         int ret = 0;
576
577         caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
578         if (!caching_ctl)
579                 return -ENOMEM;
580
581         INIT_LIST_HEAD(&caching_ctl->list);
582         mutex_init(&caching_ctl->mutex);
583         init_waitqueue_head(&caching_ctl->wait);
584         caching_ctl->block_group = cache;
585         caching_ctl->progress = cache->key.objectid;
586         refcount_set(&caching_ctl->count, 1);
587         btrfs_init_work(&caching_ctl->work, btrfs_cache_helper,
588                         caching_thread, NULL, NULL);
589
590         spin_lock(&cache->lock);
591         /*
592          * This should be a rare occasion, but this could happen I think in the
593          * case where one thread starts to load the space cache info, and then
594          * some other thread starts a transaction commit which tries to do an
595          * allocation while the other thread is still loading the space cache
596          * info.  The previous loop should have kept us from choosing this block
597          * group, but if we've moved to the state where we will wait on caching
598          * block groups we need to first check if we're doing a fast load here,
599          * so we can wait for it to finish, otherwise we could end up allocating
600          * from a block group who's cache gets evicted for one reason or
601          * another.
602          */
603         while (cache->cached == BTRFS_CACHE_FAST) {
604                 struct btrfs_caching_control *ctl;
605
606                 ctl = cache->caching_ctl;
607                 refcount_inc(&ctl->count);
608                 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
609                 spin_unlock(&cache->lock);
610
611                 schedule();
612
613                 finish_wait(&ctl->wait, &wait);
614                 put_caching_control(ctl);
615                 spin_lock(&cache->lock);
616         }
617
618         if (cache->cached != BTRFS_CACHE_NO) {
619                 spin_unlock(&cache->lock);
620                 kfree(caching_ctl);
621                 return 0;
622         }
623         WARN_ON(cache->caching_ctl);
624         cache->caching_ctl = caching_ctl;
625         cache->cached = BTRFS_CACHE_FAST;
626         spin_unlock(&cache->lock);
627
628         if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
629                 mutex_lock(&caching_ctl->mutex);
630                 ret = load_free_space_cache(fs_info, cache);
631
632                 spin_lock(&cache->lock);
633                 if (ret == 1) {
634                         cache->caching_ctl = NULL;
635                         cache->cached = BTRFS_CACHE_FINISHED;
636                         cache->last_byte_to_unpin = (u64)-1;
637                         caching_ctl->progress = (u64)-1;
638                 } else {
639                         if (load_cache_only) {
640                                 cache->caching_ctl = NULL;
641                                 cache->cached = BTRFS_CACHE_NO;
642                         } else {
643                                 cache->cached = BTRFS_CACHE_STARTED;
644                                 cache->has_caching_ctl = 1;
645                         }
646                 }
647                 spin_unlock(&cache->lock);
648 #ifdef CONFIG_BTRFS_DEBUG
649                 if (ret == 1 &&
650                     btrfs_should_fragment_free_space(cache)) {
651                         u64 bytes_used;
652
653                         spin_lock(&cache->space_info->lock);
654                         spin_lock(&cache->lock);
655                         bytes_used = cache->key.offset -
656                                 btrfs_block_group_used(&cache->item);
657                         cache->space_info->bytes_used += bytes_used >> 1;
658                         spin_unlock(&cache->lock);
659                         spin_unlock(&cache->space_info->lock);
660                         fragment_free_space(cache);
661                 }
662 #endif
663                 mutex_unlock(&caching_ctl->mutex);
664
665                 wake_up(&caching_ctl->wait);
666                 if (ret == 1) {
667                         put_caching_control(caching_ctl);
668                         free_excluded_extents(fs_info, cache);
669                         return 0;
670                 }
671         } else {
672                 /*
673                  * We're either using the free space tree or no caching at all.
674                  * Set cached to the appropriate value and wakeup any waiters.
675                  */
676                 spin_lock(&cache->lock);
677                 if (load_cache_only) {
678                         cache->caching_ctl = NULL;
679                         cache->cached = BTRFS_CACHE_NO;
680                 } else {
681                         cache->cached = BTRFS_CACHE_STARTED;
682                         cache->has_caching_ctl = 1;
683                 }
684                 spin_unlock(&cache->lock);
685                 wake_up(&caching_ctl->wait);
686         }
687
688         if (load_cache_only) {
689                 put_caching_control(caching_ctl);
690                 return 0;
691         }
692
693         down_write(&fs_info->commit_root_sem);
694         refcount_inc(&caching_ctl->count);
695         list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
696         up_write(&fs_info->commit_root_sem);
697
698         btrfs_get_block_group(cache);
699
700         btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
701
702         return ret;
703 }
704
705 /*
706  * return the block group that starts at or after bytenr
707  */
708 static struct btrfs_block_group_cache *
709 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
710 {
711         return block_group_cache_tree_search(info, bytenr, 0);
712 }
713
714 /*
715  * return the block group that contains the given bytenr
716  */
717 struct btrfs_block_group_cache *btrfs_lookup_block_group(
718                                                  struct btrfs_fs_info *info,
719                                                  u64 bytenr)
720 {
721         return block_group_cache_tree_search(info, bytenr, 1);
722 }
723
724 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
725                                                   u64 flags)
726 {
727         struct list_head *head = &info->space_info;
728         struct btrfs_space_info *found;
729
730         flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
731
732         rcu_read_lock();
733         list_for_each_entry_rcu(found, head, list) {
734                 if (found->flags & flags) {
735                         rcu_read_unlock();
736                         return found;
737                 }
738         }
739         rcu_read_unlock();
740         return NULL;
741 }
742
743 static void add_pinned_bytes(struct btrfs_fs_info *fs_info, s64 num_bytes,
744                              bool metadata, u64 root_objectid)
745 {
746         struct btrfs_space_info *space_info;
747         u64 flags;
748
749         if (metadata) {
750                 if (root_objectid == BTRFS_CHUNK_TREE_OBJECTID)
751                         flags = BTRFS_BLOCK_GROUP_SYSTEM;
752                 else
753                         flags = BTRFS_BLOCK_GROUP_METADATA;
754         } else {
755                 flags = BTRFS_BLOCK_GROUP_DATA;
756         }
757
758         space_info = __find_space_info(fs_info, flags);
759         ASSERT(space_info);
760         percpu_counter_add(&space_info->total_bytes_pinned, num_bytes);
761 }
762
763 /*
764  * after adding space to the filesystem, we need to clear the full flags
765  * on all the space infos.
766  */
767 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
768 {
769         struct list_head *head = &info->space_info;
770         struct btrfs_space_info *found;
771
772         rcu_read_lock();
773         list_for_each_entry_rcu(found, head, list)
774                 found->full = 0;
775         rcu_read_unlock();
776 }
777
778 /* simple helper to search for an existing data extent at a given offset */
779 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
780 {
781         int ret;
782         struct btrfs_key key;
783         struct btrfs_path *path;
784
785         path = btrfs_alloc_path();
786         if (!path)
787                 return -ENOMEM;
788
789         key.objectid = start;
790         key.offset = len;
791         key.type = BTRFS_EXTENT_ITEM_KEY;
792         ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
793         btrfs_free_path(path);
794         return ret;
795 }
796
797 /*
798  * helper function to lookup reference count and flags of a tree block.
799  *
800  * the head node for delayed ref is used to store the sum of all the
801  * reference count modifications queued up in the rbtree. the head
802  * node may also store the extent flags to set. This way you can check
803  * to see what the reference count and extent flags would be if all of
804  * the delayed refs are not processed.
805  */
806 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
807                              struct btrfs_fs_info *fs_info, u64 bytenr,
808                              u64 offset, int metadata, u64 *refs, u64 *flags)
809 {
810         struct btrfs_delayed_ref_head *head;
811         struct btrfs_delayed_ref_root *delayed_refs;
812         struct btrfs_path *path;
813         struct btrfs_extent_item *ei;
814         struct extent_buffer *leaf;
815         struct btrfs_key key;
816         u32 item_size;
817         u64 num_refs;
818         u64 extent_flags;
819         int ret;
820
821         /*
822          * If we don't have skinny metadata, don't bother doing anything
823          * different
824          */
825         if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
826                 offset = fs_info->nodesize;
827                 metadata = 0;
828         }
829
830         path = btrfs_alloc_path();
831         if (!path)
832                 return -ENOMEM;
833
834         if (!trans) {
835                 path->skip_locking = 1;
836                 path->search_commit_root = 1;
837         }
838
839 search_again:
840         key.objectid = bytenr;
841         key.offset = offset;
842         if (metadata)
843                 key.type = BTRFS_METADATA_ITEM_KEY;
844         else
845                 key.type = BTRFS_EXTENT_ITEM_KEY;
846
847         ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
848         if (ret < 0)
849                 goto out_free;
850
851         if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
852                 if (path->slots[0]) {
853                         path->slots[0]--;
854                         btrfs_item_key_to_cpu(path->nodes[0], &key,
855                                               path->slots[0]);
856                         if (key.objectid == bytenr &&
857                             key.type == BTRFS_EXTENT_ITEM_KEY &&
858                             key.offset == fs_info->nodesize)
859                                 ret = 0;
860                 }
861         }
862
863         if (ret == 0) {
864                 leaf = path->nodes[0];
865                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
866                 if (item_size >= sizeof(*ei)) {
867                         ei = btrfs_item_ptr(leaf, path->slots[0],
868                                             struct btrfs_extent_item);
869                         num_refs = btrfs_extent_refs(leaf, ei);
870                         extent_flags = btrfs_extent_flags(leaf, ei);
871                 } else {
872 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
873                         struct btrfs_extent_item_v0 *ei0;
874                         BUG_ON(item_size != sizeof(*ei0));
875                         ei0 = btrfs_item_ptr(leaf, path->slots[0],
876                                              struct btrfs_extent_item_v0);
877                         num_refs = btrfs_extent_refs_v0(leaf, ei0);
878                         /* FIXME: this isn't correct for data */
879                         extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
880 #else
881                         BUG();
882 #endif
883                 }
884                 BUG_ON(num_refs == 0);
885         } else {
886                 num_refs = 0;
887                 extent_flags = 0;
888                 ret = 0;
889         }
890
891         if (!trans)
892                 goto out;
893
894         delayed_refs = &trans->transaction->delayed_refs;
895         spin_lock(&delayed_refs->lock);
896         head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
897         if (head) {
898                 if (!mutex_trylock(&head->mutex)) {
899                         refcount_inc(&head->refs);
900                         spin_unlock(&delayed_refs->lock);
901
902                         btrfs_release_path(path);
903
904                         /*
905                          * Mutex was contended, block until it's released and try
906                          * again
907                          */
908                         mutex_lock(&head->mutex);
909                         mutex_unlock(&head->mutex);
910                         btrfs_put_delayed_ref_head(head);
911                         goto search_again;
912                 }
913                 spin_lock(&head->lock);
914                 if (head->extent_op && head->extent_op->update_flags)
915                         extent_flags |= head->extent_op->flags_to_set;
916                 else
917                         BUG_ON(num_refs == 0);
918
919                 num_refs += head->ref_mod;
920                 spin_unlock(&head->lock);
921                 mutex_unlock(&head->mutex);
922         }
923         spin_unlock(&delayed_refs->lock);
924 out:
925         WARN_ON(num_refs == 0);
926         if (refs)
927                 *refs = num_refs;
928         if (flags)
929                 *flags = extent_flags;
930 out_free:
931         btrfs_free_path(path);
932         return ret;
933 }
934
935 /*
936  * Back reference rules.  Back refs have three main goals:
937  *
938  * 1) differentiate between all holders of references to an extent so that
939  *    when a reference is dropped we can make sure it was a valid reference
940  *    before freeing the extent.
941  *
942  * 2) Provide enough information to quickly find the holders of an extent
943  *    if we notice a given block is corrupted or bad.
944  *
945  * 3) Make it easy to migrate blocks for FS shrinking or storage pool
946  *    maintenance.  This is actually the same as #2, but with a slightly
947  *    different use case.
948  *
949  * There are two kinds of back refs. The implicit back refs is optimized
950  * for pointers in non-shared tree blocks. For a given pointer in a block,
951  * back refs of this kind provide information about the block's owner tree
952  * and the pointer's key. These information allow us to find the block by
953  * b-tree searching. The full back refs is for pointers in tree blocks not
954  * referenced by their owner trees. The location of tree block is recorded
955  * in the back refs. Actually the full back refs is generic, and can be
956  * used in all cases the implicit back refs is used. The major shortcoming
957  * of the full back refs is its overhead. Every time a tree block gets
958  * COWed, we have to update back refs entry for all pointers in it.
959  *
960  * For a newly allocated tree block, we use implicit back refs for
961  * pointers in it. This means most tree related operations only involve
962  * implicit back refs. For a tree block created in old transaction, the
963  * only way to drop a reference to it is COW it. So we can detect the
964  * event that tree block loses its owner tree's reference and do the
965  * back refs conversion.
966  *
967  * When a tree block is COWed through a tree, there are four cases:
968  *
969  * The reference count of the block is one and the tree is the block's
970  * owner tree. Nothing to do in this case.
971  *
972  * The reference count of the block is one and the tree is not the
973  * block's owner tree. In this case, full back refs is used for pointers
974  * in the block. Remove these full back refs, add implicit back refs for
975  * every pointers in the new block.
976  *
977  * The reference count of the block is greater than one and the tree is
978  * the block's owner tree. In this case, implicit back refs is used for
979  * pointers in the block. Add full back refs for every pointers in the
980  * block, increase lower level extents' reference counts. The original
981  * implicit back refs are entailed to the new block.
982  *
983  * The reference count of the block is greater than one and the tree is
984  * not the block's owner tree. Add implicit back refs for every pointer in
985  * the new block, increase lower level extents' reference count.
986  *
987  * Back Reference Key composing:
988  *
989  * The key objectid corresponds to the first byte in the extent,
990  * The key type is used to differentiate between types of back refs.
991  * There are different meanings of the key offset for different types
992  * of back refs.
993  *
994  * File extents can be referenced by:
995  *
996  * - multiple snapshots, subvolumes, or different generations in one subvol
997  * - different files inside a single subvolume
998  * - different offsets inside a file (bookend extents in file.c)
999  *
1000  * The extent ref structure for the implicit back refs has fields for:
1001  *
1002  * - Objectid of the subvolume root
1003  * - objectid of the file holding the reference
1004  * - original offset in the file
1005  * - how many bookend extents
1006  *
1007  * The key offset for the implicit back refs is hash of the first
1008  * three fields.
1009  *
1010  * The extent ref structure for the full back refs has field for:
1011  *
1012  * - number of pointers in the tree leaf
1013  *
1014  * The key offset for the implicit back refs is the first byte of
1015  * the tree leaf
1016  *
1017  * When a file extent is allocated, The implicit back refs is used.
1018  * the fields are filled in:
1019  *
1020  *     (root_key.objectid, inode objectid, offset in file, 1)
1021  *
1022  * When a file extent is removed file truncation, we find the
1023  * corresponding implicit back refs and check the following fields:
1024  *
1025  *     (btrfs_header_owner(leaf), inode objectid, offset in file)
1026  *
1027  * Btree extents can be referenced by:
1028  *
1029  * - Different subvolumes
1030  *
1031  * Both the implicit back refs and the full back refs for tree blocks
1032  * only consist of key. The key offset for the implicit back refs is
1033  * objectid of block's owner tree. The key offset for the full back refs
1034  * is the first byte of parent block.
1035  *
1036  * When implicit back refs is used, information about the lowest key and
1037  * level of the tree block are required. These information are stored in
1038  * tree block info structure.
1039  */
1040
1041 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1042 static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
1043                                   struct btrfs_fs_info *fs_info,
1044                                   struct btrfs_path *path,
1045                                   u64 owner, u32 extra_size)
1046 {
1047         struct btrfs_root *root = fs_info->extent_root;
1048         struct btrfs_extent_item *item;
1049         struct btrfs_extent_item_v0 *ei0;
1050         struct btrfs_extent_ref_v0 *ref0;
1051         struct btrfs_tree_block_info *bi;
1052         struct extent_buffer *leaf;
1053         struct btrfs_key key;
1054         struct btrfs_key found_key;
1055         u32 new_size = sizeof(*item);
1056         u64 refs;
1057         int ret;
1058
1059         leaf = path->nodes[0];
1060         BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
1061
1062         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1063         ei0 = btrfs_item_ptr(leaf, path->slots[0],
1064                              struct btrfs_extent_item_v0);
1065         refs = btrfs_extent_refs_v0(leaf, ei0);
1066
1067         if (owner == (u64)-1) {
1068                 while (1) {
1069                         if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1070                                 ret = btrfs_next_leaf(root, path);
1071                                 if (ret < 0)
1072                                         return ret;
1073                                 BUG_ON(ret > 0); /* Corruption */
1074                                 leaf = path->nodes[0];
1075                         }
1076                         btrfs_item_key_to_cpu(leaf, &found_key,
1077                                               path->slots[0]);
1078                         BUG_ON(key.objectid != found_key.objectid);
1079                         if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
1080                                 path->slots[0]++;
1081                                 continue;
1082                         }
1083                         ref0 = btrfs_item_ptr(leaf, path->slots[0],
1084                                               struct btrfs_extent_ref_v0);
1085                         owner = btrfs_ref_objectid_v0(leaf, ref0);
1086                         break;
1087                 }
1088         }
1089         btrfs_release_path(path);
1090
1091         if (owner < BTRFS_FIRST_FREE_OBJECTID)
1092                 new_size += sizeof(*bi);
1093
1094         new_size -= sizeof(*ei0);
1095         ret = btrfs_search_slot(trans, root, &key, path,
1096                                 new_size + extra_size, 1);
1097         if (ret < 0)
1098                 return ret;
1099         BUG_ON(ret); /* Corruption */
1100
1101         btrfs_extend_item(fs_info, path, new_size);
1102
1103         leaf = path->nodes[0];
1104         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1105         btrfs_set_extent_refs(leaf, item, refs);
1106         /* FIXME: get real generation */
1107         btrfs_set_extent_generation(leaf, item, 0);
1108         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1109                 btrfs_set_extent_flags(leaf, item,
1110                                        BTRFS_EXTENT_FLAG_TREE_BLOCK |
1111                                        BTRFS_BLOCK_FLAG_FULL_BACKREF);
1112                 bi = (struct btrfs_tree_block_info *)(item + 1);
1113                 /* FIXME: get first key of the block */
1114                 memzero_extent_buffer(leaf, (unsigned long)bi, sizeof(*bi));
1115                 btrfs_set_tree_block_level(leaf, bi, (int)owner);
1116         } else {
1117                 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
1118         }
1119         btrfs_mark_buffer_dirty(leaf);
1120         return 0;
1121 }
1122 #endif
1123
1124 /*
1125  * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
1126  * is_data == BTRFS_REF_TYPE_DATA, data type is requried,
1127  * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
1128  */
1129 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
1130                                      struct btrfs_extent_inline_ref *iref,
1131                                      enum btrfs_inline_ref_type is_data)
1132 {
1133         int type = btrfs_extent_inline_ref_type(eb, iref);
1134         u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
1135
1136         if (type == BTRFS_TREE_BLOCK_REF_KEY ||
1137             type == BTRFS_SHARED_BLOCK_REF_KEY ||
1138             type == BTRFS_SHARED_DATA_REF_KEY ||
1139             type == BTRFS_EXTENT_DATA_REF_KEY) {
1140                 if (is_data == BTRFS_REF_TYPE_BLOCK) {
1141                         if (type == BTRFS_TREE_BLOCK_REF_KEY)
1142                                 return type;
1143                         if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1144                                 ASSERT(eb->fs_info);
1145                                 /*
1146                                  * Every shared one has parent tree
1147                                  * block, which must be aligned to
1148                                  * nodesize.
1149                                  */
1150                                 if (offset &&
1151                                     IS_ALIGNED(offset, eb->fs_info->nodesize))
1152                                         return type;
1153                         }
1154                 } else if (is_data == BTRFS_REF_TYPE_DATA) {
1155                         if (type == BTRFS_EXTENT_DATA_REF_KEY)
1156                                 return type;
1157                         if (type == BTRFS_SHARED_DATA_REF_KEY) {
1158                                 ASSERT(eb->fs_info);
1159                                 /*
1160                                  * Every shared one has parent tree
1161                                  * block, which must be aligned to
1162                                  * nodesize.
1163                                  */
1164                                 if (offset &&
1165                                     IS_ALIGNED(offset, eb->fs_info->nodesize))
1166                                         return type;
1167                         }
1168                 } else {
1169                         ASSERT(is_data == BTRFS_REF_TYPE_ANY);
1170                         return type;
1171                 }
1172         }
1173
1174         btrfs_print_leaf((struct extent_buffer *)eb);
1175         btrfs_err(eb->fs_info, "eb %llu invalid extent inline ref type %d",
1176                   eb->start, type);
1177         WARN_ON(1);
1178
1179         return BTRFS_REF_TYPE_INVALID;
1180 }
1181
1182 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1183 {
1184         u32 high_crc = ~(u32)0;
1185         u32 low_crc = ~(u32)0;
1186         __le64 lenum;
1187
1188         lenum = cpu_to_le64(root_objectid);
1189         high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
1190         lenum = cpu_to_le64(owner);
1191         low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
1192         lenum = cpu_to_le64(offset);
1193         low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
1194
1195         return ((u64)high_crc << 31) ^ (u64)low_crc;
1196 }
1197
1198 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1199                                      struct btrfs_extent_data_ref *ref)
1200 {
1201         return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1202                                     btrfs_extent_data_ref_objectid(leaf, ref),
1203                                     btrfs_extent_data_ref_offset(leaf, ref));
1204 }
1205
1206 static int match_extent_data_ref(struct extent_buffer *leaf,
1207                                  struct btrfs_extent_data_ref *ref,
1208                                  u64 root_objectid, u64 owner, u64 offset)
1209 {
1210         if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1211             btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1212             btrfs_extent_data_ref_offset(leaf, ref) != offset)
1213                 return 0;
1214         return 1;
1215 }
1216
1217 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1218                                            struct btrfs_path *path,
1219                                            u64 bytenr, u64 parent,
1220                                            u64 root_objectid,
1221                                            u64 owner, u64 offset)
1222 {
1223         struct btrfs_root *root = trans->fs_info->extent_root;
1224         struct btrfs_key key;
1225         struct btrfs_extent_data_ref *ref;
1226         struct extent_buffer *leaf;
1227         u32 nritems;
1228         int ret;
1229         int recow;
1230         int err = -ENOENT;
1231
1232         key.objectid = bytenr;
1233         if (parent) {
1234                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1235                 key.offset = parent;
1236         } else {
1237                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1238                 key.offset = hash_extent_data_ref(root_objectid,
1239                                                   owner, offset);
1240         }
1241 again:
1242         recow = 0;
1243         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1244         if (ret < 0) {
1245                 err = ret;
1246                 goto fail;
1247         }
1248
1249         if (parent) {
1250                 if (!ret)
1251                         return 0;
1252 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1253                 key.type = BTRFS_EXTENT_REF_V0_KEY;
1254                 btrfs_release_path(path);
1255                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1256                 if (ret < 0) {
1257                         err = ret;
1258                         goto fail;
1259                 }
1260                 if (!ret)
1261                         return 0;
1262 #endif
1263                 goto fail;
1264         }
1265
1266         leaf = path->nodes[0];
1267         nritems = btrfs_header_nritems(leaf);
1268         while (1) {
1269                 if (path->slots[0] >= nritems) {
1270                         ret = btrfs_next_leaf(root, path);
1271                         if (ret < 0)
1272                                 err = ret;
1273                         if (ret)
1274                                 goto fail;
1275
1276                         leaf = path->nodes[0];
1277                         nritems = btrfs_header_nritems(leaf);
1278                         recow = 1;
1279                 }
1280
1281                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1282                 if (key.objectid != bytenr ||
1283                     key.type != BTRFS_EXTENT_DATA_REF_KEY)
1284                         goto fail;
1285
1286                 ref = btrfs_item_ptr(leaf, path->slots[0],
1287                                      struct btrfs_extent_data_ref);
1288
1289                 if (match_extent_data_ref(leaf, ref, root_objectid,
1290                                           owner, offset)) {
1291                         if (recow) {
1292                                 btrfs_release_path(path);
1293                                 goto again;
1294                         }
1295                         err = 0;
1296                         break;
1297                 }
1298                 path->slots[0]++;
1299         }
1300 fail:
1301         return err;
1302 }
1303
1304 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1305                                            struct btrfs_path *path,
1306                                            u64 bytenr, u64 parent,
1307                                            u64 root_objectid, u64 owner,
1308                                            u64 offset, int refs_to_add)
1309 {
1310         struct btrfs_root *root = trans->fs_info->extent_root;
1311         struct btrfs_key key;
1312         struct extent_buffer *leaf;
1313         u32 size;
1314         u32 num_refs;
1315         int ret;
1316
1317         key.objectid = bytenr;
1318         if (parent) {
1319                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1320                 key.offset = parent;
1321                 size = sizeof(struct btrfs_shared_data_ref);
1322         } else {
1323                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1324                 key.offset = hash_extent_data_ref(root_objectid,
1325                                                   owner, offset);
1326                 size = sizeof(struct btrfs_extent_data_ref);
1327         }
1328
1329         ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1330         if (ret && ret != -EEXIST)
1331                 goto fail;
1332
1333         leaf = path->nodes[0];
1334         if (parent) {
1335                 struct btrfs_shared_data_ref *ref;
1336                 ref = btrfs_item_ptr(leaf, path->slots[0],
1337                                      struct btrfs_shared_data_ref);
1338                 if (ret == 0) {
1339                         btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1340                 } else {
1341                         num_refs = btrfs_shared_data_ref_count(leaf, ref);
1342                         num_refs += refs_to_add;
1343                         btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1344                 }
1345         } else {
1346                 struct btrfs_extent_data_ref *ref;
1347                 while (ret == -EEXIST) {
1348                         ref = btrfs_item_ptr(leaf, path->slots[0],
1349                                              struct btrfs_extent_data_ref);
1350                         if (match_extent_data_ref(leaf, ref, root_objectid,
1351                                                   owner, offset))
1352                                 break;
1353                         btrfs_release_path(path);
1354                         key.offset++;
1355                         ret = btrfs_insert_empty_item(trans, root, path, &key,
1356                                                       size);
1357                         if (ret && ret != -EEXIST)
1358                                 goto fail;
1359
1360                         leaf = path->nodes[0];
1361                 }
1362                 ref = btrfs_item_ptr(leaf, path->slots[0],
1363                                      struct btrfs_extent_data_ref);
1364                 if (ret == 0) {
1365                         btrfs_set_extent_data_ref_root(leaf, ref,
1366                                                        root_objectid);
1367                         btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1368                         btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1369                         btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1370                 } else {
1371                         num_refs = btrfs_extent_data_ref_count(leaf, ref);
1372                         num_refs += refs_to_add;
1373                         btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1374                 }
1375         }
1376         btrfs_mark_buffer_dirty(leaf);
1377         ret = 0;
1378 fail:
1379         btrfs_release_path(path);
1380         return ret;
1381 }
1382
1383 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1384                                            struct btrfs_path *path,
1385                                            int refs_to_drop, int *last_ref)
1386 {
1387         struct btrfs_key key;
1388         struct btrfs_extent_data_ref *ref1 = NULL;
1389         struct btrfs_shared_data_ref *ref2 = NULL;
1390         struct extent_buffer *leaf;
1391         u32 num_refs = 0;
1392         int ret = 0;
1393
1394         leaf = path->nodes[0];
1395         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1396
1397         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1398                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1399                                       struct btrfs_extent_data_ref);
1400                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1401         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1402                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1403                                       struct btrfs_shared_data_ref);
1404                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1405 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1406         } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1407                 struct btrfs_extent_ref_v0 *ref0;
1408                 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1409                                       struct btrfs_extent_ref_v0);
1410                 num_refs = btrfs_ref_count_v0(leaf, ref0);
1411 #endif
1412         } else {
1413                 BUG();
1414         }
1415
1416         BUG_ON(num_refs < refs_to_drop);
1417         num_refs -= refs_to_drop;
1418
1419         if (num_refs == 0) {
1420                 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1421                 *last_ref = 1;
1422         } else {
1423                 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1424                         btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1425                 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1426                         btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1427 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1428                 else {
1429                         struct btrfs_extent_ref_v0 *ref0;
1430                         ref0 = btrfs_item_ptr(leaf, path->slots[0],
1431                                         struct btrfs_extent_ref_v0);
1432                         btrfs_set_ref_count_v0(leaf, ref0, num_refs);
1433                 }
1434 #endif
1435                 btrfs_mark_buffer_dirty(leaf);
1436         }
1437         return ret;
1438 }
1439
1440 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
1441                                           struct btrfs_extent_inline_ref *iref)
1442 {
1443         struct btrfs_key key;
1444         struct extent_buffer *leaf;
1445         struct btrfs_extent_data_ref *ref1;
1446         struct btrfs_shared_data_ref *ref2;
1447         u32 num_refs = 0;
1448         int type;
1449
1450         leaf = path->nodes[0];
1451         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1452         if (iref) {
1453                 /*
1454                  * If type is invalid, we should have bailed out earlier than
1455                  * this call.
1456                  */
1457                 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
1458                 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1459                 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1460                         ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1461                         num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1462                 } else {
1463                         ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1464                         num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1465                 }
1466         } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1467                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1468                                       struct btrfs_extent_data_ref);
1469                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1470         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1471                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1472                                       struct btrfs_shared_data_ref);
1473                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1474 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1475         } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1476                 struct btrfs_extent_ref_v0 *ref0;
1477                 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1478                                       struct btrfs_extent_ref_v0);
1479                 num_refs = btrfs_ref_count_v0(leaf, ref0);
1480 #endif
1481         } else {
1482                 WARN_ON(1);
1483         }
1484         return num_refs;
1485 }
1486
1487 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1488                                           struct btrfs_path *path,
1489                                           u64 bytenr, u64 parent,
1490                                           u64 root_objectid)
1491 {
1492         struct btrfs_root *root = trans->fs_info->extent_root;
1493         struct btrfs_key key;
1494         int ret;
1495
1496         key.objectid = bytenr;
1497         if (parent) {
1498                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1499                 key.offset = parent;
1500         } else {
1501                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1502                 key.offset = root_objectid;
1503         }
1504
1505         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1506         if (ret > 0)
1507                 ret = -ENOENT;
1508 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1509         if (ret == -ENOENT && parent) {
1510                 btrfs_release_path(path);
1511                 key.type = BTRFS_EXTENT_REF_V0_KEY;
1512                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1513                 if (ret > 0)
1514                         ret = -ENOENT;
1515         }
1516 #endif
1517         return ret;
1518 }
1519
1520 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1521                                           struct btrfs_path *path,
1522                                           u64 bytenr, u64 parent,
1523                                           u64 root_objectid)
1524 {
1525         struct btrfs_key key;
1526         int ret;
1527
1528         key.objectid = bytenr;
1529         if (parent) {
1530                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1531                 key.offset = parent;
1532         } else {
1533                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1534                 key.offset = root_objectid;
1535         }
1536
1537         ret = btrfs_insert_empty_item(trans, trans->fs_info->extent_root,
1538                                       path, &key, 0);
1539         btrfs_release_path(path);
1540         return ret;
1541 }
1542
1543 static inline int extent_ref_type(u64 parent, u64 owner)
1544 {
1545         int type;
1546         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1547                 if (parent > 0)
1548                         type = BTRFS_SHARED_BLOCK_REF_KEY;
1549                 else
1550                         type = BTRFS_TREE_BLOCK_REF_KEY;
1551         } else {
1552                 if (parent > 0)
1553                         type = BTRFS_SHARED_DATA_REF_KEY;
1554                 else
1555                         type = BTRFS_EXTENT_DATA_REF_KEY;
1556         }
1557         return type;
1558 }
1559
1560 static int find_next_key(struct btrfs_path *path, int level,
1561                          struct btrfs_key *key)
1562
1563 {
1564         for (; level < BTRFS_MAX_LEVEL; level++) {
1565                 if (!path->nodes[level])
1566                         break;
1567                 if (path->slots[level] + 1 >=
1568                     btrfs_header_nritems(path->nodes[level]))
1569                         continue;
1570                 if (level == 0)
1571                         btrfs_item_key_to_cpu(path->nodes[level], key,
1572                                               path->slots[level] + 1);
1573                 else
1574                         btrfs_node_key_to_cpu(path->nodes[level], key,
1575                                               path->slots[level] + 1);
1576                 return 0;
1577         }
1578         return 1;
1579 }
1580
1581 /*
1582  * look for inline back ref. if back ref is found, *ref_ret is set
1583  * to the address of inline back ref, and 0 is returned.
1584  *
1585  * if back ref isn't found, *ref_ret is set to the address where it
1586  * should be inserted, and -ENOENT is returned.
1587  *
1588  * if insert is true and there are too many inline back refs, the path
1589  * points to the extent item, and -EAGAIN is returned.
1590  *
1591  * NOTE: inline back refs are ordered in the same way that back ref
1592  *       items in the tree are ordered.
1593  */
1594 static noinline_for_stack
1595 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1596                                  struct btrfs_path *path,
1597                                  struct btrfs_extent_inline_ref **ref_ret,
1598                                  u64 bytenr, u64 num_bytes,
1599                                  u64 parent, u64 root_objectid,
1600                                  u64 owner, u64 offset, int insert)
1601 {
1602         struct btrfs_fs_info *fs_info = trans->fs_info;
1603         struct btrfs_root *root = fs_info->extent_root;
1604         struct btrfs_key key;
1605         struct extent_buffer *leaf;
1606         struct btrfs_extent_item *ei;
1607         struct btrfs_extent_inline_ref *iref;
1608         u64 flags;
1609         u64 item_size;
1610         unsigned long ptr;
1611         unsigned long end;
1612         int extra_size;
1613         int type;
1614         int want;
1615         int ret;
1616         int err = 0;
1617         bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
1618         int needed;
1619
1620         key.objectid = bytenr;
1621         key.type = BTRFS_EXTENT_ITEM_KEY;
1622         key.offset = num_bytes;
1623
1624         want = extent_ref_type(parent, owner);
1625         if (insert) {
1626                 extra_size = btrfs_extent_inline_ref_size(want);
1627                 path->keep_locks = 1;
1628         } else
1629                 extra_size = -1;
1630
1631         /*
1632          * Owner is our level, so we can just add one to get the level for the
1633          * block we are interested in.
1634          */
1635         if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1636                 key.type = BTRFS_METADATA_ITEM_KEY;
1637                 key.offset = owner;
1638         }
1639
1640 again:
1641         ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1642         if (ret < 0) {
1643                 err = ret;
1644                 goto out;
1645         }
1646
1647         /*
1648          * We may be a newly converted file system which still has the old fat
1649          * extent entries for metadata, so try and see if we have one of those.
1650          */
1651         if (ret > 0 && skinny_metadata) {
1652                 skinny_metadata = false;
1653                 if (path->slots[0]) {
1654                         path->slots[0]--;
1655                         btrfs_item_key_to_cpu(path->nodes[0], &key,
1656                                               path->slots[0]);
1657                         if (key.objectid == bytenr &&
1658                             key.type == BTRFS_EXTENT_ITEM_KEY &&
1659                             key.offset == num_bytes)
1660                                 ret = 0;
1661                 }
1662                 if (ret) {
1663                         key.objectid = bytenr;
1664                         key.type = BTRFS_EXTENT_ITEM_KEY;
1665                         key.offset = num_bytes;
1666                         btrfs_release_path(path);
1667                         goto again;
1668                 }
1669         }
1670
1671         if (ret && !insert) {
1672                 err = -ENOENT;
1673                 goto out;
1674         } else if (WARN_ON(ret)) {
1675                 err = -EIO;
1676                 goto out;
1677         }
1678
1679         leaf = path->nodes[0];
1680         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1681 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1682         if (item_size < sizeof(*ei)) {
1683                 if (!insert) {
1684                         err = -ENOENT;
1685                         goto out;
1686                 }
1687                 ret = convert_extent_item_v0(trans, fs_info, path, owner,
1688                                              extra_size);
1689                 if (ret < 0) {
1690                         err = ret;
1691                         goto out;
1692                 }
1693                 leaf = path->nodes[0];
1694                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1695         }
1696 #endif
1697         BUG_ON(item_size < sizeof(*ei));
1698
1699         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1700         flags = btrfs_extent_flags(leaf, ei);
1701
1702         ptr = (unsigned long)(ei + 1);
1703         end = (unsigned long)ei + item_size;
1704
1705         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
1706                 ptr += sizeof(struct btrfs_tree_block_info);
1707                 BUG_ON(ptr > end);
1708         }
1709
1710         if (owner >= BTRFS_FIRST_FREE_OBJECTID)
1711                 needed = BTRFS_REF_TYPE_DATA;
1712         else
1713                 needed = BTRFS_REF_TYPE_BLOCK;
1714
1715         err = -ENOENT;
1716         while (1) {
1717                 if (ptr >= end) {
1718                         WARN_ON(ptr > end);
1719                         break;
1720                 }
1721                 iref = (struct btrfs_extent_inline_ref *)ptr;
1722                 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
1723                 if (type == BTRFS_REF_TYPE_INVALID) {
1724                         err = -EINVAL;
1725                         goto out;
1726                 }
1727
1728                 if (want < type)
1729                         break;
1730                 if (want > type) {
1731                         ptr += btrfs_extent_inline_ref_size(type);
1732                         continue;
1733                 }
1734
1735                 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1736                         struct btrfs_extent_data_ref *dref;
1737                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1738                         if (match_extent_data_ref(leaf, dref, root_objectid,
1739                                                   owner, offset)) {
1740                                 err = 0;
1741                                 break;
1742                         }
1743                         if (hash_extent_data_ref_item(leaf, dref) <
1744                             hash_extent_data_ref(root_objectid, owner, offset))
1745                                 break;
1746                 } else {
1747                         u64 ref_offset;
1748                         ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1749                         if (parent > 0) {
1750                                 if (parent == ref_offset) {
1751                                         err = 0;
1752                                         break;
1753                                 }
1754                                 if (ref_offset < parent)
1755                                         break;
1756                         } else {
1757                                 if (root_objectid == ref_offset) {
1758                                         err = 0;
1759                                         break;
1760                                 }
1761                                 if (ref_offset < root_objectid)
1762                                         break;
1763                         }
1764                 }
1765                 ptr += btrfs_extent_inline_ref_size(type);
1766         }
1767         if (err == -ENOENT && insert) {
1768                 if (item_size + extra_size >=
1769                     BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1770                         err = -EAGAIN;
1771                         goto out;
1772                 }
1773                 /*
1774                  * To add new inline back ref, we have to make sure
1775                  * there is no corresponding back ref item.
1776                  * For simplicity, we just do not add new inline back
1777                  * ref if there is any kind of item for this block
1778                  */
1779                 if (find_next_key(path, 0, &key) == 0 &&
1780                     key.objectid == bytenr &&
1781                     key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1782                         err = -EAGAIN;
1783                         goto out;
1784                 }
1785         }
1786         *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1787 out:
1788         if (insert) {
1789                 path->keep_locks = 0;
1790                 btrfs_unlock_up_safe(path, 1);
1791         }
1792         return err;
1793 }
1794
1795 /*
1796  * helper to add new inline back ref
1797  */
1798 static noinline_for_stack
1799 void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
1800                                  struct btrfs_path *path,
1801                                  struct btrfs_extent_inline_ref *iref,
1802                                  u64 parent, u64 root_objectid,
1803                                  u64 owner, u64 offset, int refs_to_add,
1804                                  struct btrfs_delayed_extent_op *extent_op)
1805 {
1806         struct extent_buffer *leaf;
1807         struct btrfs_extent_item *ei;
1808         unsigned long ptr;
1809         unsigned long end;
1810         unsigned long item_offset;
1811         u64 refs;
1812         int size;
1813         int type;
1814
1815         leaf = path->nodes[0];
1816         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1817         item_offset = (unsigned long)iref - (unsigned long)ei;
1818
1819         type = extent_ref_type(parent, owner);
1820         size = btrfs_extent_inline_ref_size(type);
1821
1822         btrfs_extend_item(fs_info, path, size);
1823
1824         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1825         refs = btrfs_extent_refs(leaf, ei);
1826         refs += refs_to_add;
1827         btrfs_set_extent_refs(leaf, ei, refs);
1828         if (extent_op)
1829                 __run_delayed_extent_op(extent_op, leaf, ei);
1830
1831         ptr = (unsigned long)ei + item_offset;
1832         end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1833         if (ptr < end - size)
1834                 memmove_extent_buffer(leaf, ptr + size, ptr,
1835                                       end - size - ptr);
1836
1837         iref = (struct btrfs_extent_inline_ref *)ptr;
1838         btrfs_set_extent_inline_ref_type(leaf, iref, type);
1839         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1840                 struct btrfs_extent_data_ref *dref;
1841                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1842                 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1843                 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1844                 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1845                 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1846         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1847                 struct btrfs_shared_data_ref *sref;
1848                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1849                 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1850                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1851         } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1852                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1853         } else {
1854                 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1855         }
1856         btrfs_mark_buffer_dirty(leaf);
1857 }
1858
1859 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1860                                  struct btrfs_path *path,
1861                                  struct btrfs_extent_inline_ref **ref_ret,
1862                                  u64 bytenr, u64 num_bytes, u64 parent,
1863                                  u64 root_objectid, u64 owner, u64 offset)
1864 {
1865         int ret;
1866
1867         ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1868                                            num_bytes, parent, root_objectid,
1869                                            owner, offset, 0);
1870         if (ret != -ENOENT)
1871                 return ret;
1872
1873         btrfs_release_path(path);
1874         *ref_ret = NULL;
1875
1876         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1877                 ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1878                                             root_objectid);
1879         } else {
1880                 ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1881                                              root_objectid, owner, offset);
1882         }
1883         return ret;
1884 }
1885
1886 /*
1887  * helper to update/remove inline back ref
1888  */
1889 static noinline_for_stack
1890 void update_inline_extent_backref(struct btrfs_path *path,
1891                                   struct btrfs_extent_inline_ref *iref,
1892                                   int refs_to_mod,
1893                                   struct btrfs_delayed_extent_op *extent_op,
1894                                   int *last_ref)
1895 {
1896         struct extent_buffer *leaf = path->nodes[0];
1897         struct btrfs_fs_info *fs_info = leaf->fs_info;
1898         struct btrfs_extent_item *ei;
1899         struct btrfs_extent_data_ref *dref = NULL;
1900         struct btrfs_shared_data_ref *sref = NULL;
1901         unsigned long ptr;
1902         unsigned long end;
1903         u32 item_size;
1904         int size;
1905         int type;
1906         u64 refs;
1907
1908         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1909         refs = btrfs_extent_refs(leaf, ei);
1910         WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1911         refs += refs_to_mod;
1912         btrfs_set_extent_refs(leaf, ei, refs);
1913         if (extent_op)
1914                 __run_delayed_extent_op(extent_op, leaf, ei);
1915
1916         /*
1917          * If type is invalid, we should have bailed out after
1918          * lookup_inline_extent_backref().
1919          */
1920         type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1921         ASSERT(type != BTRFS_REF_TYPE_INVALID);
1922
1923         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1924                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1925                 refs = btrfs_extent_data_ref_count(leaf, dref);
1926         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1927                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1928                 refs = btrfs_shared_data_ref_count(leaf, sref);
1929         } else {
1930                 refs = 1;
1931                 BUG_ON(refs_to_mod != -1);
1932         }
1933
1934         BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1935         refs += refs_to_mod;
1936
1937         if (refs > 0) {
1938                 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1939                         btrfs_set_extent_data_ref_count(leaf, dref, refs);
1940                 else
1941                         btrfs_set_shared_data_ref_count(leaf, sref, refs);
1942         } else {
1943                 *last_ref = 1;
1944                 size =  btrfs_extent_inline_ref_size(type);
1945                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1946                 ptr = (unsigned long)iref;
1947                 end = (unsigned long)ei + item_size;
1948                 if (ptr + size < end)
1949                         memmove_extent_buffer(leaf, ptr, ptr + size,
1950                                               end - ptr - size);
1951                 item_size -= size;
1952                 btrfs_truncate_item(fs_info, path, item_size, 1);
1953         }
1954         btrfs_mark_buffer_dirty(leaf);
1955 }
1956
1957 static noinline_for_stack
1958 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1959                                  struct btrfs_fs_info *fs_info,
1960                                  struct btrfs_path *path,
1961                                  u64 bytenr, u64 num_bytes, u64 parent,
1962                                  u64 root_objectid, u64 owner,
1963                                  u64 offset, int refs_to_add,
1964                                  struct btrfs_delayed_extent_op *extent_op)
1965 {
1966         struct btrfs_extent_inline_ref *iref;
1967         int ret;
1968
1969         ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1970                                            num_bytes, parent, root_objectid,
1971                                            owner, offset, 1);
1972         if (ret == 0) {
1973                 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1974                 update_inline_extent_backref(path, iref, refs_to_add,
1975                                              extent_op, NULL);
1976         } else if (ret == -ENOENT) {
1977                 setup_inline_extent_backref(fs_info, path, iref, parent,
1978                                             root_objectid, owner, offset,
1979                                             refs_to_add, extent_op);
1980                 ret = 0;
1981         }
1982         return ret;
1983 }
1984
1985 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1986                                  struct btrfs_path *path,
1987                                  u64 bytenr, u64 parent, u64 root_objectid,
1988                                  u64 owner, u64 offset, int refs_to_add)
1989 {
1990         int ret;
1991         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1992                 BUG_ON(refs_to_add != 1);
1993                 ret = insert_tree_block_ref(trans, path, bytenr, parent,
1994                                             root_objectid);
1995         } else {
1996                 ret = insert_extent_data_ref(trans, path, bytenr, parent,
1997                                              root_objectid, owner, offset,
1998                                              refs_to_add);
1999         }
2000         return ret;
2001 }
2002
2003 static int remove_extent_backref(struct btrfs_trans_handle *trans,
2004                                  struct btrfs_fs_info *fs_info,
2005                                  struct btrfs_path *path,
2006                                  struct btrfs_extent_inline_ref *iref,
2007                                  int refs_to_drop, int is_data, int *last_ref)
2008 {
2009         int ret = 0;
2010
2011         BUG_ON(!is_data && refs_to_drop != 1);
2012         if (iref) {
2013                 update_inline_extent_backref(path, iref, -refs_to_drop, NULL,
2014                                              last_ref);
2015         } else if (is_data) {
2016                 ret = remove_extent_data_ref(trans, path, refs_to_drop,
2017                                              last_ref);
2018         } else {
2019                 *last_ref = 1;
2020                 ret = btrfs_del_item(trans, fs_info->extent_root, path);
2021         }
2022         return ret;
2023 }
2024
2025 #define in_range(b, first, len)        ((b) >= (first) && (b) < (first) + (len))
2026 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
2027                                u64 *discarded_bytes)
2028 {
2029         int j, ret = 0;
2030         u64 bytes_left, end;
2031         u64 aligned_start = ALIGN(start, 1 << 9);
2032
2033         if (WARN_ON(start != aligned_start)) {
2034                 len -= aligned_start - start;
2035                 len = round_down(len, 1 << 9);
2036                 start = aligned_start;
2037         }
2038
2039         *discarded_bytes = 0;
2040
2041         if (!len)
2042                 return 0;
2043
2044         end = start + len;
2045         bytes_left = len;
2046
2047         /* Skip any superblocks on this device. */
2048         for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
2049                 u64 sb_start = btrfs_sb_offset(j);
2050                 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
2051                 u64 size = sb_start - start;
2052
2053                 if (!in_range(sb_start, start, bytes_left) &&
2054                     !in_range(sb_end, start, bytes_left) &&
2055                     !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
2056                         continue;
2057
2058                 /*
2059                  * Superblock spans beginning of range.  Adjust start and
2060                  * try again.
2061                  */
2062                 if (sb_start <= start) {
2063                         start += sb_end - start;
2064                         if (start > end) {
2065                                 bytes_left = 0;
2066                                 break;
2067                         }
2068                         bytes_left = end - start;
2069                         continue;
2070                 }
2071
2072                 if (size) {
2073                         ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
2074                                                    GFP_NOFS, 0);
2075                         if (!ret)
2076                                 *discarded_bytes += size;
2077                         else if (ret != -EOPNOTSUPP)
2078                                 return ret;
2079                 }
2080
2081                 start = sb_end;
2082                 if (start > end) {
2083                         bytes_left = 0;
2084                         break;
2085                 }
2086                 bytes_left = end - start;
2087         }
2088
2089         if (bytes_left) {
2090                 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
2091                                            GFP_NOFS, 0);
2092                 if (!ret)
2093                         *discarded_bytes += bytes_left;
2094         }
2095         return ret;
2096 }
2097
2098 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
2099                          u64 num_bytes, u64 *actual_bytes)
2100 {
2101         int ret;
2102         u64 discarded_bytes = 0;
2103         struct btrfs_bio *bbio = NULL;
2104
2105
2106         /*
2107          * Avoid races with device replace and make sure our bbio has devices
2108          * associated to its stripes that don't go away while we are discarding.
2109          */
2110         btrfs_bio_counter_inc_blocked(fs_info);
2111         /* Tell the block device(s) that the sectors can be discarded */
2112         ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, bytenr, &num_bytes,
2113                               &bbio, 0);
2114         /* Error condition is -ENOMEM */
2115         if (!ret) {
2116                 struct btrfs_bio_stripe *stripe = bbio->stripes;
2117                 int i;
2118
2119
2120                 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
2121                         u64 bytes;
2122                         struct request_queue *req_q;
2123
2124                         if (!stripe->dev->bdev) {
2125                                 ASSERT(btrfs_test_opt(fs_info, DEGRADED));
2126                                 continue;
2127                         }
2128                         req_q = bdev_get_queue(stripe->dev->bdev);
2129                         if (!blk_queue_discard(req_q))
2130                                 continue;
2131
2132                         ret = btrfs_issue_discard(stripe->dev->bdev,
2133                                                   stripe->physical,
2134                                                   stripe->length,
2135                                                   &bytes);
2136                         if (!ret)
2137                                 discarded_bytes += bytes;
2138                         else if (ret != -EOPNOTSUPP)
2139                                 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
2140
2141                         /*
2142                          * Just in case we get back EOPNOTSUPP for some reason,
2143                          * just ignore the return value so we don't screw up
2144                          * people calling discard_extent.
2145                          */
2146                         ret = 0;
2147                 }
2148                 btrfs_put_bbio(bbio);
2149         }
2150         btrfs_bio_counter_dec(fs_info);
2151
2152         if (actual_bytes)
2153                 *actual_bytes = discarded_bytes;
2154
2155
2156         if (ret == -EOPNOTSUPP)
2157                 ret = 0;
2158         return ret;
2159 }
2160
2161 /* Can return -ENOMEM */
2162 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2163                          struct btrfs_root *root,
2164                          u64 bytenr, u64 num_bytes, u64 parent,
2165                          u64 root_objectid, u64 owner, u64 offset)
2166 {
2167         struct btrfs_fs_info *fs_info = root->fs_info;
2168         int old_ref_mod, new_ref_mod;
2169         int ret;
2170
2171         BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
2172                root_objectid == BTRFS_TREE_LOG_OBJECTID);
2173
2174         btrfs_ref_tree_mod(root, bytenr, num_bytes, parent, root_objectid,
2175                            owner, offset, BTRFS_ADD_DELAYED_REF);
2176
2177         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
2178                 ret = btrfs_add_delayed_tree_ref(trans, bytenr,
2179                                                  num_bytes, parent,
2180                                                  root_objectid, (int)owner,
2181                                                  BTRFS_ADD_DELAYED_REF, NULL,
2182                                                  &old_ref_mod, &new_ref_mod);
2183         } else {
2184                 ret = btrfs_add_delayed_data_ref(trans, bytenr,
2185                                                  num_bytes, parent,
2186                                                  root_objectid, owner, offset,
2187                                                  0, BTRFS_ADD_DELAYED_REF,
2188                                                  &old_ref_mod, &new_ref_mod);
2189         }
2190
2191         if (ret == 0 && old_ref_mod < 0 && new_ref_mod >= 0) {
2192                 bool metadata = owner < BTRFS_FIRST_FREE_OBJECTID;
2193
2194                 add_pinned_bytes(fs_info, -num_bytes, metadata, root_objectid);
2195         }
2196
2197         return ret;
2198 }
2199
2200 /*
2201  * __btrfs_inc_extent_ref - insert backreference for a given extent
2202  *
2203  * @trans:          Handle of transaction
2204  *
2205  * @node:           The delayed ref node used to get the bytenr/length for
2206  *                  extent whose references are incremented.
2207  *
2208  * @parent:         If this is a shared extent (BTRFS_SHARED_DATA_REF_KEY/
2209  *                  BTRFS_SHARED_BLOCK_REF_KEY) then it holds the logical
2210  *                  bytenr of the parent block. Since new extents are always
2211  *                  created with indirect references, this will only be the case
2212  *                  when relocating a shared extent. In that case, root_objectid
2213  *                  will be BTRFS_TREE_RELOC_OBJECTID. Otheriwse, parent must
2214  *                  be 0
2215  *
2216  * @root_objectid:  The id of the root where this modification has originated,
2217  *                  this can be either one of the well-known metadata trees or
2218  *                  the subvolume id which references this extent.
2219  *
2220  * @owner:          For data extents it is the inode number of the owning file.
2221  *                  For metadata extents this parameter holds the level in the
2222  *                  tree of the extent.
2223  *
2224  * @offset:         For metadata extents the offset is ignored and is currently
2225  *                  always passed as 0. For data extents it is the fileoffset
2226  *                  this extent belongs to.
2227  *
2228  * @refs_to_add     Number of references to add
2229  *
2230  * @extent_op       Pointer to a structure, holding information necessary when
2231  *                  updating a tree block's flags
2232  *
2233  */
2234 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2235                                   struct btrfs_fs_info *fs_info,
2236                                   struct btrfs_delayed_ref_node *node,
2237                                   u64 parent, u64 root_objectid,
2238                                   u64 owner, u64 offset, int refs_to_add,
2239                                   struct btrfs_delayed_extent_op *extent_op)
2240 {
2241         struct btrfs_path *path;
2242         struct extent_buffer *leaf;
2243         struct btrfs_extent_item *item;
2244         struct btrfs_key key;
2245         u64 bytenr = node->bytenr;
2246         u64 num_bytes = node->num_bytes;
2247         u64 refs;
2248         int ret;
2249
2250         path = btrfs_alloc_path();
2251         if (!path)
2252                 return -ENOMEM;
2253
2254         path->reada = READA_FORWARD;
2255         path->leave_spinning = 1;
2256         /* this will setup the path even if it fails to insert the back ref */
2257         ret = insert_inline_extent_backref(trans, fs_info, path, bytenr,
2258                                            num_bytes, parent, root_objectid,
2259                                            owner, offset,
2260                                            refs_to_add, extent_op);
2261         if ((ret < 0 && ret != -EAGAIN) || !ret)
2262                 goto out;
2263
2264         /*
2265          * Ok we had -EAGAIN which means we didn't have space to insert and
2266          * inline extent ref, so just update the reference count and add a
2267          * normal backref.
2268          */
2269         leaf = path->nodes[0];
2270         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2271         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2272         refs = btrfs_extent_refs(leaf, item);
2273         btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2274         if (extent_op)
2275                 __run_delayed_extent_op(extent_op, leaf, item);
2276
2277         btrfs_mark_buffer_dirty(leaf);
2278         btrfs_release_path(path);
2279
2280         path->reada = READA_FORWARD;
2281         path->leave_spinning = 1;
2282         /* now insert the actual backref */
2283         ret = insert_extent_backref(trans, path, bytenr, parent, root_objectid,
2284                                     owner, offset, refs_to_add);
2285         if (ret)
2286                 btrfs_abort_transaction(trans, ret);
2287 out:
2288         btrfs_free_path(path);
2289         return ret;
2290 }
2291
2292 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2293                                 struct btrfs_fs_info *fs_info,
2294                                 struct btrfs_delayed_ref_node *node,
2295                                 struct btrfs_delayed_extent_op *extent_op,
2296                                 int insert_reserved)
2297 {
2298         int ret = 0;
2299         struct btrfs_delayed_data_ref *ref;
2300         struct btrfs_key ins;
2301         u64 parent = 0;
2302         u64 ref_root = 0;
2303         u64 flags = 0;
2304
2305         ins.objectid = node->bytenr;
2306         ins.offset = node->num_bytes;
2307         ins.type = BTRFS_EXTENT_ITEM_KEY;
2308
2309         ref = btrfs_delayed_node_to_data_ref(node);
2310         trace_run_delayed_data_ref(fs_info, node, ref, node->action);
2311
2312         if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2313                 parent = ref->parent;
2314         ref_root = ref->root;
2315
2316         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2317                 if (extent_op)
2318                         flags |= extent_op->flags_to_set;
2319                 ret = alloc_reserved_file_extent(trans, fs_info,
2320                                                  parent, ref_root, flags,
2321                                                  ref->objectid, ref->offset,
2322                                                  &ins, node->ref_mod);
2323         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2324                 ret = __btrfs_inc_extent_ref(trans, fs_info, node, parent,
2325                                              ref_root, ref->objectid,
2326                                              ref->offset, node->ref_mod,
2327                                              extent_op);
2328         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2329                 ret = __btrfs_free_extent(trans, node, parent,
2330                                           ref_root, ref->objectid,
2331                                           ref->offset, node->ref_mod,
2332                                           extent_op);
2333         } else {
2334                 BUG();
2335         }
2336         return ret;
2337 }
2338
2339 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2340                                     struct extent_buffer *leaf,
2341                                     struct btrfs_extent_item *ei)
2342 {
2343         u64 flags = btrfs_extent_flags(leaf, ei);
2344         if (extent_op->update_flags) {
2345                 flags |= extent_op->flags_to_set;
2346                 btrfs_set_extent_flags(leaf, ei, flags);
2347         }
2348
2349         if (extent_op->update_key) {
2350                 struct btrfs_tree_block_info *bi;
2351                 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2352                 bi = (struct btrfs_tree_block_info *)(ei + 1);
2353                 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2354         }
2355 }
2356
2357 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2358                                  struct btrfs_fs_info *fs_info,
2359                                  struct btrfs_delayed_ref_head *head,
2360                                  struct btrfs_delayed_extent_op *extent_op)
2361 {
2362         struct btrfs_key key;
2363         struct btrfs_path *path;
2364         struct btrfs_extent_item *ei;
2365         struct extent_buffer *leaf;
2366         u32 item_size;
2367         int ret;
2368         int err = 0;
2369         int metadata = !extent_op->is_data;
2370
2371         if (trans->aborted)
2372                 return 0;
2373
2374         if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2375                 metadata = 0;
2376
2377         path = btrfs_alloc_path();
2378         if (!path)
2379                 return -ENOMEM;
2380
2381         key.objectid = head->bytenr;
2382
2383         if (metadata) {
2384                 key.type = BTRFS_METADATA_ITEM_KEY;
2385                 key.offset = extent_op->level;
2386         } else {
2387                 key.type = BTRFS_EXTENT_ITEM_KEY;
2388                 key.offset = head->num_bytes;
2389         }
2390
2391 again:
2392         path->reada = READA_FORWARD;
2393         path->leave_spinning = 1;
2394         ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
2395         if (ret < 0) {
2396                 err = ret;
2397                 goto out;
2398         }
2399         if (ret > 0) {
2400                 if (metadata) {
2401                         if (path->slots[0] > 0) {
2402                                 path->slots[0]--;
2403                                 btrfs_item_key_to_cpu(path->nodes[0], &key,
2404                                                       path->slots[0]);
2405                                 if (key.objectid == head->bytenr &&
2406                                     key.type == BTRFS_EXTENT_ITEM_KEY &&
2407                                     key.offset == head->num_bytes)
2408                                         ret = 0;
2409                         }
2410                         if (ret > 0) {
2411                                 btrfs_release_path(path);
2412                                 metadata = 0;
2413
2414                                 key.objectid = head->bytenr;
2415                                 key.offset = head->num_bytes;
2416                                 key.type = BTRFS_EXTENT_ITEM_KEY;
2417                                 goto again;
2418                         }
2419                 } else {
2420                         err = -EIO;
2421                         goto out;
2422                 }
2423         }
2424
2425         leaf = path->nodes[0];
2426         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2427 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2428         if (item_size < sizeof(*ei)) {
2429                 ret = convert_extent_item_v0(trans, fs_info, path, (u64)-1, 0);
2430                 if (ret < 0) {
2431                         err = ret;
2432                         goto out;
2433                 }
2434                 leaf = path->nodes[0];
2435                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2436         }
2437 #endif
2438         BUG_ON(item_size < sizeof(*ei));
2439         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2440         __run_delayed_extent_op(extent_op, leaf, ei);
2441
2442         btrfs_mark_buffer_dirty(leaf);
2443 out:
2444         btrfs_free_path(path);
2445         return err;
2446 }
2447
2448 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2449                                 struct btrfs_fs_info *fs_info,
2450                                 struct btrfs_delayed_ref_node *node,
2451                                 struct btrfs_delayed_extent_op *extent_op,
2452                                 int insert_reserved)
2453 {
2454         int ret = 0;
2455         struct btrfs_delayed_tree_ref *ref;
2456         u64 parent = 0;
2457         u64 ref_root = 0;
2458
2459         ref = btrfs_delayed_node_to_tree_ref(node);
2460         trace_run_delayed_tree_ref(fs_info, node, ref, node->action);
2461
2462         if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2463                 parent = ref->parent;
2464         ref_root = ref->root;
2465
2466         if (node->ref_mod != 1) {
2467                 btrfs_err(fs_info,
2468         "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
2469                           node->bytenr, node->ref_mod, node->action, ref_root,
2470                           parent);
2471                 return -EIO;
2472         }
2473         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2474                 BUG_ON(!extent_op || !extent_op->update_flags);
2475                 ret = alloc_reserved_tree_block(trans, node, extent_op);
2476         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2477                 ret = __btrfs_inc_extent_ref(trans, fs_info, node,
2478                                              parent, ref_root,
2479                                              ref->level, 0, 1,
2480                                              extent_op);
2481         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2482                 ret = __btrfs_free_extent(trans, node, parent, ref_root,
2483                                           ref->level, 0, 1, extent_op);
2484         } else {
2485                 BUG();
2486         }
2487         return ret;
2488 }
2489
2490 /* helper function to actually process a single delayed ref entry */
2491 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2492                                struct btrfs_fs_info *fs_info,
2493                                struct btrfs_delayed_ref_node *node,
2494                                struct btrfs_delayed_extent_op *extent_op,
2495                                int insert_reserved)
2496 {
2497         int ret = 0;
2498
2499         if (trans->aborted) {
2500                 if (insert_reserved)
2501                         btrfs_pin_extent(fs_info, node->bytenr,
2502                                          node->num_bytes, 1);
2503                 return 0;
2504         }
2505
2506         if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2507             node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2508                 ret = run_delayed_tree_ref(trans, fs_info, node, extent_op,
2509                                            insert_reserved);
2510         else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2511                  node->type == BTRFS_SHARED_DATA_REF_KEY)
2512                 ret = run_delayed_data_ref(trans, fs_info, node, extent_op,
2513                                            insert_reserved);
2514         else
2515                 BUG();
2516         return ret;
2517 }
2518
2519 static inline struct btrfs_delayed_ref_node *
2520 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2521 {
2522         struct btrfs_delayed_ref_node *ref;
2523
2524         if (RB_EMPTY_ROOT(&head->ref_tree))
2525                 return NULL;
2526
2527         /*
2528          * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
2529          * This is to prevent a ref count from going down to zero, which deletes
2530          * the extent item from the extent tree, when there still are references
2531          * to add, which would fail because they would not find the extent item.
2532          */
2533         if (!list_empty(&head->ref_add_list))
2534                 return list_first_entry(&head->ref_add_list,
2535                                 struct btrfs_delayed_ref_node, add_list);
2536
2537         ref = rb_entry(rb_first(&head->ref_tree),
2538                        struct btrfs_delayed_ref_node, ref_node);
2539         ASSERT(list_empty(&ref->add_list));
2540         return ref;
2541 }
2542
2543 static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
2544                                       struct btrfs_delayed_ref_head *head)
2545 {
2546         spin_lock(&delayed_refs->lock);
2547         head->processing = 0;
2548         delayed_refs->num_heads_ready++;
2549         spin_unlock(&delayed_refs->lock);
2550         btrfs_delayed_ref_unlock(head);
2551 }
2552
2553 static int cleanup_extent_op(struct btrfs_trans_handle *trans,
2554                              struct btrfs_fs_info *fs_info,
2555                              struct btrfs_delayed_ref_head *head)
2556 {
2557         struct btrfs_delayed_extent_op *extent_op = head->extent_op;
2558         int ret;
2559
2560         if (!extent_op)
2561                 return 0;
2562         head->extent_op = NULL;
2563         if (head->must_insert_reserved) {
2564                 btrfs_free_delayed_extent_op(extent_op);
2565                 return 0;
2566         }
2567         spin_unlock(&head->lock);
2568         ret = run_delayed_extent_op(trans, fs_info, head, extent_op);
2569         btrfs_free_delayed_extent_op(extent_op);
2570         return ret ? ret : 1;
2571 }
2572
2573 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
2574                             struct btrfs_fs_info *fs_info,
2575                             struct btrfs_delayed_ref_head *head)
2576 {
2577         struct btrfs_delayed_ref_root *delayed_refs;
2578         int ret;
2579
2580         delayed_refs = &trans->transaction->delayed_refs;
2581
2582         ret = cleanup_extent_op(trans, fs_info, head);
2583         if (ret < 0) {
2584                 unselect_delayed_ref_head(delayed_refs, head);
2585                 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
2586                 return ret;
2587         } else if (ret) {
2588                 return ret;
2589         }
2590
2591         /*
2592          * Need to drop our head ref lock and re-acquire the delayed ref lock
2593          * and then re-check to make sure nobody got added.
2594          */
2595         spin_unlock(&head->lock);
2596         spin_lock(&delayed_refs->lock);
2597         spin_lock(&head->lock);
2598         if (!RB_EMPTY_ROOT(&head->ref_tree) || head->extent_op) {
2599                 spin_unlock(&head->lock);
2600                 spin_unlock(&delayed_refs->lock);
2601                 return 1;
2602         }
2603         delayed_refs->num_heads--;
2604         rb_erase(&head->href_node, &delayed_refs->href_root);
2605         RB_CLEAR_NODE(&head->href_node);
2606         spin_unlock(&head->lock);
2607         spin_unlock(&delayed_refs->lock);
2608         atomic_dec(&delayed_refs->num_entries);
2609
2610         trace_run_delayed_ref_head(fs_info, head, 0);
2611
2612         if (head->total_ref_mod < 0) {
2613                 struct btrfs_space_info *space_info;
2614                 u64 flags;
2615
2616                 if (head->is_data)
2617                         flags = BTRFS_BLOCK_GROUP_DATA;
2618                 else if (head->is_system)
2619                         flags = BTRFS_BLOCK_GROUP_SYSTEM;
2620                 else
2621                         flags = BTRFS_BLOCK_GROUP_METADATA;
2622                 space_info = __find_space_info(fs_info, flags);
2623                 ASSERT(space_info);
2624                 percpu_counter_add(&space_info->total_bytes_pinned,
2625                                    -head->num_bytes);
2626
2627                 if (head->is_data) {
2628                         spin_lock(&delayed_refs->lock);
2629                         delayed_refs->pending_csums -= head->num_bytes;
2630                         spin_unlock(&delayed_refs->lock);
2631                 }
2632         }
2633
2634         if (head->must_insert_reserved) {
2635                 btrfs_pin_extent(fs_info, head->bytenr,
2636                                  head->num_bytes, 1);
2637                 if (head->is_data) {
2638                         ret = btrfs_del_csums(trans, fs_info, head->bytenr,
2639                                               head->num_bytes);
2640                 }
2641         }
2642
2643         /* Also free its reserved qgroup space */
2644         btrfs_qgroup_free_delayed_ref(fs_info, head->qgroup_ref_root,
2645                                       head->qgroup_reserved);
2646         btrfs_delayed_ref_unlock(head);
2647         btrfs_put_delayed_ref_head(head);
2648         return 0;
2649 }
2650
2651 /*
2652  * Returns 0 on success or if called with an already aborted transaction.
2653  * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2654  */
2655 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2656                                              unsigned long nr)
2657 {
2658         struct btrfs_fs_info *fs_info = trans->fs_info;
2659         struct btrfs_delayed_ref_root *delayed_refs;
2660         struct btrfs_delayed_ref_node *ref;
2661         struct btrfs_delayed_ref_head *locked_ref = NULL;
2662         struct btrfs_delayed_extent_op *extent_op;
2663         ktime_t start = ktime_get();
2664         int ret;
2665         unsigned long count = 0;
2666         unsigned long actual_count = 0;
2667         int must_insert_reserved = 0;
2668
2669         delayed_refs = &trans->transaction->delayed_refs;
2670         while (1) {
2671                 if (!locked_ref) {
2672                         if (count >= nr)
2673                                 break;
2674
2675                         spin_lock(&delayed_refs->lock);
2676                         locked_ref = btrfs_select_ref_head(trans);
2677                         if (!locked_ref) {
2678                                 spin_unlock(&delayed_refs->lock);
2679                                 break;
2680                         }
2681
2682                         /* grab the lock that says we are going to process
2683                          * all the refs for this head */
2684                         ret = btrfs_delayed_ref_lock(trans, locked_ref);
2685                         spin_unlock(&delayed_refs->lock);
2686                         /*
2687                          * we may have dropped the spin lock to get the head
2688                          * mutex lock, and that might have given someone else
2689                          * time to free the head.  If that's true, it has been
2690                          * removed from our list and we can move on.
2691                          */
2692                         if (ret == -EAGAIN) {
2693                                 locked_ref = NULL;
2694                                 count++;
2695                                 continue;
2696                         }
2697                 }
2698
2699                 /*
2700                  * We need to try and merge add/drops of the same ref since we
2701                  * can run into issues with relocate dropping the implicit ref
2702                  * and then it being added back again before the drop can
2703                  * finish.  If we merged anything we need to re-loop so we can
2704                  * get a good ref.
2705                  * Or we can get node references of the same type that weren't
2706                  * merged when created due to bumps in the tree mod seq, and
2707                  * we need to merge them to prevent adding an inline extent
2708                  * backref before dropping it (triggering a BUG_ON at
2709                  * insert_inline_extent_backref()).
2710                  */
2711                 spin_lock(&locked_ref->lock);
2712                 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2713
2714                 ref = select_delayed_ref(locked_ref);
2715
2716                 if (ref && ref->seq &&
2717                     btrfs_check_delayed_seq(fs_info, ref->seq)) {
2718                         spin_unlock(&locked_ref->lock);
2719                         unselect_delayed_ref_head(delayed_refs, locked_ref);
2720                         locked_ref = NULL;
2721                         cond_resched();
2722                         count++;
2723                         continue;
2724                 }
2725
2726                 /*
2727                  * We're done processing refs in this ref_head, clean everything
2728                  * up and move on to the next ref_head.
2729                  */
2730                 if (!ref) {
2731                         ret = cleanup_ref_head(trans, fs_info, locked_ref);
2732                         if (ret > 0 ) {
2733                                 /* We dropped our lock, we need to loop. */
2734                                 ret = 0;
2735                                 continue;
2736                         } else if (ret) {
2737                                 return ret;
2738                         }
2739                         locked_ref = NULL;
2740                         count++;
2741                         continue;
2742                 }
2743
2744                 actual_count++;
2745                 ref->in_tree = 0;
2746                 rb_erase(&ref->ref_node, &locked_ref->ref_tree);
2747                 RB_CLEAR_NODE(&ref->ref_node);
2748                 if (!list_empty(&ref->add_list))
2749                         list_del(&ref->add_list);
2750                 /*
2751                  * When we play the delayed ref, also correct the ref_mod on
2752                  * head
2753                  */
2754                 switch (ref->action) {
2755                 case BTRFS_ADD_DELAYED_REF:
2756                 case BTRFS_ADD_DELAYED_EXTENT:
2757                         locked_ref->ref_mod -= ref->ref_mod;
2758                         break;
2759                 case BTRFS_DROP_DELAYED_REF:
2760                         locked_ref->ref_mod += ref->ref_mod;
2761                         break;
2762                 default:
2763                         WARN_ON(1);
2764                 }
2765                 atomic_dec(&delayed_refs->num_entries);
2766
2767                 /*
2768                  * Record the must-insert_reserved flag before we drop the spin
2769                  * lock.
2770                  */
2771                 must_insert_reserved = locked_ref->must_insert_reserved;
2772                 locked_ref->must_insert_reserved = 0;
2773
2774                 extent_op = locked_ref->extent_op;
2775                 locked_ref->extent_op = NULL;
2776                 spin_unlock(&locked_ref->lock);
2777
2778                 ret = run_one_delayed_ref(trans, fs_info, ref, extent_op,
2779                                           must_insert_reserved);
2780
2781                 btrfs_free_delayed_extent_op(extent_op);
2782                 if (ret) {
2783                         unselect_delayed_ref_head(delayed_refs, locked_ref);
2784                         btrfs_put_delayed_ref(ref);
2785                         btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
2786                                     ret);
2787                         return ret;
2788                 }
2789
2790                 btrfs_put_delayed_ref(ref);
2791                 count++;
2792                 cond_resched();
2793         }
2794
2795         /*
2796          * We don't want to include ref heads since we can have empty ref heads
2797          * and those will drastically skew our runtime down since we just do
2798          * accounting, no actual extent tree updates.
2799          */
2800         if (actual_count > 0) {
2801                 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2802                 u64 avg;
2803
2804                 /*
2805                  * We weigh the current average higher than our current runtime
2806                  * to avoid large swings in the average.
2807                  */
2808                 spin_lock(&delayed_refs->lock);
2809                 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2810                 fs_info->avg_delayed_ref_runtime = avg >> 2;    /* div by 4 */
2811                 spin_unlock(&delayed_refs->lock);
2812         }
2813         return 0;
2814 }
2815
2816 #ifdef SCRAMBLE_DELAYED_REFS
2817 /*
2818  * Normally delayed refs get processed in ascending bytenr order. This
2819  * correlates in most cases to the order added. To expose dependencies on this
2820  * order, we start to process the tree in the middle instead of the beginning
2821  */
2822 static u64 find_middle(struct rb_root *root)
2823 {
2824         struct rb_node *n = root->rb_node;
2825         struct btrfs_delayed_ref_node *entry;
2826         int alt = 1;
2827         u64 middle;
2828         u64 first = 0, last = 0;
2829
2830         n = rb_first(root);
2831         if (n) {
2832                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2833                 first = entry->bytenr;
2834         }
2835         n = rb_last(root);
2836         if (n) {
2837                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2838                 last = entry->bytenr;
2839         }
2840         n = root->rb_node;
2841
2842         while (n) {
2843                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2844                 WARN_ON(!entry->in_tree);
2845
2846                 middle = entry->bytenr;
2847
2848                 if (alt)
2849                         n = n->rb_left;
2850                 else
2851                         n = n->rb_right;
2852
2853                 alt = 1 - alt;
2854         }
2855         return middle;
2856 }
2857 #endif
2858
2859 static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
2860 {
2861         u64 num_bytes;
2862
2863         num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2864                              sizeof(struct btrfs_extent_inline_ref));
2865         if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2866                 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2867
2868         /*
2869          * We don't ever fill up leaves all the way so multiply by 2 just to be
2870          * closer to what we're really going to want to use.
2871          */
2872         return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
2873 }
2874
2875 /*
2876  * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2877  * would require to store the csums for that many bytes.
2878  */
2879 u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
2880 {
2881         u64 csum_size;
2882         u64 num_csums_per_leaf;
2883         u64 num_csums;
2884
2885         csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
2886         num_csums_per_leaf = div64_u64(csum_size,
2887                         (u64)btrfs_super_csum_size(fs_info->super_copy));
2888         num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
2889         num_csums += num_csums_per_leaf - 1;
2890         num_csums = div64_u64(num_csums, num_csums_per_leaf);
2891         return num_csums;
2892 }
2893
2894 int btrfs_check_space_for_delayed_refs(struct btrfs_trans_handle *trans,
2895                                        struct btrfs_fs_info *fs_info)
2896 {
2897         struct btrfs_block_rsv *global_rsv;
2898         u64 num_heads = trans->transaction->delayed_refs.num_heads_ready;
2899         u64 csum_bytes = trans->transaction->delayed_refs.pending_csums;
2900         unsigned int num_dirty_bgs = trans->transaction->num_dirty_bgs;
2901         u64 num_bytes, num_dirty_bgs_bytes;
2902         int ret = 0;
2903
2904         num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
2905         num_heads = heads_to_leaves(fs_info, num_heads);
2906         if (num_heads > 1)
2907                 num_bytes += (num_heads - 1) * fs_info->nodesize;
2908         num_bytes <<= 1;
2909         num_bytes += btrfs_csum_bytes_to_leaves(fs_info, csum_bytes) *
2910                                                         fs_info->nodesize;
2911         num_dirty_bgs_bytes = btrfs_calc_trans_metadata_size(fs_info,
2912                                                              num_dirty_bgs);
2913         global_rsv = &fs_info->global_block_rsv;
2914
2915         /*
2916          * If we can't allocate any more chunks lets make sure we have _lots_ of
2917          * wiggle room since running delayed refs can create more delayed refs.
2918          */
2919         if (global_rsv->space_info->full) {
2920                 num_dirty_bgs_bytes <<= 1;
2921                 num_bytes <<= 1;
2922         }
2923
2924         spin_lock(&global_rsv->lock);
2925         if (global_rsv->reserved <= num_bytes + num_dirty_bgs_bytes)
2926                 ret = 1;
2927         spin_unlock(&global_rsv->lock);
2928         return ret;
2929 }
2930
2931 int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans,
2932                                        struct btrfs_fs_info *fs_info)
2933 {
2934         u64 num_entries =
2935                 atomic_read(&trans->transaction->delayed_refs.num_entries);
2936         u64 avg_runtime;
2937         u64 val;
2938
2939         smp_mb();
2940         avg_runtime = fs_info->avg_delayed_ref_runtime;
2941         val = num_entries * avg_runtime;
2942         if (val >= NSEC_PER_SEC)
2943                 return 1;
2944         if (val >= NSEC_PER_SEC / 2)
2945                 return 2;
2946
2947         return btrfs_check_space_for_delayed_refs(trans, fs_info);
2948 }
2949
2950 struct async_delayed_refs {
2951         struct btrfs_root *root;
2952         u64 transid;
2953         int count;
2954         int error;
2955         int sync;
2956         struct completion wait;
2957         struct btrfs_work work;
2958 };
2959
2960 static inline struct async_delayed_refs *
2961 to_async_delayed_refs(struct btrfs_work *work)
2962 {
2963         return container_of(work, struct async_delayed_refs, work);
2964 }
2965
2966 static void delayed_ref_async_start(struct btrfs_work *work)
2967 {
2968         struct async_delayed_refs *async = to_async_delayed_refs(work);
2969         struct btrfs_trans_handle *trans;
2970         struct btrfs_fs_info *fs_info = async->root->fs_info;
2971         int ret;
2972
2973         /* if the commit is already started, we don't need to wait here */
2974         if (btrfs_transaction_blocked(fs_info))
2975                 goto done;
2976
2977         trans = btrfs_join_transaction(async->root);
2978         if (IS_ERR(trans)) {
2979                 async->error = PTR_ERR(trans);
2980                 goto done;
2981         }
2982
2983         /*
2984          * trans->sync means that when we call end_transaction, we won't
2985          * wait on delayed refs
2986          */
2987         trans->sync = true;
2988
2989         /* Don't bother flushing if we got into a different transaction */
2990         if (trans->transid > async->transid)
2991                 goto end;
2992
2993         ret = btrfs_run_delayed_refs(trans, async->count);
2994         if (ret)
2995                 async->error = ret;
2996 end:
2997         ret = btrfs_end_transaction(trans);
2998         if (ret && !async->error)
2999                 async->error = ret;
3000 done:
3001         if (async->sync)
3002                 complete(&async->wait);
3003         else
3004                 kfree(async);
3005 }
3006
3007 int btrfs_async_run_delayed_refs(struct btrfs_fs_info *fs_info,
3008                                  unsigned long count, u64 transid, int wait)
3009 {
3010         struct async_delayed_refs *async;
3011         int ret;
3012
3013         async = kmalloc(sizeof(*async), GFP_NOFS);
3014         if (!async)
3015                 return -ENOMEM;
3016
3017         async->root = fs_info->tree_root;
3018         async->count = count;
3019         async->error = 0;
3020         async->transid = transid;
3021         if (wait)
3022                 async->sync = 1;
3023         else
3024                 async->sync = 0;
3025         init_completion(&async->wait);
3026
3027         btrfs_init_work(&async->work, btrfs_extent_refs_helper,
3028                         delayed_ref_async_start, NULL, NULL);
3029
3030         btrfs_queue_work(fs_info->extent_workers, &async->work);
3031
3032         if (wait) {
3033                 wait_for_completion(&async->wait);
3034                 ret = async->error;
3035                 kfree(async);
3036                 return ret;
3037         }
3038         return 0;
3039 }
3040
3041 /*
3042  * this starts processing the delayed reference count updates and
3043  * extent insertions we have queued up so far.  count can be
3044  * 0, which means to process everything in the tree at the start
3045  * of the run (but not newly added entries), or it can be some target
3046  * number you'd like to process.
3047  *
3048  * Returns 0 on success or if called with an aborted transaction
3049  * Returns <0 on error and aborts the transaction
3050  */
3051 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
3052                            unsigned long count)
3053 {
3054         struct btrfs_fs_info *fs_info = trans->fs_info;
3055         struct rb_node *node;
3056         struct btrfs_delayed_ref_root *delayed_refs;
3057         struct btrfs_delayed_ref_head *head;
3058         int ret;
3059         int run_all = count == (unsigned long)-1;
3060         bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
3061
3062         /* We'll clean this up in btrfs_cleanup_transaction */
3063         if (trans->aborted)
3064                 return 0;
3065
3066         if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
3067                 return 0;
3068