diff mbox series

[V11] cgroup/rstat: Avoid flushing if there is an ongoing root flush

Message ID 172616070094.2055617.17676042522679701515.stgit@firesoul (mailing list archive)
State New
Headers show
Series [V11] cgroup/rstat: Avoid flushing if there is an ongoing root flush | expand

Commit Message

Jesper Dangaard Brouer Sept. 12, 2024, 5:07 p.m. UTC
This patch reintroduces and generalizes the "stats_flush_ongoing" concept
to avoid redundant flushes if there is an ongoing flush at cgroup root
level, addressing production lock contention issues on the global cgroup
rstat lock.

In this revision userspace readers will wait for the ongoing flusher to
complete before returning, to avoid reading out-dated stats just before
they get updated. Generally in-kernel users will attempt to skip the
flush in-order to get out of the lock contention state. Some in-kernel
users of the cgroup_rstat_flush() API depend on waiting for the flush to
complete before continuing. This patch introduce the call
cgroup_rstat_flush_relaxed() with a wait_for_flush option to satisfy both
use-cases.

At Cloudflare, we observed significant performance degradation due to
lock contention on the rstat lock, primarily caused by kswapd. The
specific mem_cgroup_flush_stats() call inlined in shrink_node, which
takes the rstat lock, is particularly problematic.

On our 12 NUMA node machines, each with a kswapd kthread per NUMA node, we
noted severe lock contention on the rstat lock, causing 12 CPUs to waste
cycles spinning every time kswapd runs. Fleet-wide stats (/proc/N/schedstat)
for kthreads revealed that we are burning an average of 20,000 CPU cores
fleet-wide on kswapd, primarily due to spinning on the rstat lock.

Here's a brief overview of the issue:
- __alloc_pages_slowpath calls wake_all_kswapds, causing all kswapdN threads
  to wake up simultaneously.
- The kswapd thread invokes shrink_node (via balance_pgdat), triggering the
  cgroup rstat flush operation as part of its work.
- balance_pgdat() has a NULL value in target_mem_cgroup, causing
  mem_cgroup_flush_stats() to flush with root_mem_cgroup.

