1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include <linux/spinlock.h>
4 #include <linux/minmax.h>
5 #include "misc.h"
6 #include "ctree.h"
7 #include "space-info.h"
8 #include "sysfs.h"
9 #include "volumes.h"
10 #include "free-space-cache.h"
11 #include "ordered-data.h"
12 #include "transaction.h"
13 #include "block-group.h"
14 #include "fs.h"
15 #include "accessors.h"
16 #include "extent-tree.h"
17 #include "zoned.h"
18 
19 /*
20  * HOW DOES SPACE RESERVATION WORK
21  *
22  * If you want to know about delalloc specifically, there is a separate comment
23  * for that with the delalloc code.  This comment is about how the whole system
24  * works generally.
25  *
26  * BASIC CONCEPTS
27  *
28  *   1) space_info.  This is the ultimate arbiter of how much space we can use.
29  *   There's a description of the bytes_ fields with the struct declaration,
30  *   refer to that for specifics on each field.  Suffice it to say that for
31  *   reservations we care about total_bytes - SUM(space_info->bytes_) when
32  *   determining if there is space to make an allocation.  There is a space_info
33  *   for METADATA, SYSTEM, and DATA areas.
34  *
35  *   2) block_rsv's.  These are basically buckets for every different type of
36  *   metadata reservation we have.  You can see the comment in the block_rsv
37  *   code on the rules for each type, but generally block_rsv->reserved is how
38  *   much space is accounted for in space_info->bytes_may_use.
39  *
40  *   3) btrfs_calc*_size.  These are the worst case calculations we used based
41  *   on the number of items we will want to modify.  We have one for changing
42  *   items, and one for inserting new items.  Generally we use these helpers to
43  *   determine the size of the block reserves, and then use the actual bytes
44  *   values to adjust the space_info counters.
45  *
46  * MAKING RESERVATIONS, THE NORMAL CASE
47  *
48  *   We call into either btrfs_reserve_data_bytes() or
49  *   btrfs_reserve_metadata_bytes(), depending on which we're looking for, with
50  *   num_bytes we want to reserve.
51  *
52  *   ->reserve
53  *     space_info->bytes_may_use += num_bytes
54  *
55  *   ->extent allocation
56  *     Call btrfs_add_reserved_bytes() which does
57  *     space_info->bytes_may_use -= num_bytes
58  *     space_info->bytes_reserved += extent_bytes
59  *
60  *   ->insert reference
61  *     Call btrfs_update_block_group() which does
62  *     space_info->bytes_reserved -= extent_bytes
63  *     space_info->bytes_used += extent_bytes
64  *
65  * MAKING RESERVATIONS, FLUSHING NORMALLY (non-priority)
66  *
67  *   Assume we are unable to simply make the reservation because we do not have
68  *   enough space
69  *
70  *   -> __reserve_bytes
71  *     create a reserve_ticket with ->bytes set to our reservation, add it to
72  *     the tail of space_info->tickets, kick async flush thread
73  *
74  *   ->handle_reserve_ticket
75  *     wait on ticket->wait for ->bytes to be reduced to 0, or ->error to be set
76  *     on the ticket.
77  *
78  *   -> btrfs_async_reclaim_metadata_space/btrfs_async_reclaim_data_space
79  *     Flushes various things attempting to free up space.
80  *
81  *   -> btrfs_try_granting_tickets()
82  *     This is called by anything that either subtracts space from
83  *     space_info->bytes_may_use, ->bytes_pinned, etc, or adds to the
84  *     space_info->total_bytes.  This loops through the ->priority_tickets and
85  *     then the ->tickets list checking to see if the reservation can be
86  *     completed.  If it can the space is added to space_info->bytes_may_use and
87  *     the ticket is woken up.
88  *
89  *   -> ticket wakeup
90  *     Check if ->bytes == 0, if it does we got our reservation and we can carry
91  *     on, if not return the appropriate error (ENOSPC, but can be EINTR if we
92  *     were interrupted.)
93  *
94  * MAKING RESERVATIONS, FLUSHING HIGH PRIORITY
95  *
96  *   Same as the above, except we add ourselves to the
97  *   space_info->priority_tickets, and we do not use ticket->wait, we simply
98  *   call flush_space() ourselves for the states that are safe for us to call
99  *   without deadlocking and hope for the best.
100  *
101  * THE FLUSHING STATES
102  *
103  *   Generally speaking we will have two cases for each state, a "nice" state
104  *   and a "ALL THE THINGS" state.  In btrfs we delay a lot of work in order to
105  *   reduce the locking over head on the various trees, and even to keep from
106  *   doing any work at all in the case of delayed refs.  Each of these delayed
107  *   things however hold reservations, and so letting them run allows us to
108  *   reclaim space so we can make new reservations.
109  *
110  *   FLUSH_DELAYED_ITEMS
111  *     Every inode has a delayed item to update the inode.  Take a simple write
112  *     for example, we would update the inode item at write time to update the
113  *     mtime, and then again at finish_ordered_io() time in order to update the
114  *     isize or bytes.  We keep these delayed items to coalesce these operations
115  *     into a single operation done on demand.  These are an easy way to reclaim
116  *     metadata space.
117  *
118  *   FLUSH_DELALLOC
119  *     Look at the delalloc comment to get an idea of how much space is reserved
120  *     for delayed allocation.  We can reclaim some of this space simply by
121  *     running delalloc, but usually we need to wait for ordered extents to
122  *     reclaim the bulk of this space.
123  *
124  *   FLUSH_DELAYED_REFS
125  *     We have a block reserve for the outstanding delayed refs space, and every
126  *     delayed ref operation holds a reservation.  Running these is a quick way
127  *     to reclaim space, but we want to hold this until the end because COW can
128  *     churn a lot and we can avoid making some extent tree modifications if we
129  *     are able to delay for as long as possible.
130  *
131  *   RESET_ZONES
132  *     This state works only for the zoned mode. On the zoned mode, we cannot
133  *     reuse once allocated then freed region until we reset the zone, due to
134  *     the sequential write zone requirement. The RESET_ZONES state resets the
135  *     zones of an unused block group and let us reuse the space. The reusing
136  *     is faster than removing the block group and allocating another block
137  *     group on the zones.
138  *
139  *   ALLOC_CHUNK
140  *     We will skip this the first time through space reservation, because of
141  *     overcommit and we don't want to have a lot of useless metadata space when
142  *     our worst case reservations will likely never come true.
143  *
144  *   RUN_DELAYED_IPUTS
145  *     If we're freeing inodes we're likely freeing checksums, file extent
146  *     items, and extent tree items.  Loads of space could be freed up by these
147  *     operations, however they won't be usable until the transaction commits.
148  *
149  *   COMMIT_TRANS
150  *     This will commit the transaction.  Historically we had a lot of logic
151  *     surrounding whether or not we'd commit the transaction, but this waits born
152  *     out of a pre-tickets era where we could end up committing the transaction
153  *     thousands of times in a row without making progress.  Now thanks to our
154  *     ticketing system we know if we're not making progress and can error
155  *     everybody out after a few commits rather than burning the disk hoping for
156  *     a different answer.
157  *
158  * OVERCOMMIT
159  *
160  *   Because we hold so many reservations for metadata we will allow you to
161  *   reserve more space than is currently free in the currently allocate
162  *   metadata space.  This only happens with metadata, data does not allow
163  *   overcommitting.
164  *
165  *   You can see the current logic for when we allow overcommit in
166  *   btrfs_can_overcommit(), but it only applies to unallocated space.  If there
167  *   is no unallocated space to be had, all reservations are kept within the
168  *   free space in the allocated metadata chunks.
169  *
170  *   Because of overcommitting, you generally want to use the
171  *   btrfs_can_overcommit() logic for metadata allocations, as it does the right
172  *   thing with or without extra unallocated space.
173  */
174 
175 u64 __pure btrfs_space_info_used(const struct btrfs_space_info *s_info,
176 			  bool may_use_included)
177 {
178 	ASSERT(s_info);
179 	return s_info->bytes_used + s_info->bytes_reserved +
180 		s_info->bytes_pinned + s_info->bytes_readonly +
181 		s_info->bytes_zone_unusable +
182 		(may_use_included ? s_info->bytes_may_use : 0);
183 }
184 
185 /*
186  * after adding space to the filesystem, we need to clear the full flags
187  * on all the space infos.
188  */
189 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
190 {
191 	struct list_head *head = &info->space_info;
192 	struct btrfs_space_info *found;
193 
194 	list_for_each_entry(found, head, list)
195 		found->full = 0;
196 }
197 
198 /*
199  * Block groups with more than this value (percents) of unusable space will be
200  * scheduled for background reclaim.
201  */
202 #define BTRFS_DEFAULT_ZONED_RECLAIM_THRESH			(75)
203 
204 #define BTRFS_UNALLOC_BLOCK_GROUP_TARGET			(10ULL)
205 
206 /*
207  * Calculate chunk size depending on volume type (regular or zoned).
208  */
209 static u64 calc_chunk_size(const struct btrfs_fs_info *fs_info, u64 flags)
210 {
211 	if (btrfs_is_zoned(fs_info))
212 		return fs_info->zone_size;
213 
214 	ASSERT(flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
215 
216 	if (flags & BTRFS_BLOCK_GROUP_DATA)
217 		return BTRFS_MAX_DATA_CHUNK_SIZE;
218 	else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
219 		return SZ_32M;
220 
221 	/* Handle BTRFS_BLOCK_GROUP_METADATA */
222 	if (fs_info->fs_devices->total_rw_bytes > 50ULL * SZ_1G)
223 		return SZ_1G;
224 
225 	return SZ_256M;
226 }
227 
228 /*
229  * Update default chunk size.
230  */
231 void btrfs_update_space_info_chunk_size(struct btrfs_space_info *space_info,
232 					u64 chunk_size)
233 {
234 	WRITE_ONCE(space_info->chunk_size, chunk_size);
235 }
236 
237 static void init_space_info(struct btrfs_fs_info *info,
238 			    struct btrfs_space_info *space_info, u64 flags)
239 {
240 	space_info->fs_info = info;
241 	for (int i = 0; i < BTRFS_NR_RAID_TYPES; i++)
242 		INIT_LIST_HEAD(&space_info->block_groups[i]);
243 	init_rwsem(&space_info->groups_sem);
244 	spin_lock_init(&space_info->lock);
245 	space_info->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
246 	space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
247 	INIT_LIST_HEAD(&space_info->ro_bgs);
248 	INIT_LIST_HEAD(&space_info->tickets);
249 	INIT_LIST_HEAD(&space_info->priority_tickets);
250 	space_info->clamp = 1;
251 	btrfs_update_space_info_chunk_size(space_info, calc_chunk_size(info, flags));
252 	space_info->subgroup_id = BTRFS_SUB_GROUP_PRIMARY;
253 
254 	if (btrfs_is_zoned(info))
255 		space_info->bg_reclaim_threshold = BTRFS_DEFAULT_ZONED_RECLAIM_THRESH;
256 }
257 
258 static int create_space_info_sub_group(struct btrfs_space_info *parent, u64 flags,
259 				       enum btrfs_space_info_sub_group id, int index)
260 {
261 	struct btrfs_fs_info *fs_info = parent->fs_info;
262 	struct btrfs_space_info *sub_group;
263 	int ret;
264 
265 	ASSERT(parent->subgroup_id == BTRFS_SUB_GROUP_PRIMARY);
266 	ASSERT(id != BTRFS_SUB_GROUP_PRIMARY);
267 
268 	sub_group = kzalloc(sizeof(*sub_group), GFP_NOFS);
269 	if (!sub_group)
270 		return -ENOMEM;
271 
272 	init_space_info(fs_info, sub_group, flags);
273 	parent->sub_group[index] = sub_group;
274 	sub_group->parent = parent;
275 	sub_group->subgroup_id = id;
276 
277 	ret = btrfs_sysfs_add_space_info_type(fs_info, sub_group);
278 	if (ret) {
279 		kfree(sub_group);
280 		parent->sub_group[index] = NULL;
281 	}
282 	return ret;
283 }
284 
285 static int create_space_info(struct btrfs_fs_info *info, u64 flags)
286 {
287 
288 	struct btrfs_space_info *space_info;
289 	int ret = 0;
290 
291 	space_info = kzalloc(sizeof(*space_info), GFP_NOFS);
292 	if (!space_info)
293 		return -ENOMEM;
294 
295 	init_space_info(info, space_info, flags);
296 
297 	if (btrfs_is_zoned(info)) {
298 		if (flags & BTRFS_BLOCK_GROUP_DATA)
299 			ret = create_space_info_sub_group(space_info, flags,
300 							  BTRFS_SUB_GROUP_DATA_RELOC,
301 							  0);
302 		else if (flags & BTRFS_BLOCK_GROUP_METADATA)
303 			ret = create_space_info_sub_group(space_info, flags,
304 							  BTRFS_SUB_GROUP_TREELOG,
305 							  0);
306 
307 		if (ret)
308 			return ret;
309 	}
310 
311 	ret = btrfs_sysfs_add_space_info_type(info, space_info);
312 	if (ret)
313 		return ret;
314 
315 	list_add(&space_info->list, &info->space_info);
316 	if (flags & BTRFS_BLOCK_GROUP_DATA)
317 		info->data_sinfo = space_info;
318 
319 	return ret;
320 }
321 
322 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
323 {
324 	struct btrfs_super_block *disk_super;
325 	u64 features;
326 	u64 flags;
327 	int mixed = 0;
328 	int ret;
329 
330 	disk_super = fs_info->super_copy;
331 	if (!btrfs_super_root(disk_super))
332 		return -EINVAL;
333 
334 	features = btrfs_super_incompat_flags(disk_super);
335 	if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
336 		mixed = 1;
337 
338 	flags = BTRFS_BLOCK_GROUP_SYSTEM;
339 	ret = create_space_info(fs_info, flags);
340 	if (ret)
341 		goto out;
342 
343 	if (mixed) {
344 		flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
345 		ret = create_space_info(fs_info, flags);
346 	} else {
347 		flags = BTRFS_BLOCK_GROUP_METADATA;
348 		ret = create_space_info(fs_info, flags);
349 		if (ret)
350 			goto out;
351 
352 		flags = BTRFS_BLOCK_GROUP_DATA;
353 		ret = create_space_info(fs_info, flags);
354 	}
355 out:
356 	return ret;
357 }
358 
359 void btrfs_add_bg_to_space_info(struct btrfs_fs_info *info,
360 				struct btrfs_block_group *block_group)
361 {
362 	struct btrfs_space_info *space_info = block_group->space_info;
363 	int factor, index;
364 
365 	factor = btrfs_bg_type_to_factor(block_group->flags);
366 
367 	spin_lock(&space_info->lock);
368 	space_info->total_bytes += block_group->length;
369 	space_info->disk_total += block_group->length * factor;
370 	space_info->bytes_used += block_group->used;
371 	space_info->disk_used += block_group->used * factor;
372 	space_info->bytes_readonly += block_group->bytes_super;
373 	btrfs_space_info_update_bytes_zone_unusable(space_info, block_group->zone_unusable);
374 	if (block_group->length > 0)
375 		space_info->full = 0;
376 	btrfs_try_granting_tickets(info, space_info);
377 	spin_unlock(&space_info->lock);
378 
379 	block_group->space_info = space_info;
380 
381 	index = btrfs_bg_flags_to_raid_index(block_group->flags);
382 	down_write(&space_info->groups_sem);
383 	list_add_tail(&block_group->list, &space_info->block_groups[index]);
384 	up_write(&space_info->groups_sem);
385 }
386 
387 struct btrfs_space_info *btrfs_find_space_info(struct btrfs_fs_info *info,
388 					       u64 flags)
389 {
390 	struct list_head *head = &info->space_info;
391 	struct btrfs_space_info *found;
392 
393 	flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
394 
395 	list_for_each_entry(found, head, list) {
396 		if (found->flags & flags)
397 			return found;
398 	}
399 	return NULL;
400 }
401 
402 static u64 calc_effective_data_chunk_size(struct btrfs_fs_info *fs_info)
403 {
404 	struct btrfs_space_info *data_sinfo;
405 	u64 data_chunk_size;
406 
407 	/*
408 	 * Calculate the data_chunk_size, space_info->chunk_size is the
409 	 * "optimal" chunk size based on the fs size.  However when we actually
410 	 * allocate the chunk we will strip this down further, making it no
411 	 * more than 10% of the disk or 1G, whichever is smaller.
412 	 *
413 	 * On the zoned mode, we need to use zone_size (= data_sinfo->chunk_size)
414 	 * as it is.
415 	 */
416 	data_sinfo = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_DATA);
417 	if (btrfs_is_zoned(fs_info))
418 		return data_sinfo->chunk_size;
419 	data_chunk_size = min(data_sinfo->chunk_size,
420 			      mult_perc(fs_info->fs_devices->total_rw_bytes, 10));
421 	return min_t(u64, data_chunk_size, SZ_1G);
422 }
423 
424 static u64 calc_available_free_space(struct btrfs_fs_info *fs_info,
425 			  const struct btrfs_space_info *space_info,
426 			  enum btrfs_reserve_flush_enum flush)
427 {
428 	u64 profile;
429 	u64 avail;
430 	u64 data_chunk_size;
431 	int factor;
432 
433 	if (space_info->flags & BTRFS_BLOCK_GROUP_SYSTEM)
434 		profile = btrfs_system_alloc_profile(fs_info);
435 	else
436 		profile = btrfs_metadata_alloc_profile(fs_info);
437 
438 	avail = atomic64_read(&fs_info->free_chunk_space);
439 
440 	/*
441 	 * If we have dup, raid1 or raid10 then only half of the free
442 	 * space is actually usable.  For raid56, the space info used
443 	 * doesn't include the parity drive, so we don't have to
444 	 * change the math
445 	 */
446 	factor = btrfs_bg_type_to_factor(profile);
447 	avail = div_u64(avail, factor);
448 	if (avail == 0)
449 		return 0;
450 
451 	data_chunk_size = calc_effective_data_chunk_size(fs_info);
452 
453 	/*
454 	 * Since data allocations immediately use block groups as part of the
455 	 * reservation, because we assume that data reservations will == actual
456 	 * usage, we could potentially overcommit and then immediately have that
457 	 * available space used by a data allocation, which could put us in a
458 	 * bind when we get close to filling the file system.
459 	 *
460 	 * To handle this simply remove the data_chunk_size from the available
461 	 * space.  If we are relatively empty this won't affect our ability to
462 	 * overcommit much, and if we're very close to full it'll keep us from
463 	 * getting into a position where we've given ourselves very little
464 	 * metadata wiggle room.
465 	 */
466 	if (avail <= data_chunk_size)
467 		return 0;
468 	avail -= data_chunk_size;
469 
470 	/*
471 	 * If we aren't flushing all things, let us overcommit up to
472 	 * 1/2th of the space. If we can flush, don't let us overcommit
473 	 * too much, let it overcommit up to 1/8 of the space.
474 	 */
475 	if (flush == BTRFS_RESERVE_FLUSH_ALL)
476 		avail >>= 3;
477 	else
478 		avail >>= 1;
479 
480 	/*
481 	 * On the zoned mode, we always allocate one zone as one chunk.
482 	 * Returning non-zone size alingned bytes here will result in
483 	 * less pressure for the async metadata reclaim process, and it
484 	 * will over-commit too much leading to ENOSPC. Align down to the
485 	 * zone size to avoid that.
486 	 */
487 	if (btrfs_is_zoned(fs_info))
488 		avail = ALIGN_DOWN(avail, fs_info->zone_size);
489 
490 	return avail;
491 }
492 
493 int btrfs_can_overcommit(struct btrfs_fs_info *fs_info,
494 			 const struct btrfs_space_info *space_info, u64 bytes,
495 			 enum btrfs_reserve_flush_enum flush)
496 {
497 	u64 avail;
498 	u64 used;
499 
500 	/* Don't overcommit when in mixed mode */
501 	if (space_info->flags & BTRFS_BLOCK_GROUP_DATA)
502 		return 0;
503 
504 	used = btrfs_space_info_used(space_info, true);
505 	avail = calc_available_free_space(fs_info, space_info, flush);
506 
507 	if (used + bytes < space_info->total_bytes + avail)
508 		return 1;
509 	return 0;
510 }
511 
512 static void remove_ticket(struct btrfs_space_info *space_info,
513 			  struct reserve_ticket *ticket)
514 {
515 	if (!list_empty(&ticket->list)) {
516 		list_del_init(&ticket->list);
517 		ASSERT(space_info->reclaim_size >= ticket->bytes);
518 		space_info->reclaim_size -= ticket->bytes;
519 	}
520 }
521 
522 /*
523  * This is for space we already have accounted in space_info->bytes_may_use, so
524  * basically when we're returning space from block_rsv's.
525  */
526 void btrfs_try_granting_tickets(struct btrfs_fs_info *fs_info,
527 				struct btrfs_space_info *space_info)
528 {
529 	struct list_head *head;
530 	enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_NO_FLUSH;
531 
532 	lockdep_assert_held(&space_info->lock);
533 
534 	head = &space_info->priority_tickets;
535 again:
536 	while (!list_empty(head)) {
537 		struct reserve_ticket *ticket;
538 		u64 used = btrfs_space_info_used(space_info, true);
539 
540 		ticket = list_first_entry(head, struct reserve_ticket, list);
541 
542 		/* Check and see if our ticket can be satisfied now. */
543 		if ((used + ticket->bytes <= space_info->total_bytes) ||
544 		    btrfs_can_overcommit(fs_info, space_info, ticket->bytes,
545 					 flush)) {
546 			btrfs_space_info_update_bytes_may_use(space_info, ticket->bytes);
547 			remove_ticket(space_info, ticket);
548 			ticket->bytes = 0;
549 			space_info->tickets_id++;
550 			wake_up(&ticket->wait);
551 		} else {
552 			break;
553 		}
554 	}
555 
556 	if (head == &space_info->priority_tickets) {
557 		head = &space_info->tickets;
558 		flush = BTRFS_RESERVE_FLUSH_ALL;
559 		goto again;
560 	}
561 }
562 
563 #define DUMP_BLOCK_RSV(fs_info, rsv_name)				\
564 do {									\
565 	struct btrfs_block_rsv *__rsv = &(fs_info)->rsv_name;		\
566 	spin_lock(&__rsv->lock);					\
567 	btrfs_info(fs_info, #rsv_name ": size %llu reserved %llu",	\
568 		   __rsv->size, __rsv->reserved);			\
569 	spin_unlock(&__rsv->lock);					\
570 } while (0)
571 
572 static const char *space_info_flag_to_str(const struct btrfs_space_info *space_info)
573 {
574 	switch (space_info->flags) {
575 	case BTRFS_BLOCK_GROUP_SYSTEM:
576 		return "SYSTEM";
577 	case BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA:
578 		return "DATA+METADATA";
579 	case BTRFS_BLOCK_GROUP_DATA:
580 		return "DATA";
581 	case BTRFS_BLOCK_GROUP_METADATA:
582 		return "METADATA";
583 	default:
584 		return "UNKNOWN";
585 	}
586 }
587 
588 static void dump_global_block_rsv(struct btrfs_fs_info *fs_info)
589 {
590 	DUMP_BLOCK_RSV(fs_info, global_block_rsv);
591 	DUMP_BLOCK_RSV(fs_info, trans_block_rsv);
592 	DUMP_BLOCK_RSV(fs_info, chunk_block_rsv);
593 	DUMP_BLOCK_RSV(fs_info, delayed_block_rsv);
594 	DUMP_BLOCK_RSV(fs_info, delayed_refs_rsv);
595 }
596 
597 static void __btrfs_dump_space_info(const struct btrfs_fs_info *fs_info,
598 				    const struct btrfs_space_info *info)
599 {
600 	const char *flag_str = space_info_flag_to_str(info);
601 	lockdep_assert_held(&info->lock);
602 
603 	/* The free space could be negative in case of overcommit */
604 	btrfs_info(fs_info,
605 		   "space_info %s (sub-group id %d) has %lld free, is %sfull",
606 		   flag_str, info->subgroup_id,
607 		   (s64)(info->total_bytes - btrfs_space_info_used(info, true)),
608 		   info->full ? "" : "not ");
609 	btrfs_info(fs_info,
610 "space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu zone_unusable=%llu",
611 		info->total_bytes, info->bytes_used, info->bytes_pinned,
612 		info->bytes_reserved, info->bytes_may_use,
613 		info->bytes_readonly, info->bytes_zone_unusable);
614 }
615 
616 void btrfs_dump_space_info(struct btrfs_fs_info *fs_info,
617 			   struct btrfs_space_info *info, u64 bytes,
618 			   int dump_block_groups)
619 {
620 	struct btrfs_block_group *cache;
621 	u64 total_avail = 0;
622 	int index = 0;
623 
624 	spin_lock(&info->lock);
625 	__btrfs_dump_space_info(fs_info, info);
626 	dump_global_block_rsv(fs_info);
627 	spin_unlock(&info->lock);
628 
629 	if (!dump_block_groups)
630 		return;
631 
632 	down_read(&info->groups_sem);
633 again:
634 	list_for_each_entry(cache, &info->block_groups[index], list) {
635 		u64 avail;
636 
637 		spin_lock(&cache->lock);
638 		avail = cache->length - cache->used - cache->pinned -
639 			cache->reserved - cache->bytes_super - cache->zone_unusable;
640 		btrfs_info(fs_info,
641 "block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %llu delalloc %llu super %llu zone_unusable (%llu bytes available) %s",
642 			   cache->start, cache->length, cache->used, cache->pinned,
643 			   cache->reserved, cache->delalloc_bytes,
644 			   cache->bytes_super, cache->zone_unusable,
645 			   avail, cache->ro ? "[readonly]" : "");
646 		spin_unlock(&cache->lock);
647 		btrfs_dump_free_space(cache, bytes);
648 		total_avail += avail;
649 	}
650 	if (++index < BTRFS_NR_RAID_TYPES)
651 		goto again;
652 	up_read(&info->groups_sem);
653 
654 	btrfs_info(fs_info, "%llu bytes available across all block groups", total_avail);
655 }
656 
657 static inline u64 calc_reclaim_items_nr(const struct btrfs_fs_info *fs_info,
658 					u64 to_reclaim)
659 {
660 	u64 bytes;
661 	u64 nr;
662 
663 	bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
664 	nr = div64_u64(to_reclaim, bytes);
665 	if (!nr)
666 		nr = 1;
667 	return nr;
668 }
669 
670 /*
671  * shrink metadata reservation for delalloc
672  */
673 static void shrink_delalloc(struct btrfs_fs_info *fs_info,
674 			    struct btrfs_space_info *space_info,
675 			    u64 to_reclaim, bool wait_ordered,
676 			    bool for_preempt)
677 {
678 	struct btrfs_trans_handle *trans;
679 	u64 delalloc_bytes;
680 	u64 ordered_bytes;
681 	u64 items;
682 	long time_left;
683 	int loops;
684 
685 	delalloc_bytes = percpu_counter_sum_positive(&fs_info->delalloc_bytes);
686 	ordered_bytes = percpu_counter_sum_positive(&fs_info->ordered_bytes);
687 	if (delalloc_bytes == 0 && ordered_bytes == 0)
688 		return;
689 
690 	/* Calc the number of the pages we need flush for space reservation */
691 	if (to_reclaim == U64_MAX) {
692 		items = U64_MAX;
693 	} else {
694 		/*
695 		 * to_reclaim is set to however much metadata we need to
696 		 * reclaim, but reclaiming that much data doesn't really track
697 		 * exactly.  What we really want to do is reclaim full inode's
698 		 * worth of reservations, however that's not available to us
699 		 * here.  We will take a fraction of the delalloc bytes for our
700 		 * flushing loops and hope for the best.  Delalloc will expand
701 		 * the amount we write to cover an entire dirty extent, which
702 		 * will reclaim the metadata reservation for that range.  If
703 		 * it's not enough subsequent flush stages will be more
704 		 * aggressive.
705 		 */
706 		to_reclaim = max(to_reclaim, delalloc_bytes >> 3);
707 		items = calc_reclaim_items_nr(fs_info, to_reclaim) * 2;
708 	}
709 
710 	trans = current->journal_info;
711 
712 	/*
713 	 * If we are doing more ordered than delalloc we need to just wait on
714 	 * ordered extents, otherwise we'll waste time trying to flush delalloc
715 	 * that likely won't give us the space back we need.
716 	 */
717 	if (ordered_bytes > delalloc_bytes && !for_preempt)
718 		wait_ordered = true;
719 
720 	loops = 0;
721 	while ((delalloc_bytes || ordered_bytes) && loops < 3) {
722 		u64 temp = min(delalloc_bytes, to_reclaim) >> PAGE_SHIFT;
723 		long nr_pages = min_t(u64, temp, LONG_MAX);
724 		int async_pages;
725 
726 		btrfs_start_delalloc_roots(fs_info, nr_pages, true);
727 
728 		/*
729 		 * We need to make sure any outstanding async pages are now
730 		 * processed before we continue.  This is because things like
731 		 * sync_inode() try to be smart and skip writing if the inode is
732 		 * marked clean.  We don't use filemap_fwrite for flushing
733 		 * because we want to control how many pages we write out at a
734 		 * time, thus this is the only safe way to make sure we've
735 		 * waited for outstanding compressed workers to have started
736 		 * their jobs and thus have ordered extents set up properly.
737 		 *
738 		 * This exists because we do not want to wait for each
739 		 * individual inode to finish its async work, we simply want to
740 		 * start the IO on everybody, and then come back here and wait
741 		 * for all of the async work to catch up.  Once we're done with
742 		 * that we know we'll have ordered extents for everything and we
743 		 * can decide if we wait for that or not.
744 		 *
745 		 * If we choose to replace this in the future, make absolutely
746 		 * sure that the proper waiting is being done in the async case,
747 		 * as there have been bugs in that area before.
748 		 */
749 		async_pages = atomic_read(&fs_info->async_delalloc_pages);
750 		if (!async_pages)
751 			goto skip_async;
752 
753 		/*
754 		 * We don't want to wait forever, if we wrote less pages in this
755 		 * loop than we have outstanding, only wait for that number of
756 		 * pages, otherwise we can wait for all async pages to finish
757 		 * before continuing.
758 		 */
759 		if (async_pages > nr_pages)
760 			async_pages -= nr_pages;
761 		else
762 			async_pages = 0;
763 		wait_event(fs_info->async_submit_wait,
764 			   atomic_read(&fs_info->async_delalloc_pages) <=
765 			   async_pages);
766 skip_async:
767 		loops++;
768 		if (wait_ordered && !trans) {
769 			btrfs_wait_ordered_roots(fs_info, items, NULL);
770 		} else {
771 			time_left = schedule_timeout_killable(1);
772 			if (time_left)
773 				break;
774 		}
775 
776 		/*
777 		 * If we are for preemption we just want a one-shot of delalloc
778 		 * flushing so we can stop flushing if we decide we don't need
779 		 * to anymore.
780 		 */
781 		if (for_preempt)
782 			break;
783 
784 		spin_lock(&space_info->lock);
785 		if (list_empty(&space_info->tickets) &&
786 		    list_empty(&space_info->priority_tickets)) {
787 			spin_unlock(&space_info->lock);
788 			break;
789 		}
790 		spin_unlock(&space_info->lock);
791 
792 		delalloc_bytes = percpu_counter_sum_positive(
793 						&fs_info->delalloc_bytes);
794 		ordered_bytes = percpu_counter_sum_positive(
795 						&fs_info->ordered_bytes);
796 	}
797 }
798 
799 /*
800  * Try to flush some data based on policy set by @state. This is only advisory
801  * and may fail for various reasons. The caller is supposed to examine the
802  * state of @space_info to detect the outcome.
803  */
804 static void flush_space(struct btrfs_fs_info *fs_info,
805 		       struct btrfs_space_info *space_info, u64 num_bytes,
806 		       enum btrfs_flush_state state, bool for_preempt)
807 {
808 	struct btrfs_root *root = fs_info->tree_root;
809 	struct btrfs_trans_handle *trans;
810 	int nr;
811 	int ret = 0;
812 
813 	switch (state) {
814 	case FLUSH_DELAYED_ITEMS_NR:
815 	case FLUSH_DELAYED_ITEMS:
816 		if (state == FLUSH_DELAYED_ITEMS_NR)
817 			nr = calc_reclaim_items_nr(fs_info, num_bytes) * 2;
818 		else
819 			nr = -1;
820 
821 		trans = btrfs_join_transaction_nostart(root);
822 		if (IS_ERR(trans)) {
823 			ret = PTR_ERR(trans);
824 			if (ret == -ENOENT)
825 				ret = 0;
826 			break;
827 		}
828 		ret = btrfs_run_delayed_items_nr(trans, nr);
829 		btrfs_end_transaction(trans);
830 		break;
831 	case FLUSH_DELALLOC:
832 	case FLUSH_DELALLOC_WAIT:
833 	case FLUSH_DELALLOC_FULL:
834 		if (state == FLUSH_DELALLOC_FULL)
835 			num_bytes = U64_MAX;
836 		shrink_delalloc(fs_info, space_info, num_bytes,
837 				state != FLUSH_DELALLOC, for_preempt);
838 		break;
839 	case FLUSH_DELAYED_REFS_NR:
840 	case FLUSH_DELAYED_REFS:
841 		trans = btrfs_join_transaction_nostart(root);
842 		if (IS_ERR(trans)) {
843 			ret = PTR_ERR(trans);
844 			if (ret == -ENOENT)
845 				ret = 0;
846 			break;
847 		}
848 		if (state == FLUSH_DELAYED_REFS_NR)
849 			btrfs_run_delayed_refs(trans, num_bytes);
850 		else
851 			btrfs_run_delayed_refs(trans, 0);
852 		btrfs_end_transaction(trans);
853 		break;
854 	case ALLOC_CHUNK:
855 	case ALLOC_CHUNK_FORCE:
856 		trans = btrfs_join_transaction(root);
857 		if (IS_ERR(trans)) {
858 			ret = PTR_ERR(trans);
859 			break;
860 		}
861 		ret = btrfs_chunk_alloc(trans, space_info,
862 				btrfs_get_alloc_profile(fs_info, space_info->flags),
863 				(state == ALLOC_CHUNK) ? CHUNK_ALLOC_NO_FORCE :
864 					CHUNK_ALLOC_FORCE);
865 		btrfs_end_transaction(trans);
866 
867 		if (ret > 0 || ret == -ENOSPC)
868 			ret = 0;
869 		break;
870 	case RUN_DELAYED_IPUTS:
871 		/*
872 		 * If we have pending delayed iputs then we could free up a
873 		 * bunch of pinned space, so make sure we run the iputs before
874 		 * we do our pinned bytes check below.
875 		 */
876 		btrfs_run_delayed_iputs(fs_info);
877 		btrfs_wait_on_delayed_iputs(fs_info);
878 		break;
879 	case COMMIT_TRANS:
880 		ASSERT(current->journal_info == NULL);
881 		/*
882 		 * We don't want to start a new transaction, just attach to the
883 		 * current one or wait it fully commits in case its commit is
884 		 * happening at the moment. Note: we don't use a nostart join
885 		 * because that does not wait for a transaction to fully commit
886 		 * (only for it to be unblocked, state TRANS_STATE_UNBLOCKED).
887 		 */
888 		ret = btrfs_commit_current_transaction(root);
889 		break;
890 	case RESET_ZONES:
891 		ret = btrfs_reset_unused_block_groups(space_info, num_bytes);
892 		break;
893 	default:
894 		ret = -ENOSPC;
895 		break;
896 	}
897 
898 	trace_btrfs_flush_space(fs_info, space_info->flags, num_bytes, state,
899 				ret, for_preempt);
900 	return;
901 }
902 
903 static u64 btrfs_calc_reclaim_metadata_size(struct btrfs_fs_info *fs_info,
904 					    const struct btrfs_space_info *space_info)
905 {
906 	u64 used;
907 	u64 avail;
908 	u64 to_reclaim = space_info->reclaim_size;
909 
910 	lockdep_assert_held(&space_info->lock);
911 
912 	avail = calc_available_free_space(fs_info, space_info,
913 					  BTRFS_RESERVE_FLUSH_ALL);
914 	used = btrfs_space_info_used(space_info, true);
915 
916 	/*
917 	 * We may be flushing because suddenly we have less space than we had
918 	 * before, and now we're well over-committed based on our current free
919 	 * space.  If that's the case add in our overage so we make sure to put
920 	 * appropriate pressure on the flushing state machine.
921 	 */
922 	if (space_info->total_bytes + avail < used)
923 		to_reclaim += used - (space_info->total_bytes + avail);
924 
925 	return to_reclaim;
926 }
927 
928 static bool need_preemptive_reclaim(struct btrfs_fs_info *fs_info,
929 				    const struct btrfs_space_info *space_info)
930 {
931 	const u64 global_rsv_size = btrfs_block_rsv_reserved(&fs_info->global_block_rsv);
932 	u64 ordered, delalloc;
933 	u64 thresh;
934 	u64 used;
935 
936 	thresh = mult_perc(space_info->total_bytes, 90);
937 
938 	lockdep_assert_held(&space_info->lock);
939 
940 	/* If we're just plain full then async reclaim just slows us down. */
941 	if ((space_info->bytes_used + space_info->bytes_reserved +
942 	     global_rsv_size) >= thresh)
943 		return false;
944 
945 	used = space_info->bytes_may_use + space_info->bytes_pinned;
946 
947 	/* The total flushable belongs to the global rsv, don't flush. */
948 	if (global_rsv_size >= used)
949 		return false;
950 
951 	/*
952 	 * 128MiB is 1/4 of the maximum global rsv size.  If we have less than
953 	 * that devoted to other reservations then there's no sense in flushing,
954 	 * we don't have a lot of things that need flushing.
955 	 */
956 	if (used - global_rsv_size <= SZ_128M)
957 		return false;
958 
959 	/*
960 	 * We have tickets queued, bail so we don't compete with the async
961 	 * flushers.
962 	 */
963 	if (space_info->reclaim_size)
964 		return false;
965 
966 	/*
967 	 * If we have over half of the free space occupied by reservations or
968 	 * pinned then we want to start flushing.
969 	 *
970 	 * We do not do the traditional thing here, which is to say
971 	 *
972 	 *   if (used >= ((total_bytes + avail) / 2))
973 	 *     return 1;
974 	 *
975 	 * because this doesn't quite work how we want.  If we had more than 50%
976 	 * of the space_info used by bytes_used and we had 0 available we'd just
977 	 * constantly run the background flusher.  Instead we want it to kick in
978 	 * if our reclaimable space exceeds our clamped free space.
979 	 *
980 	 * Our clamping range is 2^1 -> 2^8.  Practically speaking that means
981 	 * the following:
982 	 *
983 	 * Amount of RAM        Minimum threshold       Maximum threshold
984 	 *
985 	 *        256GiB                     1GiB                  128GiB
986 	 *        128GiB                   512MiB                   64GiB
987 	 *         64GiB                   256MiB                   32GiB
988 	 *         32GiB                   128MiB                   16GiB
989 	 *         16GiB                    64MiB                    8GiB
990 	 *
991 	 * These are the range our thresholds will fall in, corresponding to how
992 	 * much delalloc we need for the background flusher to kick in.
993 	 */
994 
995 	thresh = calc_available_free_space(fs_info, space_info,
996 					   BTRFS_RESERVE_FLUSH_ALL);
997 	used = space_info->bytes_used + space_info->bytes_reserved +
998 	       space_info->bytes_readonly + global_rsv_size;
999 	if (used < space_info->total_bytes)
1000 		thresh += space_info->total_bytes - used;
1001 	thresh >>= space_info->clamp;
1002 
1003 	used = space_info->bytes_pinned;
1004 
1005 	/*
1006 	 * If we have more ordered bytes than delalloc bytes then we're either
1007 	 * doing a lot of DIO, or we simply don't have a lot of delalloc waiting
1008 	 * around.  Preemptive flushing is only useful in that it can free up
1009 	 * space before tickets need to wait for things to finish.  In the case
1010 	 * of ordered extents, preemptively waiting on ordered extents gets us
1011 	 * nothing, if our reservations are tied up in ordered extents we'll
1012 	 * simply have to slow down writers by forcing them to wait on ordered
1013 	 * extents.
1014 	 *
1015 	 * In the case that ordered is larger than delalloc, only include the
1016 	 * block reserves that we would actually be able to directly reclaim
1017 	 * from.  In this case if we're heavy on metadata operations this will
1018 	 * clearly be heavy enough to warrant preemptive flushing.  In the case
1019 	 * of heavy DIO or ordered reservations, preemptive flushing will just
1020 	 * waste time and cause us to slow down.
1021 	 *
1022 	 * We want to make sure we truly are maxed out on ordered however, so
1023 	 * cut ordered in half, and if it's still higher than delalloc then we
1024 	 * can keep flushing.  This is to avoid the case where we start
1025 	 * flushing, and now delalloc == ordered and we stop preemptively
1026 	 * flushing when we could still have several gigs of delalloc to flush.
1027 	 */
1028 	ordered = percpu_counter_read_positive(&fs_info->ordered_bytes) >> 1;
1029 	delalloc = percpu_counter_read_positive(&fs_info->delalloc_bytes);
1030 	if (ordered >= delalloc)
1031 		used += btrfs_block_rsv_reserved(&fs_info->delayed_refs_rsv) +
1032 			btrfs_block_rsv_reserved(&fs_info->delayed_block_rsv);
1033 	else
1034 		used += space_info->bytes_may_use - global_rsv_size;
1035 
1036 	return (used >= thresh && !btrfs_fs_closing(fs_info) &&
1037 		!test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
1038 }
1039 
1040 static bool steal_from_global_rsv(struct btrfs_fs_info *fs_info,
1041 				  struct btrfs_space_info *space_info,
1042 				  struct reserve_ticket *ticket)
1043 {
1044 	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
1045 	u64 min_bytes;
1046 
1047 	if (!ticket->steal)
1048 		return false;
1049 
1050 	if (global_rsv->space_info != space_info)
1051 		return false;
1052 
1053 	spin_lock(&global_rsv->lock);
1054 	min_bytes = mult_perc(global_rsv->size, 10);
1055 	if (global_rsv->reserved < min_bytes + ticket->bytes) {
1056 		spin_unlock(&global_rsv->lock);
1057 		return false;
1058 	}
1059 	global_rsv->reserved -= ticket->bytes;
1060 	remove_ticket(space_info, ticket);
1061 	ticket->bytes = 0;
1062 	wake_up(&ticket->wait);
1063 	space_info->tickets_id++;
1064 	if (global_rsv->reserved < global_rsv->size)
1065 		global_rsv->full = 0;
1066 	spin_unlock(&global_rsv->lock);
1067 
1068 	return true;
1069 }
1070 
1071 /*
1072  * We've exhausted our flushing, start failing tickets.
1073  *
1074  * @fs_info - fs_info for this fs
1075  * @space_info - the space info we were flushing
1076  *
1077  * We call this when we've exhausted our flushing ability and haven't made
1078  * progress in satisfying tickets.  The reservation code handles tickets in
1079  * order, so if there is a large ticket first and then smaller ones we could
1080  * very well satisfy the smaller tickets.  This will attempt to wake up any
1081  * tickets in the list to catch this case.
1082  *
1083  * This function returns true if it was able to make progress by clearing out
1084  * other tickets, or if it stumbles across a ticket that was smaller than the
1085  * first ticket.
1086  */
1087 static bool maybe_fail_all_tickets(struct btrfs_fs_info *fs_info,
1088 				   struct btrfs_space_info *space_info)
1089 {
1090 	struct reserve_ticket *ticket;
1091 	u64 tickets_id = space_info->tickets_id;
1092 	const bool aborted = BTRFS_FS_ERROR(fs_info);
1093 
1094 	trace_btrfs_fail_all_tickets(fs_info, space_info);
1095 
1096 	if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1097 		btrfs_info(fs_info, "cannot satisfy tickets, dumping space info");
1098 		__btrfs_dump_space_info(fs_info, space_info);
1099 	}
1100 
1101 	while (!list_empty(&space_info->tickets) &&
1102 	       tickets_id == space_info->tickets_id) {
1103 		ticket = list_first_entry(&space_info->tickets,
1104 					  struct reserve_ticket, list);
1105 
1106 		if (!aborted && steal_from_global_rsv(fs_info, space_info, ticket))
1107 			return true;
1108 
1109 		if (!aborted && btrfs_test_opt(fs_info, ENOSPC_DEBUG))
1110 			btrfs_info(fs_info, "failing ticket with %llu bytes",
1111 				   ticket->bytes);
1112 
1113 		remove_ticket(space_info, ticket);
1114 		if (aborted)
1115 			ticket->error = -EIO;
1116 		else
1117 			ticket->error = -ENOSPC;
1118 		wake_up(&ticket->wait);
1119 
1120 		/*
1121 		 * We're just throwing tickets away, so more flushing may not
1122 		 * trip over btrfs_try_granting_tickets, so we need to call it
1123 		 * here to see if we can make progress with the next ticket in
1124 		 * the list.
1125 		 */
1126 		if (!aborted)
1127 			btrfs_try_granting_tickets(fs_info, space_info);
1128 	}
1129 	return (tickets_id != space_info->tickets_id);
1130 }
1131 
1132 static void do_async_reclaim_metadata_space(struct btrfs_space_info *space_info)
1133 {
1134 	struct btrfs_fs_info *fs_info = space_info->fs_info;
1135 	u64 to_reclaim;
1136 	enum btrfs_flush_state flush_state;
1137 	int commit_cycles = 0;
1138 	u64 last_tickets_id;
1139 	enum btrfs_flush_state final_state;
1140 
1141 	if (btrfs_is_zoned(fs_info))
1142 		final_state = RESET_ZONES;
1143 	else
1144 		final_state = COMMIT_TRANS;
1145 
1146 	spin_lock(&space_info->lock);
1147 	to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info);
1148 	if (!to_reclaim) {
1149 		space_info->flush = 0;
1150 		spin_unlock(&space_info->lock);
1151 		return;
1152 	}
1153 	last_tickets_id = space_info->tickets_id;
1154 	spin_unlock(&space_info->lock);
1155 
1156 	flush_state = FLUSH_DELAYED_ITEMS_NR;
1157 	do {
1158 		flush_space(fs_info, space_info, to_reclaim, flush_state, false);
1159 		spin_lock(&space_info->lock);
1160 		if (list_empty(&space_info->tickets)) {
1161 			space_info->flush = 0;
1162 			spin_unlock(&space_info->lock);
1163 			return;
1164 		}
1165 		to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info,
1166 							      space_info);
1167 		if (last_tickets_id == space_info->tickets_id) {
1168 			flush_state++;
1169 		} else {
1170 			last_tickets_id = space_info->tickets_id;
1171 			flush_state = FLUSH_DELAYED_ITEMS_NR;
1172 			if (commit_cycles)
1173 				commit_cycles--;
1174 		}
1175 
1176 		/*
1177 		 * We do not want to empty the system of delalloc unless we're
1178 		 * under heavy pressure, so allow one trip through the flushing
1179 		 * logic before we start doing a FLUSH_DELALLOC_FULL.
1180 		 */
1181 		if (flush_state == FLUSH_DELALLOC_FULL && !commit_cycles)
1182 			flush_state++;
1183 
1184 		/*
1185 		 * We don't want to force a chunk allocation until we've tried
1186 		 * pretty hard to reclaim space.  Think of the case where we
1187 		 * freed up a bunch of space and so have a lot of pinned space
1188 		 * to reclaim.  We would rather use that than possibly create a
1189 		 * underutilized metadata chunk.  So if this is our first run
1190 		 * through the flushing state machine skip ALLOC_CHUNK_FORCE and
1191 		 * commit the transaction.  If nothing has changed the next go
1192 		 * around then we can force a chunk allocation.
1193 		 */
1194 		if (flush_state == ALLOC_CHUNK_FORCE && !commit_cycles)
1195 			flush_state++;
1196 
1197 		if (flush_state > final_state) {
1198 			commit_cycles++;
1199 			if (commit_cycles > 2) {
1200 				if (maybe_fail_all_tickets(fs_info, space_info)) {
1201 					flush_state = FLUSH_DELAYED_ITEMS_NR;
1202 					commit_cycles--;
1203 				} else {
1204 					space_info->flush = 0;
1205 				}
1206 			} else {
1207 				flush_state = FLUSH_DELAYED_ITEMS_NR;
1208 			}
1209 		}
1210 		spin_unlock(&space_info->lock);
1211 	} while (flush_state <= final_state);
1212 }
1213 
1214 /*
1215  * This is for normal flushers, it can wait as much time as needed. We will
1216  * loop and continuously try to flush as long as we are making progress.  We
1217  * count progress as clearing off tickets each time we have to loop.
1218  */
1219 static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
1220 {
1221 	struct btrfs_fs_info *fs_info;
1222 	struct btrfs_space_info *space_info;
1223 
1224 	fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
1225 	space_info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
1226 	do_async_reclaim_metadata_space(space_info);
1227 	for (int i = 0; i < BTRFS_SPACE_INFO_SUB_GROUP_MAX; i++) {
1228 		if (space_info->sub_group[i])
1229 			do_async_reclaim_metadata_space(space_info->sub_group[i]);
1230 	}
1231 }
1232 
1233 /*
1234  * This handles pre-flushing of metadata space before we get to the point that
1235  * we need to start blocking threads on tickets.  The logic here is different
1236  * from the other flush paths because it doesn't rely on tickets to tell us how
1237  * much we need to flush, instead it attempts to keep us below the 80% full
1238  * watermark of space by flushing whichever reservation pool is currently the
1239  * largest.
1240  */
1241 static void btrfs_preempt_reclaim_metadata_space(struct work_struct *work)
1242 {
1243 	struct btrfs_fs_info *fs_info;
1244 	struct btrfs_space_info *space_info;
1245 	struct btrfs_block_rsv *delayed_block_rsv;
1246 	struct btrfs_block_rsv *delayed_refs_rsv;
1247 	struct btrfs_block_rsv *global_rsv;
1248 	struct btrfs_block_rsv *trans_rsv;
1249 	int loops = 0;
1250 
1251 	fs_info = container_of(work, struct btrfs_fs_info,
1252 			       preempt_reclaim_work);
1253 	space_info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
1254 	delayed_block_rsv = &fs_info->delayed_block_rsv;
1255 	delayed_refs_rsv = &fs_info->delayed_refs_rsv;
1256 	global_rsv = &fs_info->global_block_rsv;
1257 	trans_rsv = &fs_info->trans_block_rsv;
1258 
1259 	spin_lock(&space_info->lock);
1260 	while (need_preemptive_reclaim(fs_info, space_info)) {
1261 		enum btrfs_flush_state flush;
1262 		u64 delalloc_size = 0;
1263 		u64 to_reclaim, block_rsv_size;
1264 		const u64 global_rsv_size = btrfs_block_rsv_reserved(global_rsv);
1265 
1266 		loops++;
1267 
1268 		/*
1269 		 * We don't have a precise counter for the metadata being
1270 		 * reserved for delalloc, so we'll approximate it by subtracting
1271 		 * out the block rsv's space from the bytes_may_use.  If that
1272 		 * amount is higher than the individual reserves, then we can
1273 		 * assume it's tied up in delalloc reservations.
1274 		 */
1275 		block_rsv_size = global_rsv_size +
1276 			btrfs_block_rsv_reserved(delayed_block_rsv) +
1277 			btrfs_block_rsv_reserved(delayed_refs_rsv) +
1278 			btrfs_block_rsv_reserved(trans_rsv);
1279 		if (block_rsv_size < space_info->bytes_may_use)
1280 			delalloc_size = space_info->bytes_may_use - block_rsv_size;
1281 
1282 		/*
1283 		 * We don't want to include the global_rsv in our calculation,
1284 		 * because that's space we can't touch.  Subtract it from the
1285 		 * block_rsv_size for the next checks.
1286 		 */
1287 		block_rsv_size -= global_rsv_size;
1288 
1289 		/*
1290 		 * We really want to avoid flushing delalloc too much, as it
1291 		 * could result in poor allocation patterns, so only flush it if
1292 		 * it's larger than the rest of the pools combined.
1293 		 */
1294 		if (delalloc_size > block_rsv_size) {
1295 			to_reclaim = delalloc_size;
1296 			flush = FLUSH_DELALLOC;
1297 		} else if (space_info->bytes_pinned >
1298 			   (btrfs_block_rsv_reserved(delayed_block_rsv) +
1299 			    btrfs_block_rsv_reserved(delayed_refs_rsv))) {
1300 			to_reclaim = space_info->bytes_pinned;
1301 			flush = COMMIT_TRANS;
1302 		} else if (btrfs_block_rsv_reserved(delayed_block_rsv) >
1303 			   btrfs_block_rsv_reserved(delayed_refs_rsv)) {
1304 			to_reclaim = btrfs_block_rsv_reserved(delayed_block_rsv);
1305 			flush = FLUSH_DELAYED_ITEMS_NR;
1306 		} else {
1307 			to_reclaim = btrfs_block_rsv_reserved(delayed_refs_rsv);
1308 			flush = FLUSH_DELAYED_REFS_NR;
1309 		}
1310 
1311 		spin_unlock(&space_info->lock);
1312 
1313 		/*
1314 		 * We don't want to reclaim everything, just a portion, so scale
1315 		 * down the to_reclaim by 1/4.  If it takes us down to 0,
1316 		 * reclaim 1 items worth.
1317 		 */
1318 		to_reclaim >>= 2;
1319 		if (!to_reclaim)
1320 			to_reclaim = btrfs_calc_insert_metadata_size(fs_info, 1);
1321 		flush_space(fs_info, space_info, to_reclaim, flush, true);
1322 		cond_resched();
1323 		spin_lock(&space_info->lock);
1324 	}
1325 
1326 	/* We only went through once, back off our clamping. */
1327 	if (loops == 1 && !space_info->reclaim_size)
1328 		space_info->clamp = max(1, space_info->clamp - 1);
1329 	trace_btrfs_done_preemptive_reclaim(fs_info, space_info);
1330 	spin_unlock(&space_info->lock);
1331 }
1332 
1333 /*
1334  * FLUSH_DELALLOC_WAIT:
1335  *   Space is freed from flushing delalloc in one of two ways.
1336  *
1337  *   1) compression is on and we allocate less space than we reserved
1338  *   2) we are overwriting existing space
1339  *
1340  *   For #1 that extra space is reclaimed as soon as the delalloc pages are
1341  *   COWed, by way of btrfs_add_reserved_bytes() which adds the actual extent
1342  *   length to ->bytes_reserved, and subtracts the reserved space from
1343  *   ->bytes_may_use.
1344  *
1345  *   For #2 this is trickier.  Once the ordered extent runs we will drop the
1346  *   extent in the range we are overwriting, which creates a delayed ref for
1347  *   that freed extent.  This however is not reclaimed until the transaction
1348  *   commits, thus the next stages.
1349  *
1350  * RUN_DELAYED_IPUTS
1351  *   If we are freeing inodes, we want to make sure all delayed iputs have
1352  *   completed, because they could have been on an inode with i_nlink == 0, and
1353  *   thus have been truncated and freed up space.  But again this space is not
1354  *   immediately reusable, it comes in the form of a delayed ref, which must be
1355  *   run and then the transaction must be committed.
1356  *
1357  * COMMIT_TRANS
1358  *   This is where we reclaim all of the pinned space generated by running the
1359  *   iputs
1360  *
1361  * RESET_ZONES
1362  *   This state works only for the zoned mode. We scan the unused block group
1363  *   list and reset the zones and reuse the block group.
1364  *
1365  * ALLOC_CHUNK_FORCE
1366  *   For data we start with alloc chunk force, however we could have been full
1367  *   before, and then the transaction commit could have freed new block groups,
1368  *   so if we now have space to allocate do the force chunk allocation.
1369  */
1370 static const enum btrfs_flush_state data_flush_states[] = {
1371 	FLUSH_DELALLOC_FULL,
1372 	RUN_DELAYED_IPUTS,
1373 	COMMIT_TRANS,
1374 	RESET_ZONES,
1375 	ALLOC_CHUNK_FORCE,
1376 };
1377 
1378 static void do_async_reclaim_data_space(struct btrfs_space_info *space_info)
1379 {
1380 	struct btrfs_fs_info *fs_info = space_info->fs_info;
1381 	u64 last_tickets_id;
1382 	enum btrfs_flush_state flush_state = 0;
1383 
1384 	spin_lock(&space_info->lock);
1385 	if (list_empty(&space_info->tickets)) {
1386 		space_info->flush = 0;
1387 		spin_unlock(&space_info->lock);
1388 		return;
1389 	}
1390 	last_tickets_id = space_info->tickets_id;
1391 	spin_unlock(&space_info->lock);
1392 
1393 	while (!space_info->full) {
1394 		flush_space(fs_info, space_info, U64_MAX, ALLOC_CHUNK_FORCE, false);
1395 		spin_lock(&space_info->lock);
1396 		if (list_empty(&space_info->tickets)) {
1397 			space_info->flush = 0;
1398 			spin_unlock(&space_info->lock);
1399 			return;
1400 		}
1401 
1402 		/* Something happened, fail everything and bail. */
1403 		if (BTRFS_FS_ERROR(fs_info))
1404 			goto aborted_fs;
1405 		last_tickets_id = space_info->tickets_id;
1406 		spin_unlock(&space_info->lock);
1407 	}
1408 
1409 	while (flush_state < ARRAY_SIZE(data_flush_states)) {
1410 		flush_space(fs_info, space_info, U64_MAX,
1411 			    data_flush_states[flush_state], false);
1412 		spin_lock(&space_info->lock);
1413 		if (list_empty(&space_info->tickets)) {
1414 			space_info->flush = 0;
1415 			spin_unlock(&space_info->lock);
1416 			return;
1417 		}
1418 
1419 		if (last_tickets_id == space_info->tickets_id) {
1420 			flush_state++;
1421 		} else {
1422 			last_tickets_id = space_info->tickets_id;
1423 			flush_state = 0;
1424 		}
1425 
1426 		if (flush_state >= ARRAY_SIZE(data_flush_states)) {
1427 			if (space_info->full) {
1428 				if (maybe_fail_all_tickets(fs_info, space_info))
1429 					flush_state = 0;
1430 				else
1431 					space_info->flush = 0;
1432 			} else {
1433 				flush_state = 0;
1434 			}
1435 
1436 			/* Something happened, fail everything and bail. */
1437 			if (BTRFS_FS_ERROR(fs_info))
1438 				goto aborted_fs;
1439 
1440 		}
1441 		spin_unlock(&space_info->lock);
1442 	}
1443 	return;
1444 
1445 aborted_fs:
1446 	maybe_fail_all_tickets(fs_info, space_info);
1447 	space_info->flush = 0;
1448 	spin_unlock(&space_info->lock);
1449 }
1450 
1451 static void btrfs_async_reclaim_data_space(struct work_struct *work)
1452 {
1453 	struct btrfs_fs_info *fs_info;
1454 	struct btrfs_space_info *space_info;
1455 
1456 	fs_info = container_of(work, struct btrfs_fs_info, async_data_reclaim_work);
1457 	space_info = fs_info->data_sinfo;
1458 	do_async_reclaim_data_space(space_info);
1459 	for (int i = 0; i < BTRFS_SPACE_INFO_SUB_GROUP_MAX; i++)
1460 		if (space_info->sub_group[i])
1461 			do_async_reclaim_data_space(space_info->sub_group[i]);
1462 }
1463 
1464 void btrfs_init_async_reclaim_work(struct btrfs_fs_info *fs_info)
1465 {
1466 	INIT_WORK(&fs_info->async_reclaim_work, btrfs_async_reclaim_metadata_space);
1467 	INIT_WORK(&fs_info->async_data_reclaim_work, btrfs_async_reclaim_data_space);
1468 	INIT_WORK(&fs_info->preempt_reclaim_work,
1469 		  btrfs_preempt_reclaim_metadata_space);
1470 }
1471 
1472 static const enum btrfs_flush_state priority_flush_states[] = {
1473 	FLUSH_DELAYED_ITEMS_NR,
1474 	FLUSH_DELAYED_ITEMS,
1475 	RESET_ZONES,
1476 	ALLOC_CHUNK,
1477 };
1478 
1479 static const enum btrfs_flush_state evict_flush_states[] = {
1480 	FLUSH_DELAYED_ITEMS_NR,
1481 	FLUSH_DELAYED_ITEMS,
1482 	FLUSH_DELAYED_REFS_NR,
1483 	FLUSH_DELAYED_REFS,
1484 	FLUSH_DELALLOC,
1485 	FLUSH_DELALLOC_WAIT,
1486 	FLUSH_DELALLOC_FULL,
1487 	ALLOC_CHUNK,
1488 	COMMIT_TRANS,
1489 	RESET_ZONES,
1490 };
1491 
1492 static void priority_reclaim_metadata_space(struct btrfs_fs_info *fs_info,
1493 				struct btrfs_space_info *space_info,
1494 				struct reserve_ticket *ticket,
1495 				const enum btrfs_flush_state *states,
1496 				int states_nr)
1497 {
1498 	u64 to_reclaim;
1499 	int flush_state = 0;
1500 
1501 	spin_lock(&space_info->lock);
1502 	to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info);
1503 	/*
1504 	 * This is the priority reclaim path, so to_reclaim could be >0 still
1505 	 * because we may have only satisfied the priority tickets and still
1506 	 * left non priority tickets on the list.  We would then have
1507 	 * to_reclaim but ->bytes == 0.
1508 	 */
1509 	if (ticket->bytes == 0) {
1510 		spin_unlock(&space_info->lock);
1511 		return;
1512 	}
1513 
1514 	while (flush_state < states_nr) {
1515 		spin_unlock(&space_info->lock);
1516 		flush_space(fs_info, space_info, to_reclaim, states[flush_state],
1517 			    false);
1518 		flush_state++;
1519 		spin_lock(&space_info->lock);
1520 		if (ticket->bytes == 0) {
1521 			spin_unlock(&space_info->lock);
1522 			return;
1523 		}
1524 	}
1525 
1526 	/*
1527 	 * Attempt to steal from the global rsv if we can, except if the fs was
1528 	 * turned into error mode due to a transaction abort when flushing space
1529 	 * above, in that case fail with the abort error instead of returning
1530 	 * success to the caller if we can steal from the global rsv - this is
1531 	 * just to have caller fail immeditelly instead of later when trying to
1532 	 * modify the fs, making it easier to debug -ENOSPC problems.
1533 	 */
1534 	if (BTRFS_FS_ERROR(fs_info)) {
1535 		ticket->error = BTRFS_FS_ERROR(fs_info);
1536 		remove_ticket(space_info, ticket);
1537 	} else if (!steal_from_global_rsv(fs_info, space_info, ticket)) {
1538 		ticket->error = -ENOSPC;
1539 		remove_ticket(space_info, ticket);
1540 	}
1541 
1542 	/*
1543 	 * We must run try_granting_tickets here because we could be a large
1544 	 * ticket in front of a smaller ticket that can now be satisfied with
1545 	 * the available space.
1546 	 */
1547 	btrfs_try_granting_tickets(fs_info, space_info);
1548 	spin_unlock(&space_info->lock);
1549 }
1550 
1551 static void priority_reclaim_data_space(struct btrfs_fs_info *fs_info,
1552 					struct btrfs_space_info *space_info,
1553 					struct reserve_ticket *ticket)
1554 {
1555 	spin_lock(&space_info->lock);
1556 
1557 	/* We could have been granted before we got here. */
1558 	if (ticket->bytes == 0) {
1559 		spin_unlock(&space_info->lock);
1560 		return;
1561 	}
1562 
1563 	while (!space_info->full) {
1564 		spin_unlock(&space_info->lock);
1565 		flush_space(fs_info, space_info, U64_MAX, ALLOC_CHUNK_FORCE, false);
1566 		spin_lock(&space_info->lock);
1567 		if (ticket->bytes == 0) {
1568 			spin_unlock(&space_info->lock);
1569 			return;
1570 		}
1571 	}
1572 
1573 	ticket->error = -ENOSPC;
1574 	remove_ticket(space_info, ticket);
1575 	btrfs_try_granting_tickets(fs_info, space_info);
1576 	spin_unlock(&space_info->lock);
1577 }
1578 
1579 static void wait_reserve_ticket(struct btrfs_space_info *space_info,
1580 				struct reserve_ticket *ticket)
1581 
1582 {
1583 	DEFINE_WAIT(wait);
1584 	int ret = 0;
1585 
1586 	spin_lock(&space_info->lock);
1587 	while (ticket->bytes > 0 && ticket->error == 0) {
1588 		ret = prepare_to_wait_event(&ticket->wait, &wait, TASK_KILLABLE);
1589 		if (ret) {
1590 			/*
1591 			 * Delete us from the list. After we unlock the space
1592 			 * info, we don't want the async reclaim job to reserve
1593 			 * space for this ticket. If that would happen, then the
1594 			 * ticket's task would not known that space was reserved
1595 			 * despite getting an error, resulting in a space leak
1596 			 * (bytes_may_use counter of our space_info).
1597 			 */
1598 			remove_ticket(space_info, ticket);
1599 			ticket->error = -EINTR;
1600 			break;
1601 		}
1602 		spin_unlock(&space_info->lock);
1603 
1604 		schedule();
1605 
1606 		finish_wait(&ticket->wait, &wait);
1607 		spin_lock(&space_info->lock);
1608 	}
1609 	spin_unlock(&space_info->lock);
1610 }
1611 
1612 /*
1613  * Do the appropriate flushing and waiting for a ticket.
1614  *
1615  * @fs_info:    the filesystem
1616  * @space_info: space info for the reservation
1617  * @ticket:     ticket for the reservation
1618  * @start_ns:   timestamp when the reservation started
1619  * @orig_bytes: amount of bytes originally reserved
1620  * @flush:      how much we can flush
1621  *
1622  * This does the work of figuring out how to flush for the ticket, waiting for
1623  * the reservation, and returning the appropriate error if there is one.
1624  */
1625 static int handle_reserve_ticket(struct btrfs_fs_info *fs_info,
1626 				 struct btrfs_space_info *space_info,
1627 				 struct reserve_ticket *ticket,
1628 				 u64 start_ns, u64 orig_bytes,
1629 				 enum btrfs_reserve_flush_enum flush)
1630 {
1631 	int ret;
1632 
1633 	switch (flush) {
1634 	case BTRFS_RESERVE_FLUSH_DATA:
1635 	case BTRFS_RESERVE_FLUSH_ALL:
1636 	case BTRFS_RESERVE_FLUSH_ALL_STEAL:
1637 		wait_reserve_ticket(space_info, ticket);
1638 		break;
1639 	case BTRFS_RESERVE_FLUSH_LIMIT:
1640 		priority_reclaim_metadata_space(fs_info, space_info, ticket,
1641 						priority_flush_states,
1642 						ARRAY_SIZE(priority_flush_states));
1643 		break;
1644 	case BTRFS_RESERVE_FLUSH_EVICT:
1645 		priority_reclaim_metadata_space(fs_info, space_info, ticket,
1646 						evict_flush_states,
1647 						ARRAY_SIZE(evict_flush_states));
1648 		break;
1649 	case BTRFS_RESERVE_FLUSH_FREE_SPACE_INODE:
1650 		priority_reclaim_data_space(fs_info, space_info, ticket);
1651 		break;
1652 	default:
1653 		ASSERT(0);
1654 		break;
1655 	}
1656 
1657 	ret = ticket->error;
1658 	ASSERT(list_empty(&ticket->list));
1659 	/*
1660 	 * Check that we can't have an error set if the reservation succeeded,
1661 	 * as that would confuse tasks and lead them to error out without
1662 	 * releasing reserved space (if an error happens the expectation is that
1663 	 * space wasn't reserved at all).
1664 	 */
1665 	ASSERT(!(ticket->bytes == 0 && ticket->error));
1666 	trace_btrfs_reserve_ticket(fs_info, space_info->flags, orig_bytes,
1667 				   start_ns, flush, ticket->error);
1668 	return ret;
1669 }
1670 
1671 /*
1672  * This returns true if this flush state will go through the ordinary flushing
1673  * code.
1674  */
1675 static inline bool is_normal_flushing(enum btrfs_reserve_flush_enum flush)
1676 {
1677 	return	(flush == BTRFS_RESERVE_FLUSH_ALL) ||
1678 		(flush == BTRFS_RESERVE_FLUSH_ALL_STEAL);
1679 }
1680 
1681 static inline void maybe_clamp_preempt(struct btrfs_fs_info *fs_info,
1682 				       struct btrfs_space_info *space_info)
1683 {
1684 	u64 ordered = percpu_counter_sum_positive(&fs_info->ordered_bytes);
1685 	u64 delalloc = percpu_counter_sum_positive(&fs_info->delalloc_bytes);
1686 
1687 	/*
1688 	 * If we're heavy on ordered operations then clamping won't help us.  We
1689 	 * need to clamp specifically to keep up with dirty'ing buffered
1690 	 * writers, because there's not a 1:1 correlation of writing delalloc
1691 	 * and freeing space, like there is with flushing delayed refs or
1692 	 * delayed nodes.  If we're already more ordered than delalloc then
1693 	 * we're keeping up, otherwise we aren't and should probably clamp.
1694 	 */
1695 	if (ordered < delalloc)
1696 		space_info->clamp = min(space_info->clamp + 1, 8);
1697 }
1698 
1699 static inline bool can_steal(enum btrfs_reserve_flush_enum flush)
1700 {
1701 	return (flush == BTRFS_RESERVE_FLUSH_ALL_STEAL ||
1702 		flush == BTRFS_RESERVE_FLUSH_EVICT);
1703 }
1704 
1705 /*
1706  * NO_FLUSH and FLUSH_EMERGENCY don't want to create a ticket, they just want to
1707  * fail as quickly as possible.
1708  */
1709 static inline bool can_ticket(enum btrfs_reserve_flush_enum flush)
1710 {
1711 	return (flush != BTRFS_RESERVE_NO_FLUSH &&
1712 		flush != BTRFS_RESERVE_FLUSH_EMERGENCY);
1713 }
1714 
1715 /*
1716  * Try to reserve bytes from the block_rsv's space.
1717  *
1718  * @fs_info:    the filesystem
1719  * @space_info: space info we want to allocate from
1720  * @orig_bytes: number of bytes we want
1721  * @flush:      whether or not we can flush to make our reservation
1722  *
1723  * This will reserve orig_bytes number of bytes from the space info associated
1724  * with the block_rsv.  If there is not enough space it will make an attempt to
1725  * flush out space to make room.  It will do this by flushing delalloc if
1726  * possible or committing the transaction.  If flush is 0 then no attempts to
1727  * regain reservations will be made and this will fail if there is not enough
1728  * space already.
1729  */
1730 static int __reserve_bytes(struct btrfs_fs_info *fs_info,
1731 			   struct btrfs_space_info *space_info, u64 orig_bytes,
1732 			   enum btrfs_reserve_flush_enum flush)
1733 {
1734 	struct work_struct *async_work;
1735 	struct reserve_ticket ticket;
1736 	u64 start_ns = 0;
1737 	u64 used;
1738 	int ret = -ENOSPC;
1739 	bool pending_tickets;
1740 
1741 	ASSERT(orig_bytes);
1742 	/*
1743 	 * If have a transaction handle (current->journal_info != NULL), then
1744 	 * the flush method can not be neither BTRFS_RESERVE_FLUSH_ALL* nor
1745 	 * BTRFS_RESERVE_FLUSH_EVICT, as we could deadlock because those
1746 	 * flushing methods can trigger transaction commits.
1747 	 */
1748 	if (current->journal_info) {
1749 		/* One assert per line for easier debugging. */
1750 		ASSERT(flush != BTRFS_RESERVE_FLUSH_ALL);
1751 		ASSERT(flush != BTRFS_RESERVE_FLUSH_ALL_STEAL);
1752 		ASSERT(flush != BTRFS_RESERVE_FLUSH_EVICT);
1753 	}
1754 
1755 	if (flush == BTRFS_RESERVE_FLUSH_DATA)
1756 		async_work = &fs_info->async_data_reclaim_work;
1757 	else
1758 		async_work = &fs_info->async_reclaim_work;
1759 
1760 	spin_lock(&space_info->lock);
1761 	used = btrfs_space_info_used(space_info, true);
1762 
1763 	/*
1764 	 * We don't want NO_FLUSH allocations to jump everybody, they can
1765 	 * generally handle ENOSPC in a different way, so treat them the same as
1766 	 * normal flushers when it comes to skipping pending tickets.
1767 	 */
1768 	if (is_normal_flushing(flush) || (flush == BTRFS_RESERVE_NO_FLUSH))
1769 		pending_tickets = !list_empty(&space_info->tickets) ||
1770 			!list_empty(&space_info->priority_tickets);
1771 	else
1772 		pending_tickets = !list_empty(&space_info->priority_tickets);
1773 
1774 	/*
1775 	 * Carry on if we have enough space (short-circuit) OR call
1776 	 * can_overcommit() to ensure we can overcommit to continue.
1777 	 */
1778 	if (!pending_tickets &&
1779 	    ((used + orig_bytes <= space_info->total_bytes) ||
1780 	     btrfs_can_overcommit(fs_info, space_info, orig_bytes, flush))) {
1781 		btrfs_space_info_update_bytes_may_use(space_info, orig_bytes);
1782 		ret = 0;
1783 	}
1784 
1785 	/*
1786 	 * Things are dire, we need to make a reservation so we don't abort.  We
1787 	 * will let this reservation go through as long as we have actual space
1788 	 * left to allocate for the block.
1789 	 */
1790 	if (ret && unlikely(flush == BTRFS_RESERVE_FLUSH_EMERGENCY)) {
1791 		used = btrfs_space_info_used(space_info, false);
1792 		if (used + orig_bytes <= space_info->total_bytes) {
1793 			btrfs_space_info_update_bytes_may_use(space_info, orig_bytes);
1794 			ret = 0;
1795 		}
1796 	}
1797 
1798 	/*
1799 	 * If we couldn't make a reservation then setup our reservation ticket
1800 	 * and kick the async worker if it's not already running.
1801 	 *
1802 	 * If we are a priority flusher then we just need to add our ticket to
1803 	 * the list and we will do our own flushing further down.
1804 	 */
1805 	if (ret && can_ticket(flush)) {
1806 		ticket.bytes = orig_bytes;
1807 		ticket.error = 0;
1808 		space_info->reclaim_size += ticket.bytes;
1809 		init_waitqueue_head(&ticket.wait);
1810 		ticket.steal = can_steal(flush);
1811 		if (trace_btrfs_reserve_ticket_enabled())
1812 			start_ns = ktime_get_ns();
1813 
1814 		if (flush == BTRFS_RESERVE_FLUSH_ALL ||
1815 		    flush == BTRFS_RESERVE_FLUSH_ALL_STEAL ||
1816 		    flush == BTRFS_RESERVE_FLUSH_DATA) {
1817 			list_add_tail(&ticket.list, &space_info->tickets);
1818 			if (!space_info->flush) {
1819 				/*
1820 				 * We were forced to add a reserve ticket, so
1821 				 * our preemptive flushing is unable to keep
1822 				 * up.  Clamp down on the threshold for the
1823 				 * preemptive flushing in order to keep up with
1824 				 * the workload.
1825 				 */
1826 				maybe_clamp_preempt(fs_info, space_info);
1827 
1828 				space_info->flush = 1;
1829 				trace_btrfs_trigger_flush(fs_info,
1830 							  space_info->flags,
1831 							  orig_bytes, flush,
1832 							  "enospc");
1833 				queue_work(system_unbound_wq, async_work);
1834 			}
1835 		} else {
1836 			list_add_tail(&ticket.list,
1837 				      &space_info->priority_tickets);
1838 		}
1839 	} else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
1840 		/*
1841 		 * We will do the space reservation dance during log replay,
1842 		 * which means we won't have fs_info->fs_root set, so don't do
1843 		 * the async reclaim as we will panic.
1844 		 */
1845 		if (!test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags) &&
1846 		    !work_busy(&fs_info->preempt_reclaim_work) &&
1847 		    need_preemptive_reclaim(fs_info, space_info)) {
1848 			trace_btrfs_trigger_flush(fs_info, space_info->flags,
1849 						  orig_bytes, flush, "preempt");
1850 			queue_work(system_unbound_wq,
1851 				   &fs_info->preempt_reclaim_work);
1852 		}
1853 	}
1854 	spin_unlock(&space_info->lock);
1855 	if (!ret || !can_ticket(flush))
1856 		return ret;
1857 
1858 	return handle_reserve_ticket(fs_info, space_info, &ticket, start_ns,
1859 				     orig_bytes, flush);
1860 }
1861 
1862 /*
1863  * Try to reserve metadata bytes from the block_rsv's space.
1864  *
1865  * @fs_info:    the filesystem
1866  * @space_info: the space_info we're allocating for
1867  * @orig_bytes: number of bytes we want
1868  * @flush:      whether or not we can flush to make our reservation
1869  *
1870  * This will reserve orig_bytes number of bytes from the space info associated
1871  * with the block_rsv.  If there is not enough space it will make an attempt to
1872  * flush out space to make room.  It will do this by flushing delalloc if
1873  * possible or committing the transaction.  If flush is 0 then no attempts to
1874  * regain reservations will be made and this will fail if there is not enough
1875  * space already.
1876  */
1877 int btrfs_reserve_metadata_bytes(struct btrfs_fs_info *fs_info,
1878 				 struct btrfs_space_info *space_info,
1879 				 u64 orig_bytes,
1880 				 enum btrfs_reserve_flush_enum flush)
1881 {
1882 	int ret;
1883 
1884 	ret = __reserve_bytes(fs_info, space_info, orig_bytes, flush);
1885 	if (ret == -ENOSPC) {
1886 		trace_btrfs_space_reservation(fs_info, "space_info:enospc",
1887 					      space_info->flags, orig_bytes, 1);
1888 
1889 		if (btrfs_test_opt(fs_info, ENOSPC_DEBUG))
1890 			btrfs_dump_space_info(fs_info, space_info, orig_bytes, 0);
1891 	}
1892 	return ret;
1893 }
1894 
1895 /*
1896  * Try to reserve data bytes for an allocation.
1897  *
1898  * @fs_info: the filesystem
1899  * @bytes:   number of bytes we need
1900  * @flush:   how we are allowed to flush
1901  *
1902  * This will reserve bytes from the data space info.  If there is not enough
1903  * space then we will attempt to flush space as specified by flush.
1904  */
1905 int btrfs_reserve_data_bytes(struct btrfs_space_info *space_info, u64 bytes,
1906 			     enum btrfs_reserve_flush_enum flush)
1907 {
1908 	struct btrfs_fs_info *fs_info = space_info->fs_info;
1909 	int ret;
1910 
1911 	ASSERT(flush == BTRFS_RESERVE_FLUSH_DATA ||
1912 	       flush == BTRFS_RESERVE_FLUSH_FREE_SPACE_INODE ||
1913 	       flush == BTRFS_RESERVE_NO_FLUSH);
1914 	ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_DATA);
1915 
1916 	ret = __reserve_bytes(fs_info, space_info, bytes, flush);
1917 	if (ret == -ENOSPC) {
1918 		trace_btrfs_space_reservation(fs_info, "space_info:enospc",
1919 					      space_info->flags, bytes, 1);
1920 		if (btrfs_test_opt(fs_info, ENOSPC_DEBUG))
1921 			btrfs_dump_space_info(fs_info, space_info, bytes, 0);
1922 	}
1923 	return ret;
1924 }
1925 
1926 /* Dump all the space infos when we abort a transaction due to ENOSPC. */
1927 __cold void btrfs_dump_space_info_for_trans_abort(struct btrfs_fs_info *fs_info)
1928 {
1929 	struct btrfs_space_info *space_info;
1930 
1931 	btrfs_info(fs_info, "dumping space info:");
1932 	list_for_each_entry(space_info, &fs_info->space_info, list) {
1933 		spin_lock(&space_info->lock);
1934 		__btrfs_dump_space_info(fs_info, space_info);
1935 		spin_unlock(&space_info->lock);
1936 	}
1937 	dump_global_block_rsv(fs_info);
1938 }
1939 
1940 /*
1941  * Account the unused space of all the readonly block group in the space_info.
1942  * takes mirrors into account.
1943  */
1944 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
1945 {
1946 	struct btrfs_block_group *block_group;
1947 	u64 free_bytes = 0;
1948 	int factor;
1949 
1950 	/* It's df, we don't care if it's racy */
1951 	if (list_empty(&sinfo->ro_bgs))
1952 		return 0;
1953 
1954 	spin_lock(&sinfo->lock);
1955 	list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
1956 		spin_lock(&block_group->lock);
1957 
1958 		if (!block_group->ro) {
1959 			spin_unlock(&block_group->lock);
1960 			continue;
1961 		}
1962 
1963 		factor = btrfs_bg_type_to_factor(block_group->flags);
1964 		free_bytes += (block_group->length -
1965 			       block_group->used) * factor;
1966 
1967 		spin_unlock(&block_group->lock);
1968 	}
1969 	spin_unlock(&sinfo->lock);
1970 
1971 	return free_bytes;
1972 }
1973 
1974 static u64 calc_pct_ratio(u64 x, u64 y)
1975 {
1976 	int err;
1977 
1978 	if (!y)
1979 		return 0;
1980 again:
1981 	err = check_mul_overflow(100, x, &x);
1982 	if (err)
1983 		goto lose_precision;
1984 	return div64_u64(x, y);
1985 lose_precision:
1986 	x >>= 10;
1987 	y >>= 10;
1988 	if (!y)
1989 		y = 1;
1990 	goto again;
1991 }
1992 
1993 /*
1994  * A reasonable buffer for unallocated space is 10 data block_groups.
1995  * If we claw this back repeatedly, we can still achieve efficient
1996  * utilization when near full, and not do too much reclaim while
1997  * always maintaining a solid buffer for workloads that quickly
1998  * allocate and pressure the unallocated space.
1999  */
2000 static u64 calc_unalloc_target(struct btrfs_fs_info *fs_info)
2001 {
2002 	u64 chunk_sz = calc_effective_data_chunk_size(fs_info);
2003 
2004 	return BTRFS_UNALLOC_BLOCK_GROUP_TARGET * chunk_sz;
2005 }
2006 
2007 /*
2008  * The fundamental goal of automatic reclaim is to protect the filesystem's
2009  * unallocated space and thus minimize the probability of the filesystem going
2010  * read only when a metadata allocation failure causes a transaction abort.
2011  *
2012  * However, relocations happen into the space_info's unused space, therefore
2013  * automatic reclaim must also back off as that space runs low. There is no
2014  * value in doing trivial "relocations" of re-writing the same block group
2015  * into a fresh one.
2016  *
2017  * Furthermore, we want to avoid doing too much reclaim even if there are good
2018  * candidates. This is because the allocator is pretty good at filling up the
2019  * holes with writes. So we want to do just enough reclaim to try and stay
2020  * safe from running out of unallocated space but not be wasteful about it.
2021  *
2022  * Therefore, the dynamic reclaim threshold is calculated as follows:
2023  * - calculate a target unallocated amount of 5 block group sized chunks
2024  * - ratchet up the intensity of reclaim depending on how far we are from
2025  *   that target by using a formula of unalloc / target to set the threshold.
2026  *
2027  * Typically with 10 block groups as the target, the discrete values this comes
2028  * out to are 0, 10, 20, ... , 80, 90, and 99.
2029  */
2030 static int calc_dynamic_reclaim_threshold(const struct btrfs_space_info *space_info)
2031 {
2032 	struct btrfs_fs_info *fs_info = space_info->fs_info;
2033 	u64 unalloc = atomic64_read(&fs_info->free_chunk_space);
2034 	u64 target = calc_unalloc_target(fs_info);
2035 	u64 alloc = space_info->total_bytes;
2036 	u64 used = btrfs_space_info_used(space_info, false);
2037 	u64 unused = alloc - used;
2038 	u64 want = target > unalloc ? target - unalloc : 0;
2039 	u64 data_chunk_size = calc_effective_data_chunk_size(fs_info);
2040 
2041 	/* If we have no unused space, don't bother, it won't work anyway. */
2042 	if (unused < data_chunk_size)
2043 		return 0;
2044 
2045 	/* Cast to int is OK because want <= target. */
2046 	return calc_pct_ratio(want, target);
2047 }
2048 
2049 int btrfs_calc_reclaim_threshold(const struct btrfs_space_info *space_info)
2050 {
2051 	lockdep_assert_held(&space_info->lock);
2052 
2053 	if (READ_ONCE(space_info->dynamic_reclaim))
2054 		return calc_dynamic_reclaim_threshold(space_info);
2055 	return READ_ONCE(space_info->bg_reclaim_threshold);
2056 }
2057 
2058 /*
2059  * Under "urgent" reclaim, we will reclaim even fresh block groups that have
2060  * recently seen successful allocations, as we are desperate to reclaim
2061  * whatever we can to avoid ENOSPC in a transaction leading to a readonly fs.
2062  */
2063 static bool is_reclaim_urgent(struct btrfs_space_info *space_info)
2064 {
2065 	struct btrfs_fs_info *fs_info = space_info->fs_info;
2066 	u64 unalloc = atomic64_read(&fs_info->free_chunk_space);
2067 	u64 data_chunk_size = calc_effective_data_chunk_size(fs_info);
2068 
2069 	return unalloc < data_chunk_size;
2070 }
2071 
2072 static void do_reclaim_sweep(struct btrfs_space_info *space_info, int raid)
2073 {
2074 	struct btrfs_block_group *bg;
2075 	int thresh_pct;
2076 	bool try_again = true;
2077 	bool urgent;
2078 
2079 	spin_lock(&space_info->lock);
2080 	urgent = is_reclaim_urgent(space_info);
2081 	thresh_pct = btrfs_calc_reclaim_threshold(space_info);
2082 	spin_unlock(&space_info->lock);
2083 
2084 	down_read(&space_info->groups_sem);
2085 again:
2086 	list_for_each_entry(bg, &space_info->block_groups[raid], list) {
2087 		u64 thresh;
2088 		bool reclaim = false;
2089 
2090 		btrfs_get_block_group(bg);
2091 		spin_lock(&bg->lock);
2092 		thresh = mult_perc(bg->length, thresh_pct);
2093 		if (bg->used < thresh && bg->reclaim_mark) {
2094 			try_again = false;
2095 			reclaim = true;
2096 		}
2097 		bg->reclaim_mark++;
2098 		spin_unlock(&bg->lock);
2099 		if (reclaim)
2100 			btrfs_mark_bg_to_reclaim(bg);
2101 		btrfs_put_block_group(bg);
2102 	}
2103 
2104 	/*
2105 	 * In situations where we are very motivated to reclaim (low unalloc)
2106 	 * use two passes to make the reclaim mark check best effort.
2107 	 *
2108 	 * If we have any staler groups, we don't touch the fresher ones, but if we
2109 	 * really need a block group, do take a fresh one.
2110 	 */
2111 	if (try_again && urgent) {
2112 		try_again = false;
2113 		goto again;
2114 	}
2115 
2116 	up_read(&space_info->groups_sem);
2117 }
2118 
2119 void btrfs_space_info_update_reclaimable(struct btrfs_space_info *space_info, s64 bytes)
2120 {
2121 	u64 chunk_sz = calc_effective_data_chunk_size(space_info->fs_info);
2122 
2123 	lockdep_assert_held(&space_info->lock);
2124 	space_info->reclaimable_bytes += bytes;
2125 
2126 	if (space_info->reclaimable_bytes >= chunk_sz)
2127 		btrfs_set_periodic_reclaim_ready(space_info, true);
2128 }
2129 
2130 void btrfs_set_periodic_reclaim_ready(struct btrfs_space_info *space_info, bool ready)
2131 {
2132 	lockdep_assert_held(&space_info->lock);
2133 	if (!READ_ONCE(space_info->periodic_reclaim))
2134 		return;
2135 	if (ready != space_info->periodic_reclaim_ready) {
2136 		space_info->periodic_reclaim_ready = ready;
2137 		if (!ready)
2138 			space_info->reclaimable_bytes = 0;
2139 	}
2140 }
2141 
2142 bool btrfs_should_periodic_reclaim(struct btrfs_space_info *space_info)
2143 {
2144 	bool ret;
2145 
2146 	if (space_info->flags & BTRFS_BLOCK_GROUP_SYSTEM)
2147 		return false;
2148 	if (!READ_ONCE(space_info->periodic_reclaim))
2149 		return false;
2150 
2151 	spin_lock(&space_info->lock);
2152 	ret = space_info->periodic_reclaim_ready;
2153 	btrfs_set_periodic_reclaim_ready(space_info, false);
2154 	spin_unlock(&space_info->lock);
2155 
2156 	return ret;
2157 }
2158 
2159 void btrfs_reclaim_sweep(const struct btrfs_fs_info *fs_info)
2160 {
2161 	int raid;
2162 	struct btrfs_space_info *space_info;
2163 
2164 	list_for_each_entry(space_info, &fs_info->space_info, list) {
2165 		if (!btrfs_should_periodic_reclaim(space_info))
2166 			continue;
2167 		for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++)
2168 			do_reclaim_sweep(space_info, raid);
2169 	}
2170 }
2171 
2172 void btrfs_return_free_space(struct btrfs_space_info *space_info, u64 len)
2173 {
2174 	struct btrfs_fs_info *fs_info = space_info->fs_info;
2175 	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
2176 
2177 	lockdep_assert_held(&space_info->lock);
2178 
2179 	/* Prioritize the global reservation to receive the freed space. */
2180 	if (global_rsv->space_info != space_info)
2181 		goto grant;
2182 
2183 	spin_lock(&global_rsv->lock);
2184 	if (!global_rsv->full) {
2185 		u64 to_add = min(len, global_rsv->size - global_rsv->reserved);
2186 
2187 		global_rsv->reserved += to_add;
2188 		btrfs_space_info_update_bytes_may_use(space_info, to_add);
2189 		if (global_rsv->reserved >= global_rsv->size)
2190 			global_rsv->full = 1;
2191 		len -= to_add;
2192 	}
2193 	spin_unlock(&global_rsv->lock);
2194 
2195 grant:
2196 	/* Add to any tickets we may have. */
2197 	if (len)
2198 		btrfs_try_granting_tickets(fs_info, space_info);
2199 }
2200