File Index
Files and directories
Sign in
FILE

space-info.c

File preview with syntax highlighting.

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