xref: /openbmc/linux/fs/btrfs/space-info.c (revision f6fca391)
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 			     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 	found->disk_total += total_bytes * factor;
310 	found->bytes_used += bytes_used;
311 	found->disk_used += bytes_used * factor;
312 	found->bytes_readonly += bytes_readonly;
313 	found->bytes_zone_unusable += bytes_zone_unusable;
314 	if (total_bytes > 0)
315 		found->full = 0;
316 	btrfs_try_granting_tickets(info, found);
317 	spin_unlock(&found->lock);
318 	*space_info = found;
319 }
320 
321 struct btrfs_space_info *btrfs_find_space_info(struct btrfs_fs_info *info,
322 					       u64 flags)
323 {
324 	struct list_head *head = &info->space_info;
325 	struct btrfs_space_info *found;
326 
327 	flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
328 
329 	list_for_each_entry(found, head, list) {
330 		if (found->flags & flags)
331 			return found;
332 	}
333 	return NULL;
334 }
335 
336 static u64 calc_available_free_space(struct btrfs_fs_info *fs_info,
337 			  struct btrfs_space_info *space_info,
338 			  enum btrfs_reserve_flush_enum flush)
339 {
340 	u64 profile;
341 	u64 avail;
342 	int factor;
343 
344 	if (space_info->flags & BTRFS_BLOCK_GROUP_SYSTEM)
345 		profile = btrfs_system_alloc_profile(fs_info);
346 	else
347 		profile = btrfs_metadata_alloc_profile(fs_info);
348 
349 	avail = atomic64_read(&fs_info->free_chunk_space);
350 
351 	/*
352 	 * If we have dup, raid1 or raid10 then only half of the free
353 	 * space is actually usable.  For raid56, the space info used
354 	 * doesn't include the parity drive, so we don't have to
355 	 * change the math
356 	 */
357 	factor = btrfs_bg_type_to_factor(profile);
358 	avail = div_u64(avail, factor);
359 
360 	/*
361 	 * If we aren't flushing all things, let us overcommit up to
362 	 * 1/2th of the space. If we can flush, don't let us overcommit
363 	 * too much, let it overcommit up to 1/8 of the space.
364 	 */
365 	if (flush == BTRFS_RESERVE_FLUSH_ALL)
366 		avail >>= 3;
367 	else
368 		avail >>= 1;
369 	return avail;
370 }
371 
372 int btrfs_can_overcommit(struct btrfs_fs_info *fs_info,
373 			 struct btrfs_space_info *space_info, u64 bytes,
374 			 enum btrfs_reserve_flush_enum flush)
375 {
376 	u64 avail;
377 	u64 used;
378 
379 	/* Don't overcommit when in mixed mode */
380 	if (space_info->flags & BTRFS_BLOCK_GROUP_DATA)
381 		return 0;
382 
383 	used = btrfs_space_info_used(space_info, true);
384 	avail = calc_available_free_space(fs_info, space_info, flush);
385 
386 	if (used + bytes < space_info->total_bytes + avail)
387 		return 1;
388 	return 0;
389 }
390 
391 static void remove_ticket(struct btrfs_space_info *space_info,
392 			  struct reserve_ticket *ticket)
393 {
394 	if (!list_empty(&ticket->list)) {
395 		list_del_init(&ticket->list);
396 		ASSERT(space_info->reclaim_size >= ticket->bytes);
397 		space_info->reclaim_size -= ticket->bytes;
398 	}
399 }
400 
401 /*
402  * This is for space we already have accounted in space_info->bytes_may_use, so
403  * basically when we're returning space from block_rsv's.
404  */
405 void btrfs_try_granting_tickets(struct btrfs_fs_info *fs_info,
406 				struct btrfs_space_info *space_info)
407 {
408 	struct list_head *head;
409 	enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_NO_FLUSH;
410 
411 	lockdep_assert_held(&space_info->lock);
412 
413 	head = &space_info->priority_tickets;
414 again:
415 	while (!list_empty(head)) {
416 		struct reserve_ticket *ticket;
417 		u64 used = btrfs_space_info_used(space_info, true);
418 
419 		ticket = list_first_entry(head, struct reserve_ticket, list);
420 
421 		/* Check and see if our ticket can be satisfied now. */
422 		if ((used + ticket->bytes <= space_info->total_bytes) ||
423 		    btrfs_can_overcommit(fs_info, space_info, ticket->bytes,
424 					 flush)) {
425 			btrfs_space_info_update_bytes_may_use(fs_info,
426 							      space_info,
427 							      ticket->bytes);
428 			remove_ticket(space_info, ticket);
429 			ticket->bytes = 0;
430 			space_info->tickets_id++;
431 			wake_up(&ticket->wait);
432 		} else {
433 			break;
434 		}
435 	}
436 
437 	if (head == &space_info->priority_tickets) {
438 		head = &space_info->tickets;
439 		flush = BTRFS_RESERVE_FLUSH_ALL;
440 		goto again;
441 	}
442 }
443 
444 #define DUMP_BLOCK_RSV(fs_info, rsv_name)				\
445 do {									\
446 	struct btrfs_block_rsv *__rsv = &(fs_info)->rsv_name;		\
447 	spin_lock(&__rsv->lock);					\
448 	btrfs_info(fs_info, #rsv_name ": size %llu reserved %llu",	\
449 		   __rsv->size, __rsv->reserved);			\
450 	spin_unlock(&__rsv->lock);					\
451 } while (0)
452 
453 static void __btrfs_dump_space_info(struct btrfs_fs_info *fs_info,
454 				    struct btrfs_space_info *info)
455 {
456 	lockdep_assert_held(&info->lock);
457 
458 	/* The free space could be negative in case of overcommit */
459 	btrfs_info(fs_info, "space_info %llu has %lld free, is %sfull",
460 		   info->flags,
461 		   (s64)(info->total_bytes - btrfs_space_info_used(info, true)),
462 		   info->full ? "" : "not ");
463 	btrfs_info(fs_info,
464 		"space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu zone_unusable=%llu",
465 		info->total_bytes, info->bytes_used, info->bytes_pinned,
466 		info->bytes_reserved, info->bytes_may_use,
467 		info->bytes_readonly, info->bytes_zone_unusable);
468 
469 	DUMP_BLOCK_RSV(fs_info, global_block_rsv);
470 	DUMP_BLOCK_RSV(fs_info, trans_block_rsv);
471 	DUMP_BLOCK_RSV(fs_info, chunk_block_rsv);
472 	DUMP_BLOCK_RSV(fs_info, delayed_block_rsv);
473 	DUMP_BLOCK_RSV(fs_info, delayed_refs_rsv);
474 
475 }
476 
477 void btrfs_dump_space_info(struct btrfs_fs_info *fs_info,
478 			   struct btrfs_space_info *info, u64 bytes,
479 			   int dump_block_groups)
480 {
481 	struct btrfs_block_group *cache;
482 	int index = 0;
483 
484 	spin_lock(&info->lock);
485 	__btrfs_dump_space_info(fs_info, info);
486 	spin_unlock(&info->lock);
487 
488 	if (!dump_block_groups)
489 		return;
490 
491 	down_read(&info->groups_sem);
492 again:
493 	list_for_each_entry(cache, &info->block_groups[index], list) {
494 		spin_lock(&cache->lock);
495 		btrfs_info(fs_info,
496 			"block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %llu zone_unusable %s",
497 			cache->start, cache->length, cache->used, cache->pinned,
498 			cache->reserved, cache->zone_unusable,
499 			cache->ro ? "[readonly]" : "");
500 		spin_unlock(&cache->lock);
501 		btrfs_dump_free_space(cache, bytes);
502 	}
503 	if (++index < BTRFS_NR_RAID_TYPES)
504 		goto again;
505 	up_read(&info->groups_sem);
506 }
507 
508 static inline u64 calc_reclaim_items_nr(struct btrfs_fs_info *fs_info,
509 					u64 to_reclaim)
510 {
511 	u64 bytes;
512 	u64 nr;
513 
514 	bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
515 	nr = div64_u64(to_reclaim, bytes);
516 	if (!nr)
517 		nr = 1;
518 	return nr;
519 }
520 
521 #define EXTENT_SIZE_PER_ITEM	SZ_256K
522 
523 /*
524  * shrink metadata reservation for delalloc
525  */
526 static void shrink_delalloc(struct btrfs_fs_info *fs_info,
527 			    struct btrfs_space_info *space_info,
528 			    u64 to_reclaim, bool wait_ordered,
529 			    bool for_preempt)
530 {
531 	struct btrfs_trans_handle *trans;
532 	u64 delalloc_bytes;
533 	u64 ordered_bytes;
534 	u64 items;
535 	long time_left;
536 	int loops;
537 
538 	delalloc_bytes = percpu_counter_sum_positive(&fs_info->delalloc_bytes);
539 	ordered_bytes = percpu_counter_sum_positive(&fs_info->ordered_bytes);
540 	if (delalloc_bytes == 0 && ordered_bytes == 0)
541 		return;
542 
543 	/* Calc the number of the pages we need flush for space reservation */
544 	if (to_reclaim == U64_MAX) {
545 		items = U64_MAX;
546 	} else {
547 		/*
548 		 * to_reclaim is set to however much metadata we need to
549 		 * reclaim, but reclaiming that much data doesn't really track
550 		 * exactly.  What we really want to do is reclaim full inode's
551 		 * worth of reservations, however that's not available to us
552 		 * here.  We will take a fraction of the delalloc bytes for our
553 		 * flushing loops and hope for the best.  Delalloc will expand
554 		 * the amount we write to cover an entire dirty extent, which
555 		 * will reclaim the metadata reservation for that range.  If
556 		 * it's not enough subsequent flush stages will be more
557 		 * aggressive.
558 		 */
559 		to_reclaim = max(to_reclaim, delalloc_bytes >> 3);
560 		items = calc_reclaim_items_nr(fs_info, to_reclaim) * 2;
561 	}
562 
563 	trans = current->journal_info;
564 
565 	/*
566 	 * If we are doing more ordered than delalloc we need to just wait on
567 	 * ordered extents, otherwise we'll waste time trying to flush delalloc
568 	 * that likely won't give us the space back we need.
569 	 */
570 	if (ordered_bytes > delalloc_bytes && !for_preempt)
571 		wait_ordered = true;
572 
573 	loops = 0;
574 	while ((delalloc_bytes || ordered_bytes) && loops < 3) {
575 		u64 temp = min(delalloc_bytes, to_reclaim) >> PAGE_SHIFT;
576 		long nr_pages = min_t(u64, temp, LONG_MAX);
577 		int async_pages;
578 
579 		btrfs_start_delalloc_roots(fs_info, nr_pages, true);
580 
581 		/*
582 		 * We need to make sure any outstanding async pages are now
583 		 * processed before we continue.  This is because things like
584 		 * sync_inode() try to be smart and skip writing if the inode is
585 		 * marked clean.  We don't use filemap_fwrite for flushing
586 		 * because we want to control how many pages we write out at a
587 		 * time, thus this is the only safe way to make sure we've
588 		 * waited for outstanding compressed workers to have started
589 		 * their jobs and thus have ordered extents set up properly.
590 		 *
591 		 * This exists because we do not want to wait for each
592 		 * individual inode to finish its async work, we simply want to
593 		 * start the IO on everybody, and then come back here and wait
594 		 * for all of the async work to catch up.  Once we're done with
595 		 * that we know we'll have ordered extents for everything and we
596 		 * can decide if we wait for that or not.
597 		 *
598 		 * If we choose to replace this in the future, make absolutely
599 		 * sure that the proper waiting is being done in the async case,
600 		 * as there have been bugs in that area before.
601 		 */
602 		async_pages = atomic_read(&fs_info->async_delalloc_pages);
603 		if (!async_pages)
604 			goto skip_async;
605 
606 		/*
607 		 * We don't want to wait forever, if we wrote less pages in this
608 		 * loop than we have outstanding, only wait for that number of
609 		 * pages, otherwise we can wait for all async pages to finish
610 		 * before continuing.
611 		 */
612 		if (async_pages > nr_pages)
613 			async_pages -= nr_pages;
614 		else
615 			async_pages = 0;
616 		wait_event(fs_info->async_submit_wait,
617 			   atomic_read(&fs_info->async_delalloc_pages) <=
618 			   async_pages);
619 skip_async:
620 		loops++;
621 		if (wait_ordered && !trans) {
622 			btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
623 		} else {
624 			time_left = schedule_timeout_killable(1);
625 			if (time_left)
626 				break;
627 		}
628 
629 		/*
630 		 * If we are for preemption we just want a one-shot of delalloc
631 		 * flushing so we can stop flushing if we decide we don't need
632 		 * to anymore.
633 		 */
634 		if (for_preempt)
635 			break;
636 
637 		spin_lock(&space_info->lock);
638 		if (list_empty(&space_info->tickets) &&
639 		    list_empty(&space_info->priority_tickets)) {
640 			spin_unlock(&space_info->lock);
641 			break;
642 		}
643 		spin_unlock(&space_info->lock);
644 
645 		delalloc_bytes = percpu_counter_sum_positive(
646 						&fs_info->delalloc_bytes);
647 		ordered_bytes = percpu_counter_sum_positive(
648 						&fs_info->ordered_bytes);
649 	}
650 }
651 
652 /*
653  * Try to flush some data based on policy set by @state. This is only advisory
654  * and may fail for various reasons. The caller is supposed to examine the
655  * state of @space_info to detect the outcome.
656  */
657 static void flush_space(struct btrfs_fs_info *fs_info,
658 		       struct btrfs_space_info *space_info, u64 num_bytes,
659 		       enum btrfs_flush_state state, bool for_preempt)
660 {
661 	struct btrfs_root *root = fs_info->tree_root;
662 	struct btrfs_trans_handle *trans;
663 	int nr;
664 	int ret = 0;
665 
666 	switch (state) {
667 	case FLUSH_DELAYED_ITEMS_NR:
668 	case FLUSH_DELAYED_ITEMS:
669 		if (state == FLUSH_DELAYED_ITEMS_NR)
670 			nr = calc_reclaim_items_nr(fs_info, num_bytes) * 2;
671 		else
672 			nr = -1;
673 
674 		trans = btrfs_join_transaction(root);
675 		if (IS_ERR(trans)) {
676 			ret = PTR_ERR(trans);
677 			break;
678 		}
679 		ret = btrfs_run_delayed_items_nr(trans, nr);
680 		btrfs_end_transaction(trans);
681 		break;
682 	case FLUSH_DELALLOC:
683 	case FLUSH_DELALLOC_WAIT:
684 	case FLUSH_DELALLOC_FULL:
685 		if (state == FLUSH_DELALLOC_FULL)
686 			num_bytes = U64_MAX;
687 		shrink_delalloc(fs_info, space_info, num_bytes,
688 				state != FLUSH_DELALLOC, for_preempt);
689 		break;
690 	case FLUSH_DELAYED_REFS_NR:
691 	case FLUSH_DELAYED_REFS:
692 		trans = btrfs_join_transaction(root);
693 		if (IS_ERR(trans)) {
694 			ret = PTR_ERR(trans);
695 			break;
696 		}
697 		if (state == FLUSH_DELAYED_REFS_NR)
698 			nr = calc_reclaim_items_nr(fs_info, num_bytes);
699 		else
700 			nr = 0;
701 		btrfs_run_delayed_refs(trans, nr);
702 		btrfs_end_transaction(trans);
703 		break;
704 	case ALLOC_CHUNK:
705 	case ALLOC_CHUNK_FORCE:
706 		trans = btrfs_join_transaction(root);
707 		if (IS_ERR(trans)) {
708 			ret = PTR_ERR(trans);
709 			break;
710 		}
711 		ret = btrfs_chunk_alloc(trans,
712 				btrfs_get_alloc_profile(fs_info, space_info->flags),
713 				(state == ALLOC_CHUNK) ? CHUNK_ALLOC_NO_FORCE :
714 					CHUNK_ALLOC_FORCE);
715 		btrfs_end_transaction(trans);
716 		if (ret > 0 || ret == -ENOSPC)
717 			ret = 0;
718 		break;
719 	case RUN_DELAYED_IPUTS:
720 		/*
721 		 * If we have pending delayed iputs then we could free up a
722 		 * bunch of pinned space, so make sure we run the iputs before
723 		 * we do our pinned bytes check below.
724 		 */
725 		btrfs_run_delayed_iputs(fs_info);
726 		btrfs_wait_on_delayed_iputs(fs_info);
727 		break;
728 	case COMMIT_TRANS:
729 		ASSERT(current->journal_info == NULL);
730 		trans = btrfs_join_transaction(root);
731 		if (IS_ERR(trans)) {
732 			ret = PTR_ERR(trans);
733 			break;
734 		}
735 		ret = btrfs_commit_transaction(trans);
736 		break;
737 	default:
738 		ret = -ENOSPC;
739 		break;
740 	}
741 
742 	trace_btrfs_flush_space(fs_info, space_info->flags, num_bytes, state,
743 				ret, for_preempt);
744 	return;
745 }
746 
747 static inline u64
748 btrfs_calc_reclaim_metadata_size(struct btrfs_fs_info *fs_info,
749 				 struct btrfs_space_info *space_info)
750 {
751 	u64 used;
752 	u64 avail;
753 	u64 to_reclaim = space_info->reclaim_size;
754 
755 	lockdep_assert_held(&space_info->lock);
756 
757 	avail = calc_available_free_space(fs_info, space_info,
758 					  BTRFS_RESERVE_FLUSH_ALL);
759 	used = btrfs_space_info_used(space_info, true);
760 
761 	/*
762 	 * We may be flushing because suddenly we have less space than we had
763 	 * before, and now we're well over-committed based on our current free
764 	 * space.  If that's the case add in our overage so we make sure to put
765 	 * appropriate pressure on the flushing state machine.
766 	 */
767 	if (space_info->total_bytes + avail < used)
768 		to_reclaim += used - (space_info->total_bytes + avail);
769 
770 	return to_reclaim;
771 }
772 
773 static bool need_preemptive_reclaim(struct btrfs_fs_info *fs_info,
774 				    struct btrfs_space_info *space_info)
775 {
776 	u64 global_rsv_size = fs_info->global_block_rsv.reserved;
777 	u64 ordered, delalloc;
778 	u64 thresh = div_factor_fine(space_info->total_bytes, 90);
779 	u64 used;
780 
781 	lockdep_assert_held(&space_info->lock);
782 
783 	/* If we're just plain full then async reclaim just slows us down. */
784 	if ((space_info->bytes_used + space_info->bytes_reserved +
785 	     global_rsv_size) >= thresh)
786 		return false;
787 
788 	used = space_info->bytes_may_use + space_info->bytes_pinned;
789 
790 	/* The total flushable belongs to the global rsv, don't flush. */
791 	if (global_rsv_size >= used)
792 		return false;
793 
794 	/*
795 	 * 128MiB is 1/4 of the maximum global rsv size.  If we have less than
796 	 * that devoted to other reservations then there's no sense in flushing,
797 	 * we don't have a lot of things that need flushing.
798 	 */
799 	if (used - global_rsv_size <= SZ_128M)
800 		return false;
801 
802 	/*
803 	 * We have tickets queued, bail so we don't compete with the async
804 	 * flushers.
805 	 */
806 	if (space_info->reclaim_size)
807 		return false;
808 
809 	/*
810 	 * If we have over half of the free space occupied by reservations or
811 	 * pinned then we want to start flushing.
812 	 *
813 	 * We do not do the traditional thing here, which is to say
814 	 *
815 	 *   if (used >= ((total_bytes + avail) / 2))
816 	 *     return 1;
817 	 *
818 	 * because this doesn't quite work how we want.  If we had more than 50%
819 	 * of the space_info used by bytes_used and we had 0 available we'd just
820 	 * constantly run the background flusher.  Instead we want it to kick in
821 	 * if our reclaimable space exceeds our clamped free space.
822 	 *
823 	 * Our clamping range is 2^1 -> 2^8.  Practically speaking that means
824 	 * the following:
825 	 *
826 	 * Amount of RAM        Minimum threshold       Maximum threshold
827 	 *
828 	 *        256GiB                     1GiB                  128GiB
829 	 *        128GiB                   512MiB                   64GiB
830 	 *         64GiB                   256MiB                   32GiB
831 	 *         32GiB                   128MiB                   16GiB
832 	 *         16GiB                    64MiB                    8GiB
833 	 *
834 	 * These are the range our thresholds will fall in, corresponding to how
835 	 * much delalloc we need for the background flusher to kick in.
836 	 */
837 
838 	thresh = calc_available_free_space(fs_info, space_info,
839 					   BTRFS_RESERVE_FLUSH_ALL);
840 	used = space_info->bytes_used + space_info->bytes_reserved +
841 	       space_info->bytes_readonly + global_rsv_size;
842 	if (used < space_info->total_bytes)
843 		thresh += space_info->total_bytes - used;
844 	thresh >>= space_info->clamp;
845 
846 	used = space_info->bytes_pinned;
847 
848 	/*
849 	 * If we have more ordered bytes than delalloc bytes then we're either
850 	 * doing a lot of DIO, or we simply don't have a lot of delalloc waiting
851 	 * around.  Preemptive flushing is only useful in that it can free up
852 	 * space before tickets need to wait for things to finish.  In the case
853 	 * of ordered extents, preemptively waiting on ordered extents gets us
854 	 * nothing, if our reservations are tied up in ordered extents we'll
855 	 * simply have to slow down writers by forcing them to wait on ordered
856 	 * extents.
857 	 *
858 	 * In the case that ordered is larger than delalloc, only include the
859 	 * block reserves that we would actually be able to directly reclaim
860 	 * from.  In this case if we're heavy on metadata operations this will
861 	 * clearly be heavy enough to warrant preemptive flushing.  In the case
862 	 * of heavy DIO or ordered reservations, preemptive flushing will just
863 	 * waste time and cause us to slow down.
864 	 *
865 	 * We want to make sure we truly are maxed out on ordered however, so
866 	 * cut ordered in half, and if it's still higher than delalloc then we
867 	 * can keep flushing.  This is to avoid the case where we start
868 	 * flushing, and now delalloc == ordered and we stop preemptively
869 	 * flushing when we could still have several gigs of delalloc to flush.
870 	 */
871 	ordered = percpu_counter_read_positive(&fs_info->ordered_bytes) >> 1;
872 	delalloc = percpu_counter_read_positive(&fs_info->delalloc_bytes);
873 	if (ordered >= delalloc)
874 		used += fs_info->delayed_refs_rsv.reserved +
875 			fs_info->delayed_block_rsv.reserved;
876 	else
877 		used += space_info->bytes_may_use - global_rsv_size;
878 
879 	return (used >= thresh && !btrfs_fs_closing(fs_info) &&
880 		!test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
881 }
882 
883 static bool steal_from_global_rsv(struct btrfs_fs_info *fs_info,
884 				  struct btrfs_space_info *space_info,
885 				  struct reserve_ticket *ticket)
886 {
887 	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
888 	u64 min_bytes;
889 
890 	if (!ticket->steal)
891 		return false;
892 
893 	if (global_rsv->space_info != space_info)
894 		return false;
895 
896 	spin_lock(&global_rsv->lock);
897 	min_bytes = div_factor(global_rsv->size, 1);
898 	if (global_rsv->reserved < min_bytes + ticket->bytes) {
899 		spin_unlock(&global_rsv->lock);
900 		return false;
901 	}
902 	global_rsv->reserved -= ticket->bytes;
903 	remove_ticket(space_info, ticket);
904 	ticket->bytes = 0;
905 	wake_up(&ticket->wait);
906 	space_info->tickets_id++;
907 	if (global_rsv->reserved < global_rsv->size)
908 		global_rsv->full = 0;
909 	spin_unlock(&global_rsv->lock);
910 
911 	return true;
912 }
913 
914 /*
915  * maybe_fail_all_tickets - we've exhausted our flushing, start failing tickets
916  * @fs_info - fs_info for this fs
917  * @space_info - the space info we were flushing
918  *
919  * We call this when we've exhausted our flushing ability and haven't made
920  * progress in satisfying tickets.  The reservation code handles tickets in
921  * order, so if there is a large ticket first and then smaller ones we could
922  * very well satisfy the smaller tickets.  This will attempt to wake up any
923  * tickets in the list to catch this case.
924  *
925  * This function returns true if it was able to make progress by clearing out
926  * other tickets, or if it stumbles across a ticket that was smaller than the
927  * first ticket.
928  */
929 static bool maybe_fail_all_tickets(struct btrfs_fs_info *fs_info,
930 				   struct btrfs_space_info *space_info)
931 {
932 	struct reserve_ticket *ticket;
933 	u64 tickets_id = space_info->tickets_id;
934 	const bool aborted = BTRFS_FS_ERROR(fs_info);
935 
936 	trace_btrfs_fail_all_tickets(fs_info, space_info);
937 
938 	if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
939 		btrfs_info(fs_info, "cannot satisfy tickets, dumping space info");
940 		__btrfs_dump_space_info(fs_info, space_info);
941 	}
942 
943 	while (!list_empty(&space_info->tickets) &&
944 	       tickets_id == space_info->tickets_id) {
945 		ticket = list_first_entry(&space_info->tickets,
946 					  struct reserve_ticket, list);
947 
948 		if (!aborted && steal_from_global_rsv(fs_info, space_info, ticket))
949 			return true;
950 
951 		if (!aborted && btrfs_test_opt(fs_info, ENOSPC_DEBUG))
952 			btrfs_info(fs_info, "failing ticket with %llu bytes",
953 				   ticket->bytes);
954 
955 		remove_ticket(space_info, ticket);
956 		if (aborted)
957 			ticket->error = -EIO;
958 		else
959 			ticket->error = -ENOSPC;
960 		wake_up(&ticket->wait);
961 
962 		/*
963 		 * We're just throwing tickets away, so more flushing may not
964 		 * trip over btrfs_try_granting_tickets, so we need to call it
965 		 * here to see if we can make progress with the next ticket in
966 		 * the list.
967 		 */
968 		if (!aborted)
969 			btrfs_try_granting_tickets(fs_info, space_info);
970 	}
971 	return (tickets_id != space_info->tickets_id);
972 }
973 
974 /*
975  * This is for normal flushers, we can wait all goddamned day if we want to.  We
976  * will loop and continuously try to flush as long as we are making progress.
977  * We count progress as clearing off tickets each time we have to loop.
978  */
979 static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
980 {
981 	struct btrfs_fs_info *fs_info;
982 	struct btrfs_space_info *space_info;
983 	u64 to_reclaim;
984 	enum btrfs_flush_state flush_state;
985 	int commit_cycles = 0;
986 	u64 last_tickets_id;
987 
988 	fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
989 	space_info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
990 
991 	spin_lock(&space_info->lock);
992 	to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info);
993 	if (!to_reclaim) {
994 		space_info->flush = 0;
995 		spin_unlock(&space_info->lock);
996 		return;
997 	}
998 	last_tickets_id = space_info->tickets_id;
999 	spin_unlock(&space_info->lock);
1000 
1001 	flush_state = FLUSH_DELAYED_ITEMS_NR;
1002 	do {
1003 		flush_space(fs_info, space_info, to_reclaim, flush_state, false);
1004 		spin_lock(&space_info->lock);
1005 		if (list_empty(&space_info->tickets)) {
1006 			space_info->flush = 0;
1007 			spin_unlock(&space_info->lock);
1008 			return;
1009 		}
1010 		to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info,
1011 							      space_info);
1012 		if (last_tickets_id == space_info->tickets_id) {
1013 			flush_state++;
1014 		} else {
1015 			last_tickets_id = space_info->tickets_id;
1016 			flush_state = FLUSH_DELAYED_ITEMS_NR;
1017 			if (commit_cycles)
1018 				commit_cycles--;
1019 		}
1020 
1021 		/*
1022 		 * We do not want to empty the system of delalloc unless we're
1023 		 * under heavy pressure, so allow one trip through the flushing
1024 		 * logic before we start doing a FLUSH_DELALLOC_FULL.
1025 		 */
1026 		if (flush_state == FLUSH_DELALLOC_FULL && !commit_cycles)
1027 			flush_state++;
1028 
1029 		/*
1030 		 * We don't want to force a chunk allocation until we've tried
1031 		 * pretty hard to reclaim space.  Think of the case where we
1032 		 * freed up a bunch of space and so have a lot of pinned space
1033 		 * to reclaim.  We would rather use that than possibly create a
1034 		 * underutilized metadata chunk.  So if this is our first run
1035 		 * through the flushing state machine skip ALLOC_CHUNK_FORCE and
1036 		 * commit the transaction.  If nothing has changed the next go
1037 		 * around then we can force a chunk allocation.
1038 		 */
1039 		if (flush_state == ALLOC_CHUNK_FORCE && !commit_cycles)
1040 			flush_state++;
1041 
1042 		if (flush_state > COMMIT_TRANS) {
1043 			commit_cycles++;
1044 			if (commit_cycles > 2) {
1045 				if (maybe_fail_all_tickets(fs_info, space_info)) {
1046 					flush_state = FLUSH_DELAYED_ITEMS_NR;
1047 					commit_cycles--;
1048 				} else {
1049 					space_info->flush = 0;
1050 				}
1051 			} else {
1052 				flush_state = FLUSH_DELAYED_ITEMS_NR;
1053 			}
1054 		}
1055 		spin_unlock(&space_info->lock);
1056 	} while (flush_state <= COMMIT_TRANS);
1057 }
1058 
1059 /*
1060  * This handles pre-flushing of metadata space before we get to the point that
1061  * we need to start blocking threads on tickets.  The logic here is different
1062  * from the other flush paths because it doesn't rely on tickets to tell us how
1063  * much we need to flush, instead it attempts to keep us below the 80% full
1064  * watermark of space by flushing whichever reservation pool is currently the
1065  * largest.
1066  */
1067 static void btrfs_preempt_reclaim_metadata_space(struct work_struct *work)
1068 {
1069 	struct btrfs_fs_info *fs_info;
1070 	struct btrfs_space_info *space_info;
1071 	struct btrfs_block_rsv *delayed_block_rsv;
1072 	struct btrfs_block_rsv *delayed_refs_rsv;
1073 	struct btrfs_block_rsv *global_rsv;
1074 	struct btrfs_block_rsv *trans_rsv;
1075 	int loops = 0;
1076 
1077 	fs_info = container_of(work, struct btrfs_fs_info,
1078 			       preempt_reclaim_work);
1079 	space_info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
1080 	delayed_block_rsv = &fs_info->delayed_block_rsv;
1081 	delayed_refs_rsv = &fs_info->delayed_refs_rsv;
1082 	global_rsv = &fs_info->global_block_rsv;
1083 	trans_rsv = &fs_info->trans_block_rsv;
1084 
1085 	spin_lock(&space_info->lock);
1086 	while (need_preemptive_reclaim(fs_info, space_info)) {
1087 		enum btrfs_flush_state flush;
1088 		u64 delalloc_size = 0;
1089 		u64 to_reclaim, block_rsv_size;
1090 		u64 global_rsv_size = global_rsv->reserved;
1091 
1092 		loops++;
1093 
1094 		/*
1095 		 * We don't have a precise counter for the metadata being
1096 		 * reserved for delalloc, so we'll approximate it by subtracting
1097 		 * out the block rsv's space from the bytes_may_use.  If that
1098 		 * amount is higher than the individual reserves, then we can
1099 		 * assume it's tied up in delalloc reservations.
1100 		 */
1101 		block_rsv_size = global_rsv_size +
1102 			delayed_block_rsv->reserved +
1103 			delayed_refs_rsv->reserved +
1104 			trans_rsv->reserved;
1105 		if (block_rsv_size < space_info->bytes_may_use)
1106 			delalloc_size = space_info->bytes_may_use - block_rsv_size;
1107 
1108 		/*
1109 		 * We don't want to include the global_rsv in our calculation,
1110 		 * because that's space we can't touch.  Subtract it from the
1111 		 * block_rsv_size for the next checks.
1112 		 */
1113 		block_rsv_size -= global_rsv_size;
1114 
1115 		/*
1116 		 * We really want to avoid flushing delalloc too much, as it
1117 		 * could result in poor allocation patterns, so only flush it if
1118 		 * it's larger than the rest of the pools combined.
1119 		 */
1120 		if (delalloc_size > block_rsv_size) {
1121 			to_reclaim = delalloc_size;
1122 			flush = FLUSH_DELALLOC;
1123 		} else if (space_info->bytes_pinned >
1124 			   (delayed_block_rsv->reserved +
1125 			    delayed_refs_rsv->reserved)) {
1126 			to_reclaim = space_info->bytes_pinned;
1127 			flush = COMMIT_TRANS;
1128 		} else if (delayed_block_rsv->reserved >
1129 			   delayed_refs_rsv->reserved) {
1130 			to_reclaim = delayed_block_rsv->reserved;
1131 			flush = FLUSH_DELAYED_ITEMS_NR;
1132 		} else {
1133 			to_reclaim = delayed_refs_rsv->reserved;
1134 			flush = FLUSH_DELAYED_REFS_NR;
1135 		}
1136 
1137 		spin_unlock(&space_info->lock);
1138 
1139 		/*
1140 		 * We don't want to reclaim everything, just a portion, so scale
1141 		 * down the to_reclaim by 1/4.  If it takes us down to 0,
1142 		 * reclaim 1 items worth.
1143 		 */
1144 		to_reclaim >>= 2;
1145 		if (!to_reclaim)
1146 			to_reclaim = btrfs_calc_insert_metadata_size(fs_info, 1);
1147 		flush_space(fs_info, space_info, to_reclaim, flush, true);
1148 		cond_resched();
1149 		spin_lock(&space_info->lock);
1150 	}
1151 
1152 	/* We only went through once, back off our clamping. */
1153 	if (loops == 1 && !space_info->reclaim_size)
1154 		space_info->clamp = max(1, space_info->clamp - 1);
1155 	trace_btrfs_done_preemptive_reclaim(fs_info, space_info);
1156 	spin_unlock(&space_info->lock);
1157 }
1158 
1159 /*
1160  * FLUSH_DELALLOC_WAIT:
1161  *   Space is freed from flushing delalloc in one of two ways.
1162  *
1163  *   1) compression is on and we allocate less space than we reserved
1164  *   2) we are overwriting existing space
1165  *
1166  *   For #1 that extra space is reclaimed as soon as the delalloc pages are
1167  *   COWed, by way of btrfs_add_reserved_bytes() which adds the actual extent
1168  *   length to ->bytes_reserved, and subtracts the reserved space from
1169  *   ->bytes_may_use.
1170  *
1171  *   For #2 this is trickier.  Once the ordered extent runs we will drop the
1172  *   extent in the range we are overwriting, which creates a delayed ref for
1173  *   that freed extent.  This however is not reclaimed until the transaction
1174  *   commits, thus the next stages.
1175  *
1176  * RUN_DELAYED_IPUTS
1177  *   If we are freeing inodes, we want to make sure all delayed iputs have
1178  *   completed, because they could have been on an inode with i_nlink == 0, and
1179  *   thus have been truncated and freed up space.  But again this space is not
1180  *   immediately re-usable, it comes in the form of a delayed ref, which must be
1181  *   run and then the transaction must be committed.
1182  *
1183  * COMMIT_TRANS
1184  *   This is where we reclaim all of the pinned space generated by running the
1185  *   iputs
1186  *
1187  * ALLOC_CHUNK_FORCE
1188  *   For data we start with alloc chunk force, however we could have been full
1189  *   before, and then the transaction commit could have freed new block groups,
1190  *   so if we now have space to allocate do the force chunk allocation.
1191  */
1192 static const enum btrfs_flush_state data_flush_states[] = {
1193 	FLUSH_DELALLOC_FULL,
1194 	RUN_DELAYED_IPUTS,
1195 	COMMIT_TRANS,
1196 	ALLOC_CHUNK_FORCE,
1197 };
1198 
1199 static void btrfs_async_reclaim_data_space(struct work_struct *work)
1200 {
1201 	struct btrfs_fs_info *fs_info;
1202 	struct btrfs_space_info *space_info;
1203 	u64 last_tickets_id;
1204 	enum btrfs_flush_state flush_state = 0;
1205 
1206 	fs_info = container_of(work, struct btrfs_fs_info, async_data_reclaim_work);
1207 	space_info = fs_info->data_sinfo;
1208 
1209 	spin_lock(&space_info->lock);
1210 	if (list_empty(&space_info->tickets)) {
1211 		space_info->flush = 0;
1212 		spin_unlock(&space_info->lock);
1213 		return;
1214 	}
1215 	last_tickets_id = space_info->tickets_id;
1216 	spin_unlock(&space_info->lock);
1217 
1218 	while (!space_info->full) {
1219 		flush_space(fs_info, space_info, U64_MAX, ALLOC_CHUNK_FORCE, false);
1220 		spin_lock(&space_info->lock);
1221 		if (list_empty(&space_info->tickets)) {
1222 			space_info->flush = 0;
1223 			spin_unlock(&space_info->lock);
1224 			return;
1225 		}
1226 
1227 		/* Something happened, fail everything and bail. */
1228 		if (BTRFS_FS_ERROR(fs_info))
1229 			goto aborted_fs;
1230 		last_tickets_id = space_info->tickets_id;
1231 		spin_unlock(&space_info->lock);
1232 	}
1233 
1234 	while (flush_state < ARRAY_SIZE(data_flush_states)) {
1235 		flush_space(fs_info, space_info, U64_MAX,
1236 			    data_flush_states[flush_state], false);
1237 		spin_lock(&space_info->lock);
1238 		if (list_empty(&space_info->tickets)) {
1239 			space_info->flush = 0;
1240 			spin_unlock(&space_info->lock);
1241 			return;
1242 		}
1243 
1244 		if (last_tickets_id == space_info->tickets_id) {
1245 			flush_state++;
1246 		} else {
1247 			last_tickets_id = space_info->tickets_id;
1248 			flush_state = 0;
1249 		}
1250 
1251 		if (flush_state >= ARRAY_SIZE(data_flush_states)) {
1252 			if (space_info->full) {
1253 				if (maybe_fail_all_tickets(fs_info, space_info))
1254 					flush_state = 0;
1255 				else
1256 					space_info->flush = 0;
1257 			} else {
1258 				flush_state = 0;
1259 			}
1260 
1261 			/* Something happened, fail everything and bail. */
1262 			if (BTRFS_FS_ERROR(fs_info))
1263 				goto aborted_fs;
1264 
1265 		}
1266 		spin_unlock(&space_info->lock);
1267 	}
1268 	return;
1269 
1270 aborted_fs:
1271 	maybe_fail_all_tickets(fs_info, space_info);
1272 	space_info->flush = 0;
1273 	spin_unlock(&space_info->lock);
1274 }
1275 
1276 void btrfs_init_async_reclaim_work(struct btrfs_fs_info *fs_info)
1277 {
1278 	INIT_WORK(&fs_info->async_reclaim_work, btrfs_async_reclaim_metadata_space);
1279 	INIT_WORK(&fs_info->async_data_reclaim_work, btrfs_async_reclaim_data_space);
1280 	INIT_WORK(&fs_info->preempt_reclaim_work,
1281 		  btrfs_preempt_reclaim_metadata_space);
1282 }
1283 
1284 static const enum btrfs_flush_state priority_flush_states[] = {
1285 	FLUSH_DELAYED_ITEMS_NR,
1286 	FLUSH_DELAYED_ITEMS,
1287 	ALLOC_CHUNK,
1288 };
1289 
1290 static const enum btrfs_flush_state evict_flush_states[] = {
1291 	FLUSH_DELAYED_ITEMS_NR,
1292 	FLUSH_DELAYED_ITEMS,
1293 	FLUSH_DELAYED_REFS_NR,
1294 	FLUSH_DELAYED_REFS,
1295 	FLUSH_DELALLOC,
1296 	FLUSH_DELALLOC_WAIT,
1297 	FLUSH_DELALLOC_FULL,
1298 	ALLOC_CHUNK,
1299 	COMMIT_TRANS,
1300 };
1301 
1302 static void priority_reclaim_metadata_space(struct btrfs_fs_info *fs_info,
1303 				struct btrfs_space_info *space_info,
1304 				struct reserve_ticket *ticket,
1305 				const enum btrfs_flush_state *states,
1306 				int states_nr)
1307 {
1308 	u64 to_reclaim;
1309 	int flush_state = 0;
1310 
1311 	spin_lock(&space_info->lock);
1312 	to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info);
1313 	/*
1314 	 * This is the priority reclaim path, so to_reclaim could be >0 still
1315 	 * because we may have only satisfied the priority tickets and still
1316 	 * left non priority tickets on the list.  We would then have
1317 	 * to_reclaim but ->bytes == 0.
1318 	 */
1319 	if (ticket->bytes == 0) {
1320 		spin_unlock(&space_info->lock);
1321 		return;
1322 	}
1323 
1324 	while (flush_state < states_nr) {
1325 		spin_unlock(&space_info->lock);
1326 		flush_space(fs_info, space_info, to_reclaim, states[flush_state],
1327 			    false);
1328 		flush_state++;
1329 		spin_lock(&space_info->lock);
1330 		if (ticket->bytes == 0) {
1331 			spin_unlock(&space_info->lock);
1332 			return;
1333 		}
1334 	}
1335 
1336 	/* Attempt to steal from the global rsv if we can. */
1337 	if (!steal_from_global_rsv(fs_info, space_info, ticket)) {
1338 		ticket->error = -ENOSPC;
1339 		remove_ticket(space_info, ticket);
1340 	}
1341 
1342 	/*
1343 	 * We must run try_granting_tickets here because we could be a large
1344 	 * ticket in front of a smaller ticket that can now be satisfied with
1345 	 * the available space.
1346 	 */
1347 	btrfs_try_granting_tickets(fs_info, space_info);
1348 	spin_unlock(&space_info->lock);
1349 }
1350 
1351 static void priority_reclaim_data_space(struct btrfs_fs_info *fs_info,
1352 					struct btrfs_space_info *space_info,
1353 					struct reserve_ticket *ticket)
1354 {
1355 	spin_lock(&space_info->lock);
1356 
1357 	/* We could have been granted before we got here. */
1358 	if (ticket->bytes == 0) {
1359 		spin_unlock(&space_info->lock);
1360 		return;
1361 	}
1362 
1363 	while (!space_info->full) {
1364 		spin_unlock(&space_info->lock);
1365 		flush_space(fs_info, space_info, U64_MAX, ALLOC_CHUNK_FORCE, false);
1366 		spin_lock(&space_info->lock);
1367 		if (ticket->bytes == 0) {
1368 			spin_unlock(&space_info->lock);
1369 			return;
1370 		}
1371 	}
1372 
1373 	ticket->error = -ENOSPC;
1374 	remove_ticket(space_info, ticket);
1375 	btrfs_try_granting_tickets(fs_info, space_info);
1376 	spin_unlock(&space_info->lock);
1377 }
1378 
1379 static void wait_reserve_ticket(struct btrfs_fs_info *fs_info,
1380 				struct btrfs_space_info *space_info,
1381 				struct reserve_ticket *ticket)
1382 
1383 {
1384 	DEFINE_WAIT(wait);
1385 	int ret = 0;
1386 
1387 	spin_lock(&space_info->lock);
1388 	while (ticket->bytes > 0 && ticket->error == 0) {
1389 		ret = prepare_to_wait_event(&ticket->wait, &wait, TASK_KILLABLE);
1390 		if (ret) {
1391 			/*
1392 			 * Delete us from the list. After we unlock the space
1393 			 * info, we don't want the async reclaim job to reserve
1394 			 * space for this ticket. If that would happen, then the
1395 			 * ticket's task would not known that space was reserved
1396 			 * despite getting an error, resulting in a space leak
1397 			 * (bytes_may_use counter of our space_info).
1398 			 */
1399 			remove_ticket(space_info, ticket);
1400 			ticket->error = -EINTR;
1401 			break;
1402 		}
1403 		spin_unlock(&space_info->lock);
1404 
1405 		schedule();
1406 
1407 		finish_wait(&ticket->wait, &wait);
1408 		spin_lock(&space_info->lock);
1409 	}
1410 	spin_unlock(&space_info->lock);
1411 }
1412 
1413 /**
1414  * Do the appropriate flushing and waiting for a ticket
1415  *
1416  * @fs_info:    the filesystem
1417  * @space_info: space info for the reservation
1418  * @ticket:     ticket for the reservation
1419  * @start_ns:   timestamp when the reservation started
1420  * @orig_bytes: amount of bytes originally reserved
1421  * @flush:      how much we can flush
1422  *
1423  * This does the work of figuring out how to flush for the ticket, waiting for
1424  * the reservation, and returning the appropriate error if there is one.
1425  */
1426 static int handle_reserve_ticket(struct btrfs_fs_info *fs_info,
1427 				 struct btrfs_space_info *space_info,
1428 				 struct reserve_ticket *ticket,
1429 				 u64 start_ns, u64 orig_bytes,
1430 				 enum btrfs_reserve_flush_enum flush)
1431 {
1432 	int ret;
1433 
1434 	switch (flush) {
1435 	case BTRFS_RESERVE_FLUSH_DATA:
1436 	case BTRFS_RESERVE_FLUSH_ALL:
1437 	case BTRFS_RESERVE_FLUSH_ALL_STEAL:
1438 		wait_reserve_ticket(fs_info, space_info, ticket);
1439 		break;
1440 	case BTRFS_RESERVE_FLUSH_LIMIT:
1441 		priority_reclaim_metadata_space(fs_info, space_info, ticket,
1442 						priority_flush_states,
1443 						ARRAY_SIZE(priority_flush_states));
1444 		break;
1445 	case BTRFS_RESERVE_FLUSH_EVICT:
1446 		priority_reclaim_metadata_space(fs_info, space_info, ticket,
1447 						evict_flush_states,
1448 						ARRAY_SIZE(evict_flush_states));
1449 		break;
1450 	case BTRFS_RESERVE_FLUSH_FREE_SPACE_INODE:
1451 		priority_reclaim_data_space(fs_info, space_info, ticket);
1452 		break;
1453 	default:
1454 		ASSERT(0);
1455 		break;
1456 	}
1457 
1458 	ret = ticket->error;
1459 	ASSERT(list_empty(&ticket->list));
1460 	/*
1461 	 * Check that we can't have an error set if the reservation succeeded,
1462 	 * as that would confuse tasks and lead them to error out without
1463 	 * releasing reserved space (if an error happens the expectation is that
1464 	 * space wasn't reserved at all).
1465 	 */
1466 	ASSERT(!(ticket->bytes == 0 && ticket->error));
1467 	trace_btrfs_reserve_ticket(fs_info, space_info->flags, orig_bytes,
1468 				   start_ns, flush, ticket->error);
1469 	return ret;
1470 }
1471 
1472 /*
1473  * This returns true if this flush state will go through the ordinary flushing
1474  * code.
1475  */
1476 static inline bool is_normal_flushing(enum btrfs_reserve_flush_enum flush)
1477 {
1478 	return	(flush == BTRFS_RESERVE_FLUSH_ALL) ||
1479 		(flush == BTRFS_RESERVE_FLUSH_ALL_STEAL);
1480 }
1481 
1482 static inline void maybe_clamp_preempt(struct btrfs_fs_info *fs_info,
1483 				       struct btrfs_space_info *space_info)
1484 {
1485 	u64 ordered = percpu_counter_sum_positive(&fs_info->ordered_bytes);
1486 	u64 delalloc = percpu_counter_sum_positive(&fs_info->delalloc_bytes);
1487 
1488 	/*
1489 	 * If we're heavy on ordered operations then clamping won't help us.  We
1490 	 * need to clamp specifically to keep up with dirty'ing buffered
1491 	 * writers, because there's not a 1:1 correlation of writing delalloc
1492 	 * and freeing space, like there is with flushing delayed refs or
1493 	 * delayed nodes.  If we're already more ordered than delalloc then
1494 	 * we're keeping up, otherwise we aren't and should probably clamp.
1495 	 */
1496 	if (ordered < delalloc)
1497 		space_info->clamp = min(space_info->clamp + 1, 8);
1498 }
1499 
1500 static inline bool can_steal(enum btrfs_reserve_flush_enum flush)
1501 {
1502 	return (flush == BTRFS_RESERVE_FLUSH_ALL_STEAL ||
1503 		flush == BTRFS_RESERVE_FLUSH_EVICT);
1504 }
1505 
1506 /**
1507  * Try to reserve bytes from the block_rsv's space
1508  *
1509  * @fs_info:    the filesystem
1510  * @space_info: space info we want to allocate from
1511  * @orig_bytes: number of bytes we want
1512  * @flush:      whether or not we can flush to make our reservation
1513  *
1514  * This will reserve orig_bytes number of bytes from the space info associated
1515  * with the block_rsv.  If there is not enough space it will make an attempt to
1516  * flush out space to make room.  It will do this by flushing delalloc if
1517  * possible or committing the transaction.  If flush is 0 then no attempts to
1518  * regain reservations will be made and this will fail if there is not enough
1519  * space already.
1520  */
1521 static int __reserve_bytes(struct btrfs_fs_info *fs_info,
1522 			   struct btrfs_space_info *space_info, u64 orig_bytes,
1523 			   enum btrfs_reserve_flush_enum flush)
1524 {
1525 	struct work_struct *async_work;
1526 	struct reserve_ticket ticket;
1527 	u64 start_ns = 0;
1528 	u64 used;
1529 	int ret = 0;
1530 	bool pending_tickets;
1531 
1532 	ASSERT(orig_bytes);
1533 	ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_ALL);
1534 
1535 	if (flush == BTRFS_RESERVE_FLUSH_DATA)
1536 		async_work = &fs_info->async_data_reclaim_work;
1537 	else
1538 		async_work = &fs_info->async_reclaim_work;
1539 
1540 	spin_lock(&space_info->lock);
1541 	ret = -ENOSPC;
1542 	used = btrfs_space_info_used(space_info, true);
1543 
1544 	/*
1545 	 * We don't want NO_FLUSH allocations to jump everybody, they can
1546 	 * generally handle ENOSPC in a different way, so treat them the same as
1547 	 * normal flushers when it comes to skipping pending tickets.
1548 	 */
1549 	if (is_normal_flushing(flush) || (flush == BTRFS_RESERVE_NO_FLUSH))
1550 		pending_tickets = !list_empty(&space_info->tickets) ||
1551 			!list_empty(&space_info->priority_tickets);
1552 	else
1553 		pending_tickets = !list_empty(&space_info->priority_tickets);
1554 
1555 	/*
1556 	 * Carry on if we have enough space (short-circuit) OR call
1557 	 * can_overcommit() to ensure we can overcommit to continue.
1558 	 */
1559 	if (!pending_tickets &&
1560 	    ((used + orig_bytes <= space_info->total_bytes) ||
1561 	     btrfs_can_overcommit(fs_info, space_info, orig_bytes, flush))) {
1562 		btrfs_space_info_update_bytes_may_use(fs_info, space_info,
1563 						      orig_bytes);
1564 		ret = 0;
1565 	}
1566 
1567 	/*
1568 	 * If we couldn't make a reservation then setup our reservation ticket
1569 	 * and kick the async worker if it's not already running.
1570 	 *
1571 	 * If we are a priority flusher then we just need to add our ticket to
1572 	 * the list and we will do our own flushing further down.
1573 	 */
1574 	if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
1575 		ticket.bytes = orig_bytes;
1576 		ticket.error = 0;
1577 		space_info->reclaim_size += ticket.bytes;
1578 		init_waitqueue_head(&ticket.wait);
1579 		ticket.steal = can_steal(flush);
1580 		if (trace_btrfs_reserve_ticket_enabled())
1581 			start_ns = ktime_get_ns();
1582 
1583 		if (flush == BTRFS_RESERVE_FLUSH_ALL ||
1584 		    flush == BTRFS_RESERVE_FLUSH_ALL_STEAL ||
1585 		    flush == BTRFS_RESERVE_FLUSH_DATA) {
1586 			list_add_tail(&ticket.list, &space_info->tickets);
1587 			if (!space_info->flush) {
1588 				/*
1589 				 * We were forced to add a reserve ticket, so
1590 				 * our preemptive flushing is unable to keep
1591 				 * up.  Clamp down on the threshold for the
1592 				 * preemptive flushing in order to keep up with
1593 				 * the workload.
1594 				 */
1595 				maybe_clamp_preempt(fs_info, space_info);
1596 
1597 				space_info->flush = 1;
1598 				trace_btrfs_trigger_flush(fs_info,
1599 							  space_info->flags,
1600 							  orig_bytes, flush,
1601 							  "enospc");
1602 				queue_work(system_unbound_wq, async_work);
1603 			}
1604 		} else {
1605 			list_add_tail(&ticket.list,
1606 				      &space_info->priority_tickets);
1607 		}
1608 	} else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
1609 		used += orig_bytes;
1610 		/*
1611 		 * We will do the space reservation dance during log replay,
1612 		 * which means we won't have fs_info->fs_root set, so don't do
1613 		 * the async reclaim as we will panic.
1614 		 */
1615 		if (!test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags) &&
1616 		    !work_busy(&fs_info->preempt_reclaim_work) &&
1617 		    need_preemptive_reclaim(fs_info, space_info)) {
1618 			trace_btrfs_trigger_flush(fs_info, space_info->flags,
1619 						  orig_bytes, flush, "preempt");
1620 			queue_work(system_unbound_wq,
1621 				   &fs_info->preempt_reclaim_work);
1622 		}
1623 	}
1624 	spin_unlock(&space_info->lock);
1625 	if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
1626 		return ret;
1627 
1628 	return handle_reserve_ticket(fs_info, space_info, &ticket, start_ns,
1629 				     orig_bytes, flush);
1630 }
1631 
1632 /**
1633  * Trye to reserve metadata bytes from the block_rsv's space
1634  *
1635  * @fs_info:    the filesystem
1636  * @block_rsv:  block_rsv we're allocating for
1637  * @orig_bytes: number of bytes we want
1638  * @flush:      whether or not we can flush to make our reservation
1639  *
1640  * This will reserve orig_bytes number of bytes from the space info associated
1641  * with the block_rsv.  If there is not enough space it will make an attempt to
1642  * flush out space to make room.  It will do this by flushing delalloc if
1643  * possible or committing the transaction.  If flush is 0 then no attempts to
1644  * regain reservations will be made and this will fail if there is not enough
1645  * space already.
1646  */
1647 int btrfs_reserve_metadata_bytes(struct btrfs_fs_info *fs_info,
1648 				 struct btrfs_block_rsv *block_rsv,
1649 				 u64 orig_bytes,
1650 				 enum btrfs_reserve_flush_enum flush)
1651 {
1652 	int ret;
1653 
1654 	ret = __reserve_bytes(fs_info, block_rsv->space_info, orig_bytes, flush);
1655 	if (ret == -ENOSPC) {
1656 		trace_btrfs_space_reservation(fs_info, "space_info:enospc",
1657 					      block_rsv->space_info->flags,
1658 					      orig_bytes, 1);
1659 
1660 		if (btrfs_test_opt(fs_info, ENOSPC_DEBUG))
1661 			btrfs_dump_space_info(fs_info, block_rsv->space_info,
1662 					      orig_bytes, 0);
1663 	}
1664 	return ret;
1665 }
1666 
1667 /**
1668  * Try to reserve data bytes for an allocation
1669  *
1670  * @fs_info: the filesystem
1671  * @bytes:   number of bytes we need
1672  * @flush:   how we are allowed to flush
1673  *
1674  * This will reserve bytes from the data space info.  If there is not enough
1675  * space then we will attempt to flush space as specified by flush.
1676  */
1677 int btrfs_reserve_data_bytes(struct btrfs_fs_info *fs_info, u64 bytes,
1678 			     enum btrfs_reserve_flush_enum flush)
1679 {
1680 	struct btrfs_space_info *data_sinfo = fs_info->data_sinfo;
1681 	int ret;
1682 
1683 	ASSERT(flush == BTRFS_RESERVE_FLUSH_DATA ||
1684 	       flush == BTRFS_RESERVE_FLUSH_FREE_SPACE_INODE);
1685 	ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_DATA);
1686 
1687 	ret = __reserve_bytes(fs_info, data_sinfo, bytes, flush);
1688 	if (ret == -ENOSPC) {
1689 		trace_btrfs_space_reservation(fs_info, "space_info:enospc",
1690 					      data_sinfo->flags, bytes, 1);
1691 		if (btrfs_test_opt(fs_info, ENOSPC_DEBUG))
1692 			btrfs_dump_space_info(fs_info, data_sinfo, bytes, 0);
1693 	}
1694 	return ret;
1695 }
1696