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