xref: /openbmc/linux/fs/btrfs/space-info.c (revision 03fe78cc)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include "misc.h"
4 #include "ctree.h"
5 #include "space-info.h"
6 #include "sysfs.h"
7 #include "volumes.h"
8 #include "free-space-cache.h"
9 #include "ordered-data.h"
10 #include "transaction.h"
11 #include "block-group.h"
12 
13 /*
14  * HOW DOES SPACE RESERVATION WORK
15  *
16  * If you want to know about delalloc specifically, there is a separate comment
17  * for that with the delalloc code.  This comment is about how the whole system
18  * works generally.
19  *
20  * BASIC CONCEPTS
21  *
22  *   1) space_info.  This is the ultimate arbiter of how much space we can use.
23  *   There's a description of the bytes_ fields with the struct declaration,
24  *   refer to that for specifics on each field.  Suffice it to say that for
25  *   reservations we care about total_bytes - SUM(space_info->bytes_) when
26  *   determining if there is space to make an allocation.  There is a space_info
27  *   for METADATA, SYSTEM, and DATA areas.
28  *
29  *   2) block_rsv's.  These are basically buckets for every different type of
30  *   metadata reservation we have.  You can see the comment in the block_rsv
31  *   code on the rules for each type, but generally block_rsv->reserved is how
32  *   much space is accounted for in space_info->bytes_may_use.
33  *
34  *   3) btrfs_calc*_size.  These are the worst case calculations we used based
35  *   on the number of items we will want to modify.  We have one for changing
36  *   items, and one for inserting new items.  Generally we use these helpers to
37  *   determine the size of the block reserves, and then use the actual bytes
38  *   values to adjust the space_info counters.
39  *
40  * MAKING RESERVATIONS, THE NORMAL CASE
41  *
42  *   We call into either btrfs_reserve_data_bytes() or
43  *   btrfs_reserve_metadata_bytes(), depending on which we're looking for, with
44  *   num_bytes we want to reserve.
45  *
46  *   ->reserve
47  *     space_info->bytes_may_reserve += num_bytes
48  *
49  *   ->extent allocation
50  *     Call btrfs_add_reserved_bytes() which does
51  *     space_info->bytes_may_reserve -= num_bytes
52  *     space_info->bytes_reserved += extent_bytes
53  *
54  *   ->insert reference
55  *     Call btrfs_update_block_group() which does
56  *     space_info->bytes_reserved -= extent_bytes
57  *     space_info->bytes_used += extent_bytes
58  *
59  * MAKING RESERVATIONS, FLUSHING NORMALLY (non-priority)
60  *
61  *   Assume we are unable to simply make the reservation because we do not have
62  *   enough space
63  *
64  *   -> __reserve_bytes
65  *     create a reserve_ticket with ->bytes set to our reservation, add it to
66  *     the tail of space_info->tickets, kick async flush thread
67  *
68  *   ->handle_reserve_ticket
69  *     wait on ticket->wait for ->bytes to be reduced to 0, or ->error to be set
70  *     on the ticket.
71  *
72  *   -> btrfs_async_reclaim_metadata_space/btrfs_async_reclaim_data_space
73  *     Flushes various things attempting to free up space.
74  *
75  *   -> btrfs_try_granting_tickets()
76  *     This is called by anything that either subtracts space from
77  *     space_info->bytes_may_use, ->bytes_pinned, etc, or adds to the
78  *     space_info->total_bytes.  This loops through the ->priority_tickets and
79  *     then the ->tickets list checking to see if the reservation can be
80  *     completed.  If it can the space is added to space_info->bytes_may_use and
81  *     the ticket is woken up.
82  *
83  *   -> ticket wakeup
84  *     Check if ->bytes == 0, if it does we got our reservation and we can carry
85  *     on, if not return the appropriate error (ENOSPC, but can be EINTR if we
86  *     were interrupted.)
87  *
88  * MAKING RESERVATIONS, FLUSHING HIGH PRIORITY
89  *
90  *   Same as the above, except we add ourselves to the
91  *   space_info->priority_tickets, and we do not use ticket->wait, we simply
92  *   call flush_space() ourselves for the states that are safe for us to call
93  *   without deadlocking and hope for the best.
94  *
95  * THE FLUSHING STATES
96  *
97  *   Generally speaking we will have two cases for each state, a "nice" state
98  *   and a "ALL THE THINGS" state.  In btrfs we delay a lot of work in order to
99  *   reduce the locking over head on the various trees, and even to keep from
100  *   doing any work at all in the case of delayed refs.  Each of these delayed
101  *   things however hold reservations, and so letting them run allows us to
102  *   reclaim space so we can make new reservations.
103  *
104  *   FLUSH_DELAYED_ITEMS
105  *     Every inode has a delayed item to update the inode.  Take a simple write
106  *     for example, we would update the inode item at write time to update the
107  *     mtime, and then again at finish_ordered_io() time in order to update the
108  *     isize or bytes.  We keep these delayed items to coalesce these operations
109  *     into a single operation done on demand.  These are an easy way to reclaim
110  *     metadata space.
111  *
112  *   FLUSH_DELALLOC
113  *     Look at the delalloc comment to get an idea of how much space is reserved
114  *     for delayed allocation.  We can reclaim some of this space simply by
115  *     running delalloc, but usually we need to wait for ordered extents to
116  *     reclaim the bulk of this space.
117  *
118  *   FLUSH_DELAYED_REFS
119  *     We have a block reserve for the outstanding delayed refs space, and every
120  *     delayed ref operation holds a reservation.  Running these is a quick way
121  *     to reclaim space, but we want to hold this until the end because COW can
122  *     churn a lot and we can avoid making some extent tree modifications if we
123  *     are able to delay for as long as possible.
124  *
125  *   ALLOC_CHUNK
126  *     We will skip this the first time through space reservation, because of
127  *     overcommit and we don't want to have a lot of useless metadata space when
128  *     our worst case reservations will likely never come true.
129  *
130  *   RUN_DELAYED_IPUTS
131  *     If we're freeing inodes we're likely freeing checksums, file extent
132  *     items, and extent tree items.  Loads of space could be freed up by these
133  *     operations, however they won't be usable until the transaction commits.
134  *
135  *   COMMIT_TRANS
136  *     This will commit the transaction.  Historically we had a lot of logic
137  *     surrounding whether or not we'd commit the transaction, but this waits born
138  *     out of a pre-tickets era where we could end up committing the transaction
139  *     thousands of times in a row without making progress.  Now thanks to our
140  *     ticketing system we know if we're not making progress and can error
141  *     everybody out after a few commits rather than burning the disk hoping for
142  *     a different answer.
143  *
144  * OVERCOMMIT
145  *
146  *   Because we hold so many reservations for metadata we will allow you to
147  *   reserve more space than is currently free in the currently allocate
148  *   metadata space.  This only happens with metadata, data does not allow
149  *   overcommitting.
150  *
151  *   You can see the current logic for when we allow overcommit in
152  *   btrfs_can_overcommit(), but it only applies to unallocated space.  If there
153  *   is no unallocated space to be had, all reservations are kept within the
154  *   free space in the allocated metadata chunks.
155  *
156  *   Because of overcommitting, you generally want to use the
157  *   btrfs_can_overcommit() logic for metadata allocations, as it does the right
158  *   thing with or without extra unallocated space.
159  */
160 
161 u64 __pure btrfs_space_info_used(struct btrfs_space_info *s_info,
162 			  bool may_use_included)
163 {
164 	ASSERT(s_info);
165 	return s_info->bytes_used + s_info->bytes_reserved +
166 		s_info->bytes_pinned + s_info->bytes_readonly +
167 		s_info->bytes_zone_unusable +
168 		(may_use_included ? s_info->bytes_may_use : 0);
169 }
170 
171 /*
172  * after adding space to the filesystem, we need to clear the full flags
173  * on all the space infos.
174  */
175 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
176 {
177 	struct list_head *head = &info->space_info;
178 	struct btrfs_space_info *found;
179 
180 	list_for_each_entry(found, head, list)
181 		found->full = 0;
182 }
183 
184 static int create_space_info(struct btrfs_fs_info *info, u64 flags)
185 {
186 
187 	struct btrfs_space_info *space_info;
188 	int i;
189 	int ret;
190 
191 	space_info = kzalloc(sizeof(*space_info), GFP_NOFS);
192 	if (!space_info)
193 		return -ENOMEM;
194 
195 	for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
196 		INIT_LIST_HEAD(&space_info->block_groups[i]);
197 	init_rwsem(&space_info->groups_sem);
198 	spin_lock_init(&space_info->lock);
199 	space_info->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
200 	space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
201 	INIT_LIST_HEAD(&space_info->ro_bgs);
202 	INIT_LIST_HEAD(&space_info->tickets);
203 	INIT_LIST_HEAD(&space_info->priority_tickets);
204 	space_info->clamp = 1;
205 
206 	ret = btrfs_sysfs_add_space_info_type(info, space_info);
207 	if (ret)
208 		return ret;
209 
210 	list_add(&space_info->list, &info->space_info);
211 	if (flags & BTRFS_BLOCK_GROUP_DATA)
212 		info->data_sinfo = space_info;
213 
214 	return ret;
215 }
216 
217 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
218 {
219 	struct btrfs_super_block *disk_super;
220 	u64 features;
221 	u64 flags;
222 	int mixed = 0;
223 	int ret;
224 
225 	disk_super = fs_info->super_copy;
226 	if (!btrfs_super_root(disk_super))
227 		return -EINVAL;
228 
229 	features = btrfs_super_incompat_flags(disk_super);
230 	if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
231 		mixed = 1;
232 
233 	flags = BTRFS_BLOCK_GROUP_SYSTEM;
234 	ret = create_space_info(fs_info, flags);
235 	if (ret)
236 		goto out;
237 
238 	if (mixed) {
239 		flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
240 		ret = create_space_info(fs_info, flags);
241 	} else {
242 		flags = BTRFS_BLOCK_GROUP_METADATA;
243 		ret = create_space_info(fs_info, flags);
244 		if (ret)
245 			goto out;
246 
247 		flags = BTRFS_BLOCK_GROUP_DATA;
248 		ret = create_space_info(fs_info, flags);
249 	}
250 out:
251 	return ret;
252 }
253 
254 void btrfs_update_space_info(struct btrfs_fs_info *info, u64 flags,
255 			     u64 total_bytes, u64 bytes_used,
256 			     u64 bytes_readonly, u64 bytes_zone_unusable,
257 			     struct btrfs_space_info **space_info)
258 {
259 	struct btrfs_space_info *found;
260 	int factor;
261 
262 	factor = btrfs_bg_type_to_factor(flags);
263 
264 	found = btrfs_find_space_info(info, flags);
265 	ASSERT(found);
266 	spin_lock(&found->lock);
267 	found->total_bytes += total_bytes;
268 	found->disk_total += total_bytes * factor;
269 	found->bytes_used += bytes_used;
270 	found->disk_used += bytes_used * factor;
271 	found->bytes_readonly += bytes_readonly;
272 	found->bytes_zone_unusable += bytes_zone_unusable;
273 	if (total_bytes > 0)
274 		found->full = 0;
275 	btrfs_try_granting_tickets(info, found);
276 	spin_unlock(&found->lock);
277 	*space_info = found;
278 }
279 
280 struct btrfs_space_info *btrfs_find_space_info(struct btrfs_fs_info *info,
281 					       u64 flags)
282 {
283 	struct list_head *head = &info->space_info;
284 	struct btrfs_space_info *found;
285 
286 	flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
287 
288 	list_for_each_entry(found, head, list) {
289 		if (found->flags & flags)
290 			return found;
291 	}
292 	return NULL;
293 }
294 
295 static u64 calc_available_free_space(struct btrfs_fs_info *fs_info,
296 			  struct btrfs_space_info *space_info,
297 			  enum btrfs_reserve_flush_enum flush)
298 {
299 	u64 profile;
300 	u64 avail;
301 	int factor;
302 
303 	if (space_info->flags & BTRFS_BLOCK_GROUP_SYSTEM)
304 		profile = btrfs_system_alloc_profile(fs_info);
305 	else
306 		profile = btrfs_metadata_alloc_profile(fs_info);
307 
308 	avail = atomic64_read(&fs_info->free_chunk_space);
309 
310 	/*
311 	 * If we have dup, raid1 or raid10 then only half of the free
312 	 * space is actually usable.  For raid56, the space info used
313 	 * doesn't include the parity drive, so we don't have to
314 	 * change the math
315 	 */
316 	factor = btrfs_bg_type_to_factor(profile);
317 	avail = div_u64(avail, factor);
318 
319 	/*
320 	 * If we aren't flushing all things, let us overcommit up to
321 	 * 1/2th of the space. If we can flush, don't let us overcommit
322 	 * too much, let it overcommit up to 1/8 of the space.
323 	 */
324 	if (flush == BTRFS_RESERVE_FLUSH_ALL)
325 		avail >>= 3;
326 	else
327 		avail >>= 1;
328 	return avail;
329 }
330 
331 int btrfs_can_overcommit(struct btrfs_fs_info *fs_info,
332 			 struct btrfs_space_info *space_info, u64 bytes,
333 			 enum btrfs_reserve_flush_enum flush)
334 {
335 	u64 avail;
336 	u64 used;
337 
338 	/* Don't overcommit when in mixed mode */
339 	if (space_info->flags & BTRFS_BLOCK_GROUP_DATA)
340 		return 0;
341 
342 	used = btrfs_space_info_used(space_info, true);
343 	avail = calc_available_free_space(fs_info, space_info, flush);
344 
345 	if (used + bytes < space_info->total_bytes + avail)
346 		return 1;
347 	return 0;
348 }
349 
350 static void remove_ticket(struct btrfs_space_info *space_info,
351 			  struct reserve_ticket *ticket)
352 {
353 	if (!list_empty(&ticket->list)) {
354 		list_del_init(&ticket->list);
355 		ASSERT(space_info->reclaim_size >= ticket->bytes);
356 		space_info->reclaim_size -= ticket->bytes;
357 	}
358 }
359 
360 /*
361  * This is for space we already have accounted in space_info->bytes_may_use, so
362  * basically when we're returning space from block_rsv's.
363  */
364 void btrfs_try_granting_tickets(struct btrfs_fs_info *fs_info,
365 				struct btrfs_space_info *space_info)
366 {
367 	struct list_head *head;
368 	enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_NO_FLUSH;
369 
370 	lockdep_assert_held(&space_info->lock);
371 
372 	head = &space_info->priority_tickets;
373 again:
374 	while (!list_empty(head)) {
375 		struct reserve_ticket *ticket;
376 		u64 used = btrfs_space_info_used(space_info, true);
377 
378 		ticket = list_first_entry(head, struct reserve_ticket, list);
379 
380 		/* Check and see if our ticket can be satisfied now. */
381 		if ((used + ticket->bytes <= space_info->total_bytes) ||
382 		    btrfs_can_overcommit(fs_info, space_info, ticket->bytes,
383 					 flush)) {
384 			btrfs_space_info_update_bytes_may_use(fs_info,
385 							      space_info,
386 							      ticket->bytes);
387 			remove_ticket(space_info, ticket);
388 			ticket->bytes = 0;
389 			space_info->tickets_id++;
390 			wake_up(&ticket->wait);
391 		} else {
392 			break;
393 		}
394 	}
395 
396 	if (head == &space_info->priority_tickets) {
397 		head = &space_info->tickets;
398 		flush = BTRFS_RESERVE_FLUSH_ALL;
399 		goto again;
400 	}
401 }
402 
403 #define DUMP_BLOCK_RSV(fs_info, rsv_name)				\
404 do {									\
405 	struct btrfs_block_rsv *__rsv = &(fs_info)->rsv_name;		\
406 	spin_lock(&__rsv->lock);					\
407 	btrfs_info(fs_info, #rsv_name ": size %llu reserved %llu",	\
408 		   __rsv->size, __rsv->reserved);			\
409 	spin_unlock(&__rsv->lock);					\
410 } while (0)
411 
412 static void __btrfs_dump_space_info(struct btrfs_fs_info *fs_info,
413 				    struct btrfs_space_info *info)
414 {
415 	lockdep_assert_held(&info->lock);
416 
417 	btrfs_info(fs_info, "space_info %llu has %llu free, is %sfull",
418 		   info->flags,
419 		   info->total_bytes - btrfs_space_info_used(info, true),
420 		   info->full ? "" : "not ");
421 	btrfs_info(fs_info,
422 		"space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu zone_unusable=%llu",
423 		info->total_bytes, info->bytes_used, info->bytes_pinned,
424 		info->bytes_reserved, info->bytes_may_use,
425 		info->bytes_readonly, info->bytes_zone_unusable);
426 
427 	DUMP_BLOCK_RSV(fs_info, global_block_rsv);
428 	DUMP_BLOCK_RSV(fs_info, trans_block_rsv);
429 	DUMP_BLOCK_RSV(fs_info, chunk_block_rsv);
430 	DUMP_BLOCK_RSV(fs_info, delayed_block_rsv);
431 	DUMP_BLOCK_RSV(fs_info, delayed_refs_rsv);
432 
433 }
434 
435 void btrfs_dump_space_info(struct btrfs_fs_info *fs_info,
436 			   struct btrfs_space_info *info, u64 bytes,
437 			   int dump_block_groups)
438 {
439 	struct btrfs_block_group *cache;
440 	int index = 0;
441 
442 	spin_lock(&info->lock);
443 	__btrfs_dump_space_info(fs_info, info);
444 	spin_unlock(&info->lock);
445 
446 	if (!dump_block_groups)
447 		return;
448 
449 	down_read(&info->groups_sem);
450 again:
451 	list_for_each_entry(cache, &info->block_groups[index], list) {
452 		spin_lock(&cache->lock);
453 		btrfs_info(fs_info,
454 			"block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %llu zone_unusable %s",
455 			cache->start, cache->length, cache->used, cache->pinned,
456 			cache->reserved, cache->zone_unusable,
457 			cache->ro ? "[readonly]" : "");
458 		spin_unlock(&cache->lock);
459 		btrfs_dump_free_space(cache, bytes);
460 	}
461 	if (++index < BTRFS_NR_RAID_TYPES)
462 		goto again;
463 	up_read(&info->groups_sem);
464 }
465 
466 static inline u64 calc_reclaim_items_nr(struct btrfs_fs_info *fs_info,
467 					u64 to_reclaim)
468 {
469 	u64 bytes;
470 	u64 nr;
471 
472 	bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
473 	nr = div64_u64(to_reclaim, bytes);
474 	if (!nr)
475 		nr = 1;
476 	return nr;
477 }
478 
479 #define EXTENT_SIZE_PER_ITEM	SZ_256K
480 
481 /*
482  * shrink metadata reservation for delalloc
483  */
484 static void shrink_delalloc(struct btrfs_fs_info *fs_info,
485 			    struct btrfs_space_info *space_info,
486 			    u64 to_reclaim, bool wait_ordered,
487 			    bool for_preempt)
488 {
489 	struct btrfs_trans_handle *trans;
490 	u64 delalloc_bytes;
491 	u64 ordered_bytes;
492 	u64 items;
493 	long time_left;
494 	int loops;
495 
496 	delalloc_bytes = percpu_counter_sum_positive(&fs_info->delalloc_bytes);
497 	ordered_bytes = percpu_counter_sum_positive(&fs_info->ordered_bytes);
498 	if (delalloc_bytes == 0 && ordered_bytes == 0)
499 		return;
500 
501 	/* Calc the number of the pages we need flush for space reservation */
502 	if (to_reclaim == U64_MAX) {
503 		items = U64_MAX;
504 	} else {
505 		/*
506 		 * to_reclaim is set to however much metadata we need to
507 		 * reclaim, but reclaiming that much data doesn't really track
508 		 * exactly.  What we really want to do is reclaim full inode's
509 		 * worth of reservations, however that's not available to us
510 		 * here.  We will take a fraction of the delalloc bytes for our
511 		 * flushing loops and hope for the best.  Delalloc will expand
512 		 * the amount we write to cover an entire dirty extent, which
513 		 * will reclaim the metadata reservation for that range.  If
514 		 * it's not enough subsequent flush stages will be more
515 		 * aggressive.
516 		 */
517 		to_reclaim = max(to_reclaim, delalloc_bytes >> 3);
518 		items = calc_reclaim_items_nr(fs_info, to_reclaim) * 2;
519 	}
520 
521 	trans = (struct btrfs_trans_handle *)current->journal_info;
522 
523 	/*
524 	 * If we are doing more ordered than delalloc we need to just wait on
525 	 * ordered extents, otherwise we'll waste time trying to flush delalloc
526 	 * that likely won't give us the space back we need.
527 	 */
528 	if (ordered_bytes > delalloc_bytes && !for_preempt)
529 		wait_ordered = true;
530 
531 	loops = 0;
532 	while ((delalloc_bytes || ordered_bytes) && loops < 3) {
533 		u64 temp = min(delalloc_bytes, to_reclaim) >> PAGE_SHIFT;
534 		long nr_pages = min_t(u64, temp, LONG_MAX);
535 
536 		btrfs_start_delalloc_roots(fs_info, nr_pages, true);
537 
538 		loops++;
539 		if (wait_ordered && !trans) {
540 			btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
541 		} else {
542 			time_left = schedule_timeout_killable(1);
543 			if (time_left)
544 				break;
545 		}
546 
547 		/*
548 		 * If we are for preemption we just want a one-shot of delalloc
549 		 * flushing so we can stop flushing if we decide we don't need
550 		 * to anymore.
551 		 */
552 		if (for_preempt)
553 			break;
554 
555 		spin_lock(&space_info->lock);
556 		if (list_empty(&space_info->tickets) &&
557 		    list_empty(&space_info->priority_tickets)) {
558 			spin_unlock(&space_info->lock);
559 			break;
560 		}
561 		spin_unlock(&space_info->lock);
562 
563 		delalloc_bytes = percpu_counter_sum_positive(
564 						&fs_info->delalloc_bytes);
565 		ordered_bytes = percpu_counter_sum_positive(
566 						&fs_info->ordered_bytes);
567 	}
568 }
569 
570 /*
571  * Try to flush some data based on policy set by @state. This is only advisory
572  * and may fail for various reasons. The caller is supposed to examine the
573  * state of @space_info to detect the outcome.
574  */
575 static void flush_space(struct btrfs_fs_info *fs_info,
576 		       struct btrfs_space_info *space_info, u64 num_bytes,
577 		       enum btrfs_flush_state state, bool for_preempt)
578 {
579 	struct btrfs_root *root = fs_info->extent_root;
580 	struct btrfs_trans_handle *trans;
581 	int nr;
582 	int ret = 0;
583 
584 	switch (state) {
585 	case FLUSH_DELAYED_ITEMS_NR:
586 	case FLUSH_DELAYED_ITEMS:
587 		if (state == FLUSH_DELAYED_ITEMS_NR)
588 			nr = calc_reclaim_items_nr(fs_info, num_bytes) * 2;
589 		else
590 			nr = -1;
591 
592 		trans = btrfs_join_transaction(root);
593 		if (IS_ERR(trans)) {
594 			ret = PTR_ERR(trans);
595 			break;
596 		}
597 		ret = btrfs_run_delayed_items_nr(trans, nr);
598 		btrfs_end_transaction(trans);
599 		break;
600 	case FLUSH_DELALLOC:
601 	case FLUSH_DELALLOC_WAIT:
602 	case FLUSH_DELALLOC_FULL:
603 		if (state == FLUSH_DELALLOC_FULL)
604 			num_bytes = U64_MAX;
605 		shrink_delalloc(fs_info, space_info, num_bytes,
606 				state != FLUSH_DELALLOC, for_preempt);
607 		break;
608 	case FLUSH_DELAYED_REFS_NR:
609 	case FLUSH_DELAYED_REFS:
610 		trans = btrfs_join_transaction(root);
611 		if (IS_ERR(trans)) {
612 			ret = PTR_ERR(trans);
613 			break;
614 		}
615 		if (state == FLUSH_DELAYED_REFS_NR)
616 			nr = calc_reclaim_items_nr(fs_info, num_bytes);
617 		else
618 			nr = 0;
619 		btrfs_run_delayed_refs(trans, nr);
620 		btrfs_end_transaction(trans);
621 		break;
622 	case ALLOC_CHUNK:
623 	case ALLOC_CHUNK_FORCE:
624 		trans = btrfs_join_transaction(root);
625 		if (IS_ERR(trans)) {
626 			ret = PTR_ERR(trans);
627 			break;
628 		}
629 		ret = btrfs_chunk_alloc(trans,
630 				btrfs_get_alloc_profile(fs_info, space_info->flags),
631 				(state == ALLOC_CHUNK) ? CHUNK_ALLOC_NO_FORCE :
632 					CHUNK_ALLOC_FORCE);
633 		btrfs_end_transaction(trans);
634 		if (ret > 0 || ret == -ENOSPC)
635 			ret = 0;
636 		break;
637 	case RUN_DELAYED_IPUTS:
638 		/*
639 		 * If we have pending delayed iputs then we could free up a
640 		 * bunch of pinned space, so make sure we run the iputs before
641 		 * we do our pinned bytes check below.
642 		 */
643 		btrfs_run_delayed_iputs(fs_info);
644 		btrfs_wait_on_delayed_iputs(fs_info);
645 		break;
646 	case COMMIT_TRANS:
647 		ASSERT(current->journal_info == NULL);
648 		trans = btrfs_join_transaction(root);
649 		if (IS_ERR(trans)) {
650 			ret = PTR_ERR(trans);
651 			break;
652 		}
653 		ret = btrfs_commit_transaction(trans);
654 		break;
655 	default:
656 		ret = -ENOSPC;
657 		break;
658 	}
659 
660 	trace_btrfs_flush_space(fs_info, space_info->flags, num_bytes, state,
661 				ret, for_preempt);
662 	return;
663 }
664 
665 static inline u64
666 btrfs_calc_reclaim_metadata_size(struct btrfs_fs_info *fs_info,
667 				 struct btrfs_space_info *space_info)
668 {
669 	u64 used;
670 	u64 avail;
671 	u64 to_reclaim = space_info->reclaim_size;
672 
673 	lockdep_assert_held(&space_info->lock);
674 
675 	avail = calc_available_free_space(fs_info, space_info,
676 					  BTRFS_RESERVE_FLUSH_ALL);
677 	used = btrfs_space_info_used(space_info, true);
678 
679 	/*
680 	 * We may be flushing because suddenly we have less space than we had
681 	 * before, and now we're well over-committed based on our current free
682 	 * space.  If that's the case add in our overage so we make sure to put
683 	 * appropriate pressure on the flushing state machine.
684 	 */
685 	if (space_info->total_bytes + avail < used)
686 		to_reclaim += used - (space_info->total_bytes + avail);
687 
688 	return to_reclaim;
689 }
690 
691 static bool need_preemptive_reclaim(struct btrfs_fs_info *fs_info,
692 				    struct btrfs_space_info *space_info)
693 {
694 	u64 global_rsv_size = fs_info->global_block_rsv.reserved;
695 	u64 ordered, delalloc;
696 	u64 thresh = div_factor_fine(space_info->total_bytes, 98);
697 	u64 used;
698 
699 	/* If we're just plain full then async reclaim just slows us down. */
700 	if ((space_info->bytes_used + space_info->bytes_reserved +
701 	     global_rsv_size) >= thresh)
702 		return false;
703 
704 	/*
705 	 * We have tickets queued, bail so we don't compete with the async
706 	 * flushers.
707 	 */
708 	if (space_info->reclaim_size)
709 		return false;
710 
711 	/*
712 	 * If we have over half of the free space occupied by reservations or
713 	 * pinned then we want to start flushing.
714 	 *
715 	 * We do not do the traditional thing here, which is to say
716 	 *
717 	 *   if (used >= ((total_bytes + avail) / 2))
718 	 *     return 1;
719 	 *
720 	 * because this doesn't quite work how we want.  If we had more than 50%
721 	 * of the space_info used by bytes_used and we had 0 available we'd just
722 	 * constantly run the background flusher.  Instead we want it to kick in
723 	 * if our reclaimable space exceeds our clamped free space.
724 	 *
725 	 * Our clamping range is 2^1 -> 2^8.  Practically speaking that means
726 	 * the following:
727 	 *
728 	 * Amount of RAM        Minimum threshold       Maximum threshold
729 	 *
730 	 *        256GiB                     1GiB                  128GiB
731 	 *        128GiB                   512MiB                   64GiB
732 	 *         64GiB                   256MiB                   32GiB
733 	 *         32GiB                   128MiB                   16GiB
734 	 *         16GiB                    64MiB                    8GiB
735 	 *
736 	 * These are the range our thresholds will fall in, corresponding to how
737 	 * much delalloc we need for the background flusher to kick in.
738 	 */
739 
740 	thresh = calc_available_free_space(fs_info, space_info,
741 					   BTRFS_RESERVE_FLUSH_ALL);
742 	used = space_info->bytes_used + space_info->bytes_reserved +
743 	       space_info->bytes_readonly + global_rsv_size;
744 	if (used < space_info->total_bytes)
745 		thresh += space_info->total_bytes - used;
746 	thresh >>= space_info->clamp;
747 
748 	used = space_info->bytes_pinned;
749 
750 	/*
751 	 * If we have more ordered bytes than delalloc bytes then we're either
752 	 * doing a lot of DIO, or we simply don't have a lot of delalloc waiting
753 	 * around.  Preemptive flushing is only useful in that it can free up
754 	 * space before tickets need to wait for things to finish.  In the case
755 	 * of ordered extents, preemptively waiting on ordered extents gets us
756 	 * nothing, if our reservations are tied up in ordered extents we'll
757 	 * simply have to slow down writers by forcing them to wait on ordered
758 	 * extents.
759 	 *
760 	 * In the case that ordered is larger than delalloc, only include the
761 	 * block reserves that we would actually be able to directly reclaim
762 	 * from.  In this case if we're heavy on metadata operations this will
763 	 * clearly be heavy enough to warrant preemptive flushing.  In the case
764 	 * of heavy DIO or ordered reservations, preemptive flushing will just
765 	 * waste time and cause us to slow down.
766 	 *
767 	 * We want to make sure we truly are maxed out on ordered however, so
768 	 * cut ordered in half, and if it's still higher than delalloc then we
769 	 * can keep flushing.  This is to avoid the case where we start
770 	 * flushing, and now delalloc == ordered and we stop preemptively
771 	 * flushing when we could still have several gigs of delalloc to flush.
772 	 */
773 	ordered = percpu_counter_read_positive(&fs_info->ordered_bytes) >> 1;
774 	delalloc = percpu_counter_read_positive(&fs_info->delalloc_bytes);
775 	if (ordered >= delalloc)
776 		used += fs_info->delayed_refs_rsv.reserved +
777 			fs_info->delayed_block_rsv.reserved;
778 	else
779 		used += space_info->bytes_may_use - global_rsv_size;
780 
781 	return (used >= thresh && !btrfs_fs_closing(fs_info) &&
782 		!test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
783 }
784 
785 static bool steal_from_global_rsv(struct btrfs_fs_info *fs_info,
786 				  struct btrfs_space_info *space_info,
787 				  struct reserve_ticket *ticket)
788 {
789 	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
790 	u64 min_bytes;
791 
792 	if (global_rsv->space_info != space_info)
793 		return false;
794 
795 	spin_lock(&global_rsv->lock);
796 	min_bytes = div_factor(global_rsv->size, 1);
797 	if (global_rsv->reserved < min_bytes + ticket->bytes) {
798 		spin_unlock(&global_rsv->lock);
799 		return false;
800 	}
801 	global_rsv->reserved -= ticket->bytes;
802 	remove_ticket(space_info, ticket);
803 	ticket->bytes = 0;
804 	wake_up(&ticket->wait);
805 	space_info->tickets_id++;
806 	if (global_rsv->reserved < global_rsv->size)
807 		global_rsv->full = 0;
808 	spin_unlock(&global_rsv->lock);
809 
810 	return true;
811 }
812 
813 /*
814  * maybe_fail_all_tickets - we've exhausted our flushing, start failing tickets
815  * @fs_info - fs_info for this fs
816  * @space_info - the space info we were flushing
817  *
818  * We call this when we've exhausted our flushing ability and haven't made
819  * progress in satisfying tickets.  The reservation code handles tickets in
820  * order, so if there is a large ticket first and then smaller ones we could
821  * very well satisfy the smaller tickets.  This will attempt to wake up any
822  * tickets in the list to catch this case.
823  *
824  * This function returns true if it was able to make progress by clearing out
825  * other tickets, or if it stumbles across a ticket that was smaller than the
826  * first ticket.
827  */
828 static bool maybe_fail_all_tickets(struct btrfs_fs_info *fs_info,
829 				   struct btrfs_space_info *space_info)
830 {
831 	struct reserve_ticket *ticket;
832 	u64 tickets_id = space_info->tickets_id;
833 
834 	trace_btrfs_fail_all_tickets(fs_info, space_info);
835 
836 	if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
837 		btrfs_info(fs_info, "cannot satisfy tickets, dumping space info");
838 		__btrfs_dump_space_info(fs_info, space_info);
839 	}
840 
841 	while (!list_empty(&space_info->tickets) &&
842 	       tickets_id == space_info->tickets_id) {
843 		ticket = list_first_entry(&space_info->tickets,
844 					  struct reserve_ticket, list);
845 
846 		if (ticket->steal &&
847 		    steal_from_global_rsv(fs_info, space_info, ticket))
848 			return true;
849 
850 		if (btrfs_test_opt(fs_info, ENOSPC_DEBUG))
851 			btrfs_info(fs_info, "failing ticket with %llu bytes",
852 				   ticket->bytes);
853 
854 		remove_ticket(space_info, ticket);
855 		ticket->error = -ENOSPC;
856 		wake_up(&ticket->wait);
857 
858 		/*
859 		 * We're just throwing tickets away, so more flushing may not
860 		 * trip over btrfs_try_granting_tickets, so we need to call it
861 		 * here to see if we can make progress with the next ticket in
862 		 * the list.
863 		 */
864 		btrfs_try_granting_tickets(fs_info, space_info);
865 	}
866 	return (tickets_id != space_info->tickets_id);
867 }
868 
869 /*
870  * This is for normal flushers, we can wait all goddamned day if we want to.  We
871  * will loop and continuously try to flush as long as we are making progress.
872  * We count progress as clearing off tickets each time we have to loop.
873  */
874 static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
875 {
876 	struct btrfs_fs_info *fs_info;
877 	struct btrfs_space_info *space_info;
878 	u64 to_reclaim;
879 	enum btrfs_flush_state flush_state;
880 	int commit_cycles = 0;
881 	u64 last_tickets_id;
882 
883 	fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
884 	space_info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
885 
886 	spin_lock(&space_info->lock);
887 	to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info);
888 	if (!to_reclaim) {
889 		space_info->flush = 0;
890 		spin_unlock(&space_info->lock);
891 		return;
892 	}
893 	last_tickets_id = space_info->tickets_id;
894 	spin_unlock(&space_info->lock);
895 
896 	flush_state = FLUSH_DELAYED_ITEMS_NR;
897 	do {
898 		flush_space(fs_info, space_info, to_reclaim, flush_state, false);
899 		spin_lock(&space_info->lock);
900 		if (list_empty(&space_info->tickets)) {
901 			space_info->flush = 0;
902 			spin_unlock(&space_info->lock);
903 			return;
904 		}
905 		to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info,
906 							      space_info);
907 		if (last_tickets_id == space_info->tickets_id) {
908 			flush_state++;
909 		} else {
910 			last_tickets_id = space_info->tickets_id;
911 			flush_state = FLUSH_DELAYED_ITEMS_NR;
912 			if (commit_cycles)
913 				commit_cycles--;
914 		}
915 
916 		/*
917 		 * We do not want to empty the system of delalloc unless we're
918 		 * under heavy pressure, so allow one trip through the flushing
919 		 * logic before we start doing a FLUSH_DELALLOC_FULL.
920 		 */
921 		if (flush_state == FLUSH_DELALLOC_FULL && !commit_cycles)
922 			flush_state++;
923 
924 		/*
925 		 * We don't want to force a chunk allocation until we've tried
926 		 * pretty hard to reclaim space.  Think of the case where we
927 		 * freed up a bunch of space and so have a lot of pinned space
928 		 * to reclaim.  We would rather use that than possibly create a
929 		 * underutilized metadata chunk.  So if this is our first run
930 		 * through the flushing state machine skip ALLOC_CHUNK_FORCE and
931 		 * commit the transaction.  If nothing has changed the next go
932 		 * around then we can force a chunk allocation.
933 		 */
934 		if (flush_state == ALLOC_CHUNK_FORCE && !commit_cycles)
935 			flush_state++;
936 
937 		if (flush_state > COMMIT_TRANS) {
938 			commit_cycles++;
939 			if (commit_cycles > 2) {
940 				if (maybe_fail_all_tickets(fs_info, space_info)) {
941 					flush_state = FLUSH_DELAYED_ITEMS_NR;
942 					commit_cycles--;
943 				} else {
944 					space_info->flush = 0;
945 				}
946 			} else {
947 				flush_state = FLUSH_DELAYED_ITEMS_NR;
948 			}
949 		}
950 		spin_unlock(&space_info->lock);
951 	} while (flush_state <= COMMIT_TRANS);
952 }
953 
954 /*
955  * This handles pre-flushing of metadata space before we get to the point that
956  * we need to start blocking threads on tickets.  The logic here is different
957  * from the other flush paths because it doesn't rely on tickets to tell us how
958  * much we need to flush, instead it attempts to keep us below the 80% full
959  * watermark of space by flushing whichever reservation pool is currently the
960  * largest.
961  */
962 static void btrfs_preempt_reclaim_metadata_space(struct work_struct *work)
963 {
964 	struct btrfs_fs_info *fs_info;
965 	struct btrfs_space_info *space_info;
966 	struct btrfs_block_rsv *delayed_block_rsv;
967 	struct btrfs_block_rsv *delayed_refs_rsv;
968 	struct btrfs_block_rsv *global_rsv;
969 	struct btrfs_block_rsv *trans_rsv;
970 	int loops = 0;
971 
972 	fs_info = container_of(work, struct btrfs_fs_info,
973 			       preempt_reclaim_work);
974 	space_info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
975 	delayed_block_rsv = &fs_info->delayed_block_rsv;
976 	delayed_refs_rsv = &fs_info->delayed_refs_rsv;
977 	global_rsv = &fs_info->global_block_rsv;
978 	trans_rsv = &fs_info->trans_block_rsv;
979 
980 	spin_lock(&space_info->lock);
981 	while (need_preemptive_reclaim(fs_info, space_info)) {
982 		enum btrfs_flush_state flush;
983 		u64 delalloc_size = 0;
984 		u64 to_reclaim, block_rsv_size;
985 		u64 global_rsv_size = global_rsv->reserved;
986 
987 		loops++;
988 
989 		/*
990 		 * We don't have a precise counter for the metadata being
991 		 * reserved for delalloc, so we'll approximate it by subtracting
992 		 * out the block rsv's space from the bytes_may_use.  If that
993 		 * amount is higher than the individual reserves, then we can
994 		 * assume it's tied up in delalloc reservations.
995 		 */
996 		block_rsv_size = global_rsv_size +
997 			delayed_block_rsv->reserved +
998 			delayed_refs_rsv->reserved +
999 			trans_rsv->reserved;
1000 		if (block_rsv_size < space_info->bytes_may_use)
1001 			delalloc_size = space_info->bytes_may_use - block_rsv_size;
1002 		spin_unlock(&space_info->lock);
1003 
1004 		/*
1005 		 * We don't want to include the global_rsv in our calculation,
1006 		 * because that's space we can't touch.  Subtract it from the
1007 		 * block_rsv_size for the next checks.
1008 		 */
1009 		block_rsv_size -= global_rsv_size;
1010 
1011 		/*
1012 		 * We really want to avoid flushing delalloc too much, as it
1013 		 * could result in poor allocation patterns, so only flush it if
1014 		 * it's larger than the rest of the pools combined.
1015 		 */
1016 		if (delalloc_size > block_rsv_size) {
1017 			to_reclaim = delalloc_size;
1018 			flush = FLUSH_DELALLOC;
1019 		} else if (space_info->bytes_pinned >
1020 			   (delayed_block_rsv->reserved +
1021 			    delayed_refs_rsv->reserved)) {
1022 			to_reclaim = space_info->bytes_pinned;
1023 			flush = COMMIT_TRANS;
1024 		} else if (delayed_block_rsv->reserved >
1025 			   delayed_refs_rsv->reserved) {
1026 			to_reclaim = delayed_block_rsv->reserved;
1027 			flush = FLUSH_DELAYED_ITEMS_NR;
1028 		} else {
1029 			to_reclaim = delayed_refs_rsv->reserved;
1030 			flush = FLUSH_DELAYED_REFS_NR;
1031 		}
1032 
1033 		/*
1034 		 * We don't want to reclaim everything, just a portion, so scale
1035 		 * down the to_reclaim by 1/4.  If it takes us down to 0,
1036 		 * reclaim 1 items worth.
1037 		 */
1038 		to_reclaim >>= 2;
1039 		if (!to_reclaim)
1040 			to_reclaim = btrfs_calc_insert_metadata_size(fs_info, 1);
1041 		flush_space(fs_info, space_info, to_reclaim, flush, true);
1042 		cond_resched();
1043 		spin_lock(&space_info->lock);
1044 	}
1045 
1046 	/* We only went through once, back off our clamping. */
1047 	if (loops == 1 && !space_info->reclaim_size)
1048 		space_info->clamp = max(1, space_info->clamp - 1);
1049 	trace_btrfs_done_preemptive_reclaim(fs_info, space_info);
1050 	spin_unlock(&space_info->lock);
1051 }
1052 
1053 /*
1054  * FLUSH_DELALLOC_WAIT:
1055  *   Space is freed from flushing delalloc in one of two ways.
1056  *
1057  *   1) compression is on and we allocate less space than we reserved
1058  *   2) we are overwriting existing space
1059  *
1060  *   For #1 that extra space is reclaimed as soon as the delalloc pages are
1061  *   COWed, by way of btrfs_add_reserved_bytes() which adds the actual extent
1062  *   length to ->bytes_reserved, and subtracts the reserved space from
1063  *   ->bytes_may_use.
1064  *
1065  *   For #2 this is trickier.  Once the ordered extent runs we will drop the
1066  *   extent in the range we are overwriting, which creates a delayed ref for
1067  *   that freed extent.  This however is not reclaimed until the transaction
1068  *   commits, thus the next stages.
1069  *
1070  * RUN_DELAYED_IPUTS
1071  *   If we are freeing inodes, we want to make sure all delayed iputs have
1072  *   completed, because they could have been on an inode with i_nlink == 0, and
1073  *   thus have been truncated and freed up space.  But again this space is not
1074  *   immediately re-usable, it comes in the form of a delayed ref, which must be
1075  *   run and then the transaction must be committed.
1076  *
1077  * COMMIT_TRANS
1078  *   This is where we reclaim all of the pinned space generated by running the
1079  *   iputs
1080  *
1081  * ALLOC_CHUNK_FORCE
1082  *   For data we start with alloc chunk force, however we could have been full
1083  *   before, and then the transaction commit could have freed new block groups,
1084  *   so if we now have space to allocate do the force chunk allocation.
1085  */
1086 static const enum btrfs_flush_state data_flush_states[] = {
1087 	FLUSH_DELALLOC_FULL,
1088 	RUN_DELAYED_IPUTS,
1089 	COMMIT_TRANS,
1090 	ALLOC_CHUNK_FORCE,
1091 };
1092 
1093 static void btrfs_async_reclaim_data_space(struct work_struct *work)
1094 {
1095 	struct btrfs_fs_info *fs_info;
1096 	struct btrfs_space_info *space_info;
1097 	u64 last_tickets_id;
1098 	enum btrfs_flush_state flush_state = 0;
1099 
1100 	fs_info = container_of(work, struct btrfs_fs_info, async_data_reclaim_work);
1101 	space_info = fs_info->data_sinfo;
1102 
1103 	spin_lock(&space_info->lock);
1104 	if (list_empty(&space_info->tickets)) {
1105 		space_info->flush = 0;
1106 		spin_unlock(&space_info->lock);
1107 		return;
1108 	}
1109 	last_tickets_id = space_info->tickets_id;
1110 	spin_unlock(&space_info->lock);
1111 
1112 	while (!space_info->full) {
1113 		flush_space(fs_info, space_info, U64_MAX, ALLOC_CHUNK_FORCE, false);
1114 		spin_lock(&space_info->lock);
1115 		if (list_empty(&space_info->tickets)) {
1116 			space_info->flush = 0;
1117 			spin_unlock(&space_info->lock);
1118 			return;
1119 		}
1120 		last_tickets_id = space_info->tickets_id;
1121 		spin_unlock(&space_info->lock);
1122 	}
1123 
1124 	while (flush_state < ARRAY_SIZE(data_flush_states)) {
1125 		flush_space(fs_info, space_info, U64_MAX,
1126 			    data_flush_states[flush_state], false);
1127 		spin_lock(&space_info->lock);
1128 		if (list_empty(&space_info->tickets)) {
1129 			space_info->flush = 0;
1130 			spin_unlock(&space_info->lock);
1131 			return;
1132 		}
1133 
1134 		if (last_tickets_id == space_info->tickets_id) {
1135 			flush_state++;
1136 		} else {
1137 			last_tickets_id = space_info->tickets_id;
1138 			flush_state = 0;
1139 		}
1140 
1141 		if (flush_state >= ARRAY_SIZE(data_flush_states)) {
1142 			if (space_info->full) {
1143 				if (maybe_fail_all_tickets(fs_info, space_info))
1144 					flush_state = 0;
1145 				else
1146 					space_info->flush = 0;
1147 			} else {
1148 				flush_state = 0;
1149 			}
1150 		}
1151 		spin_unlock(&space_info->lock);
1152 	}
1153 }
1154 
1155 void btrfs_init_async_reclaim_work(struct btrfs_fs_info *fs_info)
1156 {
1157 	INIT_WORK(&fs_info->async_reclaim_work, btrfs_async_reclaim_metadata_space);
1158 	INIT_WORK(&fs_info->async_data_reclaim_work, btrfs_async_reclaim_data_space);
1159 	INIT_WORK(&fs_info->preempt_reclaim_work,
1160 		  btrfs_preempt_reclaim_metadata_space);
1161 }
1162 
1163 static const enum btrfs_flush_state priority_flush_states[] = {
1164 	FLUSH_DELAYED_ITEMS_NR,
1165 	FLUSH_DELAYED_ITEMS,
1166 	ALLOC_CHUNK,
1167 };
1168 
1169 static const enum btrfs_flush_state evict_flush_states[] = {
1170 	FLUSH_DELAYED_ITEMS_NR,
1171 	FLUSH_DELAYED_ITEMS,
1172 	FLUSH_DELAYED_REFS_NR,
1173 	FLUSH_DELAYED_REFS,
1174 	FLUSH_DELALLOC,
1175 	FLUSH_DELALLOC_WAIT,
1176 	FLUSH_DELALLOC_FULL,
1177 	ALLOC_CHUNK,
1178 	COMMIT_TRANS,
1179 };
1180 
1181 static void priority_reclaim_metadata_space(struct btrfs_fs_info *fs_info,
1182 				struct btrfs_space_info *space_info,
1183 				struct reserve_ticket *ticket,
1184 				const enum btrfs_flush_state *states,
1185 				int states_nr)
1186 {
1187 	u64 to_reclaim;
1188 	int flush_state;
1189 
1190 	spin_lock(&space_info->lock);
1191 	to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info);
1192 	if (!to_reclaim) {
1193 		spin_unlock(&space_info->lock);
1194 		return;
1195 	}
1196 	spin_unlock(&space_info->lock);
1197 
1198 	flush_state = 0;
1199 	do {
1200 		flush_space(fs_info, space_info, to_reclaim, states[flush_state],
1201 			    false);
1202 		flush_state++;
1203 		spin_lock(&space_info->lock);
1204 		if (ticket->bytes == 0) {
1205 			spin_unlock(&space_info->lock);
1206 			return;
1207 		}
1208 		spin_unlock(&space_info->lock);
1209 	} while (flush_state < states_nr);
1210 }
1211 
1212 static void priority_reclaim_data_space(struct btrfs_fs_info *fs_info,
1213 					struct btrfs_space_info *space_info,
1214 					struct reserve_ticket *ticket)
1215 {
1216 	while (!space_info->full) {
1217 		flush_space(fs_info, space_info, U64_MAX, ALLOC_CHUNK_FORCE, false);
1218 		spin_lock(&space_info->lock);
1219 		if (ticket->bytes == 0) {
1220 			spin_unlock(&space_info->lock);
1221 			return;
1222 		}
1223 		spin_unlock(&space_info->lock);
1224 	}
1225 }
1226 
1227 static void wait_reserve_ticket(struct btrfs_fs_info *fs_info,
1228 				struct btrfs_space_info *space_info,
1229 				struct reserve_ticket *ticket)
1230 
1231 {
1232 	DEFINE_WAIT(wait);
1233 	int ret = 0;
1234 
1235 	spin_lock(&space_info->lock);
1236 	while (ticket->bytes > 0 && ticket->error == 0) {
1237 		ret = prepare_to_wait_event(&ticket->wait, &wait, TASK_KILLABLE);
1238 		if (ret) {
1239 			/*
1240 			 * Delete us from the list. After we unlock the space
1241 			 * info, we don't want the async reclaim job to reserve
1242 			 * space for this ticket. If that would happen, then the
1243 			 * ticket's task would not known that space was reserved
1244 			 * despite getting an error, resulting in a space leak
1245 			 * (bytes_may_use counter of our space_info).
1246 			 */
1247 			remove_ticket(space_info, ticket);
1248 			ticket->error = -EINTR;
1249 			break;
1250 		}
1251 		spin_unlock(&space_info->lock);
1252 
1253 		schedule();
1254 
1255 		finish_wait(&ticket->wait, &wait);
1256 		spin_lock(&space_info->lock);
1257 	}
1258 	spin_unlock(&space_info->lock);
1259 }
1260 
1261 /**
1262  * Do the appropriate flushing and waiting for a ticket
1263  *
1264  * @fs_info:    the filesystem
1265  * @space_info: space info for the reservation
1266  * @ticket:     ticket for the reservation
1267  * @start_ns:   timestamp when the reservation started
1268  * @orig_bytes: amount of bytes originally reserved
1269  * @flush:      how much we can flush
1270  *
1271  * This does the work of figuring out how to flush for the ticket, waiting for
1272  * the reservation, and returning the appropriate error if there is one.
1273  */
1274 static int handle_reserve_ticket(struct btrfs_fs_info *fs_info,
1275 				 struct btrfs_space_info *space_info,
1276 				 struct reserve_ticket *ticket,
1277 				 u64 start_ns, u64 orig_bytes,
1278 				 enum btrfs_reserve_flush_enum flush)
1279 {
1280 	int ret;
1281 
1282 	switch (flush) {
1283 	case BTRFS_RESERVE_FLUSH_DATA:
1284 	case BTRFS_RESERVE_FLUSH_ALL:
1285 	case BTRFS_RESERVE_FLUSH_ALL_STEAL:
1286 		wait_reserve_ticket(fs_info, space_info, ticket);
1287 		break;
1288 	case BTRFS_RESERVE_FLUSH_LIMIT:
1289 		priority_reclaim_metadata_space(fs_info, space_info, ticket,
1290 						priority_flush_states,
1291 						ARRAY_SIZE(priority_flush_states));
1292 		break;
1293 	case BTRFS_RESERVE_FLUSH_EVICT:
1294 		priority_reclaim_metadata_space(fs_info, space_info, ticket,
1295 						evict_flush_states,
1296 						ARRAY_SIZE(evict_flush_states));
1297 		break;
1298 	case BTRFS_RESERVE_FLUSH_FREE_SPACE_INODE:
1299 		priority_reclaim_data_space(fs_info, space_info, ticket);
1300 		break;
1301 	default:
1302 		ASSERT(0);
1303 		break;
1304 	}
1305 
1306 	spin_lock(&space_info->lock);
1307 	ret = ticket->error;
1308 	if (ticket->bytes || ticket->error) {
1309 		/*
1310 		 * We were a priority ticket, so we need to delete ourselves
1311 		 * from the list.  Because we could have other priority tickets
1312 		 * behind us that require less space, run
1313 		 * btrfs_try_granting_tickets() to see if their reservations can
1314 		 * now be made.
1315 		 */
1316 		if (!list_empty(&ticket->list)) {
1317 			remove_ticket(space_info, ticket);
1318 			btrfs_try_granting_tickets(fs_info, space_info);
1319 		}
1320 
1321 		if (!ret)
1322 			ret = -ENOSPC;
1323 	}
1324 	spin_unlock(&space_info->lock);
1325 	ASSERT(list_empty(&ticket->list));
1326 	/*
1327 	 * Check that we can't have an error set if the reservation succeeded,
1328 	 * as that would confuse tasks and lead them to error out without
1329 	 * releasing reserved space (if an error happens the expectation is that
1330 	 * space wasn't reserved at all).
1331 	 */
1332 	ASSERT(!(ticket->bytes == 0 && ticket->error));
1333 	trace_btrfs_reserve_ticket(fs_info, space_info->flags, orig_bytes,
1334 				   start_ns, flush, ticket->error);
1335 	return ret;
1336 }
1337 
1338 /*
1339  * This returns true if this flush state will go through the ordinary flushing
1340  * code.
1341  */
1342 static inline bool is_normal_flushing(enum btrfs_reserve_flush_enum flush)
1343 {
1344 	return	(flush == BTRFS_RESERVE_FLUSH_ALL) ||
1345 		(flush == BTRFS_RESERVE_FLUSH_ALL_STEAL);
1346 }
1347 
1348 static inline void maybe_clamp_preempt(struct btrfs_fs_info *fs_info,
1349 				       struct btrfs_space_info *space_info)
1350 {
1351 	u64 ordered = percpu_counter_sum_positive(&fs_info->ordered_bytes);
1352 	u64 delalloc = percpu_counter_sum_positive(&fs_info->delalloc_bytes);
1353 
1354 	/*
1355 	 * If we're heavy on ordered operations then clamping won't help us.  We
1356 	 * need to clamp specifically to keep up with dirty'ing buffered
1357 	 * writers, because there's not a 1:1 correlation of writing delalloc
1358 	 * and freeing space, like there is with flushing delayed refs or
1359 	 * delayed nodes.  If we're already more ordered than delalloc then
1360 	 * we're keeping up, otherwise we aren't and should probably clamp.
1361 	 */
1362 	if (ordered < delalloc)
1363 		space_info->clamp = min(space_info->clamp + 1, 8);
1364 }
1365 
1366 /**
1367  * Try to reserve bytes from the block_rsv's space
1368  *
1369  * @fs_info:    the filesystem
1370  * @space_info: space info we want to allocate from
1371  * @orig_bytes: number of bytes we want
1372  * @flush:      whether or not we can flush to make our reservation
1373  *
1374  * This will reserve orig_bytes number of bytes from the space info associated
1375  * with the block_rsv.  If there is not enough space it will make an attempt to
1376  * flush out space to make room.  It will do this by flushing delalloc if
1377  * possible or committing the transaction.  If flush is 0 then no attempts to
1378  * regain reservations will be made and this will fail if there is not enough
1379  * space already.
1380  */
1381 static int __reserve_bytes(struct btrfs_fs_info *fs_info,
1382 			   struct btrfs_space_info *space_info, u64 orig_bytes,
1383 			   enum btrfs_reserve_flush_enum flush)
1384 {
1385 	struct work_struct *async_work;
1386 	struct reserve_ticket ticket;
1387 	u64 start_ns = 0;
1388 	u64 used;
1389 	int ret = 0;
1390 	bool pending_tickets;
1391 
1392 	ASSERT(orig_bytes);
1393 	ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_ALL);
1394 
1395 	if (flush == BTRFS_RESERVE_FLUSH_DATA)
1396 		async_work = &fs_info->async_data_reclaim_work;
1397 	else
1398 		async_work = &fs_info->async_reclaim_work;
1399 
1400 	spin_lock(&space_info->lock);
1401 	ret = -ENOSPC;
1402 	used = btrfs_space_info_used(space_info, true);
1403 
1404 	/*
1405 	 * We don't want NO_FLUSH allocations to jump everybody, they can
1406 	 * generally handle ENOSPC in a different way, so treat them the same as
1407 	 * normal flushers when it comes to skipping pending tickets.
1408 	 */
1409 	if (is_normal_flushing(flush) || (flush == BTRFS_RESERVE_NO_FLUSH))
1410 		pending_tickets = !list_empty(&space_info->tickets) ||
1411 			!list_empty(&space_info->priority_tickets);
1412 	else
1413 		pending_tickets = !list_empty(&space_info->priority_tickets);
1414 
1415 	/*
1416 	 * Carry on if we have enough space (short-circuit) OR call
1417 	 * can_overcommit() to ensure we can overcommit to continue.
1418 	 */
1419 	if (!pending_tickets &&
1420 	    ((used + orig_bytes <= space_info->total_bytes) ||
1421 	     btrfs_can_overcommit(fs_info, space_info, orig_bytes, flush))) {
1422 		btrfs_space_info_update_bytes_may_use(fs_info, space_info,
1423 						      orig_bytes);
1424 		ret = 0;
1425 	}
1426 
1427 	/*
1428 	 * If we couldn't make a reservation then setup our reservation ticket
1429 	 * and kick the async worker if it's not already running.
1430 	 *
1431 	 * If we are a priority flusher then we just need to add our ticket to
1432 	 * the list and we will do our own flushing further down.
1433 	 */
1434 	if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
1435 		ticket.bytes = orig_bytes;
1436 		ticket.error = 0;
1437 		space_info->reclaim_size += ticket.bytes;
1438 		init_waitqueue_head(&ticket.wait);
1439 		ticket.steal = (flush == BTRFS_RESERVE_FLUSH_ALL_STEAL);
1440 		if (trace_btrfs_reserve_ticket_enabled())
1441 			start_ns = ktime_get_ns();
1442 
1443 		if (flush == BTRFS_RESERVE_FLUSH_ALL ||
1444 		    flush == BTRFS_RESERVE_FLUSH_ALL_STEAL ||
1445 		    flush == BTRFS_RESERVE_FLUSH_DATA) {
1446 			list_add_tail(&ticket.list, &space_info->tickets);
1447 			if (!space_info->flush) {
1448 				/*
1449 				 * We were forced to add a reserve ticket, so
1450 				 * our preemptive flushing is unable to keep
1451 				 * up.  Clamp down on the threshold for the
1452 				 * preemptive flushing in order to keep up with
1453 				 * the workload.
1454 				 */
1455 				maybe_clamp_preempt(fs_info, space_info);
1456 
1457 				space_info->flush = 1;
1458 				trace_btrfs_trigger_flush(fs_info,
1459 							  space_info->flags,
1460 							  orig_bytes, flush,
1461 							  "enospc");
1462 				queue_work(system_unbound_wq, async_work);
1463 			}
1464 		} else {
1465 			list_add_tail(&ticket.list,
1466 				      &space_info->priority_tickets);
1467 		}
1468 	} else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
1469 		used += orig_bytes;
1470 		/*
1471 		 * We will do the space reservation dance during log replay,
1472 		 * which means we won't have fs_info->fs_root set, so don't do
1473 		 * the async reclaim as we will panic.
1474 		 */
1475 		if (!test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags) &&
1476 		    !work_busy(&fs_info->preempt_reclaim_work) &&
1477 		    need_preemptive_reclaim(fs_info, space_info)) {
1478 			trace_btrfs_trigger_flush(fs_info, space_info->flags,
1479 						  orig_bytes, flush, "preempt");
1480 			queue_work(system_unbound_wq,
1481 				   &fs_info->preempt_reclaim_work);
1482 		}
1483 	}
1484 	spin_unlock(&space_info->lock);
1485 	if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
1486 		return ret;
1487 
1488 	return handle_reserve_ticket(fs_info, space_info, &ticket, start_ns,
1489 				     orig_bytes, flush);
1490 }
1491 
1492 /**
1493  * Trye to reserve metadata bytes from the block_rsv's space
1494  *
1495  * @root:       the root we're allocating for
1496  * @block_rsv:  block_rsv we're allocating for
1497  * @orig_bytes: number of bytes we want
1498  * @flush:      whether or not we can flush to make our reservation
1499  *
1500  * This will reserve orig_bytes number of bytes from the space info associated
1501  * with the block_rsv.  If there is not enough space it will make an attempt to
1502  * flush out space to make room.  It will do this by flushing delalloc if
1503  * possible or committing the transaction.  If flush is 0 then no attempts to
1504  * regain reservations will be made and this will fail if there is not enough
1505  * space already.
1506  */
1507 int btrfs_reserve_metadata_bytes(struct btrfs_root *root,
1508 				 struct btrfs_block_rsv *block_rsv,
1509 				 u64 orig_bytes,
1510 				 enum btrfs_reserve_flush_enum flush)
1511 {
1512 	struct btrfs_fs_info *fs_info = root->fs_info;
1513 	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
1514 	int ret;
1515 
1516 	ret = __reserve_bytes(fs_info, block_rsv->space_info, orig_bytes, flush);
1517 	if (ret == -ENOSPC &&
1518 	    unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
1519 		if (block_rsv != global_rsv &&
1520 		    !btrfs_block_rsv_use_bytes(global_rsv, orig_bytes))
1521 			ret = 0;
1522 	}
1523 	if (ret == -ENOSPC) {
1524 		trace_btrfs_space_reservation(fs_info, "space_info:enospc",
1525 					      block_rsv->space_info->flags,
1526 					      orig_bytes, 1);
1527 
1528 		if (btrfs_test_opt(fs_info, ENOSPC_DEBUG))
1529 			btrfs_dump_space_info(fs_info, block_rsv->space_info,
1530 					      orig_bytes, 0);
1531 	}
1532 	return ret;
1533 }
1534 
1535 /**
1536  * Try to reserve data bytes for an allocation
1537  *
1538  * @fs_info: the filesystem
1539  * @bytes:   number of bytes we need
1540  * @flush:   how we are allowed to flush
1541  *
1542  * This will reserve bytes from the data space info.  If there is not enough
1543  * space then we will attempt to flush space as specified by flush.
1544  */
1545 int btrfs_reserve_data_bytes(struct btrfs_fs_info *fs_info, u64 bytes,
1546 			     enum btrfs_reserve_flush_enum flush)
1547 {
1548 	struct btrfs_space_info *data_sinfo = fs_info->data_sinfo;
1549 	int ret;
1550 
1551 	ASSERT(flush == BTRFS_RESERVE_FLUSH_DATA ||
1552 	       flush == BTRFS_RESERVE_FLUSH_FREE_SPACE_INODE);
1553 	ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_DATA);
1554 
1555 	ret = __reserve_bytes(fs_info, data_sinfo, bytes, flush);
1556 	if (ret == -ENOSPC) {
1557 		trace_btrfs_space_reservation(fs_info, "space_info:enospc",
1558 					      data_sinfo->flags, bytes, 1);
1559 		if (btrfs_test_opt(fs_info, ENOSPC_DEBUG))
1560 			btrfs_dump_space_info(fs_info, data_sinfo, bytes, 0);
1561 	}
1562 	return ret;
1563 }
1564