• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5 
6 #include <linux/sched.h>
7 #include <linux/sched/signal.h>
8 #include <linux/pagemap.h>
9 #include <linux/writeback.h>
10 #include <linux/blkdev.h>
11 #include <linux/sort.h>
12 #include <linux/rcupdate.h>
13 #include <linux/kthread.h>
14 #include <linux/slab.h>
15 #include <linux/ratelimit.h>
16 #include <linux/percpu_counter.h>
17 #include <linux/lockdep.h>
18 #include <linux/crc32c.h>
19 #include "tree-log.h"
20 #include "disk-io.h"
21 #include "print-tree.h"
22 #include "volumes.h"
23 #include "raid56.h"
24 #include "locking.h"
25 #include "free-space-cache.h"
26 #include "free-space-tree.h"
27 #include "math.h"
28 #include "sysfs.h"
29 #include "qgroup.h"
30 #include "ref-verify.h"
31 
32 #undef SCRAMBLE_DELAYED_REFS
33 
34 /*
35  * control flags for do_chunk_alloc's force field
36  * CHUNK_ALLOC_NO_FORCE means to only allocate a chunk
37  * if we really need one.
38  *
39  * CHUNK_ALLOC_LIMITED means to only try and allocate one
40  * if we have very few chunks already allocated.  This is
41  * used as part of the clustering code to help make sure
42  * we have a good pool of storage to cluster in, without
43  * filling the FS with empty chunks
44  *
45  * CHUNK_ALLOC_FORCE means it must try to allocate one
46  *
47  */
48 enum {
49 	CHUNK_ALLOC_NO_FORCE = 0,
50 	CHUNK_ALLOC_LIMITED = 1,
51 	CHUNK_ALLOC_FORCE = 2,
52 };
53 
54 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
55 			       struct btrfs_delayed_ref_node *node, u64 parent,
56 			       u64 root_objectid, u64 owner_objectid,
57 			       u64 owner_offset, int refs_to_drop,
58 			       struct btrfs_delayed_extent_op *extra_op);
59 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
60 				    struct extent_buffer *leaf,
61 				    struct btrfs_extent_item *ei);
62 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
63 				      u64 parent, u64 root_objectid,
64 				      u64 flags, u64 owner, u64 offset,
65 				      struct btrfs_key *ins, int ref_mod);
66 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
67 				     struct btrfs_delayed_ref_node *node,
68 				     struct btrfs_delayed_extent_op *extent_op);
69 static int do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
70 			  int force);
71 static int find_next_key(struct btrfs_path *path, int level,
72 			 struct btrfs_key *key);
73 static void dump_space_info(struct btrfs_fs_info *fs_info,
74 			    struct btrfs_space_info *info, u64 bytes,
75 			    int dump_block_groups);
76 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
77 			       u64 num_bytes);
78 static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
79 				     struct btrfs_space_info *space_info,
80 				     u64 num_bytes);
81 static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
82 				     struct btrfs_space_info *space_info,
83 				     u64 num_bytes);
84 
85 static noinline int
block_group_cache_done(struct btrfs_block_group_cache * cache)86 block_group_cache_done(struct btrfs_block_group_cache *cache)
87 {
88 	smp_mb();
89 	return cache->cached == BTRFS_CACHE_FINISHED ||
90 		cache->cached == BTRFS_CACHE_ERROR;
91 }
92 
block_group_bits(struct btrfs_block_group_cache * cache,u64 bits)93 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
94 {
95 	return (cache->flags & bits) == bits;
96 }
97 
btrfs_get_block_group(struct btrfs_block_group_cache * cache)98 void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
99 {
100 	atomic_inc(&cache->count);
101 }
102 
btrfs_put_block_group(struct btrfs_block_group_cache * cache)103 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
104 {
105 	if (atomic_dec_and_test(&cache->count)) {
106 		WARN_ON(cache->pinned > 0);
107 		WARN_ON(cache->reserved > 0);
108 
109 		/*
110 		 * If not empty, someone is still holding mutex of
111 		 * full_stripe_lock, which can only be released by caller.
112 		 * And it will definitely cause use-after-free when caller
113 		 * tries to release full stripe lock.
114 		 *
115 		 * No better way to resolve, but only to warn.
116 		 */
117 		WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
118 		kfree(cache->free_space_ctl);
119 		kfree(cache);
120 	}
121 }
122 
123 /*
124  * this adds the block group to the fs_info rb tree for the block group
125  * cache
126  */
btrfs_add_block_group_cache(struct btrfs_fs_info * info,struct btrfs_block_group_cache * block_group)127 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
128 				struct btrfs_block_group_cache *block_group)
129 {
130 	struct rb_node **p;
131 	struct rb_node *parent = NULL;
132 	struct btrfs_block_group_cache *cache;
133 
134 	spin_lock(&info->block_group_cache_lock);
135 	p = &info->block_group_cache_tree.rb_node;
136 
137 	while (*p) {
138 		parent = *p;
139 		cache = rb_entry(parent, struct btrfs_block_group_cache,
140 				 cache_node);
141 		if (block_group->key.objectid < cache->key.objectid) {
142 			p = &(*p)->rb_left;
143 		} else if (block_group->key.objectid > cache->key.objectid) {
144 			p = &(*p)->rb_right;
145 		} else {
146 			spin_unlock(&info->block_group_cache_lock);
147 			return -EEXIST;
148 		}
149 	}
150 
151 	rb_link_node(&block_group->cache_node, parent, p);
152 	rb_insert_color(&block_group->cache_node,
153 			&info->block_group_cache_tree);
154 
155 	if (info->first_logical_byte > block_group->key.objectid)
156 		info->first_logical_byte = block_group->key.objectid;
157 
158 	spin_unlock(&info->block_group_cache_lock);
159 
160 	return 0;
161 }
162 
163 /*
164  * This will return the block group at or after bytenr if contains is 0, else
165  * it will return the block group that contains the bytenr
166  */
167 static struct btrfs_block_group_cache *
block_group_cache_tree_search(struct btrfs_fs_info * info,u64 bytenr,int contains)168 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
169 			      int contains)
170 {
171 	struct btrfs_block_group_cache *cache, *ret = NULL;
172 	struct rb_node *n;
173 	u64 end, start;
174 
175 	spin_lock(&info->block_group_cache_lock);
176 	n = info->block_group_cache_tree.rb_node;
177 
178 	while (n) {
179 		cache = rb_entry(n, struct btrfs_block_group_cache,
180 				 cache_node);
181 		end = cache->key.objectid + cache->key.offset - 1;
182 		start = cache->key.objectid;
183 
184 		if (bytenr < start) {
185 			if (!contains && (!ret || start < ret->key.objectid))
186 				ret = cache;
187 			n = n->rb_left;
188 		} else if (bytenr > start) {
189 			if (contains && bytenr <= end) {
190 				ret = cache;
191 				break;
192 			}
193 			n = n->rb_right;
194 		} else {
195 			ret = cache;
196 			break;
197 		}
198 	}
199 	if (ret) {
200 		btrfs_get_block_group(ret);
201 		if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
202 			info->first_logical_byte = ret->key.objectid;
203 	}
204 	spin_unlock(&info->block_group_cache_lock);
205 
206 	return ret;
207 }
208 
add_excluded_extent(struct btrfs_fs_info * fs_info,u64 start,u64 num_bytes)209 static int add_excluded_extent(struct btrfs_fs_info *fs_info,
210 			       u64 start, u64 num_bytes)
211 {
212 	u64 end = start + num_bytes - 1;
213 	set_extent_bits(&fs_info->freed_extents[0],
214 			start, end, EXTENT_UPTODATE);
215 	set_extent_bits(&fs_info->freed_extents[1],
216 			start, end, EXTENT_UPTODATE);
217 	return 0;
218 }
219 
free_excluded_extents(struct btrfs_block_group_cache * cache)220 static void free_excluded_extents(struct btrfs_block_group_cache *cache)
221 {
222 	struct btrfs_fs_info *fs_info = cache->fs_info;
223 	u64 start, end;
224 
225 	start = cache->key.objectid;
226 	end = start + cache->key.offset - 1;
227 
228 	clear_extent_bits(&fs_info->freed_extents[0],
229 			  start, end, EXTENT_UPTODATE);
230 	clear_extent_bits(&fs_info->freed_extents[1],
231 			  start, end, EXTENT_UPTODATE);
232 }
233 
exclude_super_stripes(struct btrfs_block_group_cache * cache)234 static int exclude_super_stripes(struct btrfs_block_group_cache *cache)
235 {
236 	struct btrfs_fs_info *fs_info = cache->fs_info;
237 	u64 bytenr;
238 	u64 *logical;
239 	int stripe_len;
240 	int i, nr, ret;
241 
242 	if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
243 		stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
244 		cache->bytes_super += stripe_len;
245 		ret = add_excluded_extent(fs_info, cache->key.objectid,
246 					  stripe_len);
247 		if (ret)
248 			return ret;
249 	}
250 
251 	for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
252 		bytenr = btrfs_sb_offset(i);
253 		ret = btrfs_rmap_block(fs_info, cache->key.objectid,
254 				       bytenr, &logical, &nr, &stripe_len);
255 		if (ret)
256 			return ret;
257 
258 		while (nr--) {
259 			u64 start, len;
260 
261 			if (logical[nr] > cache->key.objectid +
262 			    cache->key.offset)
263 				continue;
264 
265 			if (logical[nr] + stripe_len <= cache->key.objectid)
266 				continue;
267 
268 			start = logical[nr];
269 			if (start < cache->key.objectid) {
270 				start = cache->key.objectid;
271 				len = (logical[nr] + stripe_len) - start;
272 			} else {
273 				len = min_t(u64, stripe_len,
274 					    cache->key.objectid +
275 					    cache->key.offset - start);
276 			}
277 
278 			cache->bytes_super += len;
279 			ret = add_excluded_extent(fs_info, start, len);
280 			if (ret) {
281 				kfree(logical);
282 				return ret;
283 			}
284 		}
285 
286 		kfree(logical);
287 	}
288 	return 0;
289 }
290 
291 static struct btrfs_caching_control *
get_caching_control(struct btrfs_block_group_cache * cache)292 get_caching_control(struct btrfs_block_group_cache *cache)
293 {
294 	struct btrfs_caching_control *ctl;
295 
296 	spin_lock(&cache->lock);
297 	if (!cache->caching_ctl) {
298 		spin_unlock(&cache->lock);
299 		return NULL;
300 	}
301 
302 	ctl = cache->caching_ctl;
303 	refcount_inc(&ctl->count);
304 	spin_unlock(&cache->lock);
305 	return ctl;
306 }
307 
put_caching_control(struct btrfs_caching_control * ctl)308 static void put_caching_control(struct btrfs_caching_control *ctl)
309 {
310 	if (refcount_dec_and_test(&ctl->count))
311 		kfree(ctl);
312 }
313 
314 #ifdef CONFIG_BTRFS_DEBUG
fragment_free_space(struct btrfs_block_group_cache * block_group)315 static void fragment_free_space(struct btrfs_block_group_cache *block_group)
316 {
317 	struct btrfs_fs_info *fs_info = block_group->fs_info;
318 	u64 start = block_group->key.objectid;
319 	u64 len = block_group->key.offset;
320 	u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
321 		fs_info->nodesize : fs_info->sectorsize;
322 	u64 step = chunk << 1;
323 
324 	while (len > chunk) {
325 		btrfs_remove_free_space(block_group, start, chunk);
326 		start += step;
327 		if (len < step)
328 			len = 0;
329 		else
330 			len -= step;
331 	}
332 }
333 #endif
334 
335 /*
336  * this is only called by cache_block_group, since we could have freed extents
337  * we need to check the pinned_extents for any extents that can't be used yet
338  * since their free space will be released as soon as the transaction commits.
339  */
add_new_free_space(struct btrfs_block_group_cache * block_group,u64 start,u64 end)340 u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
341 		       u64 start, u64 end)
342 {
343 	struct btrfs_fs_info *info = block_group->fs_info;
344 	u64 extent_start, extent_end, size, total_added = 0;
345 	int ret;
346 
347 	while (start < end) {
348 		ret = find_first_extent_bit(info->pinned_extents, start,
349 					    &extent_start, &extent_end,
350 					    EXTENT_DIRTY | EXTENT_UPTODATE,
351 					    NULL);
352 		if (ret)
353 			break;
354 
355 		if (extent_start <= start) {
356 			start = extent_end + 1;
357 		} else if (extent_start > start && extent_start < end) {
358 			size = extent_start - start;
359 			total_added += size;
360 			ret = btrfs_add_free_space(block_group, start,
361 						   size);
362 			BUG_ON(ret); /* -ENOMEM or logic error */
363 			start = extent_end + 1;
364 		} else {
365 			break;
366 		}
367 	}
368 
369 	if (start < end) {
370 		size = end - start;
371 		total_added += size;
372 		ret = btrfs_add_free_space(block_group, start, size);
373 		BUG_ON(ret); /* -ENOMEM or logic error */
374 	}
375 
376 	return total_added;
377 }
378 
load_extent_tree_free(struct btrfs_caching_control * caching_ctl)379 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
380 {
381 	struct btrfs_block_group_cache *block_group = caching_ctl->block_group;
382 	struct btrfs_fs_info *fs_info = block_group->fs_info;
383 	struct btrfs_root *extent_root = fs_info->extent_root;
384 	struct btrfs_path *path;
385 	struct extent_buffer *leaf;
386 	struct btrfs_key key;
387 	u64 total_found = 0;
388 	u64 last = 0;
389 	u32 nritems;
390 	int ret;
391 	bool wakeup = true;
392 
393 	path = btrfs_alloc_path();
394 	if (!path)
395 		return -ENOMEM;
396 
397 	last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
398 
399 #ifdef CONFIG_BTRFS_DEBUG
400 	/*
401 	 * If we're fragmenting we don't want to make anybody think we can
402 	 * allocate from this block group until we've had a chance to fragment
403 	 * the free space.
404 	 */
405 	if (btrfs_should_fragment_free_space(block_group))
406 		wakeup = false;
407 #endif
408 	/*
409 	 * We don't want to deadlock with somebody trying to allocate a new
410 	 * extent for the extent root while also trying to search the extent
411 	 * root to add free space.  So we skip locking and search the commit
412 	 * root, since its read-only
413 	 */
414 	path->skip_locking = 1;
415 	path->search_commit_root = 1;
416 	path->reada = READA_FORWARD;
417 
418 	key.objectid = last;
419 	key.offset = 0;
420 	key.type = BTRFS_EXTENT_ITEM_KEY;
421 
422 next:
423 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
424 	if (ret < 0)
425 		goto out;
426 
427 	leaf = path->nodes[0];
428 	nritems = btrfs_header_nritems(leaf);
429 
430 	while (1) {
431 		if (btrfs_fs_closing(fs_info) > 1) {
432 			last = (u64)-1;
433 			break;
434 		}
435 
436 		if (path->slots[0] < nritems) {
437 			btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
438 		} else {
439 			ret = find_next_key(path, 0, &key);
440 			if (ret)
441 				break;
442 
443 			if (need_resched() ||
444 			    rwsem_is_contended(&fs_info->commit_root_sem)) {
445 				if (wakeup)
446 					caching_ctl->progress = last;
447 				btrfs_release_path(path);
448 				up_read(&fs_info->commit_root_sem);
449 				mutex_unlock(&caching_ctl->mutex);
450 				cond_resched();
451 				mutex_lock(&caching_ctl->mutex);
452 				down_read(&fs_info->commit_root_sem);
453 				goto next;
454 			}
455 
456 			ret = btrfs_next_leaf(extent_root, path);
457 			if (ret < 0)
458 				goto out;
459 			if (ret)
460 				break;
461 			leaf = path->nodes[0];
462 			nritems = btrfs_header_nritems(leaf);
463 			continue;
464 		}
465 
466 		if (key.objectid < last) {
467 			key.objectid = last;
468 			key.offset = 0;
469 			key.type = BTRFS_EXTENT_ITEM_KEY;
470 
471 			if (wakeup)
472 				caching_ctl->progress = last;
473 			btrfs_release_path(path);
474 			goto next;
475 		}
476 
477 		if (key.objectid < block_group->key.objectid) {
478 			path->slots[0]++;
479 			continue;
480 		}
481 
482 		if (key.objectid >= block_group->key.objectid +
483 		    block_group->key.offset)
484 			break;
485 
486 		if (key.type == BTRFS_EXTENT_ITEM_KEY ||
487 		    key.type == BTRFS_METADATA_ITEM_KEY) {
488 			total_found += add_new_free_space(block_group, last,
489 							  key.objectid);
490 			if (key.type == BTRFS_METADATA_ITEM_KEY)
491 				last = key.objectid +
492 					fs_info->nodesize;
493 			else
494 				last = key.objectid + key.offset;
495 
496 			if (total_found > CACHING_CTL_WAKE_UP) {
497 				total_found = 0;
498 				if (wakeup)
499 					wake_up(&caching_ctl->wait);
500 			}
501 		}
502 		path->slots[0]++;
503 	}
504 	ret = 0;
505 
506 	total_found += add_new_free_space(block_group, last,
507 					  block_group->key.objectid +
508 					  block_group->key.offset);
509 	caching_ctl->progress = (u64)-1;
510 
511 out:
512 	btrfs_free_path(path);
513 	return ret;
514 }
515 
caching_thread(struct btrfs_work * work)516 static noinline void caching_thread(struct btrfs_work *work)
517 {
518 	struct btrfs_block_group_cache *block_group;
519 	struct btrfs_fs_info *fs_info;
520 	struct btrfs_caching_control *caching_ctl;
521 	int ret;
522 
523 	caching_ctl = container_of(work, struct btrfs_caching_control, work);
524 	block_group = caching_ctl->block_group;
525 	fs_info = block_group->fs_info;
526 
527 	mutex_lock(&caching_ctl->mutex);
528 	down_read(&fs_info->commit_root_sem);
529 
530 	if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
531 		ret = load_free_space_tree(caching_ctl);
532 	else
533 		ret = load_extent_tree_free(caching_ctl);
534 
535 	spin_lock(&block_group->lock);
536 	block_group->caching_ctl = NULL;
537 	block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
538 	spin_unlock(&block_group->lock);
539 
540 #ifdef CONFIG_BTRFS_DEBUG
541 	if (btrfs_should_fragment_free_space(block_group)) {
542 		u64 bytes_used;
543 
544 		spin_lock(&block_group->space_info->lock);
545 		spin_lock(&block_group->lock);
546 		bytes_used = block_group->key.offset -
547 			btrfs_block_group_used(&block_group->item);
548 		block_group->space_info->bytes_used += bytes_used >> 1;
549 		spin_unlock(&block_group->lock);
550 		spin_unlock(&block_group->space_info->lock);
551 		fragment_free_space(block_group);
552 	}
553 #endif
554 
555 	caching_ctl->progress = (u64)-1;
556 
557 	up_read(&fs_info->commit_root_sem);
558 	free_excluded_extents(block_group);
559 	mutex_unlock(&caching_ctl->mutex);
560 
561 	wake_up(&caching_ctl->wait);
562 
563 	put_caching_control(caching_ctl);
564 	btrfs_put_block_group(block_group);
565 }
566 
cache_block_group(struct btrfs_block_group_cache * cache,int load_cache_only)567 static int cache_block_group(struct btrfs_block_group_cache *cache,
568 			     int load_cache_only)
569 {
570 	DEFINE_WAIT(wait);
571 	struct btrfs_fs_info *fs_info = cache->fs_info;
572 	struct btrfs_caching_control *caching_ctl;
573 	int ret = 0;
574 
575 	caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
576 	if (!caching_ctl)
577 		return -ENOMEM;
578 
579 	INIT_LIST_HEAD(&caching_ctl->list);
580 	mutex_init(&caching_ctl->mutex);
581 	init_waitqueue_head(&caching_ctl->wait);
582 	caching_ctl->block_group = cache;
583 	caching_ctl->progress = cache->key.objectid;
584 	refcount_set(&caching_ctl->count, 1);
585 	btrfs_init_work(&caching_ctl->work, btrfs_cache_helper,
586 			caching_thread, NULL, NULL);
587 
588 	spin_lock(&cache->lock);
589 	/*
590 	 * This should be a rare occasion, but this could happen I think in the
591 	 * case where one thread starts to load the space cache info, and then
592 	 * some other thread starts a transaction commit which tries to do an
593 	 * allocation while the other thread is still loading the space cache
594 	 * info.  The previous loop should have kept us from choosing this block
595 	 * group, but if we've moved to the state where we will wait on caching
596 	 * block groups we need to first check if we're doing a fast load here,
597 	 * so we can wait for it to finish, otherwise we could end up allocating
598 	 * from a block group who's cache gets evicted for one reason or
599 	 * another.
600 	 */
601 	while (cache->cached == BTRFS_CACHE_FAST) {
602 		struct btrfs_caching_control *ctl;
603 
604 		ctl = cache->caching_ctl;
605 		refcount_inc(&ctl->count);
606 		prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
607 		spin_unlock(&cache->lock);
608 
609 		schedule();
610 
611 		finish_wait(&ctl->wait, &wait);
612 		put_caching_control(ctl);
613 		spin_lock(&cache->lock);
614 	}
615 
616 	if (cache->cached != BTRFS_CACHE_NO) {
617 		spin_unlock(&cache->lock);
618 		kfree(caching_ctl);
619 		return 0;
620 	}
621 	WARN_ON(cache->caching_ctl);
622 	cache->caching_ctl = caching_ctl;
623 	cache->cached = BTRFS_CACHE_FAST;
624 	spin_unlock(&cache->lock);
625 
626 	if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
627 		mutex_lock(&caching_ctl->mutex);
628 		ret = load_free_space_cache(fs_info, cache);
629 
630 		spin_lock(&cache->lock);
631 		if (ret == 1) {
632 			cache->caching_ctl = NULL;
633 			cache->cached = BTRFS_CACHE_FINISHED;
634 			cache->last_byte_to_unpin = (u64)-1;
635 			caching_ctl->progress = (u64)-1;
636 		} else {
637 			if (load_cache_only) {
638 				cache->caching_ctl = NULL;
639 				cache->cached = BTRFS_CACHE_NO;
640 			} else {
641 				cache->cached = BTRFS_CACHE_STARTED;
642 				cache->has_caching_ctl = 1;
643 			}
644 		}
645 		spin_unlock(&cache->lock);
646 #ifdef CONFIG_BTRFS_DEBUG
647 		if (ret == 1 &&
648 		    btrfs_should_fragment_free_space(cache)) {
649 			u64 bytes_used;
650 
651 			spin_lock(&cache->space_info->lock);
652 			spin_lock(&cache->lock);
653 			bytes_used = cache->key.offset -
654 				btrfs_block_group_used(&cache->item);
655 			cache->space_info->bytes_used += bytes_used >> 1;
656 			spin_unlock(&cache->lock);
657 			spin_unlock(&cache->space_info->lock);
658 			fragment_free_space(cache);
659 		}
660 #endif
661 		mutex_unlock(&caching_ctl->mutex);
662 
663 		wake_up(&caching_ctl->wait);
664 		if (ret == 1) {
665 			put_caching_control(caching_ctl);
666 			free_excluded_extents(cache);
667 			return 0;
668 		}
669 	} else {
670 		/*
671 		 * We're either using the free space tree or no caching at all.
672 		 * Set cached to the appropriate value and wakeup any waiters.
673 		 */
674 		spin_lock(&cache->lock);
675 		if (load_cache_only) {
676 			cache->caching_ctl = NULL;
677 			cache->cached = BTRFS_CACHE_NO;
678 		} else {
679 			cache->cached = BTRFS_CACHE_STARTED;
680 			cache->has_caching_ctl = 1;
681 		}
682 		spin_unlock(&cache->lock);
683 		wake_up(&caching_ctl->wait);
684 	}
685 
686 	if (load_cache_only) {
687 		put_caching_control(caching_ctl);
688 		return 0;
689 	}
690 
691 	down_write(&fs_info->commit_root_sem);
692 	refcount_inc(&caching_ctl->count);
693 	list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
694 	up_write(&fs_info->commit_root_sem);
695 
696 	btrfs_get_block_group(cache);
697 
698 	btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
699 
700 	return ret;
701 }
702 
703 /*
704  * return the block group that starts at or after bytenr
705  */
706 static struct btrfs_block_group_cache *
btrfs_lookup_first_block_group(struct btrfs_fs_info * info,u64 bytenr)707 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
708 {
709 	return block_group_cache_tree_search(info, bytenr, 0);
710 }
711 
712 /*
713  * return the block group that contains the given bytenr
714  */
btrfs_lookup_block_group(struct btrfs_fs_info * info,u64 bytenr)715 struct btrfs_block_group_cache *btrfs_lookup_block_group(
716 						 struct btrfs_fs_info *info,
717 						 u64 bytenr)
718 {
719 	return block_group_cache_tree_search(info, bytenr, 1);
720 }
721 
__find_space_info(struct btrfs_fs_info * info,u64 flags)722 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
723 						  u64 flags)
724 {
725 	struct list_head *head = &info->space_info;
726 	struct btrfs_space_info *found;
727 
728 	flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
729 
730 	rcu_read_lock();
731 	list_for_each_entry_rcu(found, head, list) {
732 		if (found->flags & flags) {
733 			rcu_read_unlock();
734 			return found;
735 		}
736 	}
737 	rcu_read_unlock();
738 	return NULL;
739 }
740 
add_pinned_bytes(struct btrfs_fs_info * fs_info,s64 num_bytes,bool metadata,u64 root_objectid)741 static void add_pinned_bytes(struct btrfs_fs_info *fs_info, s64 num_bytes,
742 			     bool metadata, u64 root_objectid)
743 {
744 	struct btrfs_space_info *space_info;
745 	u64 flags;
746 
747 	if (metadata) {
748 		if (root_objectid == BTRFS_CHUNK_TREE_OBJECTID)
749 			flags = BTRFS_BLOCK_GROUP_SYSTEM;
750 		else
751 			flags = BTRFS_BLOCK_GROUP_METADATA;
752 	} else {
753 		flags = BTRFS_BLOCK_GROUP_DATA;
754 	}
755 
756 	space_info = __find_space_info(fs_info, flags);
757 	ASSERT(space_info);
758 	percpu_counter_add_batch(&space_info->total_bytes_pinned, num_bytes,
759 		    BTRFS_TOTAL_BYTES_PINNED_BATCH);
760 }
761 
762 /*
763  * after adding space to the filesystem, we need to clear the full flags
764  * on all the space infos.
765  */
btrfs_clear_space_info_full(struct btrfs_fs_info * info)766 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
767 {
768 	struct list_head *head = &info->space_info;
769 	struct btrfs_space_info *found;
770 
771 	rcu_read_lock();
772 	list_for_each_entry_rcu(found, head, list)
773 		found->full = 0;
774 	rcu_read_unlock();
775 }
776 
777 /* simple helper to search for an existing data extent at a given offset */
btrfs_lookup_data_extent(struct btrfs_fs_info * fs_info,u64 start,u64 len)778 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
779 {
780 	int ret;
781 	struct btrfs_key key;
782 	struct btrfs_path *path;
783 
784 	path = btrfs_alloc_path();
785 	if (!path)
786 		return -ENOMEM;
787 
788 	key.objectid = start;
789 	key.offset = len;
790 	key.type = BTRFS_EXTENT_ITEM_KEY;
791 	ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
792 	btrfs_free_path(path);
793 	return ret;
794 }
795 
796 /*
797  * helper function to lookup reference count and flags of a tree block.
798  *
799  * the head node for delayed ref is used to store the sum of all the
800  * reference count modifications queued up in the rbtree. the head
801  * node may also store the extent flags to set. This way you can check
802  * to see what the reference count and extent flags would be if all of
803  * the delayed refs are not processed.
804  */
btrfs_lookup_extent_info(struct btrfs_trans_handle * trans,struct btrfs_fs_info * fs_info,u64 bytenr,u64 offset,int metadata,u64 * refs,u64 * flags)805 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
806 			     struct btrfs_fs_info *fs_info, u64 bytenr,
807 			     u64 offset, int metadata, u64 *refs, u64 *flags)
808 {
809 	struct btrfs_delayed_ref_head *head;
810 	struct btrfs_delayed_ref_root *delayed_refs;
811 	struct btrfs_path *path;
812 	struct btrfs_extent_item *ei;
813 	struct extent_buffer *leaf;
814 	struct btrfs_key key;
815 	u32 item_size;
816 	u64 num_refs;
817 	u64 extent_flags;
818 	int ret;
819 
820 	/*
821 	 * If we don't have skinny metadata, don't bother doing anything
822 	 * different
823 	 */
824 	if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
825 		offset = fs_info->nodesize;
826 		metadata = 0;
827 	}
828 
829 	path = btrfs_alloc_path();
830 	if (!path)
831 		return -ENOMEM;
832 
833 	if (!trans) {
834 		path->skip_locking = 1;
835 		path->search_commit_root = 1;
836 	}
837 
838 search_again:
839 	key.objectid = bytenr;
840 	key.offset = offset;
841 	if (metadata)
842 		key.type = BTRFS_METADATA_ITEM_KEY;
843 	else
844 		key.type = BTRFS_EXTENT_ITEM_KEY;
845 
846 	ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
847 	if (ret < 0)
848 		goto out_free;
849 
850 	if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
851 		if (path->slots[0]) {
852 			path->slots[0]--;
853 			btrfs_item_key_to_cpu(path->nodes[0], &key,
854 					      path->slots[0]);
855 			if (key.objectid == bytenr &&
856 			    key.type == BTRFS_EXTENT_ITEM_KEY &&
857 			    key.offset == fs_info->nodesize)
858 				ret = 0;
859 		}
860 	}
861 
862 	if (ret == 0) {
863 		leaf = path->nodes[0];
864 		item_size = btrfs_item_size_nr(leaf, path->slots[0]);
865 		if (item_size >= sizeof(*ei)) {
866 			ei = btrfs_item_ptr(leaf, path->slots[0],
867 					    struct btrfs_extent_item);
868 			num_refs = btrfs_extent_refs(leaf, ei);
869 			extent_flags = btrfs_extent_flags(leaf, ei);
870 		} else {
871 			ret = -EINVAL;
872 			btrfs_print_v0_err(fs_info);
873 			if (trans)
874 				btrfs_abort_transaction(trans, ret);
875 			else
876 				btrfs_handle_fs_error(fs_info, ret, NULL);
877 
878 			goto out_free;
879 		}
880 
881 		BUG_ON(num_refs == 0);
882 	} else {
883 		num_refs = 0;
884 		extent_flags = 0;
885 		ret = 0;
886 	}
887 
888 	if (!trans)
889 		goto out;
890 
891 	delayed_refs = &trans->transaction->delayed_refs;
892 	spin_lock(&delayed_refs->lock);
893 	head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
894 	if (head) {
895 		if (!mutex_trylock(&head->mutex)) {
896 			refcount_inc(&head->refs);
897 			spin_unlock(&delayed_refs->lock);
898 
899 			btrfs_release_path(path);
900 
901 			/*
902 			 * Mutex was contended, block until it's released and try
903 			 * again
904 			 */
905 			mutex_lock(&head->mutex);
906 			mutex_unlock(&head->mutex);
907 			btrfs_put_delayed_ref_head(head);
908 			goto search_again;
909 		}
910 		spin_lock(&head->lock);
911 		if (head->extent_op && head->extent_op->update_flags)
912 			extent_flags |= head->extent_op->flags_to_set;
913 		else
914 			BUG_ON(num_refs == 0);
915 
916 		num_refs += head->ref_mod;
917 		spin_unlock(&head->lock);
918 		mutex_unlock(&head->mutex);
919 	}
920 	spin_unlock(&delayed_refs->lock);
921 out:
922 	WARN_ON(num_refs == 0);
923 	if (refs)
924 		*refs = num_refs;
925 	if (flags)
926 		*flags = extent_flags;
927 out_free:
928 	btrfs_free_path(path);
929 	return ret;
930 }
931 
932 /*
933  * Back reference rules.  Back refs have three main goals:
934  *
935  * 1) differentiate between all holders of references to an extent so that
936  *    when a reference is dropped we can make sure it was a valid reference
937  *    before freeing the extent.
938  *
939  * 2) Provide enough information to quickly find the holders of an extent
940  *    if we notice a given block is corrupted or bad.
941  *
942  * 3) Make it easy to migrate blocks for FS shrinking or storage pool
943  *    maintenance.  This is actually the same as #2, but with a slightly
944  *    different use case.
945  *
946  * There are two kinds of back refs. The implicit back refs is optimized
947  * for pointers in non-shared tree blocks. For a given pointer in a block,
948  * back refs of this kind provide information about the block's owner tree
949  * and the pointer's key. These information allow us to find the block by
950  * b-tree searching. The full back refs is for pointers in tree blocks not
951  * referenced by their owner trees. The location of tree block is recorded
952  * in the back refs. Actually the full back refs is generic, and can be
953  * used in all cases the implicit back refs is used. The major shortcoming
954  * of the full back refs is its overhead. Every time a tree block gets
955  * COWed, we have to update back refs entry for all pointers in it.
956  *
957  * For a newly allocated tree block, we use implicit back refs for
958  * pointers in it. This means most tree related operations only involve
959  * implicit back refs. For a tree block created in old transaction, the
960  * only way to drop a reference to it is COW it. So we can detect the
961  * event that tree block loses its owner tree's reference and do the
962  * back refs conversion.
963  *
964  * When a tree block is COWed through a tree, there are four cases:
965  *
966  * The reference count of the block is one and the tree is the block's
967  * owner tree. Nothing to do in this case.
968  *
969  * The reference count of the block is one and the tree is not the
970  * block's owner tree. In this case, full back refs is used for pointers
971  * in the block. Remove these full back refs, add implicit back refs for
972  * every pointers in the new block.
973  *
974  * The reference count of the block is greater than one and the tree is
975  * the block's owner tree. In this case, implicit back refs is used for
976  * pointers in the block. Add full back refs for every pointers in the
977  * block, increase lower level extents' reference counts. The original
978  * implicit back refs are entailed to the new block.
979  *
980  * The reference count of the block is greater than one and the tree is
981  * not the block's owner tree. Add implicit back refs for every pointer in
982  * the new block, increase lower level extents' reference count.
983  *
984  * Back Reference Key composing:
985  *
986  * The key objectid corresponds to the first byte in the extent,
987  * The key type is used to differentiate between types of back refs.
988  * There are different meanings of the key offset for different types
989  * of back refs.
990  *
991  * File extents can be referenced by:
992  *
993  * - multiple snapshots, subvolumes, or different generations in one subvol
994  * - different files inside a single subvolume
995  * - different offsets inside a file (bookend extents in file.c)
996  *
997  * The extent ref structure for the implicit back refs has fields for:
998  *
999  * - Objectid of the subvolume root
1000  * - objectid of the file holding the reference
1001  * - original offset in the file
1002  * - how many bookend extents
1003  *
1004  * The key offset for the implicit back refs is hash of the first
1005  * three fields.
1006  *
1007  * The extent ref structure for the full back refs has field for:
1008  *
1009  * - number of pointers in the tree leaf
1010  *
1011  * The key offset for the implicit back refs is the first byte of
1012  * the tree leaf
1013  *
1014  * When a file extent is allocated, The implicit back refs is used.
1015  * the fields are filled in:
1016  *
1017  *     (root_key.objectid, inode objectid, offset in file, 1)
1018  *
1019  * When a file extent is removed file truncation, we find the
1020  * corresponding implicit back refs and check the following fields:
1021  *
1022  *     (btrfs_header_owner(leaf), inode objectid, offset in file)
1023  *
1024  * Btree extents can be referenced by:
1025  *
1026  * - Different subvolumes
1027  *
1028  * Both the implicit back refs and the full back refs for tree blocks
1029  * only consist of key. The key offset for the implicit back refs is
1030  * objectid of block's owner tree. The key offset for the full back refs
1031  * is the first byte of parent block.
1032  *
1033  * When implicit back refs is used, information about the lowest key and
1034  * level of the tree block are required. These information are stored in
1035  * tree block info structure.
1036  */
1037 
1038 /*
1039  * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
1040  * is_data == BTRFS_REF_TYPE_DATA, data type is requried,
1041  * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
1042  */
btrfs_get_extent_inline_ref_type(const struct extent_buffer * eb,struct btrfs_extent_inline_ref * iref,enum btrfs_inline_ref_type is_data)1043 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
1044 				     struct btrfs_extent_inline_ref *iref,
1045 				     enum btrfs_inline_ref_type is_data)
1046 {
1047 	int type = btrfs_extent_inline_ref_type(eb, iref);
1048 	u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
1049 
1050 	if (type == BTRFS_TREE_BLOCK_REF_KEY ||
1051 	    type == BTRFS_SHARED_BLOCK_REF_KEY ||
1052 	    type == BTRFS_SHARED_DATA_REF_KEY ||
1053 	    type == BTRFS_EXTENT_DATA_REF_KEY) {
1054 		if (is_data == BTRFS_REF_TYPE_BLOCK) {
1055 			if (type == BTRFS_TREE_BLOCK_REF_KEY)
1056 				return type;
1057 			if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1058 				ASSERT(eb->fs_info);
1059 				/*
1060 				 * Every shared one has parent tree block,
1061 				 * which must be aligned to sector size.
1062 				 */
1063 				if (offset &&
1064 				    IS_ALIGNED(offset, eb->fs_info->sectorsize))
1065 					return type;
1066 			}
1067 		} else if (is_data == BTRFS_REF_TYPE_DATA) {
1068 			if (type == BTRFS_EXTENT_DATA_REF_KEY)
1069 				return type;
1070 			if (type == BTRFS_SHARED_DATA_REF_KEY) {
1071 				ASSERT(eb->fs_info);
1072 				/*
1073 				 * Every shared one has parent tree block,
1074 				 * which must be aligned to sector size.
1075 				 */
1076 				if (offset &&
1077 				    IS_ALIGNED(offset, eb->fs_info->sectorsize))
1078 					return type;
1079 			}
1080 		} else {
1081 			ASSERT(is_data == BTRFS_REF_TYPE_ANY);
1082 			return type;
1083 		}
1084 	}
1085 
1086 	btrfs_print_leaf((struct extent_buffer *)eb);
1087 	btrfs_err(eb->fs_info,
1088 		  "eb %llu iref 0x%lx invalid extent inline ref type %d",
1089 		  eb->start, (unsigned long)iref, type);
1090 	WARN_ON(1);
1091 
1092 	return BTRFS_REF_TYPE_INVALID;
1093 }
1094 
hash_extent_data_ref(u64 root_objectid,u64 owner,u64 offset)1095 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1096 {
1097 	u32 high_crc = ~(u32)0;
1098 	u32 low_crc = ~(u32)0;
1099 	__le64 lenum;
1100 
1101 	lenum = cpu_to_le64(root_objectid);
1102 	high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
1103 	lenum = cpu_to_le64(owner);
1104 	low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
1105 	lenum = cpu_to_le64(offset);
1106 	low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
1107 
1108 	return ((u64)high_crc << 31) ^ (u64)low_crc;
1109 }
1110 
hash_extent_data_ref_item(struct extent_buffer * leaf,struct btrfs_extent_data_ref * ref)1111 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1112 				     struct btrfs_extent_data_ref *ref)
1113 {
1114 	return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1115 				    btrfs_extent_data_ref_objectid(leaf, ref),
1116 				    btrfs_extent_data_ref_offset(leaf, ref));
1117 }
1118 
match_extent_data_ref(struct extent_buffer * leaf,struct btrfs_extent_data_ref * ref,u64 root_objectid,u64 owner,u64 offset)1119 static int match_extent_data_ref(struct extent_buffer *leaf,
1120 				 struct btrfs_extent_data_ref *ref,
1121 				 u64 root_objectid, u64 owner, u64 offset)
1122 {
1123 	if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1124 	    btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1125 	    btrfs_extent_data_ref_offset(leaf, ref) != offset)
1126 		return 0;
1127 	return 1;
1128 }
1129 
lookup_extent_data_ref(struct btrfs_trans_handle * trans,struct btrfs_path * path,u64 bytenr,u64 parent,u64 root_objectid,u64 owner,u64 offset)1130 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1131 					   struct btrfs_path *path,
1132 					   u64 bytenr, u64 parent,
1133 					   u64 root_objectid,
1134 					   u64 owner, u64 offset)
1135 {
1136 	struct btrfs_root *root = trans->fs_info->extent_root;
1137 	struct btrfs_key key;
1138 	struct btrfs_extent_data_ref *ref;
1139 	struct extent_buffer *leaf;
1140 	u32 nritems;
1141 	int ret;
1142 	int recow;
1143 	int err = -ENOENT;
1144 
1145 	key.objectid = bytenr;
1146 	if (parent) {
1147 		key.type = BTRFS_SHARED_DATA_REF_KEY;
1148 		key.offset = parent;
1149 	} else {
1150 		key.type = BTRFS_EXTENT_DATA_REF_KEY;
1151 		key.offset = hash_extent_data_ref(root_objectid,
1152 						  owner, offset);
1153 	}
1154 again:
1155 	recow = 0;
1156 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1157 	if (ret < 0) {
1158 		err = ret;
1159 		goto fail;
1160 	}
1161 
1162 	if (parent) {
1163 		if (!ret)
1164 			return 0;
1165 		goto fail;
1166 	}
1167 
1168 	leaf = path->nodes[0];
1169 	nritems = btrfs_header_nritems(leaf);
1170 	while (1) {
1171 		if (path->slots[0] >= nritems) {
1172 			ret = btrfs_next_leaf(root, path);
1173 			if (ret < 0)
1174 				err = ret;
1175 			if (ret)
1176 				goto fail;
1177 
1178 			leaf = path->nodes[0];
1179 			nritems = btrfs_header_nritems(leaf);
1180 			recow = 1;
1181 		}
1182 
1183 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1184 		if (key.objectid != bytenr ||
1185 		    key.type != BTRFS_EXTENT_DATA_REF_KEY)
1186 			goto fail;
1187 
1188 		ref = btrfs_item_ptr(leaf, path->slots[0],
1189 				     struct btrfs_extent_data_ref);
1190 
1191 		if (match_extent_data_ref(leaf, ref, root_objectid,
1192 					  owner, offset)) {
1193 			if (recow) {
1194 				btrfs_release_path(path);
1195 				goto again;
1196 			}
1197 			err = 0;
1198 			break;
1199 		}
1200 		path->slots[0]++;
1201 	}
1202 fail:
1203 	return err;
1204 }
1205 
insert_extent_data_ref(struct btrfs_trans_handle * trans,struct btrfs_path * path,u64 bytenr,u64 parent,u64 root_objectid,u64 owner,u64 offset,int refs_to_add)1206 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1207 					   struct btrfs_path *path,
1208 					   u64 bytenr, u64 parent,
1209 					   u64 root_objectid, u64 owner,
1210 					   u64 offset, int refs_to_add)
1211 {
1212 	struct btrfs_root *root = trans->fs_info->extent_root;
1213 	struct btrfs_key key;
1214 	struct extent_buffer *leaf;
1215 	u32 size;
1216 	u32 num_refs;
1217 	int ret;
1218 
1219 	key.objectid = bytenr;
1220 	if (parent) {
1221 		key.type = BTRFS_SHARED_DATA_REF_KEY;
1222 		key.offset = parent;
1223 		size = sizeof(struct btrfs_shared_data_ref);
1224 	} else {
1225 		key.type = BTRFS_EXTENT_DATA_REF_KEY;
1226 		key.offset = hash_extent_data_ref(root_objectid,
1227 						  owner, offset);
1228 		size = sizeof(struct btrfs_extent_data_ref);
1229 	}
1230 
1231 	ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1232 	if (ret && ret != -EEXIST)
1233 		goto fail;
1234 
1235 	leaf = path->nodes[0];
1236 	if (parent) {
1237 		struct btrfs_shared_data_ref *ref;
1238 		ref = btrfs_item_ptr(leaf, path->slots[0],
1239 				     struct btrfs_shared_data_ref);
1240 		if (ret == 0) {
1241 			btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1242 		} else {
1243 			num_refs = btrfs_shared_data_ref_count(leaf, ref);
1244 			num_refs += refs_to_add;
1245 			btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1246 		}
1247 	} else {
1248 		struct btrfs_extent_data_ref *ref;
1249 		while (ret == -EEXIST) {
1250 			ref = btrfs_item_ptr(leaf, path->slots[0],
1251 					     struct btrfs_extent_data_ref);
1252 			if (match_extent_data_ref(leaf, ref, root_objectid,
1253 						  owner, offset))
1254 				break;
1255 			btrfs_release_path(path);
1256 			key.offset++;
1257 			ret = btrfs_insert_empty_item(trans, root, path, &key,
1258 						      size);
1259 			if (ret && ret != -EEXIST)
1260 				goto fail;
1261 
1262 			leaf = path->nodes[0];
1263 		}
1264 		ref = btrfs_item_ptr(leaf, path->slots[0],
1265 				     struct btrfs_extent_data_ref);
1266 		if (ret == 0) {
1267 			btrfs_set_extent_data_ref_root(leaf, ref,
1268 						       root_objectid);
1269 			btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1270 			btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1271 			btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1272 		} else {
1273 			num_refs = btrfs_extent_data_ref_count(leaf, ref);
1274 			num_refs += refs_to_add;
1275 			btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1276 		}
1277 	}
1278 	btrfs_mark_buffer_dirty(leaf);
1279 	ret = 0;
1280 fail:
1281 	btrfs_release_path(path);
1282 	return ret;
1283 }
1284 
remove_extent_data_ref(struct btrfs_trans_handle * trans,struct btrfs_path * path,int refs_to_drop,int * last_ref)1285 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1286 					   struct btrfs_path *path,
1287 					   int refs_to_drop, int *last_ref)
1288 {
1289 	struct btrfs_key key;
1290 	struct btrfs_extent_data_ref *ref1 = NULL;
1291 	struct btrfs_shared_data_ref *ref2 = NULL;
1292 	struct extent_buffer *leaf;
1293 	u32 num_refs = 0;
1294 	int ret = 0;
1295 
1296 	leaf = path->nodes[0];
1297 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1298 
1299 	if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1300 		ref1 = btrfs_item_ptr(leaf, path->slots[0],
1301 				      struct btrfs_extent_data_ref);
1302 		num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1303 	} else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1304 		ref2 = btrfs_item_ptr(leaf, path->slots[0],
1305 				      struct btrfs_shared_data_ref);
1306 		num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1307 	} else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
1308 		btrfs_print_v0_err(trans->fs_info);
1309 		btrfs_abort_transaction(trans, -EINVAL);
1310 		return -EINVAL;
1311 	} else {
1312 		BUG();
1313 	}
1314 
1315 	BUG_ON(num_refs < refs_to_drop);
1316 	num_refs -= refs_to_drop;
1317 
1318 	if (num_refs == 0) {
1319 		ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1320 		*last_ref = 1;
1321 	} else {
1322 		if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1323 			btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1324 		else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1325 			btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1326 		btrfs_mark_buffer_dirty(leaf);
1327 	}
1328 	return ret;
1329 }
1330 
extent_data_ref_count(struct btrfs_path * path,struct btrfs_extent_inline_ref * iref)1331 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
1332 					  struct btrfs_extent_inline_ref *iref)
1333 {
1334 	struct btrfs_key key;
1335 	struct extent_buffer *leaf;
1336 	struct btrfs_extent_data_ref *ref1;
1337 	struct btrfs_shared_data_ref *ref2;
1338 	u32 num_refs = 0;
1339 	int type;
1340 
1341 	leaf = path->nodes[0];
1342 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1343 
1344 	BUG_ON(key.type == BTRFS_EXTENT_REF_V0_KEY);
1345 	if (iref) {
1346 		/*
1347 		 * If type is invalid, we should have bailed out earlier than
1348 		 * this call.
1349 		 */
1350 		type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
1351 		ASSERT(type != BTRFS_REF_TYPE_INVALID);
1352 		if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1353 			ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1354 			num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1355 		} else {
1356 			ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1357 			num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1358 		}
1359 	} else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1360 		ref1 = btrfs_item_ptr(leaf, path->slots[0],
1361 				      struct btrfs_extent_data_ref);
1362 		num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1363 	} else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1364 		ref2 = btrfs_item_ptr(leaf, path->slots[0],
1365 				      struct btrfs_shared_data_ref);
1366 		num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1367 	} else {
1368 		WARN_ON(1);
1369 	}
1370 	return num_refs;
1371 }
1372 
lookup_tree_block_ref(struct btrfs_trans_handle * trans,struct btrfs_path * path,u64 bytenr,u64 parent,u64 root_objectid)1373 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1374 					  struct btrfs_path *path,
1375 					  u64 bytenr, u64 parent,
1376 					  u64 root_objectid)
1377 {
1378 	struct btrfs_root *root = trans->fs_info->extent_root;
1379 	struct btrfs_key key;
1380 	int ret;
1381 
1382 	key.objectid = bytenr;
1383 	if (parent) {
1384 		key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1385 		key.offset = parent;
1386 	} else {
1387 		key.type = BTRFS_TREE_BLOCK_REF_KEY;
1388 		key.offset = root_objectid;
1389 	}
1390 
1391 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1392 	if (ret > 0)
1393 		ret = -ENOENT;
1394 	return ret;
1395 }
1396 
insert_tree_block_ref(struct btrfs_trans_handle * trans,struct btrfs_path * path,u64 bytenr,u64 parent,u64 root_objectid)1397 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1398 					  struct btrfs_path *path,
1399 					  u64 bytenr, u64 parent,
1400 					  u64 root_objectid)
1401 {
1402 	struct btrfs_key key;
1403 	int ret;
1404 
1405 	key.objectid = bytenr;
1406 	if (parent) {
1407 		key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1408 		key.offset = parent;
1409 	} else {
1410 		key.type = BTRFS_TREE_BLOCK_REF_KEY;
1411 		key.offset = root_objectid;
1412 	}
1413 
1414 	ret = btrfs_insert_empty_item(trans, trans->fs_info->extent_root,
1415 				      path, &key, 0);
1416 	btrfs_release_path(path);
1417 	return ret;
1418 }
1419 
extent_ref_type(u64 parent,u64 owner)1420 static inline int extent_ref_type(u64 parent, u64 owner)
1421 {
1422 	int type;
1423 	if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1424 		if (parent > 0)
1425 			type = BTRFS_SHARED_BLOCK_REF_KEY;
1426 		else
1427 			type = BTRFS_TREE_BLOCK_REF_KEY;
1428 	} else {
1429 		if (parent > 0)
1430 			type = BTRFS_SHARED_DATA_REF_KEY;
1431 		else
1432 			type = BTRFS_EXTENT_DATA_REF_KEY;
1433 	}
1434 	return type;
1435 }
1436 
find_next_key(struct btrfs_path * path,int level,struct btrfs_key * key)1437 static int find_next_key(struct btrfs_path *path, int level,
1438 			 struct btrfs_key *key)
1439 
1440 {
1441 	for (; level < BTRFS_MAX_LEVEL; level++) {
1442 		if (!path->nodes[level])
1443 			break;
1444 		if (path->slots[level] + 1 >=
1445 		    btrfs_header_nritems(path->nodes[level]))
1446 			continue;
1447 		if (level == 0)
1448 			btrfs_item_key_to_cpu(path->nodes[level], key,
1449 					      path->slots[level] + 1);
1450 		else
1451 			btrfs_node_key_to_cpu(path->nodes[level], key,
1452 					      path->slots[level] + 1);
1453 		return 0;
1454 	}
1455 	return 1;
1456 }
1457 
1458 /*
1459  * look for inline back ref. if back ref is found, *ref_ret is set
1460  * to the address of inline back ref, and 0 is returned.
1461  *
1462  * if back ref isn't found, *ref_ret is set to the address where it
1463  * should be inserted, and -ENOENT is returned.
1464  *
1465  * if insert is true and there are too many inline back refs, the path
1466  * points to the extent item, and -EAGAIN is returned.
1467  *
1468  * NOTE: inline back refs are ordered in the same way that back ref
1469  *	 items in the tree are ordered.
1470  */
1471 static noinline_for_stack
lookup_inline_extent_backref(struct btrfs_trans_handle * trans,struct btrfs_path * path,struct btrfs_extent_inline_ref ** ref_ret,u64 bytenr,u64 num_bytes,u64 parent,u64 root_objectid,u64 owner,u64 offset,int insert)1472 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1473 				 struct btrfs_path *path,
1474 				 struct btrfs_extent_inline_ref **ref_ret,
1475 				 u64 bytenr, u64 num_bytes,
1476 				 u64 parent, u64 root_objectid,
1477 				 u64 owner, u64 offset, int insert)
1478 {
1479 	struct btrfs_fs_info *fs_info = trans->fs_info;
1480 	struct btrfs_root *root = fs_info->extent_root;
1481 	struct btrfs_key key;
1482 	struct extent_buffer *leaf;
1483 	struct btrfs_extent_item *ei;
1484 	struct btrfs_extent_inline_ref *iref;
1485 	u64 flags;
1486 	u64 item_size;
1487 	unsigned long ptr;
1488 	unsigned long end;
1489 	int extra_size;
1490 	int type;
1491 	int want;
1492 	int ret;
1493 	int err = 0;
1494 	bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
1495 	int needed;
1496 
1497 	key.objectid = bytenr;
1498 	key.type = BTRFS_EXTENT_ITEM_KEY;
1499 	key.offset = num_bytes;
1500 
1501 	want = extent_ref_type(parent, owner);
1502 	if (insert) {
1503 		extra_size = btrfs_extent_inline_ref_size(want);
1504 		path->keep_locks = 1;
1505 	} else
1506 		extra_size = -1;
1507 
1508 	/*
1509 	 * Owner is our level, so we can just add one to get the level for the
1510 	 * block we are interested in.
1511 	 */
1512 	if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1513 		key.type = BTRFS_METADATA_ITEM_KEY;
1514 		key.offset = owner;
1515 	}
1516 
1517 again:
1518 	ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1519 	if (ret < 0) {
1520 		err = ret;
1521 		goto out;
1522 	}
1523 
1524 	/*
1525 	 * We may be a newly converted file system which still has the old fat
1526 	 * extent entries for metadata, so try and see if we have one of those.
1527 	 */
1528 	if (ret > 0 && skinny_metadata) {
1529 		skinny_metadata = false;
1530 		if (path->slots[0]) {
1531 			path->slots[0]--;
1532 			btrfs_item_key_to_cpu(path->nodes[0], &key,
1533 					      path->slots[0]);
1534 			if (key.objectid == bytenr &&
1535 			    key.type == BTRFS_EXTENT_ITEM_KEY &&
1536 			    key.offset == num_bytes)
1537 				ret = 0;
1538 		}
1539 		if (ret) {
1540 			key.objectid = bytenr;
1541 			key.type = BTRFS_EXTENT_ITEM_KEY;
1542 			key.offset = num_bytes;
1543 			btrfs_release_path(path);
1544 			goto again;
1545 		}
1546 	}
1547 
1548 	if (ret && !insert) {
1549 		err = -ENOENT;
1550 		goto out;
1551 	} else if (WARN_ON(ret)) {
1552 		err = -EIO;
1553 		goto out;
1554 	}
1555 
1556 	leaf = path->nodes[0];
1557 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1558 	if (unlikely(item_size < sizeof(*ei))) {
1559 		err = -EINVAL;
1560 		btrfs_print_v0_err(fs_info);
1561 		btrfs_abort_transaction(trans, err);
1562 		goto out;
1563 	}
1564 
1565 	ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1566 	flags = btrfs_extent_flags(leaf, ei);
1567 
1568 	ptr = (unsigned long)(ei + 1);
1569 	end = (unsigned long)ei + item_size;
1570 
1571 	if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
1572 		ptr += sizeof(struct btrfs_tree_block_info);
1573 		BUG_ON(ptr > end);
1574 	}
1575 
1576 	if (owner >= BTRFS_FIRST_FREE_OBJECTID)
1577 		needed = BTRFS_REF_TYPE_DATA;
1578 	else
1579 		needed = BTRFS_REF_TYPE_BLOCK;
1580 
1581 	err = -ENOENT;
1582 	while (1) {
1583 		if (ptr >= end) {
1584 			WARN_ON(ptr > end);
1585 			break;
1586 		}
1587 		iref = (struct btrfs_extent_inline_ref *)ptr;
1588 		type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
1589 		if (type == BTRFS_REF_TYPE_INVALID) {
1590 			err = -EUCLEAN;
1591 			goto out;
1592 		}
1593 
1594 		if (want < type)
1595 			break;
1596 		if (want > type) {
1597 			ptr += btrfs_extent_inline_ref_size(type);
1598 			continue;
1599 		}
1600 
1601 		if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1602 			struct btrfs_extent_data_ref *dref;
1603 			dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1604 			if (match_extent_data_ref(leaf, dref, root_objectid,
1605 						  owner, offset)) {
1606 				err = 0;
1607 				break;
1608 			}
1609 			if (hash_extent_data_ref_item(leaf, dref) <
1610 			    hash_extent_data_ref(root_objectid, owner, offset))
1611 				break;
1612 		} else {
1613 			u64 ref_offset;
1614 			ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1615 			if (parent > 0) {
1616 				if (parent == ref_offset) {
1617 					err = 0;
1618 					break;
1619 				}
1620 				if (ref_offset < parent)
1621 					break;
1622 			} else {
1623 				if (root_objectid == ref_offset) {
1624 					err = 0;
1625 					break;
1626 				}
1627 				if (ref_offset < root_objectid)
1628 					break;
1629 			}
1630 		}
1631 		ptr += btrfs_extent_inline_ref_size(type);
1632 	}
1633 	if (err == -ENOENT && insert) {
1634 		if (item_size + extra_size >=
1635 		    BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1636 			err = -EAGAIN;
1637 			goto out;
1638 		}
1639 		/*
1640 		 * To add new inline back ref, we have to make sure
1641 		 * there is no corresponding back ref item.
1642 		 * For simplicity, we just do not add new inline back
1643 		 * ref if there is any kind of item for this block
1644 		 */
1645 		if (find_next_key(path, 0, &key) == 0 &&
1646 		    key.objectid == bytenr &&
1647 		    key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1648 			err = -EAGAIN;
1649 			goto out;
1650 		}
1651 	}
1652 	*ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1653 out:
1654 	if (insert) {
1655 		path->keep_locks = 0;
1656 		btrfs_unlock_up_safe(path, 1);
1657 	}
1658 	return err;
1659 }
1660 
1661 /*
1662  * helper to add new inline back ref
1663  */
1664 static noinline_for_stack
setup_inline_extent_backref(struct btrfs_fs_info * fs_info,struct btrfs_path * path,struct btrfs_extent_inline_ref * iref,u64 parent,u64 root_objectid,u64 owner,u64 offset,int refs_to_add,struct btrfs_delayed_extent_op * extent_op)1665 void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
1666 				 struct btrfs_path *path,
1667 				 struct btrfs_extent_inline_ref *iref,
1668 				 u64 parent, u64 root_objectid,
1669 				 u64 owner, u64 offset, int refs_to_add,
1670 				 struct btrfs_delayed_extent_op *extent_op)
1671 {
1672 	struct extent_buffer *leaf;
1673 	struct btrfs_extent_item *ei;
1674 	unsigned long ptr;
1675 	unsigned long end;
1676 	unsigned long item_offset;
1677 	u64 refs;
1678 	int size;
1679 	int type;
1680 
1681 	leaf = path->nodes[0];
1682 	ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1683 	item_offset = (unsigned long)iref - (unsigned long)ei;
1684 
1685 	type = extent_ref_type(parent, owner);
1686 	size = btrfs_extent_inline_ref_size(type);
1687 
1688 	btrfs_extend_item(fs_info, path, size);
1689 
1690 	ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1691 	refs = btrfs_extent_refs(leaf, ei);
1692 	refs += refs_to_add;
1693 	btrfs_set_extent_refs(leaf, ei, refs);
1694 	if (extent_op)
1695 		__run_delayed_extent_op(extent_op, leaf, ei);
1696 
1697 	ptr = (unsigned long)ei + item_offset;
1698 	end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1699 	if (ptr < end - size)
1700 		memmove_extent_buffer(leaf, ptr + size, ptr,
1701 				      end - size - ptr);
1702 
1703 	iref = (struct btrfs_extent_inline_ref *)ptr;
1704 	btrfs_set_extent_inline_ref_type(leaf, iref, type);
1705 	if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1706 		struct btrfs_extent_data_ref *dref;
1707 		dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1708 		btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1709 		btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1710 		btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1711 		btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1712 	} else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1713 		struct btrfs_shared_data_ref *sref;
1714 		sref = (struct btrfs_shared_data_ref *)(iref + 1);
1715 		btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1716 		btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1717 	} else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1718 		btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1719 	} else {
1720 		btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1721 	}
1722 	btrfs_mark_buffer_dirty(leaf);
1723 }
1724 
lookup_extent_backref(struct btrfs_trans_handle * trans,struct btrfs_path * path,struct btrfs_extent_inline_ref ** ref_ret,u64 bytenr,u64 num_bytes,u64 parent,u64 root_objectid,u64 owner,u64 offset)1725 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1726 				 struct btrfs_path *path,
1727 				 struct btrfs_extent_inline_ref **ref_ret,
1728 				 u64 bytenr, u64 num_bytes, u64 parent,
1729 				 u64 root_objectid, u64 owner, u64 offset)
1730 {
1731 	int ret;
1732 
1733 	ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1734 					   num_bytes, parent, root_objectid,
1735 					   owner, offset, 0);
1736 	if (ret != -ENOENT)
1737 		return ret;
1738 
1739 	btrfs_release_path(path);
1740 	*ref_ret = NULL;
1741 
1742 	if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1743 		ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1744 					    root_objectid);
1745 	} else {
1746 		ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1747 					     root_objectid, owner, offset);
1748 	}
1749 	return ret;
1750 }
1751 
1752 /*
1753  * helper to update/remove inline back ref
1754  */
1755 static noinline_for_stack
update_inline_extent_backref(struct btrfs_path * path,struct btrfs_extent_inline_ref * iref,int refs_to_mod,struct btrfs_delayed_extent_op * extent_op,int * last_ref)1756 void update_inline_extent_backref(struct btrfs_path *path,
1757 				  struct btrfs_extent_inline_ref *iref,
1758 				  int refs_to_mod,
1759 				  struct btrfs_delayed_extent_op *extent_op,
1760 				  int *last_ref)
1761 {
1762 	struct extent_buffer *leaf = path->nodes[0];
1763 	struct btrfs_fs_info *fs_info = leaf->fs_info;
1764 	struct btrfs_extent_item *ei;
1765 	struct btrfs_extent_data_ref *dref = NULL;
1766 	struct btrfs_shared_data_ref *sref = NULL;
1767 	unsigned long ptr;
1768 	unsigned long end;
1769 	u32 item_size;
1770 	int size;
1771 	int type;
1772 	u64 refs;
1773 
1774 	ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1775 	refs = btrfs_extent_refs(leaf, ei);
1776 	WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1777 	refs += refs_to_mod;
1778 	btrfs_set_extent_refs(leaf, ei, refs);
1779 	if (extent_op)
1780 		__run_delayed_extent_op(extent_op, leaf, ei);
1781 
1782 	/*
1783 	 * If type is invalid, we should have bailed out after
1784 	 * lookup_inline_extent_backref().
1785 	 */
1786 	type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1787 	ASSERT(type != BTRFS_REF_TYPE_INVALID);
1788 
1789 	if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1790 		dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1791 		refs = btrfs_extent_data_ref_count(leaf, dref);
1792 	} else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1793 		sref = (struct btrfs_shared_data_ref *)(iref + 1);
1794 		refs = btrfs_shared_data_ref_count(leaf, sref);
1795 	} else {
1796 		refs = 1;
1797 		BUG_ON(refs_to_mod != -1);
1798 	}
1799 
1800 	BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1801 	refs += refs_to_mod;
1802 
1803 	if (refs > 0) {
1804 		if (type == BTRFS_EXTENT_DATA_REF_KEY)
1805 			btrfs_set_extent_data_ref_count(leaf, dref, refs);
1806 		else
1807 			btrfs_set_shared_data_ref_count(leaf, sref, refs);
1808 	} else {
1809 		*last_ref = 1;
1810 		size =  btrfs_extent_inline_ref_size(type);
1811 		item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1812 		ptr = (unsigned long)iref;
1813 		end = (unsigned long)ei + item_size;
1814 		if (ptr + size < end)
1815 			memmove_extent_buffer(leaf, ptr, ptr + size,
1816 					      end - ptr - size);
1817 		item_size -= size;
1818 		btrfs_truncate_item(fs_info, path, item_size, 1);
1819 	}
1820 	btrfs_mark_buffer_dirty(leaf);
1821 }
1822 
1823 static noinline_for_stack
insert_inline_extent_backref(struct btrfs_trans_handle * trans,struct btrfs_path * path,u64 bytenr,u64 num_bytes,u64 parent,u64 root_objectid,u64 owner,u64 offset,int refs_to_add,struct btrfs_delayed_extent_op * extent_op)1824 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1825 				 struct btrfs_path *path,
1826 				 u64 bytenr, u64 num_bytes, u64 parent,
1827 				 u64 root_objectid, u64 owner,
1828 				 u64 offset, int refs_to_add,
1829 				 struct btrfs_delayed_extent_op *extent_op)
1830 {
1831 	struct btrfs_extent_inline_ref *iref;
1832 	int ret;
1833 
1834 	ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1835 					   num_bytes, parent, root_objectid,
1836 					   owner, offset, 1);
1837 	if (ret == 0) {
1838 		BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1839 		update_inline_extent_backref(path, iref, refs_to_add,
1840 					     extent_op, NULL);
1841 	} else if (ret == -ENOENT) {
1842 		setup_inline_extent_backref(trans->fs_info, path, iref, parent,
1843 					    root_objectid, owner, offset,
1844 					    refs_to_add, extent_op);
1845 		ret = 0;
1846 	}
1847 	return ret;
1848 }
1849 
insert_extent_backref(struct btrfs_trans_handle * trans,struct btrfs_path * path,u64 bytenr,u64 parent,u64 root_objectid,u64 owner,u64 offset,int refs_to_add)1850 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1851 				 struct btrfs_path *path,
1852 				 u64 bytenr, u64 parent, u64 root_objectid,
1853 				 u64 owner, u64 offset, int refs_to_add)
1854 {
1855 	int ret;
1856 	if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1857 		BUG_ON(refs_to_add != 1);
1858 		ret = insert_tree_block_ref(trans, path, bytenr, parent,
1859 					    root_objectid);
1860 	} else {
1861 		ret = insert_extent_data_ref(trans, path, bytenr, parent,
1862 					     root_objectid, owner, offset,
1863 					     refs_to_add);
1864 	}
1865 	return ret;
1866 }
1867 
remove_extent_backref(struct btrfs_trans_handle * trans,struct btrfs_path * path,struct btrfs_extent_inline_ref * iref,int refs_to_drop,int is_data,int * last_ref)1868 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1869 				 struct btrfs_path *path,
1870 				 struct btrfs_extent_inline_ref *iref,
1871 				 int refs_to_drop, int is_data, int *last_ref)
1872 {
1873 	int ret = 0;
1874 
1875 	BUG_ON(!is_data && refs_to_drop != 1);
1876 	if (iref) {
1877 		update_inline_extent_backref(path, iref, -refs_to_drop, NULL,
1878 					     last_ref);
1879 	} else if (is_data) {
1880 		ret = remove_extent_data_ref(trans, path, refs_to_drop,
1881 					     last_ref);
1882 	} else {
1883 		*last_ref = 1;
1884 		ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1885 	}
1886 	return ret;
1887 }
1888 
1889 #define in_range(b, first, len)        ((b) >= (first) && (b) < (first) + (len))
btrfs_issue_discard(struct block_device * bdev,u64 start,u64 len,u64 * discarded_bytes)1890 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1891 			       u64 *discarded_bytes)
1892 {
1893 	int j, ret = 0;
1894 	u64 bytes_left, end;
1895 	u64 aligned_start = ALIGN(start, 1 << 9);
1896 
1897 	if (WARN_ON(start != aligned_start)) {
1898 		len -= aligned_start - start;
1899 		len = round_down(len, 1 << 9);
1900 		start = aligned_start;
1901 	}
1902 
1903 	*discarded_bytes = 0;
1904 
1905 	if (!len)
1906 		return 0;
1907 
1908 	end = start + len;
1909 	bytes_left = len;
1910 
1911 	/* Skip any superblocks on this device. */
1912 	for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1913 		u64 sb_start = btrfs_sb_offset(j);
1914 		u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1915 		u64 size = sb_start - start;
1916 
1917 		if (!in_range(sb_start, start, bytes_left) &&
1918 		    !in_range(sb_end, start, bytes_left) &&
1919 		    !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1920 			continue;
1921 
1922 		/*
1923 		 * Superblock spans beginning of range.  Adjust start and
1924 		 * try again.
1925 		 */
1926 		if (sb_start <= start) {
1927 			start += sb_end - start;
1928 			if (start > end) {
1929 				bytes_left = 0;
1930 				break;
1931 			}
1932 			bytes_left = end - start;
1933 			continue;
1934 		}
1935 
1936 		if (size) {
1937 			ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1938 						   GFP_NOFS, 0);
1939 			if (!ret)
1940 				*discarded_bytes += size;
1941 			else if (ret != -EOPNOTSUPP)
1942 				return ret;
1943 		}
1944 
1945 		start = sb_end;
1946 		if (start > end) {
1947 			bytes_left = 0;
1948 			break;
1949 		}
1950 		bytes_left = end - start;
1951 	}
1952 
1953 	if (bytes_left) {
1954 		ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
1955 					   GFP_NOFS, 0);
1956 		if (!ret)
1957 			*discarded_bytes += bytes_left;
1958 	}
1959 	return ret;
1960 }
1961 
btrfs_discard_extent(struct btrfs_fs_info * fs_info,u64 bytenr,u64 num_bytes,u64 * actual_bytes)1962 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1963 			 u64 num_bytes, u64 *actual_bytes)
1964 {
1965 	int ret;
1966 	u64 discarded_bytes = 0;
1967 	struct btrfs_bio *bbio = NULL;
1968 
1969 
1970 	/*
1971 	 * Avoid races with device replace and make sure our bbio has devices
1972 	 * associated to its stripes that don't go away while we are discarding.
1973 	 */
1974 	btrfs_bio_counter_inc_blocked(fs_info);
1975 	/* Tell the block device(s) that the sectors can be discarded */
1976 	ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, bytenr, &num_bytes,
1977 			      &bbio, 0);
1978 	/* Error condition is -ENOMEM */
1979 	if (!ret) {
1980 		struct btrfs_bio_stripe *stripe = bbio->stripes;
1981 		int i;
1982 
1983 
1984 		for (i = 0; i < bbio->num_stripes; i++, stripe++) {
1985 			u64 bytes;
1986 			struct request_queue *req_q;
1987 
1988 			if (!stripe->dev->bdev) {
1989 				ASSERT(btrfs_test_opt(fs_info, DEGRADED));
1990 				continue;
1991 			}
1992 			req_q = bdev_get_queue(stripe->dev->bdev);
1993 			if (!blk_queue_discard(req_q))
1994 				continue;
1995 
1996 			ret = btrfs_issue_discard(stripe->dev->bdev,
1997 						  stripe->physical,
1998 						  stripe->length,
1999 						  &bytes);
2000 			if (!ret)
2001 				discarded_bytes += bytes;
2002 			else if (ret != -EOPNOTSUPP)
2003 				break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
2004 
2005 			/*
2006 			 * Just in case we get back EOPNOTSUPP for some reason,
2007 			 * just ignore the return value so we don't screw up
2008 			 * people calling discard_extent.
2009 			 */
2010 			ret = 0;
2011 		}
2012 		btrfs_put_bbio(bbio);
2013 	}
2014 	btrfs_bio_counter_dec(fs_info);
2015 
2016 	if (actual_bytes)
2017 		*actual_bytes = discarded_bytes;
2018 
2019 
2020 	if (ret == -EOPNOTSUPP)
2021 		ret = 0;
2022 	return ret;
2023 }
2024 
2025 /* Can return -ENOMEM */
btrfs_inc_extent_ref(struct btrfs_trans_handle * trans,struct btrfs_root * root,u64 bytenr,u64 num_bytes,u64 parent,u64 root_objectid,u64 owner,u64 offset)2026 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2027 			 struct btrfs_root *root,
2028 			 u64 bytenr, u64 num_bytes, u64 parent,
2029 			 u64 root_objectid, u64 owner, u64 offset)
2030 {
2031 	struct btrfs_fs_info *fs_info = root->fs_info;
2032 	int old_ref_mod, new_ref_mod;
2033 	int ret;
2034 
2035 	BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
2036 	       root_objectid == BTRFS_TREE_LOG_OBJECTID);
2037 
2038 	btrfs_ref_tree_mod(root, bytenr, num_bytes, parent, root_objectid,
2039 			   owner, offset, BTRFS_ADD_DELAYED_REF);
2040 
2041 	if (owner < BTRFS_FIRST_FREE_OBJECTID) {
2042 		ret = btrfs_add_delayed_tree_ref(trans, bytenr,
2043 						 num_bytes, parent,
2044 						 root_objectid, (int)owner,
2045 						 BTRFS_ADD_DELAYED_REF, NULL,
2046 						 &old_ref_mod, &new_ref_mod);
2047 	} else {
2048 		ret = btrfs_add_delayed_data_ref(trans, bytenr,
2049 						 num_bytes, parent,
2050 						 root_objectid, owner, offset,
2051 						 0, BTRFS_ADD_DELAYED_REF,
2052 						 &old_ref_mod, &new_ref_mod);
2053 	}
2054 
2055 	if (ret == 0 && old_ref_mod < 0 && new_ref_mod >= 0) {
2056 		bool metadata = owner < BTRFS_FIRST_FREE_OBJECTID;
2057 
2058 		add_pinned_bytes(fs_info, -num_bytes, metadata, root_objectid);
2059 	}
2060 
2061 	return ret;
2062 }
2063 
2064 /*
2065  * __btrfs_inc_extent_ref - insert backreference for a given extent
2066  *
2067  * @trans:	    Handle of transaction
2068  *
2069  * @node:	    The delayed ref node used to get the bytenr/length for
2070  *		    extent whose references are incremented.
2071  *
2072  * @parent:	    If this is a shared extent (BTRFS_SHARED_DATA_REF_KEY/
2073  *		    BTRFS_SHARED_BLOCK_REF_KEY) then it holds the logical
2074  *		    bytenr of the parent block. Since new extents are always
2075  *		    created with indirect references, this will only be the case
2076  *		    when relocating a shared extent. In that case, root_objectid
2077  *		    will be BTRFS_TREE_RELOC_OBJECTID. Otheriwse, parent must
2078  *		    be 0
2079  *
2080  * @root_objectid:  The id of the root where this modification has originated,
2081  *		    this can be either one of the well-known metadata trees or
2082  *		    the subvolume id which references this extent.
2083  *
2084  * @owner:	    For data extents it is the inode number of the owning file.
2085  *		    For metadata extents this parameter holds the level in the
2086  *		    tree of the extent.
2087  *
2088  * @offset:	    For metadata extents the offset is ignored and is currently
2089  *		    always passed as 0. For data extents it is the fileoffset
2090  *		    this extent belongs to.
2091  *
2092  * @refs_to_add     Number of references to add
2093  *
2094  * @extent_op       Pointer to a structure, holding information necessary when
2095  *                  updating a tree block's flags
2096  *
2097  */
__btrfs_inc_extent_ref(struct btrfs_trans_handle * trans,struct btrfs_delayed_ref_node * node,u64 parent,u64 root_objectid,u64 owner,u64 offset,int refs_to_add,struct btrfs_delayed_extent_op * extent_op)2098 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2099 				  struct btrfs_delayed_ref_node *node,
2100 				  u64 parent, u64 root_objectid,
2101 				  u64 owner, u64 offset, int refs_to_add,
2102 				  struct btrfs_delayed_extent_op *extent_op)
2103 {
2104 	struct btrfs_path *path;
2105 	struct extent_buffer *leaf;
2106 	struct btrfs_extent_item *item;
2107 	struct btrfs_key key;
2108 	u64 bytenr = node->bytenr;
2109 	u64 num_bytes = node->num_bytes;
2110 	u64 refs;
2111 	int ret;
2112 
2113 	path = btrfs_alloc_path();
2114 	if (!path)
2115 		return -ENOMEM;
2116 
2117 	path->reada = READA_FORWARD;
2118 	path->leave_spinning = 1;
2119 	/* this will setup the path even if it fails to insert the back ref */
2120 	ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
2121 					   parent, root_objectid, owner,
2122 					   offset, refs_to_add, extent_op);
2123 	if ((ret < 0 && ret != -EAGAIN) || !ret)
2124 		goto out;
2125 
2126 	/*
2127 	 * Ok we had -EAGAIN which means we didn't have space to insert and
2128 	 * inline extent ref, so just update the reference count and add a
2129 	 * normal backref.
2130 	 */
2131 	leaf = path->nodes[0];
2132 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2133 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2134 	refs = btrfs_extent_refs(leaf, item);
2135 	btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2136 	if (extent_op)
2137 		__run_delayed_extent_op(extent_op, leaf, item);
2138 
2139 	btrfs_mark_buffer_dirty(leaf);
2140 	btrfs_release_path(path);
2141 
2142 	path->reada = READA_FORWARD;
2143 	path->leave_spinning = 1;
2144 	/* now insert the actual backref */
2145 	ret = insert_extent_backref(trans, path, bytenr, parent, root_objectid,
2146 				    owner, offset, refs_to_add);
2147 	if (ret)
2148 		btrfs_abort_transaction(trans, ret);
2149 out:
2150 	btrfs_free_path(path);
2151 	return ret;
2152 }
2153 
run_delayed_data_ref(struct btrfs_trans_handle * trans,struct btrfs_delayed_ref_node * node,struct btrfs_delayed_extent_op * extent_op,int insert_reserved)2154 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2155 				struct btrfs_delayed_ref_node *node,
2156 				struct btrfs_delayed_extent_op *extent_op,
2157 				int insert_reserved)
2158 {
2159 	int ret = 0;
2160 	struct btrfs_delayed_data_ref *ref;
2161 	struct btrfs_key ins;
2162 	u64 parent = 0;
2163 	u64 ref_root = 0;
2164 	u64 flags = 0;
2165 
2166 	ins.objectid = node->bytenr;
2167 	ins.offset = node->num_bytes;
2168 	ins.type = BTRFS_EXTENT_ITEM_KEY;
2169 
2170 	ref = btrfs_delayed_node_to_data_ref(node);
2171 	trace_run_delayed_data_ref(trans->fs_info, node, ref, node->action);
2172 
2173 	if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2174 		parent = ref->parent;
2175 	ref_root = ref->root;
2176 
2177 	if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2178 		if (extent_op)
2179 			flags |= extent_op->flags_to_set;
2180 		ret = alloc_reserved_file_extent(trans, parent, ref_root,
2181 						 flags, ref->objectid,
2182 						 ref->offset, &ins,
2183 						 node->ref_mod);
2184 	} else if (node->action == BTRFS_ADD_DELAYED_REF) {
2185 		ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2186 					     ref->objectid, ref->offset,
2187 					     node->ref_mod, extent_op);
2188 	} else if (node->action == BTRFS_DROP_DELAYED_REF) {
2189 		ret = __btrfs_free_extent(trans, node, parent,
2190 					  ref_root, ref->objectid,
2191 					  ref->offset, node->ref_mod,
2192 					  extent_op);
2193 	} else {
2194 		BUG();
2195 	}
2196 	return ret;
2197 }
2198 
__run_delayed_extent_op(struct btrfs_delayed_extent_op * extent_op,struct extent_buffer * leaf,struct btrfs_extent_item * ei)2199 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2200 				    struct extent_buffer *leaf,
2201 				    struct btrfs_extent_item *ei)
2202 {
2203 	u64 flags = btrfs_extent_flags(leaf, ei);
2204 	if (extent_op->update_flags) {
2205 		flags |= extent_op->flags_to_set;
2206 		btrfs_set_extent_flags(leaf, ei, flags);
2207 	}
2208 
2209 	if (extent_op->update_key) {
2210 		struct btrfs_tree_block_info *bi;
2211 		BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2212 		bi = (struct btrfs_tree_block_info *)(ei + 1);
2213 		btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2214 	}
2215 }
2216 
run_delayed_extent_op(struct btrfs_trans_handle * trans,struct btrfs_delayed_ref_head * head,struct btrfs_delayed_extent_op * extent_op)2217 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2218 				 struct btrfs_delayed_ref_head *head,
2219 				 struct btrfs_delayed_extent_op *extent_op)
2220 {
2221 	struct btrfs_fs_info *fs_info = trans->fs_info;
2222 	struct btrfs_key key;
2223 	struct btrfs_path *path;
2224 	struct btrfs_extent_item *ei;
2225 	struct extent_buffer *leaf;
2226 	u32 item_size;
2227 	int ret;
2228 	int err = 0;
2229 	int metadata = !extent_op->is_data;
2230 
2231 	if (trans->aborted)
2232 		return 0;
2233 
2234 	if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2235 		metadata = 0;
2236 
2237 	path = btrfs_alloc_path();
2238 	if (!path)
2239 		return -ENOMEM;
2240 
2241 	key.objectid = head->bytenr;
2242 
2243 	if (metadata) {
2244 		key.type = BTRFS_METADATA_ITEM_KEY;
2245 		key.offset = extent_op->level;
2246 	} else {
2247 		key.type = BTRFS_EXTENT_ITEM_KEY;
2248 		key.offset = head->num_bytes;
2249 	}
2250 
2251 again:
2252 	path->reada = READA_FORWARD;
2253 	path->leave_spinning = 1;
2254 	ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
2255 	if (ret < 0) {
2256 		err = ret;
2257 		goto out;
2258 	}
2259 	if (ret > 0) {
2260 		if (metadata) {
2261 			if (path->slots[0] > 0) {
2262 				path->slots[0]--;
2263 				btrfs_item_key_to_cpu(path->nodes[0], &key,
2264 						      path->slots[0]);
2265 				if (key.objectid == head->bytenr &&
2266 				    key.type == BTRFS_EXTENT_ITEM_KEY &&
2267 				    key.offset == head->num_bytes)
2268 					ret = 0;
2269 			}
2270 			if (ret > 0) {
2271 				btrfs_release_path(path);
2272 				metadata = 0;
2273 
2274 				key.objectid = head->bytenr;
2275 				key.offset = head->num_bytes;
2276 				key.type = BTRFS_EXTENT_ITEM_KEY;
2277 				goto again;
2278 			}
2279 		} else {
2280 			err = -EIO;
2281 			goto out;
2282 		}
2283 	}
2284 
2285 	leaf = path->nodes[0];
2286 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2287 
2288 	if (unlikely(item_size < sizeof(*ei))) {
2289 		err = -EINVAL;
2290 		btrfs_print_v0_err(fs_info);
2291 		btrfs_abort_transaction(trans, err);
2292 		goto out;
2293 	}
2294 
2295 	ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2296 	__run_delayed_extent_op(extent_op, leaf, ei);
2297 
2298 	btrfs_mark_buffer_dirty(leaf);
2299 out:
2300 	btrfs_free_path(path);
2301 	return err;
2302 }
2303 
run_delayed_tree_ref(struct btrfs_trans_handle * trans,struct btrfs_delayed_ref_node * node,struct btrfs_delayed_extent_op * extent_op,int insert_reserved)2304 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2305 				struct btrfs_delayed_ref_node *node,
2306 				struct btrfs_delayed_extent_op *extent_op,
2307 				int insert_reserved)
2308 {
2309 	int ret = 0;
2310 	struct btrfs_delayed_tree_ref *ref;
2311 	u64 parent = 0;
2312 	u64 ref_root = 0;
2313 
2314 	ref = btrfs_delayed_node_to_tree_ref(node);
2315 	trace_run_delayed_tree_ref(trans->fs_info, node, ref, node->action);
2316 
2317 	if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2318 		parent = ref->parent;
2319 	ref_root = ref->root;
2320 
2321 	if (node->ref_mod != 1) {
2322 		btrfs_err(trans->fs_info,
2323 	"btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
2324 			  node->bytenr, node->ref_mod, node->action, ref_root,
2325 			  parent);
2326 		return -EIO;
2327 	}
2328 	if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2329 		BUG_ON(!extent_op || !extent_op->update_flags);
2330 		ret = alloc_reserved_tree_block(trans, node, extent_op);
2331 	} else if (node->action == BTRFS_ADD_DELAYED_REF) {
2332 		ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2333 					     ref->level, 0, 1, extent_op);
2334 	} else if (node->action == BTRFS_DROP_DELAYED_REF) {
2335 		ret = __btrfs_free_extent(trans, node, parent, ref_root,
2336 					  ref->level, 0, 1, extent_op);
2337 	} else {
2338 		BUG();
2339 	}
2340 	return ret;
2341 }
2342 
2343 /* helper function to actually process a single delayed ref entry */
run_one_delayed_ref(struct btrfs_trans_handle * trans,struct btrfs_delayed_ref_node * node,struct btrfs_delayed_extent_op * extent_op,int insert_reserved)2344 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2345 			       struct btrfs_delayed_ref_node *node,
2346 			       struct btrfs_delayed_extent_op *extent_op,
2347 			       int insert_reserved)
2348 {
2349 	int ret = 0;
2350 
2351 	if (trans->aborted) {
2352 		if (insert_reserved)
2353 			btrfs_pin_extent(trans->fs_info, node->bytenr,
2354 					 node->num_bytes, 1);
2355 		return 0;
2356 	}
2357 
2358 	if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2359 	    node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2360 		ret = run_delayed_tree_ref(trans, node, extent_op,
2361 					   insert_reserved);
2362 	else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2363 		 node->type == BTRFS_SHARED_DATA_REF_KEY)
2364 		ret = run_delayed_data_ref(trans, node, extent_op,
2365 					   insert_reserved);
2366 	else
2367 		BUG();
2368 	if (ret && insert_reserved)
2369 		btrfs_pin_extent(trans->fs_info, node->bytenr,
2370 				 node->num_bytes, 1);
2371 	return ret;
2372 }
2373 
2374 static inline struct btrfs_delayed_ref_node *
select_delayed_ref(struct btrfs_delayed_ref_head * head)2375 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2376 {
2377 	struct btrfs_delayed_ref_node *ref;
2378 
2379 	if (RB_EMPTY_ROOT(&head->ref_tree))
2380 		return NULL;
2381 
2382 	/*
2383 	 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
2384 	 * This is to prevent a ref count from going down to zero, which deletes
2385 	 * the extent item from the extent tree, when there still are references
2386 	 * to add, which would fail because they would not find the extent item.
2387 	 */
2388 	if (!list_empty(&head->ref_add_list))
2389 		return list_first_entry(&head->ref_add_list,
2390 				struct btrfs_delayed_ref_node, add_list);
2391 
2392 	ref = rb_entry(rb_first(&head->ref_tree),
2393 		       struct btrfs_delayed_ref_node, ref_node);
2394 	ASSERT(list_empty(&ref->add_list));
2395 	return ref;
2396 }
2397 
unselect_delayed_ref_head(struct btrfs_delayed_ref_root * delayed_refs,struct btrfs_delayed_ref_head * head)2398 static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
2399 				      struct btrfs_delayed_ref_head *head)
2400 {
2401 	spin_lock(&delayed_refs->lock);
2402 	head->processing = 0;
2403 	delayed_refs->num_heads_ready++;
2404 	spin_unlock(&delayed_refs->lock);
2405 	btrfs_delayed_ref_unlock(head);
2406 }
2407 
cleanup_extent_op(struct btrfs_trans_handle * trans,struct btrfs_delayed_ref_head * head)2408 static int cleanup_extent_op(struct btrfs_trans_handle *trans,
2409 			     struct btrfs_delayed_ref_head *head)
2410 {
2411 	struct btrfs_delayed_extent_op *extent_op = head->extent_op;
2412 	int ret;
2413 
2414 	if (!extent_op)
2415 		return 0;
2416 	head->extent_op = NULL;
2417 	if (head->must_insert_reserved) {
2418 		btrfs_free_delayed_extent_op(extent_op);
2419 		return 0;
2420 	}
2421 	spin_unlock(&head->lock);
2422 	ret = run_delayed_extent_op(trans, head, extent_op);
2423 	btrfs_free_delayed_extent_op(extent_op);
2424 	return ret ? ret : 1;
2425 }
2426 
cleanup_ref_head(struct btrfs_trans_handle * trans,struct btrfs_delayed_ref_head * head)2427 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
2428 			    struct btrfs_delayed_ref_head *head)
2429 {
2430 
2431 	struct btrfs_fs_info *fs_info = trans->fs_info;
2432 	struct btrfs_delayed_ref_root *delayed_refs;
2433 	int ret;
2434 
2435 	delayed_refs = &trans->transaction->delayed_refs;
2436 
2437 	ret = cleanup_extent_op(trans, head);
2438 	if (ret < 0) {
2439 		unselect_delayed_ref_head(delayed_refs, head);
2440 		btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
2441 		return ret;
2442 	} else if (ret) {
2443 		return ret;
2444 	}
2445 
2446 	/*
2447 	 * Need to drop our head ref lock and re-acquire the delayed ref lock
2448 	 * and then re-check to make sure nobody got added.
2449 	 */
2450 	spin_unlock(&head->lock);
2451 	spin_lock(&delayed_refs->lock);
2452 	spin_lock(&head->lock);
2453 	if (!RB_EMPTY_ROOT(&head->ref_tree) || head->extent_op) {
2454 		spin_unlock(&head->lock);
2455 		spin_unlock(&delayed_refs->lock);
2456 		return 1;
2457 	}
2458 	delayed_refs->num_heads--;
2459 	rb_erase(&head->href_node, &delayed_refs->href_root);
2460 	RB_CLEAR_NODE(&head->href_node);
2461 	spin_unlock(&head->lock);
2462 	spin_unlock(&delayed_refs->lock);
2463 	atomic_dec(&delayed_refs->num_entries);
2464 
2465 	trace_run_delayed_ref_head(fs_info, head, 0);
2466 
2467 	if (head->total_ref_mod < 0) {
2468 		struct btrfs_space_info *space_info;
2469 		u64 flags;
2470 
2471 		if (head->is_data)
2472 			flags = BTRFS_BLOCK_GROUP_DATA;
2473 		else if (head->is_system)
2474 			flags = BTRFS_BLOCK_GROUP_SYSTEM;
2475 		else
2476 			flags = BTRFS_BLOCK_GROUP_METADATA;
2477 		space_info = __find_space_info(fs_info, flags);
2478 		ASSERT(space_info);
2479 		percpu_counter_add_batch(&space_info->total_bytes_pinned,
2480 				   -head->num_bytes,
2481 				   BTRFS_TOTAL_BYTES_PINNED_BATCH);
2482 
2483 		if (head->is_data) {
2484 			spin_lock(&delayed_refs->lock);
2485 			delayed_refs->pending_csums -= head->num_bytes;
2486 			spin_unlock(&delayed_refs->lock);
2487 		}
2488 	}
2489 
2490 	if (head->must_insert_reserved) {
2491 		btrfs_pin_extent(fs_info, head->bytenr,
2492 				 head->num_bytes, 1);
2493 		if (head->is_data) {
2494 			ret = btrfs_del_csums(trans, fs_info->csum_root,
2495 					      head->bytenr, head->num_bytes);
2496 		}
2497 	}
2498 
2499 	/* Also free its reserved qgroup space */
2500 	btrfs_qgroup_free_delayed_ref(fs_info, head->qgroup_ref_root,
2501 				      head->qgroup_reserved);
2502 	btrfs_delayed_ref_unlock(head);
2503 	btrfs_put_delayed_ref_head(head);
2504 	return 0;
2505 }
2506 
2507 /*
2508  * Returns 0 on success or if called with an already aborted transaction.
2509  * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2510  */
__btrfs_run_delayed_refs(struct btrfs_trans_handle * trans,unsigned long nr)2511 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2512 					     unsigned long nr)
2513 {
2514 	struct btrfs_fs_info *fs_info = trans->fs_info;
2515 	struct btrfs_delayed_ref_root *delayed_refs;
2516 	struct btrfs_delayed_ref_node *ref;
2517 	struct btrfs_delayed_ref_head *locked_ref = NULL;
2518 	struct btrfs_delayed_extent_op *extent_op;
2519 	ktime_t start = ktime_get();
2520 	int ret;
2521 	unsigned long count = 0;
2522 	unsigned long actual_count = 0;
2523 	int must_insert_reserved = 0;
2524 
2525 	delayed_refs = &trans->transaction->delayed_refs;
2526 	while (1) {
2527 		if (!locked_ref) {
2528 			if (count >= nr)
2529 				break;
2530 
2531 			spin_lock(&delayed_refs->lock);
2532 			locked_ref = btrfs_select_ref_head(trans);
2533 			if (!locked_ref) {
2534 				spin_unlock(&delayed_refs->lock);
2535 				break;
2536 			}
2537 
2538 			/* grab the lock that says we are going to process
2539 			 * all the refs for this head */
2540 			ret = btrfs_delayed_ref_lock(trans, locked_ref);
2541 			spin_unlock(&delayed_refs->lock);
2542 			/*
2543 			 * we may have dropped the spin lock to get the head
2544 			 * mutex lock, and that might have given someone else
2545 			 * time to free the head.  If that's true, it has been
2546 			 * removed from our list and we can move on.
2547 			 */
2548 			if (ret == -EAGAIN) {
2549 				locked_ref = NULL;
2550 				count++;
2551 				continue;
2552 			}
2553 		}
2554 
2555 		/*
2556 		 * We need to try and merge add/drops of the same ref since we
2557 		 * can run into issues with relocate dropping the implicit ref
2558 		 * and then it being added back again before the drop can
2559 		 * finish.  If we merged anything we need to re-loop so we can
2560 		 * get a good ref.
2561 		 * Or we can get node references of the same type that weren't
2562 		 * merged when created due to bumps in the tree mod seq, and
2563 		 * we need to merge them to prevent adding an inline extent
2564 		 * backref before dropping it (triggering a BUG_ON at
2565 		 * insert_inline_extent_backref()).
2566 		 */
2567 		spin_lock(&locked_ref->lock);
2568 		btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2569 
2570 		ref = select_delayed_ref(locked_ref);
2571 
2572 		if (ref && ref->seq &&
2573 		    btrfs_check_delayed_seq(fs_info, ref->seq)) {
2574 			spin_unlock(&locked_ref->lock);
2575 			unselect_delayed_ref_head(delayed_refs, locked_ref);
2576 			locked_ref = NULL;
2577 			cond_resched();
2578 			count++;
2579 			continue;
2580 		}
2581 
2582 		/*
2583 		 * We're done processing refs in this ref_head, clean everything
2584 		 * up and move on to the next ref_head.
2585 		 */
2586 		if (!ref) {
2587 			ret = cleanup_ref_head(trans, locked_ref);
2588 			if (ret > 0 ) {
2589 				/* We dropped our lock, we need to loop. */
2590 				ret = 0;
2591 				continue;
2592 			} else if (ret) {
2593 				return ret;
2594 			}
2595 			locked_ref = NULL;
2596 			count++;
2597 			continue;
2598 		}
2599 
2600 		actual_count++;
2601 		ref->in_tree = 0;
2602 		rb_erase(&ref->ref_node, &locked_ref->ref_tree);
2603 		RB_CLEAR_NODE(&ref->ref_node);
2604 		if (!list_empty(&ref->add_list))
2605 			list_del(&ref->add_list);
2606 		/*
2607 		 * When we play the delayed ref, also correct the ref_mod on
2608 		 * head
2609 		 */
2610 		switch (ref->action) {
2611 		case BTRFS_ADD_DELAYED_REF:
2612 		case BTRFS_ADD_DELAYED_EXTENT:
2613 			locked_ref->ref_mod -= ref->ref_mod;
2614 			break;
2615 		case BTRFS_DROP_DELAYED_REF:
2616 			locked_ref->ref_mod += ref->ref_mod;
2617 			break;
2618 		default:
2619 			WARN_ON(1);
2620 		}
2621 		atomic_dec(&delayed_refs->num_entries);
2622 
2623 		/*
2624 		 * Record the must-insert_reserved flag before we drop the spin
2625 		 * lock.
2626 		 */
2627 		must_insert_reserved = locked_ref->must_insert_reserved;
2628 		locked_ref->must_insert_reserved = 0;
2629 
2630 		extent_op = locked_ref->extent_op;
2631 		locked_ref->extent_op = NULL;
2632 		spin_unlock(&locked_ref->lock);
2633 
2634 		ret = run_one_delayed_ref(trans, ref, extent_op,
2635 					  must_insert_reserved);
2636 
2637 		btrfs_free_delayed_extent_op(extent_op);
2638 		if (ret) {
2639 			unselect_delayed_ref_head(delayed_refs, locked_ref);
2640 			btrfs_put_delayed_ref(ref);
2641 			btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
2642 				    ret);
2643 			return ret;
2644 		}
2645 
2646 		btrfs_put_delayed_ref(ref);
2647 		count++;
2648 		cond_resched();
2649 	}
2650 
2651 	/*
2652 	 * We don't want to include ref heads since we can have empty ref heads
2653 	 * and those will drastically skew our runtime down since we just do
2654 	 * accounting, no actual extent tree updates.
2655 	 */
2656 	if (actual_count > 0) {
2657 		u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2658 		u64 avg;
2659 
2660 		/*
2661 		 * We weigh the current average higher than our current runtime
2662 		 * to avoid large swings in the average.
2663 		 */
2664 		spin_lock(&delayed_refs->lock);
2665 		avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2666 		fs_info->avg_delayed_ref_runtime = avg >> 2;	/* div by 4 */
2667 		spin_unlock(&delayed_refs->lock);
2668 	}
2669 	return 0;
2670 }
2671 
2672 #ifdef SCRAMBLE_DELAYED_REFS
2673 /*
2674  * Normally delayed refs get processed in ascending bytenr order. This
2675  * correlates in most cases to the order added. To expose dependencies on this
2676  * order, we start to process the tree in the middle instead of the beginning
2677  */
find_middle(struct rb_root * root)2678 static u64 find_middle(struct rb_root *root)
2679 {
2680 	struct rb_node *n = root->rb_node;
2681 	struct btrfs_delayed_ref_node *entry;
2682 	int alt = 1;
2683 	u64 middle;
2684 	u64 first = 0, last = 0;
2685 
2686 	n = rb_first(root);
2687 	if (n) {
2688 		entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2689 		first = entry->bytenr;
2690 	}
2691 	n = rb_last(root);
2692 	if (n) {
2693 		entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2694 		last = entry->bytenr;
2695 	}
2696 	n = root->rb_node;
2697 
2698 	while (n) {
2699 		entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2700 		WARN_ON(!entry->in_tree);
2701 
2702 		middle = entry->bytenr;
2703 
2704 		if (alt)
2705 			n = n->rb_left;
2706 		else
2707 			n = n->rb_right;
2708 
2709 		alt = 1 - alt;
2710 	}
2711 	return middle;
2712 }
2713 #endif
2714 
heads_to_leaves(struct btrfs_fs_info * fs_info,u64 heads)2715 static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
2716 {
2717 	u64 num_bytes;
2718 
2719 	num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2720 			     sizeof(struct btrfs_extent_inline_ref));
2721 	if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2722 		num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2723 
2724 	/*
2725 	 * We don't ever fill up leaves all the way so multiply by 2 just to be
2726 	 * closer to what we're really going to want to use.
2727 	 */
2728 	return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
2729 }
2730 
2731 /*
2732  * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2733  * would require to store the csums for that many bytes.
2734  */
btrfs_csum_bytes_to_leaves(struct btrfs_fs_info * fs_info,u64 csum_bytes)2735 u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
2736 {
2737 	u64 csum_size;
2738 	u64 num_csums_per_leaf;
2739 	u64 num_csums;
2740 
2741 	csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
2742 	num_csums_per_leaf = div64_u64(csum_size,
2743 			(u64)btrfs_super_csum_size(fs_info->super_copy));
2744 	num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
2745 	num_csums += num_csums_per_leaf - 1;
2746 	num_csums = div64_u64(num_csums, num_csums_per_leaf);
2747 	return num_csums;
2748 }
2749 
btrfs_check_space_for_delayed_refs(struct btrfs_trans_handle * trans,struct btrfs_fs_info * fs_info)2750 int btrfs_check_space_for_delayed_refs(struct btrfs_trans_handle *trans,
2751 				       struct btrfs_fs_info *fs_info)
2752 {
2753 	struct btrfs_block_rsv *global_rsv;
2754 	u64 num_heads = trans->transaction->delayed_refs.num_heads_ready;
2755 	u64 csum_bytes = trans->transaction->delayed_refs.pending_csums;
2756 	unsigned int num_dirty_bgs = trans->transaction->num_dirty_bgs;
2757 	u64 num_bytes, num_dirty_bgs_bytes;
2758 	int ret = 0;
2759 
2760 	num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
2761 	num_heads = heads_to_leaves(fs_info, num_heads);
2762 	if (num_heads > 1)
2763 		num_bytes += (num_heads - 1) * fs_info->nodesize;
2764 	num_bytes <<= 1;
2765 	num_bytes += btrfs_csum_bytes_to_leaves(fs_info, csum_bytes) *
2766 							fs_info->nodesize;
2767 	num_dirty_bgs_bytes = btrfs_calc_trans_metadata_size(fs_info,
2768 							     num_dirty_bgs);
2769 	global_rsv = &fs_info->global_block_rsv;
2770 
2771 	/*
2772 	 * If we can't allocate any more chunks lets make sure we have _lots_ of
2773 	 * wiggle room since running delayed refs can create more delayed refs.
2774 	 */
2775 	if (global_rsv->space_info->full) {
2776 		num_dirty_bgs_bytes <<= 1;
2777 		num_bytes <<= 1;
2778 	}
2779 
2780 	spin_lock(&global_rsv->lock);
2781 	if (global_rsv->reserved <= num_bytes + num_dirty_bgs_bytes)
2782 		ret = 1;
2783 	spin_unlock(&global_rsv->lock);
2784 	return ret;
2785 }
2786 
btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle * trans,struct btrfs_fs_info * fs_info)2787 int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans,
2788 				       struct btrfs_fs_info *fs_info)
2789 {
2790 	u64 num_entries =
2791 		atomic_read(&trans->transaction->delayed_refs.num_entries);
2792 	u64 avg_runtime;
2793 	u64 val;
2794 
2795 	smp_mb();
2796 	avg_runtime = fs_info->avg_delayed_ref_runtime;
2797 	val = num_entries * avg_runtime;
2798 	if (val >= NSEC_PER_SEC)
2799 		return 1;
2800 	if (val >= NSEC_PER_SEC / 2)
2801 		return 2;
2802 
2803 	return btrfs_check_space_for_delayed_refs(trans, fs_info);
2804 }
2805 
2806 struct async_delayed_refs {
2807 	struct btrfs_root *root;
2808 	u64 transid;
2809 	int count;
2810 	int error;
2811 	int sync;
2812 	struct completion wait;
2813 	struct btrfs_work work;
2814 };
2815 
2816 static inline struct async_delayed_refs *
to_async_delayed_refs(struct btrfs_work * work)2817 to_async_delayed_refs(struct btrfs_work *work)
2818 {
2819 	return container_of(work, struct async_delayed_refs, work);
2820 }
2821 
delayed_ref_async_start(struct btrfs_work * work)2822 static void delayed_ref_async_start(struct btrfs_work *work)
2823 {
2824 	struct async_delayed_refs *async = to_async_delayed_refs(work);
2825 	struct btrfs_trans_handle *trans;
2826 	struct btrfs_fs_info *fs_info = async->root->fs_info;
2827 	int ret;
2828 
2829 	/* if the commit is already started, we don't need to wait here */
2830 	if (btrfs_transaction_blocked(fs_info))
2831 		goto done;
2832 
2833 	trans = btrfs_join_transaction(async->root);
2834 	if (IS_ERR(trans)) {
2835 		async->error = PTR_ERR(trans);
2836 		goto done;
2837 	}
2838 
2839 	/*
2840 	 * trans->sync means that when we call end_transaction, we won't
2841 	 * wait on delayed refs
2842 	 */
2843 	trans->sync = true;
2844 
2845 	/* Don't bother flushing if we got into a different transaction */
2846 	if (trans->transid > async->transid)
2847 		goto end;
2848 
2849 	ret = btrfs_run_delayed_refs(trans, async->count);
2850 	if (ret)
2851 		async->error = ret;
2852 end:
2853 	ret = btrfs_end_transaction(trans);
2854 	if (ret && !async->error)
2855 		async->error = ret;
2856 done:
2857 	if (async->sync)
2858 		complete(&async->wait);
2859 	else
2860 		kfree(async);
2861 }
2862 
btrfs_async_run_delayed_refs(struct btrfs_fs_info * fs_info,unsigned long count,u64 transid,int wait)2863 int btrfs_async_run_delayed_refs(struct btrfs_fs_info *fs_info,
2864 				 unsigned long count, u64 transid, int wait)
2865 {
2866 	struct async_delayed_refs *async;
2867 	int ret;
2868 
2869 	async = kmalloc(sizeof(*async), GFP_NOFS);
2870 	if (!async)
2871 		return -ENOMEM;
2872 
2873 	async->root = fs_info->tree_root;
2874 	async->count = count;
2875 	async->error = 0;
2876 	async->transid = transid;
2877 	if (wait)
2878 		async->sync = 1;
2879 	else
2880 		async->sync = 0;
2881 	init_completion(&async->wait);
2882 
2883 	btrfs_init_work(&async->work, btrfs_extent_refs_helper,
2884 			delayed_ref_async_start, NULL, NULL);
2885 
2886 	btrfs_queue_work(fs_info->extent_workers, &async->work);
2887 
2888 	if (wait) {
2889 		wait_for_completion(&async->wait);
2890 		ret = async->error;
2891 		kfree(async);
2892 		return ret;
2893 	}
2894 	return 0;
2895 }
2896 
2897 /*
2898  * this starts processing the delayed reference count updates and
2899  * extent insertions we have queued up so far.  count can be
2900  * 0, which means to process everything in the tree at the start
2901  * of the run (but not newly added entries), or it can be some target
2902  * number you'd like to process.
2903  *
2904  * Returns 0 on success or if called with an aborted transaction
2905  * Returns <0 on error and aborts the transaction
2906  */
btrfs_run_delayed_refs(struct btrfs_trans_handle * trans,unsigned long count)2907 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2908 			   unsigned long count)
2909 {
2910 	struct btrfs_fs_info *fs_info = trans->fs_info;
2911 	struct rb_node *node;
2912 	struct btrfs_delayed_ref_root *delayed_refs;
2913 	struct btrfs_delayed_ref_head *head;
2914 	int ret;
2915 	int run_all = count == (unsigned long)-1;
2916 
2917 	/* We'll clean this up in btrfs_cleanup_transaction */
2918 	if (trans->aborted)
2919 		return 0;
2920 
2921 	if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2922 		return 0;
2923 
2924 	delayed_refs = &trans->transaction->delayed_refs;
2925 	if (count == 0)
2926 		count = atomic_read(&delayed_refs->num_entries) * 2;
2927 
2928 again:
2929 #ifdef SCRAMBLE_DELAYED_REFS
2930 	delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2931 #endif
2932 	ret = __btrfs_run_delayed_refs(trans, count);
2933 	if (ret < 0) {
2934 		btrfs_abort_transaction(trans, ret);
2935 		return ret;
2936 	}
2937 
2938 	if (run_all) {
2939 		if (!list_empty(&trans->new_bgs))
2940 			btrfs_create_pending_block_groups(trans);
2941 
2942 		spin_lock(&delayed_refs->lock);
2943 		node = rb_first(&delayed_refs->href_root);
2944 		if (!node) {
2945 			spin_unlock(&delayed_refs->lock);
2946 			goto out;
2947 		}
2948 		head = rb_entry(node, struct btrfs_delayed_ref_head,
2949 				href_node);
2950 		refcount_inc(&head->refs);
2951 		spin_unlock(&delayed_refs->lock);
2952 
2953 		/* Mutex was contended, block until it's released and retry. */
2954 		mutex_lock(&head->mutex);
2955 		mutex_unlock(&head->mutex);
2956 
2957 		btrfs_put_delayed_ref_head(head);
2958 		cond_resched();
2959 		goto again;
2960 	}
2961 out:
2962 	return 0;
2963 }
2964 
btrfs_set_disk_extent_flags(struct btrfs_trans_handle * trans,struct btrfs_fs_info * fs_info,u64 bytenr,u64 num_bytes,u64 flags,int level,int is_data)2965 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2966 				struct btrfs_fs_info *fs_info,
2967 				u64 bytenr, u64 num_bytes, u64 flags,
2968 				int level, int is_data)
2969 {
2970 	struct btrfs_delayed_extent_op *extent_op;
2971 	int ret;
2972 
2973 	extent_op = btrfs_alloc_delayed_extent_op();
2974 	if (!extent_op)
2975 		return -ENOMEM;
2976 
2977 	extent_op->flags_to_set = flags;
2978 	extent_op->update_flags = true;
2979 	extent_op->update_key = false;
2980 	extent_op->is_data = is_data ? true : false;
2981 	extent_op->level = level;
2982 
2983 	ret = btrfs_add_delayed_extent_op(fs_info, trans, bytenr,
2984 					  num_bytes, extent_op);
2985 	if (ret)
2986 		btrfs_free_delayed_extent_op(extent_op);
2987 	return ret;
2988 }
2989 
check_delayed_ref(struct btrfs_root * root,struct btrfs_path * path,u64 objectid,u64 offset,u64 bytenr)2990 static noinline int check_delayed_ref(struct btrfs_root *root,
2991 				      struct btrfs_path *path,
2992 				      u64 objectid, u64 offset, u64 bytenr)
2993 {
2994 	struct btrfs_delayed_ref_head *head;
2995 	struct btrfs_delayed_ref_node *ref;
2996 	struct btrfs_delayed_data_ref *data_ref;
2997 	struct btrfs_delayed_ref_root *delayed_refs;
2998 	struct btrfs_transaction *cur_trans;
2999 	struct rb_node *node;
3000 	int ret = 0;
3001 
3002 	spin_lock(&root->fs_info->trans_lock);
3003 	cur_trans = root->fs_info->running_transaction;
3004 	if (cur_trans)
3005 		refcount_inc(&cur_trans->use_count);
3006 	spin_unlock(&root->fs_info->trans_lock);
3007 	if (!cur_trans)
3008 		return 0;
3009 
3010 	delayed_refs = &cur_trans->delayed_refs;
3011 	spin_lock(&delayed_refs->lock);
3012 	head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
3013 	if (!head) {
3014 		spin_unlock(&delayed_refs->lock);
3015 		btrfs_put_transaction(cur_trans);
3016 		return 0;
3017 	}
3018 
3019 	if (!mutex_trylock(&head->mutex)) {
3020 		refcount_inc(&head->refs);
3021 		spin_unlock(&delayed_refs->lock);
3022 
3023 		btrfs_release_path(path);
3024 
3025 		/*
3026 		 * Mutex was contended, block until it's released and let
3027 		 * caller try again
3028 		 */
3029 		mutex_lock(&head->mutex);
3030 		mutex_unlock(&head->mutex);
3031 		btrfs_put_delayed_ref_head(head);
3032 		btrfs_put_transaction(cur_trans);
3033 		return -EAGAIN;
3034 	}
3035 	spin_unlock(&delayed_refs->lock);
3036 
3037 	spin_lock(&head->lock);
3038 	/*
3039 	 * XXX: We should replace this with a proper search function in the
3040 	 * future.
3041 	 */
3042 	for (node = rb_first(&head->ref_tree); node; node = rb_next(node)) {
3043 		ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
3044 		/* If it's a shared ref we know a cross reference exists */
3045 		if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
3046 			ret = 1;
3047 			break;
3048 		}
3049 
3050 		data_ref = btrfs_delayed_node_to_data_ref(ref);
3051 
3052 		/*
3053 		 * If our ref doesn't match the one we're currently looking at
3054 		 * then we have a cross reference.
3055 		 */
3056 		if (data_ref->root != root->root_key.objectid ||
3057 		    data_ref->objectid != objectid ||
3058 		    data_ref->offset != offset) {
3059 			ret = 1;
3060 			break;
3061 		}
3062 	}
3063 	spin_unlock(&head->lock);
3064 	mutex_unlock(&head->mutex);
3065 	btrfs_put_transaction(cur_trans);
3066 	return ret;
3067 }
3068 
check_committed_ref(struct btrfs_root * root,struct btrfs_path * path,u64 objectid,u64 offset,u64 bytenr)3069 static noinline int check_committed_ref(struct btrfs_root *root,
3070 					struct btrfs_path *path,
3071 					u64 objectid, u64 offset, u64 bytenr)
3072 {
3073 	struct btrfs_fs_info *fs_info = root->fs_info;
3074 	struct btrfs_root *extent_root = fs_info->extent_root;
3075 	struct extent_buffer *leaf;
3076 	struct btrfs_extent_data_ref *ref;
3077 	struct btrfs_extent_inline_ref *iref;
3078 	struct btrfs_extent_item *ei;
3079 	struct btrfs_key key;
3080 	u32 item_size;
3081 	int type;
3082 	int ret;
3083 
3084 	key.objectid = bytenr;
3085 	key.offset = (u64)-1;
3086 	key.type = BTRFS_EXTENT_ITEM_KEY;
3087 
3088 	ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
3089 	if (ret < 0)
3090 		goto out;
3091 	BUG_ON(ret == 0); /* Corruption */
3092 
3093 	ret = -ENOENT;
3094 	if (path->slots[0] == 0)
3095 		goto out;
3096 
3097 	path->slots[0]--;
3098 	leaf = path->nodes[0];
3099 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3100 
3101 	if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
3102 		goto out;
3103 
3104 	ret = 1;
3105 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3106 	ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
3107 
3108 	if (item_size != sizeof(*ei) +
3109 	    btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
3110 		goto out;
3111 
3112 	if (btrfs_extent_generation(leaf, ei) <=
3113 	    btrfs_root_last_snapshot(&root->root_item))
3114 		goto out;
3115 
3116 	iref = (struct btrfs_extent_inline_ref *)(ei + 1);
3117 
3118 	type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
3119 	if (type != BTRFS_EXTENT_DATA_REF_KEY)
3120 		goto out;
3121 
3122 	ref = (struct btrfs_extent_data_ref *)(&iref->offset);
3123 	if (btrfs_extent_refs(leaf, ei) !=
3124 	    btrfs_extent_data_ref_count(leaf, ref) ||
3125 	    btrfs_extent_data_ref_root(leaf, ref) !=
3126 	    root->root_key.objectid ||
3127 	    btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
3128 	    btrfs_extent_data_ref_offset(leaf, ref) != offset)
3129 		goto out;
3130 
3131 	ret = 0;
3132 out:
3133 	return ret;
3134 }
3135 
btrfs_cross_ref_exist(struct btrfs_root * root,u64 objectid,u64 offset,u64 bytenr)3136 int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
3137 			  u64 bytenr)
3138 {
3139 	struct btrfs_path *path;
3140 	int ret;
3141 	int ret2;
3142 
3143 	path = btrfs_alloc_path();
3144 	if (!path)
3145 		return -ENOMEM;
3146 
3147 	do {
3148 		ret = check_committed_ref(root, path, objectid,
3149 					  offset, bytenr);
3150 		if (ret && ret != -ENOENT)
3151 			goto out;
3152 
3153 		ret2 = check_delayed_ref(root, path, objectid,
3154 					 offset, bytenr);
3155 	} while (ret2 == -EAGAIN);
3156 
3157 	if (ret2 && ret2 != -ENOENT) {
3158 		ret = ret2;
3159 		goto out;
3160 	}
3161 
3162 	if (ret != -ENOENT || ret2 != -ENOENT)
3163 		ret = 0;
3164 out:
3165 	btrfs_free_path(path);
3166 	if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3167 		WARN_ON(ret > 0);
3168 	return ret;
3169 }
3170 
__btrfs_mod_ref(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct extent_buffer * buf,int full_backref,int inc)3171 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
3172 			   struct btrfs_root *root,
3173 			   struct extent_buffer *buf,
3174 			   int full_backref, int inc)
3175 {
3176 	struct btrfs_fs_info *fs_info = root->fs_info;
3177 	u64 bytenr;
3178 	u64 num_bytes;
3179 	u64 parent;
3180 	u64 ref_root;
3181 	u32 nritems;
3182 	struct btrfs_key key;
3183 	struct btrfs_file_extent_item *fi;
3184 	int i;
3185 	int level;
3186 	int ret = 0;
3187 	int (*process_func)(struct btrfs_trans_handle *,
3188 			    struct btrfs_root *,
3189 			    u64, u64, u64, u64, u64, u64);
3190 
3191 
3192 	if (btrfs_is_testing(fs_info))
3193 		return 0;
3194 
3195 	ref_root = btrfs_header_owner(buf);
3196 	nritems = btrfs_header_nritems(buf);
3197 	level = btrfs_header_level(buf);
3198 
3199 	if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
3200 		return 0;
3201 
3202 	if (inc)
3203 		process_func = btrfs_inc_extent_ref;
3204 	else
3205 		process_func = btrfs_free_extent;
3206 
3207 	if (full_backref)
3208 		parent = buf->start;
3209 	else
3210 		parent = 0;
3211 
3212 	for (i = 0; i < nritems; i++) {
3213 		if (level == 0) {
3214 			btrfs_item_key_to_cpu(buf, &key, i);
3215 			if (key.type != BTRFS_EXTENT_DATA_KEY)
3216 				continue;
3217 			fi = btrfs_item_ptr(buf, i,
3218 					    struct btrfs_file_extent_item);
3219 			if (btrfs_file_extent_type(buf, fi) ==
3220 			    BTRFS_FILE_EXTENT_INLINE)
3221 				continue;
3222 			bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
3223 			if (bytenr == 0)
3224 				continue;
3225 
3226 			num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
3227 			key.offset -= btrfs_file_extent_offset(buf, fi);
3228 			ret = process_func(trans, root, bytenr, num_bytes,
3229 					   parent, ref_root, key.objectid,
3230 					   key.offset);
3231 			if (ret)
3232 				goto fail;
3233 		} else {
3234 			bytenr = btrfs_node_blockptr(buf, i);
3235 			num_bytes = fs_info->nodesize;
3236 			ret = process_func(trans, root, bytenr, num_bytes,
3237 					   parent, ref_root, level - 1, 0);
3238 			if (ret)
3239 				goto fail;
3240 		}
3241 	}
3242 	return 0;
3243 fail:
3244 	return ret;
3245 }
3246 
btrfs_inc_ref(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct extent_buffer * buf,int full_backref)3247 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3248 		  struct extent_buffer *buf, int full_backref)
3249 {
3250 	return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
3251 }
3252 
btrfs_dec_ref(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct extent_buffer * buf,int full_backref)3253 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3254 		  struct extent_buffer *buf, int full_backref)
3255 {
3256 	return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
3257 }
3258 
write_one_cache_group(struct btrfs_trans_handle * trans,struct btrfs_fs_info * fs_info,struct btrfs_path * path,struct btrfs_block_group_cache * cache)3259 static int write_one_cache_group(struct btrfs_trans_handle *trans,
3260 				 struct btrfs_fs_info *fs_info,
3261 				 struct btrfs_path *path,
3262 				 struct btrfs_block_group_cache *cache)
3263 {
3264 	int ret;
3265 	struct btrfs_root *extent_root = fs_info->extent_root;
3266 	unsigned long bi;
3267 	struct extent_buffer *leaf;
3268 
3269 	ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
3270 	if (ret) {
3271 		if (ret > 0)
3272 			ret = -ENOENT;
3273 		goto fail;
3274 	}
3275 
3276 	leaf = path->nodes[0];
3277 	bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3278 	write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
3279 	btrfs_mark_buffer_dirty(leaf);
3280 fail:
3281 	btrfs_release_path(path);
3282 	return ret;
3283 
3284 }
3285 
3286 static struct btrfs_block_group_cache *
next_block_group(struct btrfs_fs_info * fs_info,struct btrfs_block_group_cache * cache)3287 next_block_group(struct btrfs_fs_info *fs_info,
3288 		 struct btrfs_block_group_cache *cache)
3289 {
3290 	struct rb_node *node;
3291 
3292 	spin_lock(&fs_info->block_group_cache_lock);
3293 
3294 	/* If our block group was removed, we need a full search. */
3295 	if (RB_EMPTY_NODE(&cache->cache_node)) {
3296 		const u64 next_bytenr = cache->key.objectid + cache->key.offset;
3297 
3298 		spin_unlock(&fs_info->block_group_cache_lock);
3299 		btrfs_put_block_group(cache);
3300 		cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
3301 	}
3302 	node = rb_next(&cache->cache_node);
3303 	btrfs_put_block_group(cache);
3304 	if (node) {
3305 		cache = rb_entry(node, struct btrfs_block_group_cache,
3306 				 cache_node);
3307 		btrfs_get_block_group(cache);
3308 	} else
3309 		cache = NULL;
3310 	spin_unlock(&fs_info->block_group_cache_lock);
3311 	return cache;
3312 }
3313 
cache_save_setup(struct btrfs_block_group_cache * block_group,struct btrfs_trans_handle * trans,struct btrfs_path * path)3314 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
3315 			    struct btrfs_trans_handle *trans,
3316 			    struct btrfs_path *path)
3317 {
3318 	struct btrfs_fs_info *fs_info = block_group->fs_info;
3319 	struct btrfs_root *root = fs_info->tree_root;
3320 	struct inode *inode = NULL;
3321 	struct extent_changeset *data_reserved = NULL;
3322 	u64 alloc_hint = 0;
3323 	int dcs = BTRFS_DC_ERROR;
3324 	u64 num_pages = 0;
3325 	int retries = 0;
3326 	int ret = 0;
3327 
3328 	/*
3329 	 * If this block group is smaller than 100 megs don't bother caching the
3330 	 * block group.
3331 	 */
3332 	if (block_group->key.offset < (100 * SZ_1M)) {
3333 		spin_lock(&block_group->lock);
3334 		block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3335 		spin_unlock(&block_group->lock);
3336 		return 0;
3337 	}
3338 
3339 	if (trans->aborted)
3340 		return 0;
3341 again:
3342 	inode = lookup_free_space_inode(fs_info, block_group, path);
3343 	if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3344 		ret = PTR_ERR(inode);
3345 		btrfs_release_path(path);
3346 		goto out;
3347 	}
3348 
3349 	if (IS_ERR(inode)) {
3350 		BUG_ON(retries);
3351 		retries++;
3352 
3353 		if (block_group->ro)
3354 			goto out_free;
3355 
3356 		ret = create_free_space_inode(fs_info, trans, block_group,
3357 					      path);
3358 		if (ret)
3359 			goto out_free;
3360 		goto again;
3361 	}
3362 
3363 	/*
3364 	 * We want to set the generation to 0, that way if anything goes wrong
3365 	 * from here on out we know not to trust this cache when we load up next
3366 	 * time.
3367 	 */
3368 	BTRFS_I(inode)->generation = 0;
3369 	ret = btrfs_update_inode(trans, root, inode);
3370 	if (ret) {
3371 		/*
3372 		 * So theoretically we could recover from this, simply set the
3373 		 * super cache generation to 0 so we know to invalidate the
3374 		 * cache, but then we'd have to keep track of the block groups
3375 		 * that fail this way so we know we _have_ to reset this cache
3376 		 * before the next commit or risk reading stale cache.  So to
3377 		 * limit our exposure to horrible edge cases lets just abort the
3378 		 * transaction, this only happens in really bad situations
3379 		 * anyway.
3380 		 */
3381 		btrfs_abort_transaction(trans, ret);
3382 		goto out_put;
3383 	}
3384 	WARN_ON(ret);
3385 
3386 	/* We've already setup this transaction, go ahead and exit */
3387 	if (block_group->cache_generation == trans->transid &&
3388 	    i_size_read(inode)) {
3389 		dcs = BTRFS_DC_SETUP;
3390 		goto out_put;
3391 	}
3392 
3393 	if (i_size_read(inode) > 0) {
3394 		ret = btrfs_check_trunc_cache_free_space(fs_info,
3395 					&fs_info->global_block_rsv);
3396 		if (ret)
3397 			goto out_put;
3398 
3399 		ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
3400 		if (ret)
3401 			goto out_put;
3402 	}
3403 
3404 	spin_lock(&block_group->lock);
3405 	if (block_group->cached != BTRFS_CACHE_FINISHED ||
3406 	    !btrfs_test_opt(fs_info, SPACE_CACHE)) {
3407 		/*
3408 		 * don't bother trying to write stuff out _if_
3409 		 * a) we're not cached,
3410 		 * b) we're with nospace_cache mount option,
3411 		 * c) we're with v2 space_cache (FREE_SPACE_TREE).
3412 		 */
3413 		dcs = BTRFS_DC_WRITTEN;
3414 		spin_unlock(&block_group->lock);
3415 		goto out_put;
3416 	}
3417 	spin_unlock(&block_group->lock);
3418 
3419 	/*
3420 	 * We hit an ENOSPC when setting up the cache in this transaction, just
3421 	 * skip doing the setup, we've already cleared the cache so we're safe.
3422 	 */
3423 	if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
3424 		ret = -ENOSPC;
3425 		goto out_put;
3426 	}
3427 
3428 	/*
3429 	 * Try to preallocate enough space based on how big the block group is.
3430 	 * Keep in mind this has to include any pinned space which could end up
3431 	 * taking up quite a bit since it's not folded into the other space
3432 	 * cache.
3433 	 */
3434 	num_pages = div_u64(block_group->key.offset, SZ_256M);
3435 	if (!num_pages)
3436 		num_pages = 1;
3437 
3438 	num_pages *= 16;
3439 	num_pages *= PAGE_SIZE;
3440 
3441 	ret = btrfs_check_data_free_space(inode, &data_reserved, 0, num_pages);
3442 	if (ret)
3443 		goto out_put;
3444 
3445 	ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3446 					      num_pages, num_pages,
3447 					      &alloc_hint);
3448 	/*
3449 	 * Our cache requires contiguous chunks so that we don't modify a bunch
3450 	 * of metadata or split extents when writing the cache out, which means
3451 	 * we can enospc if we are heavily fragmented in addition to just normal
3452 	 * out of space conditions.  So if we hit this just skip setting up any
3453 	 * other block groups for this transaction, maybe we'll unpin enough
3454 	 * space the next time around.
3455 	 */
3456 	if (!ret)
3457 		dcs = BTRFS_DC_SETUP;
3458 	else if (ret == -ENOSPC)
3459 		set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
3460 
3461 out_put:
3462 	iput(inode);
3463 out_free:
3464 	btrfs_release_path(path);
3465 out:
3466 	spin_lock(&block_group->lock);
3467 	if (!ret && dcs == BTRFS_DC_SETUP)
3468 		block_group->cache_generation = trans->transid;
3469 	block_group->disk_cache_state = dcs;
3470 	spin_unlock(&block_group->lock);
3471 
3472 	extent_changeset_free(data_reserved);
3473 	return ret;
3474 }
3475 
btrfs_setup_space_cache(struct btrfs_trans_handle * trans,struct btrfs_fs_info * fs_info)3476 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans,
3477 			    struct btrfs_fs_info *fs_info)
3478 {
3479 	struct btrfs_block_group_cache *cache, *tmp;
3480 	struct btrfs_transaction *cur_trans = trans->transaction;
3481 	struct btrfs_path *path;
3482 
3483 	if (list_empty(&cur_trans->dirty_bgs) ||
3484 	    !btrfs_test_opt(fs_info, SPACE_CACHE))
3485 		return 0;
3486 
3487 	path = btrfs_alloc_path();
3488 	if (!path)
3489 		return -ENOMEM;
3490 
3491 	/* Could add new block groups, use _safe just in case */
3492 	list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
3493 				 dirty_list) {
3494 		if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3495 			cache_save_setup(cache, trans, path);
3496 	}
3497 
3498 	btrfs_free_path(path);
3499 	return 0;
3500 }
3501 
3502 /*
3503  * transaction commit does final block group cache writeback during a
3504  * critical section where nothing is allowed to change the FS.  This is
3505  * required in order for the cache to actually match the block group,
3506  * but can introduce a lot of latency into the commit.
3507  *
3508  * So, btrfs_start_dirty_block_groups is here to kick off block group
3509  * cache IO.  There's a chance we'll have to redo some of it if the
3510  * block group changes again during the commit, but it greatly reduces
3511  * the commit latency by getting rid of the easy block groups while
3512  * we're still allowing others to join the commit.
3513  */
btrfs_start_dirty_block_groups(struct btrfs_trans_handle * trans)3514 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
3515 {
3516 	struct btrfs_fs_info *fs_info = trans->fs_info;
3517 	struct btrfs_block_group_cache *cache;
3518 	struct btrfs_transaction *cur_trans = trans->transaction;
3519 	int ret = 0;
3520 	int should_put;
3521 	struct btrfs_path *path = NULL;
3522 	LIST_HEAD(dirty);
3523 	struct list_head *io = &cur_trans->io_bgs;
3524 	int num_started = 0;
3525 	int loops = 0;
3526 
3527 	spin_lock(&cur_trans->dirty_bgs_lock);
3528 	if (list_empty(&cur_trans->dirty_bgs)) {
3529 		spin_unlock(&cur_trans->dirty_bgs_lock);
3530 		return 0;
3531 	}
3532 	list_splice_init(&cur_trans->dirty_bgs, &dirty);
3533 	spin_unlock(&cur_trans->dirty_bgs_lock);
3534 
3535 again:
3536 	/*
3537 	 * make sure all the block groups on our dirty list actually
3538 	 * exist
3539 	 */
3540 	btrfs_create_pending_block_groups(trans);
3541 
3542 	if (!path) {
3543 		path = btrfs_alloc_path();
3544 		if (!path)
3545 			return -ENOMEM;
3546 	}
3547 
3548 	/*
3549 	 * cache_write_mutex is here only to save us from balance or automatic
3550 	 * removal of empty block groups deleting this block group while we are
3551 	 * writing out the cache
3552 	 */
3553 	mutex_lock(&trans->transaction->cache_write_mutex);
3554 	while (!list_empty(&dirty)) {
3555 		cache = list_first_entry(&dirty,
3556 					 struct btrfs_block_group_cache,
3557 					 dirty_list);
3558 		/*
3559 		 * this can happen if something re-dirties a block
3560 		 * group that is already under IO.  Just wait for it to
3561 		 * finish and then do it all again
3562 		 */
3563 		if (!list_empty(&cache->io_list)) {
3564 			list_del_init(&cache->io_list);
3565 			btrfs_wait_cache_io(trans, cache, path);
3566 			btrfs_put_block_group(cache);
3567 		}
3568 
3569 
3570 		/*
3571 		 * btrfs_wait_cache_io uses the cache->dirty_list to decide
3572 		 * if it should update the cache_state.  Don't delete
3573 		 * until after we wait.
3574 		 *
3575 		 * Since we're not running in the commit critical section
3576 		 * we need the dirty_bgs_lock to protect from update_block_group
3577 		 */
3578 		spin_lock(&cur_trans->dirty_bgs_lock);
3579 		list_del_init(&cache->dirty_list);
3580 		spin_unlock(&cur_trans->dirty_bgs_lock);
3581 
3582 		should_put = 1;
3583 
3584 		cache_save_setup(cache, trans, path);
3585 
3586 		if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3587 			cache->io_ctl.inode = NULL;
3588 			ret = btrfs_write_out_cache(fs_info, trans,
3589 						    cache, path);
3590 			if (ret == 0 && cache->io_ctl.inode) {
3591 				num_started++;
3592 				should_put = 0;
3593 
3594 				/*
3595 				 * The cache_write_mutex is protecting the
3596 				 * io_list, also refer to the definition of
3597 				 * btrfs_transaction::io_bgs for more details
3598 				 */
3599 				list_add_tail(&cache->io_list, io);
3600 			} else {
3601 				/*
3602 				 * if we failed to write the cache, the
3603 				 * generation will be bad and life goes on
3604 				 */
3605 				ret = 0;
3606 			}
3607 		}
3608 		if (!ret) {
3609 			ret = write_one_cache_group(trans, fs_info,
3610 						    path, cache);
3611 			/*
3612 			 * Our block group might still be attached to the list
3613 			 * of new block groups in the transaction handle of some
3614 			 * other task (struct btrfs_trans_handle->new_bgs). This
3615 			 * means its block group item isn't yet in the extent
3616 			 * tree. If this happens ignore the error, as we will
3617 			 * try again later in the critical section of the
3618 			 * transaction commit.
3619 			 */
3620 			if (ret == -ENOENT) {
3621 				ret = 0;
3622 				spin_lock(&cur_trans->dirty_bgs_lock);
3623 				if (list_empty(&cache->dirty_list)) {
3624 					list_add_tail(&cache->dirty_list,
3625 						      &cur_trans->dirty_bgs);
3626 					btrfs_get_block_group(cache);
3627 				}
3628 				spin_unlock(&cur_trans->dirty_bgs_lock);
3629 			} else if (ret) {
3630 				btrfs_abort_transaction(trans, ret);
3631 			}
3632 		}
3633 
3634 		/* if its not on the io list, we need to put the block group */
3635 		if (should_put)
3636 			btrfs_put_block_group(cache);
3637 
3638 		if (ret)
3639 			break;
3640 
3641 		/*
3642 		 * Avoid blocking other tasks for too long. It might even save
3643 		 * us from writing caches for block groups that are going to be
3644 		 * removed.
3645 		 */
3646 		mutex_unlock(&trans->transaction->cache_write_mutex);
3647 		mutex_lock(&trans->transaction->cache_write_mutex);
3648 	}
3649 	mutex_unlock(&trans->transaction->cache_write_mutex);
3650 
3651 	/*
3652 	 * go through delayed refs for all the stuff we've just kicked off
3653 	 * and then loop back (just once)
3654 	 */
3655 	ret = btrfs_run_delayed_refs(trans, 0);
3656 	if (!ret && loops == 0) {
3657 		loops++;
3658 		spin_lock(&cur_trans->dirty_bgs_lock);
3659 		list_splice_init(&cur_trans->dirty_bgs, &dirty);
3660 		/*
3661 		 * dirty_bgs_lock protects us from concurrent block group
3662 		 * deletes too (not just cache_write_mutex).
3663 		 */
3664 		if (!list_empty(&dirty)) {
3665 			spin_unlock(&cur_trans->dirty_bgs_lock);
3666 			goto again;
3667 		}
3668 		spin_unlock(&cur_trans->dirty_bgs_lock);
3669 	} else if (ret < 0) {
3670 		btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
3671 	}
3672 
3673 	btrfs_free_path(path);
3674 	return ret;
3675 }
3676 
btrfs_write_dirty_block_groups(struct btrfs_trans_handle * trans,struct btrfs_fs_info * fs_info)3677 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
3678 				   struct btrfs_fs_info *fs_info)
3679 {
3680 	struct btrfs_block_group_cache *cache;
3681 	struct btrfs_transaction *cur_trans = trans->transaction;
3682 	int ret = 0;
3683 	int should_put;
3684 	struct btrfs_path *path;
3685 	struct list_head *io = &cur_trans->io_bgs;
3686 	int num_started = 0;
3687 
3688 	path = btrfs_alloc_path();
3689 	if (!path)
3690 		return -ENOMEM;
3691 
3692 	/*
3693 	 * Even though we are in the critical section of the transaction commit,
3694 	 * we can still have concurrent tasks adding elements to this
3695 	 * transaction's list of dirty block groups. These tasks correspond to
3696 	 * endio free space workers started when writeback finishes for a
3697 	 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3698 	 * allocate new block groups as a result of COWing nodes of the root
3699 	 * tree when updating the free space inode. The writeback for the space
3700 	 * caches is triggered by an earlier call to
3701 	 * btrfs_start_dirty_block_groups() and iterations of the following
3702 	 * loop.
3703 	 * Also we want to do the cache_save_setup first and then run the
3704 	 * delayed refs to make sure we have the best chance at doing this all
3705 	 * in one shot.
3706 	 */
3707 	spin_lock(&cur_trans->dirty_bgs_lock);
3708 	while (!list_empty(&cur_trans->dirty_bgs)) {
3709 		cache = list_first_entry(&cur_trans->dirty_bgs,
3710 					 struct btrfs_block_group_cache,
3711 					 dirty_list);
3712 
3713 		/*
3714 		 * this can happen if cache_save_setup re-dirties a block
3715 		 * group that is already under IO.  Just wait for it to
3716 		 * finish and then do it all again
3717 		 */
3718 		if (!list_empty(&cache->io_list)) {
3719 			spin_unlock(&cur_trans->dirty_bgs_lock);
3720 			list_del_init(&cache->io_list);
3721 			btrfs_wait_cache_io(trans, cache, path);
3722 			btrfs_put_block_group(cache);
3723 			spin_lock(&cur_trans->dirty_bgs_lock);
3724 		}
3725 
3726 		/*
3727 		 * don't remove from the dirty list until after we've waited
3728 		 * on any pending IO
3729 		 */
3730 		list_del_init(&cache->dirty_list);
3731 		spin_unlock(&cur_trans->dirty_bgs_lock);
3732 		should_put = 1;
3733 
3734 		cache_save_setup(cache, trans, path);
3735 
3736 		if (!ret)
3737 			ret = btrfs_run_delayed_refs(trans,
3738 						     (unsigned long) -1);
3739 
3740 		if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3741 			cache->io_ctl.inode = NULL;
3742 			ret = btrfs_write_out_cache(fs_info, trans,
3743 						    cache, path);
3744 			if (ret == 0 && cache->io_ctl.inode) {
3745 				num_started++;
3746 				should_put = 0;
3747 				list_add_tail(&cache->io_list, io);
3748 			} else {
3749 				/*
3750 				 * if we failed to write the cache, the
3751 				 * generation will be bad and life goes on
3752 				 */
3753 				ret = 0;
3754 			}
3755 		}
3756 		if (!ret) {
3757 			ret = write_one_cache_group(trans, fs_info,
3758 						    path, cache);
3759 			/*
3760 			 * One of the free space endio workers might have
3761 			 * created a new block group while updating a free space
3762 			 * cache's inode (at inode.c:btrfs_finish_ordered_io())
3763 			 * and hasn't released its transaction handle yet, in
3764 			 * which case the new block group is still attached to
3765 			 * its transaction handle and its creation has not
3766 			 * finished yet (no block group item in the extent tree
3767 			 * yet, etc). If this is the case, wait for all free
3768 			 * space endio workers to finish and retry. This is a
3769 			 * a very rare case so no need for a more efficient and
3770 			 * complex approach.
3771 			 */
3772 			if (ret == -ENOENT) {
3773 				wait_event(cur_trans->writer_wait,
3774 				   atomic_read(&cur_trans->num_writers) == 1);
3775 				ret = write_one_cache_group(trans, fs_info,
3776 							    path, cache);
3777 			}
3778 			if (ret)
3779 				btrfs_abort_transaction(trans, ret);
3780 		}
3781 
3782 		/* if its not on the io list, we need to put the block group */
3783 		if (should_put)
3784 			btrfs_put_block_group(cache);
3785 		spin_lock(&cur_trans->dirty_bgs_lock);
3786 	}
3787 	spin_unlock(&cur_trans->dirty_bgs_lock);
3788 
3789 	/*
3790 	 * Refer to the definition of io_bgs member for details why it's safe
3791 	 * to use it without any locking
3792 	 */
3793 	while (!list_empty(io)) {
3794 		cache = list_first_entry(io, struct btrfs_block_group_cache,
3795 					 io_list);
3796 		list_del_init(&cache->io_list);
3797 		btrfs_wait_cache_io(trans, cache, path);
3798 		btrfs_put_block_group(cache);
3799 	}
3800 
3801 	btrfs_free_path(path);
3802 	return ret;
3803 }
3804 
btrfs_extent_readonly(struct btrfs_fs_info * fs_info,u64 bytenr)3805 int btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
3806 {
3807 	struct btrfs_block_group_cache *block_group;
3808 	int readonly = 0;
3809 
3810 	block_group = btrfs_lookup_block_group(fs_info, bytenr);
3811 	if (!block_group || block_group->ro)
3812 		readonly = 1;
3813 	if (block_group)
3814 		btrfs_put_block_group(block_group);
3815 	return readonly;
3816 }
3817 
btrfs_inc_nocow_writers(struct btrfs_fs_info * fs_info,u64 bytenr)3818 bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3819 {
3820 	struct btrfs_block_group_cache *bg;
3821 	bool ret = true;
3822 
3823 	bg = btrfs_lookup_block_group(fs_info, bytenr);
3824 	if (!bg)
3825 		return false;
3826 
3827 	spin_lock(&bg->lock);
3828 	if (bg->ro)
3829 		ret = false;
3830 	else
3831 		atomic_inc(&bg->nocow_writers);
3832 	spin_unlock(&bg->lock);
3833 
3834 	/* no put on block group, done by btrfs_dec_nocow_writers */
3835 	if (!ret)
3836 		btrfs_put_block_group(bg);
3837 
3838 	return ret;
3839 
3840 }
3841 
btrfs_dec_nocow_writers(struct btrfs_fs_info * fs_info,u64 bytenr)3842 void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3843 {
3844 	struct btrfs_block_group_cache *bg;
3845 
3846 	bg = btrfs_lookup_block_group(fs_info, bytenr);
3847 	ASSERT(bg);
3848 	if (atomic_dec_and_test(&bg->nocow_writers))
3849 		wake_up_var(&bg->nocow_writers);
3850 	/*
3851 	 * Once for our lookup and once for the lookup done by a previous call
3852 	 * to btrfs_inc_nocow_writers()
3853 	 */
3854 	btrfs_put_block_group(bg);
3855 	btrfs_put_block_group(bg);
3856 }
3857 
btrfs_wait_nocow_writers(struct btrfs_block_group_cache * bg)3858 void btrfs_wait_nocow_writers(struct btrfs_block_group_cache *bg)
3859 {
3860 	wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
3861 }
3862 
alloc_name(u64 flags)3863 static const char *alloc_name(u64 flags)
3864 {
3865 	switch (flags) {
3866 	case BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA:
3867 		return "mixed";
3868 	case BTRFS_BLOCK_GROUP_METADATA:
3869 		return "metadata";
3870 	case BTRFS_BLOCK_GROUP_DATA:
3871 		return "data";
3872 	case BTRFS_BLOCK_GROUP_SYSTEM:
3873 		return "system";
3874 	default:
3875 		WARN_ON(1);
3876 		return "invalid-combination";
3877 	};
3878 }
3879 
create_space_info(struct btrfs_fs_info * info,u64 flags)3880 static int create_space_info(struct btrfs_fs_info *info, u64 flags)
3881 {
3882 
3883 	struct btrfs_space_info *space_info;
3884 	int i;
3885 	int ret;
3886 
3887 	space_info = kzalloc(sizeof(*space_info), GFP_NOFS);
3888 	if (!space_info)
3889 		return -ENOMEM;
3890 
3891 	ret = percpu_counter_init(&space_info->total_bytes_pinned, 0,
3892 				 GFP_KERNEL);
3893 	if (ret) {
3894 		kfree(space_info);
3895 		return ret;
3896 	}
3897 
3898 	for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
3899 		INIT_LIST_HEAD(&space_info->block_groups[i]);
3900 	init_rwsem(&space_info->groups_sem);
3901 	spin_lock_init(&space_info->lock);
3902 	space_info->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
3903 	space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3904 	init_waitqueue_head(&space_info->wait);
3905 	INIT_LIST_HEAD(&space_info->ro_bgs);
3906 	INIT_LIST_HEAD(&space_info->tickets);
3907 	INIT_LIST_HEAD(&space_info->priority_tickets);
3908 
3909 	ret = kobject_init_and_add(&space_info->kobj, &space_info_ktype,
3910 				    info->space_info_kobj, "%s",
3911 				    alloc_name(space_info->flags));
3912 	if (ret) {
3913 		kobject_put(&space_info->kobj);
3914 		return ret;
3915 	}
3916 
3917 	list_add_rcu(&space_info->list, &info->space_info);
3918 	if (flags & BTRFS_BLOCK_GROUP_DATA)
3919 		info->data_sinfo = space_info;
3920 
3921 	return ret;
3922 }
3923 
update_space_info(struct btrfs_fs_info * info,u64 flags,u64 total_bytes,u64 bytes_used,u64 bytes_readonly,struct btrfs_space_info ** space_info)3924 static void update_space_info(struct btrfs_fs_info *info, u64 flags,
3925 			     u64 total_bytes, u64 bytes_used,
3926 			     u64 bytes_readonly,
3927 			     struct btrfs_space_info **space_info)
3928 {
3929 	struct btrfs_space_info *found;
3930 	int factor;
3931 
3932 	factor = btrfs_bg_type_to_factor(flags);
3933 
3934 	found = __find_space_info(info, flags);
3935 	ASSERT(found);
3936 	spin_lock(&found->lock);
3937 	found->total_bytes += total_bytes;
3938 	found->disk_total += total_bytes * factor;
3939 	found->bytes_used += bytes_used;
3940 	found->disk_used += bytes_used * factor;
3941 	found->bytes_readonly += bytes_readonly;
3942 	if (total_bytes > 0)
3943 		found->full = 0;
3944 	space_info_add_new_bytes(info, found, total_bytes -
3945 				 bytes_used - bytes_readonly);
3946 	spin_unlock(&found->lock);
3947 	*space_info = found;
3948 }
3949 
set_avail_alloc_bits(struct btrfs_fs_info * fs_info,u64 flags)3950 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3951 {
3952 	u64 extra_flags = chunk_to_extended(flags) &
3953 				BTRFS_EXTENDED_PROFILE_MASK;
3954 
3955 	write_seqlock(&fs_info->profiles_lock);
3956 	if (flags & BTRFS_BLOCK_GROUP_DATA)
3957 		fs_info->avail_data_alloc_bits |= extra_flags;
3958 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
3959 		fs_info->avail_metadata_alloc_bits |= extra_flags;
3960 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3961 		fs_info->avail_system_alloc_bits |= extra_flags;
3962 	write_sequnlock(&fs_info->profiles_lock);
3963 }
3964 
3965 /*
3966  * returns target flags in extended format or 0 if restripe for this
3967  * chunk_type is not in progress
3968  *
3969  * should be called with balance_lock held
3970  */
get_restripe_target(struct btrfs_fs_info * fs_info,u64 flags)3971 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
3972 {
3973 	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3974 	u64 target = 0;
3975 
3976 	if (!bctl)
3977 		return 0;
3978 
3979 	if (flags & BTRFS_BLOCK_GROUP_DATA &&
3980 	    bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3981 		target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
3982 	} else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
3983 		   bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3984 		target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
3985 	} else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
3986 		   bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3987 		target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
3988 	}
3989 
3990 	return target;
3991 }
3992 
3993 /*
3994  * @flags: available profiles in extended format (see ctree.h)
3995  *
3996  * Returns reduced profile in chunk format.  If profile changing is in
3997  * progress (either running or paused) picks the target profile (if it's
3998  * already available), otherwise falls back to plain reducing.
3999  */
btrfs_reduce_alloc_profile(struct btrfs_fs_info * fs_info,u64 flags)4000 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
4001 {
4002 	u64 num_devices = fs_info->fs_devices->rw_devices;
4003 	u64 target;
4004 	u64 raid_type;
4005 	u64 allowed = 0;
4006 
4007 	/*
4008 	 * see if restripe for this chunk_type is in progress, if so
4009 	 * try to reduce to the target profile
4010 	 */
4011 	spin_lock(&fs_info->balance_lock);
4012 	target = get_restripe_target(fs_info, flags);
4013 	if (target) {
4014 		/* pick target profile only if it's already available */
4015 		if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
4016 			spin_unlock(&fs_info->balance_lock);
4017 			return extended_to_chunk(target);
4018 		}
4019 	}
4020 	spin_unlock(&fs_info->balance_lock);
4021 
4022 	/* First, mask out the RAID levels which aren't possible */
4023 	for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
4024 		if (num_devices >= btrfs_raid_array[raid_type].devs_min)
4025 			allowed |= btrfs_raid_array[raid_type].bg_flag;
4026 	}
4027 	allowed &= flags;
4028 
4029 	if (allowed & BTRFS_BLOCK_GROUP_RAID6)
4030 		allowed = BTRFS_BLOCK_GROUP_RAID6;
4031 	else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
4032 		allowed = BTRFS_BLOCK_GROUP_RAID5;
4033 	else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
4034 		allowed = BTRFS_BLOCK_GROUP_RAID10;
4035 	else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
4036 		allowed = BTRFS_BLOCK_GROUP_RAID1;
4037 	else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
4038 		allowed = BTRFS_BLOCK_GROUP_RAID0;
4039 
4040 	flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
4041 
4042 	return extended_to_chunk(flags | allowed);
4043 }
4044 
get_alloc_profile(struct btrfs_fs_info * fs_info,u64 orig_flags)4045 static u64 get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
4046 {
4047 	unsigned seq;
4048 	u64 flags;
4049 
4050 	do {
4051 		flags = orig_flags;
4052 		seq = read_seqbegin(&fs_info->profiles_lock);
4053 
4054 		if (flags & BTRFS_BLOCK_GROUP_DATA)
4055 			flags |= fs_info->avail_data_alloc_bits;
4056 		else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
4057 			flags |= fs_info->avail_system_alloc_bits;
4058 		else if (flags & BTRFS_BLOCK_GROUP_METADATA)
4059 			flags |= fs_info->avail_metadata_alloc_bits;
4060 	} while (read_seqretry(&fs_info->profiles_lock, seq));
4061 
4062 	return btrfs_reduce_alloc_profile(fs_info, flags);
4063 }
4064 
get_alloc_profile_by_root(struct btrfs_root * root,int data)4065 static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
4066 {
4067 	struct btrfs_fs_info *fs_info = root->fs_info;
4068 	u64 flags;
4069 	u64 ret;
4070 
4071 	if (data)
4072 		flags = BTRFS_BLOCK_GROUP_DATA;
4073 	else if (root == fs_info->chunk_root)
4074 		flags = BTRFS_BLOCK_GROUP_SYSTEM;
4075 	else
4076 		flags = BTRFS_BLOCK_GROUP_METADATA;
4077 
4078 	ret = get_alloc_profile(fs_info, flags);
4079 	return ret;
4080 }
4081 
btrfs_data_alloc_profile(struct btrfs_fs_info * fs_info)4082 u64 btrfs_data_alloc_profile(struct btrfs_fs_info *fs_info)
4083 {
4084 	return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_DATA);
4085 }
4086 
btrfs_metadata_alloc_profile(struct btrfs_fs_info * fs_info)4087 u64 btrfs_metadata_alloc_profile(struct btrfs_fs_info *fs_info)
4088 {
4089 	return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4090 }
4091 
btrfs_system_alloc_profile(struct btrfs_fs_info * fs_info)4092 u64 btrfs_system_alloc_profile(struct btrfs_fs_info *fs_info)
4093 {
4094 	return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4095 }
4096 
btrfs_space_info_used(struct btrfs_space_info * s_info,bool may_use_included)4097 static u64 btrfs_space_info_used(struct btrfs_space_info *s_info,
4098 				 bool may_use_included)
4099 {
4100 	ASSERT(s_info);
4101 	return s_info->bytes_used + s_info->bytes_reserved +
4102 		s_info->bytes_pinned + s_info->bytes_readonly +
4103 		(may_use_included ? s_info->bytes_may_use : 0);
4104 }
4105 
btrfs_alloc_data_chunk_ondemand(struct btrfs_inode * inode,u64 bytes)4106 int btrfs_alloc_data_chunk_ondemand(struct btrfs_inode *inode, u64 bytes)
4107 {
4108 	struct btrfs_root *root = inode->root;
4109 	struct btrfs_fs_info *fs_info = root->fs_info;
4110 	struct btrfs_space_info *data_sinfo = fs_info->data_sinfo;
4111 	u64 used;
4112 	int ret = 0;
4113 	int need_commit = 2;
4114 	int have_pinned_space;
4115 
4116 	/* make sure bytes are sectorsize aligned */
4117 	bytes = ALIGN(bytes, fs_info->sectorsize);
4118 
4119 	if (btrfs_is_free_space_inode(inode)) {
4120 		need_commit = 0;
4121 		ASSERT(current->journal_info);
4122 	}
4123 
4124 again:
4125 	/* make sure we have enough space to handle the data first */
4126 	spin_lock(&data_sinfo->lock);
4127 	used = btrfs_space_info_used(data_sinfo, true);
4128 
4129 	if (used + bytes > data_sinfo->total_bytes) {
4130 		struct btrfs_trans_handle *trans;
4131 
4132 		/*
4133 		 * if we don't have enough free bytes in this space then we need
4134 		 * to alloc a new chunk.
4135 		 */
4136 		if (!data_sinfo->full) {
4137 			u64 alloc_target;
4138 
4139 			data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
4140 			spin_unlock(&data_sinfo->lock);
4141 
4142 			alloc_target = btrfs_data_alloc_profile(fs_info);
4143 			/*
4144 			 * It is ugly that we don't call nolock join
4145 			 * transaction for the free space inode case here.
4146 			 * But it is safe because we only do the data space
4147 			 * reservation for the free space cache in the
4148 			 * transaction context, the common join transaction
4149 			 * just increase the counter of the current transaction
4150 			 * handler, doesn't try to acquire the trans_lock of
4151 			 * the fs.
4152 			 */
4153 			trans = btrfs_join_transaction(root);
4154 			if (IS_ERR(trans))
4155 				return PTR_ERR(trans);
4156 
4157 			ret = do_chunk_alloc(trans, alloc_target,
4158 					     CHUNK_ALLOC_NO_FORCE);
4159 			btrfs_end_transaction(trans);
4160 			if (ret < 0) {
4161 				if (ret != -ENOSPC)
4162 					return ret;
4163 				else {
4164 					have_pinned_space = 1;
4165 					goto commit_trans;
4166 				}
4167 			}
4168 
4169 			goto again;
4170 		}
4171 
4172 		/*
4173 		 * If we don't have enough pinned space to deal with this
4174 		 * allocation, and no removed chunk in current transaction,
4175 		 * don't bother committing the transaction.
4176 		 */
4177 		have_pinned_space = __percpu_counter_compare(
4178 			&data_sinfo->total_bytes_pinned,
4179 			used + bytes - data_sinfo->total_bytes,
4180 			BTRFS_TOTAL_BYTES_PINNED_BATCH);
4181 		spin_unlock(&data_sinfo->lock);
4182 
4183 		/* commit the current transaction and try again */
4184 commit_trans:
4185 		if (need_commit) {
4186 			need_commit--;
4187 
4188 			if (need_commit > 0) {
4189 				btrfs_start_delalloc_roots(fs_info, -1);
4190 				btrfs_wait_ordered_roots(fs_info, U64_MAX, 0,
4191 							 (u64)-1);
4192 			}
4193 
4194 			trans = btrfs_join_transaction(root);
4195 			if (IS_ERR(trans))
4196 				return PTR_ERR(trans);
4197 			if (have_pinned_space >= 0 ||
4198 			    test_bit(BTRFS_TRANS_HAVE_FREE_BGS,
4199 				     &trans->transaction->flags) ||
4200 			    need_commit > 0) {
4201 				ret = btrfs_commit_transaction(trans);
4202 				if (ret)
4203 					return ret;
4204 				/*
4205 				 * The cleaner kthread might still be doing iput
4206 				 * operations. Wait for it to finish so that
4207 				 * more space is released.
4208 				 */
4209 				mutex_lock(&fs_info->cleaner_delayed_iput_mutex);
4210 				mutex_unlock(&fs_info->cleaner_delayed_iput_mutex);
4211 				goto again;
4212 			} else {
4213 				btrfs_end_transaction(trans);
4214 			}
4215 		}
4216 
4217 		trace_btrfs_space_reservation(fs_info,
4218 					      "space_info:enospc",
4219 					      data_sinfo->flags, bytes, 1);
4220 		return -ENOSPC;
4221 	}
4222 	data_sinfo->bytes_may_use += bytes;
4223 	trace_btrfs_space_reservation(fs_info, "space_info",
4224 				      data_sinfo->flags, bytes, 1);
4225 	spin_unlock(&data_sinfo->lock);
4226 
4227 	return 0;
4228 }
4229 
btrfs_check_data_free_space(struct inode * inode,struct extent_changeset ** reserved,u64 start,u64 len)4230 int btrfs_check_data_free_space(struct inode *inode,
4231 			struct extent_changeset **reserved, u64 start, u64 len)
4232 {
4233 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4234 	int ret;
4235 
4236 	/* align the range */
4237 	len = round_up(start + len, fs_info->sectorsize) -
4238 	      round_down(start, fs_info->sectorsize);
4239 	start = round_down(start, fs_info->sectorsize);
4240 
4241 	ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode), len);
4242 	if (ret < 0)
4243 		return ret;
4244 
4245 	/* Use new btrfs_qgroup_reserve_data to reserve precious data space. */
4246 	ret = btrfs_qgroup_reserve_data(inode, reserved, start, len);
4247 	if (ret < 0)
4248 		btrfs_free_reserved_data_space_noquota(inode, start, len);
4249 	else
4250 		ret = 0;
4251 	return ret;
4252 }
4253 
4254 /*
4255  * Called if we need to clear a data reservation for this inode
4256  * Normally in a error case.
4257  *
4258  * This one will *NOT* use accurate qgroup reserved space API, just for case
4259  * which we can't sleep and is sure it won't affect qgroup reserved space.
4260  * Like clear_bit_hook().
4261  */
btrfs_free_reserved_data_space_noquota(struct inode * inode,u64 start,u64 len)4262 void btrfs_free_reserved_data_space_noquota(struct inode *inode, u64 start,
4263 					    u64 len)
4264 {
4265 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4266 	struct btrfs_space_info *data_sinfo;
4267 
4268 	/* Make sure the range is aligned to sectorsize */
4269 	len = round_up(start + len, fs_info->sectorsize) -
4270 	      round_down(start, fs_info->sectorsize);
4271 	start = round_down(start, fs_info->sectorsize);
4272 
4273 	data_sinfo = fs_info->data_sinfo;
4274 	spin_lock(&data_sinfo->lock);
4275 	if (WARN_ON(data_sinfo->bytes_may_use < len))
4276 		data_sinfo->bytes_may_use = 0;
4277 	else
4278 		data_sinfo->bytes_may_use -= len;
4279 	trace_btrfs_space_reservation(fs_info, "space_info",
4280 				      data_sinfo->flags, len, 0);
4281 	spin_unlock(&data_sinfo->lock);
4282 }
4283 
4284 /*
4285  * Called if we need to clear a data reservation for this inode
4286  * Normally in a error case.
4287  *
4288  * This one will handle the per-inode data rsv map for accurate reserved
4289  * space framework.
4290  */
btrfs_free_reserved_data_space(struct inode * inode,struct extent_changeset * reserved,u64 start,u64 len)4291 void btrfs_free_reserved_data_space(struct inode *inode,
4292 			struct extent_changeset *reserved, u64 start, u64 len)
4293 {
4294 	struct btrfs_root *root = BTRFS_I(inode)->root;
4295 
4296 	/* Make sure the range is aligned to sectorsize */
4297 	len = round_up(start + len, root->fs_info->sectorsize) -
4298 	      round_down(start, root->fs_info->sectorsize);
4299 	start = round_down(start, root->fs_info->sectorsize);
4300 
4301 	btrfs_free_reserved_data_space_noquota(inode, start, len);
4302 	btrfs_qgroup_free_data(inode, reserved, start, len);
4303 }
4304 
force_metadata_allocation(struct btrfs_fs_info * info)4305 static void force_metadata_allocation(struct btrfs_fs_info *info)
4306 {
4307 	struct list_head *head = &info->space_info;
4308 	struct btrfs_space_info *found;
4309 
4310 	rcu_read_lock();
4311 	list_for_each_entry_rcu(found, head, list) {
4312 		if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
4313 			found->force_alloc = CHUNK_ALLOC_FORCE;
4314 	}
4315 	rcu_read_unlock();
4316 }
4317 
calc_global_rsv_need_space(struct btrfs_block_rsv * global)4318 static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
4319 {
4320 	return (global->size << 1);
4321 }
4322 
should_alloc_chunk(struct btrfs_fs_info * fs_info,struct btrfs_space_info * sinfo,int force)4323 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
4324 			      struct btrfs_space_info *sinfo, int force)
4325 {
4326 	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4327 	u64 bytes_used = btrfs_space_info_used(sinfo, false);
4328 	u64 thresh;
4329 
4330 	if (force == CHUNK_ALLOC_FORCE)
4331 		return 1;
4332 
4333 	/*
4334 	 * We need to take into account the global rsv because for all intents
4335 	 * and purposes it's used space.  Don't worry about locking the
4336 	 * global_rsv, it doesn't change except when the transaction commits.
4337 	 */
4338 	if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
4339 		bytes_used += calc_global_rsv_need_space(global_rsv);
4340 
4341 	/*
4342 	 * in limited mode, we want to have some free space up to
4343 	 * about 1% of the FS size.
4344 	 */
4345 	if (force == CHUNK_ALLOC_LIMITED) {
4346 		thresh = btrfs_super_total_bytes(fs_info->super_copy);
4347 		thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
4348 
4349 		if (sinfo->total_bytes - bytes_used < thresh)
4350 			return 1;
4351 	}
4352 
4353 	if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
4354 		return 0;
4355 	return 1;
4356 }
4357 
get_profile_num_devs(struct btrfs_fs_info * fs_info,u64 type)4358 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
4359 {
4360 	u64 num_dev;
4361 
4362 	if (type & (BTRFS_BLOCK_GROUP_RAID10 |
4363 		    BTRFS_BLOCK_GROUP_RAID0 |
4364 		    BTRFS_BLOCK_GROUP_RAID5 |
4365 		    BTRFS_BLOCK_GROUP_RAID6))
4366 		num_dev = fs_info->fs_devices->rw_devices;
4367 	else if (type & BTRFS_BLOCK_GROUP_RAID1)
4368 		num_dev = 2;
4369 	else
4370 		num_dev = 1;	/* DUP or single */
4371 
4372 	return num_dev;
4373 }
4374 
4375 /*
4376  * If @is_allocation is true, reserve space in the system space info necessary
4377  * for allocating a chunk, otherwise if it's false, reserve space necessary for
4378  * removing a chunk.
4379  */
check_system_chunk(struct btrfs_trans_handle * trans,u64 type)4380 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
4381 {
4382 	struct btrfs_fs_info *fs_info = trans->fs_info;
4383 	struct btrfs_space_info *info;
4384 	u64 left;
4385 	u64 thresh;
4386 	int ret = 0;
4387 	u64 num_devs;
4388 
4389 	/*
4390 	 * Needed because we can end up allocating a system chunk and for an
4391 	 * atomic and race free space reservation in the chunk block reserve.
4392 	 */
4393 	lockdep_assert_held(&fs_info->chunk_mutex);
4394 
4395 	info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4396 	spin_lock(&info->lock);
4397 	left = info->total_bytes - btrfs_space_info_used(info, true);
4398 	spin_unlock(&info->lock);
4399 
4400 	num_devs = get_profile_num_devs(fs_info, type);
4401 
4402 	/* num_devs device items to update and 1 chunk item to add or remove */
4403 	thresh = btrfs_calc_trunc_metadata_size(fs_info, num_devs) +
4404 		btrfs_calc_trans_metadata_size(fs_info, 1);
4405 
4406 	if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4407 		btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
4408 			   left, thresh, type);
4409 		dump_space_info(fs_info, info, 0, 0);
4410 	}
4411 
4412 	if (left < thresh) {
4413 		u64 flags = btrfs_system_alloc_profile(fs_info);
4414 
4415 		/*
4416 		 * Ignore failure to create system chunk. We might end up not
4417 		 * needing it, as we might not need to COW all nodes/leafs from
4418 		 * the paths we visit in the chunk tree (they were already COWed
4419 		 * or created in the current transaction for example).
4420 		 */
4421 		ret = btrfs_alloc_chunk(trans, flags);
4422 	}
4423 
4424 	if (!ret) {
4425 		ret = btrfs_block_rsv_add(fs_info->chunk_root,
4426 					  &fs_info->chunk_block_rsv,
4427 					  thresh, BTRFS_RESERVE_NO_FLUSH);
4428 		if (!ret)
4429 			trans->chunk_bytes_reserved += thresh;
4430 	}
4431 }
4432 
4433 /*
4434  * If force is CHUNK_ALLOC_FORCE:
4435  *    - return 1 if it successfully allocates a chunk,
4436  *    - return errors including -ENOSPC otherwise.
4437  * If force is NOT CHUNK_ALLOC_FORCE:
4438  *    - return 0 if it doesn't need to allocate a new chunk,
4439  *    - return 1 if it successfully allocates a chunk,
4440  *    - return errors including -ENOSPC otherwise.
4441  */
do_chunk_alloc(struct btrfs_trans_handle * trans,u64 flags,int force)4442 static int do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
4443 			  int force)
4444 {
4445 	struct btrfs_fs_info *fs_info = trans->fs_info;
4446 	struct btrfs_space_info *space_info;
4447 	bool wait_for_alloc = false;
4448 	bool should_alloc = false;
4449 	int ret = 0;
4450 
4451 	/* Don't re-enter if we're already allocating a chunk */
4452 	if (trans->allocating_chunk)
4453 		return -ENOSPC;
4454 
4455 	space_info = __find_space_info(fs_info, flags);
4456 	ASSERT(space_info);
4457 
4458 	do {
4459 		spin_lock(&space_info->lock);
4460 		if (force < space_info->force_alloc)
4461 			force = space_info->force_alloc;
4462 		should_alloc = should_alloc_chunk(fs_info, space_info, force);
4463 		if (space_info->full) {
4464 			/* No more free physical space */
4465 			if (should_alloc)
4466 				ret = -ENOSPC;
4467 			else
4468 				ret = 0;
4469 			spin_unlock(&space_info->lock);
4470 			return ret;
4471 		} else if (!should_alloc) {
4472 			spin_unlock(&space_info->lock);
4473 			return 0;
4474 		} else if (space_info->chunk_alloc) {
4475 			/*
4476 			 * Someone is already allocating, so we need to block
4477 			 * until this someone is finished and then loop to
4478 			 * recheck if we should continue with our allocation
4479 			 * attempt.
4480 			 */
4481 			wait_for_alloc = true;
4482 			spin_unlock(&space_info->lock);
4483 			mutex_lock(&fs_info->chunk_mutex);
4484 			mutex_unlock(&fs_info->chunk_mutex);
4485 		} else {
4486 			/* Proceed with allocation */
4487 			space_info->chunk_alloc = 1;
4488 			wait_for_alloc = false;
4489 			spin_unlock(&space_info->lock);
4490 		}
4491 
4492 		cond_resched();
4493 	} while (wait_for_alloc);
4494 
4495 	mutex_lock(&fs_info->chunk_mutex);
4496 	trans->allocating_chunk = true;
4497 
4498 	/*
4499 	 * If we have mixed data/metadata chunks we want to make sure we keep
4500 	 * allocating mixed chunks instead of individual chunks.
4501 	 */
4502 	if (btrfs_mixed_space_info(space_info))
4503 		flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
4504 
4505 	/*
4506 	 * if we're doing a data chunk, go ahead and make sure that
4507 	 * we keep a reasonable number of metadata chunks allocated in the
4508 	 * FS as well.
4509 	 */
4510 	if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
4511 		fs_info->data_chunk_allocations++;
4512 		if (!(fs_info->data_chunk_allocations %
4513 		      fs_info->metadata_ratio))
4514 			force_metadata_allocation(fs_info);
4515 	}
4516 
4517 	/*
4518 	 * Check if we have enough space in SYSTEM chunk because we may need
4519 	 * to update devices.
4520 	 */
4521 	check_system_chunk(trans, flags);
4522 
4523 	ret = btrfs_alloc_chunk(trans, flags);
4524 	trans->allocating_chunk = false;
4525 
4526 	spin_lock(&space_info->lock);
4527 	if (ret < 0) {
4528 		if (ret == -ENOSPC)
4529 			space_info->full = 1;
4530 		else
4531 			goto out;
4532 	} else {
4533 		ret = 1;
4534 		space_info->max_extent_size = 0;
4535 	}
4536 
4537 	space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
4538 out:
4539 	space_info->chunk_alloc = 0;
4540 	spin_unlock(&space_info->lock);
4541 	mutex_unlock(&fs_info->chunk_mutex);
4542 	/*
4543 	 * When we allocate a new chunk we reserve space in the chunk block
4544 	 * reserve to make sure we can COW nodes/leafs in the chunk tree or
4545 	 * add new nodes/leafs to it if we end up needing to do it when
4546 	 * inserting the chunk item and updating device items as part of the
4547 	 * second phase of chunk allocation, performed by
4548 	 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
4549 	 * large number of new block groups to create in our transaction
4550 	 * handle's new_bgs list to avoid exhausting the chunk block reserve
4551 	 * in extreme cases - like having a single transaction create many new
4552 	 * block groups when starting to write out the free space caches of all
4553 	 * the block groups that were made dirty during the lifetime of the
4554 	 * transaction.
4555 	 */
4556 	if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
4557 		btrfs_create_pending_block_groups(trans);
4558 
4559 	return ret;
4560 }
4561 
can_overcommit(struct btrfs_fs_info * fs_info,struct btrfs_space_info * space_info,u64 bytes,enum btrfs_reserve_flush_enum flush,bool system_chunk)4562 static int can_overcommit(struct btrfs_fs_info *fs_info,
4563 			  struct btrfs_space_info *space_info, u64 bytes,
4564 			  enum btrfs_reserve_flush_enum flush,
4565 			  bool system_chunk)
4566 {
4567 	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4568 	u64 profile;
4569 	u64 space_size;
4570 	u64 avail;
4571 	u64 used;
4572 	int factor;
4573 
4574 	/* Don't overcommit when in mixed mode. */
4575 	if (space_info->flags & BTRFS_BLOCK_GROUP_DATA)
4576 		return 0;
4577 
4578 	if (system_chunk)
4579 		profile = btrfs_system_alloc_profile(fs_info);
4580 	else
4581 		profile = btrfs_metadata_alloc_profile(fs_info);
4582 
4583 	used = btrfs_space_info_used(space_info, false);
4584 
4585 	/*
4586 	 * We only want to allow over committing if we have lots of actual space
4587 	 * free, but if we don't have enough space to handle the global reserve
4588 	 * space then we could end up having a real enospc problem when trying
4589 	 * to allocate a chunk or some other such important allocation.
4590 	 */
4591 	spin_lock(&global_rsv->lock);
4592 	space_size = calc_global_rsv_need_space(global_rsv);
4593 	spin_unlock(&global_rsv->lock);
4594 	if (used + space_size >= space_info->total_bytes)
4595 		return 0;
4596 
4597 	used += space_info->bytes_may_use;
4598 
4599 	avail = atomic64_read(&fs_info->free_chunk_space);
4600 
4601 	/*
4602 	 * If we have dup, raid1 or raid10 then only half of the free
4603 	 * space is actually useable.  For raid56, the space info used
4604 	 * doesn't include the parity drive, so we don't have to
4605 	 * change the math
4606 	 */
4607 	factor = btrfs_bg_type_to_factor(profile);
4608 	avail = div_u64(avail, factor);
4609 
4610 	/*
4611 	 * If we aren't flushing all things, let us overcommit up to
4612 	 * 1/2th of the space. If we can flush, don't let us overcommit
4613 	 * too much, let it overcommit up to 1/8 of the space.
4614 	 */
4615 	if (flush == BTRFS_RESERVE_FLUSH_ALL)
4616 		avail >>= 3;
4617 	else
4618 		avail >>= 1;
4619 
4620 	if (used + bytes < space_info->total_bytes + avail)
4621 		return 1;
4622 	return 0;
4623 }
4624 
btrfs_writeback_inodes_sb_nr(struct btrfs_fs_info * fs_info,unsigned long nr_pages,int nr_items)4625 static void btrfs_writeback_inodes_sb_nr(struct btrfs_fs_info *fs_info,
4626 					 unsigned long nr_pages, int nr_items)
4627 {
4628 	struct super_block *sb = fs_info->sb;
4629 
4630 	if (down_read_trylock(&sb->s_umount)) {
4631 		writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
4632 		up_read(&sb->s_umount);
4633 	} else {
4634 		/*
4635 		 * We needn't worry the filesystem going from r/w to r/o though
4636 		 * we don't acquire ->s_umount mutex, because the filesystem
4637 		 * should guarantee the delalloc inodes list be empty after
4638 		 * the filesystem is readonly(all dirty pages are written to
4639 		 * the disk).
4640 		 */
4641 		btrfs_start_delalloc_roots(fs_info, nr_items);
4642 		if (!current->journal_info)
4643 			btrfs_wait_ordered_roots(fs_info, nr_items, 0, (u64)-1);
4644 	}
4645 }
4646 
calc_reclaim_items_nr(struct btrfs_fs_info * fs_info,u64 to_reclaim)4647 static inline u64 calc_reclaim_items_nr(struct btrfs_fs_info *fs_info,
4648 					u64 to_reclaim)
4649 {
4650 	u64 bytes;
4651 	u64 nr;
4652 
4653 	bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
4654 	nr = div64_u64(to_reclaim, bytes);
4655 	if (!nr)
4656 		nr = 1;
4657 	return nr;
4658 }
4659 
4660 #define EXTENT_SIZE_PER_ITEM	SZ_256K
4661 
4662 /*
4663  * shrink metadata reservation for delalloc
4664  */
shrink_delalloc(struct btrfs_fs_info * fs_info,u64 to_reclaim,u64 orig,bool wait_ordered)4665 static void shrink_delalloc(struct btrfs_fs_info *fs_info, u64 to_reclaim,
4666 			    u64 orig, bool wait_ordered)
4667 {
4668 	struct btrfs_space_info *space_info;
4669 	struct btrfs_trans_handle *trans;
4670 	u64 delalloc_bytes;
4671 	u64 max_reclaim;
4672 	u64 items;
4673 	long time_left;
4674 	unsigned long nr_pages;
4675 	int loops;
4676 
4677 	/* Calc the number of the pages we need flush for space reservation */
4678 	items = calc_reclaim_items_nr(fs_info, to_reclaim);
4679 	to_reclaim = items * EXTENT_SIZE_PER_ITEM;
4680 
4681 	trans = (struct btrfs_trans_handle *)current->journal_info;
4682 	space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4683 
4684 	delalloc_bytes = percpu_counter_sum_positive(
4685 						&fs_info->delalloc_bytes);
4686 	if (delalloc_bytes == 0) {
4687 		if (trans)
4688 			return;
4689 		if (wait_ordered)
4690 			btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
4691 		return;
4692 	}
4693 
4694 	loops = 0;
4695 	while (delalloc_bytes && loops < 3) {
4696 		max_reclaim = min(delalloc_bytes, to_reclaim);
4697 		nr_pages = max_reclaim >> PAGE_SHIFT;
4698 		btrfs_writeback_inodes_sb_nr(fs_info, nr_pages, items);
4699 		/*
4700 		 * We need to wait for the async pages to actually start before
4701 		 * we do anything.
4702 		 */
4703 		max_reclaim = atomic_read(&fs_info->async_delalloc_pages);
4704 		if (!max_reclaim)
4705 			goto skip_async;
4706 
4707 		if (max_reclaim <= nr_pages)
4708 			max_reclaim = 0;
4709 		else
4710 			max_reclaim -= nr_pages;
4711 
4712 		wait_event(fs_info->async_submit_wait,
4713 			   atomic_read(&fs_info->async_delalloc_pages) <=
4714 			   (int)max_reclaim);
4715 skip_async:
4716 		spin_lock(&space_info->lock);
4717 		if (list_empty(&space_info->tickets) &&
4718 		    list_empty(&space_info->priority_tickets)) {
4719 			spin_unlock(&space_info->lock);
4720 			break;
4721 		}
4722 		spin_unlock(&space_info->lock);
4723 
4724 		loops++;
4725 		if (wait_ordered && !trans) {
4726 			btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
4727 		} else {
4728 			time_left = schedule_timeout_killable(1);
4729 			if (time_left)
4730 				break;
4731 		}
4732 		delalloc_bytes = percpu_counter_sum_positive(
4733 						&fs_info->delalloc_bytes);
4734 	}
4735 }
4736 
4737 struct reserve_ticket {
4738 	u64 bytes;
4739 	int error;
4740 	struct list_head list;
4741 	wait_queue_head_t wait;
4742 };
4743 
4744 /**
4745  * maybe_commit_transaction - possibly commit the transaction if its ok to
4746  * @root - the root we're allocating for
4747  * @bytes - the number of bytes we want to reserve
4748  * @force - force the commit
4749  *
4750  * This will check to make sure that committing the transaction will actually
4751  * get us somewhere and then commit the transaction if it does.  Otherwise it
4752  * will return -ENOSPC.
4753  */
may_commit_transaction(struct btrfs_fs_info * fs_info,struct btrfs_space_info * space_info)4754 static int may_commit_transaction(struct btrfs_fs_info *fs_info,
4755 				  struct btrfs_space_info *space_info)
4756 {
4757 	struct reserve_ticket *ticket = NULL;
4758 	struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_block_rsv;
4759 	struct btrfs_trans_handle *trans;
4760 	u64 bytes;
4761 
4762 	trans = (struct btrfs_trans_handle *)current->journal_info;
4763 	if (trans)
4764 		return -EAGAIN;
4765 
4766 	spin_lock(&space_info->lock);
4767 	if (!list_empty(&space_info->priority_tickets))
4768 		ticket = list_first_entry(&space_info->priority_tickets,
4769 					  struct reserve_ticket, list);
4770 	else if (!list_empty(&space_info->tickets))
4771 		ticket = list_first_entry(&space_info->tickets,
4772 					  struct reserve_ticket, list);
4773 	bytes = (ticket) ? ticket->bytes : 0;
4774 	spin_unlock(&space_info->lock);
4775 
4776 	if (!bytes)
4777 		return 0;
4778 
4779 	/* See if there is enough pinned space to make this reservation */
4780 	if (__percpu_counter_compare(&space_info->total_bytes_pinned,
4781 				   bytes,
4782 				   BTRFS_TOTAL_BYTES_PINNED_BATCH) >= 0)
4783 		goto commit;
4784 
4785 	/*
4786 	 * See if there is some space in the delayed insertion reservation for
4787 	 * this reservation.
4788 	 */
4789 	if (space_info != delayed_rsv->space_info)
4790 		return -ENOSPC;
4791 
4792 	spin_lock(&delayed_rsv->lock);
4793 	if (delayed_rsv->size > bytes)
4794 		bytes = 0;
4795 	else
4796 		bytes -= delayed_rsv->size;
4797 	spin_unlock(&delayed_rsv->lock);
4798 
4799 	if (__percpu_counter_compare(&space_info->total_bytes_pinned,
4800 				   bytes,
4801 				   BTRFS_TOTAL_BYTES_PINNED_BATCH) < 0) {
4802 		return -ENOSPC;
4803 	}
4804 
4805 commit:
4806 	trans = btrfs_join_transaction(fs_info->extent_root);
4807 	if (IS_ERR(trans))
4808 		return -ENOSPC;
4809 
4810 	return btrfs_commit_transaction(trans);
4811 }
4812 
4813 /*
4814  * Try to flush some data based on policy set by @state. This is only advisory
4815  * and may fail for various reasons. The caller is supposed to examine the
4816  * state of @space_info to detect the outcome.
4817  */
flush_space(struct btrfs_fs_info * fs_info,struct btrfs_space_info * space_info,u64 num_bytes,int state)4818 static void flush_space(struct btrfs_fs_info *fs_info,
4819 		       struct btrfs_space_info *space_info, u64 num_bytes,
4820 		       int state)
4821 {
4822 	struct btrfs_root *root = fs_info->extent_root;
4823 	struct btrfs_trans_handle *trans;
4824 	int nr;
4825 	int ret = 0;
4826 
4827 	switch (state) {
4828 	case FLUSH_DELAYED_ITEMS_NR:
4829 	case FLUSH_DELAYED_ITEMS:
4830 		if (state == FLUSH_DELAYED_ITEMS_NR)
4831 			nr = calc_reclaim_items_nr(fs_info, num_bytes) * 2;
4832 		else
4833 			nr = -1;
4834 
4835 		trans = btrfs_join_transaction(root);
4836 		if (IS_ERR(trans)) {
4837 			ret = PTR_ERR(trans);
4838 			break;
4839 		}
4840 		ret = btrfs_run_delayed_items_nr(trans, nr);
4841 		btrfs_end_transaction(trans);
4842 		break;
4843 	case FLUSH_DELALLOC:
4844 	case FLUSH_DELALLOC_WAIT:
4845 		shrink_delalloc(fs_info, num_bytes * 2, num_bytes,
4846 				state == FLUSH_DELALLOC_WAIT);
4847 		break;
4848 	case ALLOC_CHUNK:
4849 		trans = btrfs_join_transaction(root);
4850 		if (IS_ERR(trans)) {
4851 			ret = PTR_ERR(trans);
4852 			break;
4853 		}
4854 		ret = do_chunk_alloc(trans,
4855 				     btrfs_metadata_alloc_profile(fs_info),
4856 				     CHUNK_ALLOC_NO_FORCE);
4857 		btrfs_end_transaction(trans);
4858 		if (ret > 0 || ret == -ENOSPC)
4859 			ret = 0;
4860 		break;
4861 	case COMMIT_TRANS:
4862 		ret = may_commit_transaction(fs_info, space_info);
4863 		break;
4864 	default:
4865 		ret = -ENOSPC;
4866 		break;
4867 	}
4868 
4869 	trace_btrfs_flush_space(fs_info, space_info->flags, num_bytes, state,
4870 				ret);
4871 	return;
4872 }
4873 
4874 static inline u64
btrfs_calc_reclaim_metadata_size(struct btrfs_fs_info * fs_info,struct btrfs_space_info * space_info,bool system_chunk)4875 btrfs_calc_reclaim_metadata_size(struct btrfs_fs_info *fs_info,
4876 				 struct btrfs_space_info *space_info,
4877 				 bool system_chunk)
4878 {
4879 	struct reserve_ticket *ticket;
4880 	u64 used;
4881 	u64 expected;
4882 	u64 to_reclaim = 0;
4883 
4884 	list_for_each_entry(ticket, &space_info->tickets, list)
4885 		to_reclaim += ticket->bytes;
4886 	list_for_each_entry(ticket, &space_info->priority_tickets, list)
4887 		to_reclaim += ticket->bytes;
4888 	if (to_reclaim)
4889 		return to_reclaim;
4890 
4891 	to_reclaim = min_t(u64, num_online_cpus() * SZ_1M, SZ_16M);
4892 	if (can_overcommit(fs_info, space_info, to_reclaim,
4893 			   BTRFS_RESERVE_FLUSH_ALL, system_chunk))
4894 		return 0;
4895 
4896 	used = btrfs_space_info_used(space_info, true);
4897 
4898 	if (can_overcommit(fs_info, space_info, SZ_1M,
4899 			   BTRFS_RESERVE_FLUSH_ALL, system_chunk))
4900 		expected = div_factor_fine(space_info->total_bytes, 95);
4901 	else
4902 		expected = div_factor_fine(space_info->total_bytes, 90);
4903 
4904 	if (used > expected)
4905 		to_reclaim = used - expected;
4906 	else
4907 		to_reclaim = 0;
4908 	to_reclaim = min(to_reclaim, space_info->bytes_may_use +
4909 				     space_info->bytes_reserved);
4910 	return to_reclaim;
4911 }
4912 
need_do_async_reclaim(struct btrfs_fs_info * fs_info,struct btrfs_space_info * space_info,u64 used,bool system_chunk)4913 static inline int need_do_async_reclaim(struct btrfs_fs_info *fs_info,
4914 					struct btrfs_space_info *space_info,
4915 					u64 used, bool system_chunk)
4916 {
4917 	u64 thresh = div_factor_fine(space_info->total_bytes, 98);
4918 
4919 	/* If we're just plain full then async reclaim just slows us down. */
4920 	if ((space_info->bytes_used + space_info->bytes_reserved) >= thresh)
4921 		return 0;
4922 
4923 	if (!btrfs_calc_reclaim_metadata_size(fs_info, space_info,
4924 					      system_chunk))
4925 		return 0;
4926 
4927 	return (used >= thresh && !btrfs_fs_closing(fs_info) &&
4928 		!test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
4929 }
4930 
wake_all_tickets(struct list_head * head)4931 static void wake_all_tickets(struct list_head *head)
4932 {
4933 	struct reserve_ticket *ticket;
4934 
4935 	while (!list_empty(head)) {
4936 		ticket = list_first_entry(head, struct reserve_ticket, list);
4937 		list_del_init(&ticket->list);
4938 		ticket->error = -ENOSPC;
4939 		wake_up(&ticket->wait);
4940 	}
4941 }
4942 
4943 /*
4944  * This is for normal flushers, we can wait all goddamned day if we want to.  We
4945  * will loop and continuously try to flush as long as we are making progress.
4946  * We count progress as clearing off tickets each time we have to loop.
4947  */
btrfs_async_reclaim_metadata_space(struct work_struct * work)4948 static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
4949 {
4950 	struct btrfs_fs_info *fs_info;
4951 	struct btrfs_space_info *space_info;
4952 	u64 to_reclaim;
4953 	int flush_state;
4954 	int commit_cycles = 0;
4955 	u64 last_tickets_id;
4956 
4957 	fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
4958 	space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4959 
4960 	spin_lock(&space_info->lock);
4961 	to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info,
4962 						      false);
4963 	if (!to_reclaim) {
4964 		space_info->flush = 0;
4965 		spin_unlock(&space_info->lock);
4966 		return;
4967 	}
4968 	last_tickets_id = space_info->tickets_id;
4969 	spin_unlock(&space_info->lock);
4970 
4971 	flush_state = FLUSH_DELAYED_ITEMS_NR;
4972 	do {
4973 		flush_space(fs_info, space_info, to_reclaim, flush_state);
4974 		spin_lock(&space_info->lock);
4975 		if (list_empty(&space_info->tickets)) {
4976 			space_info->flush = 0;
4977 			spin_unlock(&space_info->lock);
4978 			return;
4979 		}
4980 		to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info,
4981 							      space_info,
4982 							      false);
4983 		if (last_tickets_id == space_info->tickets_id) {
4984 			flush_state++;
4985 		} else {
4986 			last_tickets_id = space_info->tickets_id;
4987 			flush_state = FLUSH_DELAYED_ITEMS_NR;
4988 			if (commit_cycles)
4989 				commit_cycles--;
4990 		}
4991 
4992 		if (flush_state > COMMIT_TRANS) {
4993 			commit_cycles++;
4994 			if (commit_cycles > 2) {
4995 				wake_all_tickets(&space_info->tickets);
4996 				space_info->flush = 0;
4997 			} else {
4998 				flush_state = FLUSH_DELAYED_ITEMS_NR;
4999 			}
5000 		}
5001 		spin_unlock(&space_info->lock);
5002 	} while (flush_state <= COMMIT_TRANS);
5003 }
5004 
btrfs_init_async_reclaim_work(struct work_struct * work)5005 void btrfs_init_async_reclaim_work(struct work_struct *work)
5006 {
5007 	INIT_WORK(work, btrfs_async_reclaim_metadata_space);
5008 }
5009 
priority_reclaim_metadata_space(struct btrfs_fs_info * fs_info,struct btrfs_space_info * space_info,struct reserve_ticket * ticket)5010 static void priority_reclaim_metadata_space(struct btrfs_fs_info *fs_info,
5011 					    struct btrfs_space_info *space_info,
5012 					    struct reserve_ticket *ticket)
5013 {
5014 	u64 to_reclaim;
5015 	int flush_state = FLUSH_DELAYED_ITEMS_NR;
5016 
5017 	spin_lock(&space_info->lock);
5018 	to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info,
5019 						      false);
5020 	if (!to_reclaim) {
5021 		spin_unlock(&space_info->lock);
5022 		return;
5023 	}
5024 	spin_unlock(&space_info->lock);
5025 
5026 	do {
5027 		flush_space(fs_info, space_info, to_reclaim, flush_state);
5028 		flush_state++;
5029 		spin_lock(&space_info->lock);
5030 		if (ticket->bytes == 0) {
5031 			spin_unlock(&space_info->lock);
5032 			return;
5033 		}
5034 		spin_unlock(&space_info->lock);
5035 
5036 		/*
5037 		 * Priority flushers can't wait on delalloc without
5038 		 * deadlocking.
5039 		 */
5040 		if (flush_state == FLUSH_DELALLOC ||
5041 		    flush_state == FLUSH_DELALLOC_WAIT)
5042 			flush_state = ALLOC_CHUNK;
5043 	} while (flush_state < COMMIT_TRANS);
5044 }
5045 
wait_reserve_ticket(struct btrfs_fs_info * fs_info,struct btrfs_space_info * space_info,struct reserve_ticket * ticket,u64 orig_bytes)5046 static int wait_reserve_ticket(struct btrfs_fs_info *fs_info,
5047 			       struct btrfs_space_info *space_info,
5048 			       struct reserve_ticket *ticket, u64 orig_bytes)
5049 
5050 {
5051 	DEFINE_WAIT(wait);
5052 	int ret = 0;
5053 
5054 	spin_lock(&space_info->lock);
5055 	while (ticket->bytes > 0 && ticket->error == 0) {
5056 		ret = prepare_to_wait_event(&ticket->wait, &wait, TASK_KILLABLE);
5057 		if (ret) {
5058 			ret = -EINTR;
5059 			break;
5060 		}
5061 		spin_unlock(&space_info->lock);
5062 
5063 		schedule();
5064 
5065 		finish_wait(&ticket->wait, &wait);
5066 		spin_lock(&space_info->lock);
5067 	}
5068 	if (!ret)
5069 		ret = ticket->error;
5070 	if (!list_empty(&ticket->list))
5071 		list_del_init(&ticket->list);
5072 	if (ticket->bytes && ticket->bytes < orig_bytes) {
5073 		u64 num_bytes = orig_bytes - ticket->bytes;
5074 		space_info->bytes_may_use -= num_bytes;
5075 		trace_btrfs_space_reservation(fs_info, "space_info",
5076 					      space_info->flags, num_bytes, 0);
5077 	}
5078 	spin_unlock(&space_info->lock);
5079 
5080 	return ret;
5081 }
5082 
5083 /**
5084  * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5085  * @root - the root we're allocating for
5086  * @space_info - the space info we want to allocate from
5087  * @orig_bytes - the number of bytes we want
5088  * @flush - whether or not we can flush to make our reservation
5089  *
5090  * This will reserve orig_bytes number of bytes from the space info associated
5091  * with the block_rsv.  If there is not enough space it will make an attempt to
5092  * flush out space to make room.  It will do this by flushing delalloc if
5093  * possible or committing the transaction.  If flush is 0 then no attempts to
5094  * regain reservations will be made and this will fail if there is not enough
5095  * space already.
5096  */
__reserve_metadata_bytes(struct btrfs_fs_info * fs_info,struct btrfs_space_info * space_info,u64 orig_bytes,enum btrfs_reserve_flush_enum flush,bool system_chunk)5097 static int __reserve_metadata_bytes(struct btrfs_fs_info *fs_info,
5098 				    struct btrfs_space_info *space_info,
5099 				    u64 orig_bytes,
5100 				    enum btrfs_reserve_flush_enum flush,
5101 				    bool system_chunk)
5102 {
5103 	struct reserve_ticket ticket;
5104 	u64 used;
5105 	int ret = 0;
5106 
5107 	ASSERT(orig_bytes);
5108 	ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_ALL);
5109 
5110 	spin_lock(&space_info->lock);
5111 	ret = -ENOSPC;
5112 	used = btrfs_space_info_used(space_info, true);
5113 
5114 	/*
5115 	 * If we have enough space then hooray, make our reservation and carry
5116 	 * on.  If not see if we can overcommit, and if we can, hooray carry on.
5117 	 * If not things get more complicated.
5118 	 */
5119 	if (used + orig_bytes <= space_info->total_bytes) {
5120 		space_info->bytes_may_use += orig_bytes;
5121 		trace_btrfs_space_reservation(fs_info, "space_info",
5122 					      space_info->flags, orig_bytes, 1);
5123 		ret = 0;
5124 	} else if (can_overcommit(fs_info, space_info, orig_bytes, flush,
5125 				  system_chunk)) {
5126 		space_info->bytes_may_use += orig_bytes;
5127 		trace_btrfs_space_reservation(fs_info, "space_info",
5128 					      space_info->flags, orig_bytes, 1);
5129 		ret = 0;
5130 	}
5131 
5132 	/*
5133 	 * If we couldn't make a reservation then setup our reservation ticket
5134 	 * and kick the async worker if it's not already running.
5135 	 *
5136 	 * If we are a priority flusher then we just need to add our ticket to
5137 	 * the list and we will do our own flushing further down.
5138 	 */
5139 	if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
5140 		ticket.bytes = orig_bytes;
5141 		ticket.error = 0;
5142 		init_waitqueue_head(&ticket.wait);
5143 		if (flush == BTRFS_RESERVE_FLUSH_ALL) {
5144 			list_add_tail(&ticket.list, &space_info->tickets);
5145 			if (!space_info->flush) {
5146 				space_info->flush = 1;
5147 				trace_btrfs_trigger_flush(fs_info,
5148 							  space_info->flags,
5149 							  orig_bytes, flush,
5150 							  "enospc");
5151 				queue_work(system_unbound_wq,
5152 					   &fs_info->async_reclaim_work);
5153 			}
5154 		} else {
5155 			list_add_tail(&ticket.list,
5156 				      &space_info->priority_tickets);
5157 		}
5158 	} else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
5159 		used += orig_bytes;
5160 		/*
5161 		 * We will do the space reservation dance during log replay,
5162 		 * which means we won't have fs_info->fs_root set, so don't do
5163 		 * the async reclaim as we will panic.
5164 		 */
5165 		if (!test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags) &&
5166 		    need_do_async_reclaim(fs_info, space_info,
5167 					  used, system_chunk) &&
5168 		    !work_busy(&fs_info->async_reclaim_work)) {
5169 			trace_btrfs_trigger_flush(fs_info, space_info->flags,
5170 						  orig_bytes, flush, "preempt");
5171 			queue_work(system_unbound_wq,
5172 				   &fs_info->async_reclaim_work);
5173 		}
5174 	}
5175 	spin_unlock(&space_info->lock);
5176 	if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
5177 		return ret;
5178 
5179 	if (flush == BTRFS_RESERVE_FLUSH_ALL)
5180 		return wait_reserve_ticket(fs_info, space_info, &ticket,
5181 					   orig_bytes);
5182 
5183 	ret = 0;
5184 	priority_reclaim_metadata_space(fs_info, space_info, &ticket);
5185 	spin_lock(&space_info->lock);
5186 	if (ticket.bytes) {
5187 		if (ticket.bytes < orig_bytes) {
5188 			u64 num_bytes = orig_bytes - ticket.bytes;
5189 			space_info->bytes_may_use -= num_bytes;
5190 			trace_btrfs_space_reservation(fs_info, "space_info",
5191 						      space_info->flags,
5192 						      num_bytes, 0);
5193 
5194 		}
5195 		list_del_init(&ticket.list);
5196 		ret = -ENOSPC;
5197 	}
5198 	spin_unlock(&space_info->lock);
5199 	ASSERT(list_empty(&ticket.list));
5200 	return ret;
5201 }
5202 
5203 /**
5204  * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5205  * @root - the root we're allocating for
5206  * @block_rsv - the block_rsv we're allocating for
5207  * @orig_bytes - the number of bytes we want
5208  * @flush - whether or not we can flush to make our reservation
5209  *
5210  * This will reserve orgi_bytes number of bytes from the space info associated
5211  * with the block_rsv.  If there is not enough space it will make an attempt to
5212  * flush out space to make room.  It will do this by flushing delalloc if
5213  * possible or committing the transaction.  If flush is 0 then no attempts to
5214  * regain reservations will be made and this will fail if there is not enough
5215  * space already.
5216  */
reserve_metadata_bytes(struct btrfs_root * root,struct btrfs_block_rsv * block_rsv,u64 orig_bytes,enum btrfs_reserve_flush_enum flush)5217 static int reserve_metadata_bytes(struct btrfs_root *root,
5218 				  struct btrfs_block_rsv *block_rsv,
5219 				  u64 orig_bytes,
5220 				  enum btrfs_reserve_flush_enum flush)
5221 {
5222 	struct btrfs_fs_info *fs_info = root->fs_info;
5223 	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5224 	int ret;
5225 	bool system_chunk = (root == fs_info->chunk_root);
5226 
5227 	ret = __reserve_metadata_bytes(fs_info, block_rsv->space_info,
5228 				       orig_bytes, flush, system_chunk);
5229 	if (ret == -ENOSPC &&
5230 	    unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
5231 		if (block_rsv != global_rsv &&
5232 		    !block_rsv_use_bytes(global_rsv, orig_bytes))
5233 			ret = 0;
5234 	}
5235 	if (ret == -ENOSPC) {
5236 		trace_btrfs_space_reservation(fs_info, "space_info:enospc",
5237 					      block_rsv->space_info->flags,
5238 					      orig_bytes, 1);
5239 
5240 		if (btrfs_test_opt(fs_info, ENOSPC_DEBUG))
5241 			dump_space_info(fs_info, block_rsv->space_info,
5242 					orig_bytes, 0);
5243 	}
5244 	return ret;
5245 }
5246 
get_block_rsv(const struct btrfs_trans_handle * trans,const struct btrfs_root * root)5247 static struct btrfs_block_rsv *get_block_rsv(
5248 					const struct btrfs_trans_handle *trans,
5249 					const struct btrfs_root *root)
5250 {
5251 	struct btrfs_fs_info *fs_info = root->fs_info;
5252 	struct btrfs_block_rsv *block_rsv = NULL;
5253 
5254 	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
5255 	    (root == fs_info->csum_root && trans->adding_csums) ||
5256 	    (root == fs_info->uuid_root))
5257 		block_rsv = trans->block_rsv;
5258 
5259 	if (!block_rsv)
5260 		block_rsv = root->block_rsv;
5261 
5262 	if (!block_rsv)
5263 		block_rsv = &fs_info->empty_block_rsv;
5264 
5265 	return block_rsv;
5266 }
5267 
block_rsv_use_bytes(struct btrfs_block_rsv * block_rsv,u64 num_bytes)5268 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
5269 			       u64 num_bytes)
5270 {
5271 	int ret = -ENOSPC;
5272 	spin_lock(&block_rsv->lock);
5273 	if (block_rsv->reserved >= num_bytes) {
5274 		block_rsv->reserved -= num_bytes;
5275 		if (block_rsv->reserved < block_rsv->size)
5276 			block_rsv->full = 0;
5277 		ret = 0;
5278 	}
5279 	spin_unlock(&block_rsv->lock);
5280 	return ret;
5281 }
5282 
block_rsv_add_bytes(struct btrfs_block_rsv * block_rsv,u64 num_bytes,int update_size)5283 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
5284 				u64 num_bytes, int update_size)
5285 {
5286 	spin_lock(&block_rsv->lock);
5287 	block_rsv->reserved += num_bytes;
5288 	if (update_size)
5289 		block_rsv->size += num_bytes;
5290 	else if (block_rsv->reserved >= block_rsv->size)
5291 		block_rsv->full = 1;
5292 	spin_unlock(&block_rsv->lock);
5293 }
5294 
btrfs_cond_migrate_bytes(struct btrfs_fs_info * fs_info,struct btrfs_block_rsv * dest,u64 num_bytes,int min_factor)5295 int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
5296 			     struct btrfs_block_rsv *dest, u64 num_bytes,
5297 			     int min_factor)
5298 {
5299 	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5300 	u64 min_bytes;
5301 
5302 	if (global_rsv->space_info != dest->space_info)
5303 		return -ENOSPC;
5304 
5305 	spin_lock(&global_rsv->lock);
5306 	min_bytes = div_factor(global_rsv->size, min_factor);
5307 	if (global_rsv->reserved < min_bytes + num_bytes) {
5308 		spin_unlock(&global_rsv->lock);
5309 		return -ENOSPC;
5310 	}
5311 	global_rsv->reserved -= num_bytes;
5312 	if (global_rsv->reserved < global_rsv->size)
5313 		global_rsv->full = 0;
5314 	spin_unlock(&global_rsv->lock);
5315 
5316 	block_rsv_add_bytes(dest, num_bytes, 1);
5317 	return 0;
5318 }
5319 
5320 /*
5321  * This is for space we already have accounted in space_info->bytes_may_use, so
5322  * basically when we're returning space from block_rsv's.
5323  */
space_info_add_old_bytes(struct btrfs_fs_info * fs_info,struct btrfs_space_info * space_info,u64 num_bytes)5324 static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
5325 				     struct btrfs_space_info *space_info,
5326 				     u64 num_bytes)
5327 {
5328 	struct reserve_ticket *ticket;
5329 	struct list_head *head;
5330 	u64 used;
5331 	enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_NO_FLUSH;
5332 	bool check_overcommit = false;
5333 
5334 	spin_lock(&space_info->lock);
5335 	head = &space_info->priority_tickets;
5336 
5337 	/*
5338 	 * If we are over our limit then we need to check and see if we can
5339 	 * overcommit, and if we can't then we just need to free up our space
5340 	 * and not satisfy any requests.
5341 	 */
5342 	used = btrfs_space_info_used(space_info, true);
5343 	if (used - num_bytes >= space_info->total_bytes)
5344 		check_overcommit = true;
5345 again:
5346 	while (!list_empty(head) && num_bytes) {
5347 		ticket = list_first_entry(head, struct reserve_ticket,
5348 					  list);
5349 		/*
5350 		 * We use 0 bytes because this space is already reserved, so
5351 		 * adding the ticket space would be a double count.
5352 		 */
5353 		if (check_overcommit &&
5354 		    !can_overcommit(fs_info, space_info, 0, flush, false))
5355 			break;
5356 		if (num_bytes >= ticket->bytes) {
5357 			list_del_init(&ticket->list);
5358 			num_bytes -= ticket->bytes;
5359 			ticket->bytes = 0;
5360 			space_info->tickets_id++;
5361 			wake_up(&ticket->wait);
5362 		} else {
5363 			ticket->bytes -= num_bytes;
5364 			num_bytes = 0;
5365 		}
5366 	}
5367 
5368 	if (num_bytes && head == &space_info->priority_tickets) {
5369 		head = &space_info->tickets;
5370 		flush = BTRFS_RESERVE_FLUSH_ALL;
5371 		goto again;
5372 	}
5373 	space_info->bytes_may_use -= num_bytes;
5374 	trace_btrfs_space_reservation(fs_info, "space_info",
5375 				      space_info->flags, num_bytes, 0);
5376 	spin_unlock(&space_info->lock);
5377 }
5378 
5379 /*
5380  * This is for newly allocated space that isn't accounted in
5381  * space_info->bytes_may_use yet.  So if we allocate a chunk or unpin an extent
5382  * we use this helper.
5383  */
space_info_add_new_bytes(struct btrfs_fs_info * fs_info,struct btrfs_space_info * space_info,u64 num_bytes)5384 static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
5385 				     struct btrfs_space_info *space_info,
5386 				     u64 num_bytes)
5387 {
5388 	struct reserve_ticket *ticket;
5389 	struct list_head *head = &space_info->priority_tickets;
5390 
5391 again:
5392 	while (!list_empty(head) && num_bytes) {
5393 		ticket = list_first_entry(head, struct reserve_ticket,
5394 					  list);
5395 		if (num_bytes >= ticket->bytes) {
5396 			trace_btrfs_space_reservation(fs_info, "space_info",
5397 						      space_info->flags,
5398 						      ticket->bytes, 1);
5399 			list_del_init(&ticket->list);
5400 			num_bytes -= ticket->bytes;
5401 			space_info->bytes_may_use += ticket->bytes;
5402 			ticket->bytes = 0;
5403 			space_info->tickets_id++;
5404 			wake_up(&ticket->wait);
5405 		} else {
5406 			trace_btrfs_space_reservation(fs_info, "space_info",
5407 						      space_info->flags,
5408 						      num_bytes, 1);
5409 			space_info->bytes_may_use += num_bytes;
5410 			ticket->bytes -= num_bytes;
5411 			num_bytes = 0;
5412 		}
5413 	}
5414 
5415 	if (num_bytes && head == &space_info->priority_tickets) {
5416 		head = &space_info->tickets;
5417 		goto again;
5418 	}
5419 }
5420 
block_rsv_release_bytes(struct btrfs_fs_info * fs_info,struct btrfs_block_rsv * block_rsv,struct btrfs_block_rsv * dest,u64 num_bytes,u64 * qgroup_to_release_ret)5421 static u64 block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
5422 				    struct btrfs_block_rsv *block_rsv,
5423 				    struct btrfs_block_rsv *dest, u64 num_bytes,
5424 				    u64 *qgroup_to_release_ret)
5425 {
5426 	struct btrfs_space_info *space_info = block_rsv->space_info;
5427 	u64 qgroup_to_release = 0;
5428 	u64 ret;
5429 
5430 	spin_lock(&block_rsv->lock);
5431 	if (num_bytes == (u64)-1) {
5432 		num_bytes = block_rsv->size;
5433 		qgroup_to_release = block_rsv->qgroup_rsv_size;
5434 	}
5435 	block_rsv->size -= num_bytes;
5436 	if (block_rsv->reserved >= block_rsv->size) {
5437 		num_bytes = block_rsv->reserved - block_rsv->size;
5438 		block_rsv->reserved = block_rsv->size;
5439 		block_rsv->full = 1;
5440 	} else {
5441 		num_bytes = 0;
5442 	}
5443 	if (block_rsv->qgroup_rsv_reserved >= block_rsv->qgroup_rsv_size) {
5444 		qgroup_to_release = block_rsv->qgroup_rsv_reserved -
5445 				    block_rsv->qgroup_rsv_size;
5446 		block_rsv->qgroup_rsv_reserved = block_rsv->qgroup_rsv_size;
5447 	} else {
5448 		qgroup_to_release = 0;
5449 	}
5450 	spin_unlock(&block_rsv->lock);
5451 
5452 	ret = num_bytes;
5453 	if (num_bytes > 0) {
5454 		if (dest) {
5455 			spin_lock(&dest->lock);
5456 			if (!dest->full) {
5457 				u64 bytes_to_add;
5458 
5459 				bytes_to_add = dest->size - dest->reserved;
5460 				bytes_to_add = min(num_bytes, bytes_to_add);
5461 				dest->reserved += bytes_to_add;
5462 				if (dest->reserved >= dest->size)
5463 					dest->full = 1;
5464 				num_bytes -= bytes_to_add;
5465 			}
5466 			spin_unlock(&dest->lock);
5467 		}
5468 		if (num_bytes)
5469 			space_info_add_old_bytes(fs_info, space_info,
5470 						 num_bytes);
5471 	}
5472 	if (qgroup_to_release_ret)
5473 		*qgroup_to_release_ret = qgroup_to_release;
5474 	return ret;
5475 }
5476 
btrfs_block_rsv_migrate(struct btrfs_block_rsv * src,struct btrfs_block_rsv * dst,u64 num_bytes,int update_size)5477 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src,
5478 			    struct btrfs_block_rsv *dst, u64 num_bytes,
5479 			    int update_size)
5480 {
5481 	int ret;
5482 
5483 	ret = block_rsv_use_bytes(src, num_bytes);
5484 	if (ret)
5485 		return ret;
5486 
5487 	block_rsv_add_bytes(dst, num_bytes, update_size);
5488 	return 0;
5489 }
5490 
btrfs_init_block_rsv(struct btrfs_block_rsv * rsv,unsigned short type)5491 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
5492 {
5493 	memset(rsv, 0, sizeof(*rsv));
5494 	spin_lock_init(&rsv->lock);
5495 	rsv->type = type;
5496 }
5497 
btrfs_init_metadata_block_rsv(struct btrfs_fs_info * fs_info,struct btrfs_block_rsv * rsv,unsigned short type)5498 void btrfs_init_metadata_block_rsv(struct btrfs_fs_info *fs_info,
5499 				   struct btrfs_block_rsv *rsv,
5500 				   unsigned short type)
5501 {
5502 	btrfs_init_block_rsv(rsv, type);
5503 	rsv->space_info = __find_space_info(fs_info,
5504 					    BTRFS_BLOCK_GROUP_METADATA);
5505 }
5506 
btrfs_alloc_block_rsv(struct btrfs_fs_info * fs_info,unsigned short type)5507 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_fs_info *fs_info,
5508 					      unsigned short type)
5509 {
5510 	struct btrfs_block_rsv *block_rsv;
5511 
5512 	block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
5513 	if (!block_rsv)
5514 		return NULL;
5515 
5516 	btrfs_init_metadata_block_rsv(fs_info, block_rsv, type);
5517 	return block_rsv;
5518 }
5519 
btrfs_free_block_rsv(struct btrfs_fs_info * fs_info,struct btrfs_block_rsv * rsv)5520 void btrfs_free_block_rsv(struct btrfs_fs_info *fs_info,
5521 			  struct btrfs_block_rsv *rsv)
5522 {
5523 	if (!rsv)
5524 		return;
5525 	btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
5526 	kfree(rsv);
5527 }
5528 
btrfs_block_rsv_add(struct btrfs_root * root,struct btrfs_block_rsv * block_rsv,u64 num_bytes,enum btrfs_reserve_flush_enum flush)5529 int btrfs_block_rsv_add(struct btrfs_root *root,
5530 			struct btrfs_block_rsv *block_rsv, u64 num_bytes,
5531 			enum btrfs_reserve_flush_enum flush)
5532 {
5533 	int ret;
5534 
5535 	if (num_bytes == 0)
5536 		return 0;
5537 
5538 	ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5539 	if (!ret) {
5540 		block_rsv_add_bytes(block_rsv, num_bytes, 1);
5541 		return 0;
5542 	}
5543 
5544 	return ret;
5545 }
5546 
btrfs_block_rsv_check(struct btrfs_block_rsv * block_rsv,int min_factor)5547 int btrfs_block_rsv_check(struct btrfs_block_rsv *block_rsv, int min_factor)
5548 {
5549 	u64 num_bytes = 0;
5550 	int ret = -ENOSPC;
5551 
5552 	if (!block_rsv)
5553 		return 0;
5554 
5555 	spin_lock(&block_rsv->lock);
5556 	num_bytes = div_factor(block_rsv->size, min_factor);
5557 	if (block_rsv->reserved >= num_bytes)
5558 		ret = 0;
5559 	spin_unlock(&block_rsv->lock);
5560 
5561 	return ret;
5562 }
5563 
btrfs_block_rsv_refill(struct btrfs_root * root,struct btrfs_block_rsv * block_rsv,u64 min_reserved,enum btrfs_reserve_flush_enum flush)5564 int btrfs_block_rsv_refill(struct btrfs_root *root,
5565 			   struct btrfs_block_rsv *block_rsv, u64 min_reserved,
5566 			   enum btrfs_reserve_flush_enum flush)
5567 {
5568 	u64 num_bytes = 0;
5569 	int ret = -ENOSPC;
5570 
5571 	if (!block_rsv)
5572 		return 0;
5573 
5574 	spin_lock(&block_rsv->lock);
5575 	num_bytes = min_reserved;
5576 	if (block_rsv->reserved >= num_bytes)
5577 		ret = 0;
5578 	else
5579 		num_bytes -= block_rsv->reserved;
5580 	spin_unlock(&block_rsv->lock);
5581 
5582 	if (!ret)
5583 		return 0;
5584 
5585 	ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5586 	if (!ret) {
5587 		block_rsv_add_bytes(block_rsv, num_bytes, 0);
5588 		return 0;
5589 	}
5590 
5591 	return ret;
5592 }
5593 
5594 /**
5595  * btrfs_inode_rsv_refill - refill the inode block rsv.
5596  * @inode - the inode we are refilling.
5597  * @flush - the flusing restriction.
5598  *
5599  * Essentially the same as btrfs_block_rsv_refill, except it uses the
5600  * block_rsv->size as the minimum size.  We'll either refill the missing amount
5601  * or return if we already have enough space.  This will also handle the resreve
5602  * tracepoint for the reserved amount.
5603  */
btrfs_inode_rsv_refill(struct btrfs_inode * inode,enum btrfs_reserve_flush_enum flush)5604 static int btrfs_inode_rsv_refill(struct btrfs_inode *inode,
5605 				  enum btrfs_reserve_flush_enum flush)
5606 {
5607 	struct btrfs_root *root = inode->root;
5608 	struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
5609 	u64 num_bytes = 0;
5610 	u64 qgroup_num_bytes = 0;
5611 	int ret = -ENOSPC;
5612 
5613 	spin_lock(&block_rsv->lock);
5614 	if (block_rsv->reserved < block_rsv->size)
5615 		num_bytes = block_rsv->size - block_rsv->reserved;
5616 	if (block_rsv->qgroup_rsv_reserved < block_rsv->qgroup_rsv_size)
5617 		qgroup_num_bytes = block_rsv->qgroup_rsv_size -
5618 				   block_rsv->qgroup_rsv_reserved;
5619 	spin_unlock(&block_rsv->lock);
5620 
5621 	if (num_bytes == 0)
5622 		return 0;
5623 
5624 	ret = btrfs_qgroup_reserve_meta_prealloc(root, qgroup_num_bytes, true);
5625 	if (ret)
5626 		return ret;
5627 	ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5628 	if (!ret) {
5629 		block_rsv_add_bytes(block_rsv, num_bytes, 0);
5630 		trace_btrfs_space_reservation(root->fs_info, "delalloc",
5631 					      btrfs_ino(inode), num_bytes, 1);
5632 
5633 		/* Don't forget to increase qgroup_rsv_reserved */
5634 		spin_lock(&block_rsv->lock);
5635 		block_rsv->qgroup_rsv_reserved += qgroup_num_bytes;
5636 		spin_unlock(&block_rsv->lock);
5637 	} else
5638 		btrfs_qgroup_free_meta_prealloc(root, qgroup_num_bytes);
5639 	return ret;
5640 }
5641 
5642 /**
5643  * btrfs_inode_rsv_release - release any excessive reservation.
5644  * @inode - the inode we need to release from.
5645  * @qgroup_free - free or convert qgroup meta.
5646  *   Unlike normal operation, qgroup meta reservation needs to know if we are
5647  *   freeing qgroup reservation or just converting it into per-trans.  Normally
5648  *   @qgroup_free is true for error handling, and false for normal release.
5649  *
5650  * This is the same as btrfs_block_rsv_release, except that it handles the
5651  * tracepoint for the reservation.
5652  */
btrfs_inode_rsv_release(struct btrfs_inode * inode,bool qgroup_free)5653 static void btrfs_inode_rsv_release(struct btrfs_inode *inode, bool qgroup_free)
5654 {
5655 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
5656 	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5657 	struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
5658 	u64 released = 0;
5659 	u64 qgroup_to_release = 0;
5660 
5661 	/*
5662 	 * Since we statically set the block_rsv->size we just want to say we
5663 	 * are releasing 0 bytes, and then we'll just get the reservation over
5664 	 * the size free'd.
5665 	 */
5666 	released = block_rsv_release_bytes(fs_info, block_rsv, global_rsv, 0,
5667 					   &qgroup_to_release);
5668 	if (released > 0)
5669 		trace_btrfs_space_reservation(fs_info, "delalloc",
5670 					      btrfs_ino(inode), released, 0);
5671 	if (qgroup_free)
5672 		btrfs_qgroup_free_meta_prealloc(inode->root, qgroup_to_release);
5673 	else
5674 		btrfs_qgroup_convert_reserved_meta(inode->root,
5675 						   qgroup_to_release);
5676 }
5677 
btrfs_block_rsv_release(struct btrfs_fs_info * fs_info,struct btrfs_block_rsv * block_rsv,u64 num_bytes)5678 void btrfs_block_rsv_release(struct btrfs_fs_info *fs_info,
5679 			     struct btrfs_block_rsv *block_rsv,
5680 			     u64 num_bytes)
5681 {
5682 	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5683 
5684 	if (global_rsv == block_rsv ||
5685 	    block_rsv->space_info != global_rsv->space_info)
5686 		global_rsv = NULL;
5687 	block_rsv_release_bytes(fs_info, block_rsv, global_rsv, num_bytes, NULL);
5688 }
5689 
update_global_block_rsv(struct btrfs_fs_info * fs_info)5690 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
5691 {
5692 	struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
5693 	struct btrfs_space_info *sinfo = block_rsv->space_info;
5694 	u64 num_bytes;
5695 
5696 	/*
5697 	 * The global block rsv is based on the size of the extent tree, the
5698 	 * checksum tree and the root tree.  If the fs is empty we want to set
5699 	 * it to a minimal amount for safety.
5700 	 */
5701 	num_bytes = btrfs_root_used(&fs_info->extent_root->root_item) +
5702 		btrfs_root_used(&fs_info->csum_root->root_item) +
5703 		btrfs_root_used(&fs_info->tree_root->root_item);
5704 	num_bytes = max_t(u64, num_bytes, SZ_16M);
5705 
5706 	spin_lock(&sinfo->lock);
5707 	spin_lock(&block_rsv->lock);
5708 
5709 	block_rsv->size = min_t(u64, num_bytes, SZ_512M);
5710 
5711 	if (block_rsv->reserved < block_rsv->size) {
5712 		num_bytes = btrfs_space_info_used(sinfo, true);
5713 		if (sinfo->total_bytes > num_bytes) {
5714 			num_bytes = sinfo->total_bytes - num_bytes;
5715 			num_bytes = min(num_bytes,
5716 					block_rsv->size - block_rsv->reserved);
5717 			block_rsv->reserved += num_bytes;
5718 			sinfo->bytes_may_use += num_bytes;
5719 			trace_btrfs_space_reservation(fs_info, "space_info",
5720 						      sinfo->flags, num_bytes,
5721 						      1);
5722 		}
5723 	} else if (block_rsv->reserved > block_rsv->size) {
5724 		num_bytes = block_rsv->reserved - block_rsv->size;
5725 		sinfo->bytes_may_use -= num_bytes;
5726 		trace_btrfs_space_reservation(fs_info, "space_info",
5727 				      sinfo->flags, num_bytes, 0);
5728 		block_rsv->reserved = block_rsv->size;
5729 	}
5730 
5731 	if (block_rsv->reserved == block_rsv->size)
5732 		block_rsv->full = 1;
5733 	else
5734 		block_rsv->full = 0;
5735 
5736 	spin_unlock(&block_rsv->lock);
5737 	spin_unlock(&sinfo->lock);
5738 }
5739 
init_global_block_rsv(struct btrfs_fs_info * fs_info)5740 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
5741 {
5742 	struct btrfs_space_info *space_info;
5743 
5744 	space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
5745 	fs_info->chunk_block_rsv.space_info = space_info;
5746 
5747 	space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
5748 	fs_info->global_block_rsv.space_info = space_info;
5749 	fs_info->trans_block_rsv.space_info = space_info;
5750 	fs_info->empty_block_rsv.space_info = space_info;
5751 	fs_info->delayed_block_rsv.space_info = space_info;
5752 
5753 	fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
5754 	fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
5755 	fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
5756 	fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
5757 	if (fs_info->quota_root)
5758 		fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
5759 	fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
5760 
5761 	update_global_block_rsv(fs_info);
5762 }
5763 
release_global_block_rsv(struct btrfs_fs_info * fs_info)5764 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
5765 {
5766 	block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
5767 				(u64)-1, NULL);
5768 	WARN_ON(fs_info->trans_block_rsv.size > 0);
5769 	WARN_ON(fs_info->trans_block_rsv.reserved > 0);
5770 	WARN_ON(fs_info->chunk_block_rsv.size > 0);
5771 	WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
5772 	WARN_ON(fs_info->delayed_block_rsv.size > 0);
5773 	WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
5774 }
5775 
5776 
5777 /*
5778  * To be called after all the new block groups attached to the transaction
5779  * handle have been created (btrfs_create_pending_block_groups()).
5780  */
btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle * trans)5781 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
5782 {
5783 	struct btrfs_fs_info *fs_info = trans->fs_info;
5784 
5785 	if (!trans->chunk_bytes_reserved)
5786 		return;
5787 
5788 	WARN_ON_ONCE(!list_empty(&trans->new_bgs));
5789 
5790 	block_rsv_release_bytes(fs_info, &fs_info->chunk_block_rsv, NULL,
5791 				trans->chunk_bytes_reserved, NULL);
5792 	trans->chunk_bytes_reserved = 0;
5793 }
5794 
5795 /*
5796  * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
5797  * root: the root of the parent directory
5798  * rsv: block reservation
5799  * items: the number of items that we need do reservation
5800  * use_global_rsv: allow fallback to the global block reservation
5801  *
5802  * This function is used to reserve the space for snapshot/subvolume
5803  * creation and deletion. Those operations are different with the
5804  * common file/directory operations, they change two fs/file trees
5805  * and root tree, the number of items that the qgroup reserves is
5806  * different with the free space reservation. So we can not use
5807  * the space reservation mechanism in start_transaction().
5808  */
btrfs_subvolume_reserve_metadata(struct btrfs_root * root,struct btrfs_block_rsv * rsv,int items,bool use_global_rsv)5809 int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
5810 				     struct btrfs_block_rsv *rsv, int items,
5811 				     bool use_global_rsv)
5812 {
5813 	u64 qgroup_num_bytes = 0;
5814 	u64 num_bytes;
5815 	int ret;
5816 	struct btrfs_fs_info *fs_info = root->fs_info;
5817 	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5818 
5819 	if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
5820 		/* One for parent inode, two for dir entries */
5821 		qgroup_num_bytes = 3 * fs_info->nodesize;
5822 		ret = btrfs_qgroup_reserve_meta_prealloc(root,
5823 				qgroup_num_bytes, true);
5824 		if (ret)
5825 			return ret;
5826 	}
5827 
5828 	num_bytes = btrfs_calc_trans_metadata_size(fs_info, items);
5829 	rsv->space_info = __find_space_info(fs_info,
5830 					    BTRFS_BLOCK_GROUP_METADATA);
5831 	ret = btrfs_block_rsv_add(root, rsv, num_bytes,
5832 				  BTRFS_RESERVE_FLUSH_ALL);
5833 
5834 	if (ret == -ENOSPC && use_global_rsv)
5835 		ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes, 1);
5836 
5837 	if (ret && qgroup_num_bytes)
5838 		btrfs_qgroup_free_meta_prealloc(root, qgroup_num_bytes);
5839 
5840 	return ret;
5841 }
5842 
btrfs_subvolume_release_metadata(struct btrfs_fs_info * fs_info,struct btrfs_block_rsv * rsv)5843 void btrfs_subvolume_release_metadata(struct btrfs_fs_info *fs_info,
5844 				      struct btrfs_block_rsv *rsv)
5845 {
5846 	btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
5847 }
5848 
btrfs_calculate_inode_block_rsv_size(struct btrfs_fs_info * fs_info,struct btrfs_inode * inode)5849 static void btrfs_calculate_inode_block_rsv_size(struct btrfs_fs_info *fs_info,
5850 						 struct btrfs_inode *inode)
5851 {
5852 	struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
5853 	u64 reserve_size = 0;
5854 	u64 qgroup_rsv_size = 0;
5855 	u64 csum_leaves;
5856 	unsigned outstanding_extents;
5857 
5858 	lockdep_assert_held(&inode->lock);
5859 	outstanding_extents = inode->outstanding_extents;
5860 	if (outstanding_extents)
5861 		reserve_size = btrfs_calc_trans_metadata_size(fs_info,
5862 						outstanding_extents + 1);
5863 	csum_leaves = btrfs_csum_bytes_to_leaves(fs_info,
5864 						 inode->csum_bytes);
5865 	reserve_size += btrfs_calc_trans_metadata_size(fs_info,
5866 						       csum_leaves);
5867 	/*
5868 	 * For qgroup rsv, the calculation is very simple:
5869 	 * account one nodesize for each outstanding extent
5870 	 *
5871 	 * This is overestimating in most cases.
5872 	 */
5873 	qgroup_rsv_size = (u64)outstanding_extents * fs_info->nodesize;
5874 
5875 	spin_lock(&block_rsv->lock);
5876 	block_rsv->size = reserve_size;
5877 	block_rsv->qgroup_rsv_size = qgroup_rsv_size;
5878 	spin_unlock(&block_rsv->lock);
5879 }
5880 
btrfs_delalloc_reserve_metadata(struct btrfs_inode * inode,u64 num_bytes)5881 int btrfs_delalloc_reserve_metadata(struct btrfs_inode *inode, u64 num_bytes)
5882 {
5883 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
5884 	unsigned nr_extents;
5885 	enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
5886 	int ret = 0;
5887 	bool delalloc_lock = true;
5888 
5889 	/* If we are a free space inode we need to not flush since we will be in
5890 	 * the middle of a transaction commit.  We also don't need the delalloc
5891 	 * mutex since we won't race with anybody.  We need this mostly to make
5892 	 * lockdep shut its filthy mouth.
5893 	 *
5894 	 * If we have a transaction open (can happen if we call truncate_block
5895 	 * from truncate), then we need FLUSH_LIMIT so we don't deadlock.
5896 	 */
5897 	if (btrfs_is_free_space_inode(inode)) {
5898 		flush = BTRFS_RESERVE_NO_FLUSH;
5899 		delalloc_lock = false;
5900 	} else {
5901 		if (current->journal_info)
5902 			flush = BTRFS_RESERVE_FLUSH_LIMIT;
5903 
5904 		if (btrfs_transaction_in_commit(fs_info))
5905 			schedule_timeout(1);
5906 	}
5907 
5908 	if (delalloc_lock)
5909 		mutex_lock(&inode->delalloc_mutex);
5910 
5911 	num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
5912 
5913 	/* Add our new extents and calculate the new rsv size. */
5914 	spin_lock(&inode->lock);
5915 	nr_extents = count_max_extents(num_bytes);
5916 	btrfs_mod_outstanding_extents(inode, nr_extents);
5917 	inode->csum_bytes += num_bytes;
5918 	btrfs_calculate_inode_block_rsv_size(fs_info, inode);
5919 	spin_unlock(&inode->lock);
5920 
5921 	ret = btrfs_inode_rsv_refill(inode, flush);
5922 	if (unlikely(ret))
5923 		goto out_fail;
5924 
5925 	if (delalloc_lock)
5926 		mutex_unlock(&inode->delalloc_mutex);
5927 	return 0;
5928 
5929 out_fail:
5930 	spin_lock(&inode->lock);
5931 	nr_extents = count_max_extents(num_bytes);
5932 	btrfs_mod_outstanding_extents(inode, -nr_extents);
5933 	inode->csum_bytes -= num_bytes;
5934 	btrfs_calculate_inode_block_rsv_size(fs_info, inode);
5935 	spin_unlock(&inode->lock);
5936 
5937 	btrfs_inode_rsv_release(inode, true);
5938 	if (delalloc_lock)
5939 		mutex_unlock(&inode->delalloc_mutex);
5940 	return ret;
5941 }
5942 
5943 /**
5944  * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
5945  * @inode: the inode to release the reservation for.
5946  * @num_bytes: the number of bytes we are releasing.
5947  * @qgroup_free: free qgroup reservation or convert it to per-trans reservation
5948  *
5949  * This will release the metadata reservation for an inode.  This can be called
5950  * once we complete IO for a given set of bytes to release their metadata
5951  * reservations, or on error for the same reason.
5952  */
btrfs_delalloc_release_metadata(struct btrfs_inode * inode,u64 num_bytes,bool qgroup_free)5953 void btrfs_delalloc_release_metadata(struct btrfs_inode *inode, u64 num_bytes,
5954 				     bool qgroup_free)
5955 {
5956 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
5957 
5958 	num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
5959 	spin_lock(&inode->lock);
5960 	inode->csum_bytes -= num_bytes;
5961 	btrfs_calculate_inode_block_rsv_size(fs_info, inode);
5962 	spin_unlock(&inode->lock);
5963 
5964 	if (btrfs_is_testing(fs_info))
5965 		return;
5966 
5967 	btrfs_inode_rsv_release(inode, qgroup_free);
5968 }
5969 
5970 /**
5971  * btrfs_delalloc_release_extents - release our outstanding_extents
5972  * @inode: the inode to balance the reservation for.
5973  * @num_bytes: the number of bytes we originally reserved with
5974  * @qgroup_free: do we need to free qgroup meta reservation or convert them.
5975  *
5976  * When we reserve space we increase outstanding_extents for the extents we may
5977  * add.  Once we've set the range as delalloc or created our ordered extents we
5978  * have outstanding_extents to track the real usage, so we use this to free our
5979  * temporarily tracked outstanding_extents.  This _must_ be used in conjunction
5980  * with btrfs_delalloc_reserve_metadata.
5981  */
btrfs_delalloc_release_extents(struct btrfs_inode * inode,u64 num_bytes)5982 void btrfs_delalloc_release_extents(struct btrfs_inode *inode, u64 num_bytes)
5983 {
5984 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
5985 	unsigned num_extents;
5986 
5987 	spin_lock(&inode->lock);
5988 	num_extents = count_max_extents(num_bytes);
5989 	btrfs_mod_outstanding_extents(inode, -num_extents);
5990 	btrfs_calculate_inode_block_rsv_size(fs_info, inode);
5991 	spin_unlock(&inode->lock);
5992 
5993 	if (btrfs_is_testing(fs_info))
5994 		return;
5995 
5996 	btrfs_inode_rsv_release(inode, true);
5997 }
5998 
5999 /**
6000  * btrfs_delalloc_reserve_space - reserve data and metadata space for
6001  * delalloc
6002  * @inode: inode we're writing to
6003  * @start: start range we are writing to
6004  * @len: how long the range we are writing to
6005  * @reserved: mandatory parameter, record actually reserved qgroup ranges of
6006  * 	      current reservation.
6007  *
6008  * This will do the following things
6009  *
6010  * o reserve space in data space info for num bytes
6011  *   and reserve precious corresponding qgroup space
6012  *   (Done in check_data_free_space)
6013  *
6014  * o reserve space for metadata space, based on the number of outstanding
6015  *   extents and how much csums will be needed
6016  *   also reserve metadata space in a per root over-reserve method.
6017  * o add to the inodes->delalloc_bytes
6018  * o add it to the fs_info's delalloc inodes list.
6019  *   (Above 3 all done in delalloc_reserve_metadata)
6020  *
6021  * Return 0 for success
6022  * Return <0 for error(-ENOSPC or -EQUOT)
6023  */
btrfs_delalloc_reserve_space(struct inode * inode,struct extent_changeset ** reserved,u64 start,u64 len)6024 int btrfs_delalloc_reserve_space(struct inode *inode,
6025 			struct extent_changeset **reserved, u64 start, u64 len)
6026 {
6027 	int ret;
6028 
6029 	ret = btrfs_check_data_free_space(inode, reserved, start, len);
6030 	if (ret < 0)
6031 		return ret;
6032 	ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len);
6033 	if (ret < 0)
6034 		btrfs_free_reserved_data_space(inode, *reserved, start, len);
6035 	return ret;
6036 }
6037 
6038 /**
6039  * btrfs_delalloc_release_space - release data and metadata space for delalloc
6040  * @inode: inode we're releasing space for
6041  * @start: start position of the space already reserved
6042  * @len: the len of the space already reserved
6043  * @release_bytes: the len of the space we consumed or didn't use
6044  *
6045  * This function will release the metadata space that was not used and will
6046  * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
6047  * list if there are no delalloc bytes left.
6048  * Also it will handle the qgroup reserved space.
6049  */
btrfs_delalloc_release_space(struct inode * inode,struct extent_changeset * reserved,u64 start,u64 len,bool qgroup_free)6050 void btrfs_delalloc_release_space(struct inode *inode,
6051 				  struct extent_changeset *reserved,
6052 				  u64 start, u64 len, bool qgroup_free)
6053 {
6054 	btrfs_delalloc_release_metadata(BTRFS_I(inode), len, qgroup_free);
6055 	btrfs_free_reserved_data_space(inode, reserved, start, len);
6056 }
6057 
update_block_group(struct btrfs_trans_handle * trans,struct btrfs_fs_info * info,u64 bytenr,u64 num_bytes,int alloc)6058 static int update_block_group(struct btrfs_trans_handle *trans,
6059 			      struct btrfs_fs_info *info, u64 bytenr,
6060 			      u64 num_bytes, int alloc)
6061 {
6062 	struct btrfs_block_group_cache *cache = NULL;
6063 	u64 total = num_bytes;
6064 	u64 old_val;
6065 	u64 byte_in_group;
6066 	int factor;
6067 
6068 	/* block accounting for super block */
6069 	spin_lock(&info->delalloc_root_lock);
6070 	old_val = btrfs_super_bytes_used(info->super_copy);
6071 	if (alloc)
6072 		old_val += num_bytes;
6073 	else
6074 		old_val -= num_bytes;
6075 	btrfs_set_super_bytes_used(info->super_copy, old_val);
6076 	spin_unlock(&info->delalloc_root_lock);
6077 
6078 	while (total) {
6079 		cache = btrfs_lookup_block_group(info, bytenr);
6080 		if (!cache)
6081 			return -ENOENT;
6082 		factor = btrfs_bg_type_to_factor(cache->flags);
6083 
6084 		/*
6085 		 * If this block group has free space cache written out, we
6086 		 * need to make sure to load it if we are removing space.  This
6087 		 * is because we need the unpinning stage to actually add the
6088 		 * space back to the block group, otherwise we will leak space.
6089 		 */
6090 		if (!alloc && cache->cached == BTRFS_CACHE_NO)
6091 			cache_block_group(cache, 1);
6092 
6093 		byte_in_group = bytenr - cache->key.objectid;
6094 		WARN_ON(byte_in_group > cache->key.offset);
6095 
6096 		spin_lock(&cache->space_info->lock);
6097 		spin_lock(&cache->lock);
6098 
6099 		if (btrfs_test_opt(info, SPACE_CACHE) &&
6100 		    cache->disk_cache_state < BTRFS_DC_CLEAR)
6101 			cache->disk_cache_state = BTRFS_DC_CLEAR;
6102 
6103 		old_val = btrfs_block_group_used(&cache->item);
6104 		num_bytes = min(total, cache->key.offset - byte_in_group);
6105 		if (alloc) {
6106 			old_val += num_bytes;
6107 			btrfs_set_block_group_used(&cache->item, old_val);
6108 			cache->reserved -= num_bytes;
6109 			cache->space_info->bytes_reserved -= num_bytes;
6110 			cache->space_info->bytes_used += num_bytes;
6111 			cache->space_info->disk_used += num_bytes * factor;
6112 			spin_unlock(&cache->lock);
6113 			spin_unlock(&cache->space_info->lock);
6114 		} else {
6115 			old_val -= num_bytes;
6116 			btrfs_set_block_group_used(&cache->item, old_val);
6117 			cache->pinned += num_bytes;
6118 			cache->space_info->bytes_pinned += num_bytes;
6119 			cache->space_info->bytes_used -= num_bytes;
6120 			cache->space_info->disk_used -= num_bytes * factor;
6121 			spin_unlock(&cache->lock);
6122 			spin_unlock(&cache->space_info->lock);
6123 
6124 			trace_btrfs_space_reservation(info, "pinned",
6125 						      cache->space_info->flags,
6126 						      num_bytes, 1);
6127 			percpu_counter_add_batch(&cache->space_info->total_bytes_pinned,
6128 					   num_bytes,
6129 					   BTRFS_TOTAL_BYTES_PINNED_BATCH);
6130 			set_extent_dirty(info->pinned_extents,
6131 					 bytenr, bytenr + num_bytes - 1,
6132 					 GFP_NOFS | __GFP_NOFAIL);
6133 		}
6134 
6135 		spin_lock(&trans->transaction->dirty_bgs_lock);
6136 		if (list_empty(&cache->dirty_list)) {
6137 			list_add_tail(&cache->dirty_list,
6138 				      &trans->transaction->dirty_bgs);
6139 			trans->transaction->num_dirty_bgs++;
6140 			btrfs_get_block_group(cache);
6141 		}
6142 		spin_unlock(&trans->transaction->dirty_bgs_lock);
6143 
6144 		/*
6145 		 * No longer have used bytes in this block group, queue it for
6146 		 * deletion. We do this after adding the block group to the
6147 		 * dirty list to avoid races between cleaner kthread and space
6148 		 * cache writeout.
6149 		 */
6150 		if (!alloc && old_val == 0)
6151 			btrfs_mark_bg_unused(cache);
6152 
6153 		btrfs_put_block_group(cache);
6154 		total -= num_bytes;
6155 		bytenr += num_bytes;
6156 	}
6157 	return 0;
6158 }
6159 
first_logical_byte(struct btrfs_fs_info * fs_info,u64 search_start)6160 static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
6161 {
6162 	struct btrfs_block_group_cache *cache;
6163 	u64 bytenr;
6164 
6165 	spin_lock(&fs_info->block_group_cache_lock);
6166 	bytenr = fs_info->first_logical_byte;
6167 	spin_unlock(&fs_info->block_group_cache_lock);
6168 
6169 	if (bytenr < (u64)-1)
6170 		return bytenr;
6171 
6172 	cache = btrfs_lookup_first_block_group(fs_info, search_start);
6173 	if (!cache)
6174 		return 0;
6175 
6176 	bytenr = cache->key.objectid;
6177 	btrfs_put_block_group(cache);
6178 
6179 	return bytenr;
6180 }
6181 
pin_down_extent(struct btrfs_fs_info * fs_info,struct btrfs_block_group_cache * cache,u64 bytenr,u64 num_bytes,int reserved)6182 static int pin_down_extent(struct btrfs_fs_info *fs_info,
6183 			   struct btrfs_block_group_cache *cache,
6184 			   u64 bytenr, u64 num_bytes, int reserved)
6185 {
6186 	spin_lock(&cache->space_info->lock);
6187 	spin_lock(&cache->lock);
6188 	cache->pinned += num_bytes;
6189 	cache->space_info->bytes_pinned += num_bytes;
6190 	if (reserved) {
6191 		cache->reserved -= num_bytes;
6192 		cache->space_info->bytes_reserved -= num_bytes;
6193 	}
6194 	spin_unlock(&cache->lock);
6195 	spin_unlock(&cache->space_info->lock);
6196 
6197 	trace_btrfs_space_reservation(fs_info, "pinned",
6198 				      cache->space_info->flags, num_bytes, 1);
6199 	percpu_counter_add_batch(&cache->space_info->total_bytes_pinned,
6200 		    num_bytes, BTRFS_TOTAL_BYTES_PINNED_BATCH);
6201 	set_extent_dirty(fs_info->pinned_extents, bytenr,
6202 			 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
6203 	return 0;
6204 }
6205 
6206 /*
6207  * this function must be called within transaction
6208  */
btrfs_pin_extent(struct btrfs_fs_info * fs_info,u64 bytenr,u64 num_bytes,int reserved)6209 int btrfs_pin_extent(struct btrfs_fs_info *fs_info,
6210 		     u64 bytenr, u64 num_bytes, int reserved)
6211 {
6212 	struct btrfs_block_group_cache *cache;
6213 
6214 	cache = btrfs_lookup_block_group(fs_info, bytenr);
6215 	BUG_ON(!cache); /* Logic error */
6216 
6217 	pin_down_extent(fs_info, cache, bytenr, num_bytes, reserved);
6218 
6219 	btrfs_put_block_group(cache);
6220 	return 0;
6221 }
6222 
6223 /*
6224  * this function must be called within transaction
6225  */
btrfs_pin_extent_for_log_replay(struct btrfs_fs_info * fs_info,u64 bytenr,u64 num_bytes)6226 int btrfs_pin_extent_for_log_replay(struct btrfs_fs_info *fs_info,
6227 				    u64 bytenr, u64 num_bytes)
6228 {
6229 	struct btrfs_block_group_cache *cache;
6230 	int ret;
6231 
6232 	cache = btrfs_lookup_block_group(fs_info, bytenr);
6233 	if (!cache)
6234 		return -EINVAL;
6235 
6236 	/*
6237 	 * pull in the free space cache (if any) so that our pin
6238 	 * removes the free space from the cache.  We have load_only set
6239 	 * to one because the slow code to read in the free extents does check
6240 	 * the pinned extents.
6241 	 */
6242 	cache_block_group(cache, 1);
6243 
6244 	pin_down_extent(fs_info, cache, bytenr, num_bytes, 0);
6245 
6246 	/* remove us from the free space cache (if we're there at all) */
6247 	ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
6248 	btrfs_put_block_group(cache);
6249 	return ret;
6250 }
6251 
__exclude_logged_extent(struct btrfs_fs_info * fs_info,u64 start,u64 num_bytes)6252 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
6253 				   u64 start, u64 num_bytes)
6254 {
6255 	int ret;
6256 	struct btrfs_block_group_cache *block_group;
6257 	struct btrfs_caching_control *caching_ctl;
6258 
6259 	block_group = btrfs_lookup_block_group(fs_info, start);
6260 	if (!block_group)
6261 		return -EINVAL;
6262 
6263 	cache_block_group(block_group, 0);
6264 	caching_ctl = get_caching_control(block_group);
6265 
6266 	if (!caching_ctl) {
6267 		/* Logic error */
6268 		BUG_ON(!block_group_cache_done(block_group));
6269 		ret = btrfs_remove_free_space(block_group, start, num_bytes);
6270 	} else {
6271 		mutex_lock(&caching_ctl->mutex);
6272 
6273 		if (start >= caching_ctl->progress) {
6274 			ret = add_excluded_extent(fs_info, start, num_bytes);
6275 		} else if (start + num_bytes <= caching_ctl->progress) {
6276 			ret = btrfs_remove_free_space(block_group,
6277 						      start, num_bytes);
6278 		} else {
6279 			num_bytes = caching_ctl->progress - start;
6280 			ret = btrfs_remove_free_space(block_group,
6281 						      start, num_bytes);
6282 			if (ret)
6283 				goto out_lock;
6284 
6285 			num_bytes = (start + num_bytes) -
6286 				caching_ctl->progress;
6287 			start = caching_ctl->progress;
6288 			ret = add_excluded_extent(fs_info, start, num_bytes);
6289 		}
6290 out_lock:
6291 		mutex_unlock(&caching_ctl->mutex);
6292 		put_caching_control(caching_ctl);
6293 	}
6294 	btrfs_put_block_group(block_group);
6295 	return ret;
6296 }
6297 
btrfs_exclude_logged_extents(struct btrfs_fs_info * fs_info,struct extent_buffer * eb)6298 int btrfs_exclude_logged_extents(struct btrfs_fs_info *fs_info,
6299 				 struct extent_buffer *eb)
6300 {
6301 	struct btrfs_file_extent_item *item;
6302 	struct btrfs_key key;
6303 	int found_type;
6304 	int i;
6305 	int ret = 0;
6306 
6307 	if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
6308 		return 0;
6309 
6310 	for (i = 0; i < btrfs_header_nritems(eb); i++) {
6311 		btrfs_item_key_to_cpu(eb, &key, i);
6312 		if (key.type != BTRFS_EXTENT_DATA_KEY)
6313 			continue;
6314 		item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
6315 		found_type = btrfs_file_extent_type(eb, item);
6316 		if (found_type == BTRFS_FILE_EXTENT_INLINE)
6317 			continue;
6318 		if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
6319 			continue;
6320 		key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
6321 		key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
6322 		ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
6323 		if (ret)
6324 			break;
6325 	}
6326 
6327 	return ret;
6328 }
6329 
6330 static void
btrfs_inc_block_group_reservations(struct btrfs_block_group_cache * bg)6331 btrfs_inc_block_group_reservations(struct btrfs_block_group_cache *bg)
6332 {
6333 	atomic_inc(&bg->reservations);
6334 }
6335 
btrfs_dec_block_group_reservations(struct btrfs_fs_info * fs_info,const u64 start)6336 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
6337 					const u64 start)
6338 {
6339 	struct btrfs_block_group_cache *bg;
6340 
6341 	bg = btrfs_lookup_block_group(fs_info, start);
6342 	ASSERT(bg);
6343 	if (atomic_dec_and_test(&bg->reservations))
6344 		wake_up_var(&bg->reservations);
6345 	btrfs_put_block_group(bg);
6346 }
6347 
btrfs_wait_block_group_reservations(struct btrfs_block_group_cache * bg)6348 void btrfs_wait_block_group_reservations(struct btrfs_block_group_cache *bg)
6349 {
6350 	struct btrfs_space_info *space_info = bg->space_info;
6351 
6352 	ASSERT(bg->ro);
6353 
6354 	if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
6355 		return;
6356 
6357 	/*
6358 	 * Our block group is read only but before we set it to read only,
6359 	 * some task might have had allocated an extent from it already, but it
6360 	 * has not yet created a respective ordered extent (and added it to a
6361 	 * root's list of ordered extents).
6362 	 * Therefore wait for any task currently allocating extents, since the
6363 	 * block group's reservations counter is incremented while a read lock
6364 	 * on the groups' semaphore is held and decremented after releasing
6365 	 * the read access on that semaphore and creating the ordered extent.
6366 	 */
6367 	down_write(&space_info->groups_sem);
6368 	up_write(&space_info->groups_sem);
6369 
6370 	wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
6371 }
6372 
6373 /**
6374  * btrfs_add_reserved_bytes - update the block_group and space info counters
6375  * @cache:	The cache we are manipulating
6376  * @ram_bytes:  The number of bytes of file content, and will be same to
6377  *              @num_bytes except for the compress path.
6378  * @num_bytes:	The number of bytes in question
6379  * @delalloc:   The blocks are allocated for the delalloc write
6380  *
6381  * This is called by the allocator when it reserves space. If this is a
6382  * reservation and the block group has become read only we cannot make the
6383  * reservation and return -EAGAIN, otherwise this function always succeeds.
6384  */
btrfs_add_reserved_bytes(struct btrfs_block_group_cache * cache,u64 ram_bytes,u64 num_bytes,int delalloc)6385 static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
6386 				    u64 ram_bytes, u64 num_bytes, int delalloc)
6387 {
6388 	struct btrfs_space_info *space_info = cache->space_info;
6389 	int ret = 0;
6390 
6391 	spin_lock(&space_info->lock);
6392 	spin_lock(&cache->lock);
6393 	if (cache->ro) {
6394 		ret = -EAGAIN;
6395 	} else {
6396 		cache->reserved += num_bytes;
6397 		space_info->bytes_reserved += num_bytes;
6398 
6399 		trace_btrfs_space_reservation(cache->fs_info,
6400 				"space_info", space_info->flags,
6401 				ram_bytes, 0);
6402 		space_info->bytes_may_use -= ram_bytes;
6403 		if (delalloc)
6404 			cache->delalloc_bytes += num_bytes;
6405 	}
6406 	spin_unlock(&cache->lock);
6407 	spin_unlock(&space_info->lock);
6408 	return ret;
6409 }
6410 
6411 /**
6412  * btrfs_free_reserved_bytes - update the block_group and space info counters
6413  * @cache:      The cache we are manipulating
6414  * @num_bytes:  The number of bytes in question
6415  * @delalloc:   The blocks are allocated for the delalloc write
6416  *
6417  * This is called by somebody who is freeing space that was never actually used
6418  * on disk.  For example if you reserve some space for a new leaf in transaction
6419  * A and before transaction A commits you free that leaf, you call this with
6420  * reserve set to 0 in order to clear the reservation.
6421  */
6422 
btrfs_free_reserved_bytes(struct btrfs_block_group_cache * cache,u64 num_bytes,int delalloc)6423 static int btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
6424 				     u64 num_bytes, int delalloc)
6425 {
6426 	struct btrfs_space_info *space_info = cache->space_info;
6427 	int ret = 0;
6428 
6429 	spin_lock(&space_info->lock);
6430 	spin_lock(&cache->lock);
6431 	if (cache->ro)
6432 		space_info->bytes_readonly += num_bytes;
6433 	cache->reserved -= num_bytes;
6434 	space_info->bytes_reserved -= num_bytes;
6435 	space_info->max_extent_size = 0;
6436 
6437 	if (delalloc)
6438 		cache->delalloc_bytes -= num_bytes;
6439 	spin_unlock(&cache->lock);
6440 	spin_unlock(&space_info->lock);
6441 	return ret;
6442 }
btrfs_prepare_extent_commit(struct btrfs_fs_info * fs_info)6443 void btrfs_prepare_extent_commit(struct btrfs_fs_info *fs_info)
6444 {
6445 	struct btrfs_caching_control *next;
6446 	struct btrfs_caching_control *caching_ctl;
6447 	struct btrfs_block_group_cache *cache;
6448 
6449 	down_write(&fs_info->commit_root_sem);
6450 
6451 	list_for_each_entry_safe(caching_ctl, next,
6452 				 &fs_info->caching_block_groups, list) {
6453 		cache = caching_ctl->block_group;
6454 		if (block_group_cache_done(cache)) {
6455 			cache->last_byte_to_unpin = (u64)-1;
6456 			list_del_init(&caching_ctl->list);
6457 			put_caching_control(caching_ctl);
6458 		} else {
6459 			cache->last_byte_to_unpin = caching_ctl->progress;
6460 		}
6461 	}
6462 
6463 	if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6464 		fs_info->pinned_extents = &fs_info->freed_extents[1];
6465 	else
6466 		fs_info->pinned_extents = &fs_info->freed_extents[0];
6467 
6468 	up_write(&fs_info->commit_root_sem);
6469 
6470 	update_global_block_rsv(fs_info);
6471 }
6472 
6473 /*
6474  * Returns the free cluster for the given space info and sets empty_cluster to
6475  * what it should be based on the mount options.
6476  */
6477 static struct btrfs_free_cluster *
fetch_cluster_info(struct btrfs_fs_info * fs_info,struct btrfs_space_info * space_info,u64 * empty_cluster)6478 fetch_cluster_info(struct btrfs_fs_info *fs_info,
6479 		   struct btrfs_space_info *space_info, u64 *empty_cluster)
6480 {
6481 	struct btrfs_free_cluster *ret = NULL;
6482 
6483 	*empty_cluster = 0;
6484 	if (btrfs_mixed_space_info(space_info))
6485 		return ret;
6486 
6487 	if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
6488 		ret = &fs_info->meta_alloc_cluster;
6489 		if (btrfs_test_opt(fs_info, SSD))
6490 			*empty_cluster = SZ_2M;
6491 		else
6492 			*empty_cluster = SZ_64K;
6493 	} else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
6494 		   btrfs_test_opt(fs_info, SSD_SPREAD)) {
6495 		*empty_cluster = SZ_2M;
6496 		ret = &fs_info->data_alloc_cluster;
6497 	}
6498 
6499 	return ret;
6500 }
6501 
unpin_extent_range(struct btrfs_fs_info * fs_info,u64 start,u64 end,const bool return_free_space)6502 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
6503 			      u64 start, u64 end,
6504 			      const bool return_free_space)
6505 {
6506 	struct btrfs_block_group_cache *cache = NULL;
6507 	struct btrfs_space_info *space_info;
6508 	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
6509 	struct btrfs_free_cluster *cluster = NULL;
6510 	u64 len;
6511 	u64 total_unpinned = 0;
6512 	u64 empty_cluster = 0;
6513 	bool readonly;
6514 
6515 	while (start <= end) {
6516 		readonly = false;
6517 		if (!cache ||
6518 		    start >= cache->key.objectid + cache->key.offset) {
6519 			if (cache)
6520 				btrfs_put_block_group(cache);
6521 			total_unpinned = 0;
6522 			cache = btrfs_lookup_block_group(fs_info, start);
6523 			BUG_ON(!cache); /* Logic error */
6524 
6525 			cluster = fetch_cluster_info(fs_info,
6526 						     cache->space_info,
6527 						     &empty_cluster);
6528 			empty_cluster <<= 1;
6529 		}
6530 
6531 		len = cache->key.objectid + cache->key.offset - start;
6532 		len = min(len, end + 1 - start);
6533 
6534 		if (start < cache->last_byte_to_unpin) {
6535 			len = min(len, cache->last_byte_to_unpin - start);
6536 			if (return_free_space)
6537 				btrfs_add_free_space(cache, start, len);
6538 		}
6539 
6540 		start += len;
6541 		total_unpinned += len;
6542 		space_info = cache->space_info;
6543 
6544 		/*
6545 		 * If this space cluster has been marked as fragmented and we've
6546 		 * unpinned enough in this block group to potentially allow a
6547 		 * cluster to be created inside of it go ahead and clear the
6548 		 * fragmented check.
6549 		 */
6550 		if (cluster && cluster->fragmented &&
6551 		    total_unpinned > empty_cluster) {
6552 			spin_lock(&cluster->lock);
6553 			cluster->fragmented = 0;
6554 			spin_unlock(&cluster->lock);
6555 		}
6556 
6557 		spin_lock(&space_info->lock);
6558 		spin_lock(&cache->lock);
6559 		cache->pinned -= len;
6560 		space_info->bytes_pinned -= len;
6561 
6562 		trace_btrfs_space_reservation(fs_info, "pinned",
6563 					      space_info->flags, len, 0);
6564 		space_info->max_extent_size = 0;
6565 		percpu_counter_add_batch(&space_info->total_bytes_pinned,
6566 			    -len, BTRFS_TOTAL_BYTES_PINNED_BATCH);
6567 		if (cache->ro) {
6568 			space_info->bytes_readonly += len;
6569 			readonly = true;
6570 		}
6571 		spin_unlock(&cache->lock);
6572 		if (!readonly && return_free_space &&
6573 		    global_rsv->space_info == space_info) {
6574 			u64 to_add = len;
6575 
6576 			spin_lock(&global_rsv->lock);
6577 			if (!global_rsv->full) {
6578 				to_add = min(len, global_rsv->size -
6579 					     global_rsv->reserved);
6580 				global_rsv->reserved += to_add;
6581 				space_info->bytes_may_use += to_add;
6582 				if (global_rsv->reserved >= global_rsv->size)
6583 					global_rsv->full = 1;
6584 				trace_btrfs_space_reservation(fs_info,
6585 							      "space_info",
6586 							      space_info->flags,
6587 							      to_add, 1);
6588 				len -= to_add;
6589 			}
6590 			spin_unlock(&global_rsv->lock);
6591 			/* Add to any tickets we may have */
6592 			if (len)
6593 				space_info_add_new_bytes(fs_info, space_info,
6594 							 len);
6595 		}
6596 		spin_unlock(&space_info->lock);
6597 	}
6598 
6599 	if (cache)
6600 		btrfs_put_block_group(cache);
6601 	return 0;
6602 }
6603 
btrfs_finish_extent_commit(struct btrfs_trans_handle * trans)6604 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
6605 {
6606 	struct btrfs_fs_info *fs_info = trans->fs_info;
6607 	struct btrfs_block_group_cache *block_group, *tmp;
6608 	struct list_head *deleted_bgs;
6609 	struct extent_io_tree *unpin;
6610 	u64 start;
6611 	u64 end;
6612 	int ret;
6613 
6614 	if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6615 		unpin = &fs_info->freed_extents[1];
6616 	else
6617 		unpin = &fs_info->freed_extents[0];
6618 
6619 	while (!trans->aborted) {
6620 		struct extent_state *cached_state = NULL;
6621 
6622 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
6623 		ret = find_first_extent_bit(unpin, 0, &start, &end,
6624 					    EXTENT_DIRTY, &cached_state);
6625 		if (ret) {
6626 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6627 			break;
6628 		}
6629 
6630 		if (btrfs_test_opt(fs_info, DISCARD))
6631 			ret = btrfs_discard_extent(fs_info, start,
6632 						   end + 1 - start, NULL);
6633 
6634 		clear_extent_dirty(unpin, start, end, &cached_state);
6635 		unpin_extent_range(fs_info, start, end, true);
6636 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6637 		free_extent_state(cached_state);
6638 		cond_resched();
6639 	}
6640 
6641 	/*
6642 	 * Transaction is finished.  We don't need the lock anymore.  We
6643 	 * do need to clean up the block groups in case of a transaction
6644 	 * abort.
6645 	 */
6646 	deleted_bgs = &trans->transaction->deleted_bgs;
6647 	list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
6648 		u64 trimmed = 0;
6649 
6650 		ret = -EROFS;
6651 		if (!trans->aborted)
6652 			ret = btrfs_discard_extent(fs_info,
6653 						   block_group->key.objectid,
6654 						   block_group->key.offset,
6655 						   &trimmed);
6656 
6657 		list_del_init(&block_group->bg_list);
6658 		btrfs_put_block_group_trimming(block_group);
6659 		btrfs_put_block_group(block_group);
6660 
6661 		if (ret) {
6662 			const char *errstr = btrfs_decode_error(ret);
6663 			btrfs_warn(fs_info,
6664 			   "discard failed while removing blockgroup: errno=%d %s",
6665 				   ret, errstr);
6666 		}
6667 	}
6668 
6669 	return 0;
6670 }
6671 
__btrfs_free_extent(struct btrfs_trans_handle * trans,struct btrfs_delayed_ref_node * node,u64 parent,u64 root_objectid,u64 owner_objectid,u64 owner_offset,int refs_to_drop,struct btrfs_delayed_extent_op * extent_op)6672 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
6673 			       struct btrfs_delayed_ref_node *node, u64 parent,
6674 			       u64 root_objectid, u64 owner_objectid,
6675 			       u64 owner_offset, int refs_to_drop,
6676 			       struct btrfs_delayed_extent_op *extent_op)
6677 {
6678 	struct btrfs_fs_info *info = trans->fs_info;
6679 	struct btrfs_key key;
6680 	struct btrfs_path *path;
6681 	struct btrfs_root *extent_root = info->extent_root;
6682 	struct extent_buffer *leaf;
6683 	struct btrfs_extent_item *ei;
6684 	struct btrfs_extent_inline_ref *iref;
6685 	int ret;
6686 	int is_data;
6687 	int extent_slot = 0;
6688 	int found_extent = 0;
6689 	int num_to_del = 1;
6690 	u32 item_size;
6691 	u64 refs;
6692 	u64 bytenr = node->bytenr;
6693 	u64 num_bytes = node->num_bytes;
6694 	int last_ref = 0;
6695 	bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
6696 
6697 	path = btrfs_alloc_path();
6698 	if (!path)
6699 		return -ENOMEM;
6700 
6701 	path->reada = READA_FORWARD;
6702 	path->leave_spinning = 1;
6703 
6704 	is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
6705 	BUG_ON(!is_data && refs_to_drop != 1);
6706 
6707 	if (is_data)
6708 		skinny_metadata = false;
6709 
6710 	ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
6711 				    parent, root_objectid, owner_objectid,
6712 				    owner_offset);
6713 	if (ret == 0) {
6714 		extent_slot = path->slots[0];
6715 		while (extent_slot >= 0) {
6716 			btrfs_item_key_to_cpu(path->nodes[0], &key,
6717 					      extent_slot);
6718 			if (key.objectid != bytenr)
6719 				break;
6720 			if (key.type == BTRFS_EXTENT_ITEM_KEY &&
6721 			    key.offset == num_bytes) {
6722 				found_extent = 1;
6723 				break;
6724 			}
6725 			if (key.type == BTRFS_METADATA_ITEM_KEY &&
6726 			    key.offset == owner_objectid) {
6727 				found_extent = 1;
6728 				break;
6729 			}
6730 			if (path->slots[0] - extent_slot > 5)
6731 				break;
6732 			extent_slot--;
6733 		}
6734 
6735 		if (!found_extent) {
6736 			BUG_ON(iref);
6737 			ret = remove_extent_backref(trans, path, NULL,
6738 						    refs_to_drop,
6739 						    is_data, &last_ref);
6740 			if (ret) {
6741 				btrfs_abort_transaction(trans, ret);
6742 				goto out;
6743 			}
6744 			btrfs_release_path(path);
6745 			path->leave_spinning = 1;
6746 
6747 			key.objectid = bytenr;
6748 			key.type = BTRFS_EXTENT_ITEM_KEY;
6749 			key.offset = num_bytes;
6750 
6751 			if (!is_data && skinny_metadata) {
6752 				key.type = BTRFS_METADATA_ITEM_KEY;
6753 				key.offset = owner_objectid;
6754 			}
6755 
6756 			ret = btrfs_search_slot(trans, extent_root,
6757 						&key, path, -1, 1);
6758 			if (ret > 0 && skinny_metadata && path->slots[0]) {
6759 				/*
6760 				 * Couldn't find our skinny metadata item,
6761 				 * see if we have ye olde extent item.
6762 				 */
6763 				path->slots[0]--;
6764 				btrfs_item_key_to_cpu(path->nodes[0], &key,
6765 						      path->slots[0]);
6766 				if (key.objectid == bytenr &&
6767 				    key.type == BTRFS_EXTENT_ITEM_KEY &&
6768 				    key.offset == num_bytes)
6769 					ret = 0;
6770 			}
6771 
6772 			if (ret > 0 && skinny_metadata) {
6773 				skinny_metadata = false;
6774 				key.objectid = bytenr;
6775 				key.type = BTRFS_EXTENT_ITEM_KEY;
6776 				key.offset = num_bytes;
6777 				btrfs_release_path(path);
6778 				ret = btrfs_search_slot(trans, extent_root,
6779 							&key, path, -1, 1);
6780 			}
6781 
6782 			if (ret) {
6783 				btrfs_err(info,
6784 					  "umm, got %d back from search, was looking for %llu",
6785 					  ret, bytenr);
6786 				if (ret > 0)
6787 					btrfs_print_leaf(path->nodes[0]);
6788 			}
6789 			if (ret < 0) {
6790 				btrfs_abort_transaction(trans, ret);
6791 				goto out;
6792 			}
6793 			extent_slot = path->slots[0];
6794 		}
6795 	} else if (ret == -ENOENT) {
6796 		btrfs_print_leaf(path->nodes[0]);
6797 		btrfs_err(info,
6798 			"unable to find ref byte nr %llu parent %llu root %llu  owner %llu offset %llu",
6799 			bytenr, parent, root_objectid, owner_objectid,
6800 			owner_offset);
6801 		btrfs_abort_transaction(trans, ret);
6802 		goto out;
6803 	} else {
6804 		btrfs_abort_transaction(trans, ret);
6805 		goto out;
6806 	}
6807 
6808 	leaf = path->nodes[0];
6809 	item_size = btrfs_item_size_nr(leaf, extent_slot);
6810 	if (unlikely(item_size < sizeof(*ei))) {
6811 		ret = -EINVAL;
6812 		btrfs_print_v0_err(info);
6813 		btrfs_abort_transaction(trans, ret);
6814 		goto out;
6815 	}
6816 	ei = btrfs_item_ptr(leaf, extent_slot,
6817 			    struct btrfs_extent_item);
6818 	if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
6819 	    key.type == BTRFS_EXTENT_ITEM_KEY) {
6820 		struct btrfs_tree_block_info *bi;
6821 		BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
6822 		bi = (struct btrfs_tree_block_info *)(ei + 1);
6823 		WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
6824 	}
6825 
6826 	refs = btrfs_extent_refs(leaf, ei);
6827 	if (refs < refs_to_drop) {
6828 		btrfs_err(info,
6829 			  "trying to drop %d refs but we only have %Lu for bytenr %Lu",
6830 			  refs_to_drop, refs, bytenr);
6831 		ret = -EINVAL;
6832 		btrfs_abort_transaction(trans, ret);
6833 		goto out;
6834 	}
6835 	refs -= refs_to_drop;
6836 
6837 	if (refs > 0) {
6838 		if (extent_op)
6839 			__run_delayed_extent_op(extent_op, leaf, ei);
6840 		/*
6841 		 * In the case of inline back ref, reference count will
6842 		 * be updated by remove_extent_backref
6843 		 */
6844 		if (iref) {
6845 			BUG_ON(!found_extent);
6846 		} else {
6847 			btrfs_set_extent_refs(leaf, ei, refs);
6848 			btrfs_mark_buffer_dirty(leaf);
6849 		}
6850 		if (found_extent) {
6851 			ret = remove_extent_backref(trans, path, iref,
6852 						    refs_to_drop, is_data,
6853 						    &last_ref);
6854 			if (ret) {
6855 				btrfs_abort_transaction(trans, ret);
6856 				goto out;
6857 			}
6858 		}
6859 	} else {
6860 		if (found_extent) {
6861 			BUG_ON(is_data && refs_to_drop !=
6862 			       extent_data_ref_count(path, iref));
6863 			if (iref) {
6864 				BUG_ON(path->slots[0] != extent_slot);
6865 			} else {
6866 				BUG_ON(path->slots[0] != extent_slot + 1);
6867 				path->slots[0] = extent_slot;
6868 				num_to_del = 2;
6869 			}
6870 		}
6871 
6872 		last_ref = 1;
6873 		ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
6874 				      num_to_del);
6875 		if (ret) {
6876 			btrfs_abort_transaction(trans, ret);
6877 			goto out;
6878 		}
6879 		btrfs_release_path(path);
6880 
6881 		if (is_data) {
6882 			ret = btrfs_del_csums(trans, info->csum_root, bytenr,
6883 					      num_bytes);
6884 			if (ret) {
6885 				btrfs_abort_transaction(trans, ret);
6886 				goto out;
6887 			}
6888 		}
6889 
6890 		ret = add_to_free_space_tree(trans, bytenr, num_bytes);
6891 		if (ret) {
6892 			btrfs_abort_transaction(trans, ret);
6893 			goto out;
6894 		}
6895 
6896 		ret = update_block_group(trans, info, bytenr, num_bytes, 0);
6897 		if (ret) {
6898 			btrfs_abort_transaction(trans, ret);
6899 			goto out;
6900 		}
6901 	}
6902 	btrfs_release_path(path);
6903 
6904 out:
6905 	btrfs_free_path(path);
6906 	return ret;
6907 }
6908 
6909 /*
6910  * when we free an block, it is possible (and likely) that we free the last
6911  * delayed ref for that extent as well.  This searches the delayed ref tree for
6912  * a given extent, and if there are no other delayed refs to be processed, it
6913  * removes it from the tree.
6914  */
check_ref_cleanup(struct btrfs_trans_handle * trans,u64 bytenr)6915 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
6916 				      u64 bytenr)
6917 {
6918 	struct btrfs_delayed_ref_head *head;
6919 	struct btrfs_delayed_ref_root *delayed_refs;
6920 	int ret = 0;
6921 
6922 	delayed_refs = &trans->transaction->delayed_refs;
6923 	spin_lock(&delayed_refs->lock);
6924 	head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
6925 	if (!head)
6926 		goto out_delayed_unlock;
6927 
6928 	spin_lock(&head->lock);
6929 	if (!RB_EMPTY_ROOT(&head->ref_tree))
6930 		goto out;
6931 
6932 	if (head->extent_op) {
6933 		if (!head->must_insert_reserved)
6934 			goto out;
6935 		btrfs_free_delayed_extent_op(head->extent_op);
6936 		head->extent_op = NULL;
6937 	}
6938 
6939 	/*
6940 	 * waiting for the lock here would deadlock.  If someone else has it
6941 	 * locked they are already in the process of dropping it anyway
6942 	 */
6943 	if (!mutex_trylock(&head->mutex))
6944 		goto out;
6945 
6946 	/*
6947 	 * at this point we have a head with no other entries.  Go
6948 	 * ahead and process it.
6949 	 */
6950 	rb_erase(&head->href_node, &delayed_refs->href_root);
6951 	RB_CLEAR_NODE(&head->href_node);
6952 	atomic_dec(&delayed_refs->num_entries);
6953 
6954 	/*
6955 	 * we don't take a ref on the node because we're removing it from the
6956 	 * tree, so we just steal the ref the tree was holding.
6957 	 */
6958 	delayed_refs->num_heads--;
6959 	if (head->processing == 0)
6960 		delayed_refs->num_heads_ready--;
6961 	head->processing = 0;
6962 	spin_unlock(&head->lock);
6963 	spin_unlock(&delayed_refs->lock);
6964 
6965 	BUG_ON(head->extent_op);
6966 	if (head->must_insert_reserved)
6967 		ret = 1;
6968 
6969 	mutex_unlock(&head->mutex);
6970 	btrfs_put_delayed_ref_head(head);
6971 	return ret;
6972 out:
6973 	spin_unlock(&head->lock);
6974 
6975 out_delayed_unlock:
6976 	spin_unlock(&delayed_refs->lock);
6977 	return 0;
6978 }
6979 
btrfs_free_tree_block(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct extent_buffer * buf,u64 parent,int last_ref)6980 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
6981 			   struct btrfs_root *root,
6982 			   struct extent_buffer *buf,
6983 			   u64 parent, int last_ref)
6984 {
6985 	struct btrfs_fs_info *fs_info = root->fs_info;
6986 	int pin = 1;
6987 	int ret;
6988 
6989 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
6990 		int old_ref_mod, new_ref_mod;
6991 
6992 		btrfs_ref_tree_mod(root, buf->start, buf->len, parent,
6993 				   root->root_key.objectid,
6994 				   btrfs_header_level(buf), 0,
6995 				   BTRFS_DROP_DELAYED_REF);
6996 		ret = btrfs_add_delayed_tree_ref(trans, buf->start,
6997 						 buf->len, parent,
6998 						 root->root_key.objectid,
6999 						 btrfs_header_level(buf),
7000 						 BTRFS_DROP_DELAYED_REF, NULL,
7001 						 &old_ref_mod, &new_ref_mod);
7002 		BUG_ON(ret); /* -ENOMEM */
7003 		pin = old_ref_mod >= 0 && new_ref_mod < 0;
7004 	}
7005 
7006 	if (last_ref && btrfs_header_generation(buf) == trans->transid) {
7007 		struct btrfs_block_group_cache *cache;
7008 
7009 		if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
7010 			ret = check_ref_cleanup(trans, buf->start);
7011 			if (!ret)
7012 				goto out;
7013 		}
7014 
7015 		pin = 0;
7016 		cache = btrfs_lookup_block_group(fs_info, buf->start);
7017 
7018 		if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
7019 			pin_down_extent(fs_info, cache, buf->start,
7020 					buf->len, 1);
7021 			btrfs_put_block_group(cache);
7022 			goto out;
7023 		}
7024 
7025 		WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
7026 
7027 		btrfs_add_free_space(cache, buf->start, buf->len);
7028 		btrfs_free_reserved_bytes(cache, buf->len, 0);
7029 		btrfs_put_block_group(cache);
7030 		trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
7031 	}
7032 out:
7033 	if (pin)
7034 		add_pinned_bytes(fs_info, buf->len, true,
7035 				 root->root_key.objectid);
7036 
7037 	if (last_ref) {
7038 		/*
7039 		 * Deleting the buffer, clear the corrupt flag since it doesn't
7040 		 * matter anymore.
7041 		 */
7042 		clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
7043 	}
7044 }
7045 
7046 /* Can return -ENOMEM */
btrfs_free_extent(struct btrfs_trans_handle * trans,struct btrfs_root * root,u64 bytenr,u64 num_bytes,u64 parent,u64 root_objectid,u64 owner,u64 offset)7047 int btrfs_free_extent(struct btrfs_trans_handle *trans,
7048 		      struct btrfs_root *root,
7049 		      u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
7050 		      u64 owner, u64 offset)
7051 {
7052 	struct btrfs_fs_info *fs_info = root->fs_info;
7053 	int old_ref_mod, new_ref_mod;
7054 	int ret;
7055 
7056 	if (btrfs_is_testing(fs_info))
7057 		return 0;
7058 
7059 	if (root_objectid != BTRFS_TREE_LOG_OBJECTID)
7060 		btrfs_ref_tree_mod(root, bytenr, num_bytes, parent,
7061 				   root_objectid, owner, offset,
7062 				   BTRFS_DROP_DELAYED_REF);
7063 
7064 	/*
7065 	 * tree log blocks never actually go into the extent allocation
7066 	 * tree, just update pinning info and exit early.
7067 	 */
7068 	if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
7069 		WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
7070 		/* unlocks the pinned mutex */
7071 		btrfs_pin_extent(fs_info, bytenr, num_bytes, 1);
7072 		old_ref_mod = new_ref_mod = 0;
7073 		ret = 0;
7074 	} else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
7075 		ret = btrfs_add_delayed_tree_ref(trans, bytenr,
7076 						 num_bytes, parent,
7077 						 root_objectid, (int)owner,
7078 						 BTRFS_DROP_DELAYED_REF, NULL,
7079 						 &old_ref_mod, &new_ref_mod);
7080 	} else {
7081 		ret = btrfs_add_delayed_data_ref(trans, bytenr,
7082 						 num_bytes, parent,
7083 						 root_objectid, owner, offset,
7084 						 0, BTRFS_DROP_DELAYED_REF,
7085 						 &old_ref_mod, &new_ref_mod);
7086 	}
7087 
7088 	if (ret == 0 && old_ref_mod >= 0 && new_ref_mod < 0) {
7089 		bool metadata = owner < BTRFS_FIRST_FREE_OBJECTID;
7090 
7091 		add_pinned_bytes(fs_info, num_bytes, metadata, root_objectid);
7092 	}
7093 
7094 	return ret;
7095 }
7096 
7097 /*
7098  * when we wait for progress in the block group caching, its because
7099  * our allocation attempt failed at least once.  So, we must sleep
7100  * and let some progress happen before we try again.
7101  *
7102  * This function will sleep at least once waiting for new free space to
7103  * show up, and then it will check the block group free space numbers
7104  * for our min num_bytes.  Another option is to have it go ahead
7105  * and look in the rbtree for a free extent of a given size, but this
7106  * is a good start.
7107  *
7108  * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
7109  * any of the information in this block group.
7110  */
7111 static noinline void
wait_block_group_cache_progress(struct btrfs_block_group_cache * cache,u64 num_bytes)7112 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
7113 				u64 num_bytes)
7114 {
7115 	struct btrfs_caching_control *caching_ctl;
7116 
7117 	caching_ctl = get_caching_control(cache);
7118 	if (!caching_ctl)
7119 		return;
7120 
7121 	wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
7122 		   (cache->free_space_ctl->free_space >= num_bytes));
7123 
7124 	put_caching_control(caching_ctl);
7125 }
7126 
7127 static noinline int
wait_block_group_cache_done(struct btrfs_block_group_cache * cache)7128 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
7129 {
7130 	struct btrfs_caching_control *caching_ctl;
7131 	int ret = 0;
7132 
7133 	caching_ctl = get_caching_control(cache);
7134 	if (!caching_ctl)
7135 		return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
7136 
7137 	wait_event(caching_ctl->wait, block_group_cache_done(cache));
7138 	if (cache->cached == BTRFS_CACHE_ERROR)
7139 		ret = -EIO;
7140 	put_caching_control(caching_ctl);
7141 	return ret;
7142 }
7143 
7144 enum btrfs_loop_type {
7145 	LOOP_CACHING_NOWAIT = 0,
7146 	LOOP_CACHING_WAIT = 1,
7147 	LOOP_ALLOC_CHUNK = 2,
7148 	LOOP_NO_EMPTY_SIZE = 3,
7149 };
7150 
7151 static inline void
btrfs_lock_block_group(struct btrfs_block_group_cache * cache,int delalloc)7152 btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
7153 		       int delalloc)
7154 {
7155 	if (delalloc)
7156 		down_read(&cache->data_rwsem);
7157 }
7158 
7159 static inline void
btrfs_grab_block_group(struct btrfs_block_group_cache * cache,int delalloc)7160 btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
7161 		       int delalloc)
7162 {
7163 	btrfs_get_block_group(cache);
7164 	if (delalloc)
7165 		down_read(&cache->data_rwsem);
7166 }
7167 
7168 static struct btrfs_block_group_cache *
btrfs_lock_cluster(struct btrfs_block_group_cache * block_group,struct btrfs_free_cluster * cluster,int delalloc)7169 btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
7170 		   struct btrfs_free_cluster *cluster,
7171 		   int delalloc)
7172 {
7173 	struct btrfs_block_group_cache *used_bg = NULL;
7174 
7175 	spin_lock(&cluster->refill_lock);
7176 	while (1) {
7177 		used_bg = cluster->block_group;
7178 		if (!used_bg)
7179 			return NULL;
7180 
7181 		if (used_bg == block_group)
7182 			return used_bg;
7183 
7184 		btrfs_get_block_group(used_bg);
7185 
7186 		if (!delalloc)
7187 			return used_bg;
7188 
7189 		if (down_read_trylock(&used_bg->data_rwsem))
7190 			return used_bg;
7191 
7192 		spin_unlock(&cluster->refill_lock);
7193 
7194 		/* We should only have one-level nested. */
7195 		down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
7196 
7197 		spin_lock(&cluster->refill_lock);
7198 		if (used_bg == cluster->block_group)
7199 			return used_bg;
7200 
7201 		up_read(&used_bg->data_rwsem);
7202 		btrfs_put_block_group(used_bg);
7203 	}
7204 }
7205 
7206 static inline void
btrfs_release_block_group(struct btrfs_block_group_cache * cache,int delalloc)7207 btrfs_release_block_group(struct btrfs_block_group_cache *cache,
7208 			 int delalloc)
7209 {
7210 	if (delalloc)
7211 		up_read(&cache->data_rwsem);
7212 	btrfs_put_block_group(cache);
7213 }
7214 
7215 /*
7216  * walks the btree of allocated extents and find a hole of a given size.
7217  * The key ins is changed to record the hole:
7218  * ins->objectid == start position
7219  * ins->flags = BTRFS_EXTENT_ITEM_KEY
7220  * ins->offset == the size of the hole.
7221  * Any available blocks before search_start are skipped.
7222  *
7223  * If there is no suitable free space, we will record the max size of
7224  * the free space extent currently.
7225  */
find_free_extent(struct btrfs_fs_info * fs_info,u64 ram_bytes,u64 num_bytes,u64 empty_size,u64 hint_byte,struct btrfs_key * ins,u64 flags,int delalloc)7226 static noinline int find_free_extent(struct btrfs_fs_info *fs_info,
7227 				u64 ram_bytes, u64 num_bytes, u64 empty_size,
7228 				u64 hint_byte, struct btrfs_key *ins,
7229 				u64 flags, int delalloc)
7230 {
7231 	int ret = 0;
7232 	struct btrfs_root *root = fs_info->extent_root;
7233 	struct btrfs_free_cluster *last_ptr = NULL;
7234 	struct btrfs_block_group_cache *block_group = NULL;
7235 	u64 search_start = 0;
7236 	u64 max_extent_size = 0;
7237 	u64 max_free_space = 0;
7238 	u64 empty_cluster = 0;
7239 	struct btrfs_space_info *space_info;
7240 	int loop = 0;
7241 	int index = btrfs_bg_flags_to_raid_index(flags);
7242 	bool failed_cluster_refill = false;
7243 	bool failed_alloc = false;
7244 	bool use_cluster = true;
7245 	bool have_caching_bg = false;
7246 	bool orig_have_caching_bg = false;
7247 	bool full_search = false;
7248 
7249 	WARN_ON(num_bytes < fs_info->sectorsize);
7250 	ins->type = BTRFS_EXTENT_ITEM_KEY;
7251 	ins->objectid = 0;
7252 	ins->offset = 0;
7253 
7254 	trace_find_free_extent(fs_info, num_bytes, empty_size, flags);
7255 
7256 	space_info = __find_space_info(fs_info, flags);
7257 	if (!space_info) {
7258 		btrfs_err(fs_info, "No space info for %llu", flags);
7259 		return -ENOSPC;
7260 	}
7261 
7262 	/*
7263 	 * If our free space is heavily fragmented we may not be able to make
7264 	 * big contiguous allocations, so instead of doing the expensive search
7265 	 * for free space, simply return ENOSPC with our max_extent_size so we
7266 	 * can go ahead and search for a more manageable chunk.
7267 	 *
7268 	 * If our max_extent_size is large enough for our allocation simply
7269 	 * disable clustering since we will likely not be able to find enough
7270 	 * space to create a cluster and induce latency trying.
7271 	 */
7272 	if (unlikely(space_info->max_extent_size)) {
7273 		spin_lock(&space_info->lock);
7274 		if (space_info->max_extent_size &&
7275 		    num_bytes > space_info->max_extent_size) {
7276 			ins->offset = space_info->max_extent_size;
7277 			spin_unlock(&space_info->lock);
7278 			return -ENOSPC;
7279 		} else if (space_info->max_extent_size) {
7280 			use_cluster = false;
7281 		}
7282 		spin_unlock(&space_info->lock);
7283 	}
7284 
7285 	last_ptr = fetch_cluster_info(fs_info, space_info, &empty_cluster);
7286 	if (last_ptr) {
7287 		spin_lock(&last_ptr->lock);
7288 		if (last_ptr->block_group)
7289 			hint_byte = last_ptr->window_start;
7290 		if (last_ptr->fragmented) {
7291 			/*
7292 			 * We still set window_start so we can keep track of the
7293 			 * last place we found an allocation to try and save
7294 			 * some time.
7295 			 */
7296 			hint_byte = last_ptr->window_start;
7297 			use_cluster = false;
7298 		}
7299 		spin_unlock(&last_ptr->lock);
7300 	}
7301 
7302 	search_start = max(search_start, first_logical_byte(fs_info, 0));
7303 	search_start = max(search_start, hint_byte);
7304 	if (search_start == hint_byte) {
7305 		block_group = btrfs_lookup_block_group(fs_info, search_start);
7306 		/*
7307 		 * we don't want to use the block group if it doesn't match our
7308 		 * allocation bits, or if its not cached.
7309 		 *
7310 		 * However if we are re-searching with an ideal block group
7311 		 * picked out then we don't care that the block group is cached.
7312 		 */
7313 		if (block_group && block_group_bits(block_group, flags) &&
7314 		    block_group->cached != BTRFS_CACHE_NO) {
7315 			down_read(&space_info->groups_sem);
7316 			if (list_empty(&block_group->list) ||
7317 			    block_group->ro) {
7318 				/*
7319 				 * someone is removing this block group,
7320 				 * we can't jump into the have_block_group
7321 				 * target because our list pointers are not
7322 				 * valid
7323 				 */
7324 				btrfs_put_block_group(block_group);
7325 				up_read(&space_info->groups_sem);
7326 			} else {
7327 				index = btrfs_bg_flags_to_raid_index(
7328 						block_group->flags);
7329 				btrfs_lock_block_group(block_group, delalloc);
7330 				goto have_block_group;
7331 			}
7332 		} else if (block_group) {
7333 			btrfs_put_block_group(block_group);
7334 		}
7335 	}
7336 search:
7337 	have_caching_bg = false;
7338 	if (index == 0 || index == btrfs_bg_flags_to_raid_index(flags))
7339 		full_search = true;
7340 	down_read(&space_info->groups_sem);
7341 	list_for_each_entry(block_group, &space_info->block_groups[index],
7342 			    list) {
7343 		u64 offset;
7344 		int cached;
7345 
7346 		/* If the block group is read-only, we can skip it entirely. */
7347 		if (unlikely(block_group->ro))
7348 			continue;
7349 
7350 		btrfs_grab_block_group(block_group, delalloc);
7351 		search_start = block_group->key.objectid;
7352 
7353 		/*
7354 		 * this can happen if we end up cycling through all the
7355 		 * raid types, but we want to make sure we only allocate
7356 		 * for the proper type.
7357 		 */
7358 		if (!block_group_bits(block_group, flags)) {
7359 			u64 extra = BTRFS_BLOCK_GROUP_DUP |
7360 				BTRFS_BLOCK_GROUP_RAID1 |
7361 				BTRFS_BLOCK_GROUP_RAID5 |
7362 				BTRFS_BLOCK_GROUP_RAID6 |
7363 				BTRFS_BLOCK_GROUP_RAID10;
7364 
7365 			/*
7366 			 * if they asked for extra copies and this block group
7367 			 * doesn't provide them, bail.  This does allow us to
7368 			 * fill raid0 from raid1.
7369 			 */
7370 			if ((flags & extra) && !(block_group->flags & extra))
7371 				goto loop;
7372 
7373 			/*
7374 			 * This block group has different flags than we want.
7375 			 * It's possible that we have MIXED_GROUP flag but no
7376 			 * block group is mixed.  Just skip such block group.
7377 			 */
7378 			btrfs_release_block_group(block_group, delalloc);
7379 			continue;
7380 		}
7381 
7382 have_block_group:
7383 		cached = block_group_cache_done(block_group);
7384 		if (unlikely(!cached)) {
7385 			have_caching_bg = true;
7386 			ret = cache_block_group(block_group, 0);
7387 			BUG_ON(ret < 0);
7388 			ret = 0;
7389 		}
7390 
7391 		if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
7392 			goto loop;
7393 
7394 		/*
7395 		 * Ok we want to try and use the cluster allocator, so
7396 		 * lets look there
7397 		 */
7398 		if (last_ptr && use_cluster) {
7399 			struct btrfs_block_group_cache *used_block_group;
7400 			unsigned long aligned_cluster;
7401 			/*
7402 			 * the refill lock keeps out other
7403 			 * people trying to start a new cluster
7404 			 */
7405 			used_block_group = btrfs_lock_cluster(block_group,
7406 							      last_ptr,
7407 							      delalloc);
7408 			if (!used_block_group)
7409 				goto refill_cluster;
7410 
7411 			if (used_block_group != block_group &&
7412 			    (used_block_group->ro ||
7413 			     !block_group_bits(used_block_group, flags)))
7414 				goto release_cluster;
7415 
7416 			offset = btrfs_alloc_from_cluster(used_block_group,
7417 						last_ptr,
7418 						num_bytes,
7419 						used_block_group->key.objectid,
7420 						&max_extent_size);
7421 			if (offset) {
7422 				/* we have a block, we're done */
7423 				spin_unlock(&last_ptr->refill_lock);
7424 				trace_btrfs_reserve_extent_cluster(
7425 						used_block_group,
7426 						search_start, num_bytes);
7427 				if (used_block_group != block_group) {
7428 					btrfs_release_block_group(block_group,
7429 								  delalloc);
7430 					block_group = used_block_group;
7431 				}
7432 				goto checks;
7433 			}
7434 
7435 			WARN_ON(last_ptr->block_group != used_block_group);
7436 release_cluster:
7437 			/* If we are on LOOP_NO_EMPTY_SIZE, we can't
7438 			 * set up a new clusters, so lets just skip it
7439 			 * and let the allocator find whatever block
7440 			 * it can find.  If we reach this point, we
7441 			 * will have tried the cluster allocator
7442 			 * plenty of times and not have found
7443 			 * anything, so we are likely way too
7444 			 * fragmented for the clustering stuff to find
7445 			 * anything.
7446 			 *
7447 			 * However, if the cluster is taken from the
7448 			 * current block group, release the cluster
7449 			 * first, so that we stand a better chance of
7450 			 * succeeding in the unclustered
7451 			 * allocation.  */
7452 			if (loop >= LOOP_NO_EMPTY_SIZE &&
7453 			    used_block_group != block_group) {
7454 				spin_unlock(&last_ptr->refill_lock);
7455 				btrfs_release_block_group(used_block_group,
7456 							  delalloc);
7457 				goto unclustered_alloc;
7458 			}
7459 
7460 			/*
7461 			 * this cluster didn't work out, free it and
7462 			 * start over
7463 			 */
7464 			btrfs_return_cluster_to_free_space(NULL, last_ptr);
7465 
7466 			if (used_block_group != block_group)
7467 				btrfs_release_block_group(used_block_group,
7468 							  delalloc);
7469 refill_cluster:
7470 			if (loop >= LOOP_NO_EMPTY_SIZE) {
7471 				spin_unlock(&last_ptr->refill_lock);
7472 				goto unclustered_alloc;
7473 			}
7474 
7475 			aligned_cluster = max_t(unsigned long,
7476 						empty_cluster + empty_size,
7477 					      block_group->full_stripe_len);
7478 
7479 			/* allocate a cluster in this block group */
7480 			ret = btrfs_find_space_cluster(fs_info, block_group,
7481 						       last_ptr, search_start,
7482 						       num_bytes,
7483 						       aligned_cluster);
7484 			if (ret == 0) {
7485 				/*
7486 				 * now pull our allocation out of this
7487 				 * cluster
7488 				 */
7489 				offset = btrfs_alloc_from_cluster(block_group,
7490 							last_ptr,
7491 							num_bytes,
7492 							search_start,
7493 							&max_extent_size);
7494 				if (offset) {
7495 					/* we found one, proceed */
7496 					spin_unlock(&last_ptr->refill_lock);
7497 					trace_btrfs_reserve_extent_cluster(
7498 						block_group, search_start,
7499 						num_bytes);
7500 					goto checks;
7501 				}
7502 			} else if (!cached && loop > LOOP_CACHING_NOWAIT
7503 				   && !failed_cluster_refill) {
7504 				spin_unlock(&last_ptr->refill_lock);
7505 
7506 				failed_cluster_refill = true;
7507 				wait_block_group_cache_progress(block_group,
7508 				       num_bytes + empty_cluster + empty_size);
7509 				goto have_block_group;
7510 			}
7511 
7512 			/*
7513 			 * at this point we either didn't find a cluster
7514 			 * or we weren't able to allocate a block from our
7515 			 * cluster.  Free the cluster we've been trying
7516 			 * to use, and go to the next block group
7517 			 */
7518 			btrfs_return_cluster_to_free_space(NULL, last_ptr);
7519 			spin_unlock(&last_ptr->refill_lock);
7520 			goto loop;
7521 		}
7522 
7523 unclustered_alloc:
7524 		/*
7525 		 * We are doing an unclustered alloc, set the fragmented flag so
7526 		 * we don't bother trying to setup a cluster again until we get
7527 		 * more space.
7528 		 */
7529 		if (unlikely(last_ptr)) {
7530 			spin_lock(&last_ptr->lock);
7531 			last_ptr->fragmented = 1;
7532 			spin_unlock(&last_ptr->lock);
7533 		}
7534 		if (cached) {
7535 			struct btrfs_free_space_ctl *ctl =
7536 				block_group->free_space_ctl;
7537 
7538 			spin_lock(&ctl->tree_lock);
7539 			if (ctl->free_space <
7540 			    num_bytes + empty_cluster + empty_size) {
7541 				max_free_space = max(max_free_space,
7542 						     ctl->free_space);
7543 				spin_unlock(&ctl->tree_lock);
7544 				goto loop;
7545 			}
7546 			spin_unlock(&ctl->tree_lock);
7547 		}
7548 
7549 		offset = btrfs_find_space_for_alloc(block_group, search_start,
7550 						    num_bytes, empty_size,
7551 						    &max_extent_size);
7552 		/*
7553 		 * If we didn't find a chunk, and we haven't failed on this
7554 		 * block group before, and this block group is in the middle of
7555 		 * caching and we are ok with waiting, then go ahead and wait
7556 		 * for progress to be made, and set failed_alloc to true.
7557 		 *
7558 		 * If failed_alloc is true then we've already waited on this
7559 		 * block group once and should move on to the next block group.
7560 		 */
7561 		if (!offset && !failed_alloc && !cached &&
7562 		    loop > LOOP_CACHING_NOWAIT) {
7563 			wait_block_group_cache_progress(block_group,
7564 						num_bytes + empty_size);
7565 			failed_alloc = true;
7566 			goto have_block_group;
7567 		} else if (!offset) {
7568 			goto loop;
7569 		}
7570 checks:
7571 		search_start = round_up(offset, fs_info->stripesize);
7572 
7573 		/* move on to the next group */
7574 		if (search_start + num_bytes >
7575 		    block_group->key.objectid + block_group->key.offset) {
7576 			btrfs_add_free_space(block_group, offset, num_bytes);
7577 			goto loop;
7578 		}
7579 
7580 		if (offset < search_start)
7581 			btrfs_add_free_space(block_group, offset,
7582 					     search_start - offset);
7583 
7584 		ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
7585 				num_bytes, delalloc);
7586 		if (ret == -EAGAIN) {
7587 			btrfs_add_free_space(block_group, offset, num_bytes);
7588 			goto loop;
7589 		}
7590 		btrfs_inc_block_group_reservations(block_group);
7591 
7592 		/* we are all good, lets return */
7593 		ins->objectid = search_start;
7594 		ins->offset = num_bytes;
7595 
7596 		trace_btrfs_reserve_extent(block_group, search_start, num_bytes);
7597 		btrfs_release_block_group(block_group, delalloc);
7598 		break;
7599 loop:
7600 		failed_cluster_refill = false;
7601 		failed_alloc = false;
7602 		BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
7603 		       index);
7604 		btrfs_release_block_group(block_group, delalloc);
7605 		cond_resched();
7606 	}
7607 	up_read(&space_info->groups_sem);
7608 
7609 	if ((loop == LOOP_CACHING_NOWAIT) && have_caching_bg
7610 		&& !orig_have_caching_bg)
7611 		orig_have_caching_bg = true;
7612 
7613 	if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
7614 		goto search;
7615 
7616 	if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
7617 		goto search;
7618 
7619 	/*
7620 	 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
7621 	 *			caching kthreads as we move along
7622 	 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
7623 	 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
7624 	 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
7625 	 *			again
7626 	 */
7627 	if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
7628 		index = 0;
7629 		if (loop == LOOP_CACHING_NOWAIT) {
7630 			/*
7631 			 * We want to skip the LOOP_CACHING_WAIT step if we
7632 			 * don't have any uncached bgs and we've already done a
7633 			 * full search through.
7634 			 */
7635 			if (orig_have_caching_bg || !full_search)
7636 				loop = LOOP_CACHING_WAIT;
7637 			else
7638 				loop = LOOP_ALLOC_CHUNK;
7639 		} else {
7640 			loop++;
7641 		}
7642 
7643 		if (loop == LOOP_ALLOC_CHUNK) {
7644 			struct btrfs_trans_handle *trans;
7645 			int exist = 0;
7646 
7647 			trans = current->journal_info;
7648 			if (trans)
7649 				exist = 1;
7650 			else
7651 				trans = btrfs_join_transaction(root);
7652 
7653 			if (IS_ERR(trans)) {
7654 				ret = PTR_ERR(trans);
7655 				goto out;
7656 			}
7657 
7658 			ret = do_chunk_alloc(trans, flags, CHUNK_ALLOC_FORCE);
7659 
7660 			/*
7661 			 * If we can't allocate a new chunk we've already looped
7662 			 * through at least once, move on to the NO_EMPTY_SIZE
7663 			 * case.
7664 			 */
7665 			if (ret == -ENOSPC)
7666 				loop = LOOP_NO_EMPTY_SIZE;
7667 
7668 			/*
7669 			 * Do not bail out on ENOSPC since we
7670 			 * can do more things.
7671 			 */
7672 			if (ret < 0 && ret != -ENOSPC)
7673 				btrfs_abort_transaction(trans, ret);
7674 			else
7675 				ret = 0;
7676 			if (!exist)
7677 				btrfs_end_transaction(trans);
7678 			if (ret)
7679 				goto out;
7680 		}
7681 
7682 		if (loop == LOOP_NO_EMPTY_SIZE) {
7683 			/*
7684 			 * Don't loop again if we already have no empty_size and
7685 			 * no empty_cluster.
7686 			 */
7687 			if (empty_size == 0 &&
7688 			    empty_cluster == 0) {
7689 				ret = -ENOSPC;
7690 				goto out;
7691 			}
7692 			empty_size = 0;
7693 			empty_cluster = 0;
7694 		}
7695 
7696 		goto search;
7697 	} else if (!ins->objectid) {
7698 		ret = -ENOSPC;
7699 	} else if (ins->objectid) {
7700 		if (!use_cluster && last_ptr) {
7701 			spin_lock(&last_ptr->lock);
7702 			last_ptr->window_start = ins->objectid;
7703 			spin_unlock(&last_ptr->lock);
7704 		}
7705 		ret = 0;
7706 	}
7707 out:
7708 	if (ret == -ENOSPC) {
7709 		if (!max_extent_size)
7710 			max_extent_size = max_free_space;
7711 		spin_lock(&space_info->lock);
7712 		space_info->max_extent_size = max_extent_size;
7713 		spin_unlock(&space_info->lock);
7714 		ins->offset = max_extent_size;
7715 	}
7716 	return ret;
7717 }
7718 
dump_space_info(struct btrfs_fs_info * fs_info,struct btrfs_space_info * info,u64 bytes,int dump_block_groups)7719 static void dump_space_info(struct btrfs_fs_info *fs_info,
7720 			    struct btrfs_space_info *info, u64 bytes,
7721 			    int dump_block_groups)
7722 {
7723 	struct btrfs_block_group_cache *cache;
7724 	int index = 0;
7725 
7726 	spin_lock(&info->lock);
7727 	btrfs_info(fs_info, "space_info %llu has %llu free, is %sfull",
7728 		   info->flags,
7729 		   info->total_bytes - btrfs_space_info_used(info, true),
7730 		   info->full ? "" : "not ");
7731 	btrfs_info(fs_info,
7732 		"space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu",
7733 		info->total_bytes, info->bytes_used, info->bytes_pinned,
7734 		info->bytes_reserved, info->bytes_may_use,
7735 		info->bytes_readonly);
7736 	spin_unlock(&info->lock);
7737 
7738 	if (!dump_block_groups)
7739 		return;
7740 
7741 	down_read(&info->groups_sem);
7742 again:
7743 	list_for_each_entry(cache, &info->block_groups[index], list) {
7744 		spin_lock(&cache->lock);
7745 		btrfs_info(fs_info,
7746 			"block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %s",
7747 			cache->key.objectid, cache->key.offset,
7748 			btrfs_block_group_used(&cache->item), cache->pinned,
7749 			cache->reserved, cache->ro ? "[readonly]" : "");
7750 		btrfs_dump_free_space(cache, bytes);
7751 		spin_unlock(&cache->lock);
7752 	}
7753 	if (++index < BTRFS_NR_RAID_TYPES)
7754 		goto again;
7755 	up_read(&info->groups_sem);
7756 }
7757 
7758 /*
7759  * btrfs_reserve_extent - entry point to the extent allocator. Tries to find a
7760  *			  hole that is at least as big as @num_bytes.
7761  *
7762  * @root           -	The root that will contain this extent
7763  *
7764  * @ram_bytes      -	The amount of space in ram that @num_bytes take. This
7765  *			is used for accounting purposes. This value differs
7766  *			from @num_bytes only in the case of compressed extents.
7767  *
7768  * @num_bytes      -	Number of bytes to allocate on-disk.
7769  *
7770  * @min_alloc_size -	Indicates the minimum amount of space that the
7771  *			allocator should try to satisfy. In some cases
7772  *			@num_bytes may be larger than what is required and if
7773  *			the filesystem is fragmented then allocation fails.
7774  *			However, the presence of @min_alloc_size gives a
7775  *			chance to try and satisfy the smaller allocation.
7776  *
7777  * @empty_size     -	A hint that you plan on doing more COW. This is the
7778  *			size in bytes the allocator should try to find free
7779  *			next to the block it returns.  This is just a hint and
7780  *			may be ignored by the allocator.
7781  *
7782  * @hint_byte      -	Hint to the allocator to start searching above the byte
7783  *			address passed. It might be ignored.
7784  *
7785  * @ins            -	This key is modified to record the found hole. It will
7786  *			have the following values:
7787  *			ins->objectid == start position
7788  *			ins->flags = BTRFS_EXTENT_ITEM_KEY
7789  *			ins->offset == the size of the hole.
7790  *
7791  * @is_data        -	Boolean flag indicating whether an extent is
7792  *			allocated for data (true) or metadata (false)
7793  *
7794  * @delalloc       -	Boolean flag indicating whether this allocation is for
7795  *			delalloc or not. If 'true' data_rwsem of block groups
7796  *			is going to be acquired.
7797  *
7798  *
7799  * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
7800  * case -ENOSPC is returned then @ins->offset will contain the size of the
7801  * largest available hole the allocator managed to find.
7802  */
btrfs_reserve_extent(struct btrfs_root * root,u64 ram_bytes,u64 num_bytes,u64 min_alloc_size,u64 empty_size,u64 hint_byte,struct btrfs_key * ins,int is_data,int delalloc)7803 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
7804 			 u64 num_bytes, u64 min_alloc_size,
7805 			 u64 empty_size, u64 hint_byte,
7806 			 struct btrfs_key *ins, int is_data, int delalloc)
7807 {
7808 	struct btrfs_fs_info *fs_info = root->fs_info;
7809 	bool final_tried = num_bytes == min_alloc_size;
7810 	u64 flags;
7811 	int ret;
7812 
7813 	flags = get_alloc_profile_by_root(root, is_data);
7814 again:
7815 	WARN_ON(num_bytes < fs_info->sectorsize);
7816 	ret = find_free_extent(fs_info, ram_bytes, num_bytes, empty_size,
7817 			       hint_byte, ins, flags, delalloc);
7818 	if (!ret && !is_data) {
7819 		btrfs_dec_block_group_reservations(fs_info, ins->objectid);
7820 	} else if (ret == -ENOSPC) {
7821 		if (!final_tried && ins->offset) {
7822 			num_bytes = min(num_bytes >> 1, ins->offset);
7823 			num_bytes = round_down(num_bytes,
7824 					       fs_info->sectorsize);
7825 			num_bytes = max(num_bytes, min_alloc_size);
7826 			ram_bytes = num_bytes;
7827 			if (num_bytes == min_alloc_size)
7828 				final_tried = true;
7829 			goto again;
7830 		} else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
7831 			struct btrfs_space_info *sinfo;
7832 
7833 			sinfo = __find_space_info(fs_info, flags);
7834 			btrfs_err(fs_info,
7835 				  "allocation failed flags %llu, wanted %llu",
7836 				  flags, num_bytes);
7837 			if (sinfo)
7838 				dump_space_info(fs_info, sinfo, num_bytes, 1);
7839 		}
7840 	}
7841 
7842 	return ret;
7843 }
7844 
__btrfs_free_reserved_extent(struct btrfs_fs_info * fs_info,u64 start,u64 len,int pin,int delalloc)7845 static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
7846 					u64 start, u64 len,
7847 					int pin, int delalloc)
7848 {
7849 	struct btrfs_block_group_cache *cache;
7850 	int ret = 0;
7851 
7852 	cache = btrfs_lookup_block_group(fs_info, start);
7853 	if (!cache) {
7854 		btrfs_err(fs_info, "Unable to find block group for %llu",
7855 			  start);
7856 		return -ENOSPC;
7857 	}
7858 
7859 	if (pin)
7860 		pin_down_extent(fs_info, cache, start, len, 1);
7861 	else {
7862 		if (btrfs_test_opt(fs_info, DISCARD))
7863 			ret = btrfs_discard_extent(fs_info, start, len, NULL);
7864 		btrfs_add_free_space(cache, start, len);
7865 		btrfs_free_reserved_bytes(cache, len, delalloc);
7866 		trace_btrfs_reserved_extent_free(fs_info, start, len);
7867 	}
7868 
7869 	btrfs_put_block_group(cache);
7870 	return ret;
7871 }
7872 
btrfs_free_reserved_extent(struct btrfs_fs_info * fs_info,u64 start,u64 len,int delalloc)7873 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
7874 			       u64 start, u64 len, int delalloc)
7875 {
7876 	return __btrfs_free_reserved_extent(fs_info, start, len, 0, delalloc);
7877 }
7878 
btrfs_free_and_pin_reserved_extent(struct btrfs_fs_info * fs_info,u64 start,u64 len)7879 int btrfs_free_and_pin_reserved_extent(struct btrfs_fs_info *fs_info,
7880 				       u64 start, u64 len)
7881 {
7882 	return __btrfs_free_reserved_extent(fs_info, start, len, 1, 0);
7883 }
7884 
alloc_reserved_file_extent(struct btrfs_trans_handle * trans,u64 parent,u64 root_objectid,u64 flags,u64 owner,u64 offset,struct btrfs_key * ins,int ref_mod)7885 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
7886 				      u64 parent, u64 root_objectid,
7887 				      u64 flags, u64 owner, u64 offset,
7888 				      struct btrfs_key *ins, int ref_mod)
7889 {
7890 	struct btrfs_fs_info *fs_info = trans->fs_info;
7891 	int ret;
7892 	struct btrfs_extent_item *extent_item;
7893 	struct btrfs_extent_inline_ref *iref;
7894 	struct btrfs_path *path;
7895 	struct extent_buffer *leaf;
7896 	int type;
7897 	u32 size;
7898 
7899 	if (parent > 0)
7900 		type = BTRFS_SHARED_DATA_REF_KEY;
7901 	else
7902 		type = BTRFS_EXTENT_DATA_REF_KEY;
7903 
7904 	size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
7905 
7906 	path = btrfs_alloc_path();
7907 	if (!path)
7908 		return -ENOMEM;
7909 
7910 	path->leave_spinning = 1;
7911 	ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
7912 				      ins, size);
7913 	if (ret) {
7914 		btrfs_free_path(path);
7915 		return ret;
7916 	}
7917 
7918 	leaf = path->nodes[0];
7919 	extent_item = btrfs_item_ptr(leaf, path->slots[0],
7920 				     struct btrfs_extent_item);
7921 	btrfs_set_extent_refs(leaf, extent_item, ref_mod);
7922 	btrfs_set_extent_generation(leaf, extent_item, trans->transid);
7923 	btrfs_set_extent_flags(leaf, extent_item,
7924 			       flags | BTRFS_EXTENT_FLAG_DATA);
7925 
7926 	iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
7927 	btrfs_set_extent_inline_ref_type(leaf, iref, type);
7928 	if (parent > 0) {
7929 		struct btrfs_shared_data_ref *ref;
7930 		ref = (struct btrfs_shared_data_ref *)(iref + 1);
7931 		btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
7932 		btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
7933 	} else {
7934 		struct btrfs_extent_data_ref *ref;
7935 		ref = (struct btrfs_extent_data_ref *)(&iref->offset);
7936 		btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
7937 		btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
7938 		btrfs_set_extent_data_ref_offset(leaf, ref, offset);
7939 		btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
7940 	}
7941 
7942 	btrfs_mark_buffer_dirty(path->nodes[0]);
7943 	btrfs_free_path(path);
7944 
7945 	ret = remove_from_free_space_tree(trans, ins->objectid, ins->offset);
7946 	if (ret)
7947 		return ret;
7948 
7949 	ret = update_block_group(trans, fs_info, ins->objectid, ins->offset, 1);
7950 	if (ret) { /* -ENOENT, logic error */
7951 		btrfs_err(fs_info, "update block group failed for %llu %llu",
7952 			ins->objectid, ins->offset);
7953 		BUG();
7954 	}
7955 	trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
7956 	return ret;
7957 }
7958 
alloc_reserved_tree_block(struct btrfs_trans_handle * trans,struct btrfs_delayed_ref_node * node,struct btrfs_delayed_extent_op * extent_op)7959 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
7960 				     struct btrfs_delayed_ref_node *node,
7961 				     struct btrfs_delayed_extent_op *extent_op)
7962 {
7963 	struct btrfs_fs_info *fs_info = trans->fs_info;
7964 	int ret;
7965 	struct btrfs_extent_item *extent_item;
7966 	struct btrfs_key extent_key;
7967 	struct btrfs_tree_block_info *block_info;
7968 	struct btrfs_extent_inline_ref *iref;
7969 	struct btrfs_path *path;
7970 	struct extent_buffer *leaf;
7971 	struct btrfs_delayed_tree_ref *ref;
7972 	u32 size = sizeof(*extent_item) + sizeof(*iref);
7973 	u64 num_bytes;
7974 	u64 flags = extent_op->flags_to_set;
7975 	bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
7976 
7977 	ref = btrfs_delayed_node_to_tree_ref(node);
7978 
7979 	extent_key.objectid = node->bytenr;
7980 	if (skinny_metadata) {
7981 		extent_key.offset = ref->level;
7982 		extent_key.type = BTRFS_METADATA_ITEM_KEY;
7983 		num_bytes = fs_info->nodesize;
7984 	} else {
7985 		extent_key.offset = node->num_bytes;
7986 		extent_key.type = BTRFS_EXTENT_ITEM_KEY;
7987 		size += sizeof(*block_info);
7988 		num_bytes = node->num_bytes;
7989 	}
7990 
7991 	path = btrfs_alloc_path();
7992 	if (!path)
7993 		return -ENOMEM;
7994 
7995 	path->leave_spinning = 1;
7996 	ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
7997 				      &extent_key, size);
7998 	if (ret) {
7999 		btrfs_free_path(path);
8000 		return ret;
8001 	}
8002 
8003 	leaf = path->nodes[0];
8004 	extent_item = btrfs_item_ptr(leaf, path->slots[0],
8005 				     struct btrfs_extent_item);
8006 	btrfs_set_extent_refs(leaf, extent_item, 1);
8007 	btrfs_set_extent_generation(leaf, extent_item, trans->transid);
8008 	btrfs_set_extent_flags(leaf, extent_item,
8009 			       flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
8010 
8011 	if (skinny_metadata) {
8012 		iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
8013 	} else {
8014 		block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
8015 		btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
8016 		btrfs_set_tree_block_level(leaf, block_info, ref->level);
8017 		iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
8018 	}
8019 
8020 	if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
8021 		BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8022 		btrfs_set_extent_inline_ref_type(leaf, iref,
8023 						 BTRFS_SHARED_BLOCK_REF_KEY);
8024 		btrfs_set_extent_inline_ref_offset(leaf, iref, ref->parent);
8025 	} else {
8026 		btrfs_set_extent_inline_ref_type(leaf, iref,
8027 						 BTRFS_TREE_BLOCK_REF_KEY);
8028 		btrfs_set_extent_inline_ref_offset(leaf, iref, ref->root);
8029 	}
8030 
8031 	btrfs_mark_buffer_dirty(leaf);
8032 	btrfs_free_path(path);
8033 
8034 	ret = remove_from_free_space_tree(trans, extent_key.objectid,
8035 					  num_bytes);
8036 	if (ret)
8037 		return ret;
8038 
8039 	ret = update_block_group(trans, fs_info, extent_key.objectid,
8040 				 fs_info->nodesize, 1);
8041 	if (ret) { /* -ENOENT, logic error */
8042 		btrfs_err(fs_info, "update block group failed for %llu %llu",
8043 			extent_key.objectid, extent_key.offset);
8044 		BUG();
8045 	}
8046 
8047 	trace_btrfs_reserved_extent_alloc(fs_info, extent_key.objectid,
8048 					  fs_info->nodesize);
8049 	return ret;
8050 }
8051 
btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle * trans,struct btrfs_root * root,u64 owner,u64 offset,u64 ram_bytes,struct btrfs_key * ins)8052 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
8053 				     struct btrfs_root *root, u64 owner,
8054 				     u64 offset, u64 ram_bytes,
8055 				     struct btrfs_key *ins)
8056 {
8057 	int ret;
8058 
8059 	BUG_ON(root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
8060 
8061 	btrfs_ref_tree_mod(root, ins->objectid, ins->offset, 0,
8062 			   root->root_key.objectid, owner, offset,
8063 			   BTRFS_ADD_DELAYED_EXTENT);
8064 
8065 	ret = btrfs_add_delayed_data_ref(trans, ins->objectid,
8066 					 ins->offset, 0,
8067 					 root->root_key.objectid, owner,
8068 					 offset, ram_bytes,
8069 					 BTRFS_ADD_DELAYED_EXTENT, NULL, NULL);
8070 	return ret;
8071 }
8072 
8073 /*
8074  * this is used by the tree logging recovery code.  It records that
8075  * an extent has been allocated and makes sure to clear the free
8076  * space cache bits as well
8077  */
btrfs_alloc_logged_file_extent(struct btrfs_trans_handle * trans,u64 root_objectid,u64 owner,u64 offset,struct btrfs_key * ins)8078 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
8079 				   u64 root_objectid, u64 owner, u64 offset,
8080 				   struct btrfs_key *ins)
8081 {
8082 	struct btrfs_fs_info *fs_info = trans->fs_info;
8083 	int ret;
8084 	struct btrfs_block_group_cache *block_group;
8085 	struct btrfs_space_info *space_info;
8086 
8087 	/*
8088 	 * Mixed block groups will exclude before processing the log so we only
8089 	 * need to do the exclude dance if this fs isn't mixed.
8090 	 */
8091 	if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
8092 		ret = __exclude_logged_extent(fs_info, ins->objectid,
8093 					      ins->offset);
8094 		if (ret)
8095 			return ret;
8096 	}
8097 
8098 	block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
8099 	if (!block_group)
8100 		return -EINVAL;
8101 
8102 	space_info = block_group->space_info;
8103 	spin_lock(&space_info->lock);
8104 	spin_lock(&block_group->lock);
8105 	space_info->bytes_reserved += ins->offset;
8106 	block_group->reserved += ins->offset;
8107 	spin_unlock(&block_group->lock);
8108 	spin_unlock(&space_info->lock);
8109 
8110 	ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
8111 					 offset, ins, 1);
8112 	btrfs_put_block_group(block_group);
8113 	return ret;
8114 }
8115 
8116 static struct extent_buffer *
btrfs_init_new_buffer(struct btrfs_trans_handle * trans,struct btrfs_root * root,u64 bytenr,int level,u64 owner)8117 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
8118 		      u64 bytenr, int level, u64 owner)
8119 {
8120 	struct btrfs_fs_info *fs_info = root->fs_info;
8121 	struct extent_buffer *buf;
8122 
8123 	buf = btrfs_find_create_tree_block(fs_info, bytenr);
8124 	if (IS_ERR(buf))
8125 		return buf;
8126 
8127 	/*
8128 	 * Extra safety check in case the extent tree is corrupted and extent
8129 	 * allocator chooses to use a tree block which is already used and
8130 	 * locked.
8131 	 */
8132 	if (buf->lock_owner == current->pid) {
8133 		btrfs_err_rl(fs_info,
8134 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
8135 			buf->start, btrfs_header_owner(buf), current->pid);
8136 		free_extent_buffer(buf);
8137 		return ERR_PTR(-EUCLEAN);
8138 	}
8139 
8140 	btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
8141 	btrfs_tree_lock(buf);
8142 	clean_tree_block(fs_info, buf);
8143 	clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
8144 
8145 	btrfs_set_lock_blocking(buf);
8146 	set_extent_buffer_uptodate(buf);
8147 
8148 	memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
8149 	btrfs_set_header_level(buf, level);
8150 	btrfs_set_header_bytenr(buf, buf->start);
8151 	btrfs_set_header_generation(buf, trans->transid);
8152 	btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
8153 	btrfs_set_header_owner(buf, owner);
8154 	write_extent_buffer_fsid(buf, fs_info->fsid);
8155 	write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
8156 	if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
8157 		buf->log_index = root->log_transid % 2;
8158 		/*
8159 		 * we allow two log transactions at a time, use different
8160 		 * EXENT bit to differentiate dirty pages.
8161 		 */
8162 		if (buf->log_index == 0)
8163 			set_extent_dirty(&root->dirty_log_pages, buf->start,
8164 					buf->start + buf->len - 1, GFP_NOFS);
8165 		else
8166 			set_extent_new(&root->dirty_log_pages, buf->start,
8167 					buf->start + buf->len - 1);
8168 	} else {
8169 		buf->log_index = -1;
8170 		set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
8171 			 buf->start + buf->len - 1, GFP_NOFS);
8172 	}
8173 	trans->dirty = true;
8174 	/* this returns a buffer locked for blocking */
8175 	return buf;
8176 }
8177 
8178 static struct btrfs_block_rsv *
use_block_rsv(struct btrfs_trans_handle * trans,struct btrfs_root * root,u32 blocksize)8179 use_block_rsv(struct btrfs_trans_handle *trans,
8180 	      struct btrfs_root *root, u32 blocksize)
8181 {
8182 	struct btrfs_fs_info *fs_info = root->fs_info;
8183 	struct btrfs_block_rsv *block_rsv;
8184 	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
8185 	int ret;
8186 	bool global_updated = false;
8187 
8188 	block_rsv = get_block_rsv(trans, root);
8189 
8190 	if (unlikely(block_rsv->size == 0))
8191 		goto try_reserve;
8192 again:
8193 	ret = block_rsv_use_bytes(block_rsv, blocksize);
8194 	if (!ret)
8195 		return block_rsv;
8196 
8197 	if (block_rsv->failfast)
8198 		return ERR_PTR(ret);
8199 
8200 	if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
8201 		global_updated = true;
8202 		update_global_block_rsv(fs_info);
8203 		goto again;
8204 	}
8205 
8206 	if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
8207 		static DEFINE_RATELIMIT_STATE(_rs,
8208 				DEFAULT_RATELIMIT_INTERVAL * 10,
8209 				/*DEFAULT_RATELIMIT_BURST*/ 1);
8210 		if (__ratelimit(&_rs))
8211 			WARN(1, KERN_DEBUG
8212 				"BTRFS: block rsv returned %d\n", ret);
8213 	}
8214 try_reserve:
8215 	ret = reserve_metadata_bytes(root, block_rsv, blocksize,
8216 				     BTRFS_RESERVE_NO_FLUSH);
8217 	if (!ret)
8218 		return block_rsv;
8219 	/*
8220 	 * If we couldn't reserve metadata bytes try and use some from
8221 	 * the global reserve if its space type is the same as the global
8222 	 * reservation.
8223 	 */
8224 	if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
8225 	    block_rsv->space_info == global_rsv->space_info) {
8226 		ret = block_rsv_use_bytes(global_rsv, blocksize);
8227 		if (!ret)
8228 			return global_rsv;
8229 	}
8230 	return ERR_PTR(ret);
8231 }
8232 
unuse_block_rsv(struct btrfs_fs_info * fs_info,struct btrfs_block_rsv * block_rsv,u32 blocksize)8233 static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
8234 			    struct btrfs_block_rsv *block_rsv, u32 blocksize)
8235 {
8236 	block_rsv_add_bytes(block_rsv, blocksize, 0);
8237 	block_rsv_release_bytes(fs_info, block_rsv, NULL, 0, NULL);
8238 }
8239 
8240 /*
8241  * finds a free extent and does all the dirty work required for allocation
8242  * returns the tree buffer or an ERR_PTR on error.
8243  */
btrfs_alloc_tree_block(struct btrfs_trans_handle * trans,struct btrfs_root * root,u64 parent,u64 root_objectid,const struct btrfs_disk_key * key,int level,u64 hint,u64 empty_size)8244 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
8245 					     struct btrfs_root *root,
8246 					     u64 parent, u64 root_objectid,
8247 					     const struct btrfs_disk_key *key,
8248 					     int level, u64 hint,
8249 					     u64 empty_size)
8250 {
8251 	struct btrfs_fs_info *fs_info = root->fs_info;
8252 	struct btrfs_key ins;
8253 	struct btrfs_block_rsv *block_rsv;
8254 	struct extent_buffer *buf;
8255 	struct btrfs_delayed_extent_op *extent_op;
8256 	u64 flags = 0;
8257 	int ret;
8258 	u32 blocksize = fs_info->nodesize;
8259 	bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
8260 
8261 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8262 	if (btrfs_is_testing(fs_info)) {
8263 		buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
8264 					    level, root_objectid);
8265 		if (!IS_ERR(buf))
8266 			root->alloc_bytenr += blocksize;
8267 		return buf;
8268 	}
8269 #endif
8270 
8271 	block_rsv = use_block_rsv(trans, root, blocksize);
8272 	if (IS_ERR(block_rsv))
8273 		return ERR_CAST(block_rsv);
8274 
8275 	ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
8276 				   empty_size, hint, &ins, 0, 0);
8277 	if (ret)
8278 		goto out_unuse;
8279 
8280 	buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
8281 				    root_objectid);
8282 	if (IS_ERR(buf)) {
8283 		ret = PTR_ERR(buf);
8284 		goto out_free_reserved;
8285 	}
8286 
8287 	if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
8288 		if (parent == 0)
8289 			parent = ins.objectid;
8290 		flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
8291 	} else
8292 		BUG_ON(parent > 0);
8293 
8294 	if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
8295 		extent_op = btrfs_alloc_delayed_extent_op();
8296 		if (!extent_op) {
8297 			ret = -ENOMEM;
8298 			goto out_free_buf;
8299 		}
8300 		if (key)
8301 			memcpy(&extent_op->key, key, sizeof(extent_op->key));
8302 		else
8303 			memset(&extent_op->key, 0, sizeof(extent_op->key));
8304 		extent_op->flags_to_set = flags;
8305 		extent_op->update_key = skinny_metadata ? false : true;
8306 		extent_op->update_flags = true;
8307 		extent_op->is_data = false;
8308 		extent_op->level = level;
8309 
8310 		btrfs_ref_tree_mod(root, ins.objectid, ins.offset, parent,
8311 				   root_objectid, level, 0,
8312 				   BTRFS_ADD_DELAYED_EXTENT);
8313 		ret = btrfs_add_delayed_tree_ref(trans, ins.objectid,
8314 						 ins.offset, parent,
8315 						 root_objectid, level,
8316 						 BTRFS_ADD_DELAYED_EXTENT,
8317 						 extent_op, NULL, NULL);
8318 		if (ret)
8319 			goto out_free_delayed;
8320 	}
8321 	return buf;
8322 
8323 out_free_delayed:
8324 	btrfs_free_delayed_extent_op(extent_op);
8325 out_free_buf:
8326 	free_extent_buffer(buf);
8327 out_free_reserved:
8328 	btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
8329 out_unuse:
8330 	unuse_block_rsv(fs_info, block_rsv, blocksize);
8331 	return ERR_PTR(ret);
8332 }
8333 
8334 struct walk_control {
8335 	u64 refs[BTRFS_MAX_LEVEL];
8336 	u64 flags[BTRFS_MAX_LEVEL];
8337 	struct btrfs_key update_progress;
8338 	int stage;
8339 	int level;
8340 	int shared_level;
8341 	int update_ref;
8342 	int keep_locks;
8343 	int reada_slot;
8344 	int reada_count;
8345 };
8346 
8347 #define DROP_REFERENCE	1
8348 #define UPDATE_BACKREF	2
8349 
reada_walk_down(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct walk_control * wc,struct btrfs_path * path)8350 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
8351 				     struct btrfs_root *root,
8352 				     struct walk_control *wc,
8353 				     struct btrfs_path *path)
8354 {
8355 	struct btrfs_fs_info *fs_info = root->fs_info;
8356 	u64 bytenr;
8357 	u64 generation;
8358 	u64 refs;
8359 	u64 flags;
8360 	u32 nritems;
8361 	struct btrfs_key key;
8362 	struct extent_buffer *eb;
8363 	int ret;
8364 	int slot;
8365 	int nread = 0;
8366 
8367 	if (path->slots[wc->level] < wc->reada_slot) {
8368 		wc->reada_count = wc->reada_count * 2 / 3;
8369 		wc->reada_count = max(wc->reada_count, 2);
8370 	} else {
8371 		wc->reada_count = wc->reada_count * 3 / 2;
8372 		wc->reada_count = min_t(int, wc->reada_count,
8373 					BTRFS_NODEPTRS_PER_BLOCK(fs_info));
8374 	}
8375 
8376 	eb = path->nodes[wc->level];
8377 	nritems = btrfs_header_nritems(eb);
8378 
8379 	for (slot = path->slots[wc->level]; slot < nritems; slot++) {
8380 		if (nread >= wc->reada_count)
8381 			break;
8382 
8383 		cond_resched();
8384 		bytenr = btrfs_node_blockptr(eb, slot);
8385 		generation = btrfs_node_ptr_generation(eb, slot);
8386 
8387 		if (slot == path->slots[wc->level])
8388 			goto reada;
8389 
8390 		if (wc->stage == UPDATE_BACKREF &&
8391 		    generation <= root->root_key.offset)
8392 			continue;
8393 
8394 		/* We don't lock the tree block, it's OK to be racy here */
8395 		ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
8396 					       wc->level - 1, 1, &refs,
8397 					       &flags);
8398 		/* We don't care about errors in readahead. */
8399 		if (ret < 0)
8400 			continue;
8401 		BUG_ON(refs == 0);
8402 
8403 		if (wc->stage == DROP_REFERENCE) {
8404 			if (refs == 1)
8405 				goto reada;
8406 
8407 			if (wc->level == 1 &&
8408 			    (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8409 				continue;
8410 			if (!wc->update_ref ||
8411 			    generation <= root->root_key.offset)
8412 				continue;
8413 			btrfs_node_key_to_cpu(eb, &key, slot);
8414 			ret = btrfs_comp_cpu_keys(&key,
8415 						  &wc->update_progress);
8416 			if (ret < 0)
8417 				continue;
8418 		} else {
8419 			if (wc->level == 1 &&
8420 			    (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8421 				continue;
8422 		}
8423 reada:
8424 		readahead_tree_block(fs_info, bytenr);
8425 		nread++;
8426 	}
8427 	wc->reada_slot = slot;
8428 }
8429 
8430 /*
8431  * helper to process tree block while walking down the tree.
8432  *
8433  * when wc->stage == UPDATE_BACKREF, this function updates
8434  * back refs for pointers in the block.
8435  *
8436  * NOTE: return value 1 means we should stop walking down.
8437  */
walk_down_proc(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct walk_control * wc,int lookup_info)8438 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
8439 				   struct btrfs_root *root,
8440 				   struct btrfs_path *path,
8441 				   struct walk_control *wc, int lookup_info)
8442 {
8443 	struct btrfs_fs_info *fs_info = root->fs_info;
8444 	int level = wc->level;
8445 	struct extent_buffer *eb = path->nodes[level];
8446 	u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8447 	int ret;
8448 
8449 	if (wc->stage == UPDATE_BACKREF &&
8450 	    btrfs_header_owner(eb) != root->root_key.objectid)
8451 		return 1;
8452 
8453 	/*
8454 	 * when reference count of tree block is 1, it won't increase
8455 	 * again. once full backref flag is set, we never clear it.
8456 	 */
8457 	if (lookup_info &&
8458 	    ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
8459 	     (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
8460 		BUG_ON(!path->locks[level]);
8461 		ret = btrfs_lookup_extent_info(trans, fs_info,
8462 					       eb->start, level, 1,
8463 					       &wc->refs[level],
8464 					       &wc->flags[level]);
8465 		BUG_ON(ret == -ENOMEM);
8466 		if (ret)
8467 			return ret;
8468 		BUG_ON(wc->refs[level] == 0);
8469 	}
8470 
8471 	if (wc->stage == DROP_REFERENCE) {
8472 		if (wc->refs[level] > 1)
8473 			return 1;
8474 
8475 		if (path->locks[level] && !wc->keep_locks) {
8476 			btrfs_tree_unlock_rw(eb, path->locks[level]);
8477 			path->locks[level] = 0;
8478 		}
8479 		return 0;
8480 	}
8481 
8482 	/* wc->stage == UPDATE_BACKREF */
8483 	if (!(wc->flags[level] & flag)) {
8484 		BUG_ON(!path->locks[level]);
8485 		ret = btrfs_inc_ref(trans, root, eb, 1);
8486 		BUG_ON(ret); /* -ENOMEM */
8487 		ret = btrfs_dec_ref(trans, root, eb, 0);
8488 		BUG_ON(ret); /* -ENOMEM */
8489 		ret = btrfs_set_disk_extent_flags(trans, fs_info, eb->start,
8490 						  eb->len, flag,
8491 						  btrfs_header_level(eb), 0);
8492 		BUG_ON(ret); /* -ENOMEM */
8493 		wc->flags[level] |= flag;
8494 	}
8495 
8496 	/*
8497 	 * the block is shared by multiple trees, so it's not good to
8498 	 * keep the tree lock
8499 	 */
8500 	if (path->locks[level] && level > 0) {
8501 		btrfs_tree_unlock_rw(eb, path->locks[level]);
8502 		path->locks[level] = 0;
8503 	}
8504 	return 0;
8505 }
8506 
8507 /*
8508  * helper to process tree block pointer.
8509  *
8510  * when wc->stage == DROP_REFERENCE, this function checks
8511  * reference count of the block pointed to. if the block
8512  * is shared and we need update back refs for the subtree
8513  * rooted at the block, this function changes wc->stage to
8514  * UPDATE_BACKREF. if the block is shared and there is no
8515  * need to update back, this function drops the reference
8516  * to the block.
8517  *
8518  * NOTE: return value 1 means we should stop walking down.
8519  */
do_walk_down(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct walk_control * wc,int * lookup_info)8520 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
8521 				 struct btrfs_root *root,
8522 				 struct btrfs_path *path,
8523 				 struct walk_control *wc, int *lookup_info)
8524 {
8525 	struct btrfs_fs_info *fs_info = root->fs_info;
8526 	u64 bytenr;
8527 	u64 generation;
8528 	u64 parent;
8529 	u32 blocksize;
8530 	struct btrfs_key key;
8531 	struct btrfs_key first_key;
8532 	struct extent_buffer *next;
8533 	int level = wc->level;
8534 	int reada = 0;
8535 	int ret = 0;
8536 	bool need_account = false;
8537 
8538 	generation = btrfs_node_ptr_generation(path->nodes[level],
8539 					       path->slots[level]);
8540 	/*
8541 	 * if the lower level block was created before the snapshot
8542 	 * was created, we know there is no need to update back refs
8543 	 * for the subtree
8544 	 */
8545 	if (wc->stage == UPDATE_BACKREF &&
8546 	    generation <= root->root_key.offset) {
8547 		*lookup_info = 1;
8548 		return 1;
8549 	}
8550 
8551 	bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
8552 	btrfs_node_key_to_cpu(path->nodes[level], &first_key,
8553 			      path->slots[level]);
8554 	blocksize = fs_info->nodesize;
8555 
8556 	next = find_extent_buffer(fs_info, bytenr);
8557 	if (!next) {
8558 		next = btrfs_find_create_tree_block(fs_info, bytenr);
8559 		if (IS_ERR(next))
8560 			return PTR_ERR(next);
8561 
8562 		btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
8563 					       level - 1);
8564 		reada = 1;
8565 	}
8566 	btrfs_tree_lock(next);
8567 	btrfs_set_lock_blocking(next);
8568 
8569 	ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
8570 				       &wc->refs[level - 1],
8571 				       &wc->flags[level - 1]);
8572 	if (ret < 0)
8573 		goto out_unlock;
8574 
8575 	if (unlikely(wc->refs[level - 1] == 0)) {
8576 		btrfs_err(fs_info, "Missing references.");
8577 		ret = -EIO;
8578 		goto out_unlock;
8579 	}
8580 	*lookup_info = 0;
8581 
8582 	if (wc->stage == DROP_REFERENCE) {
8583 		if (wc->refs[level - 1] > 1) {
8584 			need_account = true;
8585 			if (level == 1 &&
8586 			    (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8587 				goto skip;
8588 
8589 			if (!wc->update_ref ||
8590 			    generation <= root->root_key.offset)
8591 				goto skip;
8592 
8593 			btrfs_node_key_to_cpu(path->nodes[level], &key,
8594 					      path->slots[level]);
8595 			ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
8596 			if (ret < 0)
8597 				goto skip;
8598 
8599 			wc->stage = UPDATE_BACKREF;
8600 			wc->shared_level = level - 1;
8601 		}
8602 	} else {
8603 		if (level == 1 &&
8604 		    (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8605 			goto skip;
8606 	}
8607 
8608 	if (!btrfs_buffer_uptodate(next, generation, 0)) {
8609 		btrfs_tree_unlock(next);
8610 		free_extent_buffer(next);
8611 		next = NULL;
8612 		*lookup_info = 1;
8613 	}
8614 
8615 	if (!next) {
8616 		if (reada && level == 1)
8617 			reada_walk_down(trans, root, wc, path);
8618 		next = read_tree_block(fs_info, bytenr, generation, level - 1,
8619 				       &first_key);
8620 		if (IS_ERR(next)) {
8621 			return PTR_ERR(next);
8622 		} else if (!extent_buffer_uptodate(next)) {
8623 			free_extent_buffer(next);
8624 			return -EIO;
8625 		}
8626 		btrfs_tree_lock(next);
8627 		btrfs_set_lock_blocking(next);
8628 	}
8629 
8630 	level--;
8631 	ASSERT(level == btrfs_header_level(next));
8632 	if (level != btrfs_header_level(next)) {
8633 		btrfs_err(root->fs_info, "mismatched level");
8634 		ret = -EIO;
8635 		goto out_unlock;
8636 	}
8637 	path->nodes[level] = next;
8638 	path->slots[level] = 0;
8639 	path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8640 	wc->level = level;
8641 	if (wc->level == 1)
8642 		wc->reada_slot = 0;
8643 	return 0;
8644 skip:
8645 	wc->refs[level - 1] = 0;
8646 	wc->flags[level - 1] = 0;
8647 	if (wc->stage == DROP_REFERENCE) {
8648 		if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
8649 			parent = path->nodes[level]->start;
8650 		} else {
8651 			ASSERT(root->root_key.objectid ==
8652 			       btrfs_header_owner(path->nodes[level]));
8653 			if (root->root_key.objectid !=
8654 			    btrfs_header_owner(path->nodes[level])) {
8655 				btrfs_err(root->fs_info,
8656 						"mismatched block owner");
8657 				ret = -EIO;
8658 				goto out_unlock;
8659 			}
8660 			parent = 0;
8661 		}
8662 
8663 		if (need_account) {
8664 			ret = btrfs_qgroup_trace_subtree(trans, next,
8665 							 generation, level - 1);
8666 			if (ret) {
8667 				btrfs_err_rl(fs_info,
8668 					     "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
8669 					     ret);
8670 			}
8671 		}
8672 		ret = btrfs_free_extent(trans, root, bytenr, blocksize,
8673 					parent, root->root_key.objectid,
8674 					level - 1, 0);
8675 		if (ret)
8676 			goto out_unlock;
8677 	}
8678 
8679 	*lookup_info = 1;
8680 	ret = 1;
8681 
8682 out_unlock:
8683 	btrfs_tree_unlock(next);
8684 	free_extent_buffer(next);
8685 
8686 	return ret;
8687 }
8688 
8689 /*
8690  * helper to process tree block while walking up the tree.
8691  *
8692  * when wc->stage == DROP_REFERENCE, this function drops
8693  * reference count on the block.
8694  *
8695  * when wc->stage == UPDATE_BACKREF, this function changes
8696  * wc->stage back to DROP_REFERENCE if we changed wc->stage
8697  * to UPDATE_BACKREF previously while processing the block.
8698  *
8699  * NOTE: return value 1 means we should stop walking up.
8700  */
walk_up_proc(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct walk_control * wc)8701 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
8702 				 struct btrfs_root *root,
8703 				 struct btrfs_path *path,
8704 				 struct walk_control *wc)
8705 {
8706 	struct btrfs_fs_info *fs_info = root->fs_info;
8707 	int ret;
8708 	int level = wc->level;
8709 	struct extent_buffer *eb = path->nodes[level];
8710 	u64 parent = 0;
8711 
8712 	if (wc->stage == UPDATE_BACKREF) {
8713 		BUG_ON(wc->shared_level < level);
8714 		if (level < wc->shared_level)
8715 			goto out;
8716 
8717 		ret = find_next_key(path, level + 1, &wc->update_progress);
8718 		if (ret > 0)
8719 			wc->update_ref = 0;
8720 
8721 		wc->stage = DROP_REFERENCE;
8722 		wc->shared_level = -1;
8723 		path->slots[level] = 0;
8724 
8725 		/*
8726 		 * check reference count again if the block isn't locked.
8727 		 * we should start walking down the tree again if reference
8728 		 * count is one.
8729 		 */
8730 		if (!path->locks[level]) {
8731 			BUG_ON(level == 0);
8732 			btrfs_tree_lock(eb);
8733 			btrfs_set_lock_blocking(eb);
8734 			path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8735 
8736 			ret = btrfs_lookup_extent_info(trans, fs_info,
8737 						       eb->start, level, 1,
8738 						       &wc->refs[level],
8739 						       &wc->flags[level]);
8740 			if (ret < 0) {
8741 				btrfs_tree_unlock_rw(eb, path->locks[level]);
8742 				path->locks[level] = 0;
8743 				return ret;
8744 			}
8745 			BUG_ON(wc->refs[level] == 0);
8746 			if (wc->refs[level] == 1) {
8747 				btrfs_tree_unlock_rw(eb, path->locks[level]);
8748 				path->locks[level] = 0;
8749 				return 1;
8750 			}
8751 		}
8752 	}
8753 
8754 	/* wc->stage == DROP_REFERENCE */
8755 	BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
8756 
8757 	if (wc->refs[level] == 1) {
8758 		if (level == 0) {
8759 			if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8760 				ret = btrfs_dec_ref(trans, root, eb, 1);
8761 			else
8762 				ret = btrfs_dec_ref(trans, root, eb, 0);
8763 			BUG_ON(ret); /* -ENOMEM */
8764 			ret = btrfs_qgroup_trace_leaf_items(trans, eb);
8765 			if (ret) {
8766 				btrfs_err_rl(fs_info,
8767 					     "error %d accounting leaf items. Quota is out of sync, rescan required.",
8768 					     ret);
8769 			}
8770 		}
8771 		/* make block locked assertion in clean_tree_block happy */
8772 		if (!path->locks[level] &&
8773 		    btrfs_header_generation(eb) == trans->transid) {
8774 			btrfs_tree_lock(eb);
8775 			btrfs_set_lock_blocking(eb);
8776 			path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8777 		}
8778 		clean_tree_block(fs_info, eb);
8779 	}
8780 
8781 	if (eb == root->node) {
8782 		if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8783 			parent = eb->start;
8784 		else if (root->root_key.objectid != btrfs_header_owner(eb))
8785 			goto owner_mismatch;
8786 	} else {
8787 		if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8788 			parent = path->nodes[level + 1]->start;
8789 		else if (root->root_key.objectid !=
8790 			 btrfs_header_owner(path->nodes[level + 1]))
8791 			goto owner_mismatch;
8792 	}
8793 
8794 	btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
8795 out:
8796 	wc->refs[level] = 0;
8797 	wc->flags[level] = 0;
8798 	return 0;
8799 
8800 owner_mismatch:
8801 	btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
8802 		     btrfs_header_owner(eb), root->root_key.objectid);
8803 	return -EUCLEAN;
8804 }
8805 
walk_down_tree(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct walk_control * wc)8806 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
8807 				   struct btrfs_root *root,
8808 				   struct btrfs_path *path,
8809 				   struct walk_control *wc)
8810 {
8811 	int level = wc->level;
8812 	int lookup_info = 1;
8813 	int ret;
8814 
8815 	while (level >= 0) {
8816 		ret = walk_down_proc(trans, root, path, wc, lookup_info);
8817 		if (ret > 0)
8818 			break;
8819 
8820 		if (level == 0)
8821 			break;
8822 
8823 		if (path->slots[level] >=
8824 		    btrfs_header_nritems(path->nodes[level]))
8825 			break;
8826 
8827 		ret = do_walk_down(trans, root, path, wc, &lookup_info);
8828 		if (ret > 0) {
8829 			path->slots[level]++;
8830 			continue;
8831 		} else if (ret < 0)
8832 			return ret;
8833 		level = wc->level;
8834 	}
8835 	return 0;
8836 }
8837 
walk_up_tree(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct walk_control * wc,int max_level)8838 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
8839 				 struct btrfs_root *root,
8840 				 struct btrfs_path *path,
8841 				 struct walk_control *wc, int max_level)
8842 {
8843 	int level = wc->level;
8844 	int ret;
8845 
8846 	path->slots[level] = btrfs_header_nritems(path->nodes[level]);
8847 	while (level < max_level && path->nodes[level]) {
8848 		wc->level = level;
8849 		if (path->slots[level] + 1 <
8850 		    btrfs_header_nritems(path->nodes[level])) {
8851 			path->slots[level]++;
8852 			return 0;
8853 		} else {
8854 			ret = walk_up_proc(trans, root, path, wc);
8855 			if (ret > 0)
8856 				return 0;
8857 			if (ret < 0)
8858 				return ret;
8859 
8860 			if (path->locks[level]) {
8861 				btrfs_tree_unlock_rw(path->nodes[level],
8862 						     path->locks[level]);
8863 				path->locks[level] = 0;
8864 			}
8865 			free_extent_buffer(path->nodes[level]);
8866 			path->nodes[level] = NULL;
8867 			level++;
8868 		}
8869 	}
8870 	return 1;
8871 }
8872 
8873 /*
8874  * drop a subvolume tree.
8875  *
8876  * this function traverses the tree freeing any blocks that only
8877  * referenced by the tree.
8878  *
8879  * when a shared tree block is found. this function decreases its
8880  * reference count by one. if update_ref is true, this function
8881  * also make sure backrefs for the shared block and all lower level
8882  * blocks are properly updated.
8883  *
8884  * If called with for_reloc == 0, may exit early with -EAGAIN
8885  */
btrfs_drop_snapshot(struct btrfs_root * root,struct btrfs_block_rsv * block_rsv,int update_ref,int for_reloc)8886 int btrfs_drop_snapshot(struct btrfs_root *root,
8887 			 struct btrfs_block_rsv *block_rsv, int update_ref,
8888 			 int for_reloc)
8889 {
8890 	struct btrfs_fs_info *fs_info = root->fs_info;
8891 	struct btrfs_path *path;
8892 	struct btrfs_trans_handle *trans;
8893 	struct btrfs_root *tree_root = fs_info->tree_root;
8894 	struct btrfs_root_item *root_item = &root->root_item;
8895 	struct walk_control *wc;
8896 	struct btrfs_key key;
8897 	int err = 0;
8898 	int ret;
8899 	int level;
8900 	bool root_dropped = false;
8901 
8902 	btrfs_debug(fs_info, "Drop subvolume %llu", root->objectid);
8903 
8904 	path = btrfs_alloc_path();
8905 	if (!path) {
8906 		err = -ENOMEM;
8907 		goto out;
8908 	}
8909 
8910 	wc = kzalloc(sizeof(*wc), GFP_NOFS);
8911 	if (!wc) {
8912 		btrfs_free_path(path);
8913 		err = -ENOMEM;
8914 		goto out;
8915 	}
8916 
8917 	trans = btrfs_start_transaction(tree_root, 0);
8918 	if (IS_ERR(trans)) {
8919 		err = PTR_ERR(trans);
8920 		goto out_free;
8921 	}
8922 
8923 	err = btrfs_run_delayed_items(trans);
8924 	if (err)
8925 		goto out_end_trans;
8926 
8927 	if (block_rsv)
8928 		trans->block_rsv = block_rsv;
8929 
8930 	if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
8931 		level = btrfs_header_level(root->node);
8932 		path->nodes[level] = btrfs_lock_root_node(root);
8933 		btrfs_set_lock_blocking(path->nodes[level]);
8934 		path->slots[level] = 0;
8935 		path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8936 		memset(&wc->update_progress, 0,
8937 		       sizeof(wc->update_progress));
8938 	} else {
8939 		btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
8940 		memcpy(&wc->update_progress, &key,
8941 		       sizeof(wc->update_progress));
8942 
8943 		level = root_item->drop_level;
8944 		BUG_ON(level == 0);
8945 		path->lowest_level = level;
8946 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
8947 		path->lowest_level = 0;
8948 		if (ret < 0) {
8949 			err = ret;
8950 			goto out_end_trans;
8951 		}
8952 		WARN_ON(ret > 0);
8953 
8954 		/*
8955 		 * unlock our path, this is safe because only this
8956 		 * function is allowed to delete this snapshot
8957 		 */
8958 		btrfs_unlock_up_safe(path, 0);
8959 
8960 		level = btrfs_header_level(root->node);
8961 		while (1) {
8962 			btrfs_tree_lock(path->nodes[level]);
8963 			btrfs_set_lock_blocking(path->nodes[level]);
8964 			path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8965 
8966 			ret = btrfs_lookup_extent_info(trans, fs_info,
8967 						path->nodes[level]->start,
8968 						level, 1, &wc->refs[level],
8969 						&wc->flags[level]);
8970 			if (ret < 0) {
8971 				err = ret;
8972 				goto out_end_trans;
8973 			}
8974 			BUG_ON(wc->refs[level] == 0);
8975 
8976 			if (level == root_item->drop_level)
8977 				break;
8978 
8979 			btrfs_tree_unlock(path->nodes[level]);
8980 			path->locks[level] = 0;
8981 			WARN_ON(wc->refs[level] != 1);
8982 			level--;
8983 		}
8984 	}
8985 
8986 	wc->level = level;
8987 	wc->shared_level = -1;
8988 	wc->stage = DROP_REFERENCE;
8989 	wc->update_ref = update_ref;
8990 	wc->keep_locks = 0;
8991 	wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
8992 
8993 	while (1) {
8994 
8995 		ret = walk_down_tree(trans, root, path, wc);
8996 		if (ret < 0) {
8997 			err = ret;
8998 			break;
8999 		}
9000 
9001 		ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
9002 		if (ret < 0) {
9003 			err = ret;
9004 			break;
9005 		}
9006 
9007 		if (ret > 0) {
9008 			BUG_ON(wc->stage != DROP_REFERENCE);
9009 			break;
9010 		}
9011 
9012 		if (wc->stage == DROP_REFERENCE) {
9013 			level = wc->level;
9014 			btrfs_node_key(path->nodes[level],
9015 				       &root_item->drop_progress,
9016 				       path->slots[level]);
9017 			root_item->drop_level = level;
9018 		}
9019 
9020 		BUG_ON(wc->level == 0);
9021 		if (btrfs_should_end_transaction(trans) ||
9022 		    (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
9023 			ret = btrfs_update_root(trans, tree_root,
9024 						&root->root_key,
9025 						root_item);
9026 			if (ret) {
9027 				btrfs_abort_transaction(trans, ret);
9028 				err = ret;
9029 				goto out_end_trans;
9030 			}
9031 
9032 			btrfs_end_transaction_throttle(trans);
9033 			if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
9034 				btrfs_debug(fs_info,
9035 					    "drop snapshot early exit");
9036 				err = -EAGAIN;
9037 				goto out_free;
9038 			}
9039 
9040 			trans = btrfs_start_transaction(tree_root, 0);
9041 			if (IS_ERR(trans)) {
9042 				err = PTR_ERR(trans);
9043 				goto out_free;
9044 			}
9045 			if (block_rsv)
9046 				trans->block_rsv = block_rsv;
9047 		}
9048 	}
9049 	btrfs_release_path(path);
9050 	if (err)
9051 		goto out_end_trans;
9052 
9053 	ret = btrfs_del_root(trans, &root->root_key);
9054 	if (ret) {
9055 		btrfs_abort_transaction(trans, ret);
9056 		err = ret;
9057 		goto out_end_trans;
9058 	}
9059 
9060 	if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
9061 		ret = btrfs_find_root(tree_root, &root->root_key, path,
9062 				      NULL, NULL);
9063 		if (ret < 0) {
9064 			btrfs_abort_transaction(trans, ret);
9065 			err = ret;
9066 			goto out_end_trans;
9067 		} else if (ret > 0) {
9068 			/* if we fail to delete the orphan item this time
9069 			 * around, it'll get picked up the next time.
9070 			 *
9071 			 * The most common failure here is just -ENOENT.
9072 			 */
9073 			btrfs_del_orphan_item(trans, tree_root,
9074 					      root->root_key.objectid);
9075 		}
9076 	}
9077 
9078 	if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
9079 		btrfs_add_dropped_root(trans, root);
9080 	} else {
9081 		free_extent_buffer(root->node);
9082 		free_extent_buffer(root->commit_root);
9083 		btrfs_put_fs_root(root);
9084 	}
9085 	root_dropped = true;
9086 out_end_trans:
9087 	btrfs_end_transaction_throttle(trans);
9088 out_free:
9089 	kfree(wc);
9090 	btrfs_free_path(path);
9091 out:
9092 	/*
9093 	 * So if we need to stop dropping the snapshot for whatever reason we
9094 	 * need to make sure to add it back to the dead root list so that we
9095 	 * keep trying to do the work later.  This also cleans up roots if we
9096 	 * don't have it in the radix (like when we recover after a power fail
9097 	 * or unmount) so we don't leak memory.
9098 	 */
9099 	if (!for_reloc && !root_dropped)
9100 		btrfs_add_dead_root(root);
9101 	return err;
9102 }
9103 
9104 /*
9105  * drop subtree rooted at tree block 'node'.
9106  *
9107  * NOTE: this function will unlock and release tree block 'node'
9108  * only used by relocation code
9109  */
btrfs_drop_subtree(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct extent_buffer * node,struct extent_buffer * parent)9110 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
9111 			struct btrfs_root *root,
9112 			struct extent_buffer *node,
9113 			struct extent_buffer *parent)
9114 {
9115 	struct btrfs_fs_info *fs_info = root->fs_info;
9116 	struct btrfs_path *path;
9117 	struct walk_control *wc;
9118 	int level;
9119 	int parent_level;
9120 	int ret = 0;
9121 	int wret;
9122 
9123 	BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
9124 
9125 	path = btrfs_alloc_path();
9126 	if (!path)
9127 		return -ENOMEM;
9128 
9129 	wc = kzalloc(sizeof(*wc), GFP_NOFS);
9130 	if (!wc) {
9131 		btrfs_free_path(path);
9132 		return -ENOMEM;
9133 	}
9134 
9135 	btrfs_assert_tree_locked(parent);
9136 	parent_level = btrfs_header_level(parent);
9137 	extent_buffer_get(parent);
9138 	path->nodes[parent_level] = parent;
9139 	path->slots[parent_level] = btrfs_header_nritems(parent);
9140 
9141 	btrfs_assert_tree_locked(node);
9142 	level = btrfs_header_level(node);
9143 	path->nodes[level] = node;
9144 	path->slots[level] = 0;
9145 	path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9146 
9147 	wc->refs[parent_level] = 1;
9148 	wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
9149 	wc->level = level;
9150 	wc->shared_level = -1;
9151 	wc->stage = DROP_REFERENCE;
9152 	wc->update_ref = 0;
9153 	wc->keep_locks = 1;
9154 	wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
9155 
9156 	while (1) {
9157 		wret = walk_down_tree(trans, root, path, wc);
9158 		if (wret < 0) {
9159 			ret = wret;
9160 			break;
9161 		}
9162 
9163 		wret = walk_up_tree(trans, root, path, wc, parent_level);
9164 		if (wret < 0)
9165 			ret = wret;
9166 		if (wret != 0)
9167 			break;
9168 	}
9169 
9170 	kfree(wc);
9171 	btrfs_free_path(path);
9172 	return ret;
9173 }
9174 
update_block_group_flags(struct btrfs_fs_info * fs_info,u64 flags)9175 static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
9176 {
9177 	u64 num_devices;
9178 	u64 stripped;
9179 
9180 	/*
9181 	 * if restripe for this chunk_type is on pick target profile and
9182 	 * return, otherwise do the usual balance
9183 	 */
9184 	stripped = get_restripe_target(fs_info, flags);
9185 	if (stripped)
9186 		return extended_to_chunk(stripped);
9187 
9188 	num_devices = fs_info->fs_devices->rw_devices;
9189 
9190 	stripped = BTRFS_BLOCK_GROUP_RAID0 |
9191 		BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
9192 		BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
9193 
9194 	if (num_devices == 1) {
9195 		stripped |= BTRFS_BLOCK_GROUP_DUP;
9196 		stripped = flags & ~stripped;
9197 
9198 		/* turn raid0 into single device chunks */
9199 		if (flags & BTRFS_BLOCK_GROUP_RAID0)
9200 			return stripped;
9201 
9202 		/* turn mirroring into duplication */
9203 		if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
9204 			     BTRFS_BLOCK_GROUP_RAID10))
9205 			return stripped | BTRFS_BLOCK_GROUP_DUP;
9206 	} else {
9207 		/* they already had raid on here, just return */
9208 		if (flags & stripped)
9209 			return flags;
9210 
9211 		stripped |= BTRFS_BLOCK_GROUP_DUP;
9212 		stripped = flags & ~stripped;
9213 
9214 		/* switch duplicated blocks with raid1 */
9215 		if (flags & BTRFS_BLOCK_GROUP_DUP)
9216 			return stripped | BTRFS_BLOCK_GROUP_RAID1;
9217 
9218 		/* this is drive concat, leave it alone */
9219 	}
9220 
9221 	return flags;
9222 }
9223 
inc_block_group_ro(struct btrfs_block_group_cache * cache,int force)9224 static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
9225 {
9226 	struct btrfs_space_info *sinfo = cache->space_info;
9227 	u64 num_bytes;
9228 	u64 min_allocable_bytes;
9229 	int ret = -ENOSPC;
9230 
9231 	/*
9232 	 * We need some metadata space and system metadata space for
9233 	 * allocating chunks in some corner cases until we force to set
9234 	 * it to be readonly.
9235 	 */
9236 	if ((sinfo->flags &
9237 	     (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
9238 	    !force)
9239 		min_allocable_bytes = SZ_1M;
9240 	else
9241 		min_allocable_bytes = 0;
9242 
9243 	spin_lock(&sinfo->lock);
9244 	spin_lock(&cache->lock);
9245 
9246 	if (cache->ro) {
9247 		cache->ro++;
9248 		ret = 0;
9249 		goto out;
9250 	}
9251 
9252 	num_bytes = cache->key.offset - cache->reserved - cache->pinned -
9253 		    cache->bytes_super - btrfs_block_group_used(&cache->item);
9254 
9255 	if (btrfs_space_info_used(sinfo, true) + num_bytes +
9256 	    min_allocable_bytes <= sinfo->total_bytes) {
9257 		sinfo->bytes_readonly += num_bytes;
9258 		cache->ro++;
9259 		list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
9260 		ret = 0;
9261 	}
9262 out:
9263 	spin_unlock(&cache->lock);
9264 	spin_unlock(&sinfo->lock);
9265 	return ret;
9266 }
9267 
btrfs_inc_block_group_ro(struct btrfs_block_group_cache * cache)9268 int btrfs_inc_block_group_ro(struct btrfs_block_group_cache *cache)
9269 
9270 {
9271 	struct btrfs_fs_info *fs_info = cache->fs_info;
9272 	struct btrfs_trans_handle *trans;
9273 	u64 alloc_flags;
9274 	int ret;
9275 
9276 again:
9277 	trans = btrfs_join_transaction(fs_info->extent_root);
9278 	if (IS_ERR(trans))
9279 		return PTR_ERR(trans);
9280 
9281 	/*
9282 	 * we're not allowed to set block groups readonly after the dirty
9283 	 * block groups cache has started writing.  If it already started,
9284 	 * back off and let this transaction commit
9285 	 */
9286 	mutex_lock(&fs_info->ro_block_group_mutex);
9287 	if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
9288 		u64 transid = trans->transid;
9289 
9290 		mutex_unlock(&fs_info->ro_block_group_mutex);
9291 		btrfs_end_transaction(trans);
9292 
9293 		ret = btrfs_wait_for_commit(fs_info, transid);
9294 		if (ret)
9295 			return ret;
9296 		goto again;
9297 	}
9298 
9299 	/*
9300 	 * if we are changing raid levels, try to allocate a corresponding
9301 	 * block group with the new raid level.
9302 	 */
9303 	alloc_flags = update_block_group_flags(fs_info, cache->flags);
9304 	if (alloc_flags != cache->flags) {
9305 		ret = do_chunk_alloc(trans, alloc_flags,
9306 				     CHUNK_ALLOC_FORCE);
9307 		/*
9308 		 * ENOSPC is allowed here, we may have enough space
9309 		 * already allocated at the new raid level to
9310 		 * carry on
9311 		 */
9312 		if (ret == -ENOSPC)
9313 			ret = 0;
9314 		if (ret < 0)
9315 			goto out;
9316 	}
9317 
9318 	ret = inc_block_group_ro(cache, 0);
9319 	if (!ret)
9320 		goto out;
9321 	alloc_flags = get_alloc_profile(fs_info, cache->space_info->flags);
9322 	ret = do_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
9323 	if (ret < 0)
9324 		goto out;
9325 	ret = inc_block_group_ro(cache, 0);
9326 out:
9327 	if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
9328 		alloc_flags = update_block_group_flags(fs_info, cache->flags);
9329 		mutex_lock(&fs_info->chunk_mutex);
9330 		check_system_chunk(trans, alloc_flags);
9331 		mutex_unlock(&fs_info->chunk_mutex);
9332 	}
9333 	mutex_unlock(&fs_info->ro_block_group_mutex);
9334 
9335 	btrfs_end_transaction(trans);
9336 	return ret;
9337 }
9338 
btrfs_force_chunk_alloc(struct btrfs_trans_handle * trans,u64 type)9339 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
9340 {
9341 	u64 alloc_flags = get_alloc_profile(trans->fs_info, type);
9342 
9343 	return do_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
9344 }
9345 
9346 /*
9347  * helper to account the unused space of all the readonly block group in the
9348  * space_info. takes mirrors into account.
9349  */
btrfs_account_ro_block_groups_free_space(struct btrfs_space_info * sinfo)9350 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
9351 {
9352 	struct btrfs_block_group_cache *block_group;
9353 	u64 free_bytes = 0;
9354 	int factor;
9355 
9356 	/* It's df, we don't care if it's racy */
9357 	if (list_empty(&sinfo->ro_bgs))
9358 		return 0;
9359 
9360 	spin_lock(&sinfo->lock);
9361 	list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
9362 		spin_lock(&block_group->lock);
9363 
9364 		if (!block_group->ro) {
9365 			spin_unlock(&block_group->lock);
9366 			continue;
9367 		}
9368 
9369 		factor = btrfs_bg_type_to_factor(block_group->flags);
9370 		free_bytes += (block_group->key.offset -
9371 			       btrfs_block_group_used(&block_group->item)) *
9372 			       factor;
9373 
9374 		spin_unlock(&block_group->lock);
9375 	}
9376 	spin_unlock(&sinfo->lock);
9377 
9378 	return free_bytes;
9379 }
9380 
btrfs_dec_block_group_ro(struct btrfs_block_group_cache * cache)9381 void btrfs_dec_block_group_ro(struct btrfs_block_group_cache *cache)
9382 {
9383 	struct btrfs_space_info *sinfo = cache->space_info;
9384 	u64 num_bytes;
9385 
9386 	BUG_ON(!cache->ro);
9387 
9388 	spin_lock(&sinfo->lock);
9389 	spin_lock(&cache->lock);
9390 	if (!--cache->ro) {
9391 		num_bytes = cache->key.offset - cache->reserved -
9392 			    cache->pinned - cache->bytes_super -
9393 			    btrfs_block_group_used(&cache->item);
9394 		sinfo->bytes_readonly -= num_bytes;
9395 		list_del_init(&cache->ro_list);
9396 	}
9397 	spin_unlock(&cache->lock);
9398 	spin_unlock(&sinfo->lock);
9399 }
9400 
9401 /*
9402  * checks to see if its even possible to relocate this block group.
9403  *
9404  * @return - -1 if it's not a good idea to relocate this block group, 0 if its
9405  * ok to go ahead and try.
9406  */
btrfs_can_relocate(struct btrfs_fs_info * fs_info,u64 bytenr)9407 int btrfs_can_relocate(struct btrfs_fs_info *fs_info, u64 bytenr)
9408 {
9409 	struct btrfs_root *root = fs_info->extent_root;
9410 	struct btrfs_block_group_cache *block_group;
9411 	struct btrfs_space_info *space_info;
9412 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
9413 	struct btrfs_device *device;
9414 	struct btrfs_trans_handle *trans;
9415 	u64 min_free;
9416 	u64 dev_min = 1;
9417 	u64 dev_nr = 0;
9418 	u64 target;
9419 	int debug;
9420 	int index;
9421 	int full = 0;
9422 	int ret = 0;
9423 
9424 	debug = btrfs_test_opt(fs_info, ENOSPC_DEBUG);
9425 
9426 	block_group = btrfs_lookup_block_group(fs_info, bytenr);
9427 
9428 	/* odd, couldn't find the block group, leave it alone */
9429 	if (!block_group) {
9430 		if (debug)
9431 			btrfs_warn(fs_info,
9432 				   "can't find block group for bytenr %llu",
9433 				   bytenr);
9434 		return -1;
9435 	}
9436 
9437 	min_free = btrfs_block_group_used(&block_group->item);
9438 
9439 	/* no bytes used, we're good */
9440 	if (!min_free)
9441 		goto out;
9442 
9443 	space_info = block_group->space_info;
9444 	spin_lock(&space_info->lock);
9445 
9446 	full = space_info->full;
9447 
9448 	/*
9449 	 * if this is the last block group we have in this space, we can't
9450 	 * relocate it unless we're able to allocate a new chunk below.
9451 	 *
9452 	 * Otherwise, we need to make sure we have room in the space to handle
9453 	 * all of the extents from this block group.  If we can, we're good
9454 	 */
9455 	if ((space_info->total_bytes != block_group->key.offset) &&
9456 	    (btrfs_space_info_used(space_info, false) + min_free <
9457 	     space_info->total_bytes)) {
9458 		spin_unlock(&space_info->lock);
9459 		goto out;
9460 	}
9461 	spin_unlock(&space_info->lock);
9462 
9463 	/*
9464 	 * ok we don't have enough space, but maybe we have free space on our
9465 	 * devices to allocate new chunks for relocation, so loop through our
9466 	 * alloc devices and guess if we have enough space.  if this block
9467 	 * group is going to be restriped, run checks against the target
9468 	 * profile instead of the current one.
9469 	 */
9470 	ret = -1;
9471 
9472 	/*
9473 	 * index:
9474 	 *      0: raid10
9475 	 *      1: raid1
9476 	 *      2: dup
9477 	 *      3: raid0
9478 	 *      4: single
9479 	 */
9480 	target = get_restripe_target(fs_info, block_group->flags);
9481 	if (target) {
9482 		index = btrfs_bg_flags_to_raid_index(extended_to_chunk(target));
9483 	} else {
9484 		/*
9485 		 * this is just a balance, so if we were marked as full
9486 		 * we know there is no space for a new chunk
9487 		 */
9488 		if (full) {
9489 			if (debug)
9490 				btrfs_warn(fs_info,
9491 					   "no space to alloc new chunk for block group %llu",
9492 					   block_group->key.objectid);
9493 			goto out;
9494 		}
9495 
9496 		index = btrfs_bg_flags_to_raid_index(block_group->flags);
9497 	}
9498 
9499 	if (index == BTRFS_RAID_RAID10) {
9500 		dev_min = 4;
9501 		/* Divide by 2 */
9502 		min_free >>= 1;
9503 	} else if (index == BTRFS_RAID_RAID1) {
9504 		dev_min = 2;
9505 	} else if (index == BTRFS_RAID_DUP) {
9506 		/* Multiply by 2 */
9507 		min_free <<= 1;
9508 	} else if (index == BTRFS_RAID_RAID0) {
9509 		dev_min = fs_devices->rw_devices;
9510 		min_free = div64_u64(min_free, dev_min);
9511 	}
9512 
9513 	/* We need to do this so that we can look at pending chunks */
9514 	trans = btrfs_join_transaction(root);
9515 	if (IS_ERR(trans)) {
9516 		ret = PTR_ERR(trans);
9517 		goto out;
9518 	}
9519 
9520 	mutex_lock(&fs_info->chunk_mutex);
9521 	list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
9522 		u64 dev_offset;
9523 
9524 		/*
9525 		 * check to make sure we can actually find a chunk with enough
9526 		 * space to fit our block group in.
9527 		 */
9528 		if (device->total_bytes > device->bytes_used + min_free &&
9529 		    !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
9530 			ret = find_free_dev_extent(trans, device, min_free,
9531 						   &dev_offset, NULL);
9532 			if (!ret)
9533 				dev_nr++;
9534 
9535 			if (dev_nr >= dev_min)
9536 				break;
9537 
9538 			ret = -1;
9539 		}
9540 	}
9541 	if (debug && ret == -1)
9542 		btrfs_warn(fs_info,
9543 			   "no space to allocate a new chunk for block group %llu",
9544 			   block_group->key.objectid);
9545 	mutex_unlock(&fs_info->chunk_mutex);
9546 	btrfs_end_transaction(trans);
9547 out:
9548 	btrfs_put_block_group(block_group);
9549 	return ret;
9550 }
9551 
find_first_block_group(struct btrfs_fs_info * fs_info,struct btrfs_path * path,struct btrfs_key * key)9552 static int find_first_block_group(struct btrfs_fs_info *fs_info,
9553 				  struct btrfs_path *path,
9554 				  struct btrfs_key *key)
9555 {
9556 	struct btrfs_root *root = fs_info->extent_root;
9557 	int ret = 0;
9558 	struct btrfs_key found_key;
9559 	struct extent_buffer *leaf;
9560 	struct btrfs_block_group_item bg;
9561 	u64 flags;
9562 	int slot;
9563 
9564 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
9565 	if (ret < 0)
9566 		goto out;
9567 
9568 	while (1) {
9569 		slot = path->slots[0];
9570 		leaf = path->nodes[0];
9571 		if (slot >= btrfs_header_nritems(leaf)) {
9572 			ret = btrfs_next_leaf(root, path);
9573 			if (ret == 0)
9574 				continue;
9575 			if (ret < 0)
9576 				goto out;
9577 			break;
9578 		}
9579 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
9580 
9581 		if (found_key.objectid >= key->objectid &&
9582 		    found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
9583 			struct extent_map_tree *em_tree;
9584 			struct extent_map *em;
9585 
9586 			em_tree = &root->fs_info->mapping_tree.map_tree;
9587 			read_lock(&em_tree->lock);
9588 			em = lookup_extent_mapping(em_tree, found_key.objectid,
9589 						   found_key.offset);
9590 			read_unlock(&em_tree->lock);
9591 			if (!em) {
9592 				btrfs_err(fs_info,
9593 			"logical %llu len %llu found bg but no related chunk",
9594 					  found_key.objectid, found_key.offset);
9595 				ret = -ENOENT;
9596 			} else if (em->start != found_key.objectid ||
9597 				   em->len != found_key.offset) {
9598 				btrfs_err(fs_info,
9599 		"block group %llu len %llu mismatch with chunk %llu len %llu",
9600 					  found_key.objectid, found_key.offset,
9601 					  em->start, em->len);
9602 				ret = -EUCLEAN;
9603 			} else {
9604 				read_extent_buffer(leaf, &bg,
9605 					btrfs_item_ptr_offset(leaf, slot),
9606 					sizeof(bg));
9607 				flags = btrfs_block_group_flags(&bg) &
9608 					BTRFS_BLOCK_GROUP_TYPE_MASK;
9609 
9610 				if (flags != (em->map_lookup->type &
9611 					      BTRFS_BLOCK_GROUP_TYPE_MASK)) {
9612 					btrfs_err(fs_info,
9613 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
9614 						found_key.objectid,
9615 						found_key.offset, flags,
9616 						(BTRFS_BLOCK_GROUP_TYPE_MASK &
9617 						 em->map_lookup->type));
9618 					ret = -EUCLEAN;
9619 				} else {
9620 					ret = 0;
9621 				}
9622 			}
9623 			free_extent_map(em);
9624 			goto out;
9625 		}
9626 		path->slots[0]++;
9627 	}
9628 out:
9629 	return ret;
9630 }
9631 
btrfs_put_block_group_cache(struct btrfs_fs_info * info)9632 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
9633 {
9634 	struct btrfs_block_group_cache *block_group;
9635 	u64 last = 0;
9636 
9637 	while (1) {
9638 		struct inode *inode;
9639 
9640 		block_group = btrfs_lookup_first_block_group(info, last);
9641 		while (block_group) {
9642 			wait_block_group_cache_done(block_group);
9643 			spin_lock(&block_group->lock);
9644 			if (block_group->iref)
9645 				break;
9646 			spin_unlock(&block_group->lock);
9647 			block_group = next_block_group(info, block_group);
9648 		}
9649 		if (!block_group) {
9650 			if (last == 0)
9651 				break;
9652 			last = 0;
9653 			continue;
9654 		}
9655 
9656 		inode = block_group->inode;
9657 		block_group->iref = 0;
9658 		block_group->inode = NULL;
9659 		spin_unlock(&block_group->lock);
9660 		ASSERT(block_group->io_ctl.inode == NULL);
9661 		iput(inode);
9662 		last = block_group->key.objectid + block_group->key.offset;
9663 		btrfs_put_block_group(block_group);
9664 	}
9665 }
9666 
9667 /*
9668  * Must be called only after stopping all workers, since we could have block
9669  * group caching kthreads running, and therefore they could race with us if we
9670  * freed the block groups before stopping them.
9671  */
btrfs_free_block_groups(struct btrfs_fs_info * info)9672 int btrfs_free_block_groups(struct btrfs_fs_info *info)
9673 {
9674 	struct btrfs_block_group_cache *block_group;
9675 	struct btrfs_space_info *space_info;
9676 	struct btrfs_caching_control *caching_ctl;
9677 	struct rb_node *n;
9678 
9679 	down_write(&info->commit_root_sem);
9680 	while (!list_empty(&info->caching_block_groups)) {
9681 		caching_ctl = list_entry(info->caching_block_groups.next,
9682 					 struct btrfs_caching_control, list);
9683 		list_del(&caching_ctl->list);
9684 		put_caching_control(caching_ctl);
9685 	}
9686 	up_write(&info->commit_root_sem);
9687 
9688 	spin_lock(&info->unused_bgs_lock);
9689 	while (!list_empty(&info->unused_bgs)) {
9690 		block_group = list_first_entry(&info->unused_bgs,
9691 					       struct btrfs_block_group_cache,
9692 					       bg_list);
9693 		list_del_init(&block_group->bg_list);
9694 		btrfs_put_block_group(block_group);
9695 	}
9696 	spin_unlock(&info->unused_bgs_lock);
9697 
9698 	spin_lock(&info->block_group_cache_lock);
9699 	while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
9700 		block_group = rb_entry(n, struct btrfs_block_group_cache,
9701 				       cache_node);
9702 		rb_erase(&block_group->cache_node,
9703 			 &info->block_group_cache_tree);
9704 		RB_CLEAR_NODE(&block_group->cache_node);
9705 		spin_unlock(&info->block_group_cache_lock);
9706 
9707 		down_write(&block_group->space_info->groups_sem);
9708 		list_del(&block_group->list);
9709 		up_write(&block_group->space_info->groups_sem);
9710 
9711 		/*
9712 		 * We haven't cached this block group, which means we could
9713 		 * possibly have excluded extents on this block group.
9714 		 */
9715 		if (block_group->cached == BTRFS_CACHE_NO ||
9716 		    block_group->cached == BTRFS_CACHE_ERROR)
9717 			free_excluded_extents(block_group);
9718 
9719 		btrfs_remove_free_space_cache(block_group);
9720 		ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
9721 		ASSERT(list_empty(&block_group->dirty_list));
9722 		ASSERT(list_empty(&block_group->io_list));
9723 		ASSERT(list_empty(&block_group->bg_list));
9724 		ASSERT(atomic_read(&block_group->count) == 1);
9725 		btrfs_put_block_group(block_group);
9726 
9727 		spin_lock(&info->block_group_cache_lock);
9728 	}
9729 	spin_unlock(&info->block_group_cache_lock);
9730 
9731 	/* now that all the block groups are freed, go through and
9732 	 * free all the space_info structs.  This is only called during
9733 	 * the final stages of unmount, and so we know nobody is
9734 	 * using them.  We call synchronize_rcu() once before we start,
9735 	 * just to be on the safe side.
9736 	 */
9737 	synchronize_rcu();
9738 
9739 	release_global_block_rsv(info);
9740 
9741 	while (!list_empty(&info->space_info)) {
9742 		int i;
9743 
9744 		space_info = list_entry(info->space_info.next,
9745 					struct btrfs_space_info,
9746 					list);
9747 
9748 		/*
9749 		 * Do not hide this behind enospc_debug, this is actually
9750 		 * important and indicates a real bug if this happens.
9751 		 */
9752 		if (WARN_ON(space_info->bytes_pinned > 0 ||
9753 			    space_info->bytes_reserved > 0 ||
9754 			    space_info->bytes_may_use > 0))
9755 			dump_space_info(info, space_info, 0, 0);
9756 		list_del(&space_info->list);
9757 		for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
9758 			struct kobject *kobj;
9759 			kobj = space_info->block_group_kobjs[i];
9760 			space_info->block_group_kobjs[i] = NULL;
9761 			if (kobj) {
9762 				kobject_del(kobj);
9763 				kobject_put(kobj);
9764 			}
9765 		}
9766 		kobject_del(&space_info->kobj);
9767 		kobject_put(&space_info->kobj);
9768 	}
9769 	return 0;
9770 }
9771 
9772 /* link_block_group will queue up kobjects to add when we're reclaim-safe */
btrfs_add_raid_kobjects(struct btrfs_fs_info * fs_info)9773 void btrfs_add_raid_kobjects(struct btrfs_fs_info *fs_info)
9774 {
9775 	struct btrfs_space_info *space_info;
9776 	struct raid_kobject *rkobj;
9777 	LIST_HEAD(list);
9778 	int index;
9779 	int ret = 0;
9780 
9781 	spin_lock(&fs_info->pending_raid_kobjs_lock);
9782 	list_splice_init(&fs_info->pending_raid_kobjs, &list);
9783 	spin_unlock(&fs_info->pending_raid_kobjs_lock);
9784 
9785 	list_for_each_entry(rkobj, &list, list) {
9786 		space_info = __find_space_info(fs_info, rkobj->flags);
9787 		index = btrfs_bg_flags_to_raid_index(rkobj->flags);
9788 
9789 		ret = kobject_add(&rkobj->kobj, &space_info->kobj,
9790 				  "%s", get_raid_name(index));
9791 		if (ret) {
9792 			kobject_put(&rkobj->kobj);
9793 			break;
9794 		}
9795 	}
9796 	if (ret)
9797 		btrfs_warn(fs_info,
9798 			   "failed to add kobject for block cache, ignoring");
9799 }
9800 
link_block_group(struct btrfs_block_group_cache * cache)9801 static void link_block_group(struct btrfs_block_group_cache *cache)
9802 {
9803 	struct btrfs_space_info *space_info = cache->space_info;
9804 	struct btrfs_fs_info *fs_info = cache->fs_info;
9805 	int index = btrfs_bg_flags_to_raid_index(cache->flags);
9806 	bool first = false;
9807 
9808 	down_write(&space_info->groups_sem);
9809 	if (list_empty(&space_info->block_groups[index]))
9810 		first = true;
9811 	list_add_tail(&cache->list, &space_info->block_groups[index]);
9812 	up_write(&space_info->groups_sem);
9813 
9814 	if (first) {
9815 		struct raid_kobject *rkobj = kzalloc(sizeof(*rkobj), GFP_NOFS);
9816 		if (!rkobj) {
9817 			btrfs_warn(cache->fs_info,
9818 				"couldn't alloc memory for raid level kobject");
9819 			return;
9820 		}
9821 		rkobj->flags = cache->flags;
9822 		kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
9823 
9824 		spin_lock(&fs_info->pending_raid_kobjs_lock);
9825 		list_add_tail(&rkobj->list, &fs_info->pending_raid_kobjs);
9826 		spin_unlock(&fs_info->pending_raid_kobjs_lock);
9827 		space_info->block_group_kobjs[index] = &rkobj->kobj;
9828 	}
9829 }
9830 
9831 static struct btrfs_block_group_cache *
btrfs_create_block_group_cache(struct btrfs_fs_info * fs_info,u64 start,u64 size)9832 btrfs_create_block_group_cache(struct btrfs_fs_info *fs_info,
9833 			       u64 start, u64 size)
9834 {
9835 	struct btrfs_block_group_cache *cache;
9836 
9837 	cache = kzalloc(sizeof(*cache), GFP_NOFS);
9838 	if (!cache)
9839 		return NULL;
9840 
9841 	cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
9842 					GFP_NOFS);
9843 	if (!cache->free_space_ctl) {
9844 		kfree(cache);
9845 		return NULL;
9846 	}
9847 
9848 	cache->key.objectid = start;
9849 	cache->key.offset = size;
9850 	cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9851 
9852 	cache->fs_info = fs_info;
9853 	cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
9854 	set_free_space_tree_thresholds(cache);
9855 
9856 	atomic_set(&cache->count, 1);
9857 	spin_lock_init(&cache->lock);
9858 	init_rwsem(&cache->data_rwsem);
9859 	INIT_LIST_HEAD(&cache->list);
9860 	INIT_LIST_HEAD(&cache->cluster_list);
9861 	INIT_LIST_HEAD(&cache->bg_list);
9862 	INIT_LIST_HEAD(&cache->ro_list);
9863 	INIT_LIST_HEAD(&cache->dirty_list);
9864 	INIT_LIST_HEAD(&cache->io_list);
9865 	btrfs_init_free_space_ctl(cache);
9866 	atomic_set(&cache->trimming, 0);
9867 	mutex_init(&cache->free_space_lock);
9868 	btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
9869 
9870 	return cache;
9871 }
9872 
9873 
9874 /*
9875  * Iterate all chunks and verify that each of them has the corresponding block
9876  * group
9877  */
check_chunk_block_group_mappings(struct btrfs_fs_info * fs_info)9878 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
9879 {
9880 	struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
9881 	struct extent_map *em;
9882 	struct btrfs_block_group_cache *bg;
9883 	u64 start = 0;
9884 	int ret = 0;
9885 
9886 	while (1) {
9887 		read_lock(&map_tree->map_tree.lock);
9888 		/*
9889 		 * lookup_extent_mapping will return the first extent map
9890 		 * intersecting the range, so setting @len to 1 is enough to
9891 		 * get the first chunk.
9892 		 */
9893 		em = lookup_extent_mapping(&map_tree->map_tree, start, 1);
9894 		read_unlock(&map_tree->map_tree.lock);
9895 		if (!em)
9896 			break;
9897 
9898 		bg = btrfs_lookup_block_group(fs_info, em->start);
9899 		if (!bg) {
9900 			btrfs_err(fs_info,
9901 	"chunk start=%llu len=%llu doesn't have corresponding block group",
9902 				     em->start, em->len);
9903 			ret = -EUCLEAN;
9904 			free_extent_map(em);
9905 			break;
9906 		}
9907 		if (bg->key.objectid != em->start ||
9908 		    bg->key.offset != em->len ||
9909 		    (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
9910 		    (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
9911 			btrfs_err(fs_info,
9912 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
9913 				em->start, em->len,
9914 				em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
9915 				bg->key.objectid, bg->key.offset,
9916 				bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
9917 			ret = -EUCLEAN;
9918 			free_extent_map(em);
9919 			btrfs_put_block_group(bg);
9920 			break;
9921 		}
9922 		start = em->start + em->len;
9923 		free_extent_map(em);
9924 		btrfs_put_block_group(bg);
9925 	}
9926 	return ret;
9927 }
9928 
btrfs_read_block_groups(struct btrfs_fs_info * info)9929 int btrfs_read_block_groups(struct btrfs_fs_info *info)
9930 {
9931 	struct btrfs_path *path;
9932 	int ret;
9933 	struct btrfs_block_group_cache *cache;
9934 	struct btrfs_space_info *space_info;
9935 	struct btrfs_key key;
9936 	struct btrfs_key found_key;
9937 	struct extent_buffer *leaf;
9938 	int need_clear = 0;
9939 	u64 cache_gen;
9940 	u64 feature;
9941 	int mixed;
9942 
9943 	feature = btrfs_super_incompat_flags(info->super_copy);
9944 	mixed = !!(feature & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS);
9945 
9946 	key.objectid = 0;
9947 	key.offset = 0;
9948 	key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9949 	path = btrfs_alloc_path();
9950 	if (!path)
9951 		return -ENOMEM;
9952 	path->reada = READA_FORWARD;
9953 
9954 	cache_gen = btrfs_super_cache_generation(info->super_copy);
9955 	if (btrfs_test_opt(info, SPACE_CACHE) &&
9956 	    btrfs_super_generation(info->super_copy) != cache_gen)
9957 		need_clear = 1;
9958 	if (btrfs_test_opt(info, CLEAR_CACHE))
9959 		need_clear = 1;
9960 
9961 	while (1) {
9962 		ret = find_first_block_group(info, path, &key);
9963 		if (ret > 0)
9964 			break;
9965 		if (ret != 0)
9966 			goto error;
9967 
9968 		leaf = path->nodes[0];
9969 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
9970 
9971 		cache = btrfs_create_block_group_cache(info, found_key.objectid,
9972 						       found_key.offset);
9973 		if (!cache) {
9974 			ret = -ENOMEM;
9975 			goto error;
9976 		}
9977 
9978 		if (need_clear) {
9979 			/*
9980 			 * When we mount with old space cache, we need to
9981 			 * set BTRFS_DC_CLEAR and set dirty flag.
9982 			 *
9983 			 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
9984 			 *    truncate the old free space cache inode and
9985 			 *    setup a new one.
9986 			 * b) Setting 'dirty flag' makes sure that we flush
9987 			 *    the new space cache info onto disk.
9988 			 */
9989 			if (btrfs_test_opt(info, SPACE_CACHE))
9990 				cache->disk_cache_state = BTRFS_DC_CLEAR;
9991 		}
9992 
9993 		read_extent_buffer(leaf, &cache->item,
9994 				   btrfs_item_ptr_offset(leaf, path->slots[0]),
9995 				   sizeof(cache->item));
9996 		cache->flags = btrfs_block_group_flags(&cache->item);
9997 		if (!mixed &&
9998 		    ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
9999 		    (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
10000 			btrfs_err(info,
10001 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
10002 				  cache->key.objectid);
10003 			btrfs_put_block_group(cache);
10004 			ret = -EINVAL;
10005 			goto error;
10006 		}
10007 
10008 		key.objectid = found_key.objectid + found_key.offset;
10009 		btrfs_release_path(path);
10010 
10011 		/*
10012 		 * We need to exclude the super stripes now so that the space
10013 		 * info has super bytes accounted for, otherwise we'll think
10014 		 * we have more space than we actually do.
10015 		 */
10016 		ret = exclude_super_stripes(cache);
10017 		if (ret) {
10018 			/*
10019 			 * We may have excluded something, so call this just in
10020 			 * case.
10021 			 */
10022 			free_excluded_extents(cache);
10023 			btrfs_put_block_group(cache);
10024 			goto error;
10025 		}
10026 
10027 		/*
10028 		 * check for two cases, either we are full, and therefore
10029 		 * don't need to bother with the caching work since we won't
10030 		 * find any space, or we are empty, and we can just add all
10031 		 * the space in and be done with it.  This saves us _alot_ of
10032 		 * time, particularly in the full case.
10033 		 */
10034 		if (found_key.offset == btrfs_block_group_used(&cache->item)) {
10035 			cache->last_byte_to_unpin = (u64)-1;
10036 			cache->cached = BTRFS_CACHE_FINISHED;
10037 			free_excluded_extents(cache);
10038 		} else if (btrfs_block_group_used(&cache->item) == 0) {
10039 			cache->last_byte_to_unpin = (u64)-1;
10040 			cache->cached = BTRFS_CACHE_FINISHED;
10041 			add_new_free_space(cache, found_key.objectid,
10042 					   found_key.objectid +
10043 					   found_key.offset);
10044 			free_excluded_extents(cache);
10045 		}
10046 
10047 		ret = btrfs_add_block_group_cache(info, cache);
10048 		if (ret) {
10049 			btrfs_remove_free_space_cache(cache);
10050 			btrfs_put_block_group(cache);
10051 			goto error;
10052 		}
10053 
10054 		trace_btrfs_add_block_group(info, cache, 0);
10055 		update_space_info(info, cache->flags, found_key.offset,
10056 				  btrfs_block_group_used(&cache->item),
10057 				  cache->bytes_super, &space_info);
10058 
10059 		cache->space_info = space_info;
10060 
10061 		link_block_group(cache);
10062 
10063 		set_avail_alloc_bits(info, cache->flags);
10064 		if (btrfs_chunk_readonly(info, cache->key.objectid)) {
10065 			inc_block_group_ro(cache, 1);
10066 		} else if (btrfs_block_group_used(&cache->item) == 0) {
10067 			ASSERT(list_empty(&cache->bg_list));
10068 			btrfs_mark_bg_unused(cache);
10069 		}
10070 	}
10071 
10072 	list_for_each_entry_rcu(space_info, &info->space_info, list) {
10073 		if (!(get_alloc_profile(info, space_info->flags) &
10074 		      (BTRFS_BLOCK_GROUP_RAID10 |
10075 		       BTRFS_BLOCK_GROUP_RAID1 |
10076 		       BTRFS_BLOCK_GROUP_RAID5 |
10077 		       BTRFS_BLOCK_GROUP_RAID6 |
10078 		       BTRFS_BLOCK_GROUP_DUP)))
10079 			continue;
10080 		/*
10081 		 * avoid allocating from un-mirrored block group if there are
10082 		 * mirrored block groups.
10083 		 */
10084 		list_for_each_entry(cache,
10085 				&space_info->block_groups[BTRFS_RAID_RAID0],
10086 				list)
10087 			inc_block_group_ro(cache, 1);
10088 		list_for_each_entry(cache,
10089 				&space_info->block_groups[BTRFS_RAID_SINGLE],
10090 				list)
10091 			inc_block_group_ro(cache, 1);
10092 	}
10093 
10094 	btrfs_add_raid_kobjects(info);
10095 	init_global_block_rsv(info);
10096 	ret = check_chunk_block_group_mappings(info);
10097 error:
10098 	btrfs_free_path(path);
10099 	return ret;
10100 }
10101 
btrfs_create_pending_block_groups(struct btrfs_trans_handle * trans)10102 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
10103 {
10104 	struct btrfs_fs_info *fs_info = trans->fs_info;
10105 	struct btrfs_block_group_cache *block_group;
10106 	struct btrfs_root *extent_root = fs_info->extent_root;
10107 	struct btrfs_block_group_item item;
10108 	struct btrfs_key key;
10109 	int ret = 0;
10110 
10111 	if (!trans->can_flush_pending_bgs)
10112 		return;
10113 
10114 	while (!list_empty(&trans->new_bgs)) {
10115 		block_group = list_first_entry(&trans->new_bgs,
10116 					       struct btrfs_block_group_cache,
10117 					       bg_list);
10118 		if (ret)
10119 			goto next;
10120 
10121 		spin_lock(&block_group->lock);
10122 		memcpy(&item, &block_group->item, sizeof(item));
10123 		memcpy(&key, &block_group->key, sizeof(key));
10124 		spin_unlock(&block_group->lock);
10125 
10126 		ret = btrfs_insert_item(trans, extent_root, &key, &item,
10127 					sizeof(item));
10128 		if (ret)
10129 			btrfs_abort_transaction(trans, ret);
10130 		ret = btrfs_finish_chunk_alloc(trans, key.objectid, key.offset);
10131 		if (ret)
10132 			btrfs_abort_transaction(trans, ret);
10133 		add_block_group_free_space(trans, block_group);
10134 		/* already aborted the transaction if it failed. */
10135 next:
10136 		list_del_init(&block_group->bg_list);
10137 	}
10138 	btrfs_trans_release_chunk_metadata(trans);
10139 }
10140 
btrfs_make_block_group(struct btrfs_trans_handle * trans,u64 bytes_used,u64 type,u64 chunk_offset,u64 size)10141 int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
10142 			   u64 type, u64 chunk_offset, u64 size)
10143 {
10144 	struct btrfs_fs_info *fs_info = trans->fs_info;
10145 	struct btrfs_block_group_cache *cache;
10146 	int ret;
10147 
10148 	btrfs_set_log_full_commit(fs_info, trans);
10149 
10150 	cache = btrfs_create_block_group_cache(fs_info, chunk_offset, size);
10151 	if (!cache)
10152 		return -ENOMEM;
10153 
10154 	btrfs_set_block_group_used(&cache->item, bytes_used);
10155 	btrfs_set_block_group_chunk_objectid(&cache->item,
10156 					     BTRFS_FIRST_CHUNK_TREE_OBJECTID);
10157 	btrfs_set_block_group_flags(&cache->item, type);
10158 
10159 	cache->flags = type;
10160 	cache->last_byte_to_unpin = (u64)-1;
10161 	cache->cached = BTRFS_CACHE_FINISHED;
10162 	cache->needs_free_space = 1;
10163 	ret = exclude_super_stripes(cache);
10164 	if (ret) {
10165 		/*
10166 		 * We may have excluded something, so call this just in
10167 		 * case.
10168 		 */
10169 		free_excluded_extents(cache);
10170 		btrfs_put_block_group(cache);
10171 		return ret;
10172 	}
10173 
10174 	add_new_free_space(cache, chunk_offset, chunk_offset + size);
10175 
10176 	free_excluded_extents(cache);
10177 
10178 #ifdef CONFIG_BTRFS_DEBUG
10179 	if (btrfs_should_fragment_free_space(cache)) {
10180 		u64 new_bytes_used = size - bytes_used;
10181 
10182 		bytes_used += new_bytes_used >> 1;
10183 		fragment_free_space(cache);
10184 	}
10185 #endif
10186 	/*
10187 	 * Ensure the corresponding space_info object is created and
10188 	 * assigned to our block group. We want our bg to be added to the rbtree
10189 	 * with its ->space_info set.
10190 	 */
10191 	cache->space_info = __find_space_info(fs_info, cache->flags);
10192 	ASSERT(cache->space_info);
10193 
10194 	ret = btrfs_add_block_group_cache(fs_info, cache);
10195 	if (ret) {
10196 		btrfs_remove_free_space_cache(cache);
10197 		btrfs_put_block_group(cache);
10198 		return ret;
10199 	}
10200 
10201 	/*
10202 	 * Now that our block group has its ->space_info set and is inserted in
10203 	 * the rbtree, update the space info's counters.
10204 	 */
10205 	trace_btrfs_add_block_group(fs_info, cache, 1);
10206 	update_space_info(fs_info, cache->flags, size, bytes_used,
10207 				cache->bytes_super, &cache->space_info);
10208 	update_global_block_rsv(fs_info);
10209 
10210 	link_block_group(cache);
10211 
10212 	list_add_tail(&cache->bg_list, &trans->new_bgs);
10213 
10214 	set_avail_alloc_bits(fs_info, type);
10215 	return 0;
10216 }
10217 
clear_avail_alloc_bits(struct btrfs_fs_info * fs_info,u64 flags)10218 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
10219 {
10220 	u64 extra_flags = chunk_to_extended(flags) &
10221 				BTRFS_EXTENDED_PROFILE_MASK;
10222 
10223 	write_seqlock(&fs_info->profiles_lock);
10224 	if (flags & BTRFS_BLOCK_GROUP_DATA)
10225 		fs_info->avail_data_alloc_bits &= ~extra_flags;
10226 	if (flags & BTRFS_BLOCK_GROUP_METADATA)
10227 		fs_info->avail_metadata_alloc_bits &= ~extra_flags;
10228 	if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
10229 		fs_info->avail_system_alloc_bits &= ~extra_flags;
10230 	write_sequnlock(&fs_info->profiles_lock);
10231 }
10232 
btrfs_remove_block_group(struct btrfs_trans_handle * trans,u64 group_start,struct extent_map * em)10233 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
10234 			     u64 group_start, struct extent_map *em)
10235 {
10236 	struct btrfs_fs_info *fs_info = trans->fs_info;
10237 	struct btrfs_root *root = fs_info->extent_root;
10238 	struct btrfs_path *path;
10239 	struct btrfs_block_group_cache *block_group;
10240 	struct btrfs_free_cluster *cluster;
10241 	struct btrfs_root *tree_root = fs_info->tree_root;
10242 	struct btrfs_key key;
10243 	struct inode *inode;
10244 	struct kobject *kobj = NULL;
10245 	int ret;
10246 	int index;
10247 	int factor;
10248 	struct btrfs_caching_control *caching_ctl = NULL;
10249 	bool remove_em;
10250 
10251 	block_group = btrfs_lookup_block_group(fs_info, group_start);
10252 	BUG_ON(!block_group);
10253 	BUG_ON(!block_group->ro);
10254 
10255 	trace_btrfs_remove_block_group(block_group);
10256 	/*
10257 	 * Free the reserved super bytes from this block group before
10258 	 * remove it.
10259 	 */
10260 	free_excluded_extents(block_group);
10261 	btrfs_free_ref_tree_range(fs_info, block_group->key.objectid,
10262 				  block_group->key.offset);
10263 
10264 	memcpy(&key, &block_group->key, sizeof(key));
10265 	index = btrfs_bg_flags_to_raid_index(block_group->flags);
10266 	factor = btrfs_bg_type_to_factor(block_group->flags);
10267 
10268 	/* make sure this block group isn't part of an allocation cluster */
10269 	cluster = &fs_info->data_alloc_cluster;
10270 	spin_lock(&cluster->refill_lock);
10271 	btrfs_return_cluster_to_free_space(block_group, cluster);
10272 	spin_unlock(&cluster->refill_lock);
10273 
10274 	/*
10275 	 * make sure this block group isn't part of a metadata
10276 	 * allocation cluster
10277 	 */
10278 	cluster = &fs_info->meta_alloc_cluster;
10279 	spin_lock(&cluster->refill_lock);
10280 	btrfs_return_cluster_to_free_space(block_group, cluster);
10281 	spin_unlock(&cluster->refill_lock);
10282 
10283 	path = btrfs_alloc_path();
10284 	if (!path) {
10285 		ret = -ENOMEM;
10286 		goto out;
10287 	}
10288 
10289 	/*
10290 	 * get the inode first so any iput calls done for the io_list
10291 	 * aren't the final iput (no unlinks allowed now)
10292 	 */
10293 	inode = lookup_free_space_inode(fs_info, block_group, path);
10294 
10295 	mutex_lock(&trans->transaction->cache_write_mutex);
10296 	/*
10297 	 * make sure our free spache cache IO is done before remove the
10298 	 * free space inode
10299 	 */
10300 	spin_lock(&trans->transaction->dirty_bgs_lock);
10301 	if (!list_empty(&block_group->io_list)) {
10302 		list_del_init(&block_group->io_list);
10303 
10304 		WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
10305 
10306 		spin_unlock(&trans->transaction->dirty_bgs_lock);
10307 		btrfs_wait_cache_io(trans, block_group, path);
10308 		btrfs_put_block_group(block_group);
10309 		spin_lock(&trans->transaction->dirty_bgs_lock);
10310 	}
10311 
10312 	if (!list_empty(&block_group->dirty_list)) {
10313 		list_del_init(&block_group->dirty_list);
10314 		btrfs_put_block_group(block_group);
10315 	}
10316 	spin_unlock(&trans->transaction->dirty_bgs_lock);
10317 	mutex_unlock(&trans->transaction->cache_write_mutex);
10318 
10319 	if (!IS_ERR(inode)) {
10320 		ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10321 		if (ret) {
10322 			btrfs_add_delayed_iput(inode);
10323 			goto out;
10324 		}
10325 		clear_nlink(inode);
10326 		/* One for the block groups ref */
10327 		spin_lock(&block_group->lock);
10328 		if (block_group->iref) {
10329 			block_group->iref = 0;
10330 			block_group->inode = NULL;
10331 			spin_unlock(&block_group->lock);
10332 			iput(inode);
10333 		} else {
10334 			spin_unlock(&block_group->lock);
10335 		}
10336 		/* One for our lookup ref */
10337 		btrfs_add_delayed_iput(inode);
10338 	}
10339 
10340 	key.objectid = BTRFS_FREE_SPACE_OBJECTID;
10341 	key.offset = block_group->key.objectid;
10342 	key.type = 0;
10343 
10344 	ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
10345 	if (ret < 0)
10346 		goto out;
10347 	if (ret > 0)
10348 		btrfs_release_path(path);
10349 	if (ret == 0) {
10350 		ret = btrfs_del_item(trans, tree_root, path);
10351 		if (ret)
10352 			goto out;
10353 		btrfs_release_path(path);
10354 	}
10355 
10356 	spin_lock(&fs_info->block_group_cache_lock);
10357 	rb_erase(&block_group->cache_node,
10358 		 &fs_info->block_group_cache_tree);
10359 	RB_CLEAR_NODE(&block_group->cache_node);
10360 
10361 	/* Once for the block groups rbtree */
10362 	btrfs_put_block_group(block_group);
10363 
10364 	if (fs_info->first_logical_byte == block_group->key.objectid)
10365 		fs_info->first_logical_byte = (u64)-1;
10366 	spin_unlock(&fs_info->block_group_cache_lock);
10367 
10368 	down_write(&block_group->space_info->groups_sem);
10369 	/*
10370 	 * we must use list_del_init so people can check to see if they
10371 	 * are still on the list after taking the semaphore
10372 	 */
10373 	list_del_init(&block_group->list);
10374 	if (list_empty(&block_group->space_info->block_groups[index])) {
10375 		kobj = block_group->space_info->block_group_kobjs[index];
10376 		block_group->space_info->block_group_kobjs[index] = NULL;
10377 		clear_avail_alloc_bits(fs_info, block_group->flags);
10378 	}
10379 	up_write(&block_group->space_info->groups_sem);
10380 	if (kobj) {
10381 		kobject_del(kobj);
10382 		kobject_put(kobj);
10383 	}
10384 
10385 	if (block_group->has_caching_ctl)
10386 		caching_ctl = get_caching_control(block_group);
10387 	if (block_group->cached == BTRFS_CACHE_STARTED)
10388 		wait_block_group_cache_done(block_group);
10389 	if (block_group->has_caching_ctl) {
10390 		down_write(&fs_info->commit_root_sem);
10391 		if (!caching_ctl) {
10392 			struct btrfs_caching_control *ctl;
10393 
10394 			list_for_each_entry(ctl,
10395 				    &fs_info->caching_block_groups, list)
10396 				if (ctl->block_group == block_group) {
10397 					caching_ctl = ctl;
10398 					refcount_inc(&caching_ctl->count);
10399 					break;
10400 				}
10401 		}
10402 		if (caching_ctl)
10403 			list_del_init(&caching_ctl->list);
10404 		up_write(&fs_info->commit_root_sem);
10405 		if (caching_ctl) {
10406 			/* Once for the caching bgs list and once for us. */
10407 			put_caching_control(caching_ctl);
10408 			put_caching_control(caching_ctl);
10409 		}
10410 	}
10411 
10412 	spin_lock(&trans->transaction->dirty_bgs_lock);
10413 	if (!list_empty(&block_group->dirty_list)) {
10414 		WARN_ON(1);
10415 	}
10416 	if (!list_empty(&block_group->io_list)) {
10417 		WARN_ON(1);
10418 	}
10419 	spin_unlock(&trans->transaction->dirty_bgs_lock);
10420 	btrfs_remove_free_space_cache(block_group);
10421 
10422 	spin_lock(&block_group->space_info->lock);
10423 	list_del_init(&block_group->ro_list);
10424 
10425 	if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
10426 		WARN_ON(block_group->space_info->total_bytes
10427 			< block_group->key.offset);
10428 		WARN_ON(block_group->space_info->bytes_readonly
10429 			< block_group->key.offset);
10430 		WARN_ON(block_group->space_info->disk_total
10431 			< block_group->key.offset * factor);
10432 	}
10433 	block_group->space_info->total_bytes -= block_group->key.offset;
10434 	block_group->space_info->bytes_readonly -= block_group->key.offset;
10435 	block_group->space_info->disk_total -= block_group->key.offset * factor;
10436 
10437 	spin_unlock(&block_group->space_info->lock);
10438 
10439 	memcpy(&key, &block_group->key, sizeof(key));
10440 
10441 	mutex_lock(&fs_info->chunk_mutex);
10442 	if (!list_empty(&em->list)) {
10443 		/* We're in the transaction->pending_chunks list. */
10444 		free_extent_map(em);
10445 	}
10446 	spin_lock(&block_group->lock);
10447 	block_group->removed = 1;
10448 	/*
10449 	 * At this point trimming can't start on this block group, because we
10450 	 * removed the block group from the tree fs_info->block_group_cache_tree
10451 	 * so no one can't find it anymore and even if someone already got this
10452 	 * block group before we removed it from the rbtree, they have already
10453 	 * incremented block_group->trimming - if they didn't, they won't find
10454 	 * any free space entries because we already removed them all when we
10455 	 * called btrfs_remove_free_space_cache().
10456 	 *
10457 	 * And we must not remove the extent map from the fs_info->mapping_tree
10458 	 * to prevent the same logical address range and physical device space
10459 	 * ranges from being reused for a new block group. This is because our
10460 	 * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
10461 	 * completely transactionless, so while it is trimming a range the
10462 	 * currently running transaction might finish and a new one start,
10463 	 * allowing for new block groups to be created that can reuse the same
10464 	 * physical device locations unless we take this special care.
10465 	 *
10466 	 * There may also be an implicit trim operation if the file system
10467 	 * is mounted with -odiscard. The same protections must remain
10468 	 * in place until the extents have been discarded completely when
10469 	 * the transaction commit has completed.
10470 	 */
10471 	remove_em = (atomic_read(&block_group->trimming) == 0);
10472 	/*
10473 	 * Make sure a trimmer task always sees the em in the pinned_chunks list
10474 	 * if it sees block_group->removed == 1 (needs to lock block_group->lock
10475 	 * before checking block_group->removed).
10476 	 */
10477 	if (!remove_em) {
10478 		/*
10479 		 * Our em might be in trans->transaction->pending_chunks which
10480 		 * is protected by fs_info->chunk_mutex ([lock|unlock]_chunks),
10481 		 * and so is the fs_info->pinned_chunks list.
10482 		 *
10483 		 * So at this point we must be holding the chunk_mutex to avoid
10484 		 * any races with chunk allocation (more specifically at
10485 		 * volumes.c:contains_pending_extent()), to ensure it always
10486 		 * sees the em, either in the pending_chunks list or in the
10487 		 * pinned_chunks list.
10488 		 */
10489 		list_move_tail(&em->list, &fs_info->pinned_chunks);
10490 	}
10491 	spin_unlock(&block_group->lock);
10492 
10493 	mutex_unlock(&fs_info->chunk_mutex);
10494 
10495 	ret = remove_block_group_free_space(trans, block_group);
10496 	if (ret)
10497 		goto out;
10498 
10499 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
10500 	if (ret > 0)
10501 		ret = -EIO;
10502 	if (ret < 0)
10503 		goto out;
10504 
10505 	ret = btrfs_del_item(trans, root, path);
10506 	if (ret)
10507 		goto out;
10508 
10509 	if (remove_em) {
10510 		struct extent_map_tree *em_tree;
10511 
10512 		em_tree = &fs_info->mapping_tree.map_tree;
10513 		write_lock(&em_tree->lock);
10514 		/*
10515 		 * The em might be in the pending_chunks list, so make sure the
10516 		 * chunk mutex is locked, since remove_extent_mapping() will
10517 		 * delete us from that list.
10518 		 */
10519 		remove_extent_mapping(em_tree, em);
10520 		write_unlock(&em_tree->lock);
10521 		/* once for the tree */
10522 		free_extent_map(em);
10523 	}
10524 
10525 out:
10526 	/* Once for the lookup reference */
10527 	btrfs_put_block_group(block_group);
10528 	btrfs_free_path(path);
10529 	return ret;
10530 }
10531 
10532 struct btrfs_trans_handle *
btrfs_start_trans_remove_block_group(struct btrfs_fs_info * fs_info,const u64 chunk_offset)10533 btrfs_start_trans_remove_block_group(struct btrfs_fs_info *fs_info,
10534 				     const u64 chunk_offset)
10535 {
10536 	struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
10537 	struct extent_map *em;
10538 	struct map_lookup *map;
10539 	unsigned int num_items;
10540 
10541 	read_lock(&em_tree->lock);
10542 	em = lookup_extent_mapping(em_tree, chunk_offset, 1);
10543 	read_unlock(&em_tree->lock);
10544 	ASSERT(em && em->start == chunk_offset);
10545 
10546 	/*
10547 	 * We need to reserve 3 + N units from the metadata space info in order
10548 	 * to remove a block group (done at btrfs_remove_chunk() and at
10549 	 * btrfs_remove_block_group()), which are used for:
10550 	 *
10551 	 * 1 unit for adding the free space inode's orphan (located in the tree
10552 	 * of tree roots).
10553 	 * 1 unit for deleting the block group item (located in the extent
10554 	 * tree).
10555 	 * 1 unit for deleting the free space item (located in tree of tree
10556 	 * roots).
10557 	 * N units for deleting N device extent items corresponding to each
10558 	 * stripe (located in the device tree).
10559 	 *
10560 	 * In order to remove a block group we also need to reserve units in the
10561 	 * system space info in order to update the chunk tree (update one or
10562 	 * more device items and remove one chunk item), but this is done at
10563 	 * btrfs_remove_chunk() through a call to check_system_chunk().
10564 	 */
10565 	map = em->map_lookup;
10566 	num_items = 3 + map->num_stripes;
10567 	free_extent_map(em);
10568 
10569 	return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
10570 							   num_items, 1);
10571 }
10572 
10573 /*
10574  * Process the unused_bgs list and remove any that don't have any allocated
10575  * space inside of them.
10576  */
btrfs_delete_unused_bgs(struct btrfs_fs_info * fs_info)10577 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
10578 {
10579 	struct btrfs_block_group_cache *block_group;
10580 	struct btrfs_space_info *space_info;
10581 	struct btrfs_trans_handle *trans;
10582 	int ret = 0;
10583 
10584 	if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
10585 		return;
10586 
10587 	spin_lock(&fs_info->unused_bgs_lock);
10588 	while (!list_empty(&fs_info->unused_bgs)) {
10589 		u64 start, end;
10590 		int trimming;
10591 
10592 		block_group = list_first_entry(&fs_info->unused_bgs,
10593 					       struct btrfs_block_group_cache,
10594 					       bg_list);
10595 		list_del_init(&block_group->bg_list);
10596 
10597 		space_info = block_group->space_info;
10598 
10599 		if (ret || btrfs_mixed_space_info(space_info)) {
10600 			btrfs_put_block_group(block_group);
10601 			continue;
10602 		}
10603 		spin_unlock(&fs_info->unused_bgs_lock);
10604 
10605 		mutex_lock(&fs_info->delete_unused_bgs_mutex);
10606 
10607 		/* Don't want to race with allocators so take the groups_sem */
10608 		down_write(&space_info->groups_sem);
10609 		spin_lock(&block_group->lock);
10610 		if (block_group->reserved || block_group->pinned ||
10611 		    btrfs_block_group_used(&block_group->item) ||
10612 		    block_group->ro ||
10613 		    list_is_singular(&block_group->list)) {
10614 			/*
10615 			 * We want to bail if we made new allocations or have
10616 			 * outstanding allocations in this block group.  We do
10617 			 * the ro check in case balance is currently acting on
10618 			 * this block group.
10619 			 */
10620 			trace_btrfs_skip_unused_block_group(block_group);
10621 			spin_unlock(&block_group->lock);
10622 			up_write(&space_info->groups_sem);
10623 			goto next;
10624 		}
10625 		spin_unlock(&block_group->lock);
10626 
10627 		/* We don't want to force the issue, only flip if it's ok. */
10628 		ret = inc_block_group_ro(block_group, 0);
10629 		up_write(&space_info->groups_sem);
10630 		if (ret < 0) {
10631 			ret = 0;
10632 			goto next;
10633 		}
10634 
10635 		/*
10636 		 * Want to do this before we do anything else so we can recover
10637 		 * properly if we fail to join the transaction.
10638 		 */
10639 		trans = btrfs_start_trans_remove_block_group(fs_info,
10640 						     block_group->key.objectid);
10641 		if (IS_ERR(trans)) {
10642 			btrfs_dec_block_group_ro(block_group);
10643 			ret = PTR_ERR(trans);
10644 			goto next;
10645 		}
10646 
10647 		/*
10648 		 * We could have pending pinned extents for this block group,
10649 		 * just delete them, we don't care about them anymore.
10650 		 */
10651 		start = block_group->key.objectid;
10652 		end = start + block_group->key.offset - 1;
10653 		/*
10654 		 * Hold the unused_bg_unpin_mutex lock to avoid racing with
10655 		 * btrfs_finish_extent_commit(). If we are at transaction N,
10656 		 * another task might be running finish_extent_commit() for the
10657 		 * previous transaction N - 1, and have seen a range belonging
10658 		 * to the block group in freed_extents[] before we were able to
10659 		 * clear the whole block group range from freed_extents[]. This
10660 		 * means that task can lookup for the block group after we
10661 		 * unpinned it from freed_extents[] and removed it, leading to
10662 		 * a BUG_ON() at btrfs_unpin_extent_range().
10663 		 */
10664 		mutex_lock(&fs_info->unused_bg_unpin_mutex);
10665 		ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
10666 				  EXTENT_DIRTY);
10667 		if (ret) {
10668 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
10669 			btrfs_dec_block_group_ro(block_group);
10670 			goto end_trans;
10671 		}
10672 		ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
10673 				  EXTENT_DIRTY);
10674 		if (ret) {
10675 			mutex_unlock(&fs_info->unused_bg_unpin_mutex);
10676 			btrfs_dec_block_group_ro(block_group);
10677 			goto end_trans;
10678 		}
10679 		mutex_unlock(&fs_info->unused_bg_unpin_mutex);
10680 
10681 		/* Reset pinned so btrfs_put_block_group doesn't complain */
10682 		spin_lock(&space_info->lock);
10683 		spin_lock(&block_group->lock);
10684 
10685 		space_info->bytes_pinned -= block_group->pinned;
10686 		space_info->bytes_readonly += block_group->pinned;
10687 		percpu_counter_add_batch(&space_info->total_bytes_pinned,
10688 				   -block_group->pinned,
10689 				   BTRFS_TOTAL_BYTES_PINNED_BATCH);
10690 		block_group->pinned = 0;
10691 
10692 		spin_unlock(&block_group->lock);
10693 		spin_unlock(&space_info->lock);
10694 
10695 		/* DISCARD can flip during remount */
10696 		trimming = btrfs_test_opt(fs_info, DISCARD);
10697 
10698 		/* Implicit trim during transaction commit. */
10699 		if (trimming)
10700 			btrfs_get_block_group_trimming(block_group);
10701 
10702 		/*
10703 		 * Btrfs_remove_chunk will abort the transaction if things go
10704 		 * horribly wrong.
10705 		 */
10706 		ret = btrfs_remove_chunk(trans, block_group->key.objectid);
10707 
10708 		if (ret) {
10709 			if (trimming)
10710 				btrfs_put_block_group_trimming(block_group);
10711 			goto end_trans;
10712 		}
10713 
10714 		/*
10715 		 * If we're not mounted with -odiscard, we can just forget
10716 		 * about this block group. Otherwise we'll need to wait
10717 		 * until transaction commit to do the actual discard.
10718 		 */
10719 		if (trimming) {
10720 			spin_lock(&fs_info->unused_bgs_lock);
10721 			/*
10722 			 * A concurrent scrub might have added us to the list
10723 			 * fs_info->unused_bgs, so use a list_move operation
10724 			 * to add the block group to the deleted_bgs list.
10725 			 */
10726 			list_move(&block_group->bg_list,
10727 				  &trans->transaction->deleted_bgs);
10728 			spin_unlock(&fs_info->unused_bgs_lock);
10729 			btrfs_get_block_group(block_group);
10730 		}
10731 end_trans:
10732 		btrfs_end_transaction(trans);
10733 next:
10734 		mutex_unlock(&fs_info->delete_unused_bgs_mutex);
10735 		btrfs_put_block_group(block_group);
10736 		spin_lock(&fs_info->unused_bgs_lock);
10737 	}
10738 	spin_unlock(&fs_info->unused_bgs_lock);
10739 }
10740 
btrfs_init_space_info(struct btrfs_fs_info * fs_info)10741 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
10742 {
10743 	struct btrfs_super_block *disk_super;
10744 	u64 features;
10745 	u64 flags;
10746 	int mixed = 0;
10747 	int ret;
10748 
10749 	disk_super = fs_info->super_copy;
10750 	if (!btrfs_super_root(disk_super))
10751 		return -EINVAL;
10752 
10753 	features = btrfs_super_incompat_flags(disk_super);
10754 	if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
10755 		mixed = 1;
10756 
10757 	flags = BTRFS_BLOCK_GROUP_SYSTEM;
10758 	ret = create_space_info(fs_info, flags);
10759 	if (ret)
10760 		goto out;
10761 
10762 	if (mixed) {
10763 		flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
10764 		ret = create_space_info(fs_info, flags);
10765 	} else {
10766 		flags = BTRFS_BLOCK_GROUP_METADATA;
10767 		ret = create_space_info(fs_info, flags);
10768 		if (ret)
10769 			goto out;
10770 
10771 		flags = BTRFS_BLOCK_GROUP_DATA;
10772 		ret = create_space_info(fs_info, flags);
10773 	}
10774 out:
10775 	return ret;
10776 }
10777 
btrfs_error_unpin_extent_range(struct btrfs_fs_info * fs_info,u64 start,u64 end)10778 int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
10779 				   u64 start, u64 end)
10780 {
10781 	return unpin_extent_range(fs_info, start, end, false);
10782 }
10783 
10784 /*
10785  * It used to be that old block groups would be left around forever.
10786  * Iterating over them would be enough to trim unused space.  Since we
10787  * now automatically remove them, we also need to iterate over unallocated
10788  * space.
10789  *
10790  * We don't want a transaction for this since the discard may take a
10791  * substantial amount of time.  We don't require that a transaction be
10792  * running, but we do need to take a running transaction into account
10793  * to ensure that we're not discarding chunks that were released or
10794  * allocated in the current transaction.
10795  *
10796  * Holding the chunks lock will prevent other threads from allocating
10797  * or releasing chunks, but it won't prevent a running transaction
10798  * from committing and releasing the memory that the pending chunks
10799  * list head uses.  For that, we need to take a reference to the
10800  * transaction and hold the commit root sem.  We only need to hold
10801  * it while performing the free space search since we have already
10802  * held back allocations.
10803  */
btrfs_trim_free_extents(struct btrfs_device * device,u64 minlen,u64 * trimmed)10804 static int btrfs_trim_free_extents(struct btrfs_device *device,
10805 				   u64 minlen, u64 *trimmed)
10806 {
10807 	u64 start = 0, len = 0;
10808 	int ret;
10809 
10810 	*trimmed = 0;
10811 
10812 	/* Discard not supported = nothing to do. */
10813 	if (!blk_queue_discard(bdev_get_queue(device->bdev)))
10814 		return 0;
10815 
10816 	/* Not writeable = nothing to do. */
10817 	if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
10818 		return 0;
10819 
10820 	/* No free space = nothing to do. */
10821 	if (device->total_bytes <= device->bytes_used)
10822 		return 0;
10823 
10824 	ret = 0;
10825 
10826 	while (1) {
10827 		struct btrfs_fs_info *fs_info = device->fs_info;
10828 		struct btrfs_transaction *trans;
10829 		u64 bytes;
10830 
10831 		ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
10832 		if (ret)
10833 			break;
10834 
10835 		ret = down_read_killable(&fs_info->commit_root_sem);
10836 		if (ret) {
10837 			mutex_unlock(&fs_info->chunk_mutex);
10838 			break;
10839 		}
10840 
10841 		spin_lock(&fs_info->trans_lock);
10842 		trans = fs_info->running_transaction;
10843 		if (trans)
10844 			refcount_inc(&trans->use_count);
10845 		spin_unlock(&fs_info->trans_lock);
10846 
10847 		if (!trans)
10848 			up_read(&fs_info->commit_root_sem);
10849 
10850 		ret = find_free_dev_extent_start(trans, device, minlen, start,
10851 						 &start, &len);
10852 		if (trans) {
10853 			up_read(&fs_info->commit_root_sem);
10854 			btrfs_put_transaction(trans);
10855 		}
10856 
10857 		if (ret) {
10858 			mutex_unlock(&fs_info->chunk_mutex);
10859 			if (ret == -ENOSPC)
10860 				ret = 0;
10861 			break;
10862 		}
10863 
10864 		ret = btrfs_issue_discard(device->bdev, start, len, &bytes);
10865 		mutex_unlock(&fs_info->chunk_mutex);
10866 
10867 		if (ret)
10868 			break;
10869 
10870 		start += len;
10871 		*trimmed += bytes;
10872 
10873 		if (fatal_signal_pending(current)) {
10874 			ret = -ERESTARTSYS;
10875 			break;
10876 		}
10877 
10878 		cond_resched();
10879 	}
10880 
10881 	return ret;
10882 }
10883 
10884 /*
10885  * Trim the whole filesystem by:
10886  * 1) trimming the free space in each block group
10887  * 2) trimming the unallocated space on each device
10888  *
10889  * This will also continue trimming even if a block group or device encounters
10890  * an error.  The return value will be the last error, or 0 if nothing bad
10891  * happens.
10892  */
btrfs_trim_fs(struct btrfs_fs_info * fs_info,struct fstrim_range * range)10893 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
10894 {
10895 	struct btrfs_block_group_cache *cache = NULL;
10896 	struct btrfs_device *device;
10897 	struct list_head *devices;
10898 	u64 group_trimmed;
10899 	u64 start;
10900 	u64 end;
10901 	u64 trimmed = 0;
10902 	u64 bg_failed = 0;
10903 	u64 dev_failed = 0;
10904 	int bg_ret = 0;
10905 	int dev_ret = 0;
10906 	int ret = 0;
10907 
10908 	cache = btrfs_lookup_first_block_group(fs_info, range->start);
10909 	for (; cache; cache = next_block_group(fs_info, cache)) {
10910 		if (cache->key.objectid >= (range->start + range->len)) {
10911 			btrfs_put_block_group(cache);
10912 			break;
10913 		}
10914 
10915 		start = max(range->start, cache->key.objectid);
10916 		end = min(range->start + range->len,
10917 				cache->key.objectid + cache->key.offset);
10918 
10919 		if (end - start >= range->minlen) {
10920 			if (!block_group_cache_done(cache)) {
10921 				ret = cache_block_group(cache, 0);
10922 				if (ret) {
10923 					bg_failed++;
10924 					bg_ret = ret;
10925 					continue;
10926 				}
10927 				ret = wait_block_group_cache_done(cache);
10928 				if (ret) {
10929 					bg_failed++;
10930 					bg_ret = ret;
10931 					continue;
10932 				}
10933 			}
10934 			ret = btrfs_trim_block_group(cache,
10935 						     &group_trimmed,
10936 						     start,
10937 						     end,
10938 						     range->minlen);
10939 
10940 			trimmed += group_trimmed;
10941 			if (ret) {
10942 				bg_failed++;
10943 				bg_ret = ret;
10944 				continue;
10945 			}
10946 		}
10947 	}
10948 
10949 	if (bg_failed)
10950 		btrfs_warn(fs_info,
10951 			"failed to trim %llu block group(s), last error %d",
10952 			bg_failed, bg_ret);
10953 	mutex_lock(&fs_info->fs_devices->device_list_mutex);
10954 	devices = &fs_info->fs_devices->devices;
10955 	list_for_each_entry(device, devices, dev_list) {
10956 		ret = btrfs_trim_free_extents(device, range->minlen,
10957 					      &group_trimmed);
10958 		if (ret) {
10959 			dev_failed++;
10960 			dev_ret = ret;
10961 			break;
10962 		}
10963 
10964 		trimmed += group_trimmed;
10965 	}
10966 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
10967 
10968 	if (dev_failed)
10969 		btrfs_warn(fs_info,
10970 			"failed to trim %llu device(s), last error %d",
10971 			dev_failed, dev_ret);
10972 	range->len = trimmed;
10973 	if (bg_ret)
10974 		return bg_ret;
10975 	return dev_ret;
10976 }
10977 
10978 /*
10979  * btrfs_{start,end}_write_no_snapshotting() are similar to
10980  * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
10981  * data into the page cache through nocow before the subvolume is snapshoted,
10982  * but flush the data into disk after the snapshot creation, or to prevent
10983  * operations while snapshotting is ongoing and that cause the snapshot to be
10984  * inconsistent (writes followed by expanding truncates for example).
10985  */
btrfs_end_write_no_snapshotting(struct btrfs_root * root)10986 void btrfs_end_write_no_snapshotting(struct btrfs_root *root)
10987 {
10988 	percpu_counter_dec(&root->subv_writers->counter);
10989 	cond_wake_up(&root->subv_writers->wait);
10990 }
10991 
btrfs_start_write_no_snapshotting(struct btrfs_root * root)10992 int btrfs_start_write_no_snapshotting(struct btrfs_root *root)
10993 {
10994 	if (atomic_read(&root->will_be_snapshotted))
10995 		return 0;
10996 
10997 	percpu_counter_inc(&root->subv_writers->counter);
10998 	/*
10999 	 * Make sure counter is updated before we check for snapshot creation.
11000 	 */
11001 	smp_mb();
11002 	if (atomic_read(&root->will_be_snapshotted)) {
11003 		btrfs_end_write_no_snapshotting(root);
11004 		return 0;
11005 	}
11006 	return 1;
11007 }
11008 
btrfs_wait_for_snapshot_creation(struct btrfs_root * root)11009 void btrfs_wait_for_snapshot_creation(struct btrfs_root *root)
11010 {
11011 	while (true) {
11012 		int ret;
11013 
11014 		ret = btrfs_start_write_no_snapshotting(root);
11015 		if (ret)
11016 			break;
11017 		wait_var_event(&root->will_be_snapshotted,
11018 			       !atomic_read(&root->will_be_snapshotted));
11019 	}
11020 }
11021 
btrfs_mark_bg_unused(struct btrfs_block_group_cache * bg)11022 void btrfs_mark_bg_unused(struct btrfs_block_group_cache *bg)
11023 {
11024 	struct btrfs_fs_info *fs_info = bg->fs_info;
11025 
11026 	spin_lock(&fs_info->unused_bgs_lock);
11027 	if (list_empty(&bg->bg_list)) {
11028 		btrfs_get_block_group(bg);
11029 		trace_btrfs_add_unused_block_group(bg);
11030 		list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
11031 	}
11032 	spin_unlock(&fs_info->unused_bgs_lock);
11033 }
11034