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