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