The kernel previously addressed this with a "stats_flush_ongoing" concept,
which was removed in commit 7d7ef0a4686a ("mm: memcg: restore subtree stats
flushing"). This patch reintroduces and generalizes the concept to apply to
all users of cgroup rstat, not just memcg.

It have been a general theme to replace mem_cgroup_flush_stats() with
mem_cgroup_flush_stats_ratelimited every time we see a new case of this
issue. This will hide the contention issue until something starves the
kthread that does the periodic 2 second flush (for 2 periods). In
production we are seeing kthreads getting starved longer than 20 seconds.
This often happens in connection with OOM killer. This recreates the
kswapd lock contention situation at a very unfortunate point in time.
Thus, it makes sense to have this ongoing flusher lock contention
protection in place.

In this patch only a root cgroup can become the ongoing flusher, as this solves
the production issue. Letting other levels becoming ongoing flusher cause root
cgroup to contend on the lock again.

This change significantly reduces lock contention, especially in
environments with multiple NUMA nodes, thereby improving overall system
performance.

Fixes: 7d7ef0a4686a ("mm: memcg: restore subtree stats flushing").
Signed-off-by: Jesper Dangaard Brouer <hawk@kernel.org>
---
v11:
 - Address Yosry request to wait-for-flush for userspace readers

V10: https://lore.kernel.org/all/172547884995.206112.808619042206173396.stgit@firesoul/

 block/blk-cgroup.c         |    2 -
 include/linux/cgroup.h     |    1 
 include/linux/memcontrol.h |    1 
 kernel/cgroup/rstat.c      |  133 ++++++++++++++++++++++++++++++++++++++++++--
 mm/memcontrol.c            |   40 +++++++++----
 mm/vmscan.c                |    2 -
 mm/zswap.c                 |    2 -
 7 files changed, 157 insertions(+), 24 deletions(-)

Comments

Yosry Ahmed Sept. 12, 2024, 9:41 p.m. UTC | #1
On Thu, Sep 12, 2024 at 10:07 AM Jesper Dangaard Brouer <hawk@kernel.org> wrote:
>
> This patch reintroduces and generalizes the "stats_flush_ongoing" concept
> to avoid redundant flushes if there is an ongoing flush at cgroup root
> level, addressing production lock contention issues on the global cgroup
> rstat lock.
>
> In this revision userspace readers will wait for the ongoing flusher to
> complete before returning, to avoid reading out-dated stats just before
> they get updated. Generally in-kernel users will attempt to skip the
> flush in-order to get out of the lock contention state. Some in-kernel
> users of the cgroup_rstat_flush() API depend on waiting for the flush to
> complete before continuing. This patch introduce the call
> cgroup_rstat_flush_relaxed() with a wait_for_flush option to satisfy both
> use-cases.
>
> At Cloudflare, we observed significant performance degradation due to
> lock contention on the rstat lock, primarily caused by kswapd. The
> specific mem_cgroup_flush_stats() call inlined in shrink_node, which
> takes the rstat lock, is particularly problematic.
>
> On our 12 NUMA node machines, each with a kswapd kthread per NUMA node, we
> noted severe lock contention on the rstat lock, causing 12 CPUs to waste
> cycles spinning every time kswapd runs. Fleet-wide stats (/proc/N/schedstat)
> for kthreads revealed that we are burning an average of 20,000 CPU cores
> fleet-wide on kswapd, primarily due to spinning on the rstat lock.
>
> Here's a brief overview of the issue:
> - __alloc_pages_slowpath calls wake_all_kswapds, causing all kswapdN threads
>   to wake up simultaneously.
> - The kswapd thread invokes shrink_node (via balance_pgdat), triggering the
>   cgroup rstat flush operation as part of its work.
> - balance_pgdat() has a NULL value in target_mem_cgroup, causing
>   mem_cgroup_flush_stats() to flush with root_mem_cgroup.
>
> The kernel previously addressed this with a "stats_flush_ongoing" concept,
> which was removed in commit 7d7ef0a4686a ("mm: memcg: restore subtree stats
> flushing"). This patch reintroduces and generalizes the concept to apply to
> all users of cgroup rstat, not just memcg.
>
> It have been a general theme to replace mem_cgroup_flush_stats() with
> mem_cgroup_flush_stats_ratelimited every time we see a new case of this
> issue. This will hide the contention issue until something starves the
> kthread that does the periodic 2 second flush (for 2 periods). In
> production we are seeing kthreads getting starved longer than 20 seconds.
> This often happens in connection with OOM killer. This recreates the
> kswapd lock contention situation at a very unfortunate point in time.
> Thus, it makes sense to have this ongoing flusher lock contention
> protection in place.
>
> In this patch only a root cgroup can become the ongoing flusher, as this solves
> the production issue. Letting other levels becoming ongoing flusher cause root
> cgroup to contend on the lock again.
>
> This change significantly reduces lock contention, especially in
> environments with multiple NUMA nodes, thereby improving overall system
> performance.
>
> Fixes: 7d7ef0a4686a ("mm: memcg: restore subtree stats flushing").
> Signed-off-by: Jesper Dangaard Brouer <hawk@kernel.org>
> ---

To reiterate my response on v10, I prefer that this problem is handled
at the reclaim flushing site. This started as a nice simple and
generic approach, but ended up being complex and tailored to handle
the reclaim flushing case.

I do have some comments on the current implementation nonetheless.

> v11:
>  - Address Yosry request to wait-for-flush for userspace readers
>
> V10: https://lore.kernel.org/all/172547884995.206112.808619042206173396.stgit@firesoul/
>
>  block/blk-cgroup.c         |    2 -
>  include/linux/cgroup.h     |    1
>  include/linux/memcontrol.h |    1
>  kernel/cgroup/rstat.c      |  133 ++++++++++++++++++++++++++++++++++++++++++--
>  mm/memcontrol.c            |   40 +++++++++----
>  mm/vmscan.c                |    2 -
>  mm/zswap.c                 |    2 -
>  7 files changed, 157 insertions(+), 24 deletions(-)
>
> diff --git a/block/blk-cgroup.c b/block/blk-cgroup.c
> index 37e6cc91d576..058393e7665a 100644
> --- a/block/blk-cgroup.c
> +++ b/block/blk-cgroup.c
> @@ -1200,7 +1200,7 @@ static int blkcg_print_stat(struct seq_file *sf, void *v)
>         if (!seq_css(sf)->parent)
>                 blkcg_fill_root_iostats();
>         else
> -               cgroup_rstat_flush(blkcg->css.cgroup);
> +               cgroup_rstat_flush_relaxed(blkcg->css.cgroup, true);
>
>         rcu_read_lock();
>         hlist_for_each_entry_rcu(blkg, &blkcg->blkg_list, blkcg_node) {
> diff --git a/include/linux/cgroup.h b/include/linux/cgroup.h
> index 2150ca60394b..ff65bc100ca5 100644
> --- a/include/linux/cgroup.h
> +++ b/include/linux/cgroup.h
> @@ -691,6 +691,7 @@ void cgroup_rstat_updated(struct cgroup *cgrp, int cpu);
>  void cgroup_rstat_flush(struct cgroup *cgrp);
>  void cgroup_rstat_flush_hold(struct cgroup *cgrp);
>  void cgroup_rstat_flush_release(struct cgroup *cgrp);
> +int cgroup_rstat_flush_relaxed(struct cgroup *cgrp, bool wait_for_flush);

We now have 4 different flavors of rstat flushing:

1. cgroup_rstat_flush() -> normal flush: lock, flush, unlock
2. cgroup_rstat_flush_hold() -> same, but keep the lock held
3. cgroup_rstat_flush_relaxed(wait_for_flush=true) -> if someone is
already flushing us, wait, otherwise normal
4. cgroup_rstat_flush_relaxed(wait_for_flush=false) -> if someone is
already flushing us, wait, otherwise normal

Why do we need the third one? Can't we just keep using (1) for now for
userspace readers?

>
>  /*
>   * Basic resource stats.
> diff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h
> index 030d34e9d117..7e24c5e1327f 100644
> --- a/include/linux/memcontrol.h
> +++ b/include/linux/memcontrol.h
> @@ -1026,6 +1026,7 @@ unsigned long lruvec_page_state_local(struct lruvec *lruvec,
>                                       enum node_stat_item idx);
>
>  void mem_cgroup_flush_stats(struct mem_cgroup *memcg);
> +void mem_cgroup_flush_stats_relaxed(struct mem_cgroup *memcg);
>  void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg);
>
>  void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val);
> diff --git a/kernel/cgroup/rstat.c b/kernel/cgroup/rstat.c
> index a06b45272411..80a4b949138f 100644
> --- a/kernel/cgroup/rstat.c
> +++ b/kernel/cgroup/rstat.c
> @@ -11,6 +11,9 @@
>
>  static DEFINE_SPINLOCK(cgroup_rstat_lock);
>  static DEFINE_PER_CPU(raw_spinlock_t, cgroup_rstat_cpu_lock);
> +static struct cgroup *cgrp_rstat_ongoing_flusher = NULL;
> +static struct task_struct *cgrp_rstat_ongoing_flusher_ID = NULL;

rstat_ongoing_flush_cgrp and rstat_ongoing_flush_task are probably
clearer names.

> +static DEFINE_MUTEX(cgrp_rstat_ongoing_flusher_serialize);
>
>  static void cgroup_base_stat_flush(struct cgroup *cgrp, int cpu);
>
> @@ -299,6 +302,68 @@ static inline void __cgroup_rstat_unlock(struct cgroup *cgrp, int cpu_in_loop)
>         spin_unlock_irq(&cgroup_rstat_lock);
>  }
>
> +static inline bool cgroup_is_root(struct cgroup *cgrp)
> +{
> +       return cgroup_parent(cgrp) == NULL;
> +}
> +
> +/**
> + * cgroup_rstat_trylock_flusher - Trylock that checks for on ongoing flusher
> + * @cgrp: target cgroup
> + * @strict: always lock and ignore/skip ongoing flusher checks
> + *
> + * Function return value follow trylock semantics. Returning true when lock is
> + * obtained. Returning false when not locked and it detected flushing can be
> + * skipped as another ongoing flusher is taking care of the flush.
> + *
> + * For callers that depend on flush completing before returning a strict option
> + * is provided.
> + */
> +static bool cgroup_rstat_trylock_flusher(struct cgroup *cgrp, bool strict)
> +{
> +       struct cgroup *ongoing;
> +
> +       if (strict)
> +               goto lock;

Might as well just have a cgroup_rstat_lock_flusher() function instead
of the boolean parameter, which is also consistent with the
lock/trylock semantics you are following.

> +
> +       /*
> +        * Check if ongoing flusher is already taking care of this.  Descendant
> +        * check is necessary due to cgroup v1 supporting multiple root's.
> +        */
> +       ongoing = READ_ONCE(cgrp_rstat_ongoing_flusher);
> +       if (ongoing && cgroup_is_descendant(cgrp, ongoing))

The ongoing flusher may be going away, so cgroup_is_descendant() may
be a UAF as I pointed out a few times. I actually think even taking a
ref here may not work as it may be a flush from cgroup_rstat_exit().

One thing we can do is get the root of cgrp (probably
cgrp->root->cgrp?) and compare it to cgrp_rstat_ongoing_flusher
without ever dereferencing it. If the ongoing flusher is in fact the
root of cgrp, this implies a ref on it anyway so we can dereference it
if needed.

That would obviously need a comment to explain it.

> +               return false;
> +
> +       /* Grab right to be ongoing flusher */
> +       if (!ongoing && cgroup_is_root(cgrp)) {
> +               struct cgroup *old;
> +
> +               old = cmpxchg(&cgrp_rstat_ongoing_flusher, NULL, cgrp);
> +               if (old) {
> +                       /* Lost race for being ongoing flusher */
> +                       if (cgroup_is_descendant(cgrp, old))
> +                               return false;
> +               }
> +               /* Due to lock yield combined with strict mode record ID */

This needs a more detailed comment.

> +               WRITE_ONCE(cgrp_rstat_ongoing_flusher_ID, current);

This will overwrite the ID if we lost the race but are not a
descendant of the flusher that one the race, right?

> +       }
> +lock:
> +       __cgroup_rstat_lock(cgrp, -1);
> +
> +       return true;
> +}
> +
> +static void cgroup_rstat_unlock_flusher(struct cgroup *cgrp)
> +{
> +       if (cgrp == READ_ONCE(cgrp_rstat_ongoing_flusher) &&
> +           READ_ONCE(cgrp_rstat_ongoing_flusher_ID) == current) {
> +               WRITE_ONCE(cgrp_rstat_ongoing_flusher_ID, NULL);
> +               WRITE_ONCE(cgrp_rstat_ongoing_flusher, NULL);
> +       }
> +
> +       __cgroup_rstat_unlock(cgrp, -1);
> +}
> +
>  /* see cgroup_rstat_flush() */
>  static void cgroup_rstat_flush_locked(struct cgroup *cgrp)
>         __releases(&cgroup_rstat_lock) __acquires(&cgroup_rstat_lock)
> @@ -333,6 +398,19 @@ static void cgroup_rstat_flush_locked(struct cgroup *cgrp)
>         }
>  }
>
> +static int __cgroup_rstat_flush(struct cgroup *cgrp, bool strict)
> +{
> +       might_sleep();
> +
> +       if (!cgroup_rstat_trylock_flusher(cgrp, strict))
> +               return false;
> +
> +       cgroup_rstat_flush_locked(cgrp);
> +       cgroup_rstat_unlock_flusher(cgrp);
> +
> +       return true;
> +}
> +
>  /**
>   * cgroup_rstat_flush - flush stats in @cgrp's subtree
>   * @cgrp: target cgroup
> @@ -348,11 +426,49 @@ static void cgroup_rstat_flush_locked(struct cgroup *cgrp)
>   */
>  __bpf_kfunc void cgroup_rstat_flush(struct cgroup *cgrp)
>  {
> -       might_sleep();
> +       __cgroup_rstat_flush(cgrp, true);
> +}
>
> -       __cgroup_rstat_lock(cgrp, -1);
> -       cgroup_rstat_flush_locked(cgrp);
> -       __cgroup_rstat_unlock(cgrp, -1);
> +int cgroup_rstat_flush_relaxed(struct cgroup *cgrp, bool wait_for_flush)
> +{
> +       bool flushed = __cgroup_rstat_flush(cgrp, false);
> +
> +       if (!flushed && wait_for_flush) {

Isn't the code below essentially open-coding completions in a less
efficient way? Anyway as I mentioned above I don't believe we really
need wait_for_flush for now. I was hoping we can make this work for
both in-kernel and userspace flushers, but I don't think we want to
add it just for userspace flushers.

> +               /*
> +                * Reaching here we know an ongoing flusher is running, that
> +                * will take care of flushing for us, but for caller to read
> +                * accurate stats we want to wait for this ongoing flusher.
> +                *
> +                * TODO: When lock becomes mutex and no-yielding this code can
> +                * be simplifed as we can just sleep on the mutex lock.
> +                */
> +               struct task_struct *id, *cur_id;
> +               u64 timeout;
> +
> +               id = READ_ONCE(cgrp_rstat_ongoing_flusher_ID);
> +               timeout = jiffies_64 + msecs_to_jiffies(50);
> +
> +               if (!id)
> +                       return false;
> +
> +               cond_resched();
> +               /* We might get lucky and flush already completed */
> +               cur_id = READ_ONCE(cgrp_rstat_ongoing_flusher_ID);
> +
> +               /* Due to lock yield, make sure "id" flusher completes */
> +               while (cur_id == id && time_before64(jiffies_64, timeout)) {
> +                       cond_resched();
> +                       /* Use mutex to reduce stress on global lock */
> +                       mutex_lock(&cgrp_rstat_ongoing_flusher_serialize);
> +                       __cgroup_rstat_lock(cgrp, -1);
> +                       /* Get lock with ongoing can happen due to yielding */
> +                       cur_id = READ_ONCE(cgrp_rstat_ongoing_flusher_ID);
> +                       __cgroup_rstat_unlock(cgrp, -1);
> +                       mutex_unlock(&cgrp_rstat_ongoing_flusher_serialize);
> +               }
> +       }
> +
> +       return flushed;
>  }
>
>  /**
> @@ -368,8 +484,11 @@ void cgroup_rstat_flush_hold(struct cgroup *cgrp)
>         __acquires(&cgroup_rstat_lock)
>  {
>         might_sleep();
> -       __cgroup_rstat_lock(cgrp, -1);
> -       cgroup_rstat_flush_locked(cgrp);
> +
> +       if (cgroup_rstat_trylock_flusher(cgrp, false))
> +               cgroup_rstat_flush_locked(cgrp);
> +       else
> +               __cgroup_rstat_lock(cgrp, -1);
>  }
>
>  /**
> @@ -379,7 +498,7 @@ void cgroup_rstat_flush_hold(struct cgroup *cgrp)
>  void cgroup_rstat_flush_release(struct cgroup *cgrp)
>         __releases(&cgroup_rstat_lock)
>  {
> -       __cgroup_rstat_unlock(cgrp, -1);
> +       cgroup_rstat_unlock_flusher(cgrp);
>  }
>
>  int cgroup_rstat_init(struct cgroup *cgrp)
> diff --git a/mm/memcontrol.c b/mm/memcontrol.c
> index 71fe2a95b8bd..6694f7a859b5 100644
> --- a/mm/memcontrol.c
> +++ b/mm/memcontrol.c
> @@ -871,12 +871,26 @@ static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val)
>         }
>  }
>
> -static void do_flush_stats(struct mem_cgroup *memcg)
> +static void do_flush_stats(struct mem_cgroup *memcg, bool wait_for_flush)
>  {
> -       if (mem_cgroup_is_root(memcg))
> -               WRITE_ONCE(flush_last_time, jiffies_64);
> +       bool flushed = cgroup_rstat_flush_relaxed(memcg->css.cgroup,
> +                                                 wait_for_flush);
>
> -       cgroup_rstat_flush(memcg->css.cgroup);
> +       if (mem_cgroup_is_root(memcg) && flushed)
> +                   WRITE_ONCE(flush_last_time, jiffies_64);
> +}
> +
> +static void __mem_cgroup_flush_stats(struct mem_cgroup *memcg,
> +                                    bool wait_for_flush)
> +{
> +       if (mem_cgroup_disabled())
> +               return;
> +
> +       if (!memcg)
> +               memcg = root_mem_cgroup;
> +
> +       if (memcg_vmstats_needs_flush(memcg->vmstats))
> +               do_flush_stats(memcg, wait_for_flush);
>  }
>
>  /*
> @@ -890,21 +904,19 @@ static void do_flush_stats(struct mem_cgroup *memcg)
>   */
>  void mem_cgroup_flush_stats(struct mem_cgroup *memcg)
>  {
> -       if (mem_cgroup_disabled())
> -               return;
> -
> -       if (!memcg)
> -               memcg = root_mem_cgroup;
> +       __mem_cgroup_flush_stats(memcg, true);
> +}
>
> -       if (memcg_vmstats_needs_flush(memcg->vmstats))
> -               do_flush_stats(memcg);
> +void mem_cgroup_flush_stats_relaxed(struct mem_cgroup *memcg)
> +{
> +       __mem_cgroup_flush_stats(memcg, false);
>  }
>
>  void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg)
>  {
>         /* Only flush if the periodic flusher is one full cycle late */
>         if (time_after64(jiffies_64, READ_ONCE(flush_last_time) + 2*FLUSH_TIME))
> -               mem_cgroup_flush_stats(memcg);
> +               mem_cgroup_flush_stats_relaxed(memcg);

mem_cgroup_flush_stats_ratelimited() now basically says: only flush if
the periodic flusher is late but no one else is flushing, if we end up
pursuing this we probably want to start documenting these variants.
kernel test robot Sept. 13, 2024, 9:53 p.m. UTC | #2
Hi Jesper,

kernel test robot noticed the following build errors:

[auto build test ERROR on tj-cgroup/for-next]
[also build test ERROR on axboe-block/for-next linus/master v6.11-rc7]
[cannot apply to akpm-mm/mm-everything next-20240913]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Jesper-Dangaard-Brouer/cgroup-rstat-Avoid-flushing-if-there-is-an-ongoing-root-flush/20240913-010800
base:   https://git.kernel.org/pub/scm/linux/kernel/git/tj/cgroup.git for-next
patch link:    https://lore.kernel.org/r/172616070094.2055617.17676042522679701515.stgit%40firesoul
patch subject: [PATCH V11] cgroup/rstat: Avoid flushing if there is an ongoing root flush
config: x86_64-allnoconfig (https://download.01.org/0day-ci/archive/20240914/202409140533.2vt8QPj8-lkp@intel.com/config)
compiler: clang version 18.1.8 (https://github.com/llvm/llvm-project 3b5b5c1ec4a3095ab096dd780e84d7ab81f3d7ff)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20240914/202409140533.2vt8QPj8-lkp@intel.com/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of
the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <lkp@intel.com>
| Closes: https://lore.kernel.org/oe-kbuild-all/202409140533.2vt8QPj8-lkp@intel.com/

All errors (new ones prefixed by >>):

>> mm/vmscan.c:2265:2: error: call to undeclared function 'mem_cgroup_flush_stats_relaxed'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
    2265 |         mem_cgroup_flush_stats_relaxed(sc->target_mem_cgroup);
         |         ^
   mm/vmscan.c:2265:2: note: did you mean 'mem_cgroup_flush_stats_ratelimited'?
   include/linux/memcontrol.h:1429:20: note: 'mem_cgroup_flush_stats_ratelimited' declared here
    1429 | static inline void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg)
         |                    ^
   1 error generated.


vim +/mem_cgroup_flush_stats_relaxed +2265 mm/vmscan.c

  2250	
  2251	static void prepare_scan_control(pg_data_t *pgdat, struct scan_control *sc)
  2252	{
  2253		unsigned long file;
  2254		struct lruvec *target_lruvec;
  2255	
  2256		if (lru_gen_enabled())
  2257			return;
  2258	
  2259		target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
  2260	
  2261		/*
  2262		 * Flush the memory cgroup stats, so that we read accurate per-memcg
  2263		 * lruvec stats for heuristics.
  2264		 */
> 2265		mem_cgroup_flush_stats_relaxed(sc->target_mem_cgroup);
  2266	
  2267		/*
  2268		 * Determine the scan balance between anon and file LRUs.
  2269		 */
  2270		spin_lock_irq(&target_lruvec->lru_lock);
  2271		sc->anon_cost = target_lruvec->anon_cost;
  2272		sc->file_cost = target_lruvec->file_cost;
  2273		spin_unlock_irq(&target_lruvec->lru_lock);
  2274	
  2275		/*
  2276		 * Target desirable inactive:active list ratios for the anon
  2277		 * and file LRU lists.
  2278		 */
  2279		if (!sc->force_deactivate) {
  2280			unsigned long refaults;
  2281	
  2282			/*
  2283			 * When refaults are being observed, it means a new
  2284			 * workingset is being established. Deactivate to get
  2285			 * rid of any stale active pages quickly.
  2286			 */
  2287			refaults = lruvec_page_state(target_lruvec,
  2288					WORKINGSET_ACTIVATE_ANON);
  2289			if (refaults != target_lruvec->refaults[WORKINGSET_ANON] ||
  2290				inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
  2291				sc->may_deactivate |= DEACTIVATE_ANON;
  2292			else
  2293				sc->may_deactivate &= ~DEACTIVATE_ANON;
  2294	
  2295			refaults = lruvec_page_state(target_lruvec,
  2296					WORKINGSET_ACTIVATE_FILE);
  2297			if (refaults != target_lruvec->refaults[WORKINGSET_FILE] ||
  2298			    inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
  2299				sc->may_deactivate |= DEACTIVATE_FILE;
  2300			else
  2301				sc->may_deactivate &= ~DEACTIVATE_FILE;
  2302		} else
  2303			sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
  2304	
  2305		/*
  2306		 * If we have plenty of inactive file pages that aren't
  2307		 * thrashing, try to reclaim those first before touching
  2308		 * anonymous pages.
  2309		 */
  2310		file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
  2311		if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE) &&
  2312		    !sc->no_cache_trim_mode)
  2313			sc->cache_trim_mode = 1;
  2314		else
  2315			sc->cache_trim_mode = 0;
  2316	
  2317		/*
  2318		 * Prevent the reclaimer from falling into the cache trap: as
  2319		 * cache pages start out inactive, every cache fault will tip
  2320		 * the scan balance towards the file LRU.  And as the file LRU
  2321		 * shrinks, so does the window for rotation from references.
  2322		 * This means we have a runaway feedback loop where a tiny
  2323		 * thrashing file LRU becomes infinitely more attractive than
  2324		 * anon pages.  Try to detect this based on file LRU size.
  2325		 */
  2326		if (!cgroup_reclaim(sc)) {
  2327			unsigned long total_high_wmark = 0;
  2328			unsigned long free, anon;
  2329			int z;
  2330	
  2331			free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
  2332			file = node_page_state(pgdat, NR_ACTIVE_FILE) +
  2333				   node_page_state(pgdat, NR_INACTIVE_FILE);
  2334	
  2335			for (z = 0; z < MAX_NR_ZONES; z++) {
  2336				struct zone *zone = &pgdat->node_zones[z];
  2337	
  2338				if (!managed_zone(zone))
  2339					continue;
  2340	
  2341				total_high_wmark += high_wmark_pages(zone);
  2342			}
  2343	
  2344			/*
  2345			 * Consider anon: if that's low too, this isn't a
  2346			 * runaway file reclaim problem, but rather just
  2347			 * extreme pressure. Reclaim as per usual then.
  2348			 */
  2349			anon = node_page_state(pgdat, NR_INACTIVE_ANON);
  2350	
  2351			sc->file_is_tiny =
  2352				file + free <= total_high_wmark &&
  2353				!(sc->may_deactivate & DEACTIVATE_ANON) &&
  2354				anon >> sc->priority;
  2355		}
  2356	}
  2357
kernel test robot Sept. 13, 2024, 9:54 p.m. UTC | #3
Hi Jesper,

kernel test robot noticed the following build errors:

[auto build test ERROR on tj-cgroup/for-next]
[also build test ERROR on axboe-block/for-next linus/master v6.11-rc7]
[cannot apply to akpm-mm/mm-everything next-20240913]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Jesper-Dangaard-Brouer/cgroup-rstat-Avoid-flushing-if-there-is-an-ongoing-root-flush/20240913-010800
base:   https://git.kernel.org/pub/scm/linux/kernel/git/tj/cgroup.git for-next
patch link:    https://lore.kernel.org/r/172616070094.2055617.17676042522679701515.stgit%40firesoul
patch subject: [PATCH V11] cgroup/rstat: Avoid flushing if there is an ongoing root flush
config: i386-randconfig-141-20240914 (https://download.01.org/0day-ci/archive/20240914/202409140533.XqO09tth-lkp@intel.com/config)
compiler: gcc-12 (Debian 12.2.0-14) 12.2.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20240914/202409140533.XqO09tth-lkp@intel.com/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of
the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <lkp@intel.com>
| Closes: https://lore.kernel.org/oe-kbuild-all/202409140533.XqO09tth-lkp@intel.com/

All errors (new ones prefixed by >>):

   mm/zswap.c: In function 'zswap_shrinker_count':
>> mm/zswap.c:1225:17: error: implicit declaration of function 'mem_cgroup_flush_stats_relaxed'; did you mean 'mem_cgroup_flush_stats_ratelimited'? [-Werror=implicit-function-declaration]
    1225 |                 mem_cgroup_flush_stats_relaxed(memcg);
         |                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
         |                 mem_cgroup_flush_stats_ratelimited
   cc1: some warnings being treated as errors


vim +1225 mm/zswap.c

  1197	
  1198	static unsigned long zswap_shrinker_count(struct shrinker *shrinker,
  1199			struct shrink_control *sc)
  1200	{
  1201		struct mem_cgroup *memcg = sc->memcg;
  1202		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(sc->nid));
  1203		unsigned long nr_backing, nr_stored, nr_freeable, nr_protected;
  1204	
  1205		if (!zswap_shrinker_enabled || !mem_cgroup_zswap_writeback_enabled(memcg))
  1206			return 0;
  1207	
  1208		/*
  1209		 * The shrinker resumes swap writeback, which will enter block
  1210		 * and may enter fs. XXX: Harmonize with vmscan.c __GFP_FS
  1211		 * rules (may_enter_fs()), which apply on a per-folio basis.
  1212		 */
  1213		if (!gfp_has_io_fs(sc->gfp_mask))
  1214			return 0;
  1215	
  1216		/*
  1217		 * For memcg, use the cgroup-wide ZSWAP stats since we don't
  1218		 * have them per-node and thus per-lruvec. Careful if memcg is
  1219		 * runtime-disabled: we can get sc->memcg == NULL, which is ok
  1220		 * for the lruvec, but not for memcg_page_state().
  1221		 *
  1222		 * Without memcg, use the zswap pool-wide metrics.
  1223		 */
  1224		if (!mem_cgroup_disabled()) {
> 1225			mem_cgroup_flush_stats_relaxed(memcg);
  1226			nr_backing = memcg_page_state(memcg, MEMCG_ZSWAP_B) >> PAGE_SHIFT;
  1227			nr_stored = memcg_page_state(memcg, MEMCG_ZSWAPPED);
  1228		} else {
  1229			nr_backing = zswap_total_pages();
  1230			nr_stored = atomic_read(&zswap_stored_pages);
  1231		}
  1232	
  1233		if (!nr_stored)
  1234			return 0;
  1235	
  1236		nr_protected =
  1237			atomic_long_read(&lruvec->zswap_lruvec_state.nr_zswap_protected);
  1238		nr_freeable = list_lru_shrink_count(&zswap_list_lru, sc);
  1239		/*
  1240		 * Subtract the lru size by an estimate of the number of pages
  1241		 * that should be protected.
  1242		 */
  1243		nr_freeable = nr_freeable > nr_protected ? nr_freeable - nr_protected : 0;
  1244	
  1245		/*
  1246		 * Scale the number of freeable pages by the memory saving factor.
  1247		 * This ensures that the better zswap compresses memory, the fewer
  1248		 * pages we will evict to swap (as it will otherwise incur IO for
  1249		 * relatively small memory saving).
  1250		 *
  1251		 * The memory saving factor calculated here takes same-filled pages into
  1252		 * account, but those are not freeable since they almost occupy no
  1253		 * space. Hence, we may scale nr_freeable down a little bit more than we
  1254		 * should if we have a lot of same-filled pages.
  1255		 */
  1256		return mult_frac(nr_freeable, nr_backing, nr_stored);
  1257	}
  1258
diff mbox series

Patch

diff --git a/block/blk-cgroup.c b/block/blk-cgroup.c
index 37e6cc91d576..058393e7665a 100644
--- a/block/blk-cgroup.c
+++ b/block/blk-cgroup.c
@@ -1200,7 +1200,7 @@  static int blkcg_print_stat(struct seq_file *sf, void *v)
 	if (!seq_css(sf)->parent)
 		blkcg_fill_root_iostats();
 	else
-		cgroup_rstat_flush(blkcg->css.cgroup);
+		cgroup_rstat_flush_relaxed(blkcg->css.cgroup, true);
 
 	rcu_read_lock();
 	hlist_for_each_entry_rcu(blkg, &blkcg->blkg_list, blkcg_node) {
diff --git a/include/linux/cgroup.h b/include/linux/cgroup.h
index 2150ca60394b..ff65bc100ca5 100644
--- a/include/linux/cgroup.h
+++ b/include/linux/cgroup.h
@@ -691,6 +691,7 @@  void cgroup_rstat_updated(struct cgroup *cgrp, int cpu);
 void cgroup_rstat_flush(struct cgroup *cgrp);
 void cgroup_rstat_flush_hold(struct cgroup *cgrp);
 void cgroup_rstat_flush_release(struct cgroup *cgrp);
+int cgroup_rstat_flush_relaxed(struct cgroup *cgrp, bool wait_for_flush);
 
 /*
  * Basic resource stats.
diff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h
index 030d34e9d117..7e24c5e1327f 100644
--- a/include/linux/memcontrol.h
+++ b/include/linux/memcontrol.h
@@ -1026,6 +1026,7 @@  unsigned long lruvec_page_state_local(struct lruvec *lruvec,
 				      enum node_stat_item idx);
 
 void mem_cgroup_flush_stats(struct mem_cgroup *memcg);
+void mem_cgroup_flush_stats_relaxed(struct mem_cgroup *memcg);
 void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg);
 
 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val);
diff --git a/kernel/cgroup/rstat.c b/kernel/cgroup/rstat.c
index a06b45272411..80a4b949138f 100644
--- a/kernel/cgroup/rstat.c
+++ b/kernel/cgroup/rstat.c
@@ -11,6 +11,9 @@ 
 
 static DEFINE_SPINLOCK(cgroup_rstat_lock);
 static DEFINE_PER_CPU(raw_spinlock_t, cgroup_rstat_cpu_lock);
+static struct cgroup *cgrp_rstat_ongoing_flusher = NULL;
+static struct task_struct *cgrp_rstat_ongoing_flusher_ID = NULL;
+static DEFINE_MUTEX(cgrp_rstat_ongoing_flusher_serialize);
 
 static void cgroup_base_stat_flush(struct cgroup *cgrp, int cpu);
 
@@ -299,6 +302,68 @@  static inline void __cgroup_rstat_unlock(struct cgroup *cgrp, int cpu_in_loop)
 	spin_unlock_irq(&cgroup_rstat_lock);
 }
 
+static inline bool cgroup_is_root(struct cgroup *cgrp)
+{
+	return cgroup_parent(cgrp) == NULL;
+}
+
+/**
+ * cgroup_rstat_trylock_flusher - Trylock that checks for on ongoing flusher
+ * @cgrp: target cgroup
+ * @strict: always lock and ignore/skip ongoing flusher checks
+ *
+ * Function return value follow trylock semantics. Returning true when lock is
+ * obtained. Returning false when not locked and it detected flushing can be
+ * skipped as another ongoing flusher is taking care of the flush.
+ *
+ * For callers that depend on flush completing before returning a strict option
+ * is provided.
+ */
+static bool cgroup_rstat_trylock_flusher(struct cgroup *cgrp, bool strict)
+{
+	struct cgroup *ongoing;
+
+	if (strict)
+		goto lock;
+
+	/*
+	 * Check if ongoing flusher is already taking care of this.  Descendant
+	 * check is necessary due to cgroup v1 supporting multiple root's.
+	 */
+	ongoing = READ_ONCE(cgrp_rstat_ongoing_flusher);
+	if (ongoing && cgroup_is_descendant(cgrp, ongoing))
+		return false;
+
+	/* Grab right to be ongoing flusher */
+	if (!ongoing && cgroup_is_root(cgrp)) {
+		struct cgroup *old;
+
+		old = cmpxchg(&cgrp_rstat_ongoing_flusher, NULL, cgrp);
+		if (old) {
+			/* Lost race for being ongoing flusher */
+			if (cgroup_is_descendant(cgrp, old))
+				return false;
+		}
+		/* Due to lock yield combined with strict mode record ID */
+		WRITE_ONCE(cgrp_rstat_ongoing_flusher_ID, current);
+	}
+lock:
+	__cgroup_rstat_lock(cgrp, -1);
+
+	return true;
+}
+
+static void cgroup_rstat_unlock_flusher(struct cgroup *cgrp)
+{
+	if (cgrp == READ_ONCE(cgrp_rstat_ongoing_flusher) &&
+	    READ_ONCE(cgrp_rstat_ongoing_flusher_ID) == current) {
+		WRITE_ONCE(cgrp_rstat_ongoing_flusher_ID, NULL);
+		WRITE_ONCE(cgrp_rstat_ongoing_flusher, NULL);
+	}
+
+	__cgroup_rstat_unlock(cgrp, -1);
+}
+
 /* see cgroup_rstat_flush() */
 static void cgroup_rstat_flush_locked(struct cgroup *cgrp)
 	__releases(&cgroup_rstat_lock) __acquires(&cgroup_rstat_lock)
@@ -333,6 +398,19 @@  static void cgroup_rstat_flush_locked(struct cgroup *cgrp)
 	}
 }
 
+static int __cgroup_rstat_flush(struct cgroup *cgrp, bool strict)
+{
+	might_sleep();
+
+	if (!cgroup_rstat_trylock_flusher(cgrp, strict))
+		return false;
+
+	cgroup_rstat_flush_locked(cgrp);
+	cgroup_rstat_unlock_flusher(cgrp);
+
+	return true;
+}
+
 /**
  * cgroup_rstat_flush - flush stats in @cgrp's subtree
  * @cgrp: target cgroup
@@ -348,11 +426,49 @@  static void cgroup_rstat_flush_locked(struct cgroup *cgrp)
  */
 __bpf_kfunc void cgroup_rstat_flush(struct cgroup *cgrp)
 {
-	might_sleep();
+	__cgroup_rstat_flush(cgrp, true);
+}
 
-	__cgroup_rstat_lock(cgrp, -1);
-	cgroup_rstat_flush_locked(cgrp);
-	__cgroup_rstat_unlock(cgrp, -1);
+int cgroup_rstat_flush_relaxed(struct cgroup *cgrp, bool wait_for_flush)
+{
+	bool flushed = __cgroup_rstat_flush(cgrp, false);
+
+	if (!flushed && wait_for_flush) {
+		/*
+		 * Reaching here we know an ongoing flusher is running, that
+		 * will take care of flushing for us, but for caller to read
+		 * accurate stats we want to wait for this ongoing flusher.
+		 *
+		 * TODO: When lock becomes mutex and no-yielding this code can
+		 * be simplifed as we can just sleep on the mutex lock.
+		 */
+		struct task_struct *id, *cur_id;
+		u64 timeout;
+
+		id = READ_ONCE(cgrp_rstat_ongoing_flusher_ID);
+		timeout = jiffies_64 + msecs_to_jiffies(50);
+
+		if (!id)
+			return false;
+
+		cond_resched();
+		/* We might get lucky and flush already completed */
+		cur_id = READ_ONCE(cgrp_rstat_ongoing_flusher_ID);
+
+		/* Due to lock yield, make sure "id" flusher completes */
+		while (cur_id == id && time_before64(jiffies_64, timeout)) {
+			cond_resched();
+			/* Use mutex to reduce stress on global lock */
+			mutex_lock(&cgrp_rstat_ongoing_flusher_serialize);
+			__cgroup_rstat_lock(cgrp, -1);
+			/* Get lock with ongoing can happen due to yielding */
+			cur_id = READ_ONCE(cgrp_rstat_ongoing_flusher_ID);
+			__cgroup_rstat_unlock(cgrp, -1);
+			mutex_unlock(&cgrp_rstat_ongoing_flusher_serialize);
+		}
+	}
+
+	return flushed;
 }
 
 /**
@@ -368,8 +484,11 @@  void cgroup_rstat_flush_hold(struct cgroup *cgrp)
 	__acquires(&cgroup_rstat_lock)
 {
 	might_sleep();
-	__cgroup_rstat_lock(cgrp, -1);
-	cgroup_rstat_flush_locked(cgrp);
+
+	if (cgroup_rstat_trylock_flusher(cgrp, false))
+		cgroup_rstat_flush_locked(cgrp);
+	else
+		__cgroup_rstat_lock(cgrp, -1);
 }
 
 /**
@@ -379,7 +498,7 @@  void cgroup_rstat_flush_hold(struct cgroup *cgrp)
 void cgroup_rstat_flush_release(struct cgroup *cgrp)
 	__releases(&cgroup_rstat_lock)
 {
-	__cgroup_rstat_unlock(cgrp, -1);
+	cgroup_rstat_unlock_flusher(cgrp);
 }
 
 int cgroup_rstat_init(struct cgroup *cgrp)
diff --git a/mm/memcontrol.c b/mm/memcontrol.c
index 71fe2a95b8bd..6694f7a859b5 100644
--- a/mm/memcontrol.c
+++ b/mm/memcontrol.c
@@ -871,12 +871,26 @@  static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val)
 	}
 }
 
-static void do_flush_stats(struct mem_cgroup *memcg)
+static void do_flush_stats(struct mem_cgroup *memcg, bool wait_for_flush)
 {
-	if (mem_cgroup_is_root(memcg))
-		WRITE_ONCE(flush_last_time, jiffies_64);
+	bool flushed = cgroup_rstat_flush_relaxed(memcg->css.cgroup,
+						  wait_for_flush);
 
-	cgroup_rstat_flush(memcg->css.cgroup);
+	if (mem_cgroup_is_root(memcg) && flushed)
+		    WRITE_ONCE(flush_last_time, jiffies_64);
+}
+
+static void __mem_cgroup_flush_stats(struct mem_cgroup *memcg,
+				     bool wait_for_flush)
+{
+	if (mem_cgroup_disabled())
+		return;
+
+	if (!memcg)
+		memcg = root_mem_cgroup;
+
+	if (memcg_vmstats_needs_flush(memcg->vmstats))
+		do_flush_stats(memcg, wait_for_flush);
 }
 
 /*
@@ -890,21 +904,19 @@  static void do_flush_stats(struct mem_cgroup *memcg)
  */
 void mem_cgroup_flush_stats(struct mem_cgroup *memcg)
 {
-	if (mem_cgroup_disabled())
-		return;
-
-	if (!memcg)
-		memcg = root_mem_cgroup;
+	__mem_cgroup_flush_stats(memcg, true);
+}
 
-	if (memcg_vmstats_needs_flush(memcg->vmstats))
-		do_flush_stats(memcg);
+void mem_cgroup_flush_stats_relaxed(struct mem_cgroup *memcg)
+{
+	__mem_cgroup_flush_stats(memcg, false);
 }
 
 void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg)
 {
 	/* Only flush if the periodic flusher is one full cycle late */
 	if (time_after64(jiffies_64, READ_ONCE(flush_last_time) + 2*FLUSH_TIME))
-		mem_cgroup_flush_stats(memcg);
+		mem_cgroup_flush_stats_relaxed(memcg);
 }
 
 static void flush_memcg_stats_dwork(struct work_struct *w)
