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