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