@@ -913,7 +925,7 @@  static void flush_memcg_stats_dwork(struct work_struct *w)
 	 * Deliberately ignore memcg_vmstats_needs_flush() here so that flushing
 	 * in latency-sensitive paths is as cheap as possible.
 	 */
-	do_flush_stats(root_mem_cgroup);
+	do_flush_stats(root_mem_cgroup, false);
 	queue_delayed_work(system_unbound_wq, &stats_flush_dwork, FLUSH_TIME);
 }
 
@@ -8369,7 +8381,7 @@  bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
 		 * mem_cgroup_flush_stats() ignores small changes. Use
 		 * do_flush_stats() directly to get accurate stats for charging.
 		 */
-		do_flush_stats(memcg);
+		do_flush_stats(memcg, true);
 		pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
 		if (pages < max)
 			continue;
diff --git a/mm/vmscan.c b/mm/vmscan.c
index 2e34de9cd0d4..ab1411545572 100644
--- a/mm/vmscan.c
+++ b/mm/vmscan.c
@@ -2247,7 +2247,7 @@  static void prepare_scan_control(pg_data_t *pgdat, struct scan_control *sc)
 	 * Flush the memory cgroup stats, so that we read accurate per-memcg
 	 * lruvec stats for heuristics.
 	 */
-	mem_cgroup_flush_stats(sc->target_mem_cgroup);
+	mem_cgroup_flush_stats_relaxed(sc->target_mem_cgroup);
 
 	/*
 	 * Determine the scan balance between anon and file LRUs.
diff --git a/mm/zswap.c b/mm/zswap.c
index a50e2986cd2f..db72afe37ba2 100644
--- a/mm/zswap.c
+++ b/mm/zswap.c
@@ -1237,7 +1237,7 @@  static unsigned long zswap_shrinker_count(struct shrinker *shrinker,
 	 * Without memcg, use the zswap pool-wide metrics.
 	 */
 	if (!mem_cgroup_disabled()) {
-		mem_cgroup_flush_stats(memcg);
+		mem_cgroup_flush_stats_relaxed(memcg);
 		nr_backing = memcg_page_state(memcg, MEMCG_ZSWAP_B) >> PAGE_SHIFT;
 		nr_stored = memcg_page_state(memcg, MEMCG_ZSWAPPED);
 	} else {