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