Debian Codegraph @

fs/btrfs/space-info.c

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