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