xref: /openbmc/linux/fs/btrfs/space-info.c (revision 79417d04)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include "misc.h"
4 #include "ctree.h"
5 #include "space-info.h"
6 #include "sysfs.h"
7 #include "volumes.h"
8 #include "free-space-cache.h"
9 #include "ordered-data.h"
10 #include "transaction.h"
11 #include "block-group.h"
12 
13 /*
14  * HOW DOES SPACE RESERVATION WORK
15  *
16  * If you want to know about delalloc specifically, there is a separate comment
17  * for that with the delalloc code.  This comment is about how the whole system
18  * works generally.
19  *
20  * BASIC CONCEPTS
21  *
22  *   1) space_info.  This is the ultimate arbiter of how much space we can use.
23  *   There's a description of the bytes_ fields with the struct declaration,
24  *   refer to that for specifics on each field.  Suffice it to say that for
25  *   reservations we care about total_bytes - SUM(space_info->bytes_) when
26  *   determining if there is space to make an allocation.  There is a space_info
27  *   for METADATA, SYSTEM, and DATA areas.
28  *
29  *   2) block_rsv's.  These are basically buckets for every different type of
30  *   metadata reservation we have.  You can see the comment in the block_rsv
31  *   code on the rules for each type, but generally block_rsv->reserved is how
32  *   much space is accounted for in space_info->bytes_may_use.
33  *
34  *   3) btrfs_calc*_size.  These are the worst case calculations we used based
35  *   on the number of items we will want to modify.  We have one for changing
36  *   items, and one for inserting new items.  Generally we use these helpers to
37  *   determine the size of the block reserves, and then use the actual bytes
38  *   values to adjust the space_info counters.
39  *
40  * MAKING RESERVATIONS, THE NORMAL CASE
41  *
42  *   We call into either btrfs_reserve_data_bytes() or
43  *   btrfs_reserve_metadata_bytes(), depending on which we're looking for, with
44  *   num_bytes we want to reserve.
45  *
46  *   ->reserve
47  *     space_info->bytes_may_reserve += num_bytes
48  *
49  *   ->extent allocation
50  *     Call btrfs_add_reserved_bytes() which does
51  *     space_info->bytes_may_reserve -= num_bytes
52  *     space_info->bytes_reserved += extent_bytes
53  *
54  *   ->insert reference
55  *     Call btrfs_update_block_group() which does
56  *     space_info->bytes_reserved -= extent_bytes
57  *     space_info->bytes_used += extent_bytes
58  *
59  * MAKING RESERVATIONS, FLUSHING NORMALLY (non-priority)
60  *
61  *   Assume we are unable to simply make the reservation because we do not have
62  *   enough space
63  *
64  *   -> __reserve_bytes
65  *     create a reserve_ticket with ->bytes set to our reservation, add it to
66  *     the tail of space_info->tickets, kick async flush thread
67  *
68  *   ->handle_reserve_ticket
69  *     wait on ticket->wait for ->bytes to be reduced to 0, or ->error to be set
70  *     on the ticket.
71  *
72  *   -> btrfs_async_reclaim_metadata_space/btrfs_async_reclaim_data_space
73  *     Flushes various things attempting to free up space.
74  *
75  *   -> btrfs_try_granting_tickets()
76  *     This is called by anything that either subtracts space from
77  *     space_info->bytes_may_use, ->bytes_pinned, etc, or adds to the
78  *     space_info->total_bytes.  This loops through the ->priority_tickets and
79  *     then the ->tickets list checking to see if the reservation can be
80  *     completed.  If it can the space is added to space_info->bytes_may_use and
81  *     the ticket is woken up.
82  *
83  *   -> ticket wakeup
84  *     Check if ->bytes == 0, if it does we got our reservation and we can carry
85  *     on, if not return the appropriate error (ENOSPC, but can be EINTR if we
86  *     were interrupted.)
87  *
88  * MAKING RESERVATIONS, FLUSHING HIGH PRIORITY
89  *
90  *   Same as the above, except we add ourselves to the
91  *   space_info->priority_tickets, and we do not use ticket->wait, we simply
92  *   call flush_space() ourselves for the states that are safe for us to call
93  *   without deadlocking and hope for the best.
94  *
95  * THE FLUSHING STATES
96  *
97  *   Generally speaking we will have two cases for each state, a "nice" state
98  *   and a "ALL THE THINGS" state.  In btrfs we delay a lot of work in order to
99  *   reduce the locking over head on the various trees, and even to keep from
100  *   doing any work at all in the case of delayed refs.  Each of these delayed
101  *   things however hold reservations, and so letting them run allows us to
102  *   reclaim space so we can make new reservations.
103  *
104  *   FLUSH_DELAYED_ITEMS
105  *     Every inode has a delayed item to update the inode.  Take a simple write
106  *     for example, we would update the inode item at write time to update the
107  *     mtime, and then again at finish_ordered_io() time in order to update the
108  *     isize or bytes.  We keep these delayed items to coalesce these operations
109  *     into a single operation done on demand.  These are an easy way to reclaim
110  *     metadata space.
111  *
112  *   FLUSH_DELALLOC
113  *     Look at the delalloc comment to get an idea of how much space is reserved
114  *     for delayed allocation.  We can reclaim some of this space simply by
115  *     running delalloc, but usually we need to wait for ordered extents to
116  *     reclaim the bulk of this space.
117  *
118  *   FLUSH_DELAYED_REFS
119  *     We have a block reserve for the outstanding delayed refs space, and every
120  *     delayed ref operation holds a reservation.  Running these is a quick way
121  *     to reclaim space, but we want to hold this until the end because COW can
122  *     churn a lot and we can avoid making some extent tree modifications if we
123  *     are able to delay for as long as possible.
124  *
125  *   ALLOC_CHUNK
126  *     We will skip this the first time through space reservation, because of
127  *     overcommit and we don't want to have a lot of useless metadata space when
128  *     our worst case reservations will likely never come true.
129  *
130  *   RUN_DELAYED_IPUTS
131  *     If we're freeing inodes we're likely freeing checksums, file extent
132  *     items, and extent tree items.  Loads of space could be freed up by these
133  *     operations, however they won't be usable until the transaction commits.
134  *
135  *   COMMIT_TRANS
136  *     This will commit the transaction.  Historically we had a lot of logic
137  *     surrounding whether or not we'd commit the transaction, but this waits born
138  *     out of a pre-tickets era where we could end up committing the transaction
139  *     thousands of times in a row without making progress.  Now thanks to our
140  *     ticketing system we know if we're not making progress and can error
141  *     everybody out after a few commits rather than burning the disk hoping for
142  *     a different answer.
143  *
144  * OVERCOMMIT
145  *
146  *   Because we hold so many reservations for metadata we will allow you to
147  *   reserve more space than is currently free in the currently allocate
148  *   metadata space.  This only happens with metadata, data does not allow
149  *   overcommitting.
150  *
151  *   You can see the current logic for when we allow overcommit in
152  *   btrfs_can_overcommit(), but it only applies to unallocated space.  If there
153  *   is no unallocated space to be had, all reservations are kept within the
154  *   free space in the allocated metadata chunks.
155  *
156  *   Because of overcommitting, you generally want to use the
157  *   btrfs_can_overcommit() logic for metadata allocations, as it does the right
158  *   thing with or without extra unallocated space.
159  */
160 
161 u64 __pure btrfs_space_info_used(struct btrfs_space_info *s_info,
162 			  bool may_use_included)
163 {
164 	ASSERT(s_info);
165 	return s_info->bytes_used + s_info->bytes_reserved +
166 		s_info->bytes_pinned + s_info->bytes_readonly +
167 		s_info->bytes_zone_unusable +
168 		(may_use_included ? s_info->bytes_may_use : 0);
169 }
170 
171 /*
172  * after adding space to the filesystem, we need to clear the full flags
173  * on all the space infos.
174  */
175 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
176 {
177 	struct list_head *head = &info->space_info;
178 	struct btrfs_space_info *found;
179 
180 	list_for_each_entry(found, head, list)
181 		found->full = 0;
182 }
183 
184 /*
185  * Block groups with more than this value (percents) of unusable space will be
186  * scheduled for background reclaim.
187  */
188 #define BTRFS_DEFAULT_ZONED_RECLAIM_THRESH			(75)
189 
190 /*
191  * Calculate chunk size depending on volume type (regular or zoned).
192  */
193 static u64 calc_chunk_size(const struct btrfs_fs_info *fs_info, u64 flags)
194 {
195 	if (btrfs_is_zoned(fs_info))
196 		return fs_info->zone_size;
197 
198 	ASSERT(flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
199 
200 	if (flags & BTRFS_BLOCK_GROUP_DATA)
201 		return SZ_1G;
202 	else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
203 		return SZ_32M;
204 
205 	/* Handle BTRFS_BLOCK_GROUP_METADATA */
206 	if (fs_info->fs_devices->total_rw_bytes > 50ULL * SZ_1G)
207 		return SZ_1G;
208 
209 	return SZ_256M;
210 }
211 
212 /*
213  * Update default chunk size.
214  */
215 void btrfs_update_space_info_chunk_size(struct btrfs_space_info *space_info,
216 					u64 chunk_size)
217 {
218 	WRITE_ONCE(space_info->chunk_size, chunk_size);
219 }
220 
221 static int create_space_info(struct btrfs_fs_info *info, u64 flags)
222 {
223 
224 	struct btrfs_space_info *space_info;
225 	int i;
226 	int ret;
227 
228 	space_info = kzalloc(sizeof(*space_info), GFP_NOFS);
229 	if (!space_info)
230 		return -ENOMEM;
231 
232 	for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
233 		INIT_LIST_HEAD(&space_info->block_groups[i]);
234 	init_rwsem(&space_info->groups_sem);
235 	spin_lock_init(&space_info->lock);
236 	space_info->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
237 	space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
238 	INIT_LIST_HEAD(&space_info->ro_bgs);
239 	INIT_LIST_HEAD(&space_info->tickets);
240 	INIT_LIST_HEAD(&space_info->priority_tickets);
241 	space_info->clamp = 1;
242 	btrfs_update_space_info_chunk_size(space_info, calc_chunk_size(info, flags));
243 
244 	if (btrfs_is_zoned(info))
245 		space_info->bg_reclaim_threshold = BTRFS_DEFAULT_ZONED_RECLAIM_THRESH;
246 
247 	ret = btrfs_sysfs_add_space_info_type(info, space_info);
248 	if (ret)
249 		return ret;
250 
251 	list_add(&space_info->list, &info->space_info);
252 	if (flags & BTRFS_BLOCK_GROUP_DATA)
253 		info->data_sinfo = space_info;
254 
255 	return ret;
256 }
257 
258 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
259 {
260 	struct btrfs_super_block *disk_super;
261 	u64 features;
262 	u64 flags;
263 	int mixed = 0;
264 	int ret;
265 
266 	disk_super = fs_info->super_copy;
267 	if (!btrfs_super_root(disk_super))
268 		return -EINVAL;
269 
270 	features = btrfs_super_incompat_flags(disk_super);
271 	if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
272 		mixed = 1;
273 
274 	flags = BTRFS_BLOCK_GROUP_SYSTEM;
275 	ret = create_space_info(fs_info, flags);
276 	if (ret)
277 		goto out;
278 
279 	if (mixed) {
280 		flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
281 		ret = create_space_info(fs_info, flags);
282 	} else {
283 		flags = BTRFS_BLOCK_GROUP_METADATA;
284 		ret = create_space_info(fs_info, flags);
285 		if (ret)
286 			goto out;
287 
288 		flags = BTRFS_BLOCK_GROUP_DATA;
289 		ret = create_space_info(fs_info, flags);
290 	}
291 out:
292 	return ret;
293 }
294 
295 void btrfs_update_space_info(struct btrfs_fs_info *info, u64 flags,
296 			     u64 total_bytes, u64 bytes_used,
297 			     u64 bytes_readonly, u64 bytes_zone_unusable,
298 			     bool active, struct btrfs_space_info **space_info)
299 {
300 	struct btrfs_space_info *found;
301 	int factor;
302 
303 	factor = btrfs_bg_type_to_factor(flags);
304 
305 	found = btrfs_find_space_info(info, flags);
306 	ASSERT(found);
307 	spin_lock(&found->lock);
308 	found->total_bytes += total_bytes;
309 	if (active)
310 		found->active_total_bytes += total_bytes;
311 	found->disk_total += total_bytes * factor;
312 	found->bytes_used += bytes_used;
313 	found->disk_used += bytes_used * factor;
314 	found->bytes_readonly += bytes_readonly;
315 	found->bytes_zone_unusable += bytes_zone_unusable;
316 	if (total_bytes > 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 		trans = btrfs_join_transaction(root);
728 		if (IS_ERR(trans)) {
729 			ret = PTR_ERR(trans);
730 			break;
731 		}
732 		ret = btrfs_chunk_alloc(trans,
733 				btrfs_get_alloc_profile(fs_info, space_info->flags),
734 				(state == ALLOC_CHUNK) ? CHUNK_ALLOC_NO_FORCE :
735 					CHUNK_ALLOC_FORCE);
736 		btrfs_end_transaction(trans);
737 		if (ret > 0 || ret == -ENOSPC)
738 			ret = 0;
739 		break;
740 	case RUN_DELAYED_IPUTS:
741 		/*
742 		 * If we have pending delayed iputs then we could free up a
743 		 * bunch of pinned space, so make sure we run the iputs before
744 		 * we do our pinned bytes check below.
745 		 */
746 		btrfs_run_delayed_iputs(fs_info);
747 		btrfs_wait_on_delayed_iputs(fs_info);
748 		break;
749 	case COMMIT_TRANS:
750 		ASSERT(current->journal_info == NULL);
751 		trans = btrfs_join_transaction(root);
752 		if (IS_ERR(trans)) {
753 			ret = PTR_ERR(trans);
754 			break;
755 		}
756 		ret = btrfs_commit_transaction(trans);
757 		break;
758 	default:
759 		ret = -ENOSPC;
760 		break;
761 	}
762 
763 	trace_btrfs_flush_space(fs_info, space_info->flags, num_bytes, state,
764 				ret, for_preempt);
765 	return;
766 }
767 
768 static inline u64
769 btrfs_calc_reclaim_metadata_size(struct btrfs_fs_info *fs_info,
770 				 struct btrfs_space_info *space_info)
771 {
772 	u64 used;
773 	u64 avail;
774 	u64 total;
775 	u64 to_reclaim = space_info->reclaim_size;
776 
777 	lockdep_assert_held(&space_info->lock);
778 
779 	avail = calc_available_free_space(fs_info, space_info,
780 					  BTRFS_RESERVE_FLUSH_ALL);
781 	used = btrfs_space_info_used(space_info, true);
782 
783 	/*
784 	 * We may be flushing because suddenly we have less space than we had
785 	 * before, and now we're well over-committed based on our current free
786 	 * space.  If that's the case add in our overage so we make sure to put
787 	 * appropriate pressure on the flushing state machine.
788 	 */
789 	total = writable_total_bytes(fs_info, space_info);
790 	if (total + avail < used)
791 		to_reclaim += used - (total + avail);
792 
793 	return to_reclaim;
794 }
795 
796 static bool need_preemptive_reclaim(struct btrfs_fs_info *fs_info,
797 				    struct btrfs_space_info *space_info)
798 {
799 	u64 global_rsv_size = fs_info->global_block_rsv.reserved;
800 	u64 ordered, delalloc;
801 	u64 total = writable_total_bytes(fs_info, space_info);
802 	u64 thresh;
803 	u64 used;
804 
805 	thresh = div_factor_fine(total, 90);
806 
807 	lockdep_assert_held(&space_info->lock);
808 
809 	/* If we're just plain full then async reclaim just slows us down. */
810 	if ((space_info->bytes_used + space_info->bytes_reserved +
811 	     global_rsv_size) >= thresh)
812 		return false;
813 
814 	used = space_info->bytes_may_use + space_info->bytes_pinned;
815 
816 	/* The total flushable belongs to the global rsv, don't flush. */
817 	if (global_rsv_size >= used)
818 		return false;
819 
820 	/*
821 	 * 128MiB is 1/4 of the maximum global rsv size.  If we have less than
822 	 * that devoted to other reservations then there's no sense in flushing,
823 	 * we don't have a lot of things that need flushing.
824 	 */
825 	if (used - global_rsv_size <= SZ_128M)
826 		return false;
827 
828 	/*
829 	 * We have tickets queued, bail so we don't compete with the async
830 	 * flushers.
831 	 */
832 	if (space_info->reclaim_size)
833 		return false;
834 
835 	/*
836 	 * If we have over half of the free space occupied by reservations or
837 	 * pinned then we want to start flushing.
838 	 *
839 	 * We do not do the traditional thing here, which is to say
840 	 *
841 	 *   if (used >= ((total_bytes + avail) / 2))
842 	 *     return 1;
843 	 *
844 	 * because this doesn't quite work how we want.  If we had more than 50%
845 	 * of the space_info used by bytes_used and we had 0 available we'd just
846 	 * constantly run the background flusher.  Instead we want it to kick in
847 	 * if our reclaimable space exceeds our clamped free space.
848 	 *
849 	 * Our clamping range is 2^1 -> 2^8.  Practically speaking that means
850 	 * the following:
851 	 *
852 	 * Amount of RAM        Minimum threshold       Maximum threshold
853 	 *
854 	 *        256GiB                     1GiB                  128GiB
855 	 *        128GiB                   512MiB                   64GiB
856 	 *         64GiB                   256MiB                   32GiB
857 	 *         32GiB                   128MiB                   16GiB
858 	 *         16GiB                    64MiB                    8GiB
859 	 *
860 	 * These are the range our thresholds will fall in, corresponding to how
861 	 * much delalloc we need for the background flusher to kick in.
862 	 */
863 
864 	thresh = calc_available_free_space(fs_info, space_info,
865 					   BTRFS_RESERVE_FLUSH_ALL);
866 	used = space_info->bytes_used + space_info->bytes_reserved +
867 	       space_info->bytes_readonly + global_rsv_size;
868 	if (used < total)
869 		thresh += total - used;
870 	thresh >>= space_info->clamp;
871 
872 	used = space_info->bytes_pinned;
873 
874 	/*
875 	 * If we have more ordered bytes than delalloc bytes then we're either
876 	 * doing a lot of DIO, or we simply don't have a lot of delalloc waiting
877 	 * around.  Preemptive flushing is only useful in that it can free up
878 	 * space before tickets need to wait for things to finish.  In the case
879 	 * of ordered extents, preemptively waiting on ordered extents gets us
880 	 * nothing, if our reservations are tied up in ordered extents we'll
881 	 * simply have to slow down writers by forcing them to wait on ordered
882 	 * extents.
883 	 *
884 	 * In the case that ordered is larger than delalloc, only include the
885 	 * block reserves that we would actually be able to directly reclaim
886 	 * from.  In this case if we're heavy on metadata operations this will
887 	 * clearly be heavy enough to warrant preemptive flushing.  In the case
888 	 * of heavy DIO or ordered reservations, preemptive flushing will just
889 	 * waste time and cause us to slow down.
890 	 *
891 	 * We want to make sure we truly are maxed out on ordered however, so
892 	 * cut ordered in half, and if it's still higher than delalloc then we
893 	 * can keep flushing.  This is to avoid the case where we start
894 	 * flushing, and now delalloc == ordered and we stop preemptively
895 	 * flushing when we could still have several gigs of delalloc to flush.
896 	 */
897 	ordered = percpu_counter_read_positive(&fs_info->ordered_bytes) >> 1;
898 	delalloc = percpu_counter_read_positive(&fs_info->delalloc_bytes);
899 	if (ordered >= delalloc)
900 		used += fs_info->delayed_refs_rsv.reserved +
901 			fs_info->delayed_block_rsv.reserved;
902 	else
903 		used += space_info->bytes_may_use - global_rsv_size;
904 
905 	return (used >= thresh && !btrfs_fs_closing(fs_info) &&
906 		!test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
907 }
908 
909 static bool steal_from_global_rsv(struct btrfs_fs_info *fs_info,
910 				  struct btrfs_space_info *space_info,
911 				  struct reserve_ticket *ticket)
912 {
913 	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
914 	u64 min_bytes;
915 
916 	if (!ticket->steal)
917 		return false;
918 
919 	if (global_rsv->space_info != space_info)
920 		return false;
921 
922 	spin_lock(&global_rsv->lock);
923 	min_bytes = div_factor(global_rsv->size, 1);
924 	if (global_rsv->reserved < min_bytes + ticket->bytes) {
925 		spin_unlock(&global_rsv->lock);
926 		return false;
927 	}
928 	global_rsv->reserved -= ticket->bytes;
929 	remove_ticket(space_info, ticket);
930 	ticket->bytes = 0;
931 	wake_up(&ticket->wait);
932 	space_info->tickets_id++;
933 	if (global_rsv->reserved < global_rsv->size)
934 		global_rsv->full = 0;
935 	spin_unlock(&global_rsv->lock);
936 
937 	return true;
938 }
939 
940 /*
941  * maybe_fail_all_tickets - we've exhausted our flushing, start failing tickets
942  * @fs_info - fs_info for this fs
943  * @space_info - the space info we were flushing
944  *
945  * We call this when we've exhausted our flushing ability and haven't made
946  * progress in satisfying tickets.  The reservation code handles tickets in
947  * order, so if there is a large ticket first and then smaller ones we could
948  * very well satisfy the smaller tickets.  This will attempt to wake up any
949  * tickets in the list to catch this case.
950  *
951  * This function returns true if it was able to make progress by clearing out
952  * other tickets, or if it stumbles across a ticket that was smaller than the
953  * first ticket.
954  */
955 static bool maybe_fail_all_tickets(struct btrfs_fs_info *fs_info,
956 				   struct btrfs_space_info *space_info)
957 {
958 	struct reserve_ticket *ticket;
959 	u64 tickets_id = space_info->tickets_id;
960 	const bool aborted = BTRFS_FS_ERROR(fs_info);
961 
962 	trace_btrfs_fail_all_tickets(fs_info, space_info);
963 
964 	if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
965 		btrfs_info(fs_info, "cannot satisfy tickets, dumping space info");
966 		__btrfs_dump_space_info(fs_info, space_info);
967 	}
968 
969 	while (!list_empty(&space_info->tickets) &&
970 	       tickets_id == space_info->tickets_id) {
971 		ticket = list_first_entry(&space_info->tickets,
972 					  struct reserve_ticket, list);
973 
974 		if (!aborted && steal_from_global_rsv(fs_info, space_info, ticket))
975 			return true;
976 
977 		if (!aborted && btrfs_test_opt(fs_info, ENOSPC_DEBUG))
978 			btrfs_info(fs_info, "failing ticket with %llu bytes",
979 				   ticket->bytes);
980 
981 		remove_ticket(space_info, ticket);
982 		if (aborted)
983 			ticket->error = -EIO;
984 		else
985 			ticket->error = -ENOSPC;
986 		wake_up(&ticket->wait);
987 
988 		/*
989 		 * We're just throwing tickets away, so more flushing may not
990 		 * trip over btrfs_try_granting_tickets, so we need to call it
991 		 * here to see if we can make progress with the next ticket in
992 		 * the list.
993 		 */
994 		if (!aborted)
995 			btrfs_try_granting_tickets(fs_info, space_info);
996 	}
997 	return (tickets_id != space_info->tickets_id);
998 }
999 
1000 /*
1001  * This is for normal flushers, we can wait all goddamned day if we want to.  We
1002  * will loop and continuously try to flush as long as we are making progress.
1003  * We count progress as clearing off tickets each time we have to loop.
1004  */
1005 static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
1006 {
1007 	struct btrfs_fs_info *fs_info;
1008 	struct btrfs_space_info *space_info;
1009 	u64 to_reclaim;
1010 	enum btrfs_flush_state flush_state;
1011 	int commit_cycles = 0;
1012 	u64 last_tickets_id;
1013 
1014 	fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
1015 	space_info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
1016 
1017 	spin_lock(&space_info->lock);
1018 	to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info);
1019 	if (!to_reclaim) {
1020 		space_info->flush = 0;
1021 		spin_unlock(&space_info->lock);
1022 		return;
1023 	}
1024 	last_tickets_id = space_info->tickets_id;
1025 	spin_unlock(&space_info->lock);
1026 
1027 	flush_state = FLUSH_DELAYED_ITEMS_NR;
1028 	do {
1029 		flush_space(fs_info, space_info, to_reclaim, flush_state, false);
1030 		spin_lock(&space_info->lock);
1031 		if (list_empty(&space_info->tickets)) {
1032 			space_info->flush = 0;
1033 			spin_unlock(&space_info->lock);
1034 			return;
1035 		}
1036 		to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info,
1037 							      space_info);
1038 		if (last_tickets_id == space_info->tickets_id) {
1039 			flush_state++;
1040 		} else {
1041 			last_tickets_id = space_info->tickets_id;
1042 			flush_state = FLUSH_DELAYED_ITEMS_NR;
1043 			if (commit_cycles)
1044 				commit_cycles--;
1045 		}
1046 
1047 		/*
1048 		 * We do not want to empty the system of delalloc unless we're
1049 		 * under heavy pressure, so allow one trip through the flushing
1050 		 * logic before we start doing a FLUSH_DELALLOC_FULL.
1051 		 */
1052 		if (flush_state == FLUSH_DELALLOC_FULL && !commit_cycles)
1053 			flush_state++;
1054 
1055 		/*
1056 		 * We don't want to force a chunk allocation until we've tried
1057 		 * pretty hard to reclaim space.  Think of the case where we
1058 		 * freed up a bunch of space and so have a lot of pinned space
1059 		 * to reclaim.  We would rather use that than possibly create a
1060 		 * underutilized metadata chunk.  So if this is our first run
1061 		 * through the flushing state machine skip ALLOC_CHUNK_FORCE and
1062 		 * commit the transaction.  If nothing has changed the next go
1063 		 * around then we can force a chunk allocation.
1064 		 */
1065 		if (flush_state == ALLOC_CHUNK_FORCE && !commit_cycles)
1066 			flush_state++;
1067 
1068 		if (flush_state > COMMIT_TRANS) {
1069 			commit_cycles++;
1070 			if (commit_cycles > 2) {
1071 				if (maybe_fail_all_tickets(fs_info, space_info)) {
1072 					flush_state = FLUSH_DELAYED_ITEMS_NR;
1073 					commit_cycles--;
1074 				} else {
1075 					space_info->flush = 0;
1076 				}
1077 			} else {
1078 				flush_state = FLUSH_DELAYED_ITEMS_NR;
1079 			}
1080 		}
1081 		spin_unlock(&space_info->lock);
1082 	} while (flush_state <= COMMIT_TRANS);
1083 }
1084 
1085 /*
1086  * This handles pre-flushing of metadata space before we get to the point that
1087  * we need to start blocking threads on tickets.  The logic here is different
1088  * from the other flush paths because it doesn't rely on tickets to tell us how
1089  * much we need to flush, instead it attempts to keep us below the 80% full
1090  * watermark of space by flushing whichever reservation pool is currently the
1091  * largest.
1092  */
1093 static void btrfs_preempt_reclaim_metadata_space(struct work_struct *work)
1094 {
1095 	struct btrfs_fs_info *fs_info;
1096 	struct btrfs_space_info *space_info;
1097 	struct btrfs_block_rsv *delayed_block_rsv;
1098 	struct btrfs_block_rsv *delayed_refs_rsv;
1099 	struct btrfs_block_rsv *global_rsv;
1100 	struct btrfs_block_rsv *trans_rsv;
1101 	int loops = 0;
1102 
1103 	fs_info = container_of(work, struct btrfs_fs_info,
1104 			       preempt_reclaim_work);
1105 	space_info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
1106 	delayed_block_rsv = &fs_info->delayed_block_rsv;
1107 	delayed_refs_rsv = &fs_info->delayed_refs_rsv;
1108 	global_rsv = &fs_info->global_block_rsv;
1109 	trans_rsv = &fs_info->trans_block_rsv;
1110 
1111 	spin_lock(&space_info->lock);
1112 	while (need_preemptive_reclaim(fs_info, space_info)) {
1113 		enum btrfs_flush_state flush;
1114 		u64 delalloc_size = 0;
1115 		u64 to_reclaim, block_rsv_size;
1116 		u64 global_rsv_size = global_rsv->reserved;
1117 
1118 		loops++;
1119 
1120 		/*
1121 		 * We don't have a precise counter for the metadata being
1122 		 * reserved for delalloc, so we'll approximate it by subtracting
1123 		 * out the block rsv's space from the bytes_may_use.  If that
1124 		 * amount is higher than the individual reserves, then we can
1125 		 * assume it's tied up in delalloc reservations.
1126 		 */
1127 		block_rsv_size = global_rsv_size +
1128 			delayed_block_rsv->reserved +
1129 			delayed_refs_rsv->reserved +
1130 			trans_rsv->reserved;
1131 		if (block_rsv_size < space_info->bytes_may_use)
1132 			delalloc_size = space_info->bytes_may_use - block_rsv_size;
1133 
1134 		/*
1135 		 * We don't want to include the global_rsv in our calculation,
1136 		 * because that's space we can't touch.  Subtract it from the
1137 		 * block_rsv_size for the next checks.
1138 		 */
1139 		block_rsv_size -= global_rsv_size;
1140 
1141 		/*
1142 		 * We really want to avoid flushing delalloc too much, as it
1143 		 * could result in poor allocation patterns, so only flush it if
1144 		 * it's larger than the rest of the pools combined.
1145 		 */
1146 		if (delalloc_size > block_rsv_size) {
1147 			to_reclaim = delalloc_size;
1148 			flush = FLUSH_DELALLOC;
1149 		} else if (space_info->bytes_pinned >
1150 			   (delayed_block_rsv->reserved +
1151 			    delayed_refs_rsv->reserved)) {
1152 			to_reclaim = space_info->bytes_pinned;
1153 			flush = COMMIT_TRANS;
1154 		} else if (delayed_block_rsv->reserved >
1155 			   delayed_refs_rsv->reserved) {
1156 			to_reclaim = delayed_block_rsv->reserved;
1157 			flush = FLUSH_DELAYED_ITEMS_NR;
1158 		} else {
1159 			to_reclaim = delayed_refs_rsv->reserved;
1160 			flush = FLUSH_DELAYED_REFS_NR;
1161 		}
1162 
1163 		spin_unlock(&space_info->lock);
1164 
1165 		/*
1166 		 * We don't want to reclaim everything, just a portion, so scale
1167 		 * down the to_reclaim by 1/4.  If it takes us down to 0,
1168 		 * reclaim 1 items worth.
1169 		 */
1170 		to_reclaim >>= 2;
1171 		if (!to_reclaim)
1172 			to_reclaim = btrfs_calc_insert_metadata_size(fs_info, 1);
1173 		flush_space(fs_info, space_info, to_reclaim, flush, true);
1174 		cond_resched();
1175 		spin_lock(&space_info->lock);
1176 	}
1177 
1178 	/* We only went through once, back off our clamping. */
1179 	if (loops == 1 && !space_info->reclaim_size)
1180 		space_info->clamp = max(1, space_info->clamp - 1);
1181 	trace_btrfs_done_preemptive_reclaim(fs_info, space_info);
1182 	spin_unlock(&space_info->lock);
1183 }
1184 
1185 /*
1186  * FLUSH_DELALLOC_WAIT:
1187  *   Space is freed from flushing delalloc in one of two ways.
1188  *
1189  *   1) compression is on and we allocate less space than we reserved
1190  *   2) we are overwriting existing space
1191  *
1192  *   For #1 that extra space is reclaimed as soon as the delalloc pages are
1193  *   COWed, by way of btrfs_add_reserved_bytes() which adds the actual extent
1194  *   length to ->bytes_reserved, and subtracts the reserved space from
1195  *   ->bytes_may_use.
1196  *
1197  *   For #2 this is trickier.  Once the ordered extent runs we will drop the
1198  *   extent in the range we are overwriting, which creates a delayed ref for
1199  *   that freed extent.  This however is not reclaimed until the transaction
1200  *   commits, thus the next stages.
1201  *
1202  * RUN_DELAYED_IPUTS
1203  *   If we are freeing inodes, we want to make sure all delayed iputs have
1204  *   completed, because they could have been on an inode with i_nlink == 0, and
1205  *   thus have been truncated and freed up space.  But again this space is not
1206  *   immediately re-usable, it comes in the form of a delayed ref, which must be
1207  *   run and then the transaction must be committed.
1208  *
1209  * COMMIT_TRANS
1210  *   This is where we reclaim all of the pinned space generated by running the
1211  *   iputs
1212  *
1213  * ALLOC_CHUNK_FORCE
1214  *   For data we start with alloc chunk force, however we could have been full
1215  *   before, and then the transaction commit could have freed new block groups,
1216  *   so if we now have space to allocate do the force chunk allocation.
1217  */
1218 static const enum btrfs_flush_state data_flush_states[] = {
1219 	FLUSH_DELALLOC_FULL,
1220 	RUN_DELAYED_IPUTS,
1221 	COMMIT_TRANS,
1222 	ALLOC_CHUNK_FORCE,
1223 };
1224 
1225 static void btrfs_async_reclaim_data_space(struct work_struct *work)
1226 {
1227 	struct btrfs_fs_info *fs_info;
1228 	struct btrfs_space_info *space_info;
1229 	u64 last_tickets_id;
1230 	enum btrfs_flush_state flush_state = 0;
1231 
1232 	fs_info = container_of(work, struct btrfs_fs_info, async_data_reclaim_work);
1233 	space_info = fs_info->data_sinfo;
1234 
1235 	spin_lock(&space_info->lock);
1236 	if (list_empty(&space_info->tickets)) {
1237 		space_info->flush = 0;
1238 		spin_unlock(&space_info->lock);
1239 		return;
1240 	}
1241 	last_tickets_id = space_info->tickets_id;
1242 	spin_unlock(&space_info->lock);
1243 
1244 	while (!space_info->full) {
1245 		flush_space(fs_info, space_info, U64_MAX, ALLOC_CHUNK_FORCE, false);
1246 		spin_lock(&space_info->lock);
1247 		if (list_empty(&space_info->tickets)) {
1248 			space_info->flush = 0;
1249 			spin_unlock(&space_info->lock);
1250 			return;
1251 		}
1252 
1253 		/* Something happened, fail everything and bail. */
1254 		if (BTRFS_FS_ERROR(fs_info))
1255 			goto aborted_fs;
1256 		last_tickets_id = space_info->tickets_id;
1257 		spin_unlock(&space_info->lock);
1258 	}
1259 
1260 	while (flush_state < ARRAY_SIZE(data_flush_states)) {
1261 		flush_space(fs_info, space_info, U64_MAX,
1262 			    data_flush_states[flush_state], false);
1263 		spin_lock(&space_info->lock);
1264 		if (list_empty(&space_info->tickets)) {
1265 			space_info->flush = 0;
1266 			spin_unlock(&space_info->lock);
1267 			return;
1268 		}
1269 
1270 		if (last_tickets_id == space_info->tickets_id) {
1271 			flush_state++;
1272 		} else {
1273 			last_tickets_id = space_info->tickets_id;
1274 			flush_state = 0;
1275 		}
1276 
1277 		if (flush_state >= ARRAY_SIZE(data_flush_states)) {
1278 			if (space_info->full) {
1279 				if (maybe_fail_all_tickets(fs_info, space_info))
1280 					flush_state = 0;
1281 				else
1282 					space_info->flush = 0;
1283 			} else {
1284 				flush_state = 0;
1285 			}
1286 
1287 			/* Something happened, fail everything and bail. */
1288 			if (BTRFS_FS_ERROR(fs_info))
1289 				goto aborted_fs;
1290 
1291 		}
1292 		spin_unlock(&space_info->lock);
1293 	}
1294 	return;
1295 
1296 aborted_fs:
1297 	maybe_fail_all_tickets(fs_info, space_info);
1298 	space_info->flush = 0;
1299 	spin_unlock(&space_info->lock);
1300 }
1301 
1302 void btrfs_init_async_reclaim_work(struct btrfs_fs_info *fs_info)
1303 {
1304 	INIT_WORK(&fs_info->async_reclaim_work, btrfs_async_reclaim_metadata_space);
1305 	INIT_WORK(&fs_info->async_data_reclaim_work, btrfs_async_reclaim_data_space);
1306 	INIT_WORK(&fs_info->preempt_reclaim_work,
1307 		  btrfs_preempt_reclaim_metadata_space);
1308 }
1309 
1310 static const enum btrfs_flush_state priority_flush_states[] = {
1311 	FLUSH_DELAYED_ITEMS_NR,
1312 	FLUSH_DELAYED_ITEMS,
1313 	ALLOC_CHUNK,
1314 };
1315 
1316 static const enum btrfs_flush_state evict_flush_states[] = {
1317 	FLUSH_DELAYED_ITEMS_NR,
1318 	FLUSH_DELAYED_ITEMS,
1319 	FLUSH_DELAYED_REFS_NR,
1320 	FLUSH_DELAYED_REFS,
1321 	FLUSH_DELALLOC,
1322 	FLUSH_DELALLOC_WAIT,
1323 	FLUSH_DELALLOC_FULL,
1324 	ALLOC_CHUNK,
1325 	COMMIT_TRANS,
1326 };
1327 
1328 static void priority_reclaim_metadata_space(struct btrfs_fs_info *fs_info,
1329 				struct btrfs_space_info *space_info,
1330 				struct reserve_ticket *ticket,
1331 				const enum btrfs_flush_state *states,
1332 				int states_nr)
1333 {
1334 	u64 to_reclaim;
1335 	int flush_state = 0;
1336 
1337 	spin_lock(&space_info->lock);
1338 	to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info);
1339 	/*
1340 	 * This is the priority reclaim path, so to_reclaim could be >0 still
1341 	 * because we may have only satisfied the priority tickets and still
1342 	 * left non priority tickets on the list.  We would then have
1343 	 * to_reclaim but ->bytes == 0.
1344 	 */
1345 	if (ticket->bytes == 0) {
1346 		spin_unlock(&space_info->lock);
1347 		return;
1348 	}
1349 
1350 	while (flush_state < states_nr) {
1351 		spin_unlock(&space_info->lock);
1352 		flush_space(fs_info, space_info, to_reclaim, states[flush_state],
1353 			    false);
1354 		flush_state++;
1355 		spin_lock(&space_info->lock);
1356 		if (ticket->bytes == 0) {
1357 			spin_unlock(&space_info->lock);
1358 			return;
1359 		}
1360 	}
1361 
1362 	/* Attempt to steal from the global rsv if we can. */
1363 	if (!steal_from_global_rsv(fs_info, space_info, ticket)) {
1364 		ticket->error = -ENOSPC;
1365 		remove_ticket(space_info, ticket);
1366 	}
1367 
1368 	/*
1369 	 * We must run try_granting_tickets here because we could be a large
1370 	 * ticket in front of a smaller ticket that can now be satisfied with
1371 	 * the available space.
1372 	 */
1373 	btrfs_try_granting_tickets(fs_info, space_info);
1374 	spin_unlock(&space_info->lock);
1375 }
1376 
1377 static void priority_reclaim_data_space(struct btrfs_fs_info *fs_info,
1378 					struct btrfs_space_info *space_info,
1379 					struct reserve_ticket *ticket)
1380 {
1381 	spin_lock(&space_info->lock);
1382 
1383 	/* We could have been granted before we got here. */
1384 	if (ticket->bytes == 0) {
1385 		spin_unlock(&space_info->lock);
1386 		return;
1387 	}
1388 
1389 	while (!space_info->full) {
1390 		spin_unlock(&space_info->lock);
1391 		flush_space(fs_info, space_info, U64_MAX, ALLOC_CHUNK_FORCE, false);
1392 		spin_lock(&space_info->lock);
1393 		if (ticket->bytes == 0) {
1394 			spin_unlock(&space_info->lock);
1395 			return;
1396 		}
1397 	}
1398 
1399 	ticket->error = -ENOSPC;
1400 	remove_ticket(space_info, ticket);
1401 	btrfs_try_granting_tickets(fs_info, space_info);
1402 	spin_unlock(&space_info->lock);
1403 }
1404 
1405 static void wait_reserve_ticket(struct btrfs_fs_info *fs_info,
1406 				struct btrfs_space_info *space_info,
1407 				struct reserve_ticket *ticket)
1408 
1409 {
1410 	DEFINE_WAIT(wait);
1411 	int ret = 0;
1412 
1413 	spin_lock(&space_info->lock);
1414 	while (ticket->bytes > 0 && ticket->error == 0) {
1415 		ret = prepare_to_wait_event(&ticket->wait, &wait, TASK_KILLABLE);
1416 		if (ret) {
1417 			/*
1418 			 * Delete us from the list. After we unlock the space
1419 			 * info, we don't want the async reclaim job to reserve
1420 			 * space for this ticket. If that would happen, then the
1421 			 * ticket's task would not known that space was reserved
1422 			 * despite getting an error, resulting in a space leak
1423 			 * (bytes_may_use counter of our space_info).
1424 			 */
1425 			remove_ticket(space_info, ticket);
1426 			ticket->error = -EINTR;
1427 			break;
1428 		}
1429 		spin_unlock(&space_info->lock);
1430 
1431 		schedule();
1432 
1433 		finish_wait(&ticket->wait, &wait);
1434 		spin_lock(&space_info->lock);
1435 	}
1436 	spin_unlock(&space_info->lock);
1437 }
1438 
1439 /**
1440  * Do the appropriate flushing and waiting for a ticket
1441  *
1442  * @fs_info:    the filesystem
1443  * @space_info: space info for the reservation
1444  * @ticket:     ticket for the reservation
1445  * @start_ns:   timestamp when the reservation started
1446  * @orig_bytes: amount of bytes originally reserved
1447  * @flush:      how much we can flush
1448  *
1449  * This does the work of figuring out how to flush for the ticket, waiting for
1450  * the reservation, and returning the appropriate error if there is one.
1451  */
1452 static int handle_reserve_ticket(struct btrfs_fs_info *fs_info,
1453 				 struct btrfs_space_info *space_info,
1454 				 struct reserve_ticket *ticket,
1455 				 u64 start_ns, u64 orig_bytes,
1456 				 enum btrfs_reserve_flush_enum flush)
1457 {
1458 	int ret;
1459 
1460 	switch (flush) {
1461 	case BTRFS_RESERVE_FLUSH_DATA:
1462 	case BTRFS_RESERVE_FLUSH_ALL:
1463 	case BTRFS_RESERVE_FLUSH_ALL_STEAL:
1464 		wait_reserve_ticket(fs_info, space_info, ticket);
1465 		break;
1466 	case BTRFS_RESERVE_FLUSH_LIMIT:
1467 		priority_reclaim_metadata_space(fs_info, space_info, ticket,
1468 						priority_flush_states,
1469 						ARRAY_SIZE(priority_flush_states));
1470 		break;
1471 	case BTRFS_RESERVE_FLUSH_EVICT:
1472 		priority_reclaim_metadata_space(fs_info, space_info, ticket,
1473 						evict_flush_states,
1474 						ARRAY_SIZE(evict_flush_states));
1475 		break;
1476 	case BTRFS_RESERVE_FLUSH_FREE_SPACE_INODE:
1477 		priority_reclaim_data_space(fs_info, space_info, ticket);
1478 		break;
1479 	default:
1480 		ASSERT(0);
1481 		break;
1482 	}
1483 
1484 	ret = ticket->error;
1485 	ASSERT(list_empty(&ticket->list));
1486 	/*
1487 	 * Check that we can't have an error set if the reservation succeeded,
1488 	 * as that would confuse tasks and lead them to error out without
1489 	 * releasing reserved space (if an error happens the expectation is that
1490 	 * space wasn't reserved at all).
1491 	 */
1492 	ASSERT(!(ticket->bytes == 0 && ticket->error));
1493 	trace_btrfs_reserve_ticket(fs_info, space_info->flags, orig_bytes,
1494 				   start_ns, flush, ticket->error);
1495 	return ret;
1496 }
1497 
1498 /*
1499  * This returns true if this flush state will go through the ordinary flushing
1500  * code.
1501  */
1502 static inline bool is_normal_flushing(enum btrfs_reserve_flush_enum flush)
1503 {
1504 	return	(flush == BTRFS_RESERVE_FLUSH_ALL) ||
1505 		(flush == BTRFS_RESERVE_FLUSH_ALL_STEAL);
1506 }
1507 
1508 static inline void maybe_clamp_preempt(struct btrfs_fs_info *fs_info,
1509 				       struct btrfs_space_info *space_info)
1510 {
1511 	u64 ordered = percpu_counter_sum_positive(&fs_info->ordered_bytes);
1512 	u64 delalloc = percpu_counter_sum_positive(&fs_info->delalloc_bytes);
1513 
1514 	/*
1515 	 * If we're heavy on ordered operations then clamping won't help us.  We
1516 	 * need to clamp specifically to keep up with dirty'ing buffered
1517 	 * writers, because there's not a 1:1 correlation of writing delalloc
1518 	 * and freeing space, like there is with flushing delayed refs or
1519 	 * delayed nodes.  If we're already more ordered than delalloc then
1520 	 * we're keeping up, otherwise we aren't and should probably clamp.
1521 	 */
1522 	if (ordered < delalloc)
1523 		space_info->clamp = min(space_info->clamp + 1, 8);
1524 }
1525 
1526 static inline bool can_steal(enum btrfs_reserve_flush_enum flush)
1527 {
1528 	return (flush == BTRFS_RESERVE_FLUSH_ALL_STEAL ||
1529 		flush == BTRFS_RESERVE_FLUSH_EVICT);
1530 }
1531 
1532 /**
1533  * Try to reserve bytes from the block_rsv's space
1534  *
1535  * @fs_info:    the filesystem
1536  * @space_info: space info we want to allocate from
1537  * @orig_bytes: number of bytes we want
1538  * @flush:      whether or not we can flush to make our reservation
1539  *
1540  * This will reserve orig_bytes number of bytes from the space info associated
1541  * with the block_rsv.  If there is not enough space it will make an attempt to
1542  * flush out space to make room.  It will do this by flushing delalloc if
1543  * possible or committing the transaction.  If flush is 0 then no attempts to
1544  * regain reservations will be made and this will fail if there is not enough
1545  * space already.
1546  */
1547 static int __reserve_bytes(struct btrfs_fs_info *fs_info,
1548 			   struct btrfs_space_info *space_info, u64 orig_bytes,
1549 			   enum btrfs_reserve_flush_enum flush)
1550 {
1551 	struct work_struct *async_work;
1552 	struct reserve_ticket ticket;
1553 	u64 start_ns = 0;
1554 	u64 used;
1555 	int ret = 0;
1556 	bool pending_tickets;
1557 
1558 	ASSERT(orig_bytes);
1559 	ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_ALL);
1560 
1561 	if (flush == BTRFS_RESERVE_FLUSH_DATA)
1562 		async_work = &fs_info->async_data_reclaim_work;
1563 	else
1564 		async_work = &fs_info->async_reclaim_work;
1565 
1566 	spin_lock(&space_info->lock);
1567 	ret = -ENOSPC;
1568 	used = btrfs_space_info_used(space_info, true);
1569 
1570 	/*
1571 	 * We don't want NO_FLUSH allocations to jump everybody, they can
1572 	 * generally handle ENOSPC in a different way, so treat them the same as
1573 	 * normal flushers when it comes to skipping pending tickets.
1574 	 */
1575 	if (is_normal_flushing(flush) || (flush == BTRFS_RESERVE_NO_FLUSH))
1576 		pending_tickets = !list_empty(&space_info->tickets) ||
1577 			!list_empty(&space_info->priority_tickets);
1578 	else
1579 		pending_tickets = !list_empty(&space_info->priority_tickets);
1580 
1581 	/*
1582 	 * Carry on if we have enough space (short-circuit) OR call
1583 	 * can_overcommit() to ensure we can overcommit to continue.
1584 	 */
1585 	if (!pending_tickets &&
1586 	    ((used + orig_bytes <= writable_total_bytes(fs_info, space_info)) ||
1587 	     btrfs_can_overcommit(fs_info, space_info, orig_bytes, flush))) {
1588 		btrfs_space_info_update_bytes_may_use(fs_info, space_info,
1589 						      orig_bytes);
1590 		ret = 0;
1591 	}
1592 
1593 	/*
1594 	 * If we couldn't make a reservation then setup our reservation ticket
1595 	 * and kick the async worker if it's not already running.
1596 	 *
1597 	 * If we are a priority flusher then we just need to add our ticket to
1598 	 * the list and we will do our own flushing further down.
1599 	 */
1600 	if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
1601 		ticket.bytes = orig_bytes;
1602 		ticket.error = 0;
1603 		space_info->reclaim_size += ticket.bytes;
1604 		init_waitqueue_head(&ticket.wait);
1605 		ticket.steal = can_steal(flush);
1606 		if (trace_btrfs_reserve_ticket_enabled())
1607 			start_ns = ktime_get_ns();
1608 
1609 		if (flush == BTRFS_RESERVE_FLUSH_ALL ||
1610 		    flush == BTRFS_RESERVE_FLUSH_ALL_STEAL ||
1611 		    flush == BTRFS_RESERVE_FLUSH_DATA) {
1612 			list_add_tail(&ticket.list, &space_info->tickets);
1613 			if (!space_info->flush) {
1614 				/*
1615 				 * We were forced to add a reserve ticket, so
1616 				 * our preemptive flushing is unable to keep
1617 				 * up.  Clamp down on the threshold for the
1618 				 * preemptive flushing in order to keep up with
1619 				 * the workload.
1620 				 */
1621 				maybe_clamp_preempt(fs_info, space_info);
1622 
1623 				space_info->flush = 1;
1624 				trace_btrfs_trigger_flush(fs_info,
1625 							  space_info->flags,
1626 							  orig_bytes, flush,
1627 							  "enospc");
1628 				queue_work(system_unbound_wq, async_work);
1629 			}
1630 		} else {
1631 			list_add_tail(&ticket.list,
1632 				      &space_info->priority_tickets);
1633 		}
1634 	} else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
1635 		used += orig_bytes;
1636 		/*
1637 		 * We will do the space reservation dance during log replay,
1638 		 * which means we won't have fs_info->fs_root set, so don't do
1639 		 * the async reclaim as we will panic.
1640 		 */
1641 		if (!test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags) &&
1642 		    !work_busy(&fs_info->preempt_reclaim_work) &&
1643 		    need_preemptive_reclaim(fs_info, space_info)) {
1644 			trace_btrfs_trigger_flush(fs_info, space_info->flags,
1645 						  orig_bytes, flush, "preempt");
1646 			queue_work(system_unbound_wq,
1647 				   &fs_info->preempt_reclaim_work);
1648 		}
1649 	}
1650 	spin_unlock(&space_info->lock);
1651 	if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
1652 		return ret;
1653 
1654 	return handle_reserve_ticket(fs_info, space_info, &ticket, start_ns,
1655 				     orig_bytes, flush);
1656 }
1657 
1658 /**
1659  * Trye to reserve metadata bytes from the block_rsv's space
1660  *
1661  * @fs_info:    the filesystem
1662  * @block_rsv:  block_rsv we're allocating for
1663  * @orig_bytes: number of bytes we want
1664  * @flush:      whether or not we can flush to make our reservation
1665  *
1666  * This will reserve orig_bytes number of bytes from the space info associated
1667  * with the block_rsv.  If there is not enough space it will make an attempt to
1668  * flush out space to make room.  It will do this by flushing delalloc if
1669  * possible or committing the transaction.  If flush is 0 then no attempts to
1670  * regain reservations will be made and this will fail if there is not enough
1671  * space already.
1672  */
1673 int btrfs_reserve_metadata_bytes(struct btrfs_fs_info *fs_info,
1674 				 struct btrfs_block_rsv *block_rsv,
1675 				 u64 orig_bytes,
1676 				 enum btrfs_reserve_flush_enum flush)
1677 {
1678 	int ret;
1679 
1680 	ret = __reserve_bytes(fs_info, block_rsv->space_info, orig_bytes, flush);
1681 	if (ret == -ENOSPC) {
1682 		trace_btrfs_space_reservation(fs_info, "space_info:enospc",
1683 					      block_rsv->space_info->flags,
1684 					      orig_bytes, 1);
1685 
1686 		if (btrfs_test_opt(fs_info, ENOSPC_DEBUG))
1687 			btrfs_dump_space_info(fs_info, block_rsv->space_info,
1688 					      orig_bytes, 0);
1689 	}
1690 	return ret;
1691 }
1692 
1693 /**
1694  * Try to reserve data bytes for an allocation
1695  *
1696  * @fs_info: the filesystem
1697  * @bytes:   number of bytes we need
1698  * @flush:   how we are allowed to flush
1699  *
1700  * This will reserve bytes from the data space info.  If there is not enough
1701  * space then we will attempt to flush space as specified by flush.
1702  */
1703 int btrfs_reserve_data_bytes(struct btrfs_fs_info *fs_info, u64 bytes,
1704 			     enum btrfs_reserve_flush_enum flush)
1705 {
1706 	struct btrfs_space_info *data_sinfo = fs_info->data_sinfo;
1707 	int ret;
1708 
1709 	ASSERT(flush == BTRFS_RESERVE_FLUSH_DATA ||
1710 	       flush == BTRFS_RESERVE_FLUSH_FREE_SPACE_INODE);
1711 	ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_DATA);
1712 
1713 	ret = __reserve_bytes(fs_info, data_sinfo, bytes, flush);
1714 	if (ret == -ENOSPC) {
1715 		trace_btrfs_space_reservation(fs_info, "space_info:enospc",
1716 					      data_sinfo->flags, bytes, 1);
1717 		if (btrfs_test_opt(fs_info, ENOSPC_DEBUG))
1718 			btrfs_dump_space_info(fs_info, data_sinfo, bytes, 0);
1719 	}
1720 	return ret;
1721 }
1722