]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blob - fs/btrfs/extent-tree.c
Btrfs: free tmp ulist for qgroup rescan
[mirror_ubuntu-bionic-kernel.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 "math.h"
37 #include "sysfs.h"
38 #include "qgroup.h"
39
40 #undef SCRAMBLE_DELAYED_REFS
41
42 /*
43 * control flags for do_chunk_alloc's force field
44 * CHUNK_ALLOC_NO_FORCE means to only allocate a chunk
45 * if we really need one.
46 *
47 * CHUNK_ALLOC_LIMITED means to only try and allocate one
48 * if we have very few chunks already allocated. This is
49 * used as part of the clustering code to help make sure
50 * we have a good pool of storage to cluster in, without
51 * filling the FS with empty chunks
52 *
53 * CHUNK_ALLOC_FORCE means it must try to allocate one
54 *
55 */
56 enum {
57 CHUNK_ALLOC_NO_FORCE = 0,
58 CHUNK_ALLOC_LIMITED = 1,
59 CHUNK_ALLOC_FORCE = 2,
60 };
61
62 /*
63 * Control how reservations are dealt with.
64 *
65 * RESERVE_FREE - freeing a reservation.
66 * RESERVE_ALLOC - allocating space and we need to update bytes_may_use for
67 * ENOSPC accounting
68 * RESERVE_ALLOC_NO_ACCOUNT - allocating space and we should not update
69 * bytes_may_use as the ENOSPC accounting is done elsewhere
70 */
71 enum {
72 RESERVE_FREE = 0,
73 RESERVE_ALLOC = 1,
74 RESERVE_ALLOC_NO_ACCOUNT = 2,
75 };
76
77 static int update_block_group(struct btrfs_root *root,
78 u64 bytenr, u64 num_bytes, int alloc);
79 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
80 struct btrfs_root *root,
81 u64 bytenr, u64 num_bytes, u64 parent,
82 u64 root_objectid, u64 owner_objectid,
83 u64 owner_offset, int refs_to_drop,
84 struct btrfs_delayed_extent_op *extra_op,
85 int no_quota);
86 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
87 struct extent_buffer *leaf,
88 struct btrfs_extent_item *ei);
89 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
90 struct btrfs_root *root,
91 u64 parent, u64 root_objectid,
92 u64 flags, u64 owner, u64 offset,
93 struct btrfs_key *ins, int ref_mod);
94 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
95 struct btrfs_root *root,
96 u64 parent, u64 root_objectid,
97 u64 flags, struct btrfs_disk_key *key,
98 int level, struct btrfs_key *ins,
99 int no_quota);
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 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
110 u64 num_bytes);
111 int btrfs_pin_extent(struct btrfs_root *root,
112 u64 bytenr, u64 num_bytes, int reserved);
113
114 static noinline int
115 block_group_cache_done(struct btrfs_block_group_cache *cache)
116 {
117 smp_mb();
118 return cache->cached == BTRFS_CACHE_FINISHED ||
119 cache->cached == BTRFS_CACHE_ERROR;
120 }
121
122 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
123 {
124 return (cache->flags & bits) == bits;
125 }
126
127 static void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
128 {
129 atomic_inc(&cache->count);
130 }
131
132 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
133 {
134 if (atomic_dec_and_test(&cache->count)) {
135 WARN_ON(cache->pinned > 0);
136 WARN_ON(cache->reserved > 0);
137 kfree(cache->free_space_ctl);
138 kfree(cache);
139 }
140 }
141
142 /*
143 * this adds the block group to the fs_info rb tree for the block group
144 * cache
145 */
146 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
147 struct btrfs_block_group_cache *block_group)
148 {
149 struct rb_node **p;
150 struct rb_node *parent = NULL;
151 struct btrfs_block_group_cache *cache;
152
153 spin_lock(&info->block_group_cache_lock);
154 p = &info->block_group_cache_tree.rb_node;
155
156 while (*p) {
157 parent = *p;
158 cache = rb_entry(parent, struct btrfs_block_group_cache,
159 cache_node);
160 if (block_group->key.objectid < cache->key.objectid) {
161 p = &(*p)->rb_left;
162 } else if (block_group->key.objectid > cache->key.objectid) {
163 p = &(*p)->rb_right;
164 } else {
165 spin_unlock(&info->block_group_cache_lock);
166 return -EEXIST;
167 }
168 }
169
170 rb_link_node(&block_group->cache_node, parent, p);
171 rb_insert_color(&block_group->cache_node,
172 &info->block_group_cache_tree);
173
174 if (info->first_logical_byte > block_group->key.objectid)
175 info->first_logical_byte = block_group->key.objectid;
176
177 spin_unlock(&info->block_group_cache_lock);
178
179 return 0;
180 }
181
182 /*
183 * This will return the block group at or after bytenr if contains is 0, else
184 * it will return the block group that contains the bytenr
185 */
186 static struct btrfs_block_group_cache *
187 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
188 int contains)
189 {
190 struct btrfs_block_group_cache *cache, *ret = NULL;
191 struct rb_node *n;
192 u64 end, start;
193
194 spin_lock(&info->block_group_cache_lock);
195 n = info->block_group_cache_tree.rb_node;
196
197 while (n) {
198 cache = rb_entry(n, struct btrfs_block_group_cache,
199 cache_node);
200 end = cache->key.objectid + cache->key.offset - 1;
201 start = cache->key.objectid;
202
203 if (bytenr < start) {
204 if (!contains && (!ret || start < ret->key.objectid))
205 ret = cache;
206 n = n->rb_left;
207 } else if (bytenr > start) {
208 if (contains && bytenr <= end) {
209 ret = cache;
210 break;
211 }
212 n = n->rb_right;
213 } else {
214 ret = cache;
215 break;
216 }
217 }
218 if (ret) {
219 btrfs_get_block_group(ret);
220 if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
221 info->first_logical_byte = ret->key.objectid;
222 }
223 spin_unlock(&info->block_group_cache_lock);
224
225 return ret;
226 }
227
228 static int add_excluded_extent(struct btrfs_root *root,
229 u64 start, u64 num_bytes)
230 {
231 u64 end = start + num_bytes - 1;
232 set_extent_bits(&root->fs_info->freed_extents[0],
233 start, end, EXTENT_UPTODATE, GFP_NOFS);
234 set_extent_bits(&root->fs_info->freed_extents[1],
235 start, end, EXTENT_UPTODATE, GFP_NOFS);
236 return 0;
237 }
238
239 static void free_excluded_extents(struct btrfs_root *root,
240 struct btrfs_block_group_cache *cache)
241 {
242 u64 start, end;
243
244 start = cache->key.objectid;
245 end = start + cache->key.offset - 1;
246
247 clear_extent_bits(&root->fs_info->freed_extents[0],
248 start, end, EXTENT_UPTODATE, GFP_NOFS);
249 clear_extent_bits(&root->fs_info->freed_extents[1],
250 start, end, EXTENT_UPTODATE, GFP_NOFS);
251 }
252
253 static int exclude_super_stripes(struct btrfs_root *root,
254 struct btrfs_block_group_cache *cache)
255 {
256 u64 bytenr;
257 u64 *logical;
258 int stripe_len;
259 int i, nr, ret;
260
261 if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
262 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
263 cache->bytes_super += stripe_len;
264 ret = add_excluded_extent(root, cache->key.objectid,
265 stripe_len);
266 if (ret)
267 return ret;
268 }
269
270 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
271 bytenr = btrfs_sb_offset(i);
272 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
273 cache->key.objectid, bytenr,
274 0, &logical, &nr, &stripe_len);
275 if (ret)
276 return ret;
277
278 while (nr--) {
279 u64 start, len;
280
281 if (logical[nr] > cache->key.objectid +
282 cache->key.offset)
283 continue;
284
285 if (logical[nr] + stripe_len <= cache->key.objectid)
286 continue;
287
288 start = logical[nr];
289 if (start < cache->key.objectid) {
290 start = cache->key.objectid;
291 len = (logical[nr] + stripe_len) - start;
292 } else {
293 len = min_t(u64, stripe_len,
294 cache->key.objectid +
295 cache->key.offset - start);
296 }
297
298 cache->bytes_super += len;
299 ret = add_excluded_extent(root, start, len);
300 if (ret) {
301 kfree(logical);
302 return ret;
303 }
304 }
305
306 kfree(logical);
307 }
308 return 0;
309 }
310
311 static struct btrfs_caching_control *
312 get_caching_control(struct btrfs_block_group_cache *cache)
313 {
314 struct btrfs_caching_control *ctl;
315
316 spin_lock(&cache->lock);
317 if (cache->cached != BTRFS_CACHE_STARTED) {
318 spin_unlock(&cache->lock);
319 return NULL;
320 }
321
322 /* We're loading it the fast way, so we don't have a caching_ctl. */
323 if (!cache->caching_ctl) {
324 spin_unlock(&cache->lock);
325 return NULL;
326 }
327
328 ctl = cache->caching_ctl;
329 atomic_inc(&ctl->count);
330 spin_unlock(&cache->lock);
331 return ctl;
332 }
333
334 static void put_caching_control(struct btrfs_caching_control *ctl)
335 {
336 if (atomic_dec_and_test(&ctl->count))
337 kfree(ctl);
338 }
339
340 /*
341 * this is only called by cache_block_group, since we could have freed extents
342 * we need to check the pinned_extents for any extents that can't be used yet
343 * since their free space will be released as soon as the transaction commits.
344 */
345 static u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
346 struct btrfs_fs_info *info, u64 start, u64 end)
347 {
348 u64 extent_start, extent_end, size, total_added = 0;
349 int ret;
350
351 while (start < end) {
352 ret = find_first_extent_bit(info->pinned_extents, start,
353 &extent_start, &extent_end,
354 EXTENT_DIRTY | EXTENT_UPTODATE,
355 NULL);
356 if (ret)
357 break;
358
359 if (extent_start <= start) {
360 start = extent_end + 1;
361 } else if (extent_start > start && extent_start < end) {
362 size = extent_start - start;
363 total_added += size;
364 ret = btrfs_add_free_space(block_group, start,
365 size);
366 BUG_ON(ret); /* -ENOMEM or logic error */
367 start = extent_end + 1;
368 } else {
369 break;
370 }
371 }
372
373 if (start < end) {
374 size = end - start;
375 total_added += size;
376 ret = btrfs_add_free_space(block_group, start, size);
377 BUG_ON(ret); /* -ENOMEM or logic error */
378 }
379
380 return total_added;
381 }
382
383 static noinline void caching_thread(struct btrfs_work *work)
384 {
385 struct btrfs_block_group_cache *block_group;
386 struct btrfs_fs_info *fs_info;
387 struct btrfs_caching_control *caching_ctl;
388 struct btrfs_root *extent_root;
389 struct btrfs_path *path;
390 struct extent_buffer *leaf;
391 struct btrfs_key key;
392 u64 total_found = 0;
393 u64 last = 0;
394 u32 nritems;
395 int ret = -ENOMEM;
396
397 caching_ctl = container_of(work, struct btrfs_caching_control, work);
398 block_group = caching_ctl->block_group;
399 fs_info = block_group->fs_info;
400 extent_root = fs_info->extent_root;
401
402 path = btrfs_alloc_path();
403 if (!path)
404 goto out;
405
406 last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
407
408 /*
409 * We don't want to deadlock with somebody trying to allocate a new
410 * extent for the extent root while also trying to search the extent
411 * root to add free space. So we skip locking and search the commit
412 * root, since its read-only
413 */
414 path->skip_locking = 1;
415 path->search_commit_root = 1;
416 path->reada = 1;
417
418 key.objectid = last;
419 key.offset = 0;
420 key.type = BTRFS_EXTENT_ITEM_KEY;
421 again:
422 mutex_lock(&caching_ctl->mutex);
423 /* need to make sure the commit_root doesn't disappear */
424 down_read(&fs_info->commit_root_sem);
425
426 next:
427 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
428 if (ret < 0)
429 goto err;
430
431 leaf = path->nodes[0];
432 nritems = btrfs_header_nritems(leaf);
433
434 while (1) {
435 if (btrfs_fs_closing(fs_info) > 1) {
436 last = (u64)-1;
437 break;
438 }
439
440 if (path->slots[0] < nritems) {
441 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
442 } else {
443 ret = find_next_key(path, 0, &key);
444 if (ret)
445 break;
446
447 if (need_resched() ||
448 rwsem_is_contended(&fs_info->commit_root_sem)) {
449 caching_ctl->progress = last;
450 btrfs_release_path(path);
451 up_read(&fs_info->commit_root_sem);
452 mutex_unlock(&caching_ctl->mutex);
453 cond_resched();
454 goto again;
455 }
456
457 ret = btrfs_next_leaf(extent_root, path);
458 if (ret < 0)
459 goto err;
460 if (ret)
461 break;
462 leaf = path->nodes[0];
463 nritems = btrfs_header_nritems(leaf);
464 continue;
465 }
466
467 if (key.objectid < last) {
468 key.objectid = last;
469 key.offset = 0;
470 key.type = BTRFS_EXTENT_ITEM_KEY;
471
472 caching_ctl->progress = last;
473 btrfs_release_path(path);
474 goto next;
475 }
476
477 if (key.objectid < block_group->key.objectid) {
478 path->slots[0]++;
479 continue;
480 }
481
482 if (key.objectid >= block_group->key.objectid +
483 block_group->key.offset)
484 break;
485
486 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
487 key.type == BTRFS_METADATA_ITEM_KEY) {
488 total_found += add_new_free_space(block_group,
489 fs_info, last,
490 key.objectid);
491 if (key.type == BTRFS_METADATA_ITEM_KEY)
492 last = key.objectid +
493 fs_info->tree_root->leafsize;
494 else
495 last = key.objectid + key.offset;
496
497 if (total_found > (1024 * 1024 * 2)) {
498 total_found = 0;
499 wake_up(&caching_ctl->wait);
500 }
501 }
502 path->slots[0]++;
503 }
504 ret = 0;
505
506 total_found += add_new_free_space(block_group, fs_info, last,
507 block_group->key.objectid +
508 block_group->key.offset);
509 caching_ctl->progress = (u64)-1;
510
511 spin_lock(&block_group->lock);
512 block_group->caching_ctl = NULL;
513 block_group->cached = BTRFS_CACHE_FINISHED;
514 spin_unlock(&block_group->lock);
515
516 err:
517 btrfs_free_path(path);
518 up_read(&fs_info->commit_root_sem);
519
520 free_excluded_extents(extent_root, block_group);
521
522 mutex_unlock(&caching_ctl->mutex);
523 out:
524 if (ret) {
525 spin_lock(&block_group->lock);
526 block_group->caching_ctl = NULL;
527 block_group->cached = BTRFS_CACHE_ERROR;
528 spin_unlock(&block_group->lock);
529 }
530 wake_up(&caching_ctl->wait);
531
532 put_caching_control(caching_ctl);
533 btrfs_put_block_group(block_group);
534 }
535
536 static int cache_block_group(struct btrfs_block_group_cache *cache,
537 int load_cache_only)
538 {
539 DEFINE_WAIT(wait);
540 struct btrfs_fs_info *fs_info = cache->fs_info;
541 struct btrfs_caching_control *caching_ctl;
542 int ret = 0;
543
544 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
545 if (!caching_ctl)
546 return -ENOMEM;
547
548 INIT_LIST_HEAD(&caching_ctl->list);
549 mutex_init(&caching_ctl->mutex);
550 init_waitqueue_head(&caching_ctl->wait);
551 caching_ctl->block_group = cache;
552 caching_ctl->progress = cache->key.objectid;
553 atomic_set(&caching_ctl->count, 1);
554 btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
555
556 spin_lock(&cache->lock);
557 /*
558 * This should be a rare occasion, but this could happen I think in the
559 * case where one thread starts to load the space cache info, and then
560 * some other thread starts a transaction commit which tries to do an
561 * allocation while the other thread is still loading the space cache
562 * info. The previous loop should have kept us from choosing this block
563 * group, but if we've moved to the state where we will wait on caching
564 * block groups we need to first check if we're doing a fast load here,
565 * so we can wait for it to finish, otherwise we could end up allocating
566 * from a block group who's cache gets evicted for one reason or
567 * another.
568 */
569 while (cache->cached == BTRFS_CACHE_FAST) {
570 struct btrfs_caching_control *ctl;
571
572 ctl = cache->caching_ctl;
573 atomic_inc(&ctl->count);
574 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
575 spin_unlock(&cache->lock);
576
577 schedule();
578
579 finish_wait(&ctl->wait, &wait);
580 put_caching_control(ctl);
581 spin_lock(&cache->lock);
582 }
583
584 if (cache->cached != BTRFS_CACHE_NO) {
585 spin_unlock(&cache->lock);
586 kfree(caching_ctl);
587 return 0;
588 }
589 WARN_ON(cache->caching_ctl);
590 cache->caching_ctl = caching_ctl;
591 cache->cached = BTRFS_CACHE_FAST;
592 spin_unlock(&cache->lock);
593
594 if (fs_info->mount_opt & BTRFS_MOUNT_SPACE_CACHE) {
595 ret = load_free_space_cache(fs_info, cache);
596
597 spin_lock(&cache->lock);
598 if (ret == 1) {
599 cache->caching_ctl = NULL;
600 cache->cached = BTRFS_CACHE_FINISHED;
601 cache->last_byte_to_unpin = (u64)-1;
602 } else {
603 if (load_cache_only) {
604 cache->caching_ctl = NULL;
605 cache->cached = BTRFS_CACHE_NO;
606 } else {
607 cache->cached = BTRFS_CACHE_STARTED;
608 }
609 }
610 spin_unlock(&cache->lock);
611 wake_up(&caching_ctl->wait);
612 if (ret == 1) {
613 put_caching_control(caching_ctl);
614 free_excluded_extents(fs_info->extent_root, cache);
615 return 0;
616 }
617 } else {
618 /*
619 * We are not going to do the fast caching, set cached to the
620 * appropriate value and wakeup any waiters.
621 */
622 spin_lock(&cache->lock);
623 if (load_cache_only) {
624 cache->caching_ctl = NULL;
625 cache->cached = BTRFS_CACHE_NO;
626 } else {
627 cache->cached = BTRFS_CACHE_STARTED;
628 }
629 spin_unlock(&cache->lock);
630 wake_up(&caching_ctl->wait);
631 }
632
633 if (load_cache_only) {
634 put_caching_control(caching_ctl);
635 return 0;
636 }
637
638 down_write(&fs_info->commit_root_sem);
639 atomic_inc(&caching_ctl->count);
640 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
641 up_write(&fs_info->commit_root_sem);
642
643 btrfs_get_block_group(cache);
644
645 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
646
647 return ret;
648 }
649
650 /*
651 * return the block group that starts at or after bytenr
652 */
653 static struct btrfs_block_group_cache *
654 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
655 {
656 struct btrfs_block_group_cache *cache;
657
658 cache = block_group_cache_tree_search(info, bytenr, 0);
659
660 return cache;
661 }
662
663 /*
664 * return the block group that contains the given bytenr
665 */
666 struct btrfs_block_group_cache *btrfs_lookup_block_group(
667 struct btrfs_fs_info *info,
668 u64 bytenr)
669 {
670 struct btrfs_block_group_cache *cache;
671
672 cache = block_group_cache_tree_search(info, bytenr, 1);
673
674 return cache;
675 }
676
677 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
678 u64 flags)
679 {
680 struct list_head *head = &info->space_info;
681 struct btrfs_space_info *found;
682
683 flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
684
685 rcu_read_lock();
686 list_for_each_entry_rcu(found, head, list) {
687 if (found->flags & flags) {
688 rcu_read_unlock();
689 return found;
690 }
691 }
692 rcu_read_unlock();
693 return NULL;
694 }
695
696 /*
697 * after adding space to the filesystem, we need to clear the full flags
698 * on all the space infos.
699 */
700 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
701 {
702 struct list_head *head = &info->space_info;
703 struct btrfs_space_info *found;
704
705 rcu_read_lock();
706 list_for_each_entry_rcu(found, head, list)
707 found->full = 0;
708 rcu_read_unlock();
709 }
710
711 /* simple helper to search for an existing extent at a given offset */
712 int btrfs_lookup_extent(struct btrfs_root *root, u64 start, u64 len)
713 {
714 int ret;
715 struct btrfs_key key;
716 struct btrfs_path *path;
717
718 path = btrfs_alloc_path();
719 if (!path)
720 return -ENOMEM;
721
722 key.objectid = start;
723 key.offset = len;
724 key.type = BTRFS_EXTENT_ITEM_KEY;
725 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
726 0, 0);
727 if (ret > 0) {
728 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
729 if (key.objectid == start &&
730 key.type == BTRFS_METADATA_ITEM_KEY)
731 ret = 0;
732 }
733 btrfs_free_path(path);
734 return ret;
735 }
736
737 /*
738 * helper function to lookup reference count and flags of a tree block.
739 *
740 * the head node for delayed ref is used to store the sum of all the
741 * reference count modifications queued up in the rbtree. the head
742 * node may also store the extent flags to set. This way you can check
743 * to see what the reference count and extent flags would be if all of
744 * the delayed refs are not processed.
745 */
746 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
747 struct btrfs_root *root, u64 bytenr,
748 u64 offset, int metadata, u64 *refs, u64 *flags)
749 {
750 struct btrfs_delayed_ref_head *head;
751 struct btrfs_delayed_ref_root *delayed_refs;
752 struct btrfs_path *path;
753 struct btrfs_extent_item *ei;
754 struct extent_buffer *leaf;
755 struct btrfs_key key;
756 u32 item_size;
757 u64 num_refs;
758 u64 extent_flags;
759 int ret;
760
761 /*
762 * If we don't have skinny metadata, don't bother doing anything
763 * different
764 */
765 if (metadata && !btrfs_fs_incompat(root->fs_info, SKINNY_METADATA)) {
766 offset = root->leafsize;
767 metadata = 0;
768 }
769
770 path = btrfs_alloc_path();
771 if (!path)
772 return -ENOMEM;
773
774 if (!trans) {
775 path->skip_locking = 1;
776 path->search_commit_root = 1;
777 }
778
779 search_again:
780 key.objectid = bytenr;
781 key.offset = offset;
782 if (metadata)
783 key.type = BTRFS_METADATA_ITEM_KEY;
784 else
785 key.type = BTRFS_EXTENT_ITEM_KEY;
786
787 again:
788 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
789 &key, path, 0, 0);
790 if (ret < 0)
791 goto out_free;
792
793 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
794 if (path->slots[0]) {
795 path->slots[0]--;
796 btrfs_item_key_to_cpu(path->nodes[0], &key,
797 path->slots[0]);
798 if (key.objectid == bytenr &&
799 key.type == BTRFS_EXTENT_ITEM_KEY &&
800 key.offset == root->leafsize)
801 ret = 0;
802 }
803 if (ret) {
804 key.objectid = bytenr;
805 key.type = BTRFS_EXTENT_ITEM_KEY;
806 key.offset = root->leafsize;
807 btrfs_release_path(path);
808 goto again;
809 }
810 }
811
812 if (ret == 0) {
813 leaf = path->nodes[0];
814 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
815 if (item_size >= sizeof(*ei)) {
816 ei = btrfs_item_ptr(leaf, path->slots[0],
817 struct btrfs_extent_item);
818 num_refs = btrfs_extent_refs(leaf, ei);
819 extent_flags = btrfs_extent_flags(leaf, ei);
820 } else {
821 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
822 struct btrfs_extent_item_v0 *ei0;
823 BUG_ON(item_size != sizeof(*ei0));
824 ei0 = btrfs_item_ptr(leaf, path->slots[0],
825 struct btrfs_extent_item_v0);
826 num_refs = btrfs_extent_refs_v0(leaf, ei0);
827 /* FIXME: this isn't correct for data */
828 extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
829 #else
830 BUG();
831 #endif
832 }
833 BUG_ON(num_refs == 0);
834 } else {
835 num_refs = 0;
836 extent_flags = 0;
837 ret = 0;
838 }
839
840 if (!trans)
841 goto out;
842
843 delayed_refs = &trans->transaction->delayed_refs;
844 spin_lock(&delayed_refs->lock);
845 head = btrfs_find_delayed_ref_head(trans, bytenr);
846 if (head) {
847 if (!mutex_trylock(&head->mutex)) {
848 atomic_inc(&head->node.refs);
849 spin_unlock(&delayed_refs->lock);
850
851 btrfs_release_path(path);
852
853 /*
854 * Mutex was contended, block until it's released and try
855 * again
856 */
857 mutex_lock(&head->mutex);
858 mutex_unlock(&head->mutex);
859 btrfs_put_delayed_ref(&head->node);
860 goto search_again;
861 }
862 spin_lock(&head->lock);
863 if (head->extent_op && head->extent_op->update_flags)
864 extent_flags |= head->extent_op->flags_to_set;
865 else
866 BUG_ON(num_refs == 0);
867
868 num_refs += head->node.ref_mod;
869 spin_unlock(&head->lock);
870 mutex_unlock(&head->mutex);
871 }
872 spin_unlock(&delayed_refs->lock);
873 out:
874 WARN_ON(num_refs == 0);
875 if (refs)
876 *refs = num_refs;
877 if (flags)
878 *flags = extent_flags;
879 out_free:
880 btrfs_free_path(path);
881 return ret;
882 }
883
884 /*
885 * Back reference rules. Back refs have three main goals:
886 *
887 * 1) differentiate between all holders of references to an extent so that
888 * when a reference is dropped we can make sure it was a valid reference
889 * before freeing the extent.
890 *
891 * 2) Provide enough information to quickly find the holders of an extent
892 * if we notice a given block is corrupted or bad.
893 *
894 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
895 * maintenance. This is actually the same as #2, but with a slightly
896 * different use case.
897 *
898 * There are two kinds of back refs. The implicit back refs is optimized
899 * for pointers in non-shared tree blocks. For a given pointer in a block,
900 * back refs of this kind provide information about the block's owner tree
901 * and the pointer's key. These information allow us to find the block by
902 * b-tree searching. The full back refs is for pointers in tree blocks not
903 * referenced by their owner trees. The location of tree block is recorded
904 * in the back refs. Actually the full back refs is generic, and can be
905 * used in all cases the implicit back refs is used. The major shortcoming
906 * of the full back refs is its overhead. Every time a tree block gets
907 * COWed, we have to update back refs entry for all pointers in it.
908 *
909 * For a newly allocated tree block, we use implicit back refs for
910 * pointers in it. This means most tree related operations only involve
911 * implicit back refs. For a tree block created in old transaction, the
912 * only way to drop a reference to it is COW it. So we can detect the
913 * event that tree block loses its owner tree's reference and do the
914 * back refs conversion.
915 *
916 * When a tree block is COW'd through a tree, there are four cases:
917 *
918 * The reference count of the block is one and the tree is the block's
919 * owner tree. Nothing to do in this case.
920 *
921 * The reference count of the block is one and the tree is not the
922 * block's owner tree. In this case, full back refs is used for pointers
923 * in the block. Remove these full back refs, add implicit back refs for
924 * every pointers in the new block.
925 *
926 * The reference count of the block is greater than one and the tree is
927 * the block's owner tree. In this case, implicit back refs is used for
928 * pointers in the block. Add full back refs for every pointers in the
929 * block, increase lower level extents' reference counts. The original
930 * implicit back refs are entailed to the new block.
931 *
932 * The reference count of the block is greater than one and the tree is
933 * not the block's owner tree. Add implicit back refs for every pointer in
934 * the new block, increase lower level extents' reference count.
935 *
936 * Back Reference Key composing:
937 *
938 * The key objectid corresponds to the first byte in the extent,
939 * The key type is used to differentiate between types of back refs.
940 * There are different meanings of the key offset for different types
941 * of back refs.
942 *
943 * File extents can be referenced by:
944 *
945 * - multiple snapshots, subvolumes, or different generations in one subvol
946 * - different files inside a single subvolume
947 * - different offsets inside a file (bookend extents in file.c)
948 *
949 * The extent ref structure for the implicit back refs has fields for:
950 *
951 * - Objectid of the subvolume root
952 * - objectid of the file holding the reference
953 * - original offset in the file
954 * - how many bookend extents
955 *
956 * The key offset for the implicit back refs is hash of the first
957 * three fields.
958 *
959 * The extent ref structure for the full back refs has field for:
960 *
961 * - number of pointers in the tree leaf
962 *
963 * The key offset for the implicit back refs is the first byte of
964 * the tree leaf
965 *
966 * When a file extent is allocated, The implicit back refs is used.
967 * the fields are filled in:
968 *
969 * (root_key.objectid, inode objectid, offset in file, 1)
970 *
971 * When a file extent is removed file truncation, we find the
972 * corresponding implicit back refs and check the following fields:
973 *
974 * (btrfs_header_owner(leaf), inode objectid, offset in file)
975 *
976 * Btree extents can be referenced by:
977 *
978 * - Different subvolumes
979 *
980 * Both the implicit back refs and the full back refs for tree blocks
981 * only consist of key. The key offset for the implicit back refs is
982 * objectid of block's owner tree. The key offset for the full back refs
983 * is the first byte of parent block.
984 *
985 * When implicit back refs is used, information about the lowest key and
986 * level of the tree block are required. These information are stored in
987 * tree block info structure.
988 */
989
990 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
991 static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
992 struct btrfs_root *root,
993 struct btrfs_path *path,
994 u64 owner, u32 extra_size)
995 {
996 struct btrfs_extent_item *item;
997 struct btrfs_extent_item_v0 *ei0;
998 struct btrfs_extent_ref_v0 *ref0;
999 struct btrfs_tree_block_info *bi;
1000 struct extent_buffer *leaf;
1001 struct btrfs_key key;
1002 struct btrfs_key found_key;
1003 u32 new_size = sizeof(*item);
1004 u64 refs;
1005 int ret;
1006
1007 leaf = path->nodes[0];
1008 BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
1009
1010 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1011 ei0 = btrfs_item_ptr(leaf, path->slots[0],
1012 struct btrfs_extent_item_v0);
1013 refs = btrfs_extent_refs_v0(leaf, ei0);
1014
1015 if (owner == (u64)-1) {
1016 while (1) {
1017 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1018 ret = btrfs_next_leaf(root, path);
1019 if (ret < 0)
1020 return ret;
1021 BUG_ON(ret > 0); /* Corruption */
1022 leaf = path->nodes[0];
1023 }
1024 btrfs_item_key_to_cpu(leaf, &found_key,
1025 path->slots[0]);
1026 BUG_ON(key.objectid != found_key.objectid);
1027 if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
1028 path->slots[0]++;
1029 continue;
1030 }
1031 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1032 struct btrfs_extent_ref_v0);
1033 owner = btrfs_ref_objectid_v0(leaf, ref0);
1034 break;
1035 }
1036 }
1037 btrfs_release_path(path);
1038
1039 if (owner < BTRFS_FIRST_FREE_OBJECTID)
1040 new_size += sizeof(*bi);
1041
1042 new_size -= sizeof(*ei0);
1043 ret = btrfs_search_slot(trans, root, &key, path,
1044 new_size + extra_size, 1);
1045 if (ret < 0)
1046 return ret;
1047 BUG_ON(ret); /* Corruption */
1048
1049 btrfs_extend_item(root, path, new_size);
1050
1051 leaf = path->nodes[0];
1052 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1053 btrfs_set_extent_refs(leaf, item, refs);
1054 /* FIXME: get real generation */
1055 btrfs_set_extent_generation(leaf, item, 0);
1056 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1057 btrfs_set_extent_flags(leaf, item,
1058 BTRFS_EXTENT_FLAG_TREE_BLOCK |
1059 BTRFS_BLOCK_FLAG_FULL_BACKREF);
1060 bi = (struct btrfs_tree_block_info *)(item + 1);
1061 /* FIXME: get first key of the block */
1062 memset_extent_buffer(leaf, 0, (unsigned long)bi, sizeof(*bi));
1063 btrfs_set_tree_block_level(leaf, bi, (int)owner);
1064 } else {
1065 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
1066 }
1067 btrfs_mark_buffer_dirty(leaf);
1068 return 0;
1069 }
1070 #endif
1071
1072 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1073 {
1074 u32 high_crc = ~(u32)0;
1075 u32 low_crc = ~(u32)0;
1076 __le64 lenum;
1077
1078 lenum = cpu_to_le64(root_objectid);
1079 high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
1080 lenum = cpu_to_le64(owner);
1081 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1082 lenum = cpu_to_le64(offset);
1083 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1084
1085 return ((u64)high_crc << 31) ^ (u64)low_crc;
1086 }
1087
1088 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1089 struct btrfs_extent_data_ref *ref)
1090 {
1091 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1092 btrfs_extent_data_ref_objectid(leaf, ref),
1093 btrfs_extent_data_ref_offset(leaf, ref));
1094 }
1095
1096 static int match_extent_data_ref(struct extent_buffer *leaf,
1097 struct btrfs_extent_data_ref *ref,
1098 u64 root_objectid, u64 owner, u64 offset)
1099 {
1100 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1101 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1102 btrfs_extent_data_ref_offset(leaf, ref) != offset)
1103 return 0;
1104 return 1;
1105 }
1106
1107 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1108 struct btrfs_root *root,
1109 struct btrfs_path *path,
1110 u64 bytenr, u64 parent,
1111 u64 root_objectid,
1112 u64 owner, u64 offset)
1113 {
1114 struct btrfs_key key;
1115 struct btrfs_extent_data_ref *ref;
1116 struct extent_buffer *leaf;
1117 u32 nritems;
1118 int ret;
1119 int recow;
1120 int err = -ENOENT;
1121
1122 key.objectid = bytenr;
1123 if (parent) {
1124 key.type = BTRFS_SHARED_DATA_REF_KEY;
1125 key.offset = parent;
1126 } else {
1127 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1128 key.offset = hash_extent_data_ref(root_objectid,
1129 owner, offset);
1130 }
1131 again:
1132 recow = 0;
1133 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1134 if (ret < 0) {
1135 err = ret;
1136 goto fail;
1137 }
1138
1139 if (parent) {
1140 if (!ret)
1141 return 0;
1142 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1143 key.type = BTRFS_EXTENT_REF_V0_KEY;
1144 btrfs_release_path(path);
1145 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1146 if (ret < 0) {
1147 err = ret;
1148 goto fail;
1149 }
1150 if (!ret)
1151 return 0;
1152 #endif
1153 goto fail;
1154 }
1155
1156 leaf = path->nodes[0];
1157 nritems = btrfs_header_nritems(leaf);
1158 while (1) {
1159 if (path->slots[0] >= nritems) {
1160 ret = btrfs_next_leaf(root, path);
1161 if (ret < 0)
1162 err = ret;
1163 if (ret)
1164 goto fail;
1165
1166 leaf = path->nodes[0];
1167 nritems = btrfs_header_nritems(leaf);
1168 recow = 1;
1169 }
1170
1171 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1172 if (key.objectid != bytenr ||
1173 key.type != BTRFS_EXTENT_DATA_REF_KEY)
1174 goto fail;
1175
1176 ref = btrfs_item_ptr(leaf, path->slots[0],
1177 struct btrfs_extent_data_ref);
1178
1179 if (match_extent_data_ref(leaf, ref, root_objectid,
1180 owner, offset)) {
1181 if (recow) {
1182 btrfs_release_path(path);
1183 goto again;
1184 }
1185 err = 0;
1186 break;
1187 }
1188 path->slots[0]++;
1189 }
1190 fail:
1191 return err;
1192 }
1193
1194 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1195 struct btrfs_root *root,
1196 struct btrfs_path *path,
1197 u64 bytenr, u64 parent,
1198 u64 root_objectid, u64 owner,
1199 u64 offset, int refs_to_add)
1200 {
1201 struct btrfs_key key;
1202 struct extent_buffer *leaf;
1203 u32 size;
1204 u32 num_refs;
1205 int ret;
1206
1207 key.objectid = bytenr;
1208 if (parent) {
1209 key.type = BTRFS_SHARED_DATA_REF_KEY;
1210 key.offset = parent;
1211 size = sizeof(struct btrfs_shared_data_ref);
1212 } else {
1213 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1214 key.offset = hash_extent_data_ref(root_objectid,
1215 owner, offset);
1216 size = sizeof(struct btrfs_extent_data_ref);
1217 }
1218
1219 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1220 if (ret && ret != -EEXIST)
1221 goto fail;
1222
1223 leaf = path->nodes[0];
1224 if (parent) {
1225 struct btrfs_shared_data_ref *ref;
1226 ref = btrfs_item_ptr(leaf, path->slots[0],
1227 struct btrfs_shared_data_ref);
1228 if (ret == 0) {
1229 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1230 } else {
1231 num_refs = btrfs_shared_data_ref_count(leaf, ref);
1232 num_refs += refs_to_add;
1233 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1234 }
1235 } else {
1236 struct btrfs_extent_data_ref *ref;
1237 while (ret == -EEXIST) {
1238 ref = btrfs_item_ptr(leaf, path->slots[0],
1239 struct btrfs_extent_data_ref);
1240 if (match_extent_data_ref(leaf, ref, root_objectid,
1241 owner, offset))
1242 break;
1243 btrfs_release_path(path);
1244 key.offset++;
1245 ret = btrfs_insert_empty_item(trans, root, path, &key,
1246 size);
1247 if (ret && ret != -EEXIST)
1248 goto fail;
1249
1250 leaf = path->nodes[0];
1251 }
1252 ref = btrfs_item_ptr(leaf, path->slots[0],
1253 struct btrfs_extent_data_ref);
1254 if (ret == 0) {
1255 btrfs_set_extent_data_ref_root(leaf, ref,
1256 root_objectid);
1257 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1258 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1259 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1260 } else {
1261 num_refs = btrfs_extent_data_ref_count(leaf, ref);
1262 num_refs += refs_to_add;
1263 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1264 }
1265 }
1266 btrfs_mark_buffer_dirty(leaf);
1267 ret = 0;
1268 fail:
1269 btrfs_release_path(path);
1270 return ret;
1271 }
1272
1273 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1274 struct btrfs_root *root,
1275 struct btrfs_path *path,
1276 int refs_to_drop, int *last_ref)
1277 {
1278 struct btrfs_key key;
1279 struct btrfs_extent_data_ref *ref1 = NULL;
1280 struct btrfs_shared_data_ref *ref2 = NULL;
1281 struct extent_buffer *leaf;
1282 u32 num_refs = 0;
1283 int ret = 0;
1284
1285 leaf = path->nodes[0];
1286 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1287
1288 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1289 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1290 struct btrfs_extent_data_ref);
1291 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1292 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1293 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1294 struct btrfs_shared_data_ref);
1295 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1296 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1297 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1298 struct btrfs_extent_ref_v0 *ref0;
1299 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1300 struct btrfs_extent_ref_v0);
1301 num_refs = btrfs_ref_count_v0(leaf, ref0);
1302 #endif
1303 } else {
1304 BUG();
1305 }
1306
1307 BUG_ON(num_refs < refs_to_drop);
1308 num_refs -= refs_to_drop;
1309
1310 if (num_refs == 0) {
1311 ret = btrfs_del_item(trans, root, path);
1312 *last_ref = 1;
1313 } else {
1314 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1315 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1316 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1317 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1318 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1319 else {
1320 struct btrfs_extent_ref_v0 *ref0;
1321 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1322 struct btrfs_extent_ref_v0);
1323 btrfs_set_ref_count_v0(leaf, ref0, num_refs);
1324 }
1325 #endif
1326 btrfs_mark_buffer_dirty(leaf);
1327 }
1328 return ret;
1329 }
1330
1331 static noinline u32 extent_data_ref_count(struct btrfs_root *root,
1332 struct btrfs_path *path,
1333 struct btrfs_extent_inline_ref *iref)
1334 {
1335 struct btrfs_key key;
1336 struct extent_buffer *leaf;
1337 struct btrfs_extent_data_ref *ref1;
1338 struct btrfs_shared_data_ref *ref2;
1339 u32 num_refs = 0;
1340
1341 leaf = path->nodes[0];
1342 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1343 if (iref) {
1344 if (btrfs_extent_inline_ref_type(leaf, iref) ==
1345 BTRFS_EXTENT_DATA_REF_KEY) {
1346 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1347 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1348 } else {
1349 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1350 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1351 }
1352 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1353 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1354 struct btrfs_extent_data_ref);
1355 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1356 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1357 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1358 struct btrfs_shared_data_ref);
1359 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1360 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1361 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1362 struct btrfs_extent_ref_v0 *ref0;
1363 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1364 struct btrfs_extent_ref_v0);
1365 num_refs = btrfs_ref_count_v0(leaf, ref0);
1366 #endif
1367 } else {
1368 WARN_ON(1);
1369 }
1370 return num_refs;
1371 }
1372
1373 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1374 struct btrfs_root *root,
1375 struct btrfs_path *path,
1376 u64 bytenr, u64 parent,
1377 u64 root_objectid)
1378 {
1379 struct btrfs_key key;
1380 int ret;
1381
1382 key.objectid = bytenr;
1383 if (parent) {
1384 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1385 key.offset = parent;
1386 } else {
1387 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1388 key.offset = root_objectid;
1389 }
1390
1391 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1392 if (ret > 0)
1393 ret = -ENOENT;
1394 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1395 if (ret == -ENOENT && parent) {
1396 btrfs_release_path(path);
1397 key.type = BTRFS_EXTENT_REF_V0_KEY;
1398 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1399 if (ret > 0)
1400 ret = -ENOENT;
1401 }
1402 #endif
1403 return ret;
1404 }
1405
1406 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1407 struct btrfs_root *root,
1408 struct btrfs_path *path,
1409 u64 bytenr, u64 parent,
1410 u64 root_objectid)
1411 {
1412 struct btrfs_key key;
1413 int ret;
1414
1415 key.objectid = bytenr;
1416 if (parent) {
1417 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1418 key.offset = parent;
1419 } else {
1420 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1421 key.offset = root_objectid;
1422 }
1423
1424 ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1425 btrfs_release_path(path);
1426 return ret;
1427 }
1428
1429 static inline int extent_ref_type(u64 parent, u64 owner)
1430 {
1431 int type;
1432 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1433 if (parent > 0)
1434 type = BTRFS_SHARED_BLOCK_REF_KEY;
1435 else
1436 type = BTRFS_TREE_BLOCK_REF_KEY;
1437 } else {
1438 if (parent > 0)
1439 type = BTRFS_SHARED_DATA_REF_KEY;
1440 else
1441 type = BTRFS_EXTENT_DATA_REF_KEY;
1442 }
1443 return type;
1444 }
1445
1446 static int find_next_key(struct btrfs_path *path, int level,
1447 struct btrfs_key *key)
1448
1449 {
1450 for (; level < BTRFS_MAX_LEVEL; level++) {
1451 if (!path->nodes[level])
1452 break;
1453 if (path->slots[level] + 1 >=
1454 btrfs_header_nritems(path->nodes[level]))
1455 continue;
1456 if (level == 0)
1457 btrfs_item_key_to_cpu(path->nodes[level], key,
1458 path->slots[level] + 1);
1459 else
1460 btrfs_node_key_to_cpu(path->nodes[level], key,
1461 path->slots[level] + 1);
1462 return 0;
1463 }
1464 return 1;
1465 }
1466
1467 /*
1468 * look for inline back ref. if back ref is found, *ref_ret is set
1469 * to the address of inline back ref, and 0 is returned.
1470 *
1471 * if back ref isn't found, *ref_ret is set to the address where it
1472 * should be inserted, and -ENOENT is returned.
1473 *
1474 * if insert is true and there are too many inline back refs, the path
1475 * points to the extent item, and -EAGAIN is returned.
1476 *
1477 * NOTE: inline back refs are ordered in the same way that back ref
1478 * items in the tree are ordered.
1479 */
1480 static noinline_for_stack
1481 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1482 struct btrfs_root *root,
1483 struct btrfs_path *path,
1484 struct btrfs_extent_inline_ref **ref_ret,
1485 u64 bytenr, u64 num_bytes,
1486 u64 parent, u64 root_objectid,
1487 u64 owner, u64 offset, int insert)
1488 {
1489 struct btrfs_key key;
1490 struct extent_buffer *leaf;
1491 struct btrfs_extent_item *ei;
1492 struct btrfs_extent_inline_ref *iref;
1493 u64 flags;
1494 u64 item_size;
1495 unsigned long ptr;
1496 unsigned long end;
1497 int extra_size;
1498 int type;
1499 int want;
1500 int ret;
1501 int err = 0;
1502 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
1503 SKINNY_METADATA);
1504
1505 key.objectid = bytenr;
1506 key.type = BTRFS_EXTENT_ITEM_KEY;
1507 key.offset = num_bytes;
1508
1509 want = extent_ref_type(parent, owner);
1510 if (insert) {
1511 extra_size = btrfs_extent_inline_ref_size(want);
1512 path->keep_locks = 1;
1513 } else
1514 extra_size = -1;
1515
1516 /*
1517 * Owner is our parent level, so we can just add one to get the level
1518 * for the block we are interested in.
1519 */
1520 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1521 key.type = BTRFS_METADATA_ITEM_KEY;
1522 key.offset = owner;
1523 }
1524
1525 again:
1526 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1527 if (ret < 0) {
1528 err = ret;
1529 goto out;
1530 }
1531
1532 /*
1533 * We may be a newly converted file system which still has the old fat
1534 * extent entries for metadata, so try and see if we have one of those.
1535 */
1536 if (ret > 0 && skinny_metadata) {
1537 skinny_metadata = false;
1538 if (path->slots[0]) {
1539 path->slots[0]--;
1540 btrfs_item_key_to_cpu(path->nodes[0], &key,
1541 path->slots[0]);
1542 if (key.objectid == bytenr &&
1543 key.type == BTRFS_EXTENT_ITEM_KEY &&
1544 key.offset == num_bytes)
1545 ret = 0;
1546 }
1547 if (ret) {
1548 key.objectid = bytenr;
1549 key.type = BTRFS_EXTENT_ITEM_KEY;
1550 key.offset = num_bytes;
1551 btrfs_release_path(path);
1552 goto again;
1553 }
1554 }
1555
1556 if (ret && !insert) {
1557 err = -ENOENT;
1558 goto out;
1559 } else if (WARN_ON(ret)) {
1560 err = -EIO;
1561 goto out;
1562 }
1563
1564 leaf = path->nodes[0];
1565 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1566 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1567 if (item_size < sizeof(*ei)) {
1568 if (!insert) {
1569 err = -ENOENT;
1570 goto out;
1571 }
1572 ret = convert_extent_item_v0(trans, root, path, owner,
1573 extra_size);
1574 if (ret < 0) {
1575 err = ret;
1576 goto out;
1577 }
1578 leaf = path->nodes[0];
1579 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1580 }
1581 #endif
1582 BUG_ON(item_size < sizeof(*ei));
1583
1584 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1585 flags = btrfs_extent_flags(leaf, ei);
1586
1587 ptr = (unsigned long)(ei + 1);
1588 end = (unsigned long)ei + item_size;
1589
1590 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
1591 ptr += sizeof(struct btrfs_tree_block_info);
1592 BUG_ON(ptr > end);
1593 }
1594
1595 err = -ENOENT;
1596 while (1) {
1597 if (ptr >= end) {
1598 WARN_ON(ptr > end);
1599 break;
1600 }
1601 iref = (struct btrfs_extent_inline_ref *)ptr;
1602 type = btrfs_extent_inline_ref_type(leaf, iref);
1603 if (want < type)
1604 break;
1605 if (want > type) {
1606 ptr += btrfs_extent_inline_ref_size(type);
1607 continue;
1608 }
1609
1610 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1611 struct btrfs_extent_data_ref *dref;
1612 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1613 if (match_extent_data_ref(leaf, dref, root_objectid,
1614 owner, offset)) {
1615 err = 0;
1616 break;
1617 }
1618 if (hash_extent_data_ref_item(leaf, dref) <
1619 hash_extent_data_ref(root_objectid, owner, offset))
1620 break;
1621 } else {
1622 u64 ref_offset;
1623 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1624 if (parent > 0) {
1625 if (parent == ref_offset) {
1626 err = 0;
1627 break;
1628 }
1629 if (ref_offset < parent)
1630 break;
1631 } else {
1632 if (root_objectid == ref_offset) {
1633 err = 0;
1634 break;
1635 }
1636 if (ref_offset < root_objectid)
1637 break;
1638 }
1639 }
1640 ptr += btrfs_extent_inline_ref_size(type);
1641 }
1642 if (err == -ENOENT && insert) {
1643 if (item_size + extra_size >=
1644 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1645 err = -EAGAIN;
1646 goto out;
1647 }
1648 /*
1649 * To add new inline back ref, we have to make sure
1650 * there is no corresponding back ref item.
1651 * For simplicity, we just do not add new inline back
1652 * ref if there is any kind of item for this block
1653 */
1654 if (find_next_key(path, 0, &key) == 0 &&
1655 key.objectid == bytenr &&
1656 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1657 err = -EAGAIN;
1658 goto out;
1659 }
1660 }
1661 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1662 out:
1663 if (insert) {
1664 path->keep_locks = 0;
1665 btrfs_unlock_up_safe(path, 1);
1666 }
1667 return err;
1668 }
1669
1670 /*
1671 * helper to add new inline back ref
1672 */
1673 static noinline_for_stack
1674 void setup_inline_extent_backref(struct btrfs_root *root,
1675 struct btrfs_path *path,
1676 struct btrfs_extent_inline_ref *iref,
1677 u64 parent, u64 root_objectid,
1678 u64 owner, u64 offset, int refs_to_add,
1679 struct btrfs_delayed_extent_op *extent_op)
1680 {
1681 struct extent_buffer *leaf;
1682 struct btrfs_extent_item *ei;
1683 unsigned long ptr;
1684 unsigned long end;
1685 unsigned long item_offset;
1686 u64 refs;
1687 int size;
1688 int type;
1689
1690 leaf = path->nodes[0];
1691 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1692 item_offset = (unsigned long)iref - (unsigned long)ei;
1693
1694 type = extent_ref_type(parent, owner);
1695 size = btrfs_extent_inline_ref_size(type);
1696
1697 btrfs_extend_item(root, path, size);
1698
1699 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1700 refs = btrfs_extent_refs(leaf, ei);
1701 refs += refs_to_add;
1702 btrfs_set_extent_refs(leaf, ei, refs);
1703 if (extent_op)
1704 __run_delayed_extent_op(extent_op, leaf, ei);
1705
1706 ptr = (unsigned long)ei + item_offset;
1707 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1708 if (ptr < end - size)
1709 memmove_extent_buffer(leaf, ptr + size, ptr,
1710 end - size - ptr);
1711
1712 iref = (struct btrfs_extent_inline_ref *)ptr;
1713 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1714 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1715 struct btrfs_extent_data_ref *dref;
1716 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1717 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1718 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1719 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1720 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1721 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1722 struct btrfs_shared_data_ref *sref;
1723 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1724 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1725 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1726 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1727 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1728 } else {
1729 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1730 }
1731 btrfs_mark_buffer_dirty(leaf);
1732 }
1733
1734 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1735 struct btrfs_root *root,
1736 struct btrfs_path *path,
1737 struct btrfs_extent_inline_ref **ref_ret,
1738 u64 bytenr, u64 num_bytes, u64 parent,
1739 u64 root_objectid, u64 owner, u64 offset)
1740 {
1741 int ret;
1742
1743 ret = lookup_inline_extent_backref(trans, root, path, ref_ret,
1744 bytenr, num_bytes, parent,
1745 root_objectid, owner, offset, 0);
1746 if (ret != -ENOENT)
1747 return ret;
1748
1749 btrfs_release_path(path);
1750 *ref_ret = NULL;
1751
1752 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1753 ret = lookup_tree_block_ref(trans, root, path, bytenr, parent,
1754 root_objectid);
1755 } else {
1756 ret = lookup_extent_data_ref(trans, root, path, bytenr, parent,
1757 root_objectid, owner, offset);
1758 }
1759 return ret;
1760 }
1761
1762 /*
1763 * helper to update/remove inline back ref
1764 */
1765 static noinline_for_stack
1766 void update_inline_extent_backref(struct btrfs_root *root,
1767 struct btrfs_path *path,
1768 struct btrfs_extent_inline_ref *iref,
1769 int refs_to_mod,
1770 struct btrfs_delayed_extent_op *extent_op,
1771 int *last_ref)
1772 {
1773 struct extent_buffer *leaf;
1774 struct btrfs_extent_item *ei;
1775 struct btrfs_extent_data_ref *dref = NULL;
1776 struct btrfs_shared_data_ref *sref = NULL;
1777 unsigned long ptr;
1778 unsigned long end;
1779 u32 item_size;
1780 int size;
1781 int type;
1782 u64 refs;
1783
1784 leaf = path->nodes[0];
1785 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1786 refs = btrfs_extent_refs(leaf, ei);
1787 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1788 refs += refs_to_mod;
1789 btrfs_set_extent_refs(leaf, ei, refs);
1790 if (extent_op)
1791 __run_delayed_extent_op(extent_op, leaf, ei);
1792
1793 type = btrfs_extent_inline_ref_type(leaf, iref);
1794
1795 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1796 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1797 refs = btrfs_extent_data_ref_count(leaf, dref);
1798 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1799 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1800 refs = btrfs_shared_data_ref_count(leaf, sref);
1801 } else {
1802 refs = 1;
1803 BUG_ON(refs_to_mod != -1);
1804 }
1805
1806 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1807 refs += refs_to_mod;
1808
1809 if (refs > 0) {
1810 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1811 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1812 else
1813 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1814 } else {
1815 *last_ref = 1;
1816 size = btrfs_extent_inline_ref_size(type);
1817 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1818 ptr = (unsigned long)iref;
1819 end = (unsigned long)ei + item_size;
1820 if (ptr + size < end)
1821 memmove_extent_buffer(leaf, ptr, ptr + size,
1822 end - ptr - size);
1823 item_size -= size;
1824 btrfs_truncate_item(root, path, item_size, 1);
1825 }
1826 btrfs_mark_buffer_dirty(leaf);
1827 }
1828
1829 static noinline_for_stack
1830 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1831 struct btrfs_root *root,
1832 struct btrfs_path *path,
1833 u64 bytenr, u64 num_bytes, u64 parent,
1834 u64 root_objectid, u64 owner,
1835 u64 offset, int refs_to_add,
1836 struct btrfs_delayed_extent_op *extent_op)
1837 {
1838 struct btrfs_extent_inline_ref *iref;
1839 int ret;
1840
1841 ret = lookup_inline_extent_backref(trans, root, path, &iref,
1842 bytenr, num_bytes, parent,
1843 root_objectid, owner, offset, 1);
1844 if (ret == 0) {
1845 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1846 update_inline_extent_backref(root, path, iref,
1847 refs_to_add, extent_op, NULL);
1848 } else if (ret == -ENOENT) {
1849 setup_inline_extent_backref(root, path, iref, parent,
1850 root_objectid, owner, offset,
1851 refs_to_add, extent_op);
1852 ret = 0;
1853 }
1854 return ret;
1855 }
1856
1857 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1858 struct btrfs_root *root,
1859 struct btrfs_path *path,
1860 u64 bytenr, u64 parent, u64 root_objectid,
1861 u64 owner, u64 offset, int refs_to_add)
1862 {
1863 int ret;
1864 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1865 BUG_ON(refs_to_add != 1);
1866 ret = insert_tree_block_ref(trans, root, path, bytenr,
1867 parent, root_objectid);
1868 } else {
1869 ret = insert_extent_data_ref(trans, root, path, bytenr,
1870 parent, root_objectid,
1871 owner, offset, refs_to_add);
1872 }
1873 return ret;
1874 }
1875
1876 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1877 struct btrfs_root *root,
1878 struct btrfs_path *path,
1879 struct btrfs_extent_inline_ref *iref,
1880 int refs_to_drop, int is_data, int *last_ref)
1881 {
1882 int ret = 0;
1883
1884 BUG_ON(!is_data && refs_to_drop != 1);
1885 if (iref) {
1886 update_inline_extent_backref(root, path, iref,
1887 -refs_to_drop, NULL, last_ref);
1888 } else if (is_data) {
1889 ret = remove_extent_data_ref(trans, root, path, refs_to_drop,
1890 last_ref);
1891 } else {
1892 *last_ref = 1;
1893 ret = btrfs_del_item(trans, root, path);
1894 }
1895 return ret;
1896 }
1897
1898 static int btrfs_issue_discard(struct block_device *bdev,
1899 u64 start, u64 len)
1900 {
1901 return blkdev_issue_discard(bdev, start >> 9, len >> 9, GFP_NOFS, 0);
1902 }
1903
1904 static int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
1905 u64 num_bytes, u64 *actual_bytes)
1906 {
1907 int ret;
1908 u64 discarded_bytes = 0;
1909 struct btrfs_bio *bbio = NULL;
1910
1911
1912 /* Tell the block device(s) that the sectors can be discarded */
1913 ret = btrfs_map_block(root->fs_info, REQ_DISCARD,
1914 bytenr, &num_bytes, &bbio, 0);
1915 /* Error condition is -ENOMEM */
1916 if (!ret) {
1917 struct btrfs_bio_stripe *stripe = bbio->stripes;
1918 int i;
1919
1920
1921 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
1922 if (!stripe->dev->can_discard)
1923 continue;
1924
1925 ret = btrfs_issue_discard(stripe->dev->bdev,
1926 stripe->physical,
1927 stripe->length);
1928 if (!ret)
1929 discarded_bytes += stripe->length;
1930 else if (ret != -EOPNOTSUPP)
1931 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
1932
1933 /*
1934 * Just in case we get back EOPNOTSUPP for some reason,
1935 * just ignore the return value so we don't screw up
1936 * people calling discard_extent.
1937 */
1938 ret = 0;
1939 }
1940 kfree(bbio);
1941 }
1942
1943 if (actual_bytes)
1944 *actual_bytes = discarded_bytes;
1945
1946
1947 if (ret == -EOPNOTSUPP)
1948 ret = 0;
1949 return ret;
1950 }
1951
1952 /* Can return -ENOMEM */
1953 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1954 struct btrfs_root *root,
1955 u64 bytenr, u64 num_bytes, u64 parent,
1956 u64 root_objectid, u64 owner, u64 offset,
1957 int no_quota)
1958 {
1959 int ret;
1960 struct btrfs_fs_info *fs_info = root->fs_info;
1961
1962 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
1963 root_objectid == BTRFS_TREE_LOG_OBJECTID);
1964
1965 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1966 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
1967 num_bytes,
1968 parent, root_objectid, (int)owner,
1969 BTRFS_ADD_DELAYED_REF, NULL, no_quota);
1970 } else {
1971 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
1972 num_bytes,
1973 parent, root_objectid, owner, offset,
1974 BTRFS_ADD_DELAYED_REF, NULL, no_quota);
1975 }
1976 return ret;
1977 }
1978
1979 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1980 struct btrfs_root *root,
1981 u64 bytenr, u64 num_bytes,
1982 u64 parent, u64 root_objectid,
1983 u64 owner, u64 offset, int refs_to_add,
1984 int no_quota,
1985 struct btrfs_delayed_extent_op *extent_op)
1986 {
1987 struct btrfs_fs_info *fs_info = root->fs_info;
1988 struct btrfs_path *path;
1989 struct extent_buffer *leaf;
1990 struct btrfs_extent_item *item;
1991 struct btrfs_key key;
1992 u64 refs;
1993 int ret;
1994 enum btrfs_qgroup_operation_type type = BTRFS_QGROUP_OPER_ADD_EXCL;
1995
1996 path = btrfs_alloc_path();
1997 if (!path)
1998 return -ENOMEM;
1999
2000 if (!is_fstree(root_objectid) || !root->fs_info->quota_enabled)
2001 no_quota = 1;
2002
2003 path->reada = 1;
2004 path->leave_spinning = 1;
2005 /* this will setup the path even if it fails to insert the back ref */
2006 ret = insert_inline_extent_backref(trans, fs_info->extent_root, path,
2007 bytenr, num_bytes, parent,
2008 root_objectid, owner, offset,
2009 refs_to_add, extent_op);
2010 if ((ret < 0 && ret != -EAGAIN) || (!ret && no_quota))
2011 goto out;
2012 /*
2013 * Ok we were able to insert an inline extent and it appears to be a new
2014 * reference, deal with the qgroup accounting.
2015 */
2016 if (!ret && !no_quota) {
2017 ASSERT(root->fs_info->quota_enabled);
2018 leaf = path->nodes[0];
2019 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2020 item = btrfs_item_ptr(leaf, path->slots[0],
2021 struct btrfs_extent_item);
2022 if (btrfs_extent_refs(leaf, item) > (u64)refs_to_add)
2023 type = BTRFS_QGROUP_OPER_ADD_SHARED;
2024 btrfs_release_path(path);
2025
2026 ret = btrfs_qgroup_record_ref(trans, fs_info, root_objectid,
2027 bytenr, num_bytes, type, 0);
2028 goto out;
2029 }
2030
2031 /*
2032 * Ok we had -EAGAIN which means we didn't have space to insert and
2033 * inline extent ref, so just update the reference count and add a
2034 * normal backref.
2035 */
2036 leaf = path->nodes[0];
2037 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2038 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2039 refs = btrfs_extent_refs(leaf, item);
2040 if (refs)
2041 type = BTRFS_QGROUP_OPER_ADD_SHARED;
2042 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2043 if (extent_op)
2044 __run_delayed_extent_op(extent_op, leaf, item);
2045
2046 btrfs_mark_buffer_dirty(leaf);
2047 btrfs_release_path(path);
2048
2049 if (!no_quota) {
2050 ret = btrfs_qgroup_record_ref(trans, fs_info, root_objectid,
2051 bytenr, num_bytes, type, 0);
2052 if (ret)
2053 goto out;
2054 }
2055
2056 path->reada = 1;
2057 path->leave_spinning = 1;
2058 /* now insert the actual backref */
2059 ret = insert_extent_backref(trans, root->fs_info->extent_root,
2060 path, bytenr, parent, root_objectid,
2061 owner, offset, refs_to_add);
2062 if (ret)
2063 btrfs_abort_transaction(trans, root, ret);
2064 out:
2065 btrfs_free_path(path);
2066 return ret;
2067 }
2068
2069 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2070 struct btrfs_root *root,
2071 struct btrfs_delayed_ref_node *node,
2072 struct btrfs_delayed_extent_op *extent_op,
2073 int insert_reserved)
2074 {
2075 int ret = 0;
2076 struct btrfs_delayed_data_ref *ref;
2077 struct btrfs_key ins;
2078 u64 parent = 0;
2079 u64 ref_root = 0;
2080 u64 flags = 0;
2081
2082 ins.objectid = node->bytenr;
2083 ins.offset = node->num_bytes;
2084 ins.type = BTRFS_EXTENT_ITEM_KEY;
2085
2086 ref = btrfs_delayed_node_to_data_ref(node);
2087 trace_run_delayed_data_ref(node, ref, node->action);
2088
2089 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2090 parent = ref->parent;
2091 ref_root = ref->root;
2092
2093 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2094 if (extent_op)
2095 flags |= extent_op->flags_to_set;
2096 ret = alloc_reserved_file_extent(trans, root,
2097 parent, ref_root, flags,
2098 ref->objectid, ref->offset,
2099 &ins, node->ref_mod);
2100 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2101 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
2102 node->num_bytes, parent,
2103 ref_root, ref->objectid,
2104 ref->offset, node->ref_mod,
2105 node->no_quota, extent_op);
2106 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2107 ret = __btrfs_free_extent(trans, root, node->bytenr,
2108 node->num_bytes, parent,
2109 ref_root, ref->objectid,
2110 ref->offset, node->ref_mod,
2111 extent_op, node->no_quota);
2112 } else {
2113 BUG();
2114 }
2115 return ret;
2116 }
2117
2118 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2119 struct extent_buffer *leaf,
2120 struct btrfs_extent_item *ei)
2121 {
2122 u64 flags = btrfs_extent_flags(leaf, ei);
2123 if (extent_op->update_flags) {
2124 flags |= extent_op->flags_to_set;
2125 btrfs_set_extent_flags(leaf, ei, flags);
2126 }
2127
2128 if (extent_op->update_key) {
2129 struct btrfs_tree_block_info *bi;
2130 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2131 bi = (struct btrfs_tree_block_info *)(ei + 1);
2132 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2133 }
2134 }
2135
2136 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2137 struct btrfs_root *root,
2138 struct btrfs_delayed_ref_node *node,
2139 struct btrfs_delayed_extent_op *extent_op)
2140 {
2141 struct btrfs_key key;
2142 struct btrfs_path *path;
2143 struct btrfs_extent_item *ei;
2144 struct extent_buffer *leaf;
2145 u32 item_size;
2146 int ret;
2147 int err = 0;
2148 int metadata = !extent_op->is_data;
2149
2150 if (trans->aborted)
2151 return 0;
2152
2153 if (metadata && !btrfs_fs_incompat(root->fs_info, SKINNY_METADATA))
2154 metadata = 0;
2155
2156 path = btrfs_alloc_path();
2157 if (!path)
2158 return -ENOMEM;
2159
2160 key.objectid = node->bytenr;
2161
2162 if (metadata) {
2163 key.type = BTRFS_METADATA_ITEM_KEY;
2164 key.offset = extent_op->level;
2165 } else {
2166 key.type = BTRFS_EXTENT_ITEM_KEY;
2167 key.offset = node->num_bytes;
2168 }
2169
2170 again:
2171 path->reada = 1;
2172 path->leave_spinning = 1;
2173 ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key,
2174 path, 0, 1);
2175 if (ret < 0) {
2176 err = ret;
2177 goto out;
2178 }
2179 if (ret > 0) {
2180 if (metadata) {
2181 if (path->slots[0] > 0) {
2182 path->slots[0]--;
2183 btrfs_item_key_to_cpu(path->nodes[0], &key,
2184 path->slots[0]);
2185 if (key.objectid == node->bytenr &&
2186 key.type == BTRFS_EXTENT_ITEM_KEY &&
2187 key.offset == node->num_bytes)
2188 ret = 0;
2189 }
2190 if (ret > 0) {
2191 btrfs_release_path(path);
2192 metadata = 0;
2193
2194 key.objectid = node->bytenr;
2195 key.offset = node->num_bytes;
2196 key.type = BTRFS_EXTENT_ITEM_KEY;
2197 goto again;
2198 }
2199 } else {
2200 err = -EIO;
2201 goto out;
2202 }
2203 }
2204
2205 leaf = path->nodes[0];
2206 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2207 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2208 if (item_size < sizeof(*ei)) {
2209 ret = convert_extent_item_v0(trans, root->fs_info->extent_root,
2210 path, (u64)-1, 0);
2211 if (ret < 0) {
2212 err = ret;
2213 goto out;
2214 }
2215 leaf = path->nodes[0];
2216 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2217 }
2218 #endif
2219 BUG_ON(item_size < sizeof(*ei));
2220 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2221 __run_delayed_extent_op(extent_op, leaf, ei);
2222
2223 btrfs_mark_buffer_dirty(leaf);
2224 out:
2225 btrfs_free_path(path);
2226 return err;
2227 }
2228
2229 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2230 struct btrfs_root *root,
2231 struct btrfs_delayed_ref_node *node,
2232 struct btrfs_delayed_extent_op *extent_op,
2233 int insert_reserved)
2234 {
2235 int ret = 0;
2236 struct btrfs_delayed_tree_ref *ref;
2237 struct btrfs_key ins;
2238 u64 parent = 0;
2239 u64 ref_root = 0;
2240 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
2241 SKINNY_METADATA);
2242
2243 ref = btrfs_delayed_node_to_tree_ref(node);
2244 trace_run_delayed_tree_ref(node, ref, node->action);
2245
2246 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2247 parent = ref->parent;
2248 ref_root = ref->root;
2249
2250 ins.objectid = node->bytenr;
2251 if (skinny_metadata) {
2252 ins.offset = ref->level;
2253 ins.type = BTRFS_METADATA_ITEM_KEY;
2254 } else {
2255 ins.offset = node->num_bytes;
2256 ins.type = BTRFS_EXTENT_ITEM_KEY;
2257 }
2258
2259 BUG_ON(node->ref_mod != 1);
2260 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2261 BUG_ON(!extent_op || !extent_op->update_flags);
2262 ret = alloc_reserved_tree_block(trans, root,
2263 parent, ref_root,
2264 extent_op->flags_to_set,
2265 &extent_op->key,
2266 ref->level, &ins,
2267 node->no_quota);
2268 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2269 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
2270 node->num_bytes, parent, ref_root,
2271 ref->level, 0, 1, node->no_quota,
2272 extent_op);
2273 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2274 ret = __btrfs_free_extent(trans, root, node->bytenr,
2275 node->num_bytes, parent, ref_root,
2276 ref->level, 0, 1, extent_op,
2277 node->no_quota);
2278 } else {
2279 BUG();
2280 }
2281 return ret;
2282 }
2283
2284 /* helper function to actually process a single delayed ref entry */
2285 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2286 struct btrfs_root *root,
2287 struct btrfs_delayed_ref_node *node,
2288 struct btrfs_delayed_extent_op *extent_op,
2289 int insert_reserved)
2290 {
2291 int ret = 0;
2292
2293 if (trans->aborted) {
2294 if (insert_reserved)
2295 btrfs_pin_extent(root, node->bytenr,
2296 node->num_bytes, 1);
2297 return 0;
2298 }
2299
2300 if (btrfs_delayed_ref_is_head(node)) {
2301 struct btrfs_delayed_ref_head *head;
2302 /*
2303 * we've hit the end of the chain and we were supposed
2304 * to insert this extent into the tree. But, it got
2305 * deleted before we ever needed to insert it, so all
2306 * we have to do is clean up the accounting
2307 */
2308 BUG_ON(extent_op);
2309 head = btrfs_delayed_node_to_head(node);
2310 trace_run_delayed_ref_head(node, head, node->action);
2311
2312 if (insert_reserved) {
2313 btrfs_pin_extent(root, node->bytenr,
2314 node->num_bytes, 1);
2315 if (head->is_data) {
2316 ret = btrfs_del_csums(trans, root,
2317 node->bytenr,
2318 node->num_bytes);
2319 }
2320 }
2321 return ret;
2322 }
2323
2324 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2325 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2326 ret = run_delayed_tree_ref(trans, root, node, extent_op,
2327 insert_reserved);
2328 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2329 node->type == BTRFS_SHARED_DATA_REF_KEY)
2330 ret = run_delayed_data_ref(trans, root, node, extent_op,
2331 insert_reserved);
2332 else
2333 BUG();
2334 return ret;
2335 }
2336
2337 static noinline struct btrfs_delayed_ref_node *
2338 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2339 {
2340 struct rb_node *node;
2341 struct btrfs_delayed_ref_node *ref, *last = NULL;;
2342
2343 /*
2344 * select delayed ref of type BTRFS_ADD_DELAYED_REF first.
2345 * this prevents ref count from going down to zero when
2346 * there still are pending delayed ref.
2347 */
2348 node = rb_first(&head->ref_root);
2349 while (node) {
2350 ref = rb_entry(node, struct btrfs_delayed_ref_node,
2351 rb_node);
2352 if (ref->action == BTRFS_ADD_DELAYED_REF)
2353 return ref;
2354 else if (last == NULL)
2355 last = ref;
2356 node = rb_next(node);
2357 }
2358 return last;
2359 }
2360
2361 /*
2362 * Returns 0 on success or if called with an already aborted transaction.
2363 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2364 */
2365 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2366 struct btrfs_root *root,
2367 unsigned long nr)
2368 {
2369 struct btrfs_delayed_ref_root *delayed_refs;
2370 struct btrfs_delayed_ref_node *ref;
2371 struct btrfs_delayed_ref_head *locked_ref = NULL;
2372 struct btrfs_delayed_extent_op *extent_op;
2373 struct btrfs_fs_info *fs_info = root->fs_info;
2374 ktime_t start = ktime_get();
2375 int ret;
2376 unsigned long count = 0;
2377 unsigned long actual_count = 0;
2378 int must_insert_reserved = 0;
2379
2380 delayed_refs = &trans->transaction->delayed_refs;
2381 while (1) {
2382 if (!locked_ref) {
2383 if (count >= nr)
2384 break;
2385
2386 spin_lock(&delayed_refs->lock);
2387 locked_ref = btrfs_select_ref_head(trans);
2388 if (!locked_ref) {
2389 spin_unlock(&delayed_refs->lock);
2390 break;
2391 }
2392
2393 /* grab the lock that says we are going to process
2394 * all the refs for this head */
2395 ret = btrfs_delayed_ref_lock(trans, locked_ref);
2396 spin_unlock(&delayed_refs->lock);
2397 /*
2398 * we may have dropped the spin lock to get the head
2399 * mutex lock, and that might have given someone else
2400 * time to free the head. If that's true, it has been
2401 * removed from our list and we can move on.
2402 */
2403 if (ret == -EAGAIN) {
2404 locked_ref = NULL;
2405 count++;
2406 continue;
2407 }
2408 }
2409
2410 /*
2411 * We need to try and merge add/drops of the same ref since we
2412 * can run into issues with relocate dropping the implicit ref
2413 * and then it being added back again before the drop can
2414 * finish. If we merged anything we need to re-loop so we can
2415 * get a good ref.
2416 */
2417 spin_lock(&locked_ref->lock);
2418 btrfs_merge_delayed_refs(trans, fs_info, delayed_refs,
2419 locked_ref);
2420
2421 /*
2422 * locked_ref is the head node, so we have to go one
2423 * node back for any delayed ref updates
2424 */
2425 ref = select_delayed_ref(locked_ref);
2426
2427 if (ref && ref->seq &&
2428 btrfs_check_delayed_seq(fs_info, delayed_refs, ref->seq)) {
2429 spin_unlock(&locked_ref->lock);
2430 btrfs_delayed_ref_unlock(locked_ref);
2431 spin_lock(&delayed_refs->lock);
2432 locked_ref->processing = 0;
2433 delayed_refs->num_heads_ready++;
2434 spin_unlock(&delayed_refs->lock);
2435 locked_ref = NULL;
2436 cond_resched();
2437 count++;
2438 continue;
2439 }
2440
2441 /*
2442 * record the must insert reserved flag before we
2443 * drop the spin lock.
2444 */
2445 must_insert_reserved = locked_ref->must_insert_reserved;
2446 locked_ref->must_insert_reserved = 0;
2447
2448 extent_op = locked_ref->extent_op;
2449 locked_ref->extent_op = NULL;
2450
2451 if (!ref) {
2452
2453
2454 /* All delayed refs have been processed, Go ahead
2455 * and send the head node to run_one_delayed_ref,
2456 * so that any accounting fixes can happen
2457 */
2458 ref = &locked_ref->node;
2459
2460 if (extent_op && must_insert_reserved) {
2461 btrfs_free_delayed_extent_op(extent_op);
2462 extent_op = NULL;
2463 }
2464
2465 if (extent_op) {
2466 spin_unlock(&locked_ref->lock);
2467 ret = run_delayed_extent_op(trans, root,
2468 ref, extent_op);
2469 btrfs_free_delayed_extent_op(extent_op);
2470
2471 if (ret) {
2472 /*
2473 * Need to reset must_insert_reserved if
2474 * there was an error so the abort stuff
2475 * can cleanup the reserved space
2476 * properly.
2477 */
2478 if (must_insert_reserved)
2479 locked_ref->must_insert_reserved = 1;
2480 locked_ref->processing = 0;
2481 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
2482 btrfs_delayed_ref_unlock(locked_ref);
2483 return ret;
2484 }
2485 continue;
2486 }
2487
2488 /*
2489 * Need to drop our head ref lock and re-aqcuire the
2490 * delayed ref lock and then re-check to make sure
2491 * nobody got added.
2492 */
2493 spin_unlock(&locked_ref->lock);
2494 spin_lock(&delayed_refs->lock);
2495 spin_lock(&locked_ref->lock);
2496 if (rb_first(&locked_ref->ref_root) ||
2497 locked_ref->extent_op) {
2498 spin_unlock(&locked_ref->lock);
2499 spin_unlock(&delayed_refs->lock);
2500 continue;
2501 }
2502 ref->in_tree = 0;
2503 delayed_refs->num_heads--;
2504 rb_erase(&locked_ref->href_node,
2505 &delayed_refs->href_root);
2506 spin_unlock(&delayed_refs->lock);
2507 } else {
2508 actual_count++;
2509 ref->in_tree = 0;
2510 rb_erase(&ref->rb_node, &locked_ref->ref_root);
2511 }
2512 atomic_dec(&delayed_refs->num_entries);
2513
2514 if (!btrfs_delayed_ref_is_head(ref)) {
2515 /*
2516 * when we play the delayed ref, also correct the
2517 * ref_mod on head
2518 */
2519 switch (ref->action) {
2520 case BTRFS_ADD_DELAYED_REF:
2521 case BTRFS_ADD_DELAYED_EXTENT:
2522 locked_ref->node.ref_mod -= ref->ref_mod;
2523 break;
2524 case BTRFS_DROP_DELAYED_REF:
2525 locked_ref->node.ref_mod += ref->ref_mod;
2526 break;
2527 default:
2528 WARN_ON(1);
2529 }
2530 }
2531 spin_unlock(&locked_ref->lock);
2532
2533 ret = run_one_delayed_ref(trans, root, ref, extent_op,
2534 must_insert_reserved);
2535
2536 btrfs_free_delayed_extent_op(extent_op);
2537 if (ret) {
2538 locked_ref->processing = 0;
2539 btrfs_delayed_ref_unlock(locked_ref);
2540 btrfs_put_delayed_ref(ref);
2541 btrfs_debug(fs_info, "run_one_delayed_ref returned %d", ret);
2542 return ret;
2543 }
2544
2545 /*
2546 * If this node is a head, that means all the refs in this head
2547 * have been dealt with, and we will pick the next head to deal
2548 * with, so we must unlock the head and drop it from the cluster
2549 * list before we release it.
2550 */
2551 if (btrfs_delayed_ref_is_head(ref)) {
2552 btrfs_delayed_ref_unlock(locked_ref);
2553 locked_ref = NULL;
2554 }
2555 btrfs_put_delayed_ref(ref);
2556 count++;
2557 cond_resched();
2558 }
2559
2560 /*
2561 * We don't want to include ref heads since we can have empty ref heads
2562 * and those will drastically skew our runtime down since we just do
2563 * accounting, no actual extent tree updates.
2564 */
2565 if (actual_count > 0) {
2566 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2567 u64 avg;
2568
2569 /*
2570 * We weigh the current average higher than our current runtime
2571 * to avoid large swings in the average.
2572 */
2573 spin_lock(&delayed_refs->lock);
2574 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2575 avg = div64_u64(avg, 4);
2576 fs_info->avg_delayed_ref_runtime = avg;
2577 spin_unlock(&delayed_refs->lock);
2578 }
2579 return 0;
2580 }
2581
2582 #ifdef SCRAMBLE_DELAYED_REFS
2583 /*
2584 * Normally delayed refs get processed in ascending bytenr order. This
2585 * correlates in most cases to the order added. To expose dependencies on this
2586 * order, we start to process the tree in the middle instead of the beginning
2587 */
2588 static u64 find_middle(struct rb_root *root)
2589 {
2590 struct rb_node *n = root->rb_node;
2591 struct btrfs_delayed_ref_node *entry;
2592 int alt = 1;
2593 u64 middle;
2594 u64 first = 0, last = 0;
2595
2596 n = rb_first(root);
2597 if (n) {
2598 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2599 first = entry->bytenr;
2600 }
2601 n = rb_last(root);
2602 if (n) {
2603 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2604 last = entry->bytenr;
2605 }
2606 n = root->rb_node;
2607
2608 while (n) {
2609 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2610 WARN_ON(!entry->in_tree);
2611
2612 middle = entry->bytenr;
2613
2614 if (alt)
2615 n = n->rb_left;
2616 else
2617 n = n->rb_right;
2618
2619 alt = 1 - alt;
2620 }
2621 return middle;
2622 }
2623 #endif
2624
2625 static inline u64 heads_to_leaves(struct btrfs_root *root, u64 heads)
2626 {
2627 u64 num_bytes;
2628
2629 num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2630 sizeof(struct btrfs_extent_inline_ref));
2631 if (!btrfs_fs_incompat(root->fs_info, SKINNY_METADATA))
2632 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2633
2634 /*
2635 * We don't ever fill up leaves all the way so multiply by 2 just to be
2636 * closer to what we're really going to want to ouse.
2637 */
2638 return div64_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(root));
2639 }
2640
2641 int btrfs_check_space_for_delayed_refs(struct btrfs_trans_handle *trans,
2642 struct btrfs_root *root)
2643 {
2644 struct btrfs_block_rsv *global_rsv;
2645 u64 num_heads = trans->transaction->delayed_refs.num_heads_ready;
2646 u64 num_bytes;
2647 int ret = 0;
2648
2649 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
2650 num_heads = heads_to_leaves(root, num_heads);
2651 if (num_heads > 1)
2652 num_bytes += (num_heads - 1) * root->leafsize;
2653 num_bytes <<= 1;
2654 global_rsv = &root->fs_info->global_block_rsv;
2655
2656 /*
2657 * If we can't allocate any more chunks lets make sure we have _lots_ of
2658 * wiggle room since running delayed refs can create more delayed refs.
2659 */
2660 if (global_rsv->space_info->full)
2661 num_bytes <<= 1;
2662
2663 spin_lock(&global_rsv->lock);
2664 if (global_rsv->reserved <= num_bytes)
2665 ret = 1;
2666 spin_unlock(&global_rsv->lock);
2667 return ret;
2668 }
2669
2670 int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans,
2671 struct btrfs_root *root)
2672 {
2673 struct btrfs_fs_info *fs_info = root->fs_info;
2674 u64 num_entries =
2675 atomic_read(&trans->transaction->delayed_refs.num_entries);
2676 u64 avg_runtime;
2677
2678 smp_mb();
2679 avg_runtime = fs_info->avg_delayed_ref_runtime;
2680 if (num_entries * avg_runtime >= NSEC_PER_SEC)
2681 return 1;
2682
2683 return btrfs_check_space_for_delayed_refs(trans, root);
2684 }
2685
2686 /*
2687 * this starts processing the delayed reference count updates and
2688 * extent insertions we have queued up so far. count can be
2689 * 0, which means to process everything in the tree at the start
2690 * of the run (but not newly added entries), or it can be some target
2691 * number you'd like to process.
2692 *
2693 * Returns 0 on success or if called with an aborted transaction
2694 * Returns <0 on error and aborts the transaction
2695 */
2696 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2697 struct btrfs_root *root, unsigned long count)
2698 {
2699 struct rb_node *node;
2700 struct btrfs_delayed_ref_root *delayed_refs;
2701 struct btrfs_delayed_ref_head *head;
2702 int ret;
2703 int run_all = count == (unsigned long)-1;
2704 int run_most = 0;
2705
2706 /* We'll clean this up in btrfs_cleanup_transaction */
2707 if (trans->aborted)
2708 return 0;
2709
2710 if (root == root->fs_info->extent_root)
2711 root = root->fs_info->tree_root;
2712
2713 delayed_refs = &trans->transaction->delayed_refs;
2714 if (count == 0) {
2715 count = atomic_read(&delayed_refs->num_entries) * 2;
2716 run_most = 1;
2717 }
2718
2719 again:
2720 #ifdef SCRAMBLE_DELAYED_REFS
2721 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2722 #endif
2723 ret = __btrfs_run_delayed_refs(trans, root, count);
2724 if (ret < 0) {
2725 btrfs_abort_transaction(trans, root, ret);
2726 return ret;
2727 }
2728
2729 if (run_all) {
2730 if (!list_empty(&trans->new_bgs))
2731 btrfs_create_pending_block_groups(trans, root);
2732
2733 spin_lock(&delayed_refs->lock);
2734 node = rb_first(&delayed_refs->href_root);
2735 if (!node) {
2736 spin_unlock(&delayed_refs->lock);
2737 goto out;
2738 }
2739 count = (unsigned long)-1;
2740
2741 while (node) {
2742 head = rb_entry(node, struct btrfs_delayed_ref_head,
2743 href_node);
2744 if (btrfs_delayed_ref_is_head(&head->node)) {
2745 struct btrfs_delayed_ref_node *ref;
2746
2747 ref = &head->node;
2748 atomic_inc(&ref->refs);
2749
2750 spin_unlock(&delayed_refs->lock);
2751 /*
2752 * Mutex was contended, block until it's
2753 * released and try again
2754 */
2755 mutex_lock(&head->mutex);
2756 mutex_unlock(&head->mutex);
2757
2758 btrfs_put_delayed_ref(ref);
2759 cond_resched();
2760 goto again;
2761 } else {
2762 WARN_ON(1);
2763 }
2764 node = rb_next(node);
2765 }
2766 spin_unlock(&delayed_refs->lock);
2767 cond_resched();
2768 goto again;
2769 }
2770 out:
2771 ret = btrfs_delayed_qgroup_accounting(trans, root->fs_info);
2772 if (ret)
2773 return ret;
2774 assert_qgroups_uptodate(trans);
2775 return 0;
2776 }
2777
2778 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2779 struct btrfs_root *root,
2780 u64 bytenr, u64 num_bytes, u64 flags,
2781 int level, int is_data)
2782 {
2783 struct btrfs_delayed_extent_op *extent_op;
2784 int ret;
2785
2786 extent_op = btrfs_alloc_delayed_extent_op();
2787 if (!extent_op)
2788 return -ENOMEM;
2789
2790 extent_op->flags_to_set = flags;
2791 extent_op->update_flags = 1;
2792 extent_op->update_key = 0;
2793 extent_op->is_data = is_data ? 1 : 0;
2794 extent_op->level = level;
2795
2796 ret = btrfs_add_delayed_extent_op(root->fs_info, trans, bytenr,
2797 num_bytes, extent_op);
2798 if (ret)
2799 btrfs_free_delayed_extent_op(extent_op);
2800 return ret;
2801 }
2802
2803 static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
2804 struct btrfs_root *root,
2805 struct btrfs_path *path,
2806 u64 objectid, u64 offset, u64 bytenr)
2807 {
2808 struct btrfs_delayed_ref_head *head;
2809 struct btrfs_delayed_ref_node *ref;
2810 struct btrfs_delayed_data_ref *data_ref;
2811 struct btrfs_delayed_ref_root *delayed_refs;
2812 struct rb_node *node;
2813 int ret = 0;
2814
2815 delayed_refs = &trans->transaction->delayed_refs;
2816 spin_lock(&delayed_refs->lock);
2817 head = btrfs_find_delayed_ref_head(trans, bytenr);
2818 if (!head) {
2819 spin_unlock(&delayed_refs->lock);
2820 return 0;
2821 }
2822
2823 if (!mutex_trylock(&head->mutex)) {
2824 atomic_inc(&head->node.refs);
2825 spin_unlock(&delayed_refs->lock);
2826
2827 btrfs_release_path(path);
2828
2829 /*
2830 * Mutex was contended, block until it's released and let
2831 * caller try again
2832 */
2833 mutex_lock(&head->mutex);
2834 mutex_unlock(&head->mutex);
2835 btrfs_put_delayed_ref(&head->node);
2836 return -EAGAIN;
2837 }
2838 spin_unlock(&delayed_refs->lock);
2839
2840 spin_lock(&head->lock);
2841 node = rb_first(&head->ref_root);
2842 while (node) {
2843 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2844 node = rb_next(node);
2845
2846 /* If it's a shared ref we know a cross reference exists */
2847 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
2848 ret = 1;
2849 break;
2850 }
2851
2852 data_ref = btrfs_delayed_node_to_data_ref(ref);
2853
2854 /*
2855 * If our ref doesn't match the one we're currently looking at
2856 * then we have a cross reference.
2857 */
2858 if (data_ref->root != root->root_key.objectid ||
2859 data_ref->objectid != objectid ||
2860 data_ref->offset != offset) {
2861 ret = 1;
2862 break;
2863 }
2864 }
2865 spin_unlock(&head->lock);
2866 mutex_unlock(&head->mutex);
2867 return ret;
2868 }
2869
2870 static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
2871 struct btrfs_root *root,
2872 struct btrfs_path *path,
2873 u64 objectid, u64 offset, u64 bytenr)
2874 {
2875 struct btrfs_root *extent_root = root->fs_info->extent_root;
2876 struct extent_buffer *leaf;
2877 struct btrfs_extent_data_ref *ref;
2878 struct btrfs_extent_inline_ref *iref;
2879 struct btrfs_extent_item *ei;
2880 struct btrfs_key key;
2881 u32 item_size;
2882 int ret;
2883
2884 key.objectid = bytenr;
2885 key.offset = (u64)-1;
2886 key.type = BTRFS_EXTENT_ITEM_KEY;
2887
2888 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2889 if (ret < 0)
2890 goto out;
2891 BUG_ON(ret == 0); /* Corruption */
2892
2893 ret = -ENOENT;
2894 if (path->slots[0] == 0)
2895 goto out;
2896
2897 path->slots[0]--;
2898 leaf = path->nodes[0];
2899 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2900
2901 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2902 goto out;
2903
2904 ret = 1;
2905 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2906 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2907 if (item_size < sizeof(*ei)) {
2908 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
2909 goto out;
2910 }
2911 #endif
2912 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2913
2914 if (item_size != sizeof(*ei) +
2915 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2916 goto out;
2917
2918 if (btrfs_extent_generation(leaf, ei) <=
2919 btrfs_root_last_snapshot(&root->root_item))
2920 goto out;
2921
2922 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2923 if (btrfs_extent_inline_ref_type(leaf, iref) !=
2924 BTRFS_EXTENT_DATA_REF_KEY)
2925 goto out;
2926
2927 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2928 if (btrfs_extent_refs(leaf, ei) !=
2929 btrfs_extent_data_ref_count(leaf, ref) ||
2930 btrfs_extent_data_ref_root(leaf, ref) !=
2931 root->root_key.objectid ||
2932 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2933 btrfs_extent_data_ref_offset(leaf, ref) != offset)
2934 goto out;
2935
2936 ret = 0;
2937 out:
2938 return ret;
2939 }
2940
2941 int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
2942 struct btrfs_root *root,
2943 u64 objectid, u64 offset, u64 bytenr)
2944 {
2945 struct btrfs_path *path;
2946 int ret;
2947 int ret2;
2948
2949 path = btrfs_alloc_path();
2950 if (!path)
2951 return -ENOENT;
2952
2953 do {
2954 ret = check_committed_ref(trans, root, path, objectid,
2955 offset, bytenr);
2956 if (ret && ret != -ENOENT)
2957 goto out;
2958
2959 ret2 = check_delayed_ref(trans, root, path, objectid,
2960 offset, bytenr);
2961 } while (ret2 == -EAGAIN);
2962
2963 if (ret2 && ret2 != -ENOENT) {
2964 ret = ret2;
2965 goto out;
2966 }
2967
2968 if (ret != -ENOENT || ret2 != -ENOENT)
2969 ret = 0;
2970 out:
2971 btrfs_free_path(path);
2972 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2973 WARN_ON(ret > 0);
2974 return ret;
2975 }
2976
2977 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2978 struct btrfs_root *root,
2979 struct extent_buffer *buf,
2980 int full_backref, int inc, int no_quota)
2981 {
2982 u64 bytenr;
2983 u64 num_bytes;
2984 u64 parent;
2985 u64 ref_root;
2986 u32 nritems;
2987 struct btrfs_key key;
2988 struct btrfs_file_extent_item *fi;
2989 int i;
2990 int level;
2991 int ret = 0;
2992 int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
2993 u64, u64, u64, u64, u64, u64, int);
2994
2995 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
2996 if (unlikely(test_bit(BTRFS_ROOT_DUMMY_ROOT, &root->state)))
2997 return 0;
2998 #endif
2999 ref_root = btrfs_header_owner(buf);
3000 nritems = btrfs_header_nritems(buf);
3001 level = btrfs_header_level(buf);
3002
3003 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
3004 return 0;
3005
3006 if (inc)
3007 process_func = btrfs_inc_extent_ref;
3008 else
3009 process_func = btrfs_free_extent;
3010
3011 if (full_backref)
3012 parent = buf->start;
3013 else
3014 parent = 0;
3015
3016 for (i = 0; i < nritems; i++) {
3017 if (level == 0) {
3018 btrfs_item_key_to_cpu(buf, &key, i);
3019 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
3020 continue;
3021 fi = btrfs_item_ptr(buf, i,
3022 struct btrfs_file_extent_item);
3023 if (btrfs_file_extent_type(buf, fi) ==
3024 BTRFS_FILE_EXTENT_INLINE)
3025 continue;
3026 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
3027 if (bytenr == 0)
3028 continue;
3029
3030 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
3031 key.offset -= btrfs_file_extent_offset(buf, fi);
3032 ret = process_func(trans, root, bytenr, num_bytes,
3033 parent, ref_root, key.objectid,
3034 key.offset, no_quota);
3035 if (ret)
3036 goto fail;
3037 } else {
3038 bytenr = btrfs_node_blockptr(buf, i);
3039 num_bytes = btrfs_level_size(root, level - 1);
3040 ret = process_func(trans, root, bytenr, num_bytes,
3041 parent, ref_root, level - 1, 0,
3042 no_quota);
3043 if (ret)
3044 goto fail;
3045 }
3046 }
3047 return 0;
3048 fail:
3049 return ret;
3050 }
3051
3052 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3053 struct extent_buffer *buf, int full_backref, int no_quota)
3054 {
3055 return __btrfs_mod_ref(trans, root, buf, full_backref, 1, no_quota);
3056 }
3057
3058 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3059 struct extent_buffer *buf, int full_backref, int no_quota)
3060 {
3061 return __btrfs_mod_ref(trans, root, buf, full_backref, 0, no_quota);
3062 }
3063
3064 static int write_one_cache_group(struct btrfs_trans_handle *trans,
3065 struct btrfs_root *root,
3066 struct btrfs_path *path,
3067 struct btrfs_block_group_cache *cache)
3068 {
3069 int ret;
3070 struct btrfs_root *extent_root = root->fs_info->extent_root;
3071 unsigned long bi;
3072 struct extent_buffer *leaf;
3073
3074 ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
3075 if (ret < 0)
3076 goto fail;
3077 BUG_ON(ret); /* Corruption */
3078
3079 leaf = path->nodes[0];
3080 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3081 write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
3082 btrfs_mark_buffer_dirty(leaf);
3083 btrfs_release_path(path);
3084 fail:
3085 if (ret) {
3086 btrfs_abort_transaction(trans, root, ret);
3087 return ret;
3088 }
3089 return 0;
3090
3091 }
3092
3093 static struct btrfs_block_group_cache *
3094 next_block_group(struct btrfs_root *root,
3095 struct btrfs_block_group_cache *cache)
3096 {
3097 struct rb_node *node;
3098 spin_lock(&root->fs_info->block_group_cache_lock);
3099 node = rb_next(&cache->cache_node);
3100 btrfs_put_block_group(cache);
3101 if (node) {
3102 cache = rb_entry(node, struct btrfs_block_group_cache,
3103 cache_node);
3104 btrfs_get_block_group(cache);
3105 } else
3106 cache = NULL;
3107 spin_unlock(&root->fs_info->block_group_cache_lock);
3108 return cache;
3109 }
3110
3111 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
3112 struct btrfs_trans_handle *trans,
3113 struct btrfs_path *path)
3114 {
3115 struct btrfs_root *root = block_group->fs_info->tree_root;
3116 struct inode *inode = NULL;
3117 u64 alloc_hint = 0;
3118 int dcs = BTRFS_DC_ERROR;
3119 int num_pages = 0;
3120 int retries = 0;
3121 int ret = 0;
3122
3123 /*
3124 * If this block group is smaller than 100 megs don't bother caching the
3125 * block group.
3126 */
3127 if (block_group->key.offset < (100 * 1024 * 1024)) {
3128 spin_lock(&block_group->lock);
3129 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3130 spin_unlock(&block_group->lock);
3131 return 0;
3132 }
3133
3134 again:
3135 inode = lookup_free_space_inode(root, block_group, path);
3136 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3137 ret = PTR_ERR(inode);
3138 btrfs_release_path(path);
3139 goto out;
3140 }
3141
3142 if (IS_ERR(inode)) {
3143 BUG_ON(retries);
3144 retries++;
3145
3146 if (block_group->ro)
3147 goto out_free;
3148
3149 ret = create_free_space_inode(root, trans, block_group, path);
3150 if (ret)
3151 goto out_free;
3152 goto again;
3153 }
3154
3155 /* We've already setup this transaction, go ahead and exit */
3156 if (block_group->cache_generation == trans->transid &&
3157 i_size_read(inode)) {
3158 dcs = BTRFS_DC_SETUP;
3159 goto out_put;
3160 }
3161
3162 /*
3163 * We want to set the generation to 0, that way if anything goes wrong
3164 * from here on out we know not to trust this cache when we load up next
3165 * time.
3166 */
3167 BTRFS_I(inode)->generation = 0;
3168 ret = btrfs_update_inode(trans, root, inode);
3169 WARN_ON(ret);
3170
3171 if (i_size_read(inode) > 0) {
3172 ret = btrfs_check_trunc_cache_free_space(root,
3173 &root->fs_info->global_block_rsv);
3174 if (ret)
3175 goto out_put;
3176
3177 ret = btrfs_truncate_free_space_cache(root, trans, inode);
3178 if (ret)
3179 goto out_put;
3180 }
3181
3182 spin_lock(&block_group->lock);
3183 if (block_group->cached != BTRFS_CACHE_FINISHED ||
3184 !btrfs_test_opt(root, SPACE_CACHE)) {
3185 /*
3186 * don't bother trying to write stuff out _if_
3187 * a) we're not cached,
3188 * b) we're with nospace_cache mount option.
3189 */
3190 dcs = BTRFS_DC_WRITTEN;
3191 spin_unlock(&block_group->lock);
3192 goto out_put;
3193 }
3194 spin_unlock(&block_group->lock);
3195
3196 /*
3197 * Try to preallocate enough space based on how big the block group is.
3198 * Keep in mind this has to include any pinned space which could end up
3199 * taking up quite a bit since it's not folded into the other space
3200 * cache.
3201 */
3202 num_pages = (int)div64_u64(block_group->key.offset, 256 * 1024 * 1024);
3203 if (!num_pages)
3204 num_pages = 1;
3205
3206 num_pages *= 16;
3207 num_pages *= PAGE_CACHE_SIZE;
3208
3209 ret = btrfs_check_data_free_space(inode, num_pages);
3210 if (ret)
3211 goto out_put;
3212
3213 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3214 num_pages, num_pages,
3215 &alloc_hint);
3216 if (!ret)
3217 dcs = BTRFS_DC_SETUP;
3218 btrfs_free_reserved_data_space(inode, num_pages);
3219
3220 out_put:
3221 iput(inode);
3222 out_free:
3223 btrfs_release_path(path);
3224 out:
3225 spin_lock(&block_group->lock);
3226 if (!ret && dcs == BTRFS_DC_SETUP)
3227 block_group->cache_generation = trans->transid;
3228 block_group->disk_cache_state = dcs;
3229 spin_unlock(&block_group->lock);
3230
3231 return ret;
3232 }
3233
3234 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
3235 struct btrfs_root *root)
3236 {
3237 struct btrfs_block_group_cache *cache;
3238 int err = 0;
3239 struct btrfs_path *path;
3240 u64 last = 0;
3241
3242 path = btrfs_alloc_path();
3243 if (!path)
3244 return -ENOMEM;
3245
3246 again:
3247 while (1) {
3248 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3249 while (cache) {
3250 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3251 break;
3252 cache = next_block_group(root, cache);
3253 }
3254 if (!cache) {
3255 if (last == 0)
3256 break;
3257 last = 0;
3258 continue;
3259 }
3260 err = cache_save_setup(cache, trans, path);
3261 last = cache->key.objectid + cache->key.offset;
3262 btrfs_put_block_group(cache);
3263 }
3264
3265 while (1) {
3266 if (last == 0) {
3267 err = btrfs_run_delayed_refs(trans, root,
3268 (unsigned long)-1);
3269 if (err) /* File system offline */
3270 goto out;
3271 }
3272
3273 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3274 while (cache) {
3275 if (cache->disk_cache_state == BTRFS_DC_CLEAR) {
3276 btrfs_put_block_group(cache);
3277 goto again;
3278 }
3279
3280 if (cache->dirty)
3281 break;
3282 cache = next_block_group(root, cache);
3283 }
3284 if (!cache) {
3285 if (last == 0)
3286 break;
3287 last = 0;
3288 continue;
3289 }
3290
3291 if (cache->disk_cache_state == BTRFS_DC_SETUP)
3292 cache->disk_cache_state = BTRFS_DC_NEED_WRITE;
3293 cache->dirty = 0;
3294 last = cache->key.objectid + cache->key.offset;
3295
3296 err = write_one_cache_group(trans, root, path, cache);
3297 btrfs_put_block_group(cache);
3298 if (err) /* File system offline */
3299 goto out;
3300 }
3301
3302 while (1) {
3303 /*
3304 * I don't think this is needed since we're just marking our
3305 * preallocated extent as written, but just in case it can't
3306 * hurt.
3307 */
3308 if (last == 0) {
3309 err = btrfs_run_delayed_refs(trans, root,
3310 (unsigned long)-1);
3311 if (err) /* File system offline */
3312 goto out;
3313 }
3314
3315 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3316 while (cache) {
3317 /*
3318 * Really this shouldn't happen, but it could if we
3319 * couldn't write the entire preallocated extent and
3320 * splitting the extent resulted in a new block.
3321 */
3322 if (cache->dirty) {
3323 btrfs_put_block_group(cache);
3324 goto again;
3325 }
3326 if (cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
3327 break;
3328 cache = next_block_group(root, cache);
3329 }
3330 if (!cache) {
3331 if (last == 0)
3332 break;
3333 last = 0;
3334 continue;
3335 }
3336
3337 err = btrfs_write_out_cache(root, trans, cache, path);
3338
3339 /*
3340 * If we didn't have an error then the cache state is still
3341 * NEED_WRITE, so we can set it to WRITTEN.
3342 */
3343 if (!err && cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
3344 cache->disk_cache_state = BTRFS_DC_WRITTEN;
3345 last = cache->key.objectid + cache->key.offset;
3346 btrfs_put_block_group(cache);
3347 }
3348 out:
3349
3350 btrfs_free_path(path);
3351 return err;
3352 }
3353
3354 int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
3355 {
3356 struct btrfs_block_group_cache *block_group;
3357 int readonly = 0;
3358
3359 block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
3360 if (!block_group || block_group->ro)
3361 readonly = 1;
3362 if (block_group)
3363 btrfs_put_block_group(block_group);
3364 return readonly;
3365 }
3366
3367 static const char *alloc_name(u64 flags)
3368 {
3369 switch (flags) {
3370 case BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA:
3371 return "mixed";
3372 case BTRFS_BLOCK_GROUP_METADATA:
3373 return "metadata";
3374 case BTRFS_BLOCK_GROUP_DATA:
3375 return "data";
3376 case BTRFS_BLOCK_GROUP_SYSTEM:
3377 return "system";
3378 default:
3379 WARN_ON(1);
3380 return "invalid-combination";
3381 };
3382 }
3383
3384 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
3385 u64 total_bytes, u64 bytes_used,
3386 struct btrfs_space_info **space_info)
3387 {
3388 struct btrfs_space_info *found;
3389 int i;
3390 int factor;
3391 int ret;
3392
3393 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3394 BTRFS_BLOCK_GROUP_RAID10))
3395 factor = 2;
3396 else
3397 factor = 1;
3398
3399 found = __find_space_info(info, flags);
3400 if (found) {
3401 spin_lock(&found->lock);
3402 found->total_bytes += total_bytes;
3403 found->disk_total += total_bytes * factor;
3404 found->bytes_used += bytes_used;
3405 found->disk_used += bytes_used * factor;
3406 found->full = 0;
3407 spin_unlock(&found->lock);
3408 *space_info = found;
3409 return 0;
3410 }
3411 found = kzalloc(sizeof(*found), GFP_NOFS);
3412 if (!found)
3413 return -ENOMEM;
3414
3415 ret = percpu_counter_init(&found->total_bytes_pinned, 0);
3416 if (ret) {
3417 kfree(found);
3418 return ret;
3419 }
3420
3421 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
3422 INIT_LIST_HEAD(&found->block_groups[i]);
3423 kobject_init(&found->block_group_kobjs[i], &btrfs_raid_ktype);
3424 }
3425 init_rwsem(&found->groups_sem);
3426 spin_lock_init(&found->lock);
3427 found->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
3428 found->total_bytes = total_bytes;
3429 found->disk_total = total_bytes * factor;
3430 found->bytes_used = bytes_used;
3431 found->disk_used = bytes_used * factor;
3432 found->bytes_pinned = 0;
3433 found->bytes_reserved = 0;
3434 found->bytes_readonly = 0;
3435 found->bytes_may_use = 0;
3436 found->full = 0;
3437 found->force_alloc = CHUNK_ALLOC_NO_FORCE;
3438 found->chunk_alloc = 0;
3439 found->flush = 0;
3440 init_waitqueue_head(&found->wait);
3441
3442 ret = kobject_init_and_add(&found->kobj, &space_info_ktype,
3443 info->space_info_kobj, "%s",
3444 alloc_name(found->flags));
3445 if (ret) {
3446 kfree(found);
3447 return ret;
3448 }
3449
3450 *space_info = found;
3451 list_add_rcu(&found->list, &info->space_info);
3452 if (flags & BTRFS_BLOCK_GROUP_DATA)
3453 info->data_sinfo = found;
3454
3455 return ret;
3456 }
3457
3458 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3459 {
3460 u64 extra_flags = chunk_to_extended(flags) &
3461 BTRFS_EXTENDED_PROFILE_MASK;
3462
3463 write_seqlock(&fs_info->profiles_lock);
3464 if (flags & BTRFS_BLOCK_GROUP_DATA)
3465 fs_info->avail_data_alloc_bits |= extra_flags;
3466 if (flags & BTRFS_BLOCK_GROUP_METADATA)
3467 fs_info->avail_metadata_alloc_bits |= extra_flags;
3468 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3469 fs_info->avail_system_alloc_bits |= extra_flags;
3470 write_sequnlock(&fs_info->profiles_lock);
3471 }
3472
3473 /*
3474 * returns target flags in extended format or 0 if restripe for this
3475 * chunk_type is not in progress
3476 *
3477 * should be called with either volume_mutex or balance_lock held
3478 */
3479 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
3480 {
3481 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3482 u64 target = 0;
3483
3484 if (!bctl)
3485 return 0;
3486
3487 if (flags & BTRFS_BLOCK_GROUP_DATA &&
3488 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3489 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
3490 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
3491 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3492 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
3493 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
3494 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3495 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
3496 }
3497
3498 return target;
3499 }
3500
3501 /*
3502 * @flags: available profiles in extended format (see ctree.h)
3503 *
3504 * Returns reduced profile in chunk format. If profile changing is in
3505 * progress (either running or paused) picks the target profile (if it's
3506 * already available), otherwise falls back to plain reducing.
3507 */
3508 static u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
3509 {
3510 /*
3511 * we add in the count of missing devices because we want
3512 * to make sure that any RAID levels on a degraded FS
3513 * continue to be honored.
3514 */
3515 u64 num_devices = root->fs_info->fs_devices->rw_devices +
3516 root->fs_info->fs_devices->missing_devices;
3517 u64 target;
3518 u64 tmp;
3519
3520 /*
3521 * see if restripe for this chunk_type is in progress, if so
3522 * try to reduce to the target profile
3523 */
3524 spin_lock(&root->fs_info->balance_lock);
3525 target = get_restripe_target(root->fs_info, flags);
3526 if (target) {
3527 /* pick target profile only if it's already available */
3528 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
3529 spin_unlock(&root->fs_info->balance_lock);
3530 return extended_to_chunk(target);
3531 }
3532 }
3533 spin_unlock(&root->fs_info->balance_lock);
3534
3535 /* First, mask out the RAID levels which aren't possible */
3536 if (num_devices == 1)
3537 flags &= ~(BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID0 |
3538 BTRFS_BLOCK_GROUP_RAID5);
3539 if (num_devices < 3)
3540 flags &= ~BTRFS_BLOCK_GROUP_RAID6;
3541 if (num_devices < 4)
3542 flags &= ~BTRFS_BLOCK_GROUP_RAID10;
3543
3544 tmp = flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID0 |
3545 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID5 |
3546 BTRFS_BLOCK_GROUP_RAID6 | BTRFS_BLOCK_GROUP_RAID10);
3547 flags &= ~tmp;
3548
3549 if (tmp & BTRFS_BLOCK_GROUP_RAID6)
3550 tmp = BTRFS_BLOCK_GROUP_RAID6;
3551 else if (tmp & BTRFS_BLOCK_GROUP_RAID5)
3552 tmp = BTRFS_BLOCK_GROUP_RAID5;
3553 else if (tmp & BTRFS_BLOCK_GROUP_RAID10)
3554 tmp = BTRFS_BLOCK_GROUP_RAID10;
3555 else if (tmp & BTRFS_BLOCK_GROUP_RAID1)
3556 tmp = BTRFS_BLOCK_GROUP_RAID1;
3557 else if (tmp & BTRFS_BLOCK_GROUP_RAID0)
3558 tmp = BTRFS_BLOCK_GROUP_RAID0;
3559
3560 return extended_to_chunk(flags | tmp);
3561 }
3562
3563 static u64 get_alloc_profile(struct btrfs_root *root, u64 orig_flags)
3564 {
3565 unsigned seq;
3566 u64 flags;
3567
3568 do {
3569 flags = orig_flags;
3570 seq = read_seqbegin(&root->fs_info->profiles_lock);
3571
3572 if (flags & BTRFS_BLOCK_GROUP_DATA)
3573 flags |= root->fs_info->avail_data_alloc_bits;
3574 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3575 flags |= root->fs_info->avail_system_alloc_bits;
3576 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
3577 flags |= root->fs_info->avail_metadata_alloc_bits;
3578 } while (read_seqretry(&root->fs_info->profiles_lock, seq));
3579
3580 return btrfs_reduce_alloc_profile(root, flags);
3581 }
3582
3583 u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
3584 {
3585 u64 flags;
3586 u64 ret;
3587
3588 if (data)
3589 flags = BTRFS_BLOCK_GROUP_DATA;
3590 else if (root == root->fs_info->chunk_root)
3591 flags = BTRFS_BLOCK_GROUP_SYSTEM;
3592 else
3593 flags = BTRFS_BLOCK_GROUP_METADATA;
3594
3595 ret = get_alloc_profile(root, flags);
3596 return ret;
3597 }
3598
3599 /*
3600 * This will check the space that the inode allocates from to make sure we have
3601 * enough space for bytes.
3602 */
3603 int btrfs_check_data_free_space(struct inode *inode, u64 bytes)
3604 {
3605 struct btrfs_space_info *data_sinfo;
3606 struct btrfs_root *root = BTRFS_I(inode)->root;
3607 struct btrfs_fs_info *fs_info = root->fs_info;
3608 u64 used;
3609 int ret = 0, committed = 0, alloc_chunk = 1;
3610
3611 /* make sure bytes are sectorsize aligned */
3612 bytes = ALIGN(bytes, root->sectorsize);
3613
3614 if (btrfs_is_free_space_inode(inode)) {
3615 committed = 1;
3616 ASSERT(current->journal_info);
3617 }
3618
3619 data_sinfo = fs_info->data_sinfo;
3620 if (!data_sinfo)
3621 goto alloc;
3622
3623 again:
3624 /* make sure we have enough space to handle the data first */
3625 spin_lock(&data_sinfo->lock);
3626 used = data_sinfo->bytes_used + data_sinfo->bytes_reserved +
3627 data_sinfo->bytes_pinned + data_sinfo->bytes_readonly +
3628 data_sinfo->bytes_may_use;
3629
3630 if (used + bytes > data_sinfo->total_bytes) {
3631 struct btrfs_trans_handle *trans;
3632
3633 /*
3634 * if we don't have enough free bytes in this space then we need
3635 * to alloc a new chunk.
3636 */
3637 if (!data_sinfo->full && alloc_chunk) {
3638 u64 alloc_target;
3639
3640 data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
3641 spin_unlock(&data_sinfo->lock);
3642 alloc:
3643 alloc_target = btrfs_get_alloc_profile(root, 1);
3644 /*
3645 * It is ugly that we don't call nolock join
3646 * transaction for the free space inode case here.
3647 * But it is safe because we only do the data space
3648 * reservation for the free space cache in the
3649 * transaction context, the common join transaction
3650 * just increase the counter of the current transaction
3651 * handler, doesn't try to acquire the trans_lock of
3652 * the fs.
3653 */
3654 trans = btrfs_join_transaction(root);
3655 if (IS_ERR(trans))
3656 return PTR_ERR(trans);
3657
3658 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
3659 alloc_target,
3660 CHUNK_ALLOC_NO_FORCE);
3661 btrfs_end_transaction(trans, root);
3662 if (ret < 0) {
3663 if (ret != -ENOSPC)
3664 return ret;
3665 else
3666 goto commit_trans;
3667 }
3668
3669 if (!data_sinfo)
3670 data_sinfo = fs_info->data_sinfo;
3671
3672 goto again;
3673 }
3674
3675 /*
3676 * If we don't have enough pinned space to deal with this
3677 * allocation don't bother committing the transaction.
3678 */
3679 if (percpu_counter_compare(&data_sinfo->total_bytes_pinned,
3680 bytes) < 0)
3681 committed = 1;
3682 spin_unlock(&data_sinfo->lock);
3683
3684 /* commit the current transaction and try again */
3685 commit_trans:
3686 if (!committed &&
3687 !atomic_read(&root->fs_info->open_ioctl_trans)) {
3688 committed = 1;
3689
3690 trans = btrfs_join_transaction(root);
3691 if (IS_ERR(trans))
3692 return PTR_ERR(trans);
3693 ret = btrfs_commit_transaction(trans, root);
3694 if (ret)
3695 return ret;
3696 goto again;
3697 }
3698
3699 trace_btrfs_space_reservation(root->fs_info,
3700 "space_info:enospc",
3701 data_sinfo->flags, bytes, 1);
3702 return -ENOSPC;
3703 }
3704 data_sinfo->bytes_may_use += bytes;
3705 trace_btrfs_space_reservation(root->fs_info, "space_info",
3706 data_sinfo->flags, bytes, 1);
3707 spin_unlock(&data_sinfo->lock);
3708
3709 return 0;
3710 }
3711
3712 /*
3713 * Called if we need to clear a data reservation for this inode.
3714 */
3715 void btrfs_free_reserved_data_space(struct inode *inode, u64 bytes)
3716 {
3717 struct btrfs_root *root = BTRFS_I(inode)->root;
3718 struct btrfs_space_info *data_sinfo;
3719
3720 /* make sure bytes are sectorsize aligned */
3721 bytes = ALIGN(bytes, root->sectorsize);
3722
3723 data_sinfo = root->fs_info->data_sinfo;
3724 spin_lock(&data_sinfo->lock);
3725 WARN_ON(data_sinfo->bytes_may_use < bytes);
3726 data_sinfo->bytes_may_use -= bytes;
3727 trace_btrfs_space_reservation(root->fs_info, "space_info",
3728 data_sinfo->flags, bytes, 0);
3729 spin_unlock(&data_sinfo->lock);
3730 }
3731
3732 static void force_metadata_allocation(struct btrfs_fs_info *info)
3733 {
3734 struct list_head *head = &info->space_info;
3735 struct btrfs_space_info *found;
3736
3737 rcu_read_lock();
3738 list_for_each_entry_rcu(found, head, list) {
3739 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3740 found->force_alloc = CHUNK_ALLOC_FORCE;
3741 }
3742 rcu_read_unlock();
3743 }
3744
3745 static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
3746 {
3747 return (global->size << 1);
3748 }
3749
3750 static int should_alloc_chunk(struct btrfs_root *root,
3751 struct btrfs_space_info *sinfo, int force)
3752 {
3753 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
3754 u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
3755 u64 num_allocated = sinfo->bytes_used + sinfo->bytes_reserved;
3756 u64 thresh;
3757
3758 if (force == CHUNK_ALLOC_FORCE)
3759 return 1;
3760
3761 /*
3762 * We need to take into account the global rsv because for all intents
3763 * and purposes it's used space. Don't worry about locking the
3764 * global_rsv, it doesn't change except when the transaction commits.
3765 */
3766 if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
3767 num_allocated += calc_global_rsv_need_space(global_rsv);
3768
3769 /*
3770 * in limited mode, we want to have some free space up to
3771 * about 1% of the FS size.
3772 */
3773 if (force == CHUNK_ALLOC_LIMITED) {
3774 thresh = btrfs_super_total_bytes(root->fs_info->super_copy);
3775 thresh = max_t(u64, 64 * 1024 * 1024,
3776 div_factor_fine(thresh, 1));
3777
3778 if (num_bytes - num_allocated < thresh)
3779 return 1;
3780 }
3781
3782 if (num_allocated + 2 * 1024 * 1024 < div_factor(num_bytes, 8))
3783 return 0;
3784 return 1;
3785 }
3786
3787 static u64 get_system_chunk_thresh(struct btrfs_root *root, u64 type)
3788 {
3789 u64 num_dev;
3790
3791 if (type & (BTRFS_BLOCK_GROUP_RAID10 |
3792 BTRFS_BLOCK_GROUP_RAID0 |
3793 BTRFS_BLOCK_GROUP_RAID5 |
3794 BTRFS_BLOCK_GROUP_RAID6))
3795 num_dev = root->fs_info->fs_devices->rw_devices;
3796 else if (type & BTRFS_BLOCK_GROUP_RAID1)
3797 num_dev = 2;
3798 else
3799 num_dev = 1; /* DUP or single */
3800
3801 /* metadata for updaing devices and chunk tree */
3802 return btrfs_calc_trans_metadata_size(root, num_dev + 1);
3803 }
3804
3805 static void check_system_chunk(struct btrfs_trans_handle *trans,
3806 struct btrfs_root *root, u64 type)
3807 {
3808 struct btrfs_space_info *info;
3809 u64 left;
3810 u64 thresh;
3811
3812 info = __find_space_info(root->fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3813 spin_lock(&info->lock);
3814 left = info->total_bytes - info->bytes_used - info->bytes_pinned -
3815 info->bytes_reserved - info->bytes_readonly;
3816 spin_unlock(&info->lock);
3817
3818 thresh = get_system_chunk_thresh(root, type);
3819 if (left < thresh && btrfs_test_opt(root, ENOSPC_DEBUG)) {
3820 btrfs_info(root->fs_info, "left=%llu, need=%llu, flags=%llu",
3821 left, thresh, type);
3822 dump_space_info(info, 0, 0);
3823 }
3824
3825 if (left < thresh) {
3826 u64 flags;
3827
3828 flags = btrfs_get_alloc_profile(root->fs_info->chunk_root, 0);
3829 btrfs_alloc_chunk(trans, root, flags);
3830 }
3831 }
3832
3833 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
3834 struct btrfs_root *extent_root, u64 flags, int force)
3835 {
3836 struct btrfs_space_info *space_info;
3837 struct btrfs_fs_info *fs_info = extent_root->fs_info;
3838 int wait_for_alloc = 0;
3839 int ret = 0;
3840
3841 /* Don't re-enter if we're already allocating a chunk */
3842 if (trans->allocating_chunk)
3843 return -ENOSPC;
3844
3845 space_info = __find_space_info(extent_root->fs_info, flags);
3846 if (!space_info) {
3847 ret = update_space_info(extent_root->fs_info, flags,
3848 0, 0, &space_info);
3849 BUG_ON(ret); /* -ENOMEM */
3850 }
3851 BUG_ON(!space_info); /* Logic error */
3852
3853 again:
3854 spin_lock(&space_info->lock);
3855 if (force < space_info->force_alloc)
3856 force = space_info->force_alloc;
3857 if (space_info->full) {
3858 if (should_alloc_chunk(extent_root, space_info, force))
3859 ret = -ENOSPC;
3860 else
3861 ret = 0;
3862 spin_unlock(&space_info->lock);
3863 return ret;
3864 }
3865
3866 if (!should_alloc_chunk(extent_root, space_info, force)) {
3867 spin_unlock(&space_info->lock);
3868 return 0;
3869 } else if (space_info->chunk_alloc) {
3870 wait_for_alloc = 1;
3871 } else {
3872 space_info->chunk_alloc = 1;
3873 }
3874
3875 spin_unlock(&space_info->lock);
3876
3877 mutex_lock(&fs_info->chunk_mutex);
3878
3879 /*
3880 * The chunk_mutex is held throughout the entirety of a chunk
3881 * allocation, so once we've acquired the chunk_mutex we know that the
3882 * other guy is done and we need to recheck and see if we should
3883 * allocate.
3884 */
3885 if (wait_for_alloc) {
3886 mutex_unlock(&fs_info->chunk_mutex);
3887 wait_for_alloc = 0;
3888 goto again;
3889 }
3890
3891 trans->allocating_chunk = true;
3892
3893 /*
3894 * If we have mixed data/metadata chunks we want to make sure we keep
3895 * allocating mixed chunks instead of individual chunks.
3896 */
3897 if (btrfs_mixed_space_info(space_info))
3898 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3899
3900 /*
3901 * if we're doing a data chunk, go ahead and make sure that
3902 * we keep a reasonable number of metadata chunks allocated in the
3903 * FS as well.
3904 */
3905 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3906 fs_info->data_chunk_allocations++;
3907 if (!(fs_info->data_chunk_allocations %
3908 fs_info->metadata_ratio))
3909 force_metadata_allocation(fs_info);
3910 }
3911
3912 /*
3913 * Check if we have enough space in SYSTEM chunk because we may need
3914 * to update devices.
3915 */
3916 check_system_chunk(trans, extent_root, flags);
3917
3918 ret = btrfs_alloc_chunk(trans, extent_root, flags);
3919 trans->allocating_chunk = false;
3920
3921 spin_lock(&space_info->lock);
3922 if (ret < 0 && ret != -ENOSPC)
3923 goto out;
3924 if (ret)
3925 space_info->full = 1;
3926 else
3927 ret = 1;
3928
3929 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3930 out:
3931 space_info->chunk_alloc = 0;
3932 spin_unlock(&space_info->lock);
3933 mutex_unlock(&fs_info->chunk_mutex);
3934 return ret;
3935 }
3936
3937 static int can_overcommit(struct btrfs_root *root,
3938 struct btrfs_space_info *space_info, u64 bytes,
3939 enum btrfs_reserve_flush_enum flush)
3940 {
3941 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
3942 u64 profile = btrfs_get_alloc_profile(root, 0);
3943 u64 space_size;
3944 u64 avail;
3945 u64 used;
3946
3947 used = space_info->bytes_used + space_info->bytes_reserved +
3948 space_info->bytes_pinned + space_info->bytes_readonly;
3949
3950 /*
3951 * We only want to allow over committing if we have lots of actual space
3952 * free, but if we don't have enough space to handle the global reserve
3953 * space then we could end up having a real enospc problem when trying
3954 * to allocate a chunk or some other such important allocation.
3955 */
3956 spin_lock(&global_rsv->lock);
3957 space_size = calc_global_rsv_need_space(global_rsv);
3958 spin_unlock(&global_rsv->lock);
3959 if (used + space_size >= space_info->total_bytes)
3960 return 0;
3961
3962 used += space_info->bytes_may_use;
3963
3964 spin_lock(&root->fs_info->free_chunk_lock);
3965 avail = root->fs_info->free_chunk_space;
3966 spin_unlock(&root->fs_info->free_chunk_lock);
3967
3968 /*
3969 * If we have dup, raid1 or raid10 then only half of the free
3970 * space is actually useable. For raid56, the space info used
3971 * doesn't include the parity drive, so we don't have to
3972 * change the math
3973 */
3974 if (profile & (BTRFS_BLOCK_GROUP_DUP |
3975 BTRFS_BLOCK_GROUP_RAID1 |
3976 BTRFS_BLOCK_GROUP_RAID10))
3977 avail >>= 1;
3978
3979 /*
3980 * If we aren't flushing all things, let us overcommit up to
3981 * 1/2th of the space. If we can flush, don't let us overcommit
3982 * too much, let it overcommit up to 1/8 of the space.
3983 */
3984 if (flush == BTRFS_RESERVE_FLUSH_ALL)
3985 avail >>= 3;
3986 else
3987 avail >>= 1;
3988
3989 if (used + bytes < space_info->total_bytes + avail)
3990 return 1;
3991 return 0;
3992 }
3993
3994 static void btrfs_writeback_inodes_sb_nr(struct btrfs_root *root,
3995 unsigned long nr_pages, int nr_items)
3996 {
3997 struct super_block *sb = root->fs_info->sb;
3998
3999 if (down_read_trylock(&sb->s_umount)) {
4000 writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
4001 up_read(&sb->s_umount);
4002 } else {
4003 /*
4004 * We needn't worry the filesystem going from r/w to r/o though
4005 * we don't acquire ->s_umount mutex, because the filesystem
4006 * should guarantee the delalloc inodes list be empty after
4007 * the filesystem is readonly(all dirty pages are written to
4008 * the disk).
4009 */
4010 btrfs_start_delalloc_roots(root->fs_info, 0, nr_items);
4011 if (!current->journal_info)
4012 btrfs_wait_ordered_roots(root->fs_info, nr_items);
4013 }
4014 }
4015
4016 static inline int calc_reclaim_items_nr(struct btrfs_root *root, u64 to_reclaim)
4017 {
4018 u64 bytes;
4019 int nr;
4020
4021 bytes = btrfs_calc_trans_metadata_size(root, 1);
4022 nr = (int)div64_u64(to_reclaim, bytes);
4023 if (!nr)
4024 nr = 1;
4025 return nr;
4026 }
4027
4028 #define EXTENT_SIZE_PER_ITEM (256 * 1024)
4029
4030 /*
4031 * shrink metadata reservation for delalloc
4032 */
4033 static void shrink_delalloc(struct btrfs_root *root, u64 to_reclaim, u64 orig,
4034 bool wait_ordered)
4035 {
4036 struct btrfs_block_rsv *block_rsv;
4037 struct btrfs_space_info *space_info;
4038 struct btrfs_trans_handle *trans;
4039 u64 delalloc_bytes;
4040 u64 max_reclaim;
4041 long time_left;
4042 unsigned long nr_pages;
4043 int loops;
4044 int items;
4045 enum btrfs_reserve_flush_enum flush;
4046
4047 /* Calc the number of the pages we need flush for space reservation */
4048 items = calc_reclaim_items_nr(root, to_reclaim);
4049 to_reclaim = items * EXTENT_SIZE_PER_ITEM;
4050
4051 trans = (struct btrfs_trans_handle *)current->journal_info;
4052 block_rsv = &root->fs_info->delalloc_block_rsv;
4053 space_info = block_rsv->space_info;
4054
4055 delalloc_bytes = percpu_counter_sum_positive(
4056 &root->fs_info->delalloc_bytes);
4057 if (delalloc_bytes == 0) {
4058 if (trans)
4059 return;
4060 if (wait_ordered)
4061 btrfs_wait_ordered_roots(root->fs_info, items);
4062 return;
4063 }
4064
4065 loops = 0;
4066 while (delalloc_bytes && loops < 3) {
4067 max_reclaim = min(delalloc_bytes, to_reclaim);
4068 nr_pages = max_reclaim >> PAGE_CACHE_SHIFT;
4069 btrfs_writeback_inodes_sb_nr(root, nr_pages, items);
4070 /*
4071 * We need to wait for the async pages to actually start before
4072 * we do anything.
4073 */
4074 max_reclaim = atomic_read(&root->fs_info->async_delalloc_pages);
4075 if (!max_reclaim)
4076 goto skip_async;
4077
4078 if (max_reclaim <= nr_pages)
4079 max_reclaim = 0;
4080 else
4081 max_reclaim -= nr_pages;
4082
4083 wait_event(root->fs_info->async_submit_wait,
4084 atomic_read(&root->fs_info->async_delalloc_pages) <=
4085 (int)max_reclaim);
4086 skip_async:
4087 if (!trans)
4088 flush = BTRFS_RESERVE_FLUSH_ALL;
4089 else
4090 flush = BTRFS_RESERVE_NO_FLUSH;
4091 spin_lock(&space_info->lock);
4092 if (can_overcommit(root, space_info, orig, flush)) {
4093 spin_unlock(&space_info->lock);
4094 break;
4095 }
4096 spin_unlock(&space_info->lock);
4097
4098 loops++;
4099 if (wait_ordered && !trans) {
4100 btrfs_wait_ordered_roots(root->fs_info, items);
4101 } else {
4102 time_left = schedule_timeout_killable(1);
4103 if (time_left)
4104 break;
4105 }
4106 delalloc_bytes = percpu_counter_sum_positive(
4107 &root->fs_info->delalloc_bytes);
4108 }
4109 }
4110
4111 /**
4112 * maybe_commit_transaction - possibly commit the transaction if its ok to
4113 * @root - the root we're allocating for
4114 * @bytes - the number of bytes we want to reserve
4115 * @force - force the commit
4116 *
4117 * This will check to make sure that committing the transaction will actually
4118 * get us somewhere and then commit the transaction if it does. Otherwise it
4119 * will return -ENOSPC.
4120 */
4121 static int may_commit_transaction(struct btrfs_root *root,
4122 struct btrfs_space_info *space_info,
4123 u64 bytes, int force)
4124 {
4125 struct btrfs_block_rsv *delayed_rsv = &root->fs_info->delayed_block_rsv;
4126 struct btrfs_trans_handle *trans;
4127
4128 trans = (struct btrfs_trans_handle *)current->journal_info;
4129 if (trans)
4130 return -EAGAIN;
4131
4132 if (force)
4133 goto commit;
4134
4135 /* See if there is enough pinned space to make this reservation */
4136 if (percpu_counter_compare(&space_info->total_bytes_pinned,
4137 bytes) >= 0)
4138 goto commit;
4139
4140 /*
4141 * See if there is some space in the delayed insertion reservation for
4142 * this reservation.
4143 */
4144 if (space_info != delayed_rsv->space_info)
4145 return -ENOSPC;
4146
4147 spin_lock(&delayed_rsv->lock);
4148 if (percpu_counter_compare(&space_info->total_bytes_pinned,
4149 bytes - delayed_rsv->size) >= 0) {
4150 spin_unlock(&delayed_rsv->lock);
4151 return -ENOSPC;
4152 }
4153 spin_unlock(&delayed_rsv->lock);
4154
4155 commit:
4156 trans = btrfs_join_transaction(root);
4157 if (IS_ERR(trans))
4158 return -ENOSPC;
4159
4160 return btrfs_commit_transaction(trans, root);
4161 }
4162
4163 enum flush_state {
4164 FLUSH_DELAYED_ITEMS_NR = 1,
4165 FLUSH_DELAYED_ITEMS = 2,
4166 FLUSH_DELALLOC = 3,
4167 FLUSH_DELALLOC_WAIT = 4,
4168 ALLOC_CHUNK = 5,
4169 COMMIT_TRANS = 6,
4170 };
4171
4172 static int flush_space(struct btrfs_root *root,
4173 struct btrfs_space_info *space_info, u64 num_bytes,
4174 u64 orig_bytes, int state)
4175 {
4176 struct btrfs_trans_handle *trans;
4177 int nr;
4178 int ret = 0;
4179
4180 switch (state) {
4181 case FLUSH_DELAYED_ITEMS_NR:
4182 case FLUSH_DELAYED_ITEMS:
4183 if (state == FLUSH_DELAYED_ITEMS_NR)
4184 nr = calc_reclaim_items_nr(root, num_bytes) * 2;
4185 else
4186 nr = -1;
4187
4188 trans = btrfs_join_transaction(root);
4189 if (IS_ERR(trans)) {
4190 ret = PTR_ERR(trans);
4191 break;
4192 }
4193 ret = btrfs_run_delayed_items_nr(trans, root, nr);
4194 btrfs_end_transaction(trans, root);
4195 break;
4196 case FLUSH_DELALLOC:
4197 case FLUSH_DELALLOC_WAIT:
4198 shrink_delalloc(root, num_bytes * 2, orig_bytes,
4199 state == FLUSH_DELALLOC_WAIT);
4200 break;
4201 case ALLOC_CHUNK:
4202 trans = btrfs_join_transaction(root);
4203 if (IS_ERR(trans)) {
4204 ret = PTR_ERR(trans);
4205 break;
4206 }
4207 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
4208 btrfs_get_alloc_profile(root, 0),
4209 CHUNK_ALLOC_NO_FORCE);
4210 btrfs_end_transaction(trans, root);
4211 if (ret == -ENOSPC)
4212 ret = 0;
4213 break;
4214 case COMMIT_TRANS:
4215 ret = may_commit_transaction(root, space_info, orig_bytes, 0);
4216 break;
4217 default:
4218 ret = -ENOSPC;
4219 break;
4220 }
4221
4222 return ret;
4223 }
4224
4225 static inline u64
4226 btrfs_calc_reclaim_metadata_size(struct btrfs_root *root,
4227 struct btrfs_space_info *space_info)
4228 {
4229 u64 used;
4230 u64 expected;
4231 u64 to_reclaim;
4232
4233 to_reclaim = min_t(u64, num_online_cpus() * 1024 * 1024,
4234 16 * 1024 * 1024);
4235 spin_lock(&space_info->lock);
4236 if (can_overcommit(root, space_info, to_reclaim,
4237 BTRFS_RESERVE_FLUSH_ALL)) {
4238 to_reclaim = 0;
4239 goto out;
4240 }
4241
4242 used = space_info->bytes_used + space_info->bytes_reserved +
4243 space_info->bytes_pinned + space_info->bytes_readonly +
4244 space_info->bytes_may_use;
4245 if (can_overcommit(root, space_info, 1024 * 1024,
4246 BTRFS_RESERVE_FLUSH_ALL))
4247 expected = div_factor_fine(space_info->total_bytes, 95);
4248 else
4249 expected = div_factor_fine(space_info->total_bytes, 90);
4250
4251 if (used > expected)
4252 to_reclaim = used - expected;
4253 else
4254 to_reclaim = 0;
4255 to_reclaim = min(to_reclaim, space_info->bytes_may_use +
4256 space_info->bytes_reserved);
4257 out:
4258 spin_unlock(&space_info->lock);
4259
4260 return to_reclaim;
4261 }
4262
4263 static inline int need_do_async_reclaim(struct btrfs_space_info *space_info,
4264 struct btrfs_fs_info *fs_info, u64 used)
4265 {
4266 return (used >= div_factor_fine(space_info->total_bytes, 98) &&
4267 !btrfs_fs_closing(fs_info) &&
4268 !test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
4269 }
4270
4271 static int btrfs_need_do_async_reclaim(struct btrfs_space_info *space_info,
4272 struct btrfs_fs_info *fs_info)
4273 {
4274 u64 used;
4275
4276 spin_lock(&space_info->lock);
4277 used = space_info->bytes_used + space_info->bytes_reserved +
4278 space_info->bytes_pinned + space_info->bytes_readonly +
4279 space_info->bytes_may_use;
4280 if (need_do_async_reclaim(space_info, fs_info, used)) {
4281 spin_unlock(&space_info->lock);
4282 return 1;
4283 }
4284 spin_unlock(&space_info->lock);
4285
4286 return 0;
4287 }
4288
4289 static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
4290 {
4291 struct btrfs_fs_info *fs_info;
4292 struct btrfs_space_info *space_info;
4293 u64 to_reclaim;
4294 int flush_state;
4295
4296 fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
4297 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4298
4299 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
4300 space_info);
4301 if (!to_reclaim)
4302 return;
4303
4304 flush_state = FLUSH_DELAYED_ITEMS_NR;
4305 do {
4306 flush_space(fs_info->fs_root, space_info, to_reclaim,
4307 to_reclaim, flush_state);
4308 flush_state++;
4309 if (!btrfs_need_do_async_reclaim(space_info, fs_info))
4310 return;
4311 } while (flush_state <= COMMIT_TRANS);
4312
4313 if (btrfs_need_do_async_reclaim(space_info, fs_info))
4314 queue_work(system_unbound_wq, work);
4315 }
4316
4317 void btrfs_init_async_reclaim_work(struct work_struct *work)
4318 {
4319 INIT_WORK(work, btrfs_async_reclaim_metadata_space);
4320 }
4321
4322 /**
4323 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
4324 * @root - the root we're allocating for
4325 * @block_rsv - the block_rsv we're allocating for
4326 * @orig_bytes - the number of bytes we want
4327 * @flush - whether or not we can flush to make our reservation
4328 *
4329 * This will reserve orgi_bytes number of bytes from the space info associated
4330 * with the block_rsv. If there is not enough space it will make an attempt to
4331 * flush out space to make room. It will do this by flushing delalloc if
4332 * possible or committing the transaction. If flush is 0 then no attempts to
4333 * regain reservations will be made and this will fail if there is not enough
4334 * space already.
4335 */
4336 static int reserve_metadata_bytes(struct btrfs_root *root,
4337 struct btrfs_block_rsv *block_rsv,
4338 u64 orig_bytes,
4339 enum btrfs_reserve_flush_enum flush)
4340 {
4341 struct btrfs_space_info *space_info = block_rsv->space_info;
4342 u64 used;
4343 u64 num_bytes = orig_bytes;
4344 int flush_state = FLUSH_DELAYED_ITEMS_NR;
4345 int ret = 0;
4346 bool flushing = false;
4347
4348 again:
4349 ret = 0;
4350 spin_lock(&space_info->lock);
4351 /*
4352 * We only want to wait if somebody other than us is flushing and we
4353 * are actually allowed to flush all things.
4354 */
4355 while (flush == BTRFS_RESERVE_FLUSH_ALL && !flushing &&
4356 space_info->flush) {
4357 spin_unlock(&space_info->lock);
4358 /*
4359 * If we have a trans handle we can't wait because the flusher
4360 * may have to commit the transaction, which would mean we would
4361 * deadlock since we are waiting for the flusher to finish, but
4362 * hold the current transaction open.
4363 */
4364 if (current->journal_info)
4365 return -EAGAIN;
4366 ret = wait_event_killable(space_info->wait, !space_info->flush);
4367 /* Must have been killed, return */
4368 if (ret)
4369 return -EINTR;
4370
4371 spin_lock(&space_info->lock);
4372 }
4373
4374 ret = -ENOSPC;
4375 used = space_info->bytes_used + space_info->bytes_reserved +
4376 space_info->bytes_pinned + space_info->bytes_readonly +
4377 space_info->bytes_may_use;
4378
4379 /*
4380 * The idea here is that we've not already over-reserved the block group
4381 * then we can go ahead and save our reservation first and then start
4382 * flushing if we need to. Otherwise if we've already overcommitted
4383 * lets start flushing stuff first and then come back and try to make
4384 * our reservation.
4385 */
4386 if (used <= space_info->total_bytes) {
4387 if (used + orig_bytes <= space_info->total_bytes) {
4388 space_info->bytes_may_use += orig_bytes;
4389 trace_btrfs_space_reservation(root->fs_info,
4390 "space_info", space_info->flags, orig_bytes, 1);
4391 ret = 0;
4392 } else {
4393 /*
4394 * Ok set num_bytes to orig_bytes since we aren't
4395 * overocmmitted, this way we only try and reclaim what
4396 * we need.
4397 */
4398 num_bytes = orig_bytes;
4399 }
4400 } else {
4401 /*
4402 * Ok we're over committed, set num_bytes to the overcommitted
4403 * amount plus the amount of bytes that we need for this
4404 * reservation.
4405 */
4406 num_bytes = used - space_info->total_bytes +
4407 (orig_bytes * 2);
4408 }
4409
4410 if (ret && can_overcommit(root, space_info, orig_bytes, flush)) {
4411 space_info->bytes_may_use += orig_bytes;
4412 trace_btrfs_space_reservation(root->fs_info, "space_info",
4413 space_info->flags, orig_bytes,
4414 1);
4415 ret = 0;
4416 }
4417
4418 /*
4419 * Couldn't make our reservation, save our place so while we're trying
4420 * to reclaim space we can actually use it instead of somebody else
4421 * stealing it from us.
4422 *
4423 * We make the other tasks wait for the flush only when we can flush
4424 * all things.
4425 */
4426 if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
4427 flushing = true;
4428 space_info->flush = 1;
4429 } else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
4430 used += orig_bytes;
4431 if (need_do_async_reclaim(space_info, root->fs_info, used) &&
4432 !work_busy(&root->fs_info->async_reclaim_work))
4433 queue_work(system_unbound_wq,
4434 &root->fs_info->async_reclaim_work);
4435 }
4436 spin_unlock(&space_info->lock);
4437
4438 if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
4439 goto out;
4440
4441 ret = flush_space(root, space_info, num_bytes, orig_bytes,
4442 flush_state);
4443 flush_state++;
4444
4445 /*
4446 * If we are FLUSH_LIMIT, we can not flush delalloc, or the deadlock
4447 * would happen. So skip delalloc flush.
4448 */
4449 if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
4450 (flush_state == FLUSH_DELALLOC ||
4451 flush_state == FLUSH_DELALLOC_WAIT))
4452 flush_state = ALLOC_CHUNK;
4453
4454 if (!ret)
4455 goto again;
4456 else if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
4457 flush_state < COMMIT_TRANS)
4458 goto again;
4459 else if (flush == BTRFS_RESERVE_FLUSH_ALL &&
4460 flush_state <= COMMIT_TRANS)
4461 goto again;
4462
4463 out:
4464 if (ret == -ENOSPC &&
4465 unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
4466 struct btrfs_block_rsv *global_rsv =
4467 &root->fs_info->global_block_rsv;
4468
4469 if (block_rsv != global_rsv &&
4470 !block_rsv_use_bytes(global_rsv, orig_bytes))
4471 ret = 0;
4472 }
4473 if (ret == -ENOSPC)
4474 trace_btrfs_space_reservation(root->fs_info,
4475 "space_info:enospc",
4476 space_info->flags, orig_bytes, 1);
4477 if (flushing) {
4478 spin_lock(&space_info->lock);
4479 space_info->flush = 0;
4480 wake_up_all(&space_info->wait);
4481 spin_unlock(&space_info->lock);
4482 }
4483 return ret;
4484 }
4485
4486 static struct btrfs_block_rsv *get_block_rsv(
4487 const struct btrfs_trans_handle *trans,
4488 const struct btrfs_root *root)
4489 {
4490 struct btrfs_block_rsv *block_rsv = NULL;
4491
4492 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4493 block_rsv = trans->block_rsv;
4494
4495 if (root == root->fs_info->csum_root && trans->adding_csums)
4496 block_rsv = trans->block_rsv;
4497
4498 if (root == root->fs_info->uuid_root)
4499 block_rsv = trans->block_rsv;
4500
4501 if (!block_rsv)
4502 block_rsv = root->block_rsv;
4503
4504 if (!block_rsv)
4505 block_rsv = &root->fs_info->empty_block_rsv;
4506
4507 return block_rsv;
4508 }
4509
4510 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
4511 u64 num_bytes)
4512 {
4513 int ret = -ENOSPC;
4514 spin_lock(&block_rsv->lock);
4515 if (block_rsv->reserved >= num_bytes) {
4516 block_rsv->reserved -= num_bytes;
4517 if (block_rsv->reserved < block_rsv->size)
4518 block_rsv->full = 0;
4519 ret = 0;
4520 }
4521 spin_unlock(&block_rsv->lock);
4522 return ret;
4523 }
4524
4525 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
4526 u64 num_bytes, int update_size)
4527 {
4528 spin_lock(&block_rsv->lock);
4529 block_rsv->reserved += num_bytes;
4530 if (update_size)
4531 block_rsv->size += num_bytes;
4532 else if (block_rsv->reserved >= block_rsv->size)
4533 block_rsv->full = 1;
4534 spin_unlock(&block_rsv->lock);
4535 }
4536
4537 int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
4538 struct btrfs_block_rsv *dest, u64 num_bytes,
4539 int min_factor)
4540 {
4541 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4542 u64 min_bytes;
4543
4544 if (global_rsv->space_info != dest->space_info)
4545 return -ENOSPC;
4546
4547 spin_lock(&global_rsv->lock);
4548 min_bytes = div_factor(global_rsv->size, min_factor);
4549 if (global_rsv->reserved < min_bytes + num_bytes) {
4550 spin_unlock(&global_rsv->lock);
4551 return -ENOSPC;
4552 }
4553 global_rsv->reserved -= num_bytes;
4554 if (global_rsv->reserved < global_rsv->size)
4555 global_rsv->full = 0;
4556 spin_unlock(&global_rsv->lock);
4557
4558 block_rsv_add_bytes(dest, num_bytes, 1);
4559 return 0;
4560 }
4561
4562 static void block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
4563 struct btrfs_block_rsv *block_rsv,
4564 struct btrfs_block_rsv *dest, u64 num_bytes)
4565 {
4566 struct btrfs_space_info *space_info = block_rsv->space_info;
4567
4568 spin_lock(&block_rsv->lock);
4569 if (num_bytes == (u64)-1)
4570 num_bytes = block_rsv->size;
4571 block_rsv->size -= num_bytes;
4572 if (block_rsv->reserved >= block_rsv->size) {
4573 num_bytes = block_rsv->reserved - block_rsv->size;
4574 block_rsv->reserved = block_rsv->size;
4575 block_rsv->full = 1;
4576 } else {
4577 num_bytes = 0;
4578 }
4579 spin_unlock(&block_rsv->lock);
4580
4581 if (num_bytes > 0) {
4582 if (dest) {
4583 spin_lock(&dest->lock);
4584 if (!dest->full) {
4585 u64 bytes_to_add;
4586
4587 bytes_to_add = dest->size - dest->reserved;
4588 bytes_to_add = min(num_bytes, bytes_to_add);
4589 dest->reserved += bytes_to_add;
4590 if (dest->reserved >= dest->size)
4591 dest->full = 1;
4592 num_bytes -= bytes_to_add;
4593 }
4594 spin_unlock(&dest->lock);
4595 }
4596 if (num_bytes) {
4597 spin_lock(&space_info->lock);
4598 space_info->bytes_may_use -= num_bytes;
4599 trace_btrfs_space_reservation(fs_info, "space_info",
4600 space_info->flags, num_bytes, 0);
4601 spin_unlock(&space_info->lock);
4602 }
4603 }
4604 }
4605
4606 static int block_rsv_migrate_bytes(struct btrfs_block_rsv *src,
4607 struct btrfs_block_rsv *dst, u64 num_bytes)
4608 {
4609 int ret;
4610
4611 ret = block_rsv_use_bytes(src, num_bytes);
4612 if (ret)
4613 return ret;
4614
4615 block_rsv_add_bytes(dst, num_bytes, 1);
4616 return 0;
4617 }
4618
4619 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
4620 {
4621 memset(rsv, 0, sizeof(*rsv));
4622 spin_lock_init(&rsv->lock);
4623 rsv->type = type;
4624 }
4625
4626 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_root *root,
4627 unsigned short type)
4628 {
4629 struct btrfs_block_rsv *block_rsv;
4630 struct btrfs_fs_info *fs_info = root->fs_info;
4631
4632 block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
4633 if (!block_rsv)
4634 return NULL;
4635
4636 btrfs_init_block_rsv(block_rsv, type);
4637 block_rsv->space_info = __find_space_info(fs_info,
4638 BTRFS_BLOCK_GROUP_METADATA);
4639 return block_rsv;
4640 }
4641
4642 void btrfs_free_block_rsv(struct btrfs_root *root,
4643 struct btrfs_block_rsv *rsv)
4644 {
4645 if (!rsv)
4646 return;
4647 btrfs_block_rsv_release(root, rsv, (u64)-1);
4648 kfree(rsv);
4649 }
4650
4651 int btrfs_block_rsv_add(struct btrfs_root *root,
4652 struct btrfs_block_rsv *block_rsv, u64 num_bytes,
4653 enum btrfs_reserve_flush_enum flush)
4654 {
4655 int ret;
4656
4657 if (num_bytes == 0)
4658 return 0;
4659
4660 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
4661 if (!ret) {
4662 block_rsv_add_bytes(block_rsv, num_bytes, 1);
4663 return 0;
4664 }
4665
4666 return ret;
4667 }
4668
4669 int btrfs_block_rsv_check(struct btrfs_root *root,
4670 struct btrfs_block_rsv *block_rsv, int min_factor)
4671 {
4672 u64 num_bytes = 0;
4673 int ret = -ENOSPC;
4674
4675 if (!block_rsv)
4676 return 0;
4677
4678 spin_lock(&block_rsv->lock);
4679 num_bytes = div_factor(block_rsv->size, min_factor);
4680 if (block_rsv->reserved >= num_bytes)
4681 ret = 0;
4682 spin_unlock(&block_rsv->lock);
4683
4684 return ret;
4685 }
4686
4687 int btrfs_block_rsv_refill(struct btrfs_root *root,
4688 struct btrfs_block_rsv *block_rsv, u64 min_reserved,
4689 enum btrfs_reserve_flush_enum flush)
4690 {
4691 u64 num_bytes = 0;
4692 int ret = -ENOSPC;
4693
4694 if (!block_rsv)
4695 return 0;
4696
4697 spin_lock(&block_rsv->lock);
4698 num_bytes = min_reserved;
4699 if (block_rsv->reserved >= num_bytes)
4700 ret = 0;
4701 else
4702 num_bytes -= block_rsv->reserved;
4703 spin_unlock(&block_rsv->lock);
4704
4705 if (!ret)
4706 return 0;
4707
4708 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
4709 if (!ret) {
4710 block_rsv_add_bytes(block_rsv, num_bytes, 0);
4711 return 0;
4712 }
4713
4714 return ret;
4715 }
4716
4717 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src_rsv,
4718 struct btrfs_block_rsv *dst_rsv,
4719 u64 num_bytes)
4720 {
4721 return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
4722 }
4723
4724 void btrfs_block_rsv_release(struct btrfs_root *root,
4725 struct btrfs_block_rsv *block_rsv,
4726 u64 num_bytes)
4727 {
4728 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
4729 if (global_rsv == block_rsv ||
4730 block_rsv->space_info != global_rsv->space_info)
4731 global_rsv = NULL;
4732 block_rsv_release_bytes(root->fs_info, block_rsv, global_rsv,
4733 num_bytes);
4734 }
4735
4736 /*
4737 * helper to calculate size of global block reservation.
4738 * the desired value is sum of space used by extent tree,
4739 * checksum tree and root tree
4740 */
4741 static u64 calc_global_metadata_size(struct btrfs_fs_info *fs_info)
4742 {
4743 struct btrfs_space_info *sinfo;
4744 u64 num_bytes;
4745 u64 meta_used;
4746 u64 data_used;
4747 int csum_size = btrfs_super_csum_size(fs_info->super_copy);
4748
4749 sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_DATA);
4750 spin_lock(&sinfo->lock);
4751 data_used = sinfo->bytes_used;
4752 spin_unlock(&sinfo->lock);
4753
4754 sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4755 spin_lock(&sinfo->lock);
4756 if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA)
4757 data_used = 0;
4758 meta_used = sinfo->bytes_used;
4759 spin_unlock(&sinfo->lock);
4760
4761 num_bytes = (data_used >> fs_info->sb->s_blocksize_bits) *
4762 csum_size * 2;
4763 num_bytes += div64_u64(data_used + meta_used, 50);
4764
4765 if (num_bytes * 3 > meta_used)
4766 num_bytes = div64_u64(meta_used, 3);
4767
4768 return ALIGN(num_bytes, fs_info->extent_root->leafsize << 10);
4769 }
4770
4771 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
4772 {
4773 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
4774 struct btrfs_space_info *sinfo = block_rsv->space_info;
4775 u64 num_bytes;
4776
4777 num_bytes = calc_global_metadata_size(fs_info);
4778
4779 spin_lock(&sinfo->lock);
4780 spin_lock(&block_rsv->lock);
4781
4782 block_rsv->size = min_t(u64, num_bytes, 512 * 1024 * 1024);
4783
4784 num_bytes = sinfo->bytes_used + sinfo->bytes_pinned +
4785 sinfo->bytes_reserved + sinfo->bytes_readonly +
4786 sinfo->bytes_may_use;
4787
4788 if (sinfo->total_bytes > num_bytes) {
4789 num_bytes = sinfo->total_bytes - num_bytes;
4790 block_rsv->reserved += num_bytes;
4791 sinfo->bytes_may_use += num_bytes;
4792 trace_btrfs_space_reservation(fs_info, "space_info",
4793 sinfo->flags, num_bytes, 1);
4794 }
4795
4796 if (block_rsv->reserved >= block_rsv->size) {
4797 num_bytes = block_rsv->reserved - block_rsv->size;
4798 sinfo->bytes_may_use -= num_bytes;
4799 trace_btrfs_space_reservation(fs_info, "space_info",
4800 sinfo->flags, num_bytes, 0);
4801 block_rsv->reserved = block_rsv->size;
4802 block_rsv->full = 1;
4803 }
4804
4805 spin_unlock(&block_rsv->lock);
4806 spin_unlock(&sinfo->lock);
4807 }
4808
4809 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
4810 {
4811 struct btrfs_space_info *space_info;
4812
4813 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4814 fs_info->chunk_block_rsv.space_info = space_info;
4815
4816 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4817 fs_info->global_block_rsv.space_info = space_info;
4818 fs_info->delalloc_block_rsv.space_info = space_info;
4819 fs_info->trans_block_rsv.space_info = space_info;
4820 fs_info->empty_block_rsv.space_info = space_info;
4821 fs_info->delayed_block_rsv.space_info = space_info;
4822
4823 fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
4824 fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
4825 fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
4826 fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
4827 if (fs_info->quota_root)
4828 fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
4829 fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
4830
4831 update_global_block_rsv(fs_info);
4832 }
4833
4834 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
4835 {
4836 block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
4837 (u64)-1);
4838 WARN_ON(fs_info->delalloc_block_rsv.size > 0);
4839 WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
4840 WARN_ON(fs_info->trans_block_rsv.size > 0);
4841 WARN_ON(fs_info->trans_block_rsv.reserved > 0);
4842 WARN_ON(fs_info->chunk_block_rsv.size > 0);
4843 WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
4844 WARN_ON(fs_info->delayed_block_rsv.size > 0);
4845 WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
4846 }
4847
4848 void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
4849 struct btrfs_root *root)
4850 {
4851 if (!trans->block_rsv)
4852 return;
4853
4854 if (!trans->bytes_reserved)
4855 return;
4856
4857 trace_btrfs_space_reservation(root->fs_info, "transaction",
4858 trans->transid, trans->bytes_reserved, 0);
4859 btrfs_block_rsv_release(root, trans->block_rsv, trans->bytes_reserved);
4860 trans->bytes_reserved = 0;
4861 }
4862
4863 /* Can only return 0 or -ENOSPC */
4864 int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
4865 struct inode *inode)
4866 {
4867 struct btrfs_root *root = BTRFS_I(inode)->root;
4868 struct btrfs_block_rsv *src_rsv = get_block_rsv(trans, root);
4869 struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
4870
4871 /*
4872 * We need to hold space in order to delete our orphan item once we've
4873 * added it, so this takes the reservation so we can release it later
4874 * when we are truly done with the orphan item.
4875 */
4876 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
4877 trace_btrfs_space_reservation(root->fs_info, "orphan",
4878 btrfs_ino(inode), num_bytes, 1);
4879 return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
4880 }
4881
4882 void btrfs_orphan_release_metadata(struct inode *inode)
4883 {
4884 struct btrfs_root *root = BTRFS_I(inode)->root;
4885 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
4886 trace_btrfs_space_reservation(root->fs_info, "orphan",
4887 btrfs_ino(inode), num_bytes, 0);
4888 btrfs_block_rsv_release(root, root->orphan_block_rsv, num_bytes);
4889 }
4890
4891 /*
4892 * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
4893 * root: the root of the parent directory
4894 * rsv: block reservation
4895 * items: the number of items that we need do reservation
4896 * qgroup_reserved: used to return the reserved size in qgroup
4897 *
4898 * This function is used to reserve the space for snapshot/subvolume
4899 * creation and deletion. Those operations are different with the
4900 * common file/directory operations, they change two fs/file trees
4901 * and root tree, the number of items that the qgroup reserves is
4902 * different with the free space reservation. So we can not use
4903 * the space reseravtion mechanism in start_transaction().
4904 */
4905 int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
4906 struct btrfs_block_rsv *rsv,
4907 int items,
4908 u64 *qgroup_reserved,
4909 bool use_global_rsv)
4910 {
4911 u64 num_bytes;
4912 int ret;
4913 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
4914
4915 if (root->fs_info->quota_enabled) {
4916 /* One for parent inode, two for dir entries */
4917 num_bytes = 3 * root->leafsize;
4918 ret = btrfs_qgroup_reserve(root, num_bytes);
4919 if (ret)
4920 return ret;
4921 } else {
4922 num_bytes = 0;
4923 }
4924
4925 *qgroup_reserved = num_bytes;
4926
4927 num_bytes = btrfs_calc_trans_metadata_size(root, items);
4928 rsv->space_info = __find_space_info(root->fs_info,
4929 BTRFS_BLOCK_GROUP_METADATA);
4930 ret = btrfs_block_rsv_add(root, rsv, num_bytes,
4931 BTRFS_RESERVE_FLUSH_ALL);
4932
4933 if (ret == -ENOSPC && use_global_rsv)
4934 ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes);
4935
4936 if (ret) {
4937 if (*qgroup_reserved)
4938 btrfs_qgroup_free(root, *qgroup_reserved);
4939 }
4940
4941 return ret;
4942 }
4943
4944 void btrfs_subvolume_release_metadata(struct btrfs_root *root,
4945 struct btrfs_block_rsv *rsv,
4946 u64 qgroup_reserved)
4947 {
4948 btrfs_block_rsv_release(root, rsv, (u64)-1);
4949 if (qgroup_reserved)
4950 btrfs_qgroup_free(root, qgroup_reserved);
4951 }
4952
4953 /**
4954 * drop_outstanding_extent - drop an outstanding extent
4955 * @inode: the inode we're dropping the extent for
4956 *
4957 * This is called when we are freeing up an outstanding extent, either called
4958 * after an error or after an extent is written. This will return the number of
4959 * reserved extents that need to be freed. This must be called with
4960 * BTRFS_I(inode)->lock held.
4961 */
4962 static unsigned drop_outstanding_extent(struct inode *inode)
4963 {
4964 unsigned drop_inode_space = 0;
4965 unsigned dropped_extents = 0;
4966
4967 BUG_ON(!BTRFS_I(inode)->outstanding_extents);
4968 BTRFS_I(inode)->outstanding_extents--;
4969
4970 if (BTRFS_I(inode)->outstanding_extents == 0 &&
4971 test_and_clear_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
4972 &BTRFS_I(inode)->runtime_flags))
4973 drop_inode_space = 1;
4974
4975 /*
4976 * If we have more or the same amount of outsanding extents than we have
4977 * reserved then we need to leave the reserved extents count alone.
4978 */
4979 if (BTRFS_I(inode)->outstanding_extents >=
4980 BTRFS_I(inode)->reserved_extents)
4981 return drop_inode_space;
4982
4983 dropped_extents = BTRFS_I(inode)->reserved_extents -
4984 BTRFS_I(inode)->outstanding_extents;
4985 BTRFS_I(inode)->reserved_extents -= dropped_extents;
4986 return dropped_extents + drop_inode_space;
4987 }
4988
4989 /**
4990 * calc_csum_metadata_size - return the amount of metada space that must be
4991 * reserved/free'd for the given bytes.
4992 * @inode: the inode we're manipulating
4993 * @num_bytes: the number of bytes in question
4994 * @reserve: 1 if we are reserving space, 0 if we are freeing space
4995 *
4996 * This adjusts the number of csum_bytes in the inode and then returns the
4997 * correct amount of metadata that must either be reserved or freed. We
4998 * calculate how many checksums we can fit into one leaf and then divide the
4999 * number of bytes that will need to be checksumed by this value to figure out
5000 * how many checksums will be required. If we are adding bytes then the number
5001 * may go up and we will return the number of additional bytes that must be
5002 * reserved. If it is going down we will return the number of bytes that must
5003 * be freed.
5004 *
5005 * This must be called with BTRFS_I(inode)->lock held.
5006 */
5007 static u64 calc_csum_metadata_size(struct inode *inode, u64 num_bytes,
5008 int reserve)
5009 {
5010 struct btrfs_root *root = BTRFS_I(inode)->root;
5011 u64 csum_size;
5012 int num_csums_per_leaf;
5013 int num_csums;
5014 int old_csums;
5015
5016 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM &&
5017 BTRFS_I(inode)->csum_bytes == 0)
5018 return 0;
5019
5020 old_csums = (int)div64_u64(BTRFS_I(inode)->csum_bytes, root->sectorsize);
5021 if (reserve)
5022 BTRFS_I(inode)->csum_bytes += num_bytes;
5023 else
5024 BTRFS_I(inode)->csum_bytes -= num_bytes;
5025 csum_size = BTRFS_LEAF_DATA_SIZE(root) - sizeof(struct btrfs_item);
5026 num_csums_per_leaf = (int)div64_u64(csum_size,
5027 sizeof(struct btrfs_csum_item) +
5028 sizeof(struct btrfs_disk_key));
5029 num_csums = (int)div64_u64(BTRFS_I(inode)->csum_bytes, root->sectorsize);
5030 num_csums = num_csums + num_csums_per_leaf - 1;
5031 num_csums = num_csums / num_csums_per_leaf;
5032
5033 old_csums = old_csums + num_csums_per_leaf - 1;
5034 old_csums = old_csums / num_csums_per_leaf;
5035
5036 /* No change, no need to reserve more */
5037 if (old_csums == num_csums)
5038 return 0;
5039
5040 if (reserve)
5041 return btrfs_calc_trans_metadata_size(root,
5042 num_csums - old_csums);
5043
5044 return btrfs_calc_trans_metadata_size(root, old_csums - num_csums);
5045 }
5046
5047 int btrfs_delalloc_reserve_metadata(struct inode *inode, u64 num_bytes)
5048 {
5049 struct btrfs_root *root = BTRFS_I(inode)->root;
5050 struct btrfs_block_rsv *block_rsv = &root->fs_info->delalloc_block_rsv;
5051 u64 to_reserve = 0;
5052 u64 csum_bytes;
5053 unsigned nr_extents = 0;
5054 int extra_reserve = 0;
5055 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
5056 int ret = 0;
5057 bool delalloc_lock = true;
5058 u64 to_free = 0;
5059 unsigned dropped;
5060
5061 /* If we are a free space inode we need to not flush since we will be in
5062 * the middle of a transaction commit. We also don't need the delalloc
5063 * mutex since we won't race with anybody. We need this mostly to make
5064 * lockdep shut its filthy mouth.
5065 */
5066 if (btrfs_is_free_space_inode(inode)) {
5067 flush = BTRFS_RESERVE_NO_FLUSH;
5068 delalloc_lock = false;
5069 }
5070
5071 if (flush != BTRFS_RESERVE_NO_FLUSH &&
5072 btrfs_transaction_in_commit(root->fs_info))
5073 schedule_timeout(1);
5074
5075 if (delalloc_lock)
5076 mutex_lock(&BTRFS_I(inode)->delalloc_mutex);
5077
5078 num_bytes = ALIGN(num_bytes, root->sectorsize);
5079
5080 spin_lock(&BTRFS_I(inode)->lock);
5081 BTRFS_I(inode)->outstanding_extents++;
5082
5083 if (BTRFS_I(inode)->outstanding_extents >
5084 BTRFS_I(inode)->reserved_extents)
5085 nr_extents = BTRFS_I(inode)->outstanding_extents -
5086 BTRFS_I(inode)->reserved_extents;
5087
5088 /*
5089 * Add an item to reserve for updating the inode when we complete the
5090 * delalloc io.
5091 */
5092 if (!test_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
5093 &BTRFS_I(inode)->runtime_flags)) {
5094 nr_extents++;
5095 extra_reserve = 1;
5096 }
5097
5098 to_reserve = btrfs_calc_trans_metadata_size(root, nr_extents);
5099 to_reserve += calc_csum_metadata_size(inode, num_bytes, 1);
5100 csum_bytes = BTRFS_I(inode)->csum_bytes;
5101 spin_unlock(&BTRFS_I(inode)->lock);
5102
5103 if (root->fs_info->quota_enabled) {
5104 ret = btrfs_qgroup_reserve(root, num_bytes +
5105 nr_extents * root->leafsize);
5106 if (ret)
5107 goto out_fail;
5108 }
5109
5110 ret = reserve_metadata_bytes(root, block_rsv, to_reserve, flush);
5111 if (unlikely(ret)) {
5112 if (root->fs_info->quota_enabled)
5113 btrfs_qgroup_free(root, num_bytes +
5114 nr_extents * root->leafsize);
5115 goto out_fail;
5116 }
5117
5118 spin_lock(&BTRFS_I(inode)->lock);
5119 if (extra_reserve) {
5120 set_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
5121 &BTRFS_I(inode)->runtime_flags);
5122 nr_extents--;
5123 }
5124 BTRFS_I(inode)->reserved_extents += nr_extents;
5125 spin_unlock(&BTRFS_I(inode)->lock);
5126
5127 if (delalloc_lock)
5128 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
5129
5130 if (to_reserve)
5131 trace_btrfs_space_reservation(root->fs_info, "delalloc",
5132 btrfs_ino(inode), to_reserve, 1);
5133 block_rsv_add_bytes(block_rsv, to_reserve, 1);
5134
5135 return 0;
5136
5137 out_fail:
5138 spin_lock(&BTRFS_I(inode)->lock);
5139 dropped = drop_outstanding_extent(inode);
5140 /*
5141 * If the inodes csum_bytes is the same as the original
5142 * csum_bytes then we know we haven't raced with any free()ers
5143 * so we can just reduce our inodes csum bytes and carry on.
5144 */
5145 if (BTRFS_I(inode)->csum_bytes == csum_bytes) {
5146 calc_csum_metadata_size(inode, num_bytes, 0);
5147 } else {
5148 u64 orig_csum_bytes = BTRFS_I(inode)->csum_bytes;
5149 u64 bytes;
5150
5151 /*
5152 * This is tricky, but first we need to figure out how much we
5153 * free'd from any free-ers that occured during this
5154 * reservation, so we reset ->csum_bytes to the csum_bytes
5155 * before we dropped our lock, and then call the free for the
5156 * number of bytes that were freed while we were trying our
5157 * reservation.
5158 */
5159 bytes = csum_bytes - BTRFS_I(inode)->csum_bytes;
5160 BTRFS_I(inode)->csum_bytes = csum_bytes;
5161 to_free = calc_csum_metadata_size(inode, bytes, 0);
5162
5163
5164 /*
5165 * Now we need to see how much we would have freed had we not
5166 * been making this reservation and our ->csum_bytes were not
5167 * artificially inflated.
5168 */
5169 BTRFS_I(inode)->csum_bytes = csum_bytes - num_bytes;
5170 bytes = csum_bytes - orig_csum_bytes;
5171 bytes = calc_csum_metadata_size(inode, bytes, 0);
5172
5173 /*
5174 * Now reset ->csum_bytes to what it should be. If bytes is
5175 * more than to_free then we would have free'd more space had we
5176 * not had an artificially high ->csum_bytes, so we need to free
5177 * the remainder. If bytes is the same or less then we don't
5178 * need to do anything, the other free-ers did the correct
5179 * thing.
5180 */
5181 BTRFS_I(inode)->csum_bytes = orig_csum_bytes - num_bytes;
5182 if (bytes > to_free)
5183 to_free = bytes - to_free;
5184 else
5185 to_free = 0;
5186 }
5187 spin_unlock(&BTRFS_I(inode)->lock);
5188 if (dropped)
5189 to_free += btrfs_calc_trans_metadata_size(root, dropped);
5190
5191 if (to_free) {
5192 btrfs_block_rsv_release(root, block_rsv, to_free);
5193 trace_btrfs_space_reservation(root->fs_info, "delalloc",
5194 btrfs_ino(inode), to_free, 0);
5195 }
5196 if (delalloc_lock)
5197 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
5198 return ret;
5199 }
5200
5201 /**
5202 * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
5203 * @inode: the inode to release the reservation for
5204 * @num_bytes: the number of bytes we're releasing
5205 *
5206 * This will release the metadata reservation for an inode. This can be called
5207 * once we complete IO for a given set of bytes to release their metadata
5208 * reservations.
5209 */
5210 void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
5211 {
5212 struct btrfs_root *root = BTRFS_I(inode)->root;
5213 u64 to_free = 0;
5214 unsigned dropped;
5215
5216 num_bytes = ALIGN(num_bytes, root->sectorsize);
5217 spin_lock(&BTRFS_I(inode)->lock);
5218 dropped = drop_outstanding_extent(inode);
5219
5220 if (num_bytes)
5221 to_free = calc_csum_metadata_size(inode, num_bytes, 0);
5222 spin_unlock(&BTRFS_I(inode)->lock);
5223 if (dropped > 0)
5224 to_free += btrfs_calc_trans_metadata_size(root, dropped);
5225
5226 trace_btrfs_space_reservation(root->fs_info, "delalloc",
5227 btrfs_ino(inode), to_free, 0);
5228 if (root->fs_info->quota_enabled) {
5229 btrfs_qgroup_free(root, num_bytes +
5230 dropped * root->leafsize);
5231 }
5232
5233 btrfs_block_rsv_release(root, &root->fs_info->delalloc_block_rsv,
5234 to_free);
5235 }
5236
5237 /**
5238 * btrfs_delalloc_reserve_space - reserve data and metadata space for delalloc
5239 * @inode: inode we're writing to
5240 * @num_bytes: the number of bytes we want to allocate
5241 *
5242 * This will do the following things
5243 *
5244 * o reserve space in the data space info for num_bytes
5245 * o reserve space in the metadata space info based on number of outstanding
5246 * extents and how much csums will be needed
5247 * o add to the inodes ->delalloc_bytes
5248 * o add it to the fs_info's delalloc inodes list.
5249 *
5250 * This will return 0 for success and -ENOSPC if there is no space left.
5251 */
5252 int btrfs_delalloc_reserve_space(struct inode *inode, u64 num_bytes)
5253 {
5254 int ret;
5255
5256 ret = btrfs_check_data_free_space(inode, num_bytes);
5257 if (ret)
5258 return ret;
5259
5260 ret = btrfs_delalloc_reserve_metadata(inode, num_bytes);
5261 if (ret) {
5262 btrfs_free_reserved_data_space(inode, num_bytes);
5263 return ret;
5264 }
5265
5266 return 0;
5267 }
5268
5269 /**
5270 * btrfs_delalloc_release_space - release data and metadata space for delalloc
5271 * @inode: inode we're releasing space for
5272 * @num_bytes: the number of bytes we want to free up
5273 *
5274 * This must be matched with a call to btrfs_delalloc_reserve_space. This is
5275 * called in the case that we don't need the metadata AND data reservations
5276 * anymore. So if there is an error or we insert an inline extent.
5277 *
5278 * This function will release the metadata space that was not used and will
5279 * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
5280 * list if there are no delalloc bytes left.
5281 */
5282 void btrfs_delalloc_release_space(struct inode *inode, u64 num_bytes)
5283 {
5284 btrfs_delalloc_release_metadata(inode, num_bytes);
5285 btrfs_free_reserved_data_space(inode, num_bytes);
5286 }
5287
5288 static int update_block_group(struct btrfs_root *root,
5289 u64 bytenr, u64 num_bytes, int alloc)
5290 {
5291 struct btrfs_block_group_cache *cache = NULL;
5292 struct btrfs_fs_info *info = root->fs_info;
5293 u64 total = num_bytes;
5294 u64 old_val;
5295 u64 byte_in_group;
5296 int factor;
5297
5298 /* block accounting for super block */
5299 spin_lock(&info->delalloc_root_lock);
5300 old_val = btrfs_super_bytes_used(info->super_copy);
5301 if (alloc)
5302 old_val += num_bytes;
5303 else
5304 old_val -= num_bytes;
5305 btrfs_set_super_bytes_used(info->super_copy, old_val);
5306 spin_unlock(&info->delalloc_root_lock);
5307
5308 while (total) {
5309 cache = btrfs_lookup_block_group(info, bytenr);
5310 if (!cache)
5311 return -ENOENT;
5312 if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
5313 BTRFS_BLOCK_GROUP_RAID1 |
5314 BTRFS_BLOCK_GROUP_RAID10))
5315 factor = 2;
5316 else
5317 factor = 1;
5318 /*
5319 * If this block group has free space cache written out, we
5320 * need to make sure to load it if we are removing space. This
5321 * is because we need the unpinning stage to actually add the
5322 * space back to the block group, otherwise we will leak space.
5323 */
5324 if (!alloc && cache->cached == BTRFS_CACHE_NO)
5325 cache_block_group(cache, 1);
5326
5327 byte_in_group = bytenr - cache->key.objectid;
5328 WARN_ON(byte_in_group > cache->key.offset);
5329
5330 spin_lock(&cache->space_info->lock);
5331 spin_lock(&cache->lock);
5332
5333 if (btrfs_test_opt(root, SPACE_CACHE) &&
5334 cache->disk_cache_state < BTRFS_DC_CLEAR)
5335 cache->disk_cache_state = BTRFS_DC_CLEAR;
5336
5337 cache->dirty = 1;
5338 old_val = btrfs_block_group_used(&cache->item);
5339 num_bytes = min(total, cache->key.offset - byte_in_group);
5340 if (alloc) {
5341 old_val += num_bytes;
5342 btrfs_set_block_group_used(&cache->item, old_val);
5343 cache->reserved -= num_bytes;
5344 cache->space_info->bytes_reserved -= num_bytes;
5345 cache->space_info->bytes_used += num_bytes;
5346 cache->space_info->disk_used += num_bytes * factor;
5347 spin_unlock(&cache->lock);
5348 spin_unlock(&cache->space_info->lock);
5349 } else {
5350 old_val -= num_bytes;
5351 btrfs_set_block_group_used(&cache->item, old_val);
5352 cache->pinned += num_bytes;
5353 cache->space_info->bytes_pinned += num_bytes;
5354 cache->space_info->bytes_used -= num_bytes;
5355 cache->space_info->disk_used -= num_bytes * factor;
5356 spin_unlock(&cache->lock);
5357 spin_unlock(&cache->space_info->lock);
5358
5359 set_extent_dirty(info->pinned_extents,
5360 bytenr, bytenr + num_bytes - 1,
5361 GFP_NOFS | __GFP_NOFAIL);
5362 }
5363 btrfs_put_block_group(cache);
5364 total -= num_bytes;
5365 bytenr += num_bytes;
5366 }
5367 return 0;
5368 }
5369
5370 static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
5371 {
5372 struct btrfs_block_group_cache *cache;
5373 u64 bytenr;
5374
5375 spin_lock(&root->fs_info->block_group_cache_lock);
5376 bytenr = root->fs_info->first_logical_byte;
5377 spin_unlock(&root->fs_info->block_group_cache_lock);
5378
5379 if (bytenr < (u64)-1)
5380 return bytenr;
5381
5382 cache = btrfs_lookup_first_block_group(root->fs_info, search_start);
5383 if (!cache)
5384 return 0;
5385
5386 bytenr = cache->key.objectid;
5387 btrfs_put_block_group(cache);
5388
5389 return bytenr;
5390 }
5391
5392 static int pin_down_extent(struct btrfs_root *root,
5393 struct btrfs_block_group_cache *cache,
5394 u64 bytenr, u64 num_bytes, int reserved)
5395 {
5396 spin_lock(&cache->space_info->lock);
5397 spin_lock(&cache->lock);
5398 cache->pinned += num_bytes;
5399 cache->space_info->bytes_pinned += num_bytes;
5400 if (reserved) {
5401 cache->reserved -= num_bytes;
5402 cache->space_info->bytes_reserved -= num_bytes;
5403 }
5404 spin_unlock(&cache->lock);
5405 spin_unlock(&cache->space_info->lock);
5406
5407 set_extent_dirty(root->fs_info->pinned_extents, bytenr,
5408 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
5409 if (reserved)
5410 trace_btrfs_reserved_extent_free(root, bytenr, num_bytes);
5411 return 0;
5412 }
5413
5414 /*
5415 * this function must be called within transaction
5416 */
5417 int btrfs_pin_extent(struct btrfs_root *root,
5418 u64 bytenr, u64 num_bytes, int reserved)
5419 {
5420 struct btrfs_block_group_cache *cache;
5421
5422 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
5423 BUG_ON(!cache); /* Logic error */
5424
5425 pin_down_extent(root, cache, bytenr, num_bytes, reserved);
5426
5427 btrfs_put_block_group(cache);
5428 return 0;
5429 }
5430
5431 /*
5432 * this function must be called within transaction
5433 */
5434 int btrfs_pin_extent_for_log_replay(struct btrfs_root *root,
5435 u64 bytenr, u64 num_bytes)
5436 {
5437 struct btrfs_block_group_cache *cache;
5438 int ret;
5439
5440 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
5441 if (!cache)
5442 return -EINVAL;
5443
5444 /*
5445 * pull in the free space cache (if any) so that our pin
5446 * removes the free space from the cache. We have load_only set
5447 * to one because the slow code to read in the free extents does check
5448 * the pinned extents.
5449 */
5450 cache_block_group(cache, 1);
5451
5452 pin_down_extent(root, cache, bytenr, num_bytes, 0);
5453
5454 /* remove us from the free space cache (if we're there at all) */
5455 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
5456 btrfs_put_block_group(cache);
5457 return ret;
5458 }
5459
5460 static int __exclude_logged_extent(struct btrfs_root *root, u64 start, u64 num_bytes)
5461 {
5462 int ret;
5463 struct btrfs_block_group_cache *block_group;
5464 struct btrfs_caching_control *caching_ctl;
5465
5466 block_group = btrfs_lookup_block_group(root->fs_info, start);
5467 if (!block_group)
5468 return -EINVAL;
5469
5470 cache_block_group(block_group, 0);
5471 caching_ctl = get_caching_control(block_group);
5472
5473 if (!caching_ctl) {
5474 /* Logic error */
5475 BUG_ON(!block_group_cache_done(block_group));
5476 ret = btrfs_remove_free_space(block_group, start, num_bytes);
5477 } else {
5478 mutex_lock(&caching_ctl->mutex);
5479
5480 if (start >= caching_ctl->progress) {
5481 ret = add_excluded_extent(root, start, num_bytes);
5482 } else if (start + num_bytes <= caching_ctl->progress) {
5483 ret = btrfs_remove_free_space(block_group,
5484 start, num_bytes);
5485 } else {
5486 num_bytes = caching_ctl->progress - start;
5487 ret = btrfs_remove_free_space(block_group,
5488 start, num_bytes);
5489 if (ret)
5490 goto out_lock;
5491
5492 num_bytes = (start + num_bytes) -
5493 caching_ctl->progress;
5494 start = caching_ctl->progress;
5495 ret = add_excluded_extent(root, start, num_bytes);
5496 }
5497 out_lock:
5498 mutex_unlock(&caching_ctl->mutex);
5499 put_caching_control(caching_ctl);
5500 }
5501 btrfs_put_block_group(block_group);
5502 return ret;
5503 }
5504
5505 int btrfs_exclude_logged_extents(struct btrfs_root *log,
5506 struct extent_buffer *eb)
5507 {
5508 struct btrfs_file_extent_item *item;
5509 struct btrfs_key key;
5510 int found_type;
5511 int i;
5512
5513 if (!btrfs_fs_incompat(log->fs_info, MIXED_GROUPS))
5514 return 0;
5515
5516 for (i = 0; i < btrfs_header_nritems(eb); i++) {
5517 btrfs_item_key_to_cpu(eb, &key, i);
5518 if (key.type != BTRFS_EXTENT_DATA_KEY)
5519 continue;
5520 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
5521 found_type = btrfs_file_extent_type(eb, item);
5522 if (found_type == BTRFS_FILE_EXTENT_INLINE)
5523 continue;
5524 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
5525 continue;
5526 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
5527 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
5528 __exclude_logged_extent(log, key.objectid, key.offset);
5529 }
5530
5531 return 0;
5532 }
5533
5534 /**
5535 * btrfs_update_reserved_bytes - update the block_group and space info counters
5536 * @cache: The cache we are manipulating
5537 * @num_bytes: The number of bytes in question
5538 * @reserve: One of the reservation enums
5539 *
5540 * This is called by the allocator when it reserves space, or by somebody who is
5541 * freeing space that was never actually used on disk. For example if you
5542 * reserve some space for a new leaf in transaction A and before transaction A
5543 * commits you free that leaf, you call this with reserve set to 0 in order to
5544 * clear the reservation.
5545 *
5546 * Metadata reservations should be called with RESERVE_ALLOC so we do the proper
5547 * ENOSPC accounting. For data we handle the reservation through clearing the
5548 * delalloc bits in the io_tree. We have to do this since we could end up
5549 * allocating less disk space for the amount of data we have reserved in the
5550 * case of compression.
5551 *
5552 * If this is a reservation and the block group has become read only we cannot
5553 * make the reservation and return -EAGAIN, otherwise this function always
5554 * succeeds.
5555 */
5556 static int btrfs_update_reserved_bytes(struct btrfs_block_group_cache *cache,
5557 u64 num_bytes, int reserve)
5558 {
5559 struct btrfs_space_info *space_info = cache->space_info;
5560 int ret = 0;
5561
5562 spin_lock(&space_info->lock);
5563 spin_lock(&cache->lock);
5564 if (reserve != RESERVE_FREE) {
5565 if (cache->ro) {
5566 ret = -EAGAIN;
5567 } else {
5568 cache->reserved += num_bytes;
5569 space_info->bytes_reserved += num_bytes;
5570 if (reserve == RESERVE_ALLOC) {
5571 trace_btrfs_space_reservation(cache->fs_info,
5572 "space_info", space_info->flags,
5573 num_bytes, 0);
5574 space_info->bytes_may_use -= num_bytes;
5575 }
5576 }
5577 } else {
5578 if (cache->ro)
5579 space_info->bytes_readonly += num_bytes;
5580 cache->reserved -= num_bytes;
5581 space_info->bytes_reserved -= num_bytes;
5582 }
5583 spin_unlock(&cache->lock);
5584 spin_unlock(&space_info->lock);
5585 return ret;
5586 }
5587
5588 void btrfs_prepare_extent_commit(struct btrfs_trans_handle *trans,
5589 struct btrfs_root *root)
5590 {
5591 struct btrfs_fs_info *fs_info = root->fs_info;
5592 struct btrfs_caching_control *next;
5593 struct btrfs_caching_control *caching_ctl;
5594 struct btrfs_block_group_cache *cache;
5595 struct btrfs_space_info *space_info;
5596
5597 down_write(&fs_info->commit_root_sem);
5598
5599 list_for_each_entry_safe(caching_ctl, next,
5600 &fs_info->caching_block_groups, list) {
5601 cache = caching_ctl->block_group;
5602 if (block_group_cache_done(cache)) {
5603 cache->last_byte_to_unpin = (u64)-1;
5604 list_del_init(&caching_ctl->list);
5605 put_caching_control(caching_ctl);
5606 } else {
5607 cache->last_byte_to_unpin = caching_ctl->progress;
5608 }
5609 }
5610
5611 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
5612 fs_info->pinned_extents = &fs_info->freed_extents[1];
5613 else
5614 fs_info->pinned_extents = &fs_info->freed_extents[0];
5615
5616 up_write(&fs_info->commit_root_sem);
5617
5618 list_for_each_entry_rcu(space_info, &fs_info->space_info, list)
5619 percpu_counter_set(&space_info->total_bytes_pinned, 0);
5620
5621 update_global_block_rsv(fs_info);
5622 }
5623
5624 static int unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
5625 {
5626 struct btrfs_fs_info *fs_info = root->fs_info;
5627 struct btrfs_block_group_cache *cache = NULL;
5628 struct btrfs_space_info *space_info;
5629 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5630 u64 len;
5631 bool readonly;
5632
5633 while (start <= end) {
5634 readonly = false;
5635 if (!cache ||
5636 start >= cache->key.objectid + cache->key.offset) {
5637 if (cache)
5638 btrfs_put_block_group(cache);
5639 cache = btrfs_lookup_block_group(fs_info, start);
5640 BUG_ON(!cache); /* Logic error */
5641 }
5642
5643 len = cache->key.objectid + cache->key.offset - start;
5644 len = min(len, end + 1 - start);
5645
5646 if (start < cache->last_byte_to_unpin) {
5647 len = min(len, cache->last_byte_to_unpin - start);
5648 btrfs_add_free_space(cache, start, len);
5649 }
5650
5651 start += len;
5652 space_info = cache->space_info;
5653
5654 spin_lock(&space_info->lock);
5655 spin_lock(&cache->lock);
5656 cache->pinned -= len;
5657 space_info->bytes_pinned -= len;
5658 if (cache->ro) {
5659 space_info->bytes_readonly += len;
5660 readonly = true;
5661 }
5662 spin_unlock(&cache->lock);
5663 if (!readonly && global_rsv->space_info == space_info) {
5664 spin_lock(&global_rsv->lock);
5665 if (!global_rsv->full) {
5666 len = min(len, global_rsv->size -
5667 global_rsv->reserved);
5668 global_rsv->reserved += len;
5669 space_info->bytes_may_use += len;
5670 if (global_rsv->reserved >= global_rsv->size)
5671 global_rsv->full = 1;
5672 }
5673 spin_unlock(&global_rsv->lock);
5674 }
5675 spin_unlock(&space_info->lock);
5676 }
5677
5678 if (cache)
5679 btrfs_put_block_group(cache);
5680 return 0;
5681 }
5682
5683 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
5684 struct btrfs_root *root)
5685 {
5686 struct btrfs_fs_info *fs_info = root->fs_info;
5687 struct extent_io_tree *unpin;
5688 u64 start;
5689 u64 end;
5690 int ret;
5691
5692 if (trans->aborted)
5693 return 0;
5694
5695 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
5696 unpin = &fs_info->freed_extents[1];
5697 else
5698 unpin = &fs_info->freed_extents[0];
5699
5700 while (1) {
5701 ret = find_first_extent_bit(unpin, 0, &start, &end,
5702 EXTENT_DIRTY, NULL);
5703 if (ret)
5704 break;
5705
5706 if (btrfs_test_opt(root, DISCARD))
5707 ret = btrfs_discard_extent(root, start,
5708 end + 1 - start, NULL);
5709
5710 clear_extent_dirty(unpin, start, end, GFP_NOFS);
5711 unpin_extent_range(root, start, end);
5712 cond_resched();
5713 }
5714
5715 return 0;
5716 }
5717
5718 static void add_pinned_bytes(struct btrfs_fs_info *fs_info, u64 num_bytes,
5719 u64 owner, u64 root_objectid)
5720 {
5721 struct btrfs_space_info *space_info;
5722 u64 flags;
5723
5724 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
5725 if (root_objectid == BTRFS_CHUNK_TREE_OBJECTID)
5726 flags = BTRFS_BLOCK_GROUP_SYSTEM;
5727 else
5728 flags = BTRFS_BLOCK_GROUP_METADATA;
5729 } else {
5730 flags = BTRFS_BLOCK_GROUP_DATA;
5731 }
5732
5733 space_info = __find_space_info(fs_info, flags);
5734 BUG_ON(!space_info); /* Logic bug */
5735 percpu_counter_add(&space_info->total_bytes_pinned, num_bytes);
5736 }
5737
5738
5739 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
5740 struct btrfs_root *root,
5741 u64 bytenr, u64 num_bytes, u64 parent,
5742 u64 root_objectid, u64 owner_objectid,
5743 u64 owner_offset, int refs_to_drop,
5744 struct btrfs_delayed_extent_op *extent_op,
5745 int no_quota)
5746 {
5747 struct btrfs_key key;
5748 struct btrfs_path *path;
5749 struct btrfs_fs_info *info = root->fs_info;
5750 struct btrfs_root *extent_root = info->extent_root;
5751 struct extent_buffer *leaf;
5752 struct btrfs_extent_item *ei;
5753 struct btrfs_extent_inline_ref *iref;
5754 int ret;
5755 int is_data;
5756 int extent_slot = 0;
5757 int found_extent = 0;
5758 int num_to_del = 1;
5759 u32 item_size;
5760 u64 refs;
5761 int last_ref = 0;
5762 enum btrfs_qgroup_operation_type type = BTRFS_QGROUP_OPER_SUB_EXCL;
5763 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
5764 SKINNY_METADATA);
5765
5766 if (!info->quota_enabled || !is_fstree(root_objectid))
5767 no_quota = 1;
5768
5769 path = btrfs_alloc_path();
5770 if (!path)
5771 return -ENOMEM;
5772
5773 path->reada = 1;
5774 path->leave_spinning = 1;
5775
5776 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
5777 BUG_ON(!is_data && refs_to_drop != 1);
5778
5779 if (is_data)
5780 skinny_metadata = 0;
5781
5782 ret = lookup_extent_backref(trans, extent_root, path, &iref,
5783 bytenr, num_bytes, parent,
5784 root_objectid, owner_objectid,
5785 owner_offset);
5786 if (ret == 0) {
5787 extent_slot = path->slots[0];
5788 while (extent_slot >= 0) {
5789 btrfs_item_key_to_cpu(path->nodes[0], &key,
5790 extent_slot);
5791 if (key.objectid != bytenr)
5792 break;
5793 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
5794 key.offset == num_bytes) {
5795 found_extent = 1;
5796 break;
5797 }
5798 if (key.type == BTRFS_METADATA_ITEM_KEY &&
5799 key.offset == owner_objectid) {
5800 found_extent = 1;
5801 break;
5802 }
5803 if (path->slots[0] - extent_slot > 5)
5804 break;
5805 extent_slot--;
5806 }
5807 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5808 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
5809 if (found_extent && item_size < sizeof(*ei))
5810 found_extent = 0;
5811 #endif
5812 if (!found_extent) {
5813 BUG_ON(iref);
5814 ret = remove_extent_backref(trans, extent_root, path,
5815 NULL, refs_to_drop,
5816 is_data, &last_ref);
5817 if (ret) {
5818 btrfs_abort_transaction(trans, extent_root, ret);
5819 goto out;
5820 }
5821 btrfs_release_path(path);
5822 path->leave_spinning = 1;
5823
5824 key.objectid = bytenr;
5825 key.type = BTRFS_EXTENT_ITEM_KEY;
5826 key.offset = num_bytes;
5827
5828 if (!is_data && skinny_metadata) {
5829 key.type = BTRFS_METADATA_ITEM_KEY;
5830 key.offset = owner_objectid;
5831 }
5832
5833 ret = btrfs_search_slot(trans, extent_root,
5834 &key, path, -1, 1);
5835 if (ret > 0 && skinny_metadata && path->slots[0]) {
5836 /*
5837 * Couldn't find our skinny metadata item,
5838 * see if we have ye olde extent item.
5839 */
5840 path->slots[0]--;
5841 btrfs_item_key_to_cpu(path->nodes[0], &key,
5842 path->slots[0]);
5843 if (key.objectid == bytenr &&
5844 key.type == BTRFS_EXTENT_ITEM_KEY &&
5845 key.offset == num_bytes)
5846 ret = 0;
5847 }
5848
5849 if (ret > 0 && skinny_metadata) {
5850 skinny_metadata = false;
5851 key.objectid = bytenr;
5852 key.type = BTRFS_EXTENT_ITEM_KEY;
5853 key.offset = num_bytes;
5854 btrfs_release_path(path);
5855 ret = btrfs_search_slot(trans, extent_root,
5856 &key, path, -1, 1);
5857 }
5858
5859 if (ret) {
5860 btrfs_err(info, "umm, got %d back from search, was looking for %llu",
5861 ret, bytenr);
5862 if (ret > 0)
5863 btrfs_print_leaf(extent_root,
5864 path->nodes[0]);
5865 }
5866 if (ret < 0) {
5867 btrfs_abort_transaction(trans, extent_root, ret);
5868 goto out;
5869 }
5870 extent_slot = path->slots[0];
5871 }
5872 } else if (WARN_ON(ret == -ENOENT)) {
5873 btrfs_print_leaf(extent_root, path->nodes[0]);
5874 btrfs_err(info,
5875 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
5876 bytenr, parent, root_objectid, owner_objectid,
5877 owner_offset);
5878 btrfs_abort_transaction(trans, extent_root, ret);
5879 goto out;
5880 } else {
5881 btrfs_abort_transaction(trans, extent_root, ret);
5882 goto out;
5883 }
5884
5885 leaf = path->nodes[0];
5886 item_size = btrfs_item_size_nr(leaf, extent_slot);
5887 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5888 if (item_size < sizeof(*ei)) {
5889 BUG_ON(found_extent || extent_slot != path->slots[0]);
5890 ret = convert_extent_item_v0(trans, extent_root, path,
5891 owner_objectid, 0);
5892 if (ret < 0) {
5893 btrfs_abort_transaction(trans, extent_root, ret);
5894 goto out;
5895 }
5896
5897 btrfs_release_path(path);
5898 path->leave_spinning = 1;
5899
5900 key.objectid = bytenr;
5901 key.type = BTRFS_EXTENT_ITEM_KEY;
5902 key.offset = num_bytes;
5903
5904 ret = btrfs_search_slot(trans, extent_root, &key, path,
5905 -1, 1);
5906 if (ret) {
5907 btrfs_err(info, "umm, got %d back from search, was looking for %llu",
5908 ret, bytenr);
5909 btrfs_print_leaf(extent_root, path->nodes[0]);
5910 }
5911 if (ret < 0) {
5912 btrfs_abort_transaction(trans, extent_root, ret);
5913 goto out;
5914 }
5915
5916 extent_slot = path->slots[0];
5917 leaf = path->nodes[0];
5918 item_size = btrfs_item_size_nr(leaf, extent_slot);
5919 }
5920 #endif
5921 BUG_ON(item_size < sizeof(*ei));
5922 ei = btrfs_item_ptr(leaf, extent_slot,
5923 struct btrfs_extent_item);
5924 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
5925 key.type == BTRFS_EXTENT_ITEM_KEY) {
5926 struct btrfs_tree_block_info *bi;
5927 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
5928 bi = (struct btrfs_tree_block_info *)(ei + 1);
5929 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
5930 }
5931
5932 refs = btrfs_extent_refs(leaf, ei);
5933 if (refs < refs_to_drop) {
5934 btrfs_err(info, "trying to drop %d refs but we only have %Lu "
5935 "for bytenr %Lu", refs_to_drop, refs, bytenr);
5936 ret = -EINVAL;
5937 btrfs_abort_transaction(trans, extent_root, ret);
5938 goto out;
5939 }
5940 refs -= refs_to_drop;
5941
5942 if (refs > 0) {
5943 type = BTRFS_QGROUP_OPER_SUB_SHARED;
5944 if (extent_op)
5945 __run_delayed_extent_op(extent_op, leaf, ei);
5946 /*
5947 * In the case of inline back ref, reference count will
5948 * be updated by remove_extent_backref
5949 */
5950 if (iref) {
5951 BUG_ON(!found_extent);
5952 } else {
5953 btrfs_set_extent_refs(leaf, ei, refs);
5954 btrfs_mark_buffer_dirty(leaf);
5955 }
5956 if (found_extent) {
5957 ret = remove_extent_backref(trans, extent_root, path,
5958 iref, refs_to_drop,
5959 is_data, &last_ref);
5960 if (ret) {
5961 btrfs_abort_transaction(trans, extent_root, ret);
5962 goto out;
5963 }
5964 }
5965 add_pinned_bytes(root->fs_info, -num_bytes, owner_objectid,
5966 root_objectid);
5967 } else {
5968 if (found_extent) {
5969 BUG_ON(is_data && refs_to_drop !=
5970 extent_data_ref_count(root, path, iref));
5971 if (iref) {
5972 BUG_ON(path->slots[0] != extent_slot);
5973 } else {
5974 BUG_ON(path->slots[0] != extent_slot + 1);
5975 path->slots[0] = extent_slot;
5976 num_to_del = 2;
5977 }
5978 }
5979
5980 last_ref = 1;
5981 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
5982 num_to_del);
5983 if (ret) {
5984 btrfs_abort_transaction(trans, extent_root, ret);
5985 goto out;
5986 }
5987 btrfs_release_path(path);
5988
5989 if (is_data) {
5990 ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
5991 if (ret) {
5992 btrfs_abort_transaction(trans, extent_root, ret);
5993 goto out;
5994 }
5995 }
5996
5997 ret = update_block_group(root, bytenr, num_bytes, 0);
5998 if (ret) {
5999 btrfs_abort_transaction(trans, extent_root, ret);
6000 goto out;
6001 }
6002 }
6003 btrfs_release_path(path);
6004
6005 /* Deal with the quota accounting */
6006 if (!ret && last_ref && !no_quota) {
6007 int mod_seq = 0;
6008
6009 if (owner_objectid >= BTRFS_FIRST_FREE_OBJECTID &&
6010 type == BTRFS_QGROUP_OPER_SUB_SHARED)
6011 mod_seq = 1;
6012
6013 ret = btrfs_qgroup_record_ref(trans, info, root_objectid,
6014 bytenr, num_bytes, type,
6015 mod_seq);
6016 }
6017 out:
6018 btrfs_free_path(path);
6019 return ret;
6020 }
6021
6022 /*
6023 * when we free an block, it is possible (and likely) that we free the last
6024 * delayed ref for that extent as well. This searches the delayed ref tree for
6025 * a given extent, and if there are no other delayed refs to be processed, it
6026 * removes it from the tree.
6027 */
6028 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
6029 struct btrfs_root *root, u64 bytenr)
6030 {
6031 struct btrfs_delayed_ref_head *head;
6032 struct btrfs_delayed_ref_root *delayed_refs;
6033 int ret = 0;
6034
6035 delayed_refs = &trans->transaction->delayed_refs;
6036 spin_lock(&delayed_refs->lock);
6037 head = btrfs_find_delayed_ref_head(trans, bytenr);
6038 if (!head)
6039 goto out_delayed_unlock;
6040
6041 spin_lock(&head->lock);
6042 if (rb_first(&head->ref_root))
6043 goto out;
6044
6045 if (head->extent_op) {
6046 if (!head->must_insert_reserved)
6047 goto out;
6048 btrfs_free_delayed_extent_op(head->extent_op);
6049 head->extent_op = NULL;
6050 }
6051
6052 /*
6053 * waiting for the lock here would deadlock. If someone else has it
6054 * locked they are already in the process of dropping it anyway
6055 */
6056 if (!mutex_trylock(&head->mutex))
6057 goto out;
6058
6059 /*
6060 * at this point we have a head with no other entries. Go
6061 * ahead and process it.
6062 */
6063 head->node.in_tree = 0;
6064 rb_erase(&head->href_node, &delayed_refs->href_root);
6065
6066 atomic_dec(&delayed_refs->num_entries);
6067
6068 /*
6069 * we don't take a ref on the node because we're removing it from the
6070 * tree, so we just steal the ref the tree was holding.
6071 */
6072 delayed_refs->num_heads--;
6073 if (head->processing == 0)
6074 delayed_refs->num_heads_ready--;
6075 head->processing = 0;
6076 spin_unlock(&head->lock);
6077 spin_unlock(&delayed_refs->lock);
6078
6079 BUG_ON(head->extent_op);
6080 if (head->must_insert_reserved)
6081 ret = 1;
6082
6083 mutex_unlock(&head->mutex);
6084 btrfs_put_delayed_ref(&head->node);
6085 return ret;
6086 out:
6087 spin_unlock(&head->lock);
6088
6089 out_delayed_unlock:
6090 spin_unlock(&delayed_refs->lock);
6091 return 0;
6092 }
6093
6094 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
6095 struct btrfs_root *root,
6096 struct extent_buffer *buf,
6097 u64 parent, int last_ref)
6098 {
6099 struct btrfs_block_group_cache *cache = NULL;
6100 int pin = 1;
6101 int ret;
6102
6103 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
6104 ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
6105 buf->start, buf->len,
6106 parent, root->root_key.objectid,
6107 btrfs_header_level(buf),
6108 BTRFS_DROP_DELAYED_REF, NULL, 0);
6109 BUG_ON(ret); /* -ENOMEM */
6110 }
6111
6112 if (!last_ref)
6113 return;
6114
6115 cache = btrfs_lookup_block_group(root->fs_info, buf->start);
6116
6117 if (btrfs_header_generation(buf) == trans->transid) {
6118 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
6119 ret = check_ref_cleanup(trans, root, buf->start);
6120 if (!ret)
6121 goto out;
6122 }
6123
6124 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
6125 pin_down_extent(root, cache, buf->start, buf->len, 1);
6126 goto out;
6127 }
6128
6129 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
6130
6131 btrfs_add_free_space(cache, buf->start, buf->len);
6132 btrfs_update_reserved_bytes(cache, buf->len, RESERVE_FREE);
6133 trace_btrfs_reserved_extent_free(root, buf->start, buf->len);
6134 pin = 0;
6135 }
6136 out:
6137 if (pin)
6138 add_pinned_bytes(root->fs_info, buf->len,
6139 btrfs_header_level(buf),
6140 root->root_key.objectid);
6141
6142 /*
6143 * Deleting the buffer, clear the corrupt flag since it doesn't matter
6144 * anymore.
6145 */
6146 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
6147 btrfs_put_block_group(cache);
6148 }
6149
6150 /* Can return -ENOMEM */
6151 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_root *root,
6152 u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
6153 u64 owner, u64 offset, int no_quota)
6154 {
6155 int ret;
6156 struct btrfs_fs_info *fs_info = root->fs_info;
6157
6158 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
6159 if (unlikely(test_bit(BTRFS_ROOT_DUMMY_ROOT, &root->state)))
6160 return 0;
6161 #endif
6162 add_pinned_bytes(root->fs_info, num_bytes, owner, root_objectid);
6163
6164 /*
6165 * tree log blocks never actually go into the extent allocation
6166 * tree, just update pinning info and exit early.
6167 */
6168 if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
6169 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
6170 /* unlocks the pinned mutex */
6171 btrfs_pin_extent(root, bytenr, num_bytes, 1);
6172 ret = 0;
6173 } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
6174 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
6175 num_bytes,
6176 parent, root_objectid, (int)owner,
6177 BTRFS_DROP_DELAYED_REF, NULL, no_quota);
6178 } else {
6179 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
6180 num_bytes,
6181 parent, root_objectid, owner,
6182 offset, BTRFS_DROP_DELAYED_REF,
6183 NULL, no_quota);
6184 }
6185 return ret;
6186 }
6187
6188 static u64 stripe_align(struct btrfs_root *root,
6189 struct btrfs_block_group_cache *cache,
6190 u64 val, u64 num_bytes)
6191 {
6192 u64 ret = ALIGN(val, root->stripesize);
6193 return ret;
6194 }
6195
6196 /*
6197 * when we wait for progress in the block group caching, its because
6198 * our allocation attempt failed at least once. So, we must sleep
6199 * and let some progress happen before we try again.
6200 *
6201 * This function will sleep at least once waiting for new free space to
6202 * show up, and then it will check the block group free space numbers
6203 * for our min num_bytes. Another option is to have it go ahead
6204 * and look in the rbtree for a free extent of a given size, but this
6205 * is a good start.
6206 *
6207 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
6208 * any of the information in this block group.
6209 */
6210 static noinline void
6211 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
6212 u64 num_bytes)
6213 {
6214 struct btrfs_caching_control *caching_ctl;
6215
6216 caching_ctl = get_caching_control(cache);
6217 if (!caching_ctl)
6218 return;
6219
6220 wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
6221 (cache->free_space_ctl->free_space >= num_bytes));
6222
6223 put_caching_control(caching_ctl);
6224 }
6225
6226 static noinline int
6227 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
6228 {
6229 struct btrfs_caching_control *caching_ctl;
6230 int ret = 0;
6231
6232 caching_ctl = get_caching_control(cache);
6233 if (!caching_ctl)
6234 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
6235
6236 wait_event(caching_ctl->wait, block_group_cache_done(cache));
6237 if (cache->cached == BTRFS_CACHE_ERROR)
6238 ret = -EIO;
6239 put_caching_control(caching_ctl);
6240 return ret;
6241 }
6242
6243 int __get_raid_index(u64 flags)
6244 {
6245 if (flags & BTRFS_BLOCK_GROUP_RAID10)
6246 return BTRFS_RAID_RAID10;
6247 else if (flags & BTRFS_BLOCK_GROUP_RAID1)
6248 return BTRFS_RAID_RAID1;
6249 else if (flags & BTRFS_BLOCK_GROUP_DUP)
6250 return BTRFS_RAID_DUP;
6251 else if (flags & BTRFS_BLOCK_GROUP_RAID0)
6252 return BTRFS_RAID_RAID0;
6253 else if (flags & BTRFS_BLOCK_GROUP_RAID5)
6254 return BTRFS_RAID_RAID5;
6255 else if (flags & BTRFS_BLOCK_GROUP_RAID6)
6256 return BTRFS_RAID_RAID6;
6257
6258 return BTRFS_RAID_SINGLE; /* BTRFS_BLOCK_GROUP_SINGLE */
6259 }
6260
6261 int get_block_group_index(struct btrfs_block_group_cache *cache)
6262 {
6263 return __get_raid_index(cache->flags);
6264 }
6265
6266 static const char *btrfs_raid_type_names[BTRFS_NR_RAID_TYPES] = {
6267 [BTRFS_RAID_RAID10] = "raid10",
6268 [BTRFS_RAID_RAID1] = "raid1",
6269 [BTRFS_RAID_DUP] = "dup",
6270 [BTRFS_RAID_RAID0] = "raid0",
6271 [BTRFS_RAID_SINGLE] = "single",
6272 [BTRFS_RAID_RAID5] = "raid5",
6273 [BTRFS_RAID_RAID6] = "raid6",
6274 };
6275
6276 static const char *get_raid_name(enum btrfs_raid_types type)
6277 {
6278 if (type >= BTRFS_NR_RAID_TYPES)
6279 return NULL;
6280
6281 return btrfs_raid_type_names[type];
6282 }
6283
6284 enum btrfs_loop_type {
6285 LOOP_CACHING_NOWAIT = 0,
6286 LOOP_CACHING_WAIT = 1,
6287 LOOP_ALLOC_CHUNK = 2,
6288 LOOP_NO_EMPTY_SIZE = 3,
6289 };
6290
6291 /*
6292 * walks the btree of allocated extents and find a hole of a given size.
6293 * The key ins is changed to record the hole:
6294 * ins->objectid == start position
6295 * ins->flags = BTRFS_EXTENT_ITEM_KEY
6296 * ins->offset == the size of the hole.
6297 * Any available blocks before search_start are skipped.
6298 *
6299 * If there is no suitable free space, we will record the max size of
6300 * the free space extent currently.
6301 */
6302 static noinline int find_free_extent(struct btrfs_root *orig_root,
6303 u64 num_bytes, u64 empty_size,
6304 u64 hint_byte, struct btrfs_key *ins,
6305 u64 flags)
6306 {
6307 int ret = 0;
6308 struct btrfs_root *root = orig_root->fs_info->extent_root;
6309 struct btrfs_free_cluster *last_ptr = NULL;
6310 struct btrfs_block_group_cache *block_group = NULL;
6311 u64 search_start = 0;
6312 u64 max_extent_size = 0;
6313 int empty_cluster = 2 * 1024 * 1024;
6314 struct btrfs_space_info *space_info;
6315 int loop = 0;
6316 int index = __get_raid_index(flags);
6317 int alloc_type = (flags & BTRFS_BLOCK_GROUP_DATA) ?
6318 RESERVE_ALLOC_NO_ACCOUNT : RESERVE_ALLOC;
6319 bool failed_cluster_refill = false;
6320 bool failed_alloc = false;
6321 bool use_cluster = true;
6322 bool have_caching_bg = false;
6323
6324 WARN_ON(num_bytes < root->sectorsize);
6325 btrfs_set_key_type(ins, BTRFS_EXTENT_ITEM_KEY);
6326 ins->objectid = 0;
6327 ins->offset = 0;
6328
6329 trace_find_free_extent(orig_root, num_bytes, empty_size, flags);
6330
6331 space_info = __find_space_info(root->fs_info, flags);
6332 if (!space_info) {
6333 btrfs_err(root->fs_info, "No space info for %llu", flags);
6334 return -ENOSPC;
6335 }
6336
6337 /*
6338 * If the space info is for both data and metadata it means we have a
6339 * small filesystem and we can't use the clustering stuff.
6340 */
6341 if (btrfs_mixed_space_info(space_info))
6342 use_cluster = false;
6343
6344 if (flags & BTRFS_BLOCK_GROUP_METADATA && use_cluster) {
6345 last_ptr = &root->fs_info->meta_alloc_cluster;
6346 if (!btrfs_test_opt(root, SSD))
6347 empty_cluster = 64 * 1024;
6348 }
6349
6350 if ((flags & BTRFS_BLOCK_GROUP_DATA) && use_cluster &&
6351 btrfs_test_opt(root, SSD)) {
6352 last_ptr = &root->fs_info->data_alloc_cluster;
6353 }
6354
6355 if (last_ptr) {
6356 spin_lock(&last_ptr->lock);
6357 if (last_ptr->block_group)
6358 hint_byte = last_ptr->window_start;
6359 spin_unlock(&last_ptr->lock);
6360 }
6361
6362 search_start = max(search_start, first_logical_byte(root, 0));
6363 search_start = max(search_start, hint_byte);
6364
6365 if (!last_ptr)
6366 empty_cluster = 0;
6367
6368 if (search_start == hint_byte) {
6369 block_group = btrfs_lookup_block_group(root->fs_info,
6370 search_start);
6371 /*
6372 * we don't want to use the block group if it doesn't match our
6373 * allocation bits, or if its not cached.
6374 *
6375 * However if we are re-searching with an ideal block group
6376 * picked out then we don't care that the block group is cached.
6377 */
6378 if (block_group && block_group_bits(block_group, flags) &&
6379 block_group->cached != BTRFS_CACHE_NO) {
6380 down_read(&space_info->groups_sem);
6381 if (list_empty(&block_group->list) ||
6382 block_group->ro) {
6383 /*
6384 * someone is removing this block group,
6385 * we can't jump into the have_block_group
6386 * target because our list pointers are not
6387 * valid
6388 */
6389 btrfs_put_block_group(block_group);
6390 up_read(&space_info->groups_sem);
6391 } else {
6392 index = get_block_group_index(block_group);
6393 goto have_block_group;
6394 }
6395 } else if (block_group) {
6396 btrfs_put_block_group(block_group);
6397 }
6398 }
6399 search:
6400 have_caching_bg = false;
6401 down_read(&space_info->groups_sem);
6402 list_for_each_entry(block_group, &space_info->block_groups[index],
6403 list) {
6404 u64 offset;
6405 int cached;
6406
6407 btrfs_get_block_group(block_group);
6408 search_start = block_group->key.objectid;
6409
6410 /*
6411 * this can happen if we end up cycling through all the
6412 * raid types, but we want to make sure we only allocate
6413 * for the proper type.
6414 */
6415 if (!block_group_bits(block_group, flags)) {
6416 u64 extra = BTRFS_BLOCK_GROUP_DUP |
6417 BTRFS_BLOCK_GROUP_RAID1 |
6418 BTRFS_BLOCK_GROUP_RAID5 |
6419 BTRFS_BLOCK_GROUP_RAID6 |
6420 BTRFS_BLOCK_GROUP_RAID10;
6421
6422 /*
6423 * if they asked for extra copies and this block group
6424 * doesn't provide them, bail. This does allow us to
6425 * fill raid0 from raid1.
6426 */
6427 if ((flags & extra) && !(block_group->flags & extra))
6428 goto loop;
6429 }
6430
6431 have_block_group:
6432 cached = block_group_cache_done(block_group);
6433 if (unlikely(!cached)) {
6434 ret = cache_block_group(block_group, 0);
6435 BUG_ON(ret < 0);
6436 ret = 0;
6437 }
6438
6439 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
6440 goto loop;
6441 if (unlikely(block_group->ro))
6442 goto loop;
6443
6444 /*
6445 * Ok we want to try and use the cluster allocator, so
6446 * lets look there
6447 */
6448 if (last_ptr) {
6449 struct btrfs_block_group_cache *used_block_group;
6450 unsigned long aligned_cluster;
6451 /*
6452 * the refill lock keeps out other
6453 * people trying to start a new cluster
6454 */
6455 spin_lock(&last_ptr->refill_lock);
6456 used_block_group = last_ptr->block_group;
6457 if (used_block_group != block_group &&
6458 (!used_block_group ||
6459 used_block_group->ro ||
6460 !block_group_bits(used_block_group, flags)))
6461 goto refill_cluster;
6462
6463 if (used_block_group != block_group)
6464 btrfs_get_block_group(used_block_group);
6465
6466 offset = btrfs_alloc_from_cluster(used_block_group,
6467 last_ptr,
6468 num_bytes,
6469 used_block_group->key.objectid,
6470 &max_extent_size);
6471 if (offset) {
6472 /* we have a block, we're done */
6473 spin_unlock(&last_ptr->refill_lock);
6474 trace_btrfs_reserve_extent_cluster(root,
6475 used_block_group,
6476 search_start, num_bytes);
6477 if (used_block_group != block_group) {
6478 btrfs_put_block_group(block_group);
6479 block_group = used_block_group;
6480 }
6481 goto checks;
6482 }
6483
6484 WARN_ON(last_ptr->block_group != used_block_group);
6485 if (used_block_group != block_group)
6486 btrfs_put_block_group(used_block_group);
6487 refill_cluster:
6488 /* If we are on LOOP_NO_EMPTY_SIZE, we can't
6489 * set up a new clusters, so lets just skip it
6490 * and let the allocator find whatever block
6491 * it can find. If we reach this point, we
6492 * will have tried the cluster allocator
6493 * plenty of times and not have found
6494 * anything, so we are likely way too
6495 * fragmented for the clustering stuff to find
6496 * anything.
6497 *
6498 * However, if the cluster is taken from the
6499 * current block group, release the cluster
6500 * first, so that we stand a better chance of
6501 * succeeding in the unclustered
6502 * allocation. */
6503 if (loop >= LOOP_NO_EMPTY_SIZE &&
6504 last_ptr->block_group != block_group) {
6505 spin_unlock(&last_ptr->refill_lock);
6506 goto unclustered_alloc;
6507 }
6508
6509 /*
6510 * this cluster didn't work out, free it and
6511 * start over
6512 */
6513 btrfs_return_cluster_to_free_space(NULL, last_ptr);
6514
6515 if (loop >= LOOP_NO_EMPTY_SIZE) {
6516 spin_unlock(&last_ptr->refill_lock);
6517 goto unclustered_alloc;
6518 }
6519
6520 aligned_cluster = max_t(unsigned long,
6521 empty_cluster + empty_size,
6522 block_group->full_stripe_len);
6523
6524 /* allocate a cluster in this block group */
6525 ret = btrfs_find_space_cluster(root, block_group,
6526 last_ptr, search_start,
6527 num_bytes,
6528 aligned_cluster);
6529 if (ret == 0) {
6530 /*
6531 * now pull our allocation out of this
6532 * cluster
6533 */
6534 offset = btrfs_alloc_from_cluster(block_group,
6535 last_ptr,
6536 num_bytes,
6537 search_start,
6538 &max_extent_size);
6539 if (offset) {
6540 /* we found one, proceed */
6541 spin_unlock(&last_ptr->refill_lock);
6542 trace_btrfs_reserve_extent_cluster(root,
6543 block_group, search_start,
6544 num_bytes);
6545 goto checks;
6546 }
6547 } else if (!cached && loop > LOOP_CACHING_NOWAIT
6548 && !failed_cluster_refill) {
6549 spin_unlock(&last_ptr->refill_lock);
6550
6551 failed_cluster_refill = true;
6552 wait_block_group_cache_progress(block_group,
6553 num_bytes + empty_cluster + empty_size);
6554 goto have_block_group;
6555 }
6556
6557 /*
6558 * at this point we either didn't find a cluster
6559 * or we weren't able to allocate a block from our
6560 * cluster. Free the cluster we've been trying
6561 * to use, and go to the next block group
6562 */
6563 btrfs_return_cluster_to_free_space(NULL, last_ptr);
6564 spin_unlock(&last_ptr->refill_lock);
6565 goto loop;
6566 }
6567
6568 unclustered_alloc:
6569 spin_lock(&block_group->free_space_ctl->tree_lock);
6570 if (cached &&
6571 block_group->free_space_ctl->free_space <
6572 num_bytes + empty_cluster + empty_size) {
6573 if (block_group->free_space_ctl->free_space >
6574 max_extent_size)
6575 max_extent_size =
6576 block_group->free_space_ctl->free_space;
6577 spin_unlock(&block_group->free_space_ctl->tree_lock);
6578 goto loop;
6579 }
6580 spin_unlock(&block_group->free_space_ctl->tree_lock);
6581
6582 offset = btrfs_find_space_for_alloc(block_group, search_start,
6583 num_bytes, empty_size,
6584 &max_extent_size);
6585 /*
6586 * If we didn't find a chunk, and we haven't failed on this
6587 * block group before, and this block group is in the middle of
6588 * caching and we are ok with waiting, then go ahead and wait
6589 * for progress to be made, and set failed_alloc to true.
6590 *
6591 * If failed_alloc is true then we've already waited on this
6592 * block group once and should move on to the next block group.
6593 */
6594 if (!offset && !failed_alloc && !cached &&
6595 loop > LOOP_CACHING_NOWAIT) {
6596 wait_block_group_cache_progress(block_group,
6597 num_bytes + empty_size);
6598 failed_alloc = true;
6599 goto have_block_group;
6600 } else if (!offset) {
6601 if (!cached)
6602 have_caching_bg = true;
6603 goto loop;
6604 }
6605 checks:
6606 search_start = stripe_align(root, block_group,
6607 offset, num_bytes);
6608
6609 /* move on to the next group */
6610 if (search_start + num_bytes >
6611 block_group->key.objectid + block_group->key.offset) {
6612 btrfs_add_free_space(block_group, offset, num_bytes);
6613 goto loop;
6614 }
6615
6616 if (offset < search_start)
6617 btrfs_add_free_space(block_group, offset,
6618 search_start - offset);
6619 BUG_ON(offset > search_start);
6620
6621 ret = btrfs_update_reserved_bytes(block_group, num_bytes,
6622 alloc_type);
6623 if (ret == -EAGAIN) {
6624 btrfs_add_free_space(block_group, offset, num_bytes);
6625 goto loop;
6626 }
6627
6628 /* we are all good, lets return */
6629 ins->objectid = search_start;
6630 ins->offset = num_bytes;
6631
6632 trace_btrfs_reserve_extent(orig_root, block_group,
6633 search_start, num_bytes);
6634 btrfs_put_block_group(block_group);
6635 break;
6636 loop:
6637 failed_cluster_refill = false;
6638 failed_alloc = false;
6639 BUG_ON(index != get_block_group_index(block_group));
6640 btrfs_put_block_group(block_group);
6641 }
6642 up_read(&space_info->groups_sem);
6643
6644 if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
6645 goto search;
6646
6647 if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
6648 goto search;
6649
6650 /*
6651 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
6652 * caching kthreads as we move along
6653 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
6654 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
6655 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
6656 * again
6657 */
6658 if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
6659 index = 0;
6660 loop++;
6661 if (loop == LOOP_ALLOC_CHUNK) {
6662 struct btrfs_trans_handle *trans;
6663 int exist = 0;
6664
6665 trans = current->journal_info;
6666 if (trans)
6667 exist = 1;
6668 else
6669 trans = btrfs_join_transaction(root);
6670
6671 if (IS_ERR(trans)) {
6672 ret = PTR_ERR(trans);
6673 goto out;
6674 }
6675
6676 ret = do_chunk_alloc(trans, root, flags,
6677 CHUNK_ALLOC_FORCE);
6678 /*
6679 * Do not bail out on ENOSPC since we
6680 * can do more things.
6681 */
6682 if (ret < 0 && ret != -ENOSPC)
6683 btrfs_abort_transaction(trans,
6684 root, ret);
6685 else
6686 ret = 0;
6687 if (!exist)
6688 btrfs_end_transaction(trans, root);
6689 if (ret)
6690 goto out;
6691 }
6692
6693 if (loop == LOOP_NO_EMPTY_SIZE) {
6694 empty_size = 0;
6695 empty_cluster = 0;
6696 }
6697
6698 goto search;
6699 } else if (!ins->objectid) {
6700 ret = -ENOSPC;
6701 } else if (ins->objectid) {
6702 ret = 0;
6703 }
6704 out:
6705 if (ret == -ENOSPC)
6706 ins->offset = max_extent_size;
6707 return ret;
6708 }
6709
6710 static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
6711 int dump_block_groups)
6712 {
6713 struct btrfs_block_group_cache *cache;
6714 int index = 0;
6715
6716 spin_lock(&info->lock);
6717 printk(KERN_INFO "BTRFS: space_info %llu has %llu free, is %sfull\n",
6718 info->flags,
6719 info->total_bytes - info->bytes_used - info->bytes_pinned -
6720 info->bytes_reserved - info->bytes_readonly,
6721 (info->full) ? "" : "not ");
6722 printk(KERN_INFO "BTRFS: space_info total=%llu, used=%llu, pinned=%llu, "
6723 "reserved=%llu, may_use=%llu, readonly=%llu\n",
6724 info->total_bytes, info->bytes_used, info->bytes_pinned,
6725 info->bytes_reserved, info->bytes_may_use,
6726 info->bytes_readonly);
6727 spin_unlock(&info->lock);
6728
6729 if (!dump_block_groups)
6730 return;
6731
6732 down_read(&info->groups_sem);
6733 again:
6734 list_for_each_entry(cache, &info->block_groups[index], list) {
6735 spin_lock(&cache->lock);
6736 printk(KERN_INFO "BTRFS: "
6737 "block group %llu has %llu bytes, "
6738 "%llu used %llu pinned %llu reserved %s\n",
6739 cache->key.objectid, cache->key.offset,
6740 btrfs_block_group_used(&cache->item), cache->pinned,
6741 cache->reserved, cache->ro ? "[readonly]" : "");
6742 btrfs_dump_free_space(cache, bytes);
6743 spin_unlock(&cache->lock);
6744 }
6745 if (++index < BTRFS_NR_RAID_TYPES)
6746 goto again;
6747 up_read(&info->groups_sem);
6748 }
6749
6750 int btrfs_reserve_extent(struct btrfs_root *root,
6751 u64 num_bytes, u64 min_alloc_size,
6752 u64 empty_size, u64 hint_byte,
6753 struct btrfs_key *ins, int is_data)
6754 {
6755 bool final_tried = false;
6756 u64 flags;
6757 int ret;
6758
6759 flags = btrfs_get_alloc_profile(root, is_data);
6760 again:
6761 WARN_ON(num_bytes < root->sectorsize);
6762 ret = find_free_extent(root, num_bytes, empty_size, hint_byte, ins,
6763 flags);
6764
6765 if (ret == -ENOSPC) {
6766 if (!final_tried && ins->offset) {
6767 num_bytes = min(num_bytes >> 1, ins->offset);
6768 num_bytes = round_down(num_bytes, root->sectorsize);
6769 num_bytes = max(num_bytes, min_alloc_size);
6770 if (num_bytes == min_alloc_size)
6771 final_tried = true;
6772 goto again;
6773 } else if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
6774 struct btrfs_space_info *sinfo;
6775
6776 sinfo = __find_space_info(root->fs_info, flags);
6777 btrfs_err(root->fs_info, "allocation failed flags %llu, wanted %llu",
6778 flags, num_bytes);
6779 if (sinfo)
6780 dump_space_info(sinfo, num_bytes, 1);
6781 }
6782 }
6783
6784 return ret;
6785 }
6786
6787 static int __btrfs_free_reserved_extent(struct btrfs_root *root,
6788 u64 start, u64 len, int pin)
6789 {
6790 struct btrfs_block_group_cache *cache;
6791 int ret = 0;
6792
6793 cache = btrfs_lookup_block_group(root->fs_info, start);
6794 if (!cache) {
6795 btrfs_err(root->fs_info, "Unable to find block group for %llu",
6796 start);
6797 return -ENOSPC;
6798 }
6799
6800 if (btrfs_test_opt(root, DISCARD))
6801 ret = btrfs_discard_extent(root, start, len, NULL);
6802
6803 if (pin)
6804 pin_down_extent(root, cache, start, len, 1);
6805 else {
6806 btrfs_add_free_space(cache, start, len);
6807 btrfs_update_reserved_bytes(cache, len, RESERVE_FREE);
6808 }
6809 btrfs_put_block_group(cache);
6810
6811 trace_btrfs_reserved_extent_free(root, start, len);
6812
6813 return ret;
6814 }
6815
6816 int btrfs_free_reserved_extent(struct btrfs_root *root,
6817 u64 start, u64 len)
6818 {
6819 return __btrfs_free_reserved_extent(root, start, len, 0);
6820 }
6821
6822 int btrfs_free_and_pin_reserved_extent(struct btrfs_root *root,
6823 u64 start, u64 len)
6824 {
6825 return __btrfs_free_reserved_extent(root, start, len, 1);
6826 }
6827
6828 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
6829 struct btrfs_root *root,
6830 u64 parent, u64 root_objectid,
6831 u64 flags, u64 owner, u64 offset,
6832 struct btrfs_key *ins, int ref_mod)
6833 {
6834 int ret;
6835 struct btrfs_fs_info *fs_info = root->fs_info;
6836 struct btrfs_extent_item *extent_item;
6837 struct btrfs_extent_inline_ref *iref;
6838 struct btrfs_path *path;
6839 struct extent_buffer *leaf;
6840 int type;
6841 u32 size;
6842
6843 if (parent > 0)
6844 type = BTRFS_SHARED_DATA_REF_KEY;
6845 else
6846 type = BTRFS_EXTENT_DATA_REF_KEY;
6847
6848 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
6849
6850 path = btrfs_alloc_path();
6851 if (!path)
6852 return -ENOMEM;
6853
6854 path->leave_spinning = 1;
6855 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
6856 ins, size);
6857 if (ret) {
6858 btrfs_free_path(path);
6859 return ret;
6860 }
6861
6862 leaf = path->nodes[0];
6863 extent_item = btrfs_item_ptr(leaf, path->slots[0],
6864 struct btrfs_extent_item);
6865 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
6866 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
6867 btrfs_set_extent_flags(leaf, extent_item,
6868 flags | BTRFS_EXTENT_FLAG_DATA);
6869
6870 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
6871 btrfs_set_extent_inline_ref_type(leaf, iref, type);
6872 if (parent > 0) {
6873 struct btrfs_shared_data_ref *ref;
6874 ref = (struct btrfs_shared_data_ref *)(iref + 1);
6875 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
6876 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
6877 } else {
6878 struct btrfs_extent_data_ref *ref;
6879 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
6880 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
6881 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
6882 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
6883 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
6884 }
6885
6886 btrfs_mark_buffer_dirty(path->nodes[0]);
6887 btrfs_free_path(path);
6888
6889 /* Always set parent to 0 here since its exclusive anyway. */
6890 ret = btrfs_qgroup_record_ref(trans, fs_info, root_objectid,
6891 ins->objectid, ins->offset,
6892 BTRFS_QGROUP_OPER_ADD_EXCL, 0);
6893 if (ret)
6894 return ret;
6895
6896 ret = update_block_group(root, ins->objectid, ins->offset, 1);
6897 if (ret) { /* -ENOENT, logic error */
6898 btrfs_err(fs_info, "update block group failed for %llu %llu",
6899 ins->objectid, ins->offset);
6900 BUG();
6901 }
6902 trace_btrfs_reserved_extent_alloc(root, ins->objectid, ins->offset);
6903 return ret;
6904 }
6905
6906 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
6907 struct btrfs_root *root,
6908 u64 parent, u64 root_objectid,
6909 u64 flags, struct btrfs_disk_key *key,
6910 int level, struct btrfs_key *ins,
6911 int no_quota)
6912 {
6913 int ret;
6914 struct btrfs_fs_info *fs_info = root->fs_info;
6915 struct btrfs_extent_item *extent_item;
6916 struct btrfs_tree_block_info *block_info;
6917 struct btrfs_extent_inline_ref *iref;
6918 struct btrfs_path *path;
6919 struct extent_buffer *leaf;
6920 u32 size = sizeof(*extent_item) + sizeof(*iref);
6921 u64 num_bytes = ins->offset;
6922 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
6923 SKINNY_METADATA);
6924
6925 if (!skinny_metadata)
6926 size += sizeof(*block_info);
6927
6928 path = btrfs_alloc_path();
6929 if (!path) {
6930 btrfs_free_and_pin_reserved_extent(root, ins->objectid,
6931 root->leafsize);
6932 return -ENOMEM;
6933 }
6934
6935 path->leave_spinning = 1;
6936 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
6937 ins, size);
6938 if (ret) {
6939 btrfs_free_and_pin_reserved_extent(root, ins->objectid,
6940 root->leafsize);
6941 btrfs_free_path(path);
6942 return ret;
6943 }
6944
6945 leaf = path->nodes[0];
6946 extent_item = btrfs_item_ptr(leaf, path->slots[0],
6947 struct btrfs_extent_item);
6948 btrfs_set_extent_refs(leaf, extent_item, 1);
6949 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
6950 btrfs_set_extent_flags(leaf, extent_item,
6951 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
6952
6953 if (skinny_metadata) {
6954 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
6955 num_bytes = root->leafsize;
6956 } else {
6957 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
6958 btrfs_set_tree_block_key(leaf, block_info, key);
6959 btrfs_set_tree_block_level(leaf, block_info, level);
6960 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
6961 }
6962
6963 if (parent > 0) {
6964 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
6965 btrfs_set_extent_inline_ref_type(leaf, iref,
6966 BTRFS_SHARED_BLOCK_REF_KEY);
6967 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
6968 } else {
6969 btrfs_set_extent_inline_ref_type(leaf, iref,
6970 BTRFS_TREE_BLOCK_REF_KEY);
6971 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
6972 }
6973
6974 btrfs_mark_buffer_dirty(leaf);
6975 btrfs_free_path(path);
6976
6977 if (!no_quota) {
6978 ret = btrfs_qgroup_record_ref(trans, fs_info, root_objectid,
6979 ins->objectid, num_bytes,
6980 BTRFS_QGROUP_OPER_ADD_EXCL, 0);
6981 if (ret)
6982 return ret;
6983 }
6984
6985 ret = update_block_group(root, ins->objectid, root->leafsize, 1);
6986 if (ret) { /* -ENOENT, logic error */
6987 btrfs_err(fs_info, "update block group failed for %llu %llu",
6988 ins->objectid, ins->offset);
6989 BUG();
6990 }
6991
6992 trace_btrfs_reserved_extent_alloc(root, ins->objectid, root->leafsize);
6993 return ret;
6994 }
6995
6996 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
6997 struct btrfs_root *root,
6998 u64 root_objectid, u64 owner,
6999 u64 offset, struct btrfs_key *ins)
7000 {
7001 int ret;
7002
7003 BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
7004
7005 ret = btrfs_add_delayed_data_ref(root->fs_info, trans, ins->objectid,
7006 ins->offset, 0,
7007 root_objectid, owner, offset,
7008 BTRFS_ADD_DELAYED_EXTENT, NULL, 0);
7009 return ret;
7010 }
7011
7012 /*
7013 * this is used by the tree logging recovery code. It records that
7014 * an extent has been allocated and makes sure to clear the free
7015 * space cache bits as well
7016 */
7017 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
7018 struct btrfs_root *root,
7019 u64 root_objectid, u64 owner, u64 offset,
7020 struct btrfs_key *ins)
7021 {
7022 int ret;
7023 struct btrfs_block_group_cache *block_group;
7024
7025 /*
7026 * Mixed block groups will exclude before processing the log so we only
7027 * need to do the exlude dance if this fs isn't mixed.
7028 */
7029 if (!btrfs_fs_incompat(root->fs_info, MIXED_GROUPS)) {
7030 ret = __exclude_logged_extent(root, ins->objectid, ins->offset);
7031 if (ret)
7032 return ret;
7033 }
7034
7035 block_group = btrfs_lookup_block_group(root->fs_info, ins->objectid);
7036 if (!block_group)
7037 return -EINVAL;
7038
7039 ret = btrfs_update_reserved_bytes(block_group, ins->offset,
7040 RESERVE_ALLOC_NO_ACCOUNT);
7041 BUG_ON(ret); /* logic error */
7042 ret = alloc_reserved_file_extent(trans, root, 0, root_objectid,
7043 0, owner, offset, ins, 1);
7044 btrfs_put_block_group(block_group);
7045 return ret;
7046 }
7047
7048 static struct extent_buffer *
7049 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
7050 u64 bytenr, u32 blocksize, int level)
7051 {
7052 struct extent_buffer *buf;
7053
7054 buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
7055 if (!buf)
7056 return ERR_PTR(-ENOMEM);
7057 btrfs_set_header_generation(buf, trans->transid);
7058 btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
7059 btrfs_tree_lock(buf);
7060 clean_tree_block(trans, root, buf);
7061 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
7062
7063 btrfs_set_lock_blocking(buf);
7064 btrfs_set_buffer_uptodate(buf);
7065
7066 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
7067 /*
7068 * we allow two log transactions at a time, use different
7069 * EXENT bit to differentiate dirty pages.
7070 */
7071 if (root->log_transid % 2 == 0)
7072 set_extent_dirty(&root->dirty_log_pages, buf->start,
7073 buf->start + buf->len - 1, GFP_NOFS);
7074 else
7075 set_extent_new(&root->dirty_log_pages, buf->start,
7076 buf->start + buf->len - 1, GFP_NOFS);
7077 } else {
7078 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
7079 buf->start + buf->len - 1, GFP_NOFS);
7080 }
7081 trans->blocks_used++;
7082 /* this returns a buffer locked for blocking */
7083 return buf;
7084 }
7085
7086 static struct btrfs_block_rsv *
7087 use_block_rsv(struct btrfs_trans_handle *trans,
7088 struct btrfs_root *root, u32 blocksize)
7089 {
7090 struct btrfs_block_rsv *block_rsv;
7091 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
7092 int ret;
7093 bool global_updated = false;
7094
7095 block_rsv = get_block_rsv(trans, root);
7096
7097 if (unlikely(block_rsv->size == 0))
7098 goto try_reserve;
7099 again:
7100 ret = block_rsv_use_bytes(block_rsv, blocksize);
7101 if (!ret)
7102 return block_rsv;
7103
7104 if (block_rsv->failfast)
7105 return ERR_PTR(ret);
7106
7107 if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
7108 global_updated = true;
7109 update_global_block_rsv(root->fs_info);
7110 goto again;
7111 }
7112
7113 if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
7114 static DEFINE_RATELIMIT_STATE(_rs,
7115 DEFAULT_RATELIMIT_INTERVAL * 10,
7116 /*DEFAULT_RATELIMIT_BURST*/ 1);
7117 if (__ratelimit(&_rs))
7118 WARN(1, KERN_DEBUG
7119 "BTRFS: block rsv returned %d\n", ret);
7120 }
7121 try_reserve:
7122 ret = reserve_metadata_bytes(root, block_rsv, blocksize,
7123 BTRFS_RESERVE_NO_FLUSH);
7124 if (!ret)
7125 return block_rsv;
7126 /*
7127 * If we couldn't reserve metadata bytes try and use some from
7128 * the global reserve if its space type is the same as the global
7129 * reservation.
7130 */
7131 if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
7132 block_rsv->space_info == global_rsv->space_info) {
7133 ret = block_rsv_use_bytes(global_rsv, blocksize);
7134 if (!ret)
7135 return global_rsv;
7136 }
7137 return ERR_PTR(ret);
7138 }
7139
7140 static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
7141 struct btrfs_block_rsv *block_rsv, u32 blocksize)
7142 {
7143 block_rsv_add_bytes(block_rsv, blocksize, 0);
7144 block_rsv_release_bytes(fs_info, block_rsv, NULL, 0);
7145 }
7146
7147 /*
7148 * finds a free extent and does all the dirty work required for allocation
7149 * returns the key for the extent through ins, and a tree buffer for
7150 * the first block of the extent through buf.
7151 *
7152 * returns the tree buffer or NULL.
7153 */
7154 struct extent_buffer *btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
7155 struct btrfs_root *root, u32 blocksize,
7156 u64 parent, u64 root_objectid,
7157 struct btrfs_disk_key *key, int level,
7158 u64 hint, u64 empty_size)
7159 {
7160 struct btrfs_key ins;
7161 struct btrfs_block_rsv *block_rsv;
7162 struct extent_buffer *buf;
7163 u64 flags = 0;
7164 int ret;
7165 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
7166 SKINNY_METADATA);
7167
7168 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
7169 if (unlikely(test_bit(BTRFS_ROOT_DUMMY_ROOT, &root->state))) {
7170 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
7171 blocksize, level);
7172 if (!IS_ERR(buf))
7173 root->alloc_bytenr += blocksize;
7174 return buf;
7175 }
7176 #endif
7177 block_rsv = use_block_rsv(trans, root, blocksize);
7178 if (IS_ERR(block_rsv))
7179 return ERR_CAST(block_rsv);
7180
7181 ret = btrfs_reserve_extent(root, blocksize, blocksize,
7182 empty_size, hint, &ins, 0);
7183 if (ret) {
7184 unuse_block_rsv(root->fs_info, block_rsv, blocksize);
7185 return ERR_PTR(ret);
7186 }
7187
7188 buf = btrfs_init_new_buffer(trans, root, ins.objectid,
7189 blocksize, level);
7190 BUG_ON(IS_ERR(buf)); /* -ENOMEM */
7191
7192 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
7193 if (parent == 0)
7194 parent = ins.objectid;
7195 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7196 } else
7197 BUG_ON(parent > 0);
7198
7199 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
7200 struct btrfs_delayed_extent_op *extent_op;
7201 extent_op = btrfs_alloc_delayed_extent_op();
7202 BUG_ON(!extent_op); /* -ENOMEM */
7203 if (key)
7204 memcpy(&extent_op->key, key, sizeof(extent_op->key));
7205 else
7206 memset(&extent_op->key, 0, sizeof(extent_op->key));
7207 extent_op->flags_to_set = flags;
7208 if (skinny_metadata)
7209 extent_op->update_key = 0;
7210 else
7211 extent_op->update_key = 1;
7212 extent_op->update_flags = 1;
7213 extent_op->is_data = 0;
7214 extent_op->level = level;
7215
7216 ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
7217 ins.objectid,
7218 ins.offset, parent, root_objectid,
7219 level, BTRFS_ADD_DELAYED_EXTENT,
7220 extent_op, 0);
7221 BUG_ON(ret); /* -ENOMEM */
7222 }
7223 return buf;
7224 }
7225
7226 struct walk_control {
7227 u64 refs[BTRFS_MAX_LEVEL];
7228 u64 flags[BTRFS_MAX_LEVEL];
7229 struct btrfs_key update_progress;
7230 int stage;
7231 int level;
7232 int shared_level;
7233 int update_ref;
7234 int keep_locks;
7235 int reada_slot;
7236 int reada_count;
7237 int for_reloc;
7238 };
7239
7240 #define DROP_REFERENCE 1
7241 #define UPDATE_BACKREF 2
7242
7243 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
7244 struct btrfs_root *root,
7245 struct walk_control *wc,
7246 struct btrfs_path *path)
7247 {
7248 u64 bytenr;
7249 u64 generation;
7250 u64 refs;
7251 u64 flags;
7252 u32 nritems;
7253 u32 blocksize;
7254 struct btrfs_key key;
7255 struct extent_buffer *eb;
7256 int ret;
7257 int slot;
7258 int nread = 0;
7259
7260 if (path->slots[wc->level] < wc->reada_slot) {
7261 wc->reada_count = wc->reada_count * 2 / 3;
7262 wc->reada_count = max(wc->reada_count, 2);
7263 } else {
7264 wc->reada_count = wc->reada_count * 3 / 2;
7265 wc->reada_count = min_t(int, wc->reada_count,
7266 BTRFS_NODEPTRS_PER_BLOCK(root));
7267 }
7268
7269 eb = path->nodes[wc->level];
7270 nritems = btrfs_header_nritems(eb);
7271 blocksize = btrfs_level_size(root, wc->level - 1);
7272
7273 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
7274 if (nread >= wc->reada_count)
7275 break;
7276
7277 cond_resched();
7278 bytenr = btrfs_node_blockptr(eb, slot);
7279 generation = btrfs_node_ptr_generation(eb, slot);
7280
7281 if (slot == path->slots[wc->level])
7282 goto reada;
7283
7284 if (wc->stage == UPDATE_BACKREF &&
7285 generation <= root->root_key.offset)
7286 continue;
7287
7288 /* We don't lock the tree block, it's OK to be racy here */
7289 ret = btrfs_lookup_extent_info(trans, root, bytenr,
7290 wc->level - 1, 1, &refs,
7291 &flags);
7292 /* We don't care about errors in readahead. */
7293 if (ret < 0)
7294 continue;
7295 BUG_ON(refs == 0);
7296
7297 if (wc->stage == DROP_REFERENCE) {
7298 if (refs == 1)
7299 goto reada;
7300
7301 if (wc->level == 1 &&
7302 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7303 continue;
7304 if (!wc->update_ref ||
7305 generation <= root->root_key.offset)
7306 continue;
7307 btrfs_node_key_to_cpu(eb, &key, slot);
7308 ret = btrfs_comp_cpu_keys(&key,
7309 &wc->update_progress);
7310 if (ret < 0)
7311 continue;
7312 } else {
7313 if (wc->level == 1 &&
7314 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7315 continue;
7316 }
7317 reada:
7318 ret = readahead_tree_block(root, bytenr, blocksize,
7319 generation);
7320 if (ret)
7321 break;
7322 nread++;
7323 }
7324 wc->reada_slot = slot;
7325 }
7326
7327 /*
7328 * helper to process tree block while walking down the tree.
7329 *
7330 * when wc->stage == UPDATE_BACKREF, this function updates
7331 * back refs for pointers in the block.
7332 *
7333 * NOTE: return value 1 means we should stop walking down.
7334 */
7335 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
7336 struct btrfs_root *root,
7337 struct btrfs_path *path,
7338 struct walk_control *wc, int lookup_info)
7339 {
7340 int level = wc->level;
7341 struct extent_buffer *eb = path->nodes[level];
7342 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
7343 int ret;
7344
7345 if (wc->stage == UPDATE_BACKREF &&
7346 btrfs_header_owner(eb) != root->root_key.objectid)
7347 return 1;
7348
7349 /*
7350 * when reference count of tree block is 1, it won't increase
7351 * again. once full backref flag is set, we never clear it.
7352 */
7353 if (lookup_info &&
7354 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
7355 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
7356 BUG_ON(!path->locks[level]);
7357 ret = btrfs_lookup_extent_info(trans, root,
7358 eb->start, level, 1,
7359 &wc->refs[level],
7360 &wc->flags[level]);
7361 BUG_ON(ret == -ENOMEM);
7362 if (ret)
7363 return ret;
7364 BUG_ON(wc->refs[level] == 0);
7365 }
7366
7367 if (wc->stage == DROP_REFERENCE) {
7368 if (wc->refs[level] > 1)
7369 return 1;
7370
7371 if (path->locks[level] && !wc->keep_locks) {
7372 btrfs_tree_unlock_rw(eb, path->locks[level]);
7373 path->locks[level] = 0;
7374 }
7375 return 0;
7376 }
7377
7378 /* wc->stage == UPDATE_BACKREF */
7379 if (!(wc->flags[level] & flag)) {
7380 BUG_ON(!path->locks[level]);
7381 ret = btrfs_inc_ref(trans, root, eb, 1, wc->for_reloc);
7382 BUG_ON(ret); /* -ENOMEM */
7383 ret = btrfs_dec_ref(trans, root, eb, 0, wc->for_reloc);
7384 BUG_ON(ret); /* -ENOMEM */
7385 ret = btrfs_set_disk_extent_flags(trans, root, eb->start,
7386 eb->len, flag,
7387 btrfs_header_level(eb), 0);
7388 BUG_ON(ret); /* -ENOMEM */
7389 wc->flags[level] |= flag;
7390 }
7391
7392 /*
7393 * the block is shared by multiple trees, so it's not good to
7394 * keep the tree lock
7395 */
7396 if (path->locks[level] && level > 0) {
7397 btrfs_tree_unlock_rw(eb, path->locks[level]);
7398 path->locks[level] = 0;
7399 }
7400 return 0;
7401 }
7402
7403 /*
7404 * helper to process tree block pointer.
7405 *
7406 * when wc->stage == DROP_REFERENCE, this function checks
7407 * reference count of the block pointed to. if the block
7408 * is shared and we need update back refs for the subtree
7409 * rooted at the block, this function changes wc->stage to
7410 * UPDATE_BACKREF. if the block is shared and there is no
7411 * need to update back, this function drops the reference
7412 * to the block.
7413 *
7414 * NOTE: return value 1 means we should stop walking down.
7415 */
7416 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
7417 struct btrfs_root *root,
7418 struct btrfs_path *path,
7419 struct walk_control *wc, int *lookup_info)
7420 {
7421 u64 bytenr;
7422 u64 generation;
7423 u64 parent;
7424 u32 blocksize;
7425 struct btrfs_key key;
7426 struct extent_buffer *next;
7427 int level = wc->level;
7428 int reada = 0;
7429 int ret = 0;
7430
7431 generation = btrfs_node_ptr_generation(path->nodes[level],
7432 path->slots[level]);
7433 /*
7434 * if the lower level block was created before the snapshot
7435 * was created, we know there is no need to update back refs
7436 * for the subtree
7437 */
7438 if (wc->stage == UPDATE_BACKREF &&
7439 generation <= root->root_key.offset) {
7440 *lookup_info = 1;
7441 return 1;
7442 }
7443
7444 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
7445 blocksize = btrfs_level_size(root, level - 1);
7446
7447 next = btrfs_find_tree_block(root, bytenr, blocksize);
7448 if (!next) {
7449 next = btrfs_find_create_tree_block(root, bytenr, blocksize);
7450 if (!next)
7451 return -ENOMEM;
7452 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
7453 level - 1);
7454 reada = 1;
7455 }
7456 btrfs_tree_lock(next);
7457 btrfs_set_lock_blocking(next);
7458
7459 ret = btrfs_lookup_extent_info(trans, root, bytenr, level - 1, 1,
7460 &wc->refs[level - 1],
7461 &wc->flags[level - 1]);
7462 if (ret < 0) {
7463 btrfs_tree_unlock(next);
7464 return ret;
7465 }
7466
7467 if (unlikely(wc->refs[level - 1] == 0)) {
7468 btrfs_err(root->fs_info, "Missing references.");
7469 BUG();
7470 }
7471 *lookup_info = 0;
7472
7473 if (wc->stage == DROP_REFERENCE) {
7474 if (wc->refs[level - 1] > 1) {
7475 if (level == 1 &&
7476 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7477 goto skip;
7478
7479 if (!wc->update_ref ||
7480 generation <= root->root_key.offset)
7481 goto skip;
7482
7483 btrfs_node_key_to_cpu(path->nodes[level], &key,
7484 path->slots[level]);
7485 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
7486 if (ret < 0)
7487 goto skip;
7488
7489 wc->stage = UPDATE_BACKREF;
7490 wc->shared_level = level - 1;
7491 }
7492 } else {
7493 if (level == 1 &&
7494 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7495 goto skip;
7496 }
7497
7498 if (!btrfs_buffer_uptodate(next, generation, 0)) {
7499 btrfs_tree_unlock(next);
7500 free_extent_buffer(next);
7501 next = NULL;
7502 *lookup_info = 1;
7503 }
7504
7505 if (!next) {
7506 if (reada && level == 1)
7507 reada_walk_down(trans, root, wc, path);
7508 next = read_tree_block(root, bytenr, blocksize, generation);
7509 if (!next || !extent_buffer_uptodate(next)) {
7510 free_extent_buffer(next);
7511 return -EIO;
7512 }
7513 btrfs_tree_lock(next);
7514 btrfs_set_lock_blocking(next);
7515 }
7516
7517 level--;
7518 BUG_ON(level != btrfs_header_level(next));
7519 path->nodes[level] = next;
7520 path->slots[level] = 0;
7521 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7522 wc->level = level;
7523 if (wc->level == 1)
7524 wc->reada_slot = 0;
7525 return 0;
7526 skip:
7527 wc->refs[level - 1] = 0;
7528 wc->flags[level - 1] = 0;
7529 if (wc->stage == DROP_REFERENCE) {
7530 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
7531 parent = path->nodes[level]->start;
7532 } else {
7533 BUG_ON(root->root_key.objectid !=
7534 btrfs_header_owner(path->nodes[level]));
7535 parent = 0;
7536 }
7537
7538 ret = btrfs_free_extent(trans, root, bytenr, blocksize, parent,
7539 root->root_key.objectid, level - 1, 0, 0);
7540 BUG_ON(ret); /* -ENOMEM */
7541 }
7542 btrfs_tree_unlock(next);
7543 free_extent_buffer(next);
7544 *lookup_info = 1;
7545 return 1;
7546 }
7547
7548 /*
7549 * helper to process tree block while walking up the tree.
7550 *
7551 * when wc->stage == DROP_REFERENCE, this function drops
7552 * reference count on the block.
7553 *
7554 * when wc->stage == UPDATE_BACKREF, this function changes
7555 * wc->stage back to DROP_REFERENCE if we changed wc->stage
7556 * to UPDATE_BACKREF previously while processing the block.
7557 *
7558 * NOTE: return value 1 means we should stop walking up.
7559 */
7560 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
7561 struct btrfs_root *root,
7562 struct btrfs_path *path,
7563 struct walk_control *wc)
7564 {
7565 int ret;
7566 int level = wc->level;
7567 struct extent_buffer *eb = path->nodes[level];
7568 u64 parent = 0;
7569
7570 if (wc->stage == UPDATE_BACKREF) {
7571 BUG_ON(wc->shared_level < level);
7572 if (level < wc->shared_level)
7573 goto out;
7574
7575 ret = find_next_key(path, level + 1, &wc->update_progress);
7576 if (ret > 0)
7577 wc->update_ref = 0;
7578
7579 wc->stage = DROP_REFERENCE;
7580 wc->shared_level = -1;
7581 path->slots[level] = 0;
7582
7583 /*
7584 * check reference count again if the block isn't locked.
7585 * we should start walking down the tree again if reference
7586 * count is one.
7587 */
7588 if (!path->locks[level]) {
7589 BUG_ON(level == 0);
7590 btrfs_tree_lock(eb);
7591 btrfs_set_lock_blocking(eb);
7592 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7593
7594 ret = btrfs_lookup_extent_info(trans, root,
7595 eb->start, level, 1,
7596 &wc->refs[level],
7597 &wc->flags[level]);
7598 if (ret < 0) {
7599 btrfs_tree_unlock_rw(eb, path->locks[level]);
7600 path->locks[level] = 0;
7601 return ret;
7602 }
7603 BUG_ON(wc->refs[level] == 0);
7604 if (wc->refs[level] == 1) {
7605 btrfs_tree_unlock_rw(eb, path->locks[level]);
7606 path->locks[level] = 0;
7607 return 1;
7608 }
7609 }
7610 }
7611
7612 /* wc->stage == DROP_REFERENCE */
7613 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
7614
7615 if (wc->refs[level] == 1) {
7616 if (level == 0) {
7617 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
7618 ret = btrfs_dec_ref(trans, root, eb, 1,
7619 wc->for_reloc);
7620 else
7621 ret = btrfs_dec_ref(trans, root, eb, 0,
7622 wc->for_reloc);
7623 BUG_ON(ret); /* -ENOMEM */
7624 }
7625 /* make block locked assertion in clean_tree_block happy */
7626 if (!path->locks[level] &&
7627 btrfs_header_generation(eb) == trans->transid) {
7628 btrfs_tree_lock(eb);
7629 btrfs_set_lock_blocking(eb);
7630 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7631 }
7632 clean_tree_block(trans, root, eb);
7633 }
7634
7635 if (eb == root->node) {
7636 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
7637 parent = eb->start;
7638 else
7639 BUG_ON(root->root_key.objectid !=
7640 btrfs_header_owner(eb));
7641 } else {
7642 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
7643 parent = path->nodes[level + 1]->start;
7644 else
7645 BUG_ON(root->root_key.objectid !=
7646 btrfs_header_owner(path->nodes[level + 1]));
7647 }
7648
7649 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
7650 out:
7651 wc->refs[level] = 0;
7652 wc->flags[level] = 0;
7653 return 0;
7654 }
7655
7656 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
7657 struct btrfs_root *root,
7658 struct btrfs_path *path,
7659 struct walk_control *wc)
7660 {
7661 int level = wc->level;
7662 int lookup_info = 1;
7663 int ret;
7664
7665 while (level >= 0) {
7666 ret = walk_down_proc(trans, root, path, wc, lookup_info);
7667 if (ret > 0)
7668 break;
7669
7670 if (level == 0)
7671 break;
7672
7673 if (path->slots[level] >=
7674 btrfs_header_nritems(path->nodes[level]))
7675 break;
7676
7677 ret = do_walk_down(trans, root, path, wc, &lookup_info);
7678 if (ret > 0) {
7679 path->slots[level]++;
7680 continue;
7681 } else if (ret < 0)
7682 return ret;
7683 level = wc->level;
7684 }
7685 return 0;
7686 }
7687
7688 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
7689 struct btrfs_root *root,
7690 struct btrfs_path *path,
7691 struct walk_control *wc, int max_level)
7692 {
7693 int level = wc->level;
7694 int ret;
7695
7696 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
7697 while (level < max_level && path->nodes[level]) {
7698 wc->level = level;
7699 if (path->slots[level] + 1 <
7700 btrfs_header_nritems(path->nodes[level])) {
7701 path->slots[level]++;
7702 return 0;
7703 } else {
7704 ret = walk_up_proc(trans, root, path, wc);
7705 if (ret > 0)
7706 return 0;
7707
7708 if (path->locks[level]) {
7709 btrfs_tree_unlock_rw(path->nodes[level],
7710 path->locks[level]);
7711 path->locks[level] = 0;
7712 }
7713 free_extent_buffer(path->nodes[level]);
7714 path->nodes[level] = NULL;
7715 level++;
7716 }
7717 }
7718 return 1;
7719 }
7720
7721 /*
7722 * drop a subvolume tree.
7723 *
7724 * this function traverses the tree freeing any blocks that only
7725 * referenced by the tree.
7726 *
7727 * when a shared tree block is found. this function decreases its
7728 * reference count by one. if update_ref is true, this function
7729 * also make sure backrefs for the shared block and all lower level
7730 * blocks are properly updated.
7731 *
7732 * If called with for_reloc == 0, may exit early with -EAGAIN
7733 */
7734 int btrfs_drop_snapshot(struct btrfs_root *root,
7735 struct btrfs_block_rsv *block_rsv, int update_ref,
7736 int for_reloc)
7737 {
7738 struct btrfs_path *path;
7739 struct btrfs_trans_handle *trans;
7740 struct btrfs_root *tree_root = root->fs_info->tree_root;
7741 struct btrfs_root_item *root_item = &root->root_item;
7742 struct walk_control *wc;
7743 struct btrfs_key key;
7744 int err = 0;
7745 int ret;
7746 int level;
7747 bool root_dropped = false;
7748
7749 path = btrfs_alloc_path();
7750 if (!path) {
7751 err = -ENOMEM;
7752 goto out;
7753 }
7754
7755 wc = kzalloc(sizeof(*wc), GFP_NOFS);
7756 if (!wc) {
7757 btrfs_free_path(path);
7758 err = -ENOMEM;
7759 goto out;
7760 }
7761
7762 trans = btrfs_start_transaction(tree_root, 0);
7763 if (IS_ERR(trans)) {
7764 err = PTR_ERR(trans);
7765 goto out_free;
7766 }
7767
7768 if (block_rsv)
7769 trans->block_rsv = block_rsv;
7770
7771 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
7772 level = btrfs_header_level(root->node);
7773 path->nodes[level] = btrfs_lock_root_node(root);
7774 btrfs_set_lock_blocking(path->nodes[level]);
7775 path->slots[level] = 0;
7776 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7777 memset(&wc->update_progress, 0,
7778 sizeof(wc->update_progress));
7779 } else {
7780 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
7781 memcpy(&wc->update_progress, &key,
7782 sizeof(wc->update_progress));
7783
7784 level = root_item->drop_level;
7785 BUG_ON(level == 0);
7786 path->lowest_level = level;
7787 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7788 path->lowest_level = 0;
7789 if (ret < 0) {
7790 err = ret;
7791 goto out_end_trans;
7792 }
7793 WARN_ON(ret > 0);
7794
7795 /*
7796 * unlock our path, this is safe because only this
7797 * function is allowed to delete this snapshot
7798 */
7799 btrfs_unlock_up_safe(path, 0);
7800
7801 level = btrfs_header_level(root->node);
7802 while (1) {
7803 btrfs_tree_lock(path->nodes[level]);
7804 btrfs_set_lock_blocking(path->nodes[level]);
7805 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7806
7807 ret = btrfs_lookup_extent_info(trans, root,
7808 path->nodes[level]->start,
7809 level, 1, &wc->refs[level],
7810 &wc->flags[level]);
7811 if (ret < 0) {
7812 err = ret;
7813 goto out_end_trans;
7814 }
7815 BUG_ON(wc->refs[level] == 0);
7816
7817 if (level == root_item->drop_level)
7818 break;
7819
7820 btrfs_tree_unlock(path->nodes[level]);
7821 path->locks[level] = 0;
7822 WARN_ON(wc->refs[level] != 1);
7823 level--;
7824 }
7825 }
7826
7827 wc->level = level;
7828 wc->shared_level = -1;
7829 wc->stage = DROP_REFERENCE;
7830 wc->update_ref = update_ref;
7831 wc->keep_locks = 0;
7832 wc->for_reloc = for_reloc;
7833 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
7834
7835 while (1) {
7836
7837 ret = walk_down_tree(trans, root, path, wc);
7838 if (ret < 0) {
7839 err = ret;
7840 break;
7841 }
7842
7843 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
7844 if (ret < 0) {
7845 err = ret;
7846 break;
7847 }
7848
7849 if (ret > 0) {
7850 BUG_ON(wc->stage != DROP_REFERENCE);
7851 break;
7852 }
7853
7854 if (wc->stage == DROP_REFERENCE) {
7855 level = wc->level;
7856 btrfs_node_key(path->nodes[level],
7857 &root_item->drop_progress,
7858 path->slots[level]);
7859 root_item->drop_level = level;
7860 }
7861
7862 BUG_ON(wc->level == 0);
7863 if (btrfs_should_end_transaction(trans, tree_root) ||
7864 (!for_reloc && btrfs_need_cleaner_sleep(root))) {
7865 ret = btrfs_update_root(trans, tree_root,
7866 &root->root_key,
7867 root_item);
7868 if (ret) {
7869 btrfs_abort_transaction(trans, tree_root, ret);
7870 err = ret;
7871 goto out_end_trans;
7872 }
7873
7874 btrfs_end_transaction_throttle(trans, tree_root);
7875 if (!for_reloc && btrfs_need_cleaner_sleep(root)) {
7876 pr_debug("BTRFS: drop snapshot early exit\n");
7877 err = -EAGAIN;
7878 goto out_free;
7879 }
7880
7881 trans = btrfs_start_transaction(tree_root, 0);
7882 if (IS_ERR(trans)) {
7883 err = PTR_ERR(trans);
7884 goto out_free;
7885 }
7886 if (block_rsv)
7887 trans->block_rsv = block_rsv;
7888 }
7889 }
7890 btrfs_release_path(path);
7891 if (err)
7892 goto out_end_trans;
7893
7894 ret = btrfs_del_root(trans, tree_root, &root->root_key);
7895 if (ret) {
7896 btrfs_abort_transaction(trans, tree_root, ret);
7897 goto out_end_trans;
7898 }
7899
7900 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
7901 ret = btrfs_find_root(tree_root, &root->root_key, path,
7902 NULL, NULL);
7903 if (ret < 0) {
7904 btrfs_abort_transaction(trans, tree_root, ret);
7905 err = ret;
7906 goto out_end_trans;
7907 } else if (ret > 0) {
7908 /* if we fail to delete the orphan item this time
7909 * around, it'll get picked up the next time.
7910 *
7911 * The most common failure here is just -ENOENT.
7912 */
7913 btrfs_del_orphan_item(trans, tree_root,
7914 root->root_key.objectid);
7915 }
7916 }
7917
7918 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
7919 btrfs_drop_and_free_fs_root(tree_root->fs_info, root);
7920 } else {
7921 free_extent_buffer(root->node);
7922 free_extent_buffer(root->commit_root);
7923 btrfs_put_fs_root(root);
7924 }
7925 root_dropped = true;
7926 out_end_trans:
7927 btrfs_end_transaction_throttle(trans, tree_root);
7928 out_free:
7929 kfree(wc);
7930 btrfs_free_path(path);
7931 out:
7932 /*
7933 * So if we need to stop dropping the snapshot for whatever reason we
7934 * need to make sure to add it back to the dead root list so that we
7935 * keep trying to do the work later. This also cleans up roots if we
7936 * don't have it in the radix (like when we recover after a power fail
7937 * or unmount) so we don't leak memory.
7938 */
7939 if (!for_reloc && root_dropped == false)
7940 btrfs_add_dead_root(root);
7941 if (err && err != -EAGAIN)
7942 btrfs_std_error(root->fs_info, err);
7943 return err;
7944 }
7945
7946 /*
7947 * drop subtree rooted at tree block 'node'.
7948 *
7949 * NOTE: this function will unlock and release tree block 'node'
7950 * only used by relocation code
7951 */
7952 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
7953 struct btrfs_root *root,
7954 struct extent_buffer *node,
7955 struct extent_buffer *parent)
7956 {
7957 struct btrfs_path *path;
7958 struct walk_control *wc;
7959 int level;
7960 int parent_level;
7961 int ret = 0;
7962 int wret;
7963
7964 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
7965
7966 path = btrfs_alloc_path();
7967 if (!path)
7968 return -ENOMEM;
7969
7970 wc = kzalloc(sizeof(*wc), GFP_NOFS);
7971 if (!wc) {
7972 btrfs_free_path(path);
7973 return -ENOMEM;
7974 }
7975
7976 btrfs_assert_tree_locked(parent);
7977 parent_level = btrfs_header_level(parent);
7978 extent_buffer_get(parent);
7979 path->nodes[parent_level] = parent;
7980 path->slots[parent_level] = btrfs_header_nritems(parent);
7981
7982 btrfs_assert_tree_locked(node);
7983 level = btrfs_header_level(node);
7984 path->nodes[level] = node;
7985 path->slots[level] = 0;
7986 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7987
7988 wc->refs[parent_level] = 1;
7989 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
7990 wc->level = level;
7991 wc->shared_level = -1;
7992 wc->stage = DROP_REFERENCE;
7993 wc->update_ref = 0;
7994 wc->keep_locks = 1;
7995 wc->for_reloc = 1;
7996 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
7997
7998 while (1) {
7999 wret = walk_down_tree(trans, root, path, wc);
8000 if (wret < 0) {
8001 ret = wret;
8002 break;
8003 }
8004
8005 wret = walk_up_tree(trans, root, path, wc, parent_level);
8006 if (wret < 0)
8007 ret = wret;
8008 if (wret != 0)
8009 break;
8010 }
8011
8012 kfree(wc);
8013 btrfs_free_path(path);
8014 return ret;
8015 }
8016
8017 static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
8018 {
8019 u64 num_devices;
8020 u64 stripped;
8021
8022 /*
8023 * if restripe for this chunk_type is on pick target profile and
8024 * return, otherwise do the usual balance
8025 */
8026 stripped = get_restripe_target(root->fs_info, flags);
8027 if (stripped)
8028 return extended_to_chunk(stripped);
8029
8030 /*
8031 * we add in the count of missing devices because we want
8032 * to make sure that any RAID levels on a degraded FS
8033 * continue to be honored.
8034 */
8035 num_devices = root->fs_info->fs_devices->rw_devices +
8036 root->fs_info->fs_devices->missing_devices;
8037
8038 stripped = BTRFS_BLOCK_GROUP_RAID0 |
8039 BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
8040 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
8041
8042 if (num_devices == 1) {
8043 stripped |= BTRFS_BLOCK_GROUP_DUP;
8044 stripped = flags & ~stripped;
8045
8046 /* turn raid0 into single device chunks */
8047 if (flags & BTRFS_BLOCK_GROUP_RAID0)
8048 return stripped;
8049
8050 /* turn mirroring into duplication */
8051 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
8052 BTRFS_BLOCK_GROUP_RAID10))
8053 return stripped | BTRFS_BLOCK_GROUP_DUP;
8054 } else {
8055 /* they already had raid on here, just return */
8056 if (flags & stripped)
8057 return flags;
8058
8059 stripped |= BTRFS_BLOCK_GROUP_DUP;
8060 stripped = flags & ~stripped;
8061
8062 /* switch duplicated blocks with raid1 */
8063 if (flags & BTRFS_BLOCK_GROUP_DUP)
8064 return stripped | BTRFS_BLOCK_GROUP_RAID1;
8065
8066 /* this is drive concat, leave it alone */
8067 }
8068
8069 return flags;
8070 }
8071
8072 static int set_block_group_ro(struct btrfs_block_group_cache *cache, int force)
8073 {
8074 struct btrfs_space_info *sinfo = cache->space_info;
8075 u64 num_bytes;
8076 u64 min_allocable_bytes;
8077 int ret = -ENOSPC;
8078
8079
8080 /*
8081 * We need some metadata space and system metadata space for
8082 * allocating chunks in some corner cases until we force to set
8083 * it to be readonly.
8084 */
8085 if ((sinfo->flags &
8086 (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
8087 !force)
8088 min_allocable_bytes = 1 * 1024 * 1024;
8089 else
8090 min_allocable_bytes = 0;
8091
8092 spin_lock(&sinfo->lock);
8093 spin_lock(&cache->lock);
8094
8095 if (cache->ro) {
8096 ret = 0;
8097 goto out;
8098 }
8099
8100 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
8101 cache->bytes_super - btrfs_block_group_used(&cache->item);
8102
8103 if (sinfo->bytes_used + sinfo->bytes_reserved + sinfo->bytes_pinned +
8104 sinfo->bytes_may_use + sinfo->bytes_readonly + num_bytes +
8105 min_allocable_bytes <= sinfo->total_bytes) {
8106 sinfo->bytes_readonly += num_bytes;
8107 cache->ro = 1;
8108 ret = 0;
8109 }
8110 out:
8111 spin_unlock(&cache->lock);
8112 spin_unlock(&sinfo->lock);
8113 return ret;
8114 }
8115
8116 int btrfs_set_block_group_ro(struct btrfs_root *root,
8117 struct btrfs_block_group_cache *cache)
8118
8119 {
8120 struct btrfs_trans_handle *trans;
8121 u64 alloc_flags;
8122 int ret;
8123
8124 BUG_ON(cache->ro);
8125
8126 trans = btrfs_join_transaction(root);
8127 if (IS_ERR(trans))
8128 return PTR_ERR(trans);
8129
8130 alloc_flags = update_block_group_flags(root, cache->flags);
8131 if (alloc_flags != cache->flags) {
8132 ret = do_chunk_alloc(trans, root, alloc_flags,
8133 CHUNK_ALLOC_FORCE);
8134 if (ret < 0)
8135 goto out;
8136 }
8137
8138 ret = set_block_group_ro(cache, 0);
8139 if (!ret)
8140 goto out;
8141 alloc_flags = get_alloc_profile(root, cache->space_info->flags);
8142 ret = do_chunk_alloc(trans, root, alloc_flags,
8143 CHUNK_ALLOC_FORCE);
8144 if (ret < 0)
8145 goto out;
8146 ret = set_block_group_ro(cache, 0);
8147 out:
8148 btrfs_end_transaction(trans, root);
8149 return ret;
8150 }
8151
8152 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
8153 struct btrfs_root *root, u64 type)
8154 {
8155 u64 alloc_flags = get_alloc_profile(root, type);
8156 return do_chunk_alloc(trans, root, alloc_flags,
8157 CHUNK_ALLOC_FORCE);
8158 }
8159
8160 /*
8161 * helper to account the unused space of all the readonly block group in the
8162 * list. takes mirrors into account.
8163 */
8164 static u64 __btrfs_get_ro_block_group_free_space(struct list_head *groups_list)
8165 {
8166 struct btrfs_block_group_cache *block_group;
8167 u64 free_bytes = 0;
8168 int factor;
8169
8170 list_for_each_entry(block_group, groups_list, list) {
8171 spin_lock(&block_group->lock);
8172
8173 if (!block_group->ro) {
8174 spin_unlock(&block_group->lock);
8175 continue;
8176 }
8177
8178 if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
8179 BTRFS_BLOCK_GROUP_RAID10 |
8180 BTRFS_BLOCK_GROUP_DUP))
8181 factor = 2;
8182 else
8183 factor = 1;
8184
8185 free_bytes += (block_group->key.offset -
8186 btrfs_block_group_used(&block_group->item)) *
8187 factor;
8188
8189 spin_unlock(&block_group->lock);
8190 }
8191
8192 return free_bytes;
8193 }
8194
8195 /*
8196 * helper to account the unused space of all the readonly block group in the
8197 * space_info. takes mirrors into account.
8198 */
8199 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
8200 {
8201 int i;
8202 u64 free_bytes = 0;
8203
8204 spin_lock(&sinfo->lock);
8205
8206 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
8207 if (!list_empty(&sinfo->block_groups[i]))
8208 free_bytes += __btrfs_get_ro_block_group_free_space(
8209 &sinfo->block_groups[i]);
8210
8211 spin_unlock(&sinfo->lock);
8212
8213 return free_bytes;
8214 }
8215
8216 void btrfs_set_block_group_rw(struct btrfs_root *root,
8217 struct btrfs_block_group_cache *cache)
8218 {
8219 struct btrfs_space_info *sinfo = cache->space_info;
8220 u64 num_bytes;
8221
8222 BUG_ON(!cache->ro);
8223
8224 spin_lock(&sinfo->lock);
8225 spin_lock(&cache->lock);
8226 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
8227 cache->bytes_super - btrfs_block_group_used(&cache->item);
8228 sinfo->bytes_readonly -= num_bytes;
8229 cache->ro = 0;
8230 spin_unlock(&cache->lock);
8231 spin_unlock(&sinfo->lock);
8232 }
8233
8234 /*
8235 * checks to see if its even possible to relocate this block group.
8236 *
8237 * @return - -1 if it's not a good idea to relocate this block group, 0 if its
8238 * ok to go ahead and try.
8239 */
8240 int btrfs_can_relocate(struct btrfs_root *root, u64 bytenr)
8241 {
8242 struct btrfs_block_group_cache *block_group;
8243 struct btrfs_space_info *space_info;
8244 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
8245 struct btrfs_device *device;
8246 struct btrfs_trans_handle *trans;
8247 u64 min_free;
8248 u64 dev_min = 1;
8249 u64 dev_nr = 0;
8250 u64 target;
8251 int index;
8252 int full = 0;
8253 int ret = 0;
8254
8255 block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
8256
8257 /* odd, couldn't find the block group, leave it alone */
8258 if (!block_group)
8259 return -1;
8260
8261 min_free = btrfs_block_group_used(&block_group->item);
8262
8263 /* no bytes used, we're good */
8264 if (!min_free)
8265 goto out;
8266
8267 space_info = block_group->space_info;
8268 spin_lock(&space_info->lock);
8269
8270 full = space_info->full;
8271
8272 /*
8273 * if this is the last block group we have in this space, we can't
8274 * relocate it unless we're able to allocate a new chunk below.
8275 *
8276 * Otherwise, we need to make sure we have room in the space to handle
8277 * all of the extents from this block group. If we can, we're good
8278 */
8279 if ((space_info->total_bytes != block_group->key.offset) &&
8280 (space_info->bytes_used + space_info->bytes_reserved +
8281 space_info->bytes_pinned + space_info->bytes_readonly +
8282 min_free < space_info->total_bytes)) {
8283 spin_unlock(&space_info->lock);
8284 goto out;
8285 }
8286 spin_unlock(&space_info->lock);
8287
8288 /*
8289 * ok we don't have enough space, but maybe we have free space on our
8290 * devices to allocate new chunks for relocation, so loop through our
8291 * alloc devices and guess if we have enough space. if this block
8292 * group is going to be restriped, run checks against the target
8293 * profile instead of the current one.
8294 */
8295 ret = -1;
8296
8297 /*
8298 * index:
8299 * 0: raid10
8300 * 1: raid1
8301 * 2: dup
8302 * 3: raid0
8303 * 4: single
8304 */
8305 target = get_restripe_target(root->fs_info, block_group->flags);
8306 if (target) {
8307 index = __get_raid_index(extended_to_chunk(target));
8308 } else {
8309 /*
8310 * this is just a balance, so if we were marked as full
8311 * we know there is no space for a new chunk
8312 */
8313 if (full)
8314 goto out;
8315
8316 index = get_block_group_index(block_group);
8317 }
8318
8319 if (index == BTRFS_RAID_RAID10) {
8320 dev_min = 4;
8321 /* Divide by 2 */
8322 min_free >>= 1;
8323 } else if (index == BTRFS_RAID_RAID1) {
8324 dev_min = 2;
8325 } else if (index == BTRFS_RAID_DUP) {
8326 /* Multiply by 2 */
8327 min_free <<= 1;
8328 } else if (index == BTRFS_RAID_RAID0) {
8329 dev_min = fs_devices->rw_devices;
8330 do_div(min_free, dev_min);
8331 }
8332
8333 /* We need to do this so that we can look at pending chunks */
8334 trans = btrfs_join_transaction(root);
8335 if (IS_ERR(trans)) {
8336 ret = PTR_ERR(trans);
8337 goto out;
8338 }
8339
8340 mutex_lock(&root->fs_info->chunk_mutex);
8341 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
8342 u64 dev_offset;
8343
8344 /*
8345 * check to make sure we can actually find a chunk with enough
8346 * space to fit our block group in.
8347 */
8348 if (device->total_bytes > device->bytes_used + min_free &&
8349 !device->is_tgtdev_for_dev_replace) {
8350 ret = find_free_dev_extent(trans, device, min_free,
8351 &dev_offset, NULL);
8352 if (!ret)
8353 dev_nr++;
8354
8355 if (dev_nr >= dev_min)
8356 break;
8357
8358 ret = -1;
8359 }
8360 }
8361 mutex_unlock(&root->fs_info->chunk_mutex);
8362 btrfs_end_transaction(trans, root);
8363 out:
8364 btrfs_put_block_group(block_group);
8365 return ret;
8366 }
8367
8368 static int find_first_block_group(struct btrfs_root *root,
8369 struct btrfs_path *path, struct btrfs_key *key)
8370 {
8371 int ret = 0;
8372 struct btrfs_key found_key;
8373 struct extent_buffer *leaf;
8374 int slot;
8375
8376 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
8377 if (ret < 0)
8378 goto out;
8379
8380 while (1) {
8381 slot = path->slots[0];
8382 leaf = path->nodes[0];
8383 if (slot >= btrfs_header_nritems(leaf)) {
8384 ret = btrfs_next_leaf(root, path);
8385 if (ret == 0)
8386 continue;
8387 if (ret < 0)
8388 goto out;
8389 break;
8390 }
8391 btrfs_item_key_to_cpu(leaf, &found_key, slot);
8392
8393 if (found_key.objectid >= key->objectid &&
8394 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
8395 ret = 0;
8396 goto out;
8397 }
8398 path->slots[0]++;
8399 }
8400 out:
8401 return ret;
8402 }
8403
8404 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
8405 {
8406 struct btrfs_block_group_cache *block_group;
8407 u64 last = 0;
8408
8409 while (1) {
8410 struct inode *inode;
8411
8412 block_group = btrfs_lookup_first_block_group(info, last);
8413 while (block_group) {
8414 spin_lock(&block_group->lock);
8415 if (block_group->iref)
8416 break;
8417 spin_unlock(&block_group->lock);
8418 block_group = next_block_group(info->tree_root,
8419 block_group);
8420 }
8421 if (!block_group) {
8422 if (last == 0)
8423 break;
8424 last = 0;
8425 continue;
8426 }
8427
8428 inode = block_group->inode;
8429 block_group->iref = 0;
8430 block_group->inode = NULL;
8431 spin_unlock(&block_group->lock);
8432 iput(inode);
8433 last = block_group->key.objectid + block_group->key.offset;
8434 btrfs_put_block_group(block_group);
8435 }
8436 }
8437
8438 int btrfs_free_block_groups(struct btrfs_fs_info *info)
8439 {
8440 struct btrfs_block_group_cache *block_group;
8441 struct btrfs_space_info *space_info;
8442 struct btrfs_caching_control *caching_ctl;
8443 struct rb_node *n;
8444
8445 down_write(&info->commit_root_sem);
8446 while (!list_empty(&info->caching_block_groups)) {
8447 caching_ctl = list_entry(info->caching_block_groups.next,
8448 struct btrfs_caching_control, list);
8449 list_del(&caching_ctl->list);
8450 put_caching_control(caching_ctl);
8451 }
8452 up_write(&info->commit_root_sem);
8453
8454 spin_lock(&info->block_group_cache_lock);
8455 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
8456 block_group = rb_entry(n, struct btrfs_block_group_cache,
8457 cache_node);
8458 rb_erase(&block_group->cache_node,
8459 &info->block_group_cache_tree);
8460 spin_unlock(&info->block_group_cache_lock);
8461
8462 down_write(&block_group->space_info->groups_sem);
8463 list_del(&block_group->list);
8464 up_write(&block_group->space_info->groups_sem);
8465
8466 if (block_group->cached == BTRFS_CACHE_STARTED)
8467 wait_block_group_cache_done(block_group);
8468
8469 /*
8470 * We haven't cached this block group, which means we could
8471 * possibly have excluded extents on this block group.
8472 */
8473 if (block_group->cached == BTRFS_CACHE_NO ||
8474 block_group->cached == BTRFS_CACHE_ERROR)
8475 free_excluded_extents(info->extent_root, block_group);
8476
8477 btrfs_remove_free_space_cache(block_group);
8478 btrfs_put_block_group(block_group);
8479
8480 spin_lock(&info->block_group_cache_lock);
8481 }
8482 spin_unlock(&info->block_group_cache_lock);
8483
8484 /* now that all the block groups are freed, go through and
8485 * free all the space_info structs. This is only called during
8486 * the final stages of unmount, and so we know nobody is
8487 * using them. We call synchronize_rcu() once before we start,
8488 * just to be on the safe side.
8489 */
8490 synchronize_rcu();
8491
8492 release_global_block_rsv(info);
8493
8494 while (!list_empty(&info->space_info)) {
8495 int i;
8496
8497 space_info = list_entry(info->space_info.next,
8498 struct btrfs_space_info,
8499 list);
8500 if (btrfs_test_opt(info->tree_root, ENOSPC_DEBUG)) {
8501 if (WARN_ON(space_info->bytes_pinned > 0 ||
8502 space_info->bytes_reserved > 0 ||
8503 space_info->bytes_may_use > 0)) {
8504 dump_space_info(space_info, 0, 0);
8505 }
8506 }
8507 list_del(&space_info->list);
8508 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
8509 struct kobject *kobj;
8510 kobj = &space_info->block_group_kobjs[i];
8511 if (kobj->parent) {
8512 kobject_del(kobj);
8513 kobject_put(kobj);
8514 }
8515 }
8516 kobject_del(&space_info->kobj);
8517 kobject_put(&space_info->kobj);
8518 }
8519 return 0;
8520 }
8521
8522 static void __link_block_group(struct btrfs_space_info *space_info,
8523 struct btrfs_block_group_cache *cache)
8524 {
8525 int index = get_block_group_index(cache);
8526 bool first = false;
8527
8528 down_write(&space_info->groups_sem);
8529 if (list_empty(&space_info->block_groups[index]))
8530 first = true;
8531 list_add_tail(&cache->list, &space_info->block_groups[index]);
8532 up_write(&space_info->groups_sem);
8533
8534 if (first) {
8535 struct kobject *kobj = &space_info->block_group_kobjs[index];
8536 int ret;
8537
8538 kobject_get(&space_info->kobj); /* put in release */
8539 ret = kobject_add(kobj, &space_info->kobj, "%s",
8540 get_raid_name(index));
8541 if (ret) {
8542 pr_warn("BTRFS: failed to add kobject for block cache. ignoring.\n");
8543 kobject_put(&space_info->kobj);
8544 }
8545 }
8546 }
8547
8548 static struct btrfs_block_group_cache *
8549 btrfs_create_block_group_cache(struct btrfs_root *root, u64 start, u64 size)
8550 {
8551 struct btrfs_block_group_cache *cache;
8552
8553 cache = kzalloc(sizeof(*cache), GFP_NOFS);
8554 if (!cache)
8555 return NULL;
8556
8557 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
8558 GFP_NOFS);
8559 if (!cache->free_space_ctl) {
8560 kfree(cache);
8561 return NULL;
8562 }
8563
8564 cache->key.objectid = start;
8565 cache->key.offset = size;
8566 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
8567
8568 cache->sectorsize = root->sectorsize;
8569 cache->fs_info = root->fs_info;
8570 cache->full_stripe_len = btrfs_full_stripe_len(root,
8571 &root->fs_info->mapping_tree,
8572 start);
8573 atomic_set(&cache->count, 1);
8574 spin_lock_init(&cache->lock);
8575 INIT_LIST_HEAD(&cache->list);
8576 INIT_LIST_HEAD(&cache->cluster_list);
8577 INIT_LIST_HEAD(&cache->new_bg_list);
8578 btrfs_init_free_space_ctl(cache);
8579
8580 return cache;
8581 }
8582
8583 int btrfs_read_block_groups(struct btrfs_root *root)
8584 {
8585 struct btrfs_path *path;
8586 int ret;
8587 struct btrfs_block_group_cache *cache;
8588 struct btrfs_fs_info *info = root->fs_info;
8589 struct btrfs_space_info *space_info;
8590 struct btrfs_key key;
8591 struct btrfs_key found_key;
8592 struct extent_buffer *leaf;
8593 int need_clear = 0;
8594 u64 cache_gen;
8595
8596 root = info->extent_root;
8597 key.objectid = 0;
8598 key.offset = 0;
8599 btrfs_set_key_type(&key, BTRFS_BLOCK_GROUP_ITEM_KEY);
8600 path = btrfs_alloc_path();
8601 if (!path)
8602 return -ENOMEM;
8603 path->reada = 1;
8604
8605 cache_gen = btrfs_super_cache_generation(root->fs_info->super_copy);
8606 if (btrfs_test_opt(root, SPACE_CACHE) &&
8607 btrfs_super_generation(root->fs_info->super_copy) != cache_gen)
8608 need_clear = 1;
8609 if (btrfs_test_opt(root, CLEAR_CACHE))
8610 need_clear = 1;
8611
8612 while (1) {
8613 ret = find_first_block_group(root, path, &key);
8614 if (ret > 0)
8615 break;
8616 if (ret != 0)
8617 goto error;
8618
8619 leaf = path->nodes[0];
8620 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8621
8622 cache = btrfs_create_block_group_cache(root, found_key.objectid,
8623 found_key.offset);
8624 if (!cache) {
8625 ret = -ENOMEM;
8626 goto error;
8627 }
8628
8629 if (need_clear) {
8630 /*
8631 * When we mount with old space cache, we need to
8632 * set BTRFS_DC_CLEAR and set dirty flag.
8633 *
8634 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
8635 * truncate the old free space cache inode and
8636 * setup a new one.
8637 * b) Setting 'dirty flag' makes sure that we flush
8638 * the new space cache info onto disk.
8639 */
8640 cache->disk_cache_state = BTRFS_DC_CLEAR;
8641 if (btrfs_test_opt(root, SPACE_CACHE))
8642 cache->dirty = 1;
8643 }
8644
8645 read_extent_buffer(leaf, &cache->item,
8646 btrfs_item_ptr_offset(leaf, path->slots[0]),
8647 sizeof(cache->item));
8648 cache->flags = btrfs_block_group_flags(&cache->item);
8649
8650 key.objectid = found_key.objectid + found_key.offset;
8651 btrfs_release_path(path);
8652
8653 /*
8654 * We need to exclude the super stripes now so that the space
8655 * info has super bytes accounted for, otherwise we'll think
8656 * we have more space than we actually do.
8657 */
8658 ret = exclude_super_stripes(root, cache);
8659 if (ret) {
8660 /*
8661 * We may have excluded something, so call this just in
8662 * case.
8663 */
8664 free_excluded_extents(root, cache);
8665 btrfs_put_block_group(cache);
8666 goto error;
8667 }
8668
8669 /*
8670 * check for two cases, either we are full, and therefore
8671 * don't need to bother with the caching work since we won't
8672 * find any space, or we are empty, and we can just add all
8673 * the space in and be done with it. This saves us _alot_ of
8674 * time, particularly in the full case.
8675 */
8676 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
8677 cache->last_byte_to_unpin = (u64)-1;
8678 cache->cached = BTRFS_CACHE_FINISHED;
8679 free_excluded_extents(root, cache);
8680 } else if (btrfs_block_group_used(&cache->item) == 0) {
8681 cache->last_byte_to_unpin = (u64)-1;
8682 cache->cached = BTRFS_CACHE_FINISHED;
8683 add_new_free_space(cache, root->fs_info,
8684 found_key.objectid,
8685 found_key.objectid +
8686 found_key.offset);
8687 free_excluded_extents(root, cache);
8688 }
8689
8690 ret = btrfs_add_block_group_cache(root->fs_info, cache);
8691 if (ret) {
8692 btrfs_remove_free_space_cache(cache);
8693 btrfs_put_block_group(cache);
8694 goto error;
8695 }
8696
8697 ret = update_space_info(info, cache->flags, found_key.offset,
8698 btrfs_block_group_used(&cache->item),
8699 &space_info);
8700 if (ret) {
8701 btrfs_remove_free_space_cache(cache);
8702 spin_lock(&info->block_group_cache_lock);
8703 rb_erase(&cache->cache_node,
8704 &info->block_group_cache_tree);
8705 spin_unlock(&info->block_group_cache_lock);
8706 btrfs_put_block_group(cache);
8707 goto error;
8708 }
8709
8710 cache->space_info = space_info;
8711 spin_lock(&cache->space_info->lock);
8712 cache->space_info->bytes_readonly += cache->bytes_super;
8713 spin_unlock(&cache->space_info->lock);
8714
8715 __link_block_group(space_info, cache);
8716
8717 set_avail_alloc_bits(root->fs_info, cache->flags);
8718 if (btrfs_chunk_readonly(root, cache->key.objectid))
8719 set_block_group_ro(cache, 1);
8720 }
8721
8722 list_for_each_entry_rcu(space_info, &root->fs_info->space_info, list) {
8723 if (!(get_alloc_profile(root, space_info->flags) &
8724 (BTRFS_BLOCK_GROUP_RAID10 |
8725 BTRFS_BLOCK_GROUP_RAID1 |
8726 BTRFS_BLOCK_GROUP_RAID5 |
8727 BTRFS_BLOCK_GROUP_RAID6 |
8728 BTRFS_BLOCK_GROUP_DUP)))
8729 continue;
8730 /*
8731 * avoid allocating from un-mirrored block group if there are
8732 * mirrored block groups.
8733 */
8734 list_for_each_entry(cache,
8735 &space_info->block_groups[BTRFS_RAID_RAID0],
8736 list)
8737 set_block_group_ro(cache, 1);
8738 list_for_each_entry(cache,
8739 &space_info->block_groups[BTRFS_RAID_SINGLE],
8740 list)
8741 set_block_group_ro(cache, 1);
8742 }
8743
8744 init_global_block_rsv(info);
8745 ret = 0;
8746 error:
8747 btrfs_free_path(path);
8748 return ret;
8749 }
8750
8751 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans,
8752 struct btrfs_root *root)
8753 {
8754 struct btrfs_block_group_cache *block_group, *tmp;
8755 struct btrfs_root *extent_root = root->fs_info->extent_root;
8756 struct btrfs_block_group_item item;
8757 struct btrfs_key key;
8758 int ret = 0;
8759
8760 list_for_each_entry_safe(block_group, tmp, &trans->new_bgs,
8761 new_bg_list) {
8762 list_del_init(&block_group->new_bg_list);
8763
8764 if (ret)
8765 continue;
8766
8767 spin_lock(&block_group->lock);
8768 memcpy(&item, &block_group->item, sizeof(item));
8769 memcpy(&key, &block_group->key, sizeof(key));
8770 spin_unlock(&block_group->lock);
8771
8772 ret = btrfs_insert_item(trans, extent_root, &key, &item,
8773 sizeof(item));
8774 if (ret)
8775 btrfs_abort_transaction(trans, extent_root, ret);
8776 ret = btrfs_finish_chunk_alloc(trans, extent_root,
8777 key.objectid, key.offset);
8778 if (ret)
8779 btrfs_abort_transaction(trans, extent_root, ret);
8780 }
8781 }
8782
8783 int btrfs_make_block_group(struct btrfs_trans_handle *trans,
8784 struct btrfs_root *root, u64 bytes_used,
8785 u64 type, u64 chunk_objectid, u64 chunk_offset,
8786 u64 size)
8787 {
8788 int ret;
8789 struct btrfs_root *extent_root;
8790 struct btrfs_block_group_cache *cache;
8791
8792 extent_root = root->fs_info->extent_root;
8793
8794 btrfs_set_log_full_commit(root->fs_info, trans);
8795
8796 cache = btrfs_create_block_group_cache(root, chunk_offset, size);
8797 if (!cache)
8798 return -ENOMEM;
8799
8800 btrfs_set_block_group_used(&cache->item, bytes_used);
8801 btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
8802 btrfs_set_block_group_flags(&cache->item, type);
8803
8804 cache->flags = type;
8805 cache->last_byte_to_unpin = (u64)-1;
8806 cache->cached = BTRFS_CACHE_FINISHED;
8807 ret = exclude_super_stripes(root, cache);
8808 if (ret) {
8809 /*
8810 * We may have excluded something, so call this just in
8811 * case.
8812 */
8813 free_excluded_extents(root, cache);
8814 btrfs_put_block_group(cache);
8815 return ret;
8816 }
8817
8818 add_new_free_space(cache, root->fs_info, chunk_offset,
8819 chunk_offset + size);
8820
8821 free_excluded_extents(root, cache);
8822
8823 ret = btrfs_add_block_group_cache(root->fs_info, cache);
8824 if (ret) {
8825 btrfs_remove_free_space_cache(cache);
8826 btrfs_put_block_group(cache);
8827 return ret;
8828 }
8829
8830 ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
8831 &cache->space_info);
8832 if (ret) {
8833 btrfs_remove_free_space_cache(cache);
8834 spin_lock(&root->fs_info->block_group_cache_lock);
8835 rb_erase(&cache->cache_node,
8836 &root->fs_info->block_group_cache_tree);
8837 spin_unlock(&root->fs_info->block_group_cache_lock);
8838 btrfs_put_block_group(cache);
8839 return ret;
8840 }
8841 update_global_block_rsv(root->fs_info);
8842
8843 spin_lock(&cache->space_info->lock);
8844 cache->space_info->bytes_readonly += cache->bytes_super;
8845 spin_unlock(&cache->space_info->lock);
8846
8847 __link_block_group(cache->space_info, cache);
8848
8849 list_add_tail(&cache->new_bg_list, &trans->new_bgs);
8850
8851 set_avail_alloc_bits(extent_root->fs_info, type);
8852
8853 return 0;
8854 }
8855
8856 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
8857 {
8858 u64 extra_flags = chunk_to_extended(flags) &
8859 BTRFS_EXTENDED_PROFILE_MASK;
8860
8861 write_seqlock(&fs_info->profiles_lock);
8862 if (flags & BTRFS_BLOCK_GROUP_DATA)
8863 fs_info->avail_data_alloc_bits &= ~extra_flags;
8864 if (flags & BTRFS_BLOCK_GROUP_METADATA)
8865 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
8866 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
8867 fs_info->avail_system_alloc_bits &= ~extra_flags;
8868 write_sequnlock(&fs_info->profiles_lock);
8869 }
8870
8871 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
8872 struct btrfs_root *root, u64 group_start)
8873 {
8874 struct btrfs_path *path;
8875 struct btrfs_block_group_cache *block_group;
8876 struct btrfs_free_cluster *cluster;
8877 struct btrfs_root *tree_root = root->fs_info->tree_root;
8878 struct btrfs_key key;
8879 struct inode *inode;
8880 int ret;
8881 int index;
8882 int factor;
8883
8884 root = root->fs_info->extent_root;
8885
8886 block_group = btrfs_lookup_block_group(root->fs_info, group_start);
8887 BUG_ON(!block_group);
8888 BUG_ON(!block_group->ro);
8889
8890 /*
8891 * Free the reserved super bytes from this block group before
8892 * remove it.
8893 */
8894 free_excluded_extents(root, block_group);
8895
8896 memcpy(&key, &block_group->key, sizeof(key));
8897 index = get_block_group_index(block_group);
8898 if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
8899 BTRFS_BLOCK_GROUP_RAID1 |
8900 BTRFS_BLOCK_GROUP_RAID10))
8901 factor = 2;
8902 else
8903 factor = 1;
8904
8905 /* make sure this block group isn't part of an allocation cluster */
8906 cluster = &root->fs_info->data_alloc_cluster;
8907 spin_lock(&cluster->refill_lock);
8908 btrfs_return_cluster_to_free_space(block_group, cluster);
8909 spin_unlock(&cluster->refill_lock);
8910
8911 /*
8912 * make sure this block group isn't part of a metadata
8913 * allocation cluster
8914 */
8915 cluster = &root->fs_info->meta_alloc_cluster;
8916 spin_lock(&cluster->refill_lock);
8917 btrfs_return_cluster_to_free_space(block_group, cluster);
8918 spin_unlock(&cluster->refill_lock);
8919
8920 path = btrfs_alloc_path();
8921 if (!path) {
8922 ret = -ENOMEM;
8923 goto out;
8924 }
8925
8926 inode = lookup_free_space_inode(tree_root, block_group, path);
8927 if (!IS_ERR(inode)) {
8928 ret = btrfs_orphan_add(trans, inode);
8929 if (ret) {
8930 btrfs_add_delayed_iput(inode);
8931 goto out;
8932 }
8933 clear_nlink(inode);
8934 /* One for the block groups ref */
8935 spin_lock(&block_group->lock);
8936 if (block_group->iref) {
8937 block_group->iref = 0;
8938 block_group->inode = NULL;
8939 spin_unlock(&block_group->lock);
8940 iput(inode);
8941 } else {
8942 spin_unlock(&block_group->lock);
8943 }
8944 /* One for our lookup ref */
8945 btrfs_add_delayed_iput(inode);
8946 }
8947
8948 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
8949 key.offset = block_group->key.objectid;
8950 key.type = 0;
8951
8952 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
8953 if (ret < 0)
8954 goto out;
8955 if (ret > 0)
8956 btrfs_release_path(path);
8957 if (ret == 0) {
8958 ret = btrfs_del_item(trans, tree_root, path);
8959 if (ret)
8960 goto out;
8961 btrfs_release_path(path);
8962 }
8963
8964 spin_lock(&root->fs_info->block_group_cache_lock);
8965 rb_erase(&block_group->cache_node,
8966 &root->fs_info->block_group_cache_tree);
8967
8968 if (root->fs_info->first_logical_byte == block_group->key.objectid)
8969 root->fs_info->first_logical_byte = (u64)-1;
8970 spin_unlock(&root->fs_info->block_group_cache_lock);
8971
8972 down_write(&block_group->space_info->groups_sem);
8973 /*
8974 * we must use list_del_init so people can check to see if they
8975 * are still on the list after taking the semaphore
8976 */
8977 list_del_init(&block_group->list);
8978 if (list_empty(&block_group->space_info->block_groups[index])) {
8979 kobject_del(&block_group->space_info->block_group_kobjs[index]);
8980 kobject_put(&block_group->space_info->block_group_kobjs[index]);
8981 clear_avail_alloc_bits(root->fs_info, block_group->flags);
8982 }
8983 up_write(&block_group->space_info->groups_sem);
8984
8985 if (block_group->cached == BTRFS_CACHE_STARTED)
8986 wait_block_group_cache_done(block_group);
8987
8988 btrfs_remove_free_space_cache(block_group);
8989
8990 spin_lock(&block_group->space_info->lock);
8991 block_group->space_info->total_bytes -= block_group->key.offset;
8992 block_group->space_info->bytes_readonly -= block_group->key.offset;
8993 block_group->space_info->disk_total -= block_group->key.offset * factor;
8994 spin_unlock(&block_group->space_info->lock);
8995
8996 memcpy(&key, &block_group->key, sizeof(key));
8997
8998 btrfs_clear_space_info_full(root->fs_info);
8999
9000 btrfs_put_block_group(block_group);
9001 btrfs_put_block_group(block_group);
9002
9003 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
9004 if (ret > 0)
9005 ret = -EIO;
9006 if (ret < 0)
9007 goto out;
9008
9009 ret = btrfs_del_item(trans, root, path);
9010 out:
9011 btrfs_free_path(path);
9012 return ret;
9013 }
9014
9015 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
9016 {
9017 struct btrfs_space_info *space_info;
9018 struct btrfs_super_block *disk_super;
9019 u64 features;
9020 u64 flags;
9021 int mixed = 0;
9022 int ret;
9023
9024 disk_super = fs_info->super_copy;
9025 if (!btrfs_super_root(disk_super))
9026 return 1;
9027
9028 features = btrfs_super_incompat_flags(disk_super);
9029 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
9030 mixed = 1;
9031
9032 flags = BTRFS_BLOCK_GROUP_SYSTEM;
9033 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
9034 if (ret)
9035 goto out;
9036
9037 if (mixed) {
9038 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
9039 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
9040 } else {
9041 flags = BTRFS_BLOCK_GROUP_METADATA;
9042 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
9043 if (ret)
9044 goto out;
9045
9046 flags = BTRFS_BLOCK_GROUP_DATA;
9047 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
9048 }
9049 out:
9050 return ret;
9051 }
9052
9053 int btrfs_error_unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
9054 {
9055 return unpin_extent_range(root, start, end);
9056 }
9057
9058 int btrfs_error_discard_extent(struct btrfs_root *root, u64 bytenr,
9059 u64 num_bytes, u64 *actual_bytes)
9060 {
9061 return btrfs_discard_extent(root, bytenr, num_bytes, actual_bytes);
9062 }
9063
9064 int btrfs_trim_fs(struct btrfs_root *root, struct fstrim_range *range)
9065 {
9066 struct btrfs_fs_info *fs_info = root->fs_info;
9067 struct btrfs_block_group_cache *cache = NULL;
9068 u64 group_trimmed;
9069 u64 start;
9070 u64 end;
9071 u64 trimmed = 0;
9072 u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
9073 int ret = 0;
9074
9075 /*
9076 * try to trim all FS space, our block group may start from non-zero.
9077 */
9078 if (range->len == total_bytes)
9079 cache = btrfs_lookup_first_block_group(fs_info, range->start);
9080 else
9081 cache = btrfs_lookup_block_group(fs_info, range->start);
9082
9083 while (cache) {
9084 if (cache->key.objectid >= (range->start + range->len)) {
9085 btrfs_put_block_group(cache);
9086 break;
9087 }
9088
9089 start = max(range->start, cache->key.objectid);
9090 end = min(range->start + range->len,
9091 cache->key.objectid + cache->key.offset);
9092
9093 if (end - start >= range->minlen) {
9094 if (!block_group_cache_done(cache)) {
9095 ret = cache_block_group(cache, 0);
9096 if (ret) {
9097 btrfs_put_block_group(cache);
9098 break;
9099 }
9100 ret = wait_block_group_cache_done(cache);
9101 if (ret) {
9102 btrfs_put_block_group(cache);
9103 break;
9104 }
9105 }
9106 ret = btrfs_trim_block_group(cache,
9107 &group_trimmed,
9108 start,
9109 end,
9110 range->minlen);
9111
9112 trimmed += group_trimmed;
9113 if (ret) {
9114 btrfs_put_block_group(cache);
9115 break;
9116 }
9117 }
9118
9119 cache = next_block_group(fs_info->tree_root, cache);
9120 }
9121
9122 range->len = trimmed;
9123 return ret;
9124 }
9125
9126 /*
9127 * btrfs_{start,end}_write() is similar to mnt_{want, drop}_write(),
9128 * they are used to prevent the some tasks writing data into the page cache
9129 * by nocow before the subvolume is snapshoted, but flush the data into
9130 * the disk after the snapshot creation.
9131 */
9132 void btrfs_end_nocow_write(struct btrfs_root *root)
9133 {
9134 percpu_counter_dec(&root->subv_writers->counter);
9135 /*
9136 * Make sure counter is updated before we wake up
9137 * waiters.
9138 */
9139 smp_mb();
9140 if (waitqueue_active(&root->subv_writers->wait))
9141 wake_up(&root->subv_writers->wait);
9142 }
9143
9144 int btrfs_start_nocow_write(struct btrfs_root *root)
9145 {
9146 if (unlikely(atomic_read(&root->will_be_snapshoted)))
9147 return 0;
9148
9149 percpu_counter_inc(&root->subv_writers->counter);
9150 /*
9151 * Make sure counter is updated before we check for snapshot creation.
9152 */
9153 smp_mb();
9154 if (unlikely(atomic_read(&root->will_be_snapshoted))) {
9155 btrfs_end_nocow_write(root);
9156 return 0;
9157 }
9158 return 1;
9159 }