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