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