1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * mm/page-writeback.c 4 * 5 * Copyright (C) 2002, Linus Torvalds. 6 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra 7 * 8 * Contains functions related to writing back dirty pages at the 9 * address_space level. 10 * 11 * 10Apr2002 Andrew Morton 12 * Initial version 13 */ 14 15 #include <linux/kernel.h> 16 #include <linux/math64.h> 17 #include <linux/export.h> 18 #include <linux/spinlock.h> 19 #include <linux/fs.h> 20 #include <linux/mm.h> 21 #include <linux/swap.h> 22 #include <linux/slab.h> 23 #include <linux/pagemap.h> 24 #include <linux/writeback.h> 25 #include <linux/init.h> 26 #include <linux/backing-dev.h> 27 #include <linux/task_io_accounting_ops.h> 28 #include <linux/mpage.h> 29 #include <linux/rmap.h> 30 #include <linux/percpu.h> 31 #include <linux/smp.h> 32 #include <linux/sysctl.h> 33 #include <linux/cpu.h> 34 #include <linux/syscalls.h> 35 #include <linux/folio_batch.h> 36 #include <linux/timer.h> 37 #include <linux/sched/rt.h> 38 #include <linux/sched/signal.h> 39 #include <linux/mm_inline.h> 40 #include <linux/shmem_fs.h> 41 #include <trace/events/writeback.h> 42 43 #include "internal.h" 44 45 /* 46 * Sleep at most 200ms at a time in balance_dirty_pages(). 47 */ 48 #define MAX_PAUSE max(HZ/5, 1) 49 50 /* 51 * Try to keep balance_dirty_pages() call intervals higher than this many pages 52 * by raising pause time to max_pause when falls below it. 53 */ 54 #define DIRTY_POLL_THRESH (128 >> (PAGE_SHIFT - 10)) 55 56 /* 57 * Estimate write bandwidth or update dirty limit at 200ms intervals. 58 */ 59 #define BANDWIDTH_INTERVAL max(HZ/5, 1) 60 61 #define RATELIMIT_CALC_SHIFT 10 62 63 /* 64 * After a CPU has dirtied this many pages, balance_dirty_pages_ratelimited 65 * will look to see if it needs to force writeback or throttling. 66 */ 67 static long ratelimit_pages = 32; 68 69 /* The following parameters are exported via /proc/sys/vm */ 70 71 /* 72 * Start background writeback (via writeback threads) at this percentage 73 */ 74 static int dirty_background_ratio = 10; 75 76 /* 77 * dirty_background_bytes starts at 0 (disabled) so that it is a function of 78 * dirty_background_ratio * the amount of dirtyable memory 79 */ 80 static unsigned long dirty_background_bytes; 81 82 /* 83 * free highmem will not be subtracted from the total free memory 84 * for calculating free ratios if vm_highmem_is_dirtyable is true 85 */ 86 static int vm_highmem_is_dirtyable; 87 88 /* 89 * The generator of dirty data starts writeback at this percentage 90 */ 91 static int vm_dirty_ratio = 20; 92 93 /* 94 * vm_dirty_bytes starts at 0 (disabled) so that it is a function of 95 * vm_dirty_ratio * the amount of dirtyable memory 96 */ 97 static unsigned long vm_dirty_bytes; 98 99 /* 100 * The interval between `kupdate'-style writebacks 101 */ 102 unsigned int dirty_writeback_interval = 5 * 100; /* centiseconds */ 103 104 EXPORT_SYMBOL_GPL(dirty_writeback_interval); 105 106 /* 107 * The longest time for which data is allowed to remain dirty 108 */ 109 unsigned int dirty_expire_interval = 30 * 100; /* centiseconds */ 110 111 /* End of sysctl-exported parameters */ 112 113 struct wb_domain global_wb_domain; 114 115 /* 116 * Length of period for aging writeout fractions of bdis. This is an 117 * arbitrarily chosen number. The longer the period, the slower fractions will 118 * reflect changes in current writeout rate. 119 */ 120 #define VM_COMPLETIONS_PERIOD_LEN (3*HZ) 121 122 #ifdef CONFIG_CGROUP_WRITEBACK 123 124 #define GDTC_INIT(__wb) .wb = (__wb), \ 125 .dom = &global_wb_domain, \ 126 .wb_completions = &(__wb)->completions 127 128 #define GDTC_INIT_NO_WB .dom = &global_wb_domain 129 130 #define MDTC_INIT(__wb, __gdtc) .wb = (__wb), \ 131 .dom = mem_cgroup_wb_domain(__wb), \ 132 .wb_completions = &(__wb)->memcg_completions, \ 133 .gdtc = __gdtc 134 135 static bool mdtc_valid(struct dirty_throttle_control *dtc) 136 { 137 return dtc->dom; 138 } 139 140 static struct wb_domain *dtc_dom(struct dirty_throttle_control *dtc) 141 { 142 return dtc->dom; 143 } 144 145 static struct dirty_throttle_control *mdtc_gdtc(struct dirty_throttle_control *mdtc) 146 { 147 return mdtc->gdtc; 148 } 149 150 static struct fprop_local_percpu *wb_memcg_completions(struct bdi_writeback *wb) 151 { 152 return &wb->memcg_completions; 153 } 154 155 static void wb_min_max_ratio(struct bdi_writeback *wb, 156 unsigned long *minp, unsigned long *maxp) 157 { 158 unsigned long this_bw = READ_ONCE(wb->avg_write_bandwidth); 159 unsigned long tot_bw = atomic_long_read(&wb->bdi->tot_write_bandwidth); 160 unsigned long long min = wb->bdi->min_ratio; 161 unsigned long long max = wb->bdi->max_ratio; 162 163 /* 164 * @wb may already be clean by the time control reaches here and 165 * the total may not include its bw. 166 */ 167 if (this_bw < tot_bw) { 168 if (min) { 169 min *= this_bw; 170 min = div64_ul(min, tot_bw); 171 } 172 if (max < 100 * BDI_RATIO_SCALE) { 173 max *= this_bw; 174 max = div64_ul(max, tot_bw); 175 } 176 } 177 178 *minp = min; 179 *maxp = max; 180 } 181 182 #else /* CONFIG_CGROUP_WRITEBACK */ 183 184 #define GDTC_INIT(__wb) .wb = (__wb), \ 185 .wb_completions = &(__wb)->completions 186 #define GDTC_INIT_NO_WB 187 #define MDTC_INIT(__wb, __gdtc) 188 189 static bool mdtc_valid(struct dirty_throttle_control *dtc) 190 { 191 return false; 192 } 193 194 static struct wb_domain *dtc_dom(struct dirty_throttle_control *dtc) 195 { 196 return &global_wb_domain; 197 } 198 199 static struct dirty_throttle_control *mdtc_gdtc(struct dirty_throttle_control *mdtc) 200 { 201 return NULL; 202 } 203 204 static struct fprop_local_percpu *wb_memcg_completions(struct bdi_writeback *wb) 205 { 206 return NULL; 207 } 208 209 static void wb_min_max_ratio(struct bdi_writeback *wb, 210 unsigned long *minp, unsigned long *maxp) 211 { 212 *minp = wb->bdi->min_ratio; 213 *maxp = wb->bdi->max_ratio; 214 } 215 216 #endif /* CONFIG_CGROUP_WRITEBACK */ 217 218 /* 219 * In a memory zone, there is a certain amount of pages we consider 220 * available for the page cache, which is essentially the number of 221 * free and reclaimable pages, minus some zone reserves to protect 222 * lowmem and the ability to uphold the zone's watermarks without 223 * requiring writeback. 224 * 225 * This number of dirtyable pages is the base value of which the 226 * user-configurable dirty ratio is the effective number of pages that 227 * are allowed to be actually dirtied. Per individual zone, or 228 * globally by using the sum of dirtyable pages over all zones. 229 * 230 * Because the user is allowed to specify the dirty limit globally as 231 * absolute number of bytes, calculating the per-zone dirty limit can 232 * require translating the configured limit into a percentage of 233 * global dirtyable memory first. 234 */ 235 236 /** 237 * node_dirtyable_memory - number of dirtyable pages in a node 238 * @pgdat: the node 239 * 240 * Return: the node's number of pages potentially available for dirty 241 * page cache. This is the base value for the per-node dirty limits. 242 */ 243 static unsigned long node_dirtyable_memory(struct pglist_data *pgdat) 244 { 245 unsigned long nr_pages = 0; 246 int z; 247 248 for (z = 0; z < MAX_NR_ZONES; z++) { 249 struct zone *zone = pgdat->node_zones + z; 250 251 if (!populated_zone(zone)) 252 continue; 253 254 nr_pages += zone_page_state(zone, NR_FREE_PAGES); 255 } 256 257 /* 258 * Pages reserved for the kernel should not be considered 259 * dirtyable, to prevent a situation where reclaim has to 260 * clean pages in order to balance the zones. 261 */ 262 nr_pages -= min(nr_pages, pgdat->totalreserve_pages); 263 264 nr_pages += node_page_state(pgdat, NR_INACTIVE_FILE); 265 nr_pages += node_page_state(pgdat, NR_ACTIVE_FILE); 266 267 return nr_pages; 268 } 269 270 static unsigned long highmem_dirtyable_memory(unsigned long total) 271 { 272 #ifdef CONFIG_HIGHMEM 273 int node; 274 unsigned long x = 0; 275 int i; 276 277 for_each_node_state(node, N_HIGH_MEMORY) { 278 for (i = ZONE_NORMAL + 1; i < MAX_NR_ZONES; i++) { 279 struct zone *z; 280 unsigned long nr_pages; 281 282 if (!is_highmem_idx(i)) 283 continue; 284 285 z = &NODE_DATA(node)->node_zones[i]; 286 if (!populated_zone(z)) 287 continue; 288 289 nr_pages = zone_page_state(z, NR_FREE_PAGES); 290 /* watch for underflows */ 291 nr_pages -= min(nr_pages, high_wmark_pages(z)); 292 nr_pages += zone_page_state(z, NR_ZONE_INACTIVE_FILE); 293 nr_pages += zone_page_state(z, NR_ZONE_ACTIVE_FILE); 294 x += nr_pages; 295 } 296 } 297 298 /* 299 * Make sure that the number of highmem pages is never larger 300 * than the number of the total dirtyable memory. This can only 301 * occur in very strange VM situations but we want to make sure 302 * that this does not occur. 303 */ 304 return min(x, total); 305 #else 306 return 0; 307 #endif 308 } 309 310 /** 311 * global_dirtyable_memory - number of globally dirtyable pages 312 * 313 * Return: the global number of pages potentially available for dirty 314 * page cache. This is the base value for the global dirty limits. 315 */ 316 static unsigned long global_dirtyable_memory(void) 317 { 318 unsigned long x; 319 320 x = global_zone_page_state(NR_FREE_PAGES); 321 /* 322 * Pages reserved for the kernel should not be considered 323 * dirtyable, to prevent a situation where reclaim has to 324 * clean pages in order to balance the zones. 325 */ 326 x -= min(x, totalreserve_pages); 327 328 x += global_node_page_state(NR_INACTIVE_FILE); 329 x += global_node_page_state(NR_ACTIVE_FILE); 330 331 if (!vm_highmem_is_dirtyable) 332 x -= highmem_dirtyable_memory(x); 333 334 return x + 1; /* Ensure that we never return 0 */ 335 } 336 337 /** 338 * domain_dirty_limits - calculate thresh and bg_thresh for a wb_domain 339 * @dtc: dirty_throttle_control of interest 340 * 341 * Calculate @dtc->thresh and ->bg_thresh considering 342 * vm_dirty_{bytes|ratio} and dirty_background_{bytes|ratio}. The caller 343 * must ensure that @dtc->avail is set before calling this function. The 344 * dirty limits will be lifted by 1/4 for real-time tasks. 345 */ 346 static void domain_dirty_limits(struct dirty_throttle_control *dtc) 347 { 348 const unsigned long available_memory = dtc->avail; 349 struct dirty_throttle_control *gdtc = mdtc_gdtc(dtc); 350 unsigned long bytes = vm_dirty_bytes; 351 unsigned long bg_bytes = dirty_background_bytes; 352 /* convert ratios to per-PAGE_SIZE for higher precision */ 353 unsigned long ratio = (vm_dirty_ratio * PAGE_SIZE) / 100; 354 unsigned long bg_ratio = (dirty_background_ratio * PAGE_SIZE) / 100; 355 unsigned long thresh; 356 unsigned long bg_thresh; 357 struct task_struct *tsk; 358 359 /* gdtc is !NULL iff @dtc is for memcg domain */ 360 if (gdtc) { 361 unsigned long global_avail = gdtc->avail; 362 363 /* 364 * The byte settings can't be applied directly to memcg 365 * domains. Convert them to ratios by scaling against 366 * globally available memory. As the ratios are in 367 * per-PAGE_SIZE, they can be obtained by dividing bytes by 368 * number of pages. 369 */ 370 if (bytes) 371 ratio = min(DIV_ROUND_UP(bytes, global_avail), 372 PAGE_SIZE); 373 if (bg_bytes) 374 bg_ratio = min(DIV_ROUND_UP(bg_bytes, global_avail), 375 PAGE_SIZE); 376 bytes = bg_bytes = 0; 377 } 378 379 if (bytes) 380 thresh = DIV_ROUND_UP(bytes, PAGE_SIZE); 381 else 382 thresh = (ratio * available_memory) / PAGE_SIZE; 383 384 if (bg_bytes) 385 bg_thresh = DIV_ROUND_UP(bg_bytes, PAGE_SIZE); 386 else 387 bg_thresh = (bg_ratio * available_memory) / PAGE_SIZE; 388 389 tsk = current; 390 if (rt_or_dl_task(tsk)) { 391 bg_thresh += bg_thresh / 4 + global_wb_domain.dirty_limit / 32; 392 thresh += thresh / 4 + global_wb_domain.dirty_limit / 32; 393 } 394 /* 395 * Dirty throttling logic assumes the limits in page units fit into 396 * 32-bits. This gives 16TB dirty limits max which is hopefully enough. 397 */ 398 if (thresh > UINT_MAX) 399 thresh = UINT_MAX; 400 /* This makes sure bg_thresh is within 32-bits as well */ 401 if (bg_thresh >= thresh) 402 bg_thresh = thresh / 2; 403 dtc->thresh = thresh; 404 dtc->bg_thresh = bg_thresh; 405 406 /* we should eventually report the domain in the TP */ 407 if (!gdtc) 408 trace_global_dirty_state(bg_thresh, thresh); 409 } 410 411 /** 412 * global_dirty_limits - background-writeback and dirty-throttling thresholds 413 * @pbackground: out parameter for bg_thresh 414 * @pdirty: out parameter for thresh 415 * 416 * Calculate bg_thresh and thresh for global_wb_domain. See 417 * domain_dirty_limits() for details. 418 */ 419 void global_dirty_limits(unsigned long *pbackground, unsigned long *pdirty) 420 { 421 struct dirty_throttle_control gdtc = { GDTC_INIT_NO_WB }; 422 423 gdtc.avail = global_dirtyable_memory(); 424 domain_dirty_limits(&gdtc); 425 426 *pbackground = gdtc.bg_thresh; 427 *pdirty = gdtc.thresh; 428 } 429 430 /** 431 * node_dirty_limit - maximum number of dirty pages allowed in a node 432 * @pgdat: the node 433 * 434 * Return: the maximum number of dirty pages allowed in a node, based 435 * on the node's dirtyable memory. 436 */ 437 static unsigned long node_dirty_limit(struct pglist_data *pgdat) 438 { 439 unsigned long node_memory = node_dirtyable_memory(pgdat); 440 struct task_struct *tsk = current; 441 unsigned long dirty; 442 443 if (vm_dirty_bytes) 444 dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE) * 445 node_memory / global_dirtyable_memory(); 446 else 447 dirty = vm_dirty_ratio * node_memory / 100; 448 449 if (rt_or_dl_task(tsk)) 450 dirty += dirty / 4; 451 452 /* 453 * Dirty throttling logic assumes the limits in page units fit into 454 * 32-bits. This gives 16TB dirty limits max which is hopefully enough. 455 */ 456 return min_t(unsigned long, dirty, UINT_MAX); 457 } 458 459 /** 460 * node_dirty_ok - tells whether a node is within its dirty limits 461 * @pgdat: the node to check 462 * 463 * Return: %true when the dirty pages in @pgdat are within the node's 464 * dirty limit, %false if the limit is exceeded. 465 */ 466 bool node_dirty_ok(struct pglist_data *pgdat) 467 { 468 unsigned long limit = node_dirty_limit(pgdat); 469 unsigned long nr_pages = 0; 470 471 nr_pages += node_page_state(pgdat, NR_FILE_DIRTY); 472 nr_pages += node_page_state(pgdat, NR_WRITEBACK); 473 474 return nr_pages <= limit; 475 } 476 477 #ifdef CONFIG_SYSCTL 478 static int dirty_background_ratio_handler(const struct ctl_table *table, int write, 479 void *buffer, size_t *lenp, loff_t *ppos) 480 { 481 int ret; 482 483 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); 484 if (ret == 0 && write) 485 dirty_background_bytes = 0; 486 return ret; 487 } 488 489 static int dirty_background_bytes_handler(const struct ctl_table *table, int write, 490 void *buffer, size_t *lenp, loff_t *ppos) 491 { 492 int ret; 493 unsigned long old_bytes = dirty_background_bytes; 494 495 ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos); 496 if (ret == 0 && write) { 497 if (DIV_ROUND_UP(dirty_background_bytes, PAGE_SIZE) > 498 UINT_MAX) { 499 dirty_background_bytes = old_bytes; 500 return -ERANGE; 501 } 502 dirty_background_ratio = 0; 503 } 504 return ret; 505 } 506 507 static int dirty_ratio_handler(const struct ctl_table *table, int write, void *buffer, 508 size_t *lenp, loff_t *ppos) 509 { 510 int old_ratio = vm_dirty_ratio; 511 int ret; 512 513 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); 514 if (ret == 0 && write && vm_dirty_ratio != old_ratio) { 515 vm_dirty_bytes = 0; 516 writeback_set_ratelimit(); 517 } 518 return ret; 519 } 520 521 static int dirty_bytes_handler(const struct ctl_table *table, int write, 522 void *buffer, size_t *lenp, loff_t *ppos) 523 { 524 unsigned long old_bytes = vm_dirty_bytes; 525 int ret; 526 527 ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos); 528 if (ret == 0 && write && vm_dirty_bytes != old_bytes) { 529 if (DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE) > UINT_MAX) { 530 vm_dirty_bytes = old_bytes; 531 return -ERANGE; 532 } 533 writeback_set_ratelimit(); 534 vm_dirty_ratio = 0; 535 } 536 return ret; 537 } 538 #endif 539 540 static unsigned long wp_next_time(unsigned long cur_time) 541 { 542 cur_time += VM_COMPLETIONS_PERIOD_LEN; 543 /* 0 has a special meaning... */ 544 if (!cur_time) 545 return 1; 546 return cur_time; 547 } 548 549 static void wb_domain_writeout_add(struct wb_domain *dom, 550 struct fprop_local_percpu *completions, 551 unsigned int max_prop_frac, long nr) 552 { 553 __fprop_add_percpu_max(&dom->completions, completions, 554 max_prop_frac, nr); 555 /* First event after period switching was turned off? */ 556 if (unlikely(!dom->period_time)) { 557 /* 558 * We can race with other wb_domain_writeout_add calls here but 559 * it does not cause any harm since the resulting time when 560 * timer will fire and what is in writeout_period_time will be 561 * roughly the same. 562 */ 563 dom->period_time = wp_next_time(jiffies); 564 mod_timer(&dom->period_timer, dom->period_time); 565 } 566 } 567 568 /* 569 * Increment @wb's writeout completion count and the global writeout 570 * completion count. Called from __folio_end_writeback(). 571 */ 572 static inline void __wb_writeout_add(struct bdi_writeback *wb, long nr) 573 { 574 struct wb_domain *cgdom; 575 576 wb_stat_mod(wb, WB_WRITTEN, nr); 577 wb_domain_writeout_add(&global_wb_domain, &wb->completions, 578 wb->bdi->max_prop_frac, nr); 579 580 cgdom = mem_cgroup_wb_domain(wb); 581 if (cgdom) 582 wb_domain_writeout_add(cgdom, wb_memcg_completions(wb), 583 wb->bdi->max_prop_frac, nr); 584 } 585 586 /* 587 * On idle system, we can be called long after we scheduled because we use 588 * deferred timers so count with missed periods. 589 */ 590 static void writeout_period(struct timer_list *t) 591 { 592 struct wb_domain *dom = timer_container_of(dom, t, period_timer); 593 int miss_periods = (jiffies - dom->period_time) / 594 VM_COMPLETIONS_PERIOD_LEN; 595 596 if (fprop_new_period(&dom->completions, miss_periods + 1)) { 597 dom->period_time = wp_next_time(dom->period_time + 598 miss_periods * VM_COMPLETIONS_PERIOD_LEN); 599 mod_timer(&dom->period_timer, dom->period_time); 600 } else { 601 /* 602 * Aging has zeroed all fractions. Stop wasting CPU on period 603 * updates. 604 */ 605 dom->period_time = 0; 606 } 607 } 608 609 int wb_domain_init(struct wb_domain *dom, gfp_t gfp) 610 { 611 memset(dom, 0, sizeof(*dom)); 612 613 spin_lock_init(&dom->lock); 614 615 timer_setup(&dom->period_timer, writeout_period, TIMER_DEFERRABLE); 616 617 dom->dirty_limit_tstamp = jiffies; 618 619 return fprop_global_init(&dom->completions, gfp); 620 } 621 622 #ifdef CONFIG_CGROUP_WRITEBACK 623 void wb_domain_exit(struct wb_domain *dom) 624 { 625 timer_delete_sync(&dom->period_timer); 626 fprop_global_destroy(&dom->completions); 627 } 628 #endif 629 630 /* 631 * bdi_min_ratio keeps the sum of the minimum dirty shares of all 632 * registered backing devices, which, for obvious reasons, can not 633 * exceed 100%. 634 */ 635 static unsigned int bdi_min_ratio; 636 637 static int bdi_check_pages_limit(unsigned long pages) 638 { 639 unsigned long max_dirty_pages = global_dirtyable_memory(); 640 641 if (pages > max_dirty_pages) 642 return -EINVAL; 643 644 return 0; 645 } 646 647 static unsigned long bdi_ratio_from_pages(unsigned long pages) 648 { 649 unsigned long background_thresh; 650 unsigned long dirty_thresh; 651 unsigned long ratio; 652 653 global_dirty_limits(&background_thresh, &dirty_thresh); 654 if (!dirty_thresh) 655 return -EINVAL; 656 ratio = div64_u64(pages * 100ULL * BDI_RATIO_SCALE, dirty_thresh); 657 658 return ratio; 659 } 660 661 static u64 bdi_get_bytes(unsigned int ratio) 662 { 663 unsigned long background_thresh; 664 unsigned long dirty_thresh; 665 u64 bytes; 666 667 global_dirty_limits(&background_thresh, &dirty_thresh); 668 bytes = (dirty_thresh * PAGE_SIZE * ratio) / BDI_RATIO_SCALE / 100; 669 670 return bytes; 671 } 672 673 static int __bdi_set_min_ratio(struct backing_dev_info *bdi, unsigned int min_ratio) 674 { 675 unsigned int delta; 676 int ret = 0; 677 678 if (min_ratio > 100 * BDI_RATIO_SCALE) 679 return -EINVAL; 680 681 spin_lock_bh(&bdi_lock); 682 if (min_ratio > bdi->max_ratio) { 683 ret = -EINVAL; 684 } else { 685 if (min_ratio < bdi->min_ratio) { 686 delta = bdi->min_ratio - min_ratio; 687 bdi_min_ratio -= delta; 688 bdi->min_ratio = min_ratio; 689 } else { 690 delta = min_ratio - bdi->min_ratio; 691 if (bdi_min_ratio + delta < 100 * BDI_RATIO_SCALE) { 692 bdi_min_ratio += delta; 693 bdi->min_ratio = min_ratio; 694 } else { 695 ret = -EINVAL; 696 } 697 } 698 } 699 spin_unlock_bh(&bdi_lock); 700 701 return ret; 702 } 703 704 static int __bdi_set_max_ratio(struct backing_dev_info *bdi, unsigned int max_ratio) 705 { 706 int ret = 0; 707 708 if (max_ratio > 100 * BDI_RATIO_SCALE) 709 return -EINVAL; 710 711 spin_lock_bh(&bdi_lock); 712 if (bdi->min_ratio > max_ratio) { 713 ret = -EINVAL; 714 } else { 715 bdi->max_ratio = max_ratio; 716 bdi->max_prop_frac = (FPROP_FRAC_BASE * max_ratio) / 717 (100 * BDI_RATIO_SCALE); 718 } 719 spin_unlock_bh(&bdi_lock); 720 721 return ret; 722 } 723 724 int bdi_set_min_ratio_no_scale(struct backing_dev_info *bdi, unsigned int min_ratio) 725 { 726 return __bdi_set_min_ratio(bdi, min_ratio); 727 } 728 729 int bdi_set_max_ratio_no_scale(struct backing_dev_info *bdi, unsigned int max_ratio) 730 { 731 return __bdi_set_max_ratio(bdi, max_ratio); 732 } 733 734 int bdi_set_min_ratio(struct backing_dev_info *bdi, unsigned int min_ratio) 735 { 736 return __bdi_set_min_ratio(bdi, min_ratio * BDI_RATIO_SCALE); 737 } 738 739 int bdi_set_max_ratio(struct backing_dev_info *bdi, unsigned int max_ratio) 740 { 741 return __bdi_set_max_ratio(bdi, max_ratio * BDI_RATIO_SCALE); 742 } 743 EXPORT_SYMBOL(bdi_set_max_ratio); 744 745 u64 bdi_get_min_bytes(struct backing_dev_info *bdi) 746 { 747 return bdi_get_bytes(bdi->min_ratio); 748 } 749 750 int bdi_set_min_bytes(struct backing_dev_info *bdi, u64 min_bytes) 751 { 752 int ret; 753 unsigned long pages = min_bytes >> PAGE_SHIFT; 754 long min_ratio; 755 756 ret = bdi_check_pages_limit(pages); 757 if (ret) 758 return ret; 759 760 min_ratio = bdi_ratio_from_pages(pages); 761 if (min_ratio < 0) 762 return min_ratio; 763 return __bdi_set_min_ratio(bdi, min_ratio); 764 } 765 766 u64 bdi_get_max_bytes(struct backing_dev_info *bdi) 767 { 768 return bdi_get_bytes(bdi->max_ratio); 769 } 770 771 int bdi_set_max_bytes(struct backing_dev_info *bdi, u64 max_bytes) 772 { 773 int ret; 774 unsigned long pages = max_bytes >> PAGE_SHIFT; 775 long max_ratio; 776 777 ret = bdi_check_pages_limit(pages); 778 if (ret) 779 return ret; 780 781 max_ratio = bdi_ratio_from_pages(pages); 782 if (max_ratio < 0) 783 return max_ratio; 784 return __bdi_set_max_ratio(bdi, max_ratio); 785 } 786 787 int bdi_set_strict_limit(struct backing_dev_info *bdi, unsigned int strict_limit) 788 { 789 if (strict_limit > 1) 790 return -EINVAL; 791 792 spin_lock_bh(&bdi_lock); 793 if (strict_limit) 794 bdi->capabilities |= BDI_CAP_STRICTLIMIT; 795 else 796 bdi->capabilities &= ~BDI_CAP_STRICTLIMIT; 797 spin_unlock_bh(&bdi_lock); 798 799 return 0; 800 } 801 802 static unsigned long dirty_freerun_ceiling(unsigned long thresh, 803 unsigned long bg_thresh) 804 { 805 return (thresh + bg_thresh) / 2; 806 } 807 808 static unsigned long hard_dirty_limit(struct wb_domain *dom, 809 unsigned long thresh) 810 { 811 return max(thresh, dom->dirty_limit); 812 } 813 814 /* 815 * Memory which can be further allocated to a memcg domain is capped by 816 * system-wide clean memory excluding the amount being used in the domain. 817 */ 818 static void mdtc_calc_avail(struct dirty_throttle_control *mdtc, 819 unsigned long filepages, unsigned long headroom) 820 { 821 struct dirty_throttle_control *gdtc = mdtc_gdtc(mdtc); 822 unsigned long clean = filepages - min(filepages, mdtc->dirty); 823 unsigned long global_clean = gdtc->avail - min(gdtc->avail, gdtc->dirty); 824 unsigned long other_clean = global_clean - min(global_clean, clean); 825 826 mdtc->avail = filepages + min(headroom, other_clean); 827 } 828 829 static inline bool dtc_is_global(struct dirty_throttle_control *dtc) 830 { 831 return mdtc_gdtc(dtc) == NULL; 832 } 833 834 /* 835 * Dirty background will ignore pages being written as we're trying to 836 * decide whether to put more under writeback. 837 */ 838 static void domain_dirty_avail(struct dirty_throttle_control *dtc, 839 bool include_writeback) 840 { 841 if (dtc_is_global(dtc)) { 842 dtc->avail = global_dirtyable_memory(); 843 dtc->dirty = global_node_page_state(NR_FILE_DIRTY); 844 if (include_writeback) 845 dtc->dirty += global_node_page_state(NR_WRITEBACK); 846 } else { 847 unsigned long filepages = 0, headroom = 0, writeback = 0; 848 849 mem_cgroup_wb_stats(dtc->wb, &filepages, &headroom, &dtc->dirty, 850 &writeback); 851 if (include_writeback) 852 dtc->dirty += writeback; 853 mdtc_calc_avail(dtc, filepages, headroom); 854 } 855 } 856 857 /** 858 * __wb_calc_thresh - @wb's share of dirty threshold 859 * @dtc: dirty_throttle_context of interest 860 * @thresh: dirty throttling or dirty background threshold of wb_domain in @dtc 861 * 862 * Note that balance_dirty_pages() will only seriously take dirty throttling 863 * threshold as a hard limit when sleeping max_pause per page is not enough 864 * to keep the dirty pages under control. For example, when the device is 865 * completely stalled due to some error conditions, or when there are 1000 866 * dd tasks writing to a slow 10MB/s USB key. 867 * In the other normal situations, it acts more gently by throttling the tasks 868 * more (rather than completely block them) when the wb dirty pages go high. 869 * 870 * It allocates high/low dirty limits to fast/slow devices, in order to prevent 871 * - starving fast devices 872 * - piling up dirty pages (that will take long time to sync) on slow devices 873 * 874 * The wb's share of dirty limit will be adapting to its throughput and 875 * bounded by the bdi->min_ratio and/or bdi->max_ratio parameters, if set. 876 * 877 * Return: @wb's dirty limit in pages. For dirty throttling limit, the term 878 * "dirty" in the context of dirty balancing includes all PG_dirty and 879 * PG_writeback pages. 880 */ 881 static unsigned long __wb_calc_thresh(struct dirty_throttle_control *dtc, 882 unsigned long thresh) 883 { 884 struct wb_domain *dom = dtc_dom(dtc); 885 struct bdi_writeback *wb = dtc->wb; 886 u64 threshold = thresh; 887 u64 wb_thresh; 888 u64 wb_max_thresh; 889 unsigned long numerator, denominator; 890 unsigned long wb_min_ratio, wb_max_ratio; 891 892 /* 893 * Calculate this wb's share of the thresh ratio. 894 */ 895 fprop_fraction_percpu(&dom->completions, dtc->wb_completions, 896 &numerator, &denominator); 897 898 wb_thresh = div_u64(threshold * (100 * BDI_RATIO_SCALE - bdi_min_ratio), 899 100 * BDI_RATIO_SCALE); 900 wb_thresh *= numerator; 901 wb_thresh = div64_ul(wb_thresh, denominator); 902 903 wb_min_max_ratio(wb, &wb_min_ratio, &wb_max_ratio); 904 905 wb_thresh += div_u64(threshold * wb_min_ratio, 100 * BDI_RATIO_SCALE); 906 907 /* 908 * It's very possible that wb_thresh is close to 0 not because the 909 * device is slow, but that it has remained inactive for long time. 910 * Honour such devices a reasonable good (hopefully IO efficient) 911 * threshold, so that the occasional writes won't be blocked and active 912 * writes can rampup the threshold quickly. 913 */ 914 if (thresh > dtc->dirty) { 915 if (unlikely(wb->bdi->capabilities & BDI_CAP_STRICTLIMIT)) 916 wb_thresh = max(wb_thresh, (thresh - dtc->dirty) / 100); 917 else 918 wb_thresh = max(wb_thresh, (thresh - dtc->dirty) / 8); 919 } 920 921 wb_max_thresh = div_u64(threshold * wb_max_ratio, 100 * BDI_RATIO_SCALE); 922 if (wb_thresh > wb_max_thresh) 923 wb_thresh = wb_max_thresh; 924 925 return wb_thresh; 926 } 927 928 unsigned long wb_calc_thresh(struct bdi_writeback *wb, unsigned long thresh) 929 { 930 struct dirty_throttle_control gdtc = { GDTC_INIT(wb) }; 931 932 domain_dirty_avail(&gdtc, true); 933 return __wb_calc_thresh(&gdtc, thresh); 934 } 935 936 unsigned long cgwb_calc_thresh(struct bdi_writeback *wb) 937 { 938 struct dirty_throttle_control gdtc = { GDTC_INIT_NO_WB }; 939 struct dirty_throttle_control mdtc = { MDTC_INIT(wb, &gdtc) }; 940 941 domain_dirty_avail(&gdtc, true); 942 domain_dirty_avail(&mdtc, true); 943 domain_dirty_limits(&mdtc); 944 945 return __wb_calc_thresh(&mdtc, mdtc.thresh); 946 } 947 948 /* 949 * setpoint - dirty 3 950 * f(dirty) := 1.0 + (----------------) 951 * limit - setpoint 952 * 953 * it's a 3rd order polynomial that subjects to 954 * 955 * (1) f(freerun) = 2.0 => rampup dirty_ratelimit reasonably fast 956 * (2) f(setpoint) = 1.0 => the balance point 957 * (3) f(limit) = 0 => the hard limit 958 * (4) df/dx <= 0 => negative feedback control 959 * (5) the closer to setpoint, the smaller |df/dx| (and the reverse) 960 * => fast response on large errors; small oscillation near setpoint 961 */ 962 static long long pos_ratio_polynom(unsigned long setpoint, 963 unsigned long dirty, 964 unsigned long limit) 965 { 966 long long pos_ratio; 967 long x; 968 969 x = div64_s64(((s64)setpoint - (s64)dirty) << RATELIMIT_CALC_SHIFT, 970 (limit - setpoint) | 1); 971 pos_ratio = x; 972 pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT; 973 pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT; 974 pos_ratio += 1 << RATELIMIT_CALC_SHIFT; 975 976 return clamp(pos_ratio, 0LL, 2LL << RATELIMIT_CALC_SHIFT); 977 } 978 979 /* 980 * Dirty position control. 981 * 982 * (o) global/bdi setpoints 983 * 984 * We want the dirty pages be balanced around the global/wb setpoints. 985 * When the number of dirty pages is higher/lower than the setpoint, the 986 * dirty position control ratio (and hence task dirty ratelimit) will be 987 * decreased/increased to bring the dirty pages back to the setpoint. 988 * 989 * pos_ratio = 1 << RATELIMIT_CALC_SHIFT 990 * 991 * if (dirty < setpoint) scale up pos_ratio 992 * if (dirty > setpoint) scale down pos_ratio 993 * 994 * if (wb_dirty < wb_setpoint) scale up pos_ratio 995 * if (wb_dirty > wb_setpoint) scale down pos_ratio 996 * 997 * task_ratelimit = dirty_ratelimit * pos_ratio >> RATELIMIT_CALC_SHIFT 998 * 999 * (o) global control line 1000 * 1001 * ^ pos_ratio 1002 * | 1003 * | |<===== global dirty control scope ======>| 1004 * 2.0 * * * * * * * 1005 * | .* 1006 * | . * 1007 * | . * 1008 * | . * 1009 * | . * 1010 * | . * 1011 * 1.0 ................................* 1012 * | . . * 1013 * | . . * 1014 * | . . * 1015 * | . . * 1016 * | . . * 1017 * 0 +------------.------------------.----------------------*-------------> 1018 * freerun^ setpoint^ limit^ dirty pages 1019 * 1020 * (o) wb control line 1021 * 1022 * ^ pos_ratio 1023 * | 1024 * | * 1025 * | * 1026 * | * 1027 * | * 1028 * | * |<=========== span ============>| 1029 * 1.0 .......................* 1030 * | . * 1031 * | . * 1032 * | . * 1033 * | . * 1034 * | . * 1035 * | . * 1036 * | . * 1037 * | . * 1038 * | . * 1039 * | . * 1040 * | . * 1041 * 1/4 ...............................................* * * * * * * * * * * * 1042 * | . . 1043 * | . . 1044 * | . . 1045 * 0 +----------------------.-------------------------------.-------------> 1046 * wb_setpoint^ x_intercept^ 1047 * 1048 * The wb control line won't drop below pos_ratio=1/4, so that wb_dirty can 1049 * be smoothly throttled down to normal if it starts high in situations like 1050 * - start writing to a slow SD card and a fast disk at the same time. The SD 1051 * card's wb_dirty may rush to many times higher than wb_setpoint. 1052 * - the wb dirty thresh drops quickly due to change of JBOD workload 1053 */ 1054 static void wb_position_ratio(struct dirty_throttle_control *dtc) 1055 { 1056 struct bdi_writeback *wb = dtc->wb; 1057 unsigned long write_bw = READ_ONCE(wb->avg_write_bandwidth); 1058 unsigned long freerun = dirty_freerun_ceiling(dtc->thresh, dtc->bg_thresh); 1059 unsigned long limit = dtc->limit = hard_dirty_limit(dtc_dom(dtc), dtc->thresh); 1060 unsigned long wb_thresh = dtc->wb_thresh; 1061 unsigned long x_intercept; 1062 unsigned long setpoint; /* dirty pages' target balance point */ 1063 unsigned long wb_setpoint; 1064 unsigned long span; 1065 long long pos_ratio; /* for scaling up/down the rate limit */ 1066 long x; 1067 1068 dtc->pos_ratio = 0; 1069 1070 if (unlikely(dtc->dirty >= limit)) 1071 return; 1072 1073 /* 1074 * global setpoint 1075 * 1076 * See comment for pos_ratio_polynom(). 1077 */ 1078 setpoint = (freerun + limit) / 2; 1079 pos_ratio = pos_ratio_polynom(setpoint, dtc->dirty, limit); 1080 1081 /* 1082 * The strictlimit feature is a tool preventing mistrusted filesystems 1083 * from growing a large number of dirty pages before throttling. For 1084 * such filesystems balance_dirty_pages always checks wb counters 1085 * against wb limits. Even if global "nr_dirty" is under "freerun". 1086 * This is especially important for fuse which sets bdi->max_ratio to 1087 * 1% by default. 1088 * 1089 * Here, in wb_position_ratio(), we calculate pos_ratio based on 1090 * two values: wb_dirty and wb_thresh. Let's consider an example: 1091 * total amount of RAM is 16GB, bdi->max_ratio is equal to 1%, global 1092 * limits are set by default to 10% and 20% (background and throttle). 1093 * Then wb_thresh is 1% of 20% of 16GB. This amounts to ~8K pages. 1094 * wb_calc_thresh(wb, bg_thresh) is about ~4K pages. wb_setpoint is 1095 * about ~6K pages (as the average of background and throttle wb 1096 * limits). The 3rd order polynomial will provide positive feedback if 1097 * wb_dirty is under wb_setpoint and vice versa. 1098 * 1099 * Note, that we cannot use global counters in these calculations 1100 * because we want to throttle process writing to a strictlimit wb 1101 * much earlier than global "freerun" is reached (~23MB vs. ~2.3GB 1102 * in the example above). 1103 */ 1104 if (unlikely(wb->bdi->capabilities & BDI_CAP_STRICTLIMIT)) { 1105 long long wb_pos_ratio; 1106 1107 if (dtc->wb_dirty >= wb_thresh) 1108 return; 1109 1110 wb_setpoint = dirty_freerun_ceiling(wb_thresh, 1111 dtc->wb_bg_thresh); 1112 1113 if (wb_setpoint == 0 || wb_setpoint == wb_thresh) 1114 return; 1115 1116 wb_pos_ratio = pos_ratio_polynom(wb_setpoint, dtc->wb_dirty, 1117 wb_thresh); 1118 1119 /* 1120 * Typically, for strictlimit case, wb_setpoint << setpoint 1121 * and pos_ratio >> wb_pos_ratio. In the other words global 1122 * state ("dirty") is not limiting factor and we have to 1123 * make decision based on wb counters. But there is an 1124 * important case when global pos_ratio should get precedence: 1125 * global limits are exceeded (e.g. due to activities on other 1126 * wb's) while given strictlimit wb is below limit. 1127 * 1128 * "pos_ratio * wb_pos_ratio" would work for the case above, 1129 * but it would look too non-natural for the case of all 1130 * activity in the system coming from a single strictlimit wb 1131 * with bdi->max_ratio == 100%. 1132 * 1133 * Note that min() below somewhat changes the dynamics of the 1134 * control system. Normally, pos_ratio value can be well over 3 1135 * (when globally we are at freerun and wb is well below wb 1136 * setpoint). Now the maximum pos_ratio in the same situation 1137 * is 2. We might want to tweak this if we observe the control 1138 * system is too slow to adapt. 1139 */ 1140 dtc->pos_ratio = min(pos_ratio, wb_pos_ratio); 1141 return; 1142 } 1143 1144 /* 1145 * We have computed basic pos_ratio above based on global situation. If 1146 * the wb is over/under its share of dirty pages, we want to scale 1147 * pos_ratio further down/up. That is done by the following mechanism. 1148 */ 1149 1150 /* 1151 * wb setpoint 1152 * 1153 * f(wb_dirty) := 1.0 + k * (wb_dirty - wb_setpoint) 1154 * 1155 * x_intercept - wb_dirty 1156 * := -------------------------- 1157 * x_intercept - wb_setpoint 1158 * 1159 * The main wb control line is a linear function that subjects to 1160 * 1161 * (1) f(wb_setpoint) = 1.0 1162 * (2) k = - 1 / (8 * write_bw) (in single wb case) 1163 * or equally: x_intercept = wb_setpoint + 8 * write_bw 1164 * 1165 * For single wb case, the dirty pages are observed to fluctuate 1166 * regularly within range 1167 * [wb_setpoint - write_bw/2, wb_setpoint + write_bw/2] 1168 * for various filesystems, where (2) can yield in a reasonable 12.5% 1169 * fluctuation range for pos_ratio. 1170 * 1171 * For JBOD case, wb_thresh (not wb_dirty!) could fluctuate up to its 1172 * own size, so move the slope over accordingly and choose a slope that 1173 * yields 100% pos_ratio fluctuation on suddenly doubled wb_thresh. 1174 */ 1175 if (unlikely(wb_thresh > dtc->thresh)) 1176 wb_thresh = dtc->thresh; 1177 /* 1178 * scale global setpoint to wb's: 1179 * wb_setpoint = setpoint * wb_thresh / thresh 1180 */ 1181 x = div_u64((u64)wb_thresh << 16, dtc->thresh | 1); 1182 wb_setpoint = setpoint * (u64)x >> 16; 1183 /* 1184 * Use span=(8*write_bw) in single wb case as indicated by 1185 * (thresh - wb_thresh ~= 0) and transit to wb_thresh in JBOD case. 1186 * 1187 * wb_thresh thresh - wb_thresh 1188 * span = --------- * (8 * write_bw) + ------------------ * wb_thresh 1189 * thresh thresh 1190 */ 1191 span = (dtc->thresh - wb_thresh + 8 * write_bw) * (u64)x >> 16; 1192 x_intercept = wb_setpoint + span; 1193 1194 if (dtc->wb_dirty < x_intercept - span / 4) { 1195 pos_ratio = div64_u64(pos_ratio * (x_intercept - dtc->wb_dirty), 1196 (x_intercept - wb_setpoint) | 1); 1197 } else 1198 pos_ratio /= 4; 1199 1200 /* 1201 * wb reserve area, safeguard against dirty pool underrun and disk idle 1202 * It may push the desired control point of global dirty pages higher 1203 * than setpoint. 1204 */ 1205 x_intercept = wb_thresh / 2; 1206 if (dtc->wb_dirty < x_intercept) { 1207 if (dtc->wb_dirty > x_intercept / 8) 1208 pos_ratio = div_u64(pos_ratio * x_intercept, 1209 dtc->wb_dirty); 1210 else 1211 pos_ratio *= 8; 1212 } 1213 1214 dtc->pos_ratio = pos_ratio; 1215 } 1216 1217 static void wb_update_write_bandwidth(struct bdi_writeback *wb, 1218 unsigned long elapsed, 1219 unsigned long written) 1220 { 1221 const unsigned long period = roundup_pow_of_two(3 * HZ); 1222 unsigned long avg = wb->avg_write_bandwidth; 1223 unsigned long old = wb->write_bandwidth; 1224 u64 bw; 1225 1226 /* 1227 * bw = written * HZ / elapsed 1228 * 1229 * bw * elapsed + write_bandwidth * (period - elapsed) 1230 * write_bandwidth = --------------------------------------------------- 1231 * period 1232 * 1233 * @written may have decreased due to folio_redirty_for_writepage(). 1234 * Avoid underflowing @bw calculation. 1235 */ 1236 bw = written - min(written, wb->written_stamp); 1237 bw *= HZ; 1238 if (unlikely(elapsed > period)) { 1239 bw = div64_ul(bw, elapsed); 1240 avg = bw; 1241 goto out; 1242 } 1243 bw += (u64)wb->write_bandwidth * (period - elapsed); 1244 bw >>= ilog2(period); 1245 1246 /* 1247 * one more level of smoothing, for filtering out sudden spikes 1248 */ 1249 if (avg > old && old >= (unsigned long)bw) 1250 avg -= (avg - old) >> 3; 1251 1252 if (avg < old && old <= (unsigned long)bw) 1253 avg += (old - avg) >> 3; 1254 1255 out: 1256 /* keep avg > 0 to guarantee that tot > 0 if there are dirty wbs */ 1257 avg = max(avg, 1LU); 1258 if (wb_has_dirty_io(wb)) { 1259 long delta = avg - wb->avg_write_bandwidth; 1260 WARN_ON_ONCE(atomic_long_add_return(delta, 1261 &wb->bdi->tot_write_bandwidth) <= 0); 1262 } 1263 wb->write_bandwidth = bw; 1264 WRITE_ONCE(wb->avg_write_bandwidth, avg); 1265 } 1266 1267 static void update_dirty_limit(struct dirty_throttle_control *dtc) 1268 { 1269 struct wb_domain *dom = dtc_dom(dtc); 1270 unsigned long thresh = dtc->thresh; 1271 unsigned long limit = dom->dirty_limit; 1272 1273 /* 1274 * Follow up in one step. 1275 */ 1276 if (limit < thresh) { 1277 limit = thresh; 1278 goto update; 1279 } 1280 1281 /* 1282 * Follow down slowly. Use the higher one as the target, because thresh 1283 * may drop below dirty. This is exactly the reason to introduce 1284 * dom->dirty_limit which is guaranteed to lie above the dirty pages. 1285 */ 1286 thresh = max(thresh, dtc->dirty); 1287 if (limit > thresh) { 1288 limit -= (limit - thresh) >> 5; 1289 goto update; 1290 } 1291 return; 1292 update: 1293 dom->dirty_limit = limit; 1294 } 1295 1296 static void domain_update_dirty_limit(struct dirty_throttle_control *dtc, 1297 unsigned long now) 1298 { 1299 struct wb_domain *dom = dtc_dom(dtc); 1300 1301 /* 1302 * check locklessly first to optimize away locking for the most time 1303 */ 1304 if (time_before(now, dom->dirty_limit_tstamp + BANDWIDTH_INTERVAL)) 1305 return; 1306 1307 spin_lock(&dom->lock); 1308 if (time_after_eq(now, dom->dirty_limit_tstamp + BANDWIDTH_INTERVAL)) { 1309 update_dirty_limit(dtc); 1310 dom->dirty_limit_tstamp = now; 1311 } 1312 spin_unlock(&dom->lock); 1313 } 1314 1315 /* 1316 * Maintain wb->dirty_ratelimit, the base dirty throttle rate. 1317 * 1318 * Normal wb tasks will be curbed at or below it in long term. 1319 * Obviously it should be around (write_bw / N) when there are N dd tasks. 1320 */ 1321 static void wb_update_dirty_ratelimit(struct dirty_throttle_control *dtc, 1322 unsigned long dirtied, 1323 unsigned long elapsed) 1324 { 1325 struct bdi_writeback *wb = dtc->wb; 1326 unsigned long dirty = dtc->dirty; 1327 unsigned long freerun = dirty_freerun_ceiling(dtc->thresh, dtc->bg_thresh); 1328 unsigned long limit = hard_dirty_limit(dtc_dom(dtc), dtc->thresh); 1329 unsigned long setpoint = (freerun + limit) / 2; 1330 unsigned long write_bw = wb->avg_write_bandwidth; 1331 unsigned long dirty_ratelimit = wb->dirty_ratelimit; 1332 unsigned long dirty_rate; 1333 unsigned long task_ratelimit; 1334 unsigned long balanced_dirty_ratelimit; 1335 unsigned long step; 1336 unsigned long x; 1337 unsigned long shift; 1338 1339 /* 1340 * The dirty rate will match the writeout rate in long term, except 1341 * when dirty pages are truncated by userspace or re-dirtied by FS. 1342 */ 1343 dirty_rate = (dirtied - wb->dirtied_stamp) * HZ / elapsed; 1344 1345 /* 1346 * task_ratelimit reflects each dd's dirty rate for the past 200ms. 1347 */ 1348 task_ratelimit = (u64)dirty_ratelimit * 1349 dtc->pos_ratio >> RATELIMIT_CALC_SHIFT; 1350 task_ratelimit++; /* it helps rampup dirty_ratelimit from tiny values */ 1351 1352 /* 1353 * A linear estimation of the "balanced" throttle rate. The theory is, 1354 * if there are N dd tasks, each throttled at task_ratelimit, the wb's 1355 * dirty_rate will be measured to be (N * task_ratelimit). So the below 1356 * formula will yield the balanced rate limit (write_bw / N). 1357 * 1358 * Note that the expanded form is not a pure rate feedback: 1359 * rate_(i+1) = rate_(i) * (write_bw / dirty_rate) (1) 1360 * but also takes pos_ratio into account: 1361 * rate_(i+1) = rate_(i) * (write_bw / dirty_rate) * pos_ratio (2) 1362 * 1363 * (1) is not realistic because pos_ratio also takes part in balancing 1364 * the dirty rate. Consider the state 1365 * pos_ratio = 0.5 (3) 1366 * rate = 2 * (write_bw / N) (4) 1367 * If (1) is used, it will stuck in that state! Because each dd will 1368 * be throttled at 1369 * task_ratelimit = pos_ratio * rate = (write_bw / N) (5) 1370 * yielding 1371 * dirty_rate = N * task_ratelimit = write_bw (6) 1372 * put (6) into (1) we get 1373 * rate_(i+1) = rate_(i) (7) 1374 * 1375 * So we end up using (2) to always keep 1376 * rate_(i+1) ~= (write_bw / N) (8) 1377 * regardless of the value of pos_ratio. As long as (8) is satisfied, 1378 * pos_ratio is able to drive itself to 1.0, which is not only where 1379 * the dirty count meet the setpoint, but also where the slope of 1380 * pos_ratio is most flat and hence task_ratelimit is least fluctuated. 1381 */ 1382 balanced_dirty_ratelimit = div_u64((u64)task_ratelimit * write_bw, 1383 dirty_rate | 1); 1384 /* 1385 * balanced_dirty_ratelimit ~= (write_bw / N) <= write_bw 1386 */ 1387 if (unlikely(balanced_dirty_ratelimit > write_bw)) 1388 balanced_dirty_ratelimit = write_bw; 1389 1390 /* 1391 * We could safely do this and return immediately: 1392 * 1393 * wb->dirty_ratelimit = balanced_dirty_ratelimit; 1394 * 1395 * However to get a more stable dirty_ratelimit, the below elaborated 1396 * code makes use of task_ratelimit to filter out singular points and 1397 * limit the step size. 1398 * 1399 * The below code essentially only uses the relative value of 1400 * 1401 * task_ratelimit - dirty_ratelimit 1402 * = (pos_ratio - 1) * dirty_ratelimit 1403 * 1404 * which reflects the direction and size of dirty position error. 1405 */ 1406 1407 /* 1408 * dirty_ratelimit will follow balanced_dirty_ratelimit iff 1409 * task_ratelimit is on the same side of dirty_ratelimit, too. 1410 * For example, when 1411 * - dirty_ratelimit > balanced_dirty_ratelimit 1412 * - dirty_ratelimit > task_ratelimit (dirty pages are above setpoint) 1413 * lowering dirty_ratelimit will help meet both the position and rate 1414 * control targets. Otherwise, don't update dirty_ratelimit if it will 1415 * only help meet the rate target. After all, what the users ultimately 1416 * feel and care are stable dirty rate and small position error. 1417 * 1418 * |task_ratelimit - dirty_ratelimit| is used to limit the step size 1419 * and filter out the singular points of balanced_dirty_ratelimit. Which 1420 * keeps jumping around randomly and can even leap far away at times 1421 * due to the small 200ms estimation period of dirty_rate (we want to 1422 * keep that period small to reduce time lags). 1423 */ 1424 step = 0; 1425 1426 /* 1427 * For strictlimit case, calculations above were based on wb counters 1428 * and limits (starting from pos_ratio = wb_position_ratio() and up to 1429 * balanced_dirty_ratelimit = task_ratelimit * write_bw / dirty_rate). 1430 * Hence, to calculate "step" properly, we have to use wb_dirty as 1431 * "dirty" and wb_setpoint as "setpoint". 1432 */ 1433 if (unlikely(wb->bdi->capabilities & BDI_CAP_STRICTLIMIT)) { 1434 dirty = dtc->wb_dirty; 1435 setpoint = (dtc->wb_thresh + dtc->wb_bg_thresh) / 2; 1436 } 1437 1438 if (dirty < setpoint) { 1439 x = min3(wb->balanced_dirty_ratelimit, 1440 balanced_dirty_ratelimit, task_ratelimit); 1441 if (dirty_ratelimit < x) 1442 step = x - dirty_ratelimit; 1443 } else { 1444 x = max3(wb->balanced_dirty_ratelimit, 1445 balanced_dirty_ratelimit, task_ratelimit); 1446 if (dirty_ratelimit > x) 1447 step = dirty_ratelimit - x; 1448 } 1449 1450 /* 1451 * Don't pursue 100% rate matching. It's impossible since the balanced 1452 * rate itself is constantly fluctuating. So decrease the track speed 1453 * when it gets close to the target. Helps eliminate pointless tremors. 1454 */ 1455 shift = dirty_ratelimit / (2 * step + 1); 1456 if (shift < BITS_PER_LONG) 1457 step = DIV_ROUND_UP(step >> shift, 8); 1458 else 1459 step = 0; 1460 1461 if (dirty_ratelimit < balanced_dirty_ratelimit) 1462 dirty_ratelimit += step; 1463 else 1464 dirty_ratelimit -= step; 1465 1466 WRITE_ONCE(wb->dirty_ratelimit, max(dirty_ratelimit, 1UL)); 1467 wb->balanced_dirty_ratelimit = balanced_dirty_ratelimit; 1468 1469 trace_bdi_dirty_ratelimit(wb, dirty_rate, task_ratelimit); 1470 } 1471 1472 static void __wb_update_bandwidth(struct dirty_throttle_control *gdtc, 1473 struct dirty_throttle_control *mdtc, 1474 bool update_ratelimit) 1475 { 1476 struct bdi_writeback *wb = gdtc->wb; 1477 unsigned long now = jiffies; 1478 unsigned long elapsed; 1479 unsigned long dirtied; 1480 unsigned long written; 1481 1482 spin_lock(&wb->list_lock); 1483 1484 /* 1485 * Lockless checks for elapsed time are racy and delayed update after 1486 * IO completion doesn't do it at all (to make sure written pages are 1487 * accounted reasonably quickly). Make sure elapsed >= 1 to avoid 1488 * division errors. 1489 */ 1490 elapsed = max(now - wb->bw_time_stamp, 1UL); 1491 dirtied = percpu_counter_read(&wb->stat[WB_DIRTIED]); 1492 written = percpu_counter_read(&wb->stat[WB_WRITTEN]); 1493 1494 if (update_ratelimit) { 1495 domain_update_dirty_limit(gdtc, now); 1496 wb_update_dirty_ratelimit(gdtc, dirtied, elapsed); 1497 1498 /* 1499 * @mdtc is always NULL if !CGROUP_WRITEBACK but the 1500 * compiler has no way to figure that out. Help it. 1501 */ 1502 if (IS_ENABLED(CONFIG_CGROUP_WRITEBACK) && mdtc) { 1503 domain_update_dirty_limit(mdtc, now); 1504 wb_update_dirty_ratelimit(mdtc, dirtied, elapsed); 1505 } 1506 } 1507 wb_update_write_bandwidth(wb, elapsed, written); 1508 1509 wb->dirtied_stamp = dirtied; 1510 wb->written_stamp = written; 1511 WRITE_ONCE(wb->bw_time_stamp, now); 1512 spin_unlock(&wb->list_lock); 1513 } 1514 1515 void wb_update_bandwidth(struct bdi_writeback *wb) 1516 { 1517 struct dirty_throttle_control gdtc = { GDTC_INIT(wb) }; 1518 1519 __wb_update_bandwidth(&gdtc, NULL, false); 1520 } 1521 1522 /* Interval after which we consider wb idle and don't estimate bandwidth */ 1523 #define WB_BANDWIDTH_IDLE_JIF (HZ) 1524 1525 static void wb_bandwidth_estimate_start(struct bdi_writeback *wb) 1526 { 1527 unsigned long now = jiffies; 1528 unsigned long elapsed = now - READ_ONCE(wb->bw_time_stamp); 1529 1530 if (elapsed > WB_BANDWIDTH_IDLE_JIF && 1531 !atomic_read(&wb->writeback_inodes)) { 1532 spin_lock(&wb->list_lock); 1533 wb->dirtied_stamp = wb_stat(wb, WB_DIRTIED); 1534 wb->written_stamp = wb_stat(wb, WB_WRITTEN); 1535 WRITE_ONCE(wb->bw_time_stamp, now); 1536 spin_unlock(&wb->list_lock); 1537 } 1538 } 1539 1540 /* 1541 * After a task dirtied this many pages, balance_dirty_pages_ratelimited() 1542 * will look to see if it needs to start dirty throttling. 1543 * 1544 * If dirty_poll_interval is too low, big NUMA machines will call the expensive 1545 * global_zone_page_state() too often. So scale it near-sqrt to the safety margin 1546 * (the number of pages we may dirty without exceeding the dirty limits). 1547 */ 1548 static unsigned long dirty_poll_interval(unsigned long dirty, 1549 unsigned long thresh) 1550 { 1551 if (thresh > dirty) 1552 return 1UL << (ilog2(thresh - dirty) >> 1); 1553 1554 return 1; 1555 } 1556 1557 static unsigned long wb_max_pause(struct bdi_writeback *wb, 1558 unsigned long wb_dirty) 1559 { 1560 unsigned long bw = READ_ONCE(wb->avg_write_bandwidth); 1561 unsigned long t; 1562 1563 /* 1564 * Limit pause time for small memory systems. If sleeping for too long 1565 * time, a small pool of dirty/writeback pages may go empty and disk go 1566 * idle. 1567 * 1568 * 8 serves as the safety ratio. 1569 */ 1570 t = wb_dirty / (1 + bw / roundup_pow_of_two(1 + HZ / 8)); 1571 t++; 1572 1573 return min_t(unsigned long, t, MAX_PAUSE); 1574 } 1575 1576 static long wb_min_pause(struct bdi_writeback *wb, 1577 long max_pause, 1578 unsigned long task_ratelimit, 1579 unsigned long dirty_ratelimit, 1580 int *nr_dirtied_pause) 1581 { 1582 long hi = ilog2(READ_ONCE(wb->avg_write_bandwidth)); 1583 long lo = ilog2(READ_ONCE(wb->dirty_ratelimit)); 1584 long t; /* target pause */ 1585 long pause; /* estimated next pause */ 1586 int pages; /* target nr_dirtied_pause */ 1587 1588 /* target for 10ms pause on 1-dd case */ 1589 t = max(1, HZ / 100); 1590 1591 /* 1592 * Scale up pause time for concurrent dirtiers in order to reduce CPU 1593 * overheads. 1594 * 1595 * (N * 10ms) on 2^N concurrent tasks. 1596 */ 1597 if (hi > lo) 1598 t += (hi - lo) * (10 * HZ) / 1024; 1599 1600 /* 1601 * This is a bit convoluted. We try to base the next nr_dirtied_pause 1602 * on the much more stable dirty_ratelimit. However the next pause time 1603 * will be computed based on task_ratelimit and the two rate limits may 1604 * depart considerably at some time. Especially if task_ratelimit goes 1605 * below dirty_ratelimit/2 and the target pause is max_pause, the next 1606 * pause time will be max_pause*2 _trimmed down_ to max_pause. As a 1607 * result task_ratelimit won't be executed faithfully, which could 1608 * eventually bring down dirty_ratelimit. 1609 * 1610 * We apply two rules to fix it up: 1611 * 1) try to estimate the next pause time and if necessary, use a lower 1612 * nr_dirtied_pause so as not to exceed max_pause. When this happens, 1613 * nr_dirtied_pause will be "dancing" with task_ratelimit. 1614 * 2) limit the target pause time to max_pause/2, so that the normal 1615 * small fluctuations of task_ratelimit won't trigger rule (1) and 1616 * nr_dirtied_pause will remain as stable as dirty_ratelimit. 1617 */ 1618 t = min(t, 1 + max_pause / 2); 1619 pages = dirty_ratelimit * t / roundup_pow_of_two(HZ); 1620 1621 /* 1622 * Tiny nr_dirtied_pause is found to hurt I/O performance in the test 1623 * case fio-mmap-randwrite-64k, which does 16*{sync read, async write}. 1624 * When the 16 consecutive reads are often interrupted by some dirty 1625 * throttling pause during the async writes, cfq will go into idles 1626 * (deadline is fine). So push nr_dirtied_pause as high as possible 1627 * until reaches DIRTY_POLL_THRESH=32 pages. 1628 */ 1629 if (pages < DIRTY_POLL_THRESH) { 1630 t = max_pause; 1631 pages = dirty_ratelimit * t / roundup_pow_of_two(HZ); 1632 if (pages > DIRTY_POLL_THRESH) { 1633 pages = DIRTY_POLL_THRESH; 1634 t = HZ * DIRTY_POLL_THRESH / dirty_ratelimit; 1635 } 1636 } 1637 1638 pause = HZ * pages / (task_ratelimit + 1); 1639 if (pause > max_pause) { 1640 t = max_pause; 1641 pages = task_ratelimit * t / roundup_pow_of_two(HZ); 1642 } 1643 1644 *nr_dirtied_pause = pages; 1645 /* 1646 * The minimal pause time will normally be half the target pause time. 1647 */ 1648 return pages >= DIRTY_POLL_THRESH ? 1 + t / 2 : t; 1649 } 1650 1651 static inline void wb_dirty_limits(struct dirty_throttle_control *dtc) 1652 { 1653 struct bdi_writeback *wb = dtc->wb; 1654 unsigned long wb_reclaimable; 1655 1656 /* 1657 * wb_thresh is not treated as some limiting factor as 1658 * dirty_thresh, due to reasons 1659 * - in JBOD setup, wb_thresh can fluctuate a lot 1660 * - in a system with HDD and USB key, the USB key may somehow 1661 * go into state (wb_dirty >> wb_thresh) either because 1662 * wb_dirty starts high, or because wb_thresh drops low. 1663 * In this case we don't want to hard throttle the USB key 1664 * dirtiers for 100 seconds until wb_dirty drops under 1665 * wb_thresh. Instead the auxiliary wb control line in 1666 * wb_position_ratio() will let the dirtier task progress 1667 * at some rate <= (write_bw / 2) for bringing down wb_dirty. 1668 */ 1669 dtc->wb_thresh = __wb_calc_thresh(dtc, dtc->thresh); 1670 dtc->wb_bg_thresh = dtc->thresh ? 1671 div_u64((u64)dtc->wb_thresh * dtc->bg_thresh, dtc->thresh) : 0; 1672 1673 /* 1674 * In order to avoid the stacked BDI deadlock we need 1675 * to ensure we accurately count the 'dirty' pages when 1676 * the threshold is low. 1677 * 1678 * Otherwise it would be possible to get thresh+n pages 1679 * reported dirty, even though there are thresh-m pages 1680 * actually dirty; with m+n sitting in the percpu 1681 * deltas. 1682 */ 1683 if (dtc->wb_thresh < 2 * wb_stat_error()) { 1684 wb_reclaimable = wb_stat_sum(wb, WB_RECLAIMABLE); 1685 dtc->wb_dirty = wb_reclaimable + wb_stat_sum(wb, WB_WRITEBACK); 1686 } else { 1687 wb_reclaimable = wb_stat(wb, WB_RECLAIMABLE); 1688 dtc->wb_dirty = wb_reclaimable + wb_stat(wb, WB_WRITEBACK); 1689 } 1690 } 1691 1692 static unsigned long domain_poll_intv(struct dirty_throttle_control *dtc, 1693 bool strictlimit) 1694 { 1695 unsigned long dirty, thresh; 1696 1697 if (strictlimit) { 1698 dirty = dtc->wb_dirty; 1699 thresh = dtc->wb_thresh; 1700 } else { 1701 dirty = dtc->dirty; 1702 thresh = dtc->thresh; 1703 } 1704 1705 return dirty_poll_interval(dirty, thresh); 1706 } 1707 1708 /* 1709 * Throttle it only when the background writeback cannot catch-up. This avoids 1710 * (excessively) small writeouts when the wb limits are ramping up in case of 1711 * !strictlimit. 1712 * 1713 * In strictlimit case make decision based on the wb counters and limits. Small 1714 * writeouts when the wb limits are ramping up are the price we consciously pay 1715 * for strictlimit-ing. 1716 */ 1717 static void domain_dirty_freerun(struct dirty_throttle_control *dtc, 1718 bool strictlimit) 1719 { 1720 unsigned long dirty, thresh, bg_thresh; 1721 1722 if (unlikely(strictlimit)) { 1723 wb_dirty_limits(dtc); 1724 dirty = dtc->wb_dirty; 1725 thresh = dtc->wb_thresh; 1726 bg_thresh = dtc->wb_bg_thresh; 1727 } else { 1728 dirty = dtc->dirty; 1729 thresh = dtc->thresh; 1730 bg_thresh = dtc->bg_thresh; 1731 } 1732 dtc->freerun = dirty <= dirty_freerun_ceiling(thresh, bg_thresh); 1733 } 1734 1735 static void balance_domain_limits(struct dirty_throttle_control *dtc, 1736 bool strictlimit) 1737 { 1738 domain_dirty_avail(dtc, true); 1739 domain_dirty_limits(dtc); 1740 domain_dirty_freerun(dtc, strictlimit); 1741 } 1742 1743 static void wb_dirty_freerun(struct dirty_throttle_control *dtc, 1744 bool strictlimit) 1745 { 1746 dtc->freerun = false; 1747 1748 /* was already handled in domain_dirty_freerun */ 1749 if (strictlimit) 1750 return; 1751 1752 wb_dirty_limits(dtc); 1753 /* 1754 * LOCAL_THROTTLE tasks must not be throttled when below the per-wb 1755 * freerun ceiling. 1756 */ 1757 if (!(current->flags & PF_LOCAL_THROTTLE)) 1758 return; 1759 1760 dtc->freerun = dtc->wb_dirty < 1761 dirty_freerun_ceiling(dtc->wb_thresh, dtc->wb_bg_thresh); 1762 } 1763 1764 static inline void wb_dirty_exceeded(struct dirty_throttle_control *dtc, 1765 bool strictlimit) 1766 { 1767 dtc->dirty_exceeded = (dtc->wb_dirty > dtc->wb_thresh) && 1768 ((dtc->dirty > dtc->thresh) || strictlimit); 1769 } 1770 1771 /* 1772 * The limits fields dirty_exceeded and pos_ratio won't be updated if wb is 1773 * in freerun state. Please don't use these invalid fields in freerun case. 1774 */ 1775 static void balance_wb_limits(struct dirty_throttle_control *dtc, 1776 bool strictlimit) 1777 { 1778 wb_dirty_freerun(dtc, strictlimit); 1779 if (dtc->freerun) 1780 return; 1781 1782 wb_dirty_exceeded(dtc, strictlimit); 1783 wb_position_ratio(dtc); 1784 } 1785 1786 /* 1787 * balance_dirty_pages() must be called by processes which are generating dirty 1788 * data. It looks at the number of dirty pages in the machine and will force 1789 * the caller to wait once crossing the (background_thresh + dirty_thresh) / 2. 1790 * If we're over `background_thresh' then the writeback threads are woken to 1791 * perform some writeout. 1792 */ 1793 static int balance_dirty_pages(struct bdi_writeback *wb, 1794 unsigned long pages_dirtied, unsigned int flags) 1795 { 1796 struct dirty_throttle_control gdtc_stor = { GDTC_INIT(wb) }; 1797 struct dirty_throttle_control mdtc_stor = { MDTC_INIT(wb, &gdtc_stor) }; 1798 struct dirty_throttle_control * const gdtc = &gdtc_stor; 1799 struct dirty_throttle_control * const mdtc = mdtc_valid(&mdtc_stor) ? 1800 &mdtc_stor : NULL; 1801 struct dirty_throttle_control *sdtc; 1802 unsigned long nr_dirty; 1803 long period; 1804 long pause; 1805 long max_pause; 1806 long min_pause; 1807 int nr_dirtied_pause; 1808 unsigned long task_ratelimit; 1809 unsigned long dirty_ratelimit; 1810 struct backing_dev_info *bdi = wb->bdi; 1811 bool strictlimit = bdi->capabilities & BDI_CAP_STRICTLIMIT; 1812 unsigned long start_time = jiffies; 1813 int ret = 0; 1814 1815 for (;;) { 1816 unsigned long now = jiffies; 1817 1818 nr_dirty = global_node_page_state(NR_FILE_DIRTY); 1819 1820 balance_domain_limits(gdtc, strictlimit); 1821 if (mdtc) { 1822 /* 1823 * If @wb belongs to !root memcg, repeat the same 1824 * basic calculations for the memcg domain. 1825 */ 1826 balance_domain_limits(mdtc, strictlimit); 1827 } 1828 1829 if (!writeback_in_progress(wb) && 1830 (nr_dirty > gdtc->bg_thresh || 1831 (strictlimit && gdtc->wb_dirty > gdtc->wb_bg_thresh))) 1832 wb_start_background_writeback(wb); 1833 1834 /* 1835 * If memcg domain is in effect, @dirty should be under 1836 * both global and memcg freerun ceilings. 1837 */ 1838 if (gdtc->freerun && (!mdtc || mdtc->freerun)) { 1839 unsigned long intv; 1840 unsigned long m_intv; 1841 1842 free_running: 1843 intv = domain_poll_intv(gdtc, strictlimit); 1844 m_intv = ULONG_MAX; 1845 1846 current->dirty_paused_when = now; 1847 current->nr_dirtied = 0; 1848 if (mdtc) 1849 m_intv = domain_poll_intv(mdtc, strictlimit); 1850 current->nr_dirtied_pause = min(intv, m_intv); 1851 break; 1852 } 1853 1854 /* 1855 * Unconditionally start background writeback if it's not 1856 * already in progress. We need to do this because the global 1857 * dirty threshold check above (nr_dirty > gdtc->bg_thresh) 1858 * doesn't account for the memcg-based throttling case. memcg 1859 * uses its own dirty count and thresholds and can trigger 1860 * throttling even when global nr_dirty < gdtc->bg_thresh 1861 * 1862 * Writeback needs to be started else the writer stalls in the 1863 * throttle loop waiting for dirty pages to be written back 1864 * while no writeback is running. 1865 */ 1866 if (unlikely(!writeback_in_progress(wb))) 1867 wb_start_background_writeback(wb); 1868 1869 mem_cgroup_flush_foreign(wb); 1870 1871 /* 1872 * Calculate global domain's pos_ratio and select the 1873 * global dtc by default. 1874 */ 1875 balance_wb_limits(gdtc, strictlimit); 1876 if (gdtc->freerun) 1877 goto free_running; 1878 sdtc = gdtc; 1879 1880 if (mdtc) { 1881 /* 1882 * If memcg domain is in effect, calculate its 1883 * pos_ratio. @wb should satisfy constraints from 1884 * both global and memcg domains. Choose the one 1885 * w/ lower pos_ratio. 1886 */ 1887 balance_wb_limits(mdtc, strictlimit); 1888 if (mdtc->freerun) 1889 goto free_running; 1890 if (mdtc->pos_ratio < gdtc->pos_ratio) 1891 sdtc = mdtc; 1892 } 1893 1894 wb->dirty_exceeded = gdtc->dirty_exceeded || 1895 (mdtc && mdtc->dirty_exceeded); 1896 if (time_is_before_jiffies(READ_ONCE(wb->bw_time_stamp) + 1897 BANDWIDTH_INTERVAL)) 1898 __wb_update_bandwidth(gdtc, mdtc, true); 1899 1900 /* throttle according to the chosen dtc */ 1901 dirty_ratelimit = READ_ONCE(wb->dirty_ratelimit); 1902 task_ratelimit = ((u64)dirty_ratelimit * sdtc->pos_ratio) >> 1903 RATELIMIT_CALC_SHIFT; 1904 max_pause = wb_max_pause(wb, sdtc->wb_dirty); 1905 min_pause = wb_min_pause(wb, max_pause, 1906 task_ratelimit, dirty_ratelimit, 1907 &nr_dirtied_pause); 1908 1909 if (unlikely(task_ratelimit == 0)) { 1910 period = max_pause; 1911 pause = max_pause; 1912 goto pause; 1913 } 1914 period = HZ * pages_dirtied / task_ratelimit; 1915 pause = period; 1916 if (current->dirty_paused_when) 1917 pause -= now - current->dirty_paused_when; 1918 /* 1919 * For less than 1s think time (ext3/4 may block the dirtier 1920 * for up to 800ms from time to time on 1-HDD; so does xfs, 1921 * however at much less frequency), try to compensate it in 1922 * future periods by updating the virtual time; otherwise just 1923 * do a reset, as it may be a light dirtier. 1924 */ 1925 if (pause < min_pause) { 1926 trace_balance_dirty_pages(wb, 1927 sdtc, 1928 dirty_ratelimit, 1929 task_ratelimit, 1930 pages_dirtied, 1931 period, 1932 min(pause, 0L), 1933 start_time); 1934 if (pause < -HZ) { 1935 current->dirty_paused_when = now; 1936 current->nr_dirtied = 0; 1937 } else if (period) { 1938 current->dirty_paused_when += period; 1939 current->nr_dirtied = 0; 1940 } else if (current->nr_dirtied_pause <= pages_dirtied) 1941 current->nr_dirtied_pause += pages_dirtied; 1942 break; 1943 } 1944 if (unlikely(pause > max_pause)) { 1945 /* for occasional dropped task_ratelimit */ 1946 now += min(pause - max_pause, max_pause); 1947 pause = max_pause; 1948 } 1949 1950 pause: 1951 trace_balance_dirty_pages(wb, 1952 sdtc, 1953 dirty_ratelimit, 1954 task_ratelimit, 1955 pages_dirtied, 1956 period, 1957 pause, 1958 start_time); 1959 if (flags & BDP_ASYNC) { 1960 ret = -EAGAIN; 1961 break; 1962 } 1963 __set_current_state(TASK_KILLABLE); 1964 bdi->last_bdp_sleep = jiffies; 1965 io_schedule_timeout(pause); 1966 1967 current->dirty_paused_when = now + pause; 1968 current->nr_dirtied = 0; 1969 current->nr_dirtied_pause = nr_dirtied_pause; 1970 1971 /* 1972 * This is typically equal to (dirty < thresh) and can also 1973 * keep "1000+ dd on a slow USB stick" under control. 1974 */ 1975 if (task_ratelimit) 1976 break; 1977 1978 /* 1979 * In the case of an unresponsive NFS server and the NFS dirty 1980 * pages exceeds dirty_thresh, give the other good wb's a pipe 1981 * to go through, so that tasks on them still remain responsive. 1982 * 1983 * In theory 1 page is enough to keep the consumer-producer 1984 * pipe going: the flusher cleans 1 page => the task dirties 1 1985 * more page. However wb_dirty has accounting errors. So use 1986 * the larger and more IO friendly wb_stat_error. 1987 */ 1988 if (sdtc->wb_dirty <= wb_stat_error()) 1989 break; 1990 1991 if (fatal_signal_pending(current)) 1992 break; 1993 } 1994 return ret; 1995 } 1996 1997 static DEFINE_PER_CPU(int, bdp_ratelimits); 1998 1999 /* 2000 * Normal tasks are throttled by 2001 * loop { 2002 * dirty tsk->nr_dirtied_pause pages; 2003 * take a snap in balance_dirty_pages(); 2004 * } 2005 * However there is a worst case. If every task exit immediately when dirtied 2006 * (tsk->nr_dirtied_pause - 1) pages, balance_dirty_pages() will never be 2007 * called to throttle the page dirties. The solution is to save the not yet 2008 * throttled page dirties in dirty_throttle_leaks on task exit and charge them 2009 * randomly into the running tasks. This works well for the above worst case, 2010 * as the new task will pick up and accumulate the old task's leaked dirty 2011 * count and eventually get throttled. 2012 */ 2013 DEFINE_PER_CPU(int, dirty_throttle_leaks) = 0; 2014 2015 /** 2016 * balance_dirty_pages_ratelimited_flags - Balance dirty memory state. 2017 * @mapping: address_space which was dirtied. 2018 * @flags: BDP flags. 2019 * 2020 * Processes which are dirtying memory should call in here once for each page 2021 * which was newly dirtied. The function will periodically check the system's 2022 * dirty state and will initiate writeback if needed. 2023 * 2024 * See balance_dirty_pages_ratelimited() for details. 2025 * 2026 * Return: If @flags contains BDP_ASYNC, it may return -EAGAIN to 2027 * indicate that memory is out of balance and the caller must wait 2028 * for I/O to complete. Otherwise, it will return 0 to indicate 2029 * that either memory was already in balance, or it was able to sleep 2030 * until the amount of dirty memory returned to balance. 2031 */ 2032 int balance_dirty_pages_ratelimited_flags(struct address_space *mapping, 2033 unsigned int flags) 2034 { 2035 struct inode *inode = mapping->host; 2036 struct backing_dev_info *bdi = inode_to_bdi(inode); 2037 struct bdi_writeback *wb = NULL; 2038 int ratelimit; 2039 int ret = 0; 2040 int *p; 2041 2042 if (!(bdi->capabilities & BDI_CAP_WRITEBACK)) 2043 return ret; 2044 2045 if (inode_cgwb_enabled(inode)) 2046 wb = wb_get_create_current(bdi, GFP_KERNEL); 2047 if (!wb) 2048 wb = &bdi->wb; 2049 2050 ratelimit = current->nr_dirtied_pause; 2051 if (wb->dirty_exceeded) 2052 ratelimit = min(ratelimit, 32 >> (PAGE_SHIFT - 10)); 2053 2054 preempt_disable(); 2055 /* 2056 * This prevents one CPU to accumulate too many dirtied pages without 2057 * calling into balance_dirty_pages(), which can happen when there are 2058 * 1000+ tasks, all of them start dirtying pages at exactly the same 2059 * time, hence all honoured too large initial task->nr_dirtied_pause. 2060 */ 2061 p = this_cpu_ptr(&bdp_ratelimits); 2062 if (unlikely(current->nr_dirtied >= ratelimit)) 2063 *p = 0; 2064 else if (unlikely(*p >= ratelimit_pages)) { 2065 *p = 0; 2066 ratelimit = 0; 2067 } 2068 /* 2069 * Pick up the dirtied pages by the exited tasks. This avoids lots of 2070 * short-lived tasks (eg. gcc invocations in a kernel build) escaping 2071 * the dirty throttling and livelock other long-run dirtiers. 2072 */ 2073 p = this_cpu_ptr(&dirty_throttle_leaks); 2074 if (*p > 0 && current->nr_dirtied < ratelimit) { 2075 unsigned long nr_pages_dirtied; 2076 nr_pages_dirtied = min(*p, ratelimit - current->nr_dirtied); 2077 *p -= nr_pages_dirtied; 2078 current->nr_dirtied += nr_pages_dirtied; 2079 } 2080 preempt_enable(); 2081 2082 if (unlikely(current->nr_dirtied >= ratelimit)) 2083 ret = balance_dirty_pages(wb, current->nr_dirtied, flags); 2084 2085 wb_put(wb); 2086 return ret; 2087 } 2088 EXPORT_SYMBOL_GPL(balance_dirty_pages_ratelimited_flags); 2089 2090 /** 2091 * balance_dirty_pages_ratelimited - balance dirty memory state. 2092 * @mapping: address_space which was dirtied. 2093 * 2094 * Processes which are dirtying memory should call in here once for each page 2095 * which was newly dirtied. The function will periodically check the system's 2096 * dirty state and will initiate writeback if needed. 2097 * 2098 * Once we're over the dirty memory limit we decrease the ratelimiting 2099 * by a lot, to prevent individual processes from overshooting the limit 2100 * by (ratelimit_pages) each. 2101 */ 2102 void balance_dirty_pages_ratelimited(struct address_space *mapping) 2103 { 2104 balance_dirty_pages_ratelimited_flags(mapping, 0); 2105 } 2106 EXPORT_SYMBOL(balance_dirty_pages_ratelimited); 2107 2108 /* 2109 * Similar to wb_dirty_limits, wb_bg_dirty_limits also calculates dirty 2110 * and thresh, but it's for background writeback. 2111 */ 2112 static void wb_bg_dirty_limits(struct dirty_throttle_control *dtc) 2113 { 2114 struct bdi_writeback *wb = dtc->wb; 2115 2116 dtc->wb_bg_thresh = __wb_calc_thresh(dtc, dtc->bg_thresh); 2117 if (dtc->wb_bg_thresh < 2 * wb_stat_error()) 2118 dtc->wb_dirty = wb_stat_sum(wb, WB_RECLAIMABLE); 2119 else 2120 dtc->wb_dirty = wb_stat(wb, WB_RECLAIMABLE); 2121 } 2122 2123 static bool domain_over_bg_thresh(struct dirty_throttle_control *dtc) 2124 { 2125 domain_dirty_avail(dtc, false); 2126 domain_dirty_limits(dtc); 2127 if (dtc->dirty > dtc->bg_thresh) 2128 return true; 2129 2130 wb_bg_dirty_limits(dtc); 2131 if (dtc->wb_dirty > dtc->wb_bg_thresh) 2132 return true; 2133 2134 return false; 2135 } 2136 2137 /** 2138 * wb_over_bg_thresh - does @wb need to be written back? 2139 * @wb: bdi_writeback of interest 2140 * 2141 * Determines whether background writeback should keep writing @wb or it's 2142 * clean enough. 2143 * 2144 * Return: %true if writeback should continue. 2145 */ 2146 bool wb_over_bg_thresh(struct bdi_writeback *wb) 2147 { 2148 struct dirty_throttle_control gdtc = { GDTC_INIT(wb) }; 2149 struct dirty_throttle_control mdtc = { MDTC_INIT(wb, &gdtc) }; 2150 2151 if (domain_over_bg_thresh(&gdtc)) 2152 return true; 2153 2154 if (mdtc_valid(&mdtc)) 2155 return domain_over_bg_thresh(&mdtc); 2156 2157 return false; 2158 } 2159 2160 #ifdef CONFIG_SYSCTL 2161 /* 2162 * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs 2163 */ 2164 static int dirty_writeback_centisecs_handler(const struct ctl_table *table, int write, 2165 void *buffer, size_t *length, loff_t *ppos) 2166 { 2167 unsigned int old_interval = dirty_writeback_interval; 2168 int ret; 2169 2170 ret = proc_dointvec(table, write, buffer, length, ppos); 2171 2172 /* 2173 * Writing 0 to dirty_writeback_interval will disable periodic writeback 2174 * and a different non-zero value will wakeup the writeback threads. 2175 * wb_wakeup_delayed() would be more appropriate, but it's a pain to 2176 * iterate over all bdis and wbs. 2177 * The reason we do this is to make the change take effect immediately. 2178 */ 2179 if (!ret && write && dirty_writeback_interval && 2180 dirty_writeback_interval != old_interval) 2181 wakeup_flusher_threads(WB_REASON_PERIODIC); 2182 2183 return ret; 2184 } 2185 #endif 2186 2187 /* 2188 * If ratelimit_pages is too high then we can get into dirty-data overload 2189 * if a large number of processes all perform writes at the same time. 2190 * 2191 * Here we set ratelimit_pages to a level which ensures that when all CPUs are 2192 * dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory 2193 * thresholds. 2194 */ 2195 2196 void writeback_set_ratelimit(void) 2197 { 2198 struct wb_domain *dom = &global_wb_domain; 2199 unsigned long background_thresh; 2200 unsigned long dirty_thresh; 2201 2202 global_dirty_limits(&background_thresh, &dirty_thresh); 2203 dom->dirty_limit = dirty_thresh; 2204 ratelimit_pages = dirty_thresh / (num_online_cpus() * 32); 2205 if (ratelimit_pages < 16) 2206 ratelimit_pages = 16; 2207 } 2208 2209 static int page_writeback_cpu_online(unsigned int cpu) 2210 { 2211 writeback_set_ratelimit(); 2212 return 0; 2213 } 2214 2215 #ifdef CONFIG_SYSCTL 2216 2217 static int laptop_mode; 2218 static int laptop_mode_handler(const struct ctl_table *table, int write, 2219 void *buffer, size_t *lenp, loff_t *ppos) 2220 { 2221 int ret = proc_dointvec_jiffies(table, write, buffer, lenp, ppos); 2222 2223 if (!ret && write) 2224 pr_warn("%s: vm.laptop_mode is deprecated. Ignoring setting.\n", 2225 current->comm); 2226 2227 return ret; 2228 } 2229 2230 /* this is needed for the proc_doulongvec_minmax of vm_dirty_bytes */ 2231 static const unsigned long dirty_bytes_min = 2 * PAGE_SIZE; 2232 2233 static const struct ctl_table vm_page_writeback_sysctls[] = { 2234 { 2235 .procname = "dirty_background_ratio", 2236 .data = &dirty_background_ratio, 2237 .maxlen = sizeof(dirty_background_ratio), 2238 .mode = 0644, 2239 .proc_handler = dirty_background_ratio_handler, 2240 .extra1 = SYSCTL_ZERO, 2241 .extra2 = SYSCTL_ONE_HUNDRED, 2242 }, 2243 { 2244 .procname = "dirty_background_bytes", 2245 .data = &dirty_background_bytes, 2246 .maxlen = sizeof(dirty_background_bytes), 2247 .mode = 0644, 2248 .proc_handler = dirty_background_bytes_handler, 2249 .extra1 = SYSCTL_LONG_ONE, 2250 }, 2251 { 2252 .procname = "dirty_ratio", 2253 .data = &vm_dirty_ratio, 2254 .maxlen = sizeof(vm_dirty_ratio), 2255 .mode = 0644, 2256 .proc_handler = dirty_ratio_handler, 2257 .extra1 = SYSCTL_ZERO, 2258 .extra2 = SYSCTL_ONE_HUNDRED, 2259 }, 2260 { 2261 .procname = "dirty_bytes", 2262 .data = &vm_dirty_bytes, 2263 .maxlen = sizeof(vm_dirty_bytes), 2264 .mode = 0644, 2265 .proc_handler = dirty_bytes_handler, 2266 .extra1 = (void *)&dirty_bytes_min, 2267 }, 2268 { 2269 .procname = "dirty_writeback_centisecs", 2270 .data = &dirty_writeback_interval, 2271 .maxlen = sizeof(dirty_writeback_interval), 2272 .mode = 0644, 2273 .proc_handler = dirty_writeback_centisecs_handler, 2274 }, 2275 { 2276 .procname = "dirty_expire_centisecs", 2277 .data = &dirty_expire_interval, 2278 .maxlen = sizeof(dirty_expire_interval), 2279 .mode = 0644, 2280 .proc_handler = proc_dointvec_minmax, 2281 .extra1 = SYSCTL_ZERO, 2282 }, 2283 #ifdef CONFIG_HIGHMEM 2284 { 2285 .procname = "highmem_is_dirtyable", 2286 .data = &vm_highmem_is_dirtyable, 2287 .maxlen = sizeof(vm_highmem_is_dirtyable), 2288 .mode = 0644, 2289 .proc_handler = proc_dointvec_minmax, 2290 .extra1 = SYSCTL_ZERO, 2291 .extra2 = SYSCTL_ONE, 2292 }, 2293 #endif 2294 { 2295 .procname = "laptop_mode", 2296 .data = &laptop_mode, 2297 .maxlen = sizeof(laptop_mode), 2298 .mode = 0644, 2299 .proc_handler = laptop_mode_handler, 2300 }, 2301 }; 2302 #endif 2303 2304 /* 2305 * Called early on to tune the page writeback dirty limits. 2306 * 2307 * We used to scale dirty pages according to how total memory 2308 * related to pages that could be allocated for buffers. 2309 * 2310 * However, that was when we used "dirty_ratio" to scale with 2311 * all memory, and we don't do that any more. "dirty_ratio" 2312 * is now applied to total non-HIGHPAGE memory, and as such we can't 2313 * get into the old insane situation any more where we had 2314 * large amounts of dirty pages compared to a small amount of 2315 * non-HIGHMEM memory. 2316 * 2317 * But we might still want to scale the dirty_ratio by how 2318 * much memory the box has.. 2319 */ 2320 void __init page_writeback_init(void) 2321 { 2322 BUG_ON(wb_domain_init(&global_wb_domain, GFP_KERNEL)); 2323 2324 cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "mm/writeback:online", 2325 page_writeback_cpu_online, NULL); 2326 cpuhp_setup_state(CPUHP_MM_WRITEBACK_DEAD, "mm/writeback:dead", NULL, 2327 page_writeback_cpu_online); 2328 #ifdef CONFIG_SYSCTL 2329 register_sysctl_init("vm", vm_page_writeback_sysctls); 2330 #endif 2331 } 2332 2333 /** 2334 * tag_pages_for_writeback - tag pages to be written by writeback 2335 * @mapping: address space structure to write 2336 * @start: starting page index 2337 * @end: ending page index (inclusive) 2338 * 2339 * This function scans the page range from @start to @end (inclusive) and tags 2340 * all pages that have DIRTY tag set with a special TOWRITE tag. The caller 2341 * can then use the TOWRITE tag to identify pages eligible for writeback. 2342 * This mechanism is used to avoid livelocking of writeback by a process 2343 * steadily creating new dirty pages in the file (thus it is important for this 2344 * function to be quick so that it can tag pages faster than a dirtying process 2345 * can create them). 2346 */ 2347 void tag_pages_for_writeback(struct address_space *mapping, 2348 pgoff_t start, pgoff_t end) 2349 { 2350 XA_STATE(xas, &mapping->i_pages, start); 2351 unsigned int tagged = 0; 2352 void *page; 2353 2354 xas_lock_irq(&xas); 2355 xas_for_each_marked(&xas, page, end, PAGECACHE_TAG_DIRTY) { 2356 xas_set_mark(&xas, PAGECACHE_TAG_TOWRITE); 2357 if (++tagged % XA_CHECK_SCHED) 2358 continue; 2359 2360 xas_pause(&xas); 2361 xas_unlock_irq(&xas); 2362 cond_resched(); 2363 xas_lock_irq(&xas); 2364 } 2365 xas_unlock_irq(&xas); 2366 } 2367 EXPORT_SYMBOL(tag_pages_for_writeback); 2368 2369 static bool folio_prepare_writeback(struct address_space *mapping, 2370 struct writeback_control *wbc, struct folio *folio) 2371 { 2372 /* 2373 * Folio truncated or invalidated. We can freely skip it then, 2374 * even for data integrity operations: the folio has disappeared 2375 * concurrently, so there could be no real expectation of this 2376 * data integrity operation even if there is now a new, dirty 2377 * folio at the same pagecache index. 2378 */ 2379 if (unlikely(folio->mapping != mapping)) 2380 return false; 2381 2382 /* 2383 * Did somebody else write it for us? 2384 */ 2385 if (!folio_test_dirty(folio)) 2386 return false; 2387 2388 if (folio_test_writeback(folio)) { 2389 if (wbc->sync_mode == WB_SYNC_NONE) 2390 return false; 2391 folio_wait_writeback(folio); 2392 } 2393 BUG_ON(folio_test_writeback(folio)); 2394 2395 if (!folio_clear_dirty_for_io(folio)) 2396 return false; 2397 2398 return true; 2399 } 2400 2401 2402 static pgoff_t wbc_end(struct writeback_control *wbc) 2403 { 2404 if (wbc->range_cyclic) 2405 return -1; 2406 return wbc->range_end >> PAGE_SHIFT; 2407 } 2408 2409 static struct folio *writeback_get_folio(struct address_space *mapping, 2410 struct writeback_control *wbc) 2411 { 2412 struct folio *folio; 2413 2414 retry: 2415 folio = folio_batch_next(&wbc->fbatch); 2416 if (!folio) { 2417 folio_batch_release(&wbc->fbatch); 2418 cond_resched(); 2419 filemap_get_folios_tag(mapping, &wbc->index, wbc_end(wbc), 2420 wbc_to_tag(wbc), &wbc->fbatch); 2421 folio = folio_batch_next(&wbc->fbatch); 2422 if (!folio) 2423 return NULL; 2424 } 2425 2426 folio_lock(folio); 2427 if (unlikely(!folio_prepare_writeback(mapping, wbc, folio))) { 2428 folio_unlock(folio); 2429 goto retry; 2430 } 2431 2432 trace_wbc_writepage(wbc, inode_to_bdi(mapping->host)); 2433 return folio; 2434 } 2435 2436 /** 2437 * writeback_iter - iterate folio of a mapping for writeback 2438 * @mapping: address space structure to write 2439 * @wbc: writeback context 2440 * @folio: previously iterated folio (%NULL to start) 2441 * @error: in-out pointer for writeback errors (see below) 2442 * 2443 * This function returns the next folio for the writeback operation described by 2444 * @wbc on @mapping and should be called in a while loop in the ->writepages 2445 * implementation. 2446 * 2447 * To start the writeback operation, %NULL is passed in the @folio argument, and 2448 * for every subsequent iteration the folio returned previously should be passed 2449 * back in. 2450 * 2451 * If there was an error in the per-folio writeback inside the writeback_iter() 2452 * loop, @error should be set to the error value. 2453 * 2454 * Once the writeback described in @wbc has finished, this function will return 2455 * %NULL and if there was an error in any iteration restore it to @error. 2456 * 2457 * Note: callers should not manually break out of the loop using break or goto 2458 * but must keep calling writeback_iter() until it returns %NULL. 2459 * 2460 * Return: the folio to write or %NULL if the loop is done. 2461 */ 2462 struct folio *writeback_iter(struct address_space *mapping, 2463 struct writeback_control *wbc, struct folio *folio, int *error) 2464 { 2465 if (!folio) { 2466 folio_batch_init(&wbc->fbatch); 2467 wbc->saved_err = *error = 0; 2468 2469 /* 2470 * For range cyclic writeback we remember where we stopped so 2471 * that we can continue where we stopped. 2472 * 2473 * For non-cyclic writeback we always start at the beginning of 2474 * the passed in range. 2475 */ 2476 if (wbc->range_cyclic) 2477 wbc->index = mapping->writeback_index; 2478 else 2479 wbc->index = wbc->range_start >> PAGE_SHIFT; 2480 2481 /* 2482 * To avoid livelocks when other processes dirty new pages, we 2483 * first tag pages which should be written back and only then 2484 * start writing them. 2485 * 2486 * For data-integrity writeback we have to be careful so that we 2487 * do not miss some pages (e.g., because some other process has 2488 * cleared the TOWRITE tag we set). The rule we follow is that 2489 * TOWRITE tag can be cleared only by the process clearing the 2490 * DIRTY tag (and submitting the page for I/O). 2491 */ 2492 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages) 2493 tag_pages_for_writeback(mapping, wbc->index, 2494 wbc_end(wbc)); 2495 } else { 2496 wbc->nr_to_write -= folio_nr_pages(folio); 2497 2498 WARN_ON_ONCE(*error > 0); 2499 2500 /* 2501 * For integrity writeback we have to keep going until we have 2502 * written all the folios we tagged for writeback above, even if 2503 * we run past wbc->nr_to_write or encounter errors. 2504 * We stash away the first error we encounter in wbc->saved_err 2505 * so that it can be retrieved when we're done. This is because 2506 * the file system may still have state to clear for each folio. 2507 * 2508 * For background writeback we exit as soon as we run past 2509 * wbc->nr_to_write or encounter the first error. 2510 */ 2511 if (wbc->sync_mode == WB_SYNC_ALL) { 2512 if (*error && !wbc->saved_err) 2513 wbc->saved_err = *error; 2514 } else { 2515 if (*error || wbc->nr_to_write <= 0) 2516 goto done; 2517 } 2518 } 2519 2520 folio = writeback_get_folio(mapping, wbc); 2521 if (!folio) { 2522 /* 2523 * To avoid deadlocks between range_cyclic writeback and callers 2524 * that hold folios in writeback to aggregate I/O until 2525 * the writeback iteration finishes, we do not loop back to the 2526 * start of the file. Doing so causes a folio lock/folio 2527 * writeback access order inversion - we should only ever lock 2528 * multiple folios in ascending folio->index order, and looping 2529 * back to the start of the file violates that rule and causes 2530 * deadlocks. 2531 */ 2532 if (wbc->range_cyclic) 2533 mapping->writeback_index = 0; 2534 2535 /* 2536 * Return the first error we encountered (if there was any) to 2537 * the caller. 2538 */ 2539 *error = wbc->saved_err; 2540 } 2541 return folio; 2542 2543 done: 2544 if (wbc->range_cyclic) 2545 mapping->writeback_index = folio_next_index(folio); 2546 folio_batch_release(&wbc->fbatch); 2547 return NULL; 2548 } 2549 EXPORT_SYMBOL_GPL(writeback_iter); 2550 2551 int do_writepages(struct address_space *mapping, struct writeback_control *wbc) 2552 { 2553 int ret; 2554 struct bdi_writeback *wb; 2555 2556 if (wbc->nr_to_write <= 0) 2557 return 0; 2558 wb = inode_to_wb_wbc(mapping->host, wbc); 2559 wb_bandwidth_estimate_start(wb); 2560 while (1) { 2561 if (mapping->a_ops->writepages) 2562 ret = mapping->a_ops->writepages(mapping, wbc); 2563 else 2564 /* deal with chardevs and other special files */ 2565 ret = 0; 2566 if (ret != -ENOMEM || wbc->sync_mode != WB_SYNC_ALL) 2567 break; 2568 2569 /* 2570 * Lacking an allocation context or the locality or writeback 2571 * state of any of the inode's pages, throttle based on 2572 * writeback activity on the local node. It's as good a 2573 * guess as any. 2574 */ 2575 reclaim_throttle(NODE_DATA(numa_node_id()), 2576 VMSCAN_THROTTLE_WRITEBACK); 2577 } 2578 /* 2579 * Usually few pages are written by now from those we've just submitted 2580 * but if there's constant writeback being submitted, this makes sure 2581 * writeback bandwidth is updated once in a while. 2582 */ 2583 if (time_is_before_jiffies(READ_ONCE(wb->bw_time_stamp) + 2584 BANDWIDTH_INTERVAL)) 2585 wb_update_bandwidth(wb); 2586 return ret; 2587 } 2588 2589 /* 2590 * For address_spaces which do not use buffers nor write back. 2591 */ 2592 bool noop_dirty_folio(struct address_space *mapping, struct folio *folio) 2593 { 2594 if (!folio_test_dirty(folio)) 2595 return !folio_test_set_dirty(folio); 2596 return false; 2597 } 2598 EXPORT_SYMBOL(noop_dirty_folio); 2599 2600 /* 2601 * Helper function for set_page_dirty family. 2602 * 2603 * NOTE: This relies on being atomic wrt interrupts. 2604 */ 2605 static void folio_account_dirtied(struct folio *folio, 2606 struct address_space *mapping) 2607 { 2608 struct inode *inode = mapping->host; 2609 2610 trace_writeback_dirty_folio(folio, mapping); 2611 2612 if (mapping_can_writeback(mapping)) { 2613 struct bdi_writeback *wb; 2614 long nr = folio_nr_pages(folio); 2615 2616 inode_attach_wb(inode, folio); 2617 wb = inode_to_wb(inode); 2618 2619 lruvec_stat_mod_folio(folio, NR_FILE_DIRTY, nr); 2620 if (folio_test_dropbehind(folio)) 2621 wb_stat_mod(wb, WB_DONTCACHE_DIRTY, nr); 2622 __zone_stat_mod_folio(folio, NR_ZONE_WRITE_PENDING, nr); 2623 __node_stat_mod_folio(folio, NR_DIRTIED, nr); 2624 wb_stat_mod(wb, WB_RECLAIMABLE, nr); 2625 wb_stat_mod(wb, WB_DIRTIED, nr); 2626 task_io_account_write(nr * PAGE_SIZE); 2627 current->nr_dirtied += nr; 2628 __this_cpu_add(bdp_ratelimits, nr); 2629 2630 mem_cgroup_track_foreign_dirty(folio, wb); 2631 } 2632 } 2633 2634 /* 2635 * Helper function for deaccounting dirty page without writeback. 2636 * 2637 */ 2638 void folio_account_cleaned(struct folio *folio, struct bdi_writeback *wb) 2639 { 2640 long nr = folio_nr_pages(folio); 2641 2642 lruvec_stat_mod_folio(folio, NR_FILE_DIRTY, -nr); 2643 if (folio_test_dropbehind(folio)) 2644 wb_stat_mod(wb, WB_DONTCACHE_DIRTY, -nr); 2645 zone_stat_mod_folio(folio, NR_ZONE_WRITE_PENDING, -nr); 2646 wb_stat_mod(wb, WB_RECLAIMABLE, -nr); 2647 task_io_account_cancelled_write(nr * PAGE_SIZE); 2648 } 2649 2650 /* 2651 * Mark the folio dirty, and set it dirty in the page cache. 2652 * 2653 * If warn is true, then emit a warning if the folio is not uptodate and has 2654 * not been truncated. 2655 * 2656 * It is the caller's responsibility to prevent the folio from being truncated 2657 * while this function is in progress, although it may have been truncated 2658 * before this function is called. Most callers have the folio locked. 2659 * A few have the folio blocked from truncation through other means (e.g. 2660 * zap_vma() has it mapped and is holding the page table lock). 2661 * When called from mark_buffer_dirty(), the filesystem should hold a 2662 * reference to the buffer_head that is being marked dirty, which causes 2663 * try_to_free_buffers() to fail. 2664 */ 2665 void __folio_mark_dirty(struct folio *folio, struct address_space *mapping, 2666 int warn) 2667 { 2668 unsigned long flags; 2669 2670 /* 2671 * Shmem writeback relies on swap, and swap writeback is LRU based, 2672 * not using the dirty mark. 2673 */ 2674 VM_WARN_ON_ONCE(folio_test_swapcache(folio) || shmem_mapping(mapping)); 2675 2676 xa_lock_irqsave(&mapping->i_pages, flags); 2677 if (folio->mapping) { /* Race with truncate? */ 2678 WARN_ON_ONCE(warn && !folio_test_uptodate(folio)); 2679 folio_account_dirtied(folio, mapping); 2680 __xa_set_mark(&mapping->i_pages, folio->index, 2681 PAGECACHE_TAG_DIRTY); 2682 } 2683 xa_unlock_irqrestore(&mapping->i_pages, flags); 2684 } 2685 2686 /** 2687 * filemap_dirty_folio - Mark a folio dirty for filesystems which do not use buffer_heads. 2688 * @mapping: Address space this folio belongs to. 2689 * @folio: Folio to be marked as dirty. 2690 * 2691 * Filesystems which do not use buffer heads should call this function 2692 * from their dirty_folio address space operation. It ignores the 2693 * contents of folio_get_private(), so if the filesystem marks individual 2694 * blocks as dirty, the filesystem should handle that itself. 2695 * 2696 * This is also sometimes used by filesystems which use buffer_heads when 2697 * a single buffer is being dirtied: we want to set the folio dirty in 2698 * that case, but not all the buffers. This is a "bottom-up" dirtying, 2699 * whereas block_dirty_folio() is a "top-down" dirtying. 2700 * 2701 * The caller must ensure this doesn't race with truncation. Most will 2702 * simply hold the folio lock, but e.g. zap_pte_range() calls with the 2703 * folio mapped and the pte lock held, which also locks out truncation. 2704 */ 2705 bool filemap_dirty_folio(struct address_space *mapping, struct folio *folio) 2706 { 2707 if (folio_test_set_dirty(folio)) 2708 return false; 2709 2710 __folio_mark_dirty(folio, mapping, !folio_has_attached_private(folio)); 2711 2712 if (mapping->host) { 2713 /* !PageAnon && !swapper_space */ 2714 __mark_inode_dirty(mapping->host, I_DIRTY_PAGES); 2715 } 2716 return true; 2717 } 2718 EXPORT_SYMBOL(filemap_dirty_folio); 2719 2720 /** 2721 * folio_redirty_for_writepage - Decline to write a dirty folio. 2722 * @wbc: The writeback control. 2723 * @folio: The folio. 2724 * 2725 * When a writepage implementation decides that it doesn't want to write 2726 * @folio for some reason, it should call this function, unlock @folio and 2727 * return 0. 2728 * 2729 * Return: True if we redirtied the folio. False if someone else dirtied 2730 * it first. 2731 */ 2732 bool folio_redirty_for_writepage(struct writeback_control *wbc, 2733 struct folio *folio) 2734 { 2735 struct address_space *mapping = folio->mapping; 2736 long nr = folio_nr_pages(folio); 2737 bool ret; 2738 2739 wbc->pages_skipped += nr; 2740 ret = filemap_dirty_folio(mapping, folio); 2741 if (mapping && mapping_can_writeback(mapping)) { 2742 struct inode *inode = mapping->host; 2743 struct bdi_writeback *wb; 2744 struct wb_lock_cookie cookie = {}; 2745 2746 wb = unlocked_inode_to_wb_begin(inode, &cookie); 2747 current->nr_dirtied -= nr; 2748 node_stat_mod_folio(folio, NR_DIRTIED, -nr); 2749 wb_stat_mod(wb, WB_DIRTIED, -nr); 2750 unlocked_inode_to_wb_end(inode, &cookie); 2751 } 2752 return ret; 2753 } 2754 EXPORT_SYMBOL(folio_redirty_for_writepage); 2755 2756 /** 2757 * folio_mark_dirty - Mark a folio as being modified. 2758 * @folio: The folio. 2759 * 2760 * The folio may not be truncated while this function is running. 2761 * Holding the folio lock is sufficient to prevent truncation, but some 2762 * callers cannot acquire a sleeping lock. These callers instead hold 2763 * the page table lock for a page table which contains at least one page 2764 * in this folio. Truncation will block on the page table lock as it 2765 * unmaps pages before removing the folio from its mapping. 2766 * 2767 * .. DANGER:: 2768 * Do not use this on a folio obtained from a function like 2769 * get_user_pages_fast() without holding appropriate locks; you might want to 2770 * use set_page_dirty_lock() or folio_mark_dirty_lock() instead. 2771 * 2772 * Return: True if the folio was newly dirtied, false if it was already dirty. 2773 */ 2774 bool folio_mark_dirty(struct folio *folio) 2775 { 2776 struct address_space *mapping = folio_mapping(folio); 2777 2778 if (likely(mapping)) { 2779 /* 2780 * readahead/folio_deactivate could remain 2781 * PG_readahead/PG_reclaim due to race with folio_end_writeback 2782 * About readahead, if the folio is written, the flags would be 2783 * reset. So no problem. 2784 * About folio_deactivate, if the folio is redirtied, 2785 * the flag will be reset. So no problem. but if the 2786 * folio is used by readahead it will confuse readahead 2787 * and make it restart the size rampup process. But it's 2788 * a trivial problem. 2789 */ 2790 if (folio_test_reclaim(folio)) 2791 folio_clear_reclaim(folio); 2792 return mapping->a_ops->dirty_folio(mapping, folio); 2793 } 2794 2795 return noop_dirty_folio(mapping, folio); 2796 } 2797 EXPORT_SYMBOL(folio_mark_dirty); 2798 2799 /* 2800 * folio_mark_dirty() is racy if the caller has no reference against 2801 * folio->mapping->host, and if the folio is unlocked. This is because another 2802 * CPU could truncate the folio off the mapping and then free the mapping. 2803 * 2804 * Usually, the folio _is_ locked, or the caller is a user-space process which 2805 * holds a reference on the inode by having an open file. 2806 * 2807 * In other cases, the folio should be locked before running folio_mark_dirty(). 2808 */ 2809 bool folio_mark_dirty_lock(struct folio *folio) 2810 { 2811 bool ret; 2812 2813 folio_lock(folio); 2814 ret = folio_mark_dirty(folio); 2815 folio_unlock(folio); 2816 return ret; 2817 } 2818 EXPORT_SYMBOL(folio_mark_dirty_lock); 2819 2820 /* 2821 * This cancels just the dirty bit on the kernel page itself, it does NOT 2822 * actually remove dirty bits on any mmap's that may be around. It also 2823 * leaves the page tagged dirty, so any sync activity will still find it on 2824 * the dirty lists, and in particular, clear_page_dirty_for_io() will still 2825 * look at the dirty bits in the VM. 2826 * 2827 * Doing this should *normally* only ever be done when a page is truncated, 2828 * and is not actually mapped anywhere at all. However, fs/buffer.c does 2829 * this when it notices that somebody has cleaned out all the buffers on a 2830 * page without actually doing it through the VM. Can you say "ext3 is 2831 * horribly ugly"? Thought you could. 2832 */ 2833 void __folio_cancel_dirty(struct folio *folio) 2834 { 2835 struct address_space *mapping = folio_mapping(folio); 2836 2837 if (mapping_can_writeback(mapping)) { 2838 struct inode *inode = mapping->host; 2839 struct bdi_writeback *wb; 2840 struct wb_lock_cookie cookie = {}; 2841 2842 wb = unlocked_inode_to_wb_begin(inode, &cookie); 2843 2844 if (folio_test_clear_dirty(folio)) 2845 folio_account_cleaned(folio, wb); 2846 2847 unlocked_inode_to_wb_end(inode, &cookie); 2848 } else { 2849 folio_clear_dirty(folio); 2850 } 2851 } 2852 EXPORT_SYMBOL(__folio_cancel_dirty); 2853 2854 /* 2855 * Clear a folio's dirty flag, while caring for dirty memory accounting. 2856 * Returns true if the folio was previously dirty. 2857 * 2858 * This is for preparing to put the folio under writeout. We leave 2859 * the folio tagged as dirty in the xarray so that a concurrent 2860 * write-for-sync can discover it via a PAGECACHE_TAG_DIRTY walk. 2861 * The ->writepage implementation will run either folio_start_writeback() 2862 * or folio_mark_dirty(), at which stage we bring the folio's dirty flag 2863 * and xarray dirty tag back into sync. 2864 * 2865 * This incoherency between the folio's dirty flag and xarray tag is 2866 * unfortunate, but it only exists while the folio is locked. 2867 */ 2868 bool folio_clear_dirty_for_io(struct folio *folio) 2869 { 2870 struct address_space *mapping = folio_mapping(folio); 2871 bool ret = false; 2872 2873 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 2874 2875 if (mapping && mapping_can_writeback(mapping)) { 2876 struct inode *inode = mapping->host; 2877 struct bdi_writeback *wb; 2878 struct wb_lock_cookie cookie = {}; 2879 2880 /* 2881 * Yes, Virginia, this is indeed insane. 2882 * 2883 * We use this sequence to make sure that 2884 * (a) we account for dirty stats properly 2885 * (b) we tell the low-level filesystem to 2886 * mark the whole folio dirty if it was 2887 * dirty in a pagetable. Only to then 2888 * (c) clean the folio again and return 1 to 2889 * cause the writeback. 2890 * 2891 * This way we avoid all nasty races with the 2892 * dirty bit in multiple places and clearing 2893 * them concurrently from different threads. 2894 * 2895 * Note! Normally the "folio_mark_dirty(folio)" 2896 * has no effect on the actual dirty bit - since 2897 * that will already usually be set. But we 2898 * need the side effects, and it can help us 2899 * avoid races. 2900 * 2901 * We basically use the folio "master dirty bit" 2902 * as a serialization point for all the different 2903 * threads doing their things. 2904 */ 2905 if (folio_mkclean(folio)) 2906 folio_mark_dirty(folio); 2907 /* 2908 * We carefully synchronise fault handlers against 2909 * installing a dirty pte and marking the folio dirty 2910 * at this point. We do this by having them hold the 2911 * page lock while dirtying the folio, and folios are 2912 * always locked coming in here, so we get the desired 2913 * exclusion. 2914 */ 2915 wb = unlocked_inode_to_wb_begin(inode, &cookie); 2916 if (folio_test_clear_dirty(folio)) { 2917 long nr = folio_nr_pages(folio); 2918 lruvec_stat_mod_folio(folio, NR_FILE_DIRTY, -nr); 2919 if (folio_test_dropbehind(folio)) 2920 wb_stat_mod(wb, WB_DONTCACHE_DIRTY, -nr); 2921 zone_stat_mod_folio(folio, NR_ZONE_WRITE_PENDING, -nr); 2922 wb_stat_mod(wb, WB_RECLAIMABLE, -nr); 2923 ret = true; 2924 } 2925 unlocked_inode_to_wb_end(inode, &cookie); 2926 return ret; 2927 } 2928 return folio_test_clear_dirty(folio); 2929 } 2930 EXPORT_SYMBOL(folio_clear_dirty_for_io); 2931 2932 static void wb_inode_writeback_start(struct bdi_writeback *wb) 2933 { 2934 atomic_inc(&wb->writeback_inodes); 2935 } 2936 2937 static void wb_inode_writeback_end(struct bdi_writeback *wb) 2938 { 2939 unsigned long flags; 2940 atomic_dec(&wb->writeback_inodes); 2941 /* 2942 * Make sure estimate of writeback throughput gets updated after 2943 * writeback completed. We delay the update by BANDWIDTH_INTERVAL 2944 * (which is the interval other bandwidth updates use for batching) so 2945 * that if multiple inodes end writeback at a similar time, they get 2946 * batched into one bandwidth update. 2947 */ 2948 spin_lock_irqsave(&wb->work_lock, flags); 2949 if (test_bit(WB_registered, &wb->state)) 2950 queue_delayed_work(bdi_wq, &wb->bw_dwork, BANDWIDTH_INTERVAL); 2951 spin_unlock_irqrestore(&wb->work_lock, flags); 2952 } 2953 2954 bool __folio_end_writeback(struct folio *folio) 2955 { 2956 long nr = folio_nr_pages(folio); 2957 struct address_space *mapping = folio_mapping(folio); 2958 bool ret; 2959 2960 if (mapping && mapping_use_writeback_tags(mapping)) { 2961 struct inode *inode = mapping->host; 2962 struct bdi_writeback *wb; 2963 unsigned long flags; 2964 2965 xa_lock_irqsave(&mapping->i_pages, flags); 2966 ret = folio_xor_flags_has_waiters(folio, 1 << PG_writeback); 2967 __xa_clear_mark(&mapping->i_pages, folio->index, 2968 PAGECACHE_TAG_WRITEBACK); 2969 2970 wb = inode_to_wb(inode); 2971 wb_stat_mod(wb, WB_WRITEBACK, -nr); 2972 __wb_writeout_add(wb, nr); 2973 if (!mapping_tagged(mapping, PAGECACHE_TAG_WRITEBACK)) { 2974 wb_inode_writeback_end(wb); 2975 if (mapping->host) 2976 sb_clear_inode_writeback(mapping->host); 2977 } 2978 2979 xa_unlock_irqrestore(&mapping->i_pages, flags); 2980 } else { 2981 ret = folio_xor_flags_has_waiters(folio, 1 << PG_writeback); 2982 } 2983 2984 lruvec_stat_mod_folio(folio, NR_WRITEBACK, -nr); 2985 zone_stat_mod_folio(folio, NR_ZONE_WRITE_PENDING, -nr); 2986 node_stat_mod_folio(folio, NR_WRITTEN, nr); 2987 2988 return ret; 2989 } 2990 2991 void __folio_start_writeback(struct folio *folio, bool keep_write) 2992 { 2993 long nr = folio_nr_pages(folio); 2994 struct address_space *mapping = folio_mapping(folio); 2995 int access_ret; 2996 2997 VM_BUG_ON_FOLIO(folio_test_writeback(folio), folio); 2998 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 2999 3000 if (mapping && mapping_use_writeback_tags(mapping)) { 3001 XA_STATE(xas, &mapping->i_pages, folio->index); 3002 struct inode *inode = mapping->host; 3003 struct bdi_writeback *wb; 3004 unsigned long flags; 3005 bool on_wblist; 3006 3007 xas_lock_irqsave(&xas, flags); 3008 xas_load(&xas); 3009 folio_test_set_writeback(folio); 3010 3011 on_wblist = mapping_tagged(mapping, PAGECACHE_TAG_WRITEBACK); 3012 3013 xas_set_mark(&xas, PAGECACHE_TAG_WRITEBACK); 3014 wb = inode_to_wb(inode); 3015 wb_stat_mod(wb, WB_WRITEBACK, nr); 3016 if (!on_wblist) { 3017 wb_inode_writeback_start(wb); 3018 /* 3019 * We can come through here when swapping anonymous 3020 * folios, so we don't necessarily have an inode to 3021 * track for sync. 3022 */ 3023 if (mapping->host) 3024 sb_mark_inode_writeback(mapping->host); 3025 } 3026 3027 if (!folio_test_dirty(folio)) 3028 xas_clear_mark(&xas, PAGECACHE_TAG_DIRTY); 3029 if (!keep_write) 3030 xas_clear_mark(&xas, PAGECACHE_TAG_TOWRITE); 3031 xas_unlock_irqrestore(&xas, flags); 3032 } else { 3033 folio_test_set_writeback(folio); 3034 } 3035 3036 lruvec_stat_mod_folio(folio, NR_WRITEBACK, nr); 3037 zone_stat_mod_folio(folio, NR_ZONE_WRITE_PENDING, nr); 3038 3039 access_ret = arch_make_folio_accessible(folio); 3040 /* 3041 * If writeback has been triggered on a page that cannot be made 3042 * accessible, it is too late to recover here. 3043 */ 3044 VM_BUG_ON_FOLIO(access_ret != 0, folio); 3045 } 3046 EXPORT_SYMBOL(__folio_start_writeback); 3047 3048 /** 3049 * folio_wait_writeback - Wait for a folio to finish writeback. 3050 * @folio: The folio to wait for. 3051 * 3052 * If the folio is currently being written back to storage, wait for the 3053 * I/O to complete. 3054 * 3055 * Context: Sleeps. Must be called in process context and with 3056 * no spinlocks held. Caller should hold a reference on the folio. 3057 * If the folio is not locked, writeback may start again after writeback 3058 * has finished. 3059 */ 3060 void folio_wait_writeback(struct folio *folio) 3061 { 3062 while (folio_test_writeback(folio)) { 3063 trace_folio_wait_writeback(folio, folio_mapping(folio)); 3064 folio_wait_bit(folio, PG_writeback); 3065 } 3066 } 3067 EXPORT_SYMBOL_GPL(folio_wait_writeback); 3068 3069 /** 3070 * folio_wait_writeback_killable - Wait for a folio to finish writeback. 3071 * @folio: The folio to wait for. 3072 * 3073 * If the folio is currently being written back to storage, wait for the 3074 * I/O to complete or a fatal signal to arrive. 3075 * 3076 * Context: Sleeps. Must be called in process context and with 3077 * no spinlocks held. Caller should hold a reference on the folio. 3078 * If the folio is not locked, writeback may start again after writeback 3079 * has finished. 3080 * Return: 0 on success, -EINTR if we get a fatal signal while waiting. 3081 */ 3082 int folio_wait_writeback_killable(struct folio *folio) 3083 { 3084 while (folio_test_writeback(folio)) { 3085 trace_folio_wait_writeback(folio, folio_mapping(folio)); 3086 if (folio_wait_bit_killable(folio, PG_writeback)) 3087 return -EINTR; 3088 } 3089 3090 return 0; 3091 } 3092 EXPORT_SYMBOL_GPL(folio_wait_writeback_killable); 3093 3094 /** 3095 * folio_wait_stable() - wait for writeback to finish, if necessary. 3096 * @folio: The folio to wait on. 3097 * 3098 * This function determines if the given folio is related to a backing 3099 * device that requires folio contents to be held stable during writeback. 3100 * If so, then it will wait for any pending writeback to complete. 3101 * 3102 * Context: Sleeps. Must be called in process context and with 3103 * no spinlocks held. Caller should hold a reference on the folio. 3104 * If the folio is not locked, writeback may start again after writeback 3105 * has finished. 3106 */ 3107 void folio_wait_stable(struct folio *folio) 3108 { 3109 if (mapping_stable_writes(folio_mapping(folio))) 3110 folio_wait_writeback(folio); 3111 } 3112 EXPORT_SYMBOL_GPL(folio_wait_stable); 3113