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