From nobody Fri Jan 2 17:11:02 2026 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id D6329CD68EB for ; Tue, 10 Oct 2023 03:21:36 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1441976AbjJJDVa (ORCPT ); Mon, 9 Oct 2023 23:21:30 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:34808 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1441959AbjJJDVY (ORCPT ); Mon, 9 Oct 2023 23:21:24 -0400 Received: from mail-yb1-xb49.google.com (mail-yb1-xb49.google.com [IPv6:2607:f8b0:4864:20::b49]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id D0C1BA6 for ; Mon, 9 Oct 2023 20:21:22 -0700 (PDT) Received: by mail-yb1-xb49.google.com with SMTP id 3f1490d57ef6-c647150c254so4608763276.1 for ; Mon, 09 Oct 2023 20:21:22 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1696908082; x=1697512882; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=Txx2Z/24+3F8Cj+NRtOMU7JL27MtRQwWcbI2dA3u7/E=; b=hy3FXdt8nWVJipZ9sJI1zwZLXulM+5YQg9PMfnYfavjXBk8VGzkYlmS8Qb125iXUSl g6PicacYZEPQwKF+4trujJz25wAL1a2U834PrTEI43SKtjX2DaT+cs90cca+vBxo38FB XJwsFsg1ORFgE/3KICaUNMJPqvUUqK/JIj4rzqC6C25SPFs6YxaNnkAPS/wD8H5mg136 Gact1W1Mw5lNbkByEYOyHkmUSGkf48rQSS8cAbG3beVTSPuambGxRiojimDiYIrC39ZK YxiWLnPTQ3epuFWNhEfuQBxTVnsgl9KA1FUci227Sp3W9eafgObnJISqSVEzjP2/itYr HavQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1696908082; x=1697512882; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=Txx2Z/24+3F8Cj+NRtOMU7JL27MtRQwWcbI2dA3u7/E=; b=TTKXgXNn9zJulFxjA2xqQnZB88r3+bONQPzH7858K4cYlAtJZ0QeH35MXjeUEVRbkG FCbqtkqU2OInzmGpKkeR0Z6BgjTLCZ5uiKO2637kAa3vEAuAqhRT+S+Sp089H57L7FAi nFNHSXi4ChrBsNezBcLh7VFVVVvjEB4NKDvXtCDNQsZr26wF7iGMgoLk2VFPp41QB0zB p1iBrJVhTx7jAe6Mym+UO0uTJP7l0wBocoX1Ws4PKfo0KTP5+7hL7QJW7OefCWgZpbPD +yT7oYVTPSjO+//lNK61PUqnN0jkAvlz9viKHyoXdk1OdNaev6n+QfwaCDQseTLfQqo1 rx9w== X-Gm-Message-State: AOJu0YyJ1TBfZztR+8bkrJWYd+Z9q4WnfG4WfjojqaIQF1Y8jX+06Z5W r0NIXHGkyjIEY25HJY/VDS+psqrVPR2WepBe X-Google-Smtp-Source: AGHT+IHSbb76MuDQgDE4hYiCssfBhZ3erWto8iacOIEWAeUiJ3Vxcha6qRANQmltbAbW17YqbUuNXt2O9PobRH8R X-Received: from yosry.c.googlers.com ([fda3:e722:ac3:cc00:20:ed76:c0a8:29b4]) (user=yosryahmed job=sendgmr) by 2002:a25:824f:0:b0:d9a:66eb:b516 with SMTP id d15-20020a25824f000000b00d9a66ebb516mr1411ybn.6.1696908082104; Mon, 09 Oct 2023 20:21:22 -0700 (PDT) Date: Tue, 10 Oct 2023 03:21:12 +0000 In-Reply-To: <20231010032117.1577496-1-yosryahmed@google.com> Mime-Version: 1.0 References: <20231010032117.1577496-1-yosryahmed@google.com> X-Mailer: git-send-email 2.42.0.609.gbb76f46606-goog Message-ID: <20231010032117.1577496-2-yosryahmed@google.com> Subject: [PATCH v2 1/5] mm: memcg: change flush_next_time to flush_last_time From: Yosry Ahmed To: Andrew Morton Cc: Johannes Weiner , Michal Hocko , Roman Gushchin , Shakeel Butt , Muchun Song , Ivan Babrou , Tejun Heo , "=?UTF-8?q?Michal=20Koutn=C3=BD?=" , Waiman Long , kernel-team@cloudflare.com, Wei Xu , Greg Thelen , linux-mm@kvack.org, cgroups@vger.kernel.org, linux-kernel@vger.kernel.org, Yosry Ahmed Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" flush_next_time is an inaccurate name. It's not the next time that periodic flushing will happen, it's rather the next time that ratelimited flushing can happen if the periodic flusher is late. Simplify its semantics by just storing the timestamp of the last flush instead, flush_last_time. Move the 2*FLUSH_TIME addition to mem_cgroup_flush_stats_ratelimited(), and add a comment explaining it. This way, all the ratelimiting semantics live in one place. No functional change intended. Signed-off-by: Yosry Ahmed Tested-by: Domenico Cerasuolo --- mm/memcontrol.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/mm/memcontrol.c b/mm/memcontrol.c index 2fb30abaf267..4a194fcc9533 100644 --- a/mm/memcontrol.c +++ b/mm/memcontrol.c @@ -590,7 +590,7 @@ static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush= _memcg_stats_dwork); static DEFINE_PER_CPU(unsigned int, stats_updates); static atomic_t stats_flush_ongoing =3D ATOMIC_INIT(0); static atomic_t stats_flush_threshold =3D ATOMIC_INIT(0); -static u64 flush_next_time; +static u64 flush_last_time; =20 #define FLUSH_TIME (2UL*HZ) =20 @@ -650,7 +650,7 @@ static void do_flush_stats(void) atomic_xchg(&stats_flush_ongoing, 1)) return; =20 - WRITE_ONCE(flush_next_time, jiffies_64 + 2*FLUSH_TIME); + WRITE_ONCE(flush_last_time, jiffies_64); =20 cgroup_rstat_flush(root_mem_cgroup->css.cgroup); =20 @@ -666,7 +666,8 @@ void mem_cgroup_flush_stats(void) =20 void mem_cgroup_flush_stats_ratelimited(void) { - if (time_after64(jiffies_64, READ_ONCE(flush_next_time))) + /* 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(); } =20 --=20 2.42.0.609.gbb76f46606-goog From nobody Fri Jan 2 17:11:02 2026 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 1D775CD68EA for ; Tue, 10 Oct 2023 03:21:37 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1441991AbjJJDVc (ORCPT ); Mon, 9 Oct 2023 23:21:32 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:37672 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1441967AbjJJDV0 (ORCPT ); Mon, 9 Oct 2023 23:21:26 -0400 Received: from mail-yb1-xb49.google.com (mail-yb1-xb49.google.com [IPv6:2607:f8b0:4864:20::b49]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id A7AF59E for ; Mon, 9 Oct 2023 20:21:24 -0700 (PDT) Received: by mail-yb1-xb49.google.com with SMTP id 3f1490d57ef6-d9a4a89ab5fso789591276.3 for ; Mon, 09 Oct 2023 20:21:24 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1696908084; x=1697512884; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=hC1pWunCMBCtxVf3YGG9j/q6Xl3rVbI2nQig93EJD1c=; b=yJL49vSJJ4IGXvINefEv9WQidpmtBVzYC6kKfAJ4r62g3i0soq5k5DBOcEv/Jfvg4b PpiV7IkuaHNDFyvHkDdUOhhQbcXN/OkwnsgYpQ3xuCtLxKn0ObQWP+RiCgYwQXPPWH4m 42DZvp5VZQQpDhVbD3SQYoeHoAIknD8NcNYSyAOl31isjOMXEmozxbblWsrIFjirPfEI lwBoTPshl2GSB5kxC6SPLir6nUQYpjMiVD1jW5taP2CmmJL5xTUMP3kG9IlSev42XwnQ zONR2NHp8+QKb5+B3o4562VgWZkbU4aW54d0NKQNBYaZoJOUPjIfJnbZ3S5AhY14Jlen MsTg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1696908084; x=1697512884; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=hC1pWunCMBCtxVf3YGG9j/q6Xl3rVbI2nQig93EJD1c=; b=rUr32wM+tXbzu6iW/dZ5DK+2strRctRpghKsenbVWIgD1m2uthjB83/s4xLL2yILEA KFTXAd2qmnYxt9RgtdAu1ypfsM88tPqnqhET3/kWD2C35W79z7xbw2X26pSJAkDjRhDw PO6wHjK/YEIg7xaCUgK3BvDhq44Pd6Jw8+u0E+UhdthFtUhUfoPL7X8Jg0UZ+ZtaX4sU s1z6WdnIX/k0krOEF4f9jlXAO8zF8zDeEAFRTEYxvNFQH63Iunu5hvGFXWdhKhSRAEV3 0yBnRMcWdP+cMdM8ACPXJGtUm4iWpGAZ+PQCsiiFGoL8O0VledkTytkxXfo0Zhn2OpQW xUww== X-Gm-Message-State: AOJu0YwkGh4cH1hYBCCq1YGAzbAI60Clqbyd4Gxp/FgLAnaj56jQCDff yAYqrVJkUxCC5H5E2B4PjG6WK+GT16IPn1I4 X-Google-Smtp-Source: AGHT+IFIrbr9jnt8AKgjFXbiV/tkMci7vpdggI/qLBKz9UQMIl0xyavjRIGPF8xVVyjEs532DFKybC2OPjpal40i X-Received: from yosry.c.googlers.com ([fda3:e722:ac3:cc00:20:ed76:c0a8:29b4]) (user=yosryahmed job=sendgmr) by 2002:a5b:b50:0:b0:d80:904d:c211 with SMTP id b16-20020a5b0b50000000b00d80904dc211mr250724ybr.7.1696908083837; Mon, 09 Oct 2023 20:21:23 -0700 (PDT) Date: Tue, 10 Oct 2023 03:21:13 +0000 In-Reply-To: <20231010032117.1577496-1-yosryahmed@google.com> Mime-Version: 1.0 References: <20231010032117.1577496-1-yosryahmed@google.com> X-Mailer: git-send-email 2.42.0.609.gbb76f46606-goog Message-ID: <20231010032117.1577496-3-yosryahmed@google.com> Subject: [PATCH v2 2/5] mm: memcg: move vmstats structs definition above flushing code From: Yosry Ahmed To: Andrew Morton Cc: Johannes Weiner , Michal Hocko , Roman Gushchin , Shakeel Butt , Muchun Song , Ivan Babrou , Tejun Heo , "=?UTF-8?q?Michal=20Koutn=C3=BD?=" , Waiman Long , kernel-team@cloudflare.com, Wei Xu , Greg Thelen , linux-mm@kvack.org, cgroups@vger.kernel.org, linux-kernel@vger.kernel.org, Yosry Ahmed Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" The following patch will make use of those structs in the flushing code, so move their definitions (and a few other dependencies) a little bit up to reduce the diff noise in the following patch. No functional change intended. Signed-off-by: Yosry Ahmed Tested-by: Domenico Cerasuolo --- mm/memcontrol.c | 146 ++++++++++++++++++++++++------------------------ 1 file changed, 73 insertions(+), 73 deletions(-) diff --git a/mm/memcontrol.c b/mm/memcontrol.c index 4a194fcc9533..a393f1399a2b 100644 --- a/mm/memcontrol.c +++ b/mm/memcontrol.c @@ -570,6 +570,79 @@ mem_cgroup_largest_soft_limit_node(struct mem_cgroup_t= ree_per_node *mctz) return mz; } =20 +/* Subset of vm_event_item to report for memcg event stats */ +static const unsigned int memcg_vm_event_stat[] =3D { + PGPGIN, + PGPGOUT, + PGSCAN_KSWAPD, + PGSCAN_DIRECT, + PGSCAN_KHUGEPAGED, + PGSTEAL_KSWAPD, + PGSTEAL_DIRECT, + PGSTEAL_KHUGEPAGED, + PGFAULT, + PGMAJFAULT, + PGREFILL, + PGACTIVATE, + PGDEACTIVATE, + PGLAZYFREE, + PGLAZYFREED, +#if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP) + ZSWPIN, + ZSWPOUT, +#endif +#ifdef CONFIG_TRANSPARENT_HUGEPAGE + THP_FAULT_ALLOC, + THP_COLLAPSE_ALLOC, + THP_SWPOUT, + THP_SWPOUT_FALLBACK, +#endif +}; + +#define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat) +static int mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly; + +static void init_memcg_events(void) +{ + int i; + + for (i =3D 0; i < NR_MEMCG_EVENTS; ++i) + mem_cgroup_events_index[memcg_vm_event_stat[i]] =3D i + 1; +} + +static inline int memcg_events_index(enum vm_event_item idx) +{ + return mem_cgroup_events_index[idx] - 1; +} + +struct memcg_vmstats_percpu { + /* Local (CPU and cgroup) page state & events */ + long state[MEMCG_NR_STAT]; + unsigned long events[NR_MEMCG_EVENTS]; + + /* Delta calculation for lockless upward propagation */ + long state_prev[MEMCG_NR_STAT]; + unsigned long events_prev[NR_MEMCG_EVENTS]; + + /* Cgroup1: threshold notifications & softlimit tree updates */ + unsigned long nr_page_events; + unsigned long targets[MEM_CGROUP_NTARGETS]; +}; + +struct memcg_vmstats { + /* Aggregated (CPU and subtree) page state & events */ + long state[MEMCG_NR_STAT]; + unsigned long events[NR_MEMCG_EVENTS]; + + /* Non-hierarchical (CPU aggregated) page state & events */ + long state_local[MEMCG_NR_STAT]; + unsigned long events_local[NR_MEMCG_EVENTS]; + + /* Pending child counts during tree propagation */ + long state_pending[MEMCG_NR_STAT]; + unsigned long events_pending[NR_MEMCG_EVENTS]; +}; + /* * memcg and lruvec stats flushing * @@ -681,79 +754,6 @@ static void flush_memcg_stats_dwork(struct work_struct= *w) queue_delayed_work(system_unbound_wq, &stats_flush_dwork, FLUSH_TIME); } =20 -/* Subset of vm_event_item to report for memcg event stats */ -static const unsigned int memcg_vm_event_stat[] =3D { - PGPGIN, - PGPGOUT, - PGSCAN_KSWAPD, - PGSCAN_DIRECT, - PGSCAN_KHUGEPAGED, - PGSTEAL_KSWAPD, - PGSTEAL_DIRECT, - PGSTEAL_KHUGEPAGED, - PGFAULT, - PGMAJFAULT, - PGREFILL, - PGACTIVATE, - PGDEACTIVATE, - PGLAZYFREE, - PGLAZYFREED, -#if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_ZSWAP) - ZSWPIN, - ZSWPOUT, -#endif -#ifdef CONFIG_TRANSPARENT_HUGEPAGE - THP_FAULT_ALLOC, - THP_COLLAPSE_ALLOC, - THP_SWPOUT, - THP_SWPOUT_FALLBACK, -#endif -}; - -#define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat) -static int mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly; - -static void init_memcg_events(void) -{ - int i; - - for (i =3D 0; i < NR_MEMCG_EVENTS; ++i) - mem_cgroup_events_index[memcg_vm_event_stat[i]] =3D i + 1; -} - -static inline int memcg_events_index(enum vm_event_item idx) -{ - return mem_cgroup_events_index[idx] - 1; -} - -struct memcg_vmstats_percpu { - /* Local (CPU and cgroup) page state & events */ - long state[MEMCG_NR_STAT]; - unsigned long events[NR_MEMCG_EVENTS]; - - /* Delta calculation for lockless upward propagation */ - long state_prev[MEMCG_NR_STAT]; - unsigned long events_prev[NR_MEMCG_EVENTS]; - - /* Cgroup1: threshold notifications & softlimit tree updates */ - unsigned long nr_page_events; - unsigned long targets[MEM_CGROUP_NTARGETS]; -}; - -struct memcg_vmstats { - /* Aggregated (CPU and subtree) page state & events */ - long state[MEMCG_NR_STAT]; - unsigned long events[NR_MEMCG_EVENTS]; - - /* Non-hierarchical (CPU aggregated) page state & events */ - long state_local[MEMCG_NR_STAT]; - unsigned long events_local[NR_MEMCG_EVENTS]; - - /* Pending child counts during tree propagation */ - long state_pending[MEMCG_NR_STAT]; - unsigned long events_pending[NR_MEMCG_EVENTS]; -}; - unsigned long memcg_page_state(struct mem_cgroup *memcg, int idx) { long x =3D READ_ONCE(memcg->vmstats->state[idx]); --=20 2.42.0.609.gbb76f46606-goog From nobody Fri Jan 2 17:11:02 2026 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 2668ECD68E6 for ; Tue, 10 Oct 2023 03:21:40 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1441977AbjJJDVi (ORCPT ); Mon, 9 Oct 2023 23:21:38 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:37722 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1441974AbjJJDV3 (ORCPT ); Mon, 9 Oct 2023 23:21:29 -0400 Received: from mail-yw1-x1149.google.com (mail-yw1-x1149.google.com [IPv6:2607:f8b0:4864:20::1149]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 6596AAC for ; Mon, 9 Oct 2023 20:21:26 -0700 (PDT) Received: by mail-yw1-x1149.google.com with SMTP id 00721157ae682-59f61a639b9so80191267b3.1 for ; Mon, 09 Oct 2023 20:21:26 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1696908085; x=1697512885; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=XEDO979juocfA6e748Gdg1ojA/11BVhtMp+K0OvWH0c=; b=cFy98PfiP1+ILre97PV1XvTfRsee/TTpqaTzPcb3lr1BPgIL0Ad5lTdIa415wsXVHg HuB/Hj3rQnaFIaGVZqqCy4MoHYCCZcPUekhXpQ/enyXWmNWV64aiUWHTE0Xz54v4r4HW B8CI2VOMQuGIyT13hvqx5JsRUnTfTVdXmX731migJxMCa8/oE7DOCuZskaK+GgEjP8u2 LIumpbii48bruRrZMfoHp/IbZJjd17RSQGfidbFMBzQEKdg9+PovxJhfNQ+KCPEXbD5U UnohDJ+VYmnYzffFzV/yWz4u1niGoDp/JhjHjhV8QUEOzsHaKe89SDIP3n0HCU5vCutq A4dQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1696908085; x=1697512885; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=XEDO979juocfA6e748Gdg1ojA/11BVhtMp+K0OvWH0c=; b=IOyEfhchvqWyHNCrsrm4VbkIaPvD6r39jGRESE8RrDcA8vBC1QWUtAg0/kHn0cAirt 7bw5Q0Yuh43ql+U2NLNYuoHGUbia9DsC7SY+US8/l7dD/5bSrGU/pY80qkkPV8ShQ+Q4 yrQJYMtlK0Nto8+6C5JNlvlNaRPG5BPRPT/iJHggCzCiimJHDzUMiKRMGTS5Q9fA+MoJ w47i8d8lWbyJYMrcHkdrHuILBwQ9l5VigCbjDmStk0UWDZ0Rrh4p+bu2E4TNTlCoRpdu CMyGpXszHvhvxigAs08F33wDCdwNpbJpRXlski0mrY+NAxTZjf1dXSn//IGuT150g2hM 0NOQ== X-Gm-Message-State: AOJu0YzBidz/GFGplZ/pU5C0LuCDh/1W5FaM1s4H6wgLz7S1+CRpnj4a 6aCiLiBh+3lwYUOHPvVE0m8XDNWSZwAljXnx X-Google-Smtp-Source: AGHT+IG8kcJ/dn9Ahg31ZEvjLGaGuCajxb48R9RWsECmkth4fjZtYHFlyQOjLuGiUbhEeB/vJfn9WBvb6ywt7IeI X-Received: from yosry.c.googlers.com ([fda3:e722:ac3:cc00:20:ed76:c0a8:29b4]) (user=yosryahmed job=sendgmr) by 2002:a81:b209:0:b0:59b:e1db:562c with SMTP id q9-20020a81b209000000b0059be1db562cmr319164ywh.5.1696908085640; Mon, 09 Oct 2023 20:21:25 -0700 (PDT) Date: Tue, 10 Oct 2023 03:21:14 +0000 In-Reply-To: <20231010032117.1577496-1-yosryahmed@google.com> Mime-Version: 1.0 References: <20231010032117.1577496-1-yosryahmed@google.com> X-Mailer: git-send-email 2.42.0.609.gbb76f46606-goog Message-ID: <20231010032117.1577496-4-yosryahmed@google.com> Subject: [PATCH v2 3/5] mm: memcg: make stats flushing threshold per-memcg From: Yosry Ahmed To: Andrew Morton Cc: Johannes Weiner , Michal Hocko , Roman Gushchin , Shakeel Butt , Muchun Song , Ivan Babrou , Tejun Heo , "=?UTF-8?q?Michal=20Koutn=C3=BD?=" , Waiman Long , kernel-team@cloudflare.com, Wei Xu , Greg Thelen , linux-mm@kvack.org, cgroups@vger.kernel.org, linux-kernel@vger.kernel.org, Yosry Ahmed Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" A global counter for the magnitude of memcg stats update is maintained on the memcg side to avoid invoking rstat flushes when the pending updates are not significant. This avoids unnecessary flushes, which are not very cheap even if there isn't a lot of stats to flush. It also avoids unnecessary lock contention on the underlying global rstat lock. Make this threshold per-memcg. The scheme is followed where percpu (now also per-memcg) counters are incremented in the update path, and only propagated to per-memcg atomics when they exceed a certain threshold. This provides two benefits: (a) On large machines with a lot of memcgs, the global threshold can be reached relatively fast, so guarding the underlying lock becomes less effective. Making the threshold per-memcg avoids this. (b) Having a global threshold makes it hard to do subtree flushes, as we cannot reset the global counter except for a full flush. Per-memcg counters removes this as a blocker from doing subtree flushes, which helps avoid unnecessary work when the stats of a small subtree are needed. Nothing is free, of course. This comes at a cost: (a) A new per-cpu counter per memcg, consuming NR_CPUS * NR_MEMCGS * 4 bytes. The extra memory usage is insigificant. (b) More work on the update side, although in the common case it will only be percpu counter updates. The amount of work scales with the number of ancestors (i.e. tree depth). This is not a new concept, adding a cgroup to the rstat tree involves a parent loop, so is charging. Testing results below show no significant regressions. (c) The error margin in the stats for the system as a whole increases from NR_CPUS * MEMCG_CHARGE_BATCH to NR_CPUS * MEMCG_CHARGE_BATCH * NR_MEMCGS. This is probably fine because we have a similar per-memcg error in charges coming from percpu stocks, and we have a periodic flusher that makes sure we always flush all the stats every 2s anyway. This patch was tested to make sure no significant regressions are introduced on the update path as follows. The following benchmarks were ran in a cgroup that is 4 levels deep (/sys/fs/cgroup/a/b/c/d), which is deeper than a usual setup: (a) neper [1] with 1000 flows and 100 threads (single machine). The values in the table are the average of server and client throughputs in mbps after 30 iterations, each running for 30s: tcp_rr tcp_stream Base 9504218.56 357366.84 Patched 9656205.68 356978.39 Delta +1.6% -0.1% Standard Deviation 0.95% 1.03% An increase in the performance of tcp_rr doesn't really make sense, but it's probably in the noise. The same tests were ran with 1 flow and 1 thread but the throughput was too noisy to make any conclusions (the averages did not show regressions nonetheless). Looking at perf for one iteration of the above test, __mod_memcg_state() (which is where memcg_rstat_updated() is called) does not show up at all without this patch, but it shows up with this patch as 1.06% for tcp_rr and 0.36% for tcp_stream. (b) "stress-ng --vm 0 -t 1m --times --perf". I don't understand stress-ng very well, so I am not sure that's the best way to test this, but it spawns 384 workers and spits a lot of metrics which looks nice :) I picked a few ones that seem to be relevant to the stats update path. I also included cache misses as this patch introduce more atomics that may bounce between cpu caches: Metric Base Patched Delta Cache Misses 3.394 B/sec 3.433 B/sec +1.14% Cache L1D Read 0.148 T/sec 0.154 T/sec +4.05% Cache L1D Read Miss 20.430 B/sec 21.820 B/sec +6.8% Page Faults Total 4.304 M/sec 4.535 M/sec +5.4% Page Faults Minor 4.304 M/sec 4.535 M/sec +5.4% Page Faults Major 18.794 /sec 0.000 /sec Kmalloc 0.153 M/sec 0.152 M/sec -0.65% Kfree 0.152 M/sec 0.153 M/sec +0.65% MM Page Alloc 4.640 M/sec 4.898 M/sec +5.56% MM Page Free 4.639 M/sec 4.897 M/sec +5.56% Lock Contention Begin 0.362 M/sec 0.479 M/sec +32.32% Lock Contention End 0.362 M/sec 0.479 M/sec +32.32% page-cache add 238.057 /sec 0.000 /sec page-cache del 6.265 /sec 6.267 /sec -0.03% This is only using a single run in each case. I am not sure what to make out of most of these numbers, but they mostly seem in the noise (some better, some worse). The lock contention numbers are interesting. I am not sure if higher is better or worse here. No new locks or lock sections are introduced by this patch either way. Looking at perf, __mod_memcg_state() shows up as 0.00% with and without this patch. This is suspicious, but I verified while stress-ng is running that all the threads are in the right cgroup. (3) will-it-scale page_fault tests. These tests (specifically per_process_ops in page_fault3 test) detected a 25.9% regression before for a change in the stats update path [2]. These are the numbers from 30 runs (+ is good): LABEL | MEAN | MEDIAN | STDDEV | Suggested-by if appropriate :) Suggested-by. Suggested-by: Wei Xu Tested-by: Domenico Cerasuolo ------------------------------+-------------+-------------+------------- page_fault1_per_process_ops | | | | (A) base | 265207.738 | 262941.000 | 12112.379 | (B) patched | 249249.191 | 248781.000 | 8767.457 | | -6.02% | -5.39% | | page_fault1_per_thread_ops | | | | (A) base | 241618.484 | 240209.000 | 10162.207 | (B) patched | 229820.671 | 229108.000 | 7506.582 | | -4.88% | -4.62% | | page_fault1_scalability | | | (A) base | 0.03545 | 0.035705 | 0.0015837 | (B) patched | 0.029952 | 0.029957 | 0.0013551 | | -9.29% | -9.35% | | page_fault2_per_process_ops | | | (A) base | 203916.148 | 203496.000 | 2908.331 | (B) patched | 186975.419 | 187023.000 | 1991.100 | | -6.85% | -6.90% | | page_fault2_per_thread_ops | | | (A) base | 170604.972 | 170532.000 | 1624.834 | (B) patched | 163100.260 | 163263.000 | 1517.967 | | -4.40% | -4.26% | | page_fault2_scalability | | | (A) base | 0.054603 | 0.054693 | 0.00080196 | (B) patched | 0.044882 | 0.044957 | 0.0011766 | | -0.05% | +0.33% | | page_fault3_per_process_ops | | | (A) base | 1299821.099 | 1297918.000 | 9882.872 | (B) patched | 1248700.839 | 1247168.000 | 8454.891 | | -3.93% | -3.91% | | page_fault3_per_thread_ops | | | (A) base | 387216.963 | 387115.000 | 1605.760 | (B) patched | 368538.213 | 368826.000 | 1852.594 | | -4.82% | -4.72% | | page_fault3_scalability | | | (A) base | 0.59909 | 0.59367 | 0.01256 | (B) patched | 0.59995 | 0.59769 | 0.010088 | | +0.14% | +0.68% | | There is some microbenchmarks regressions (and some minute improvements), but nothing outside the normal variance of this benchmark between kernel versions. The fix for [2] assumes that 3% is noise -- and there were no further practical complaints), so hopefully this means that such variations in these microbenchmarks do not reflect on practical workloads. [1]https://github.com/google/neper [2]https://lore.kernel.org/all/20190520063534.GB19312@shao2-debian/ Signed-off-by: Yosry Ahmed --- mm/memcontrol.c | 49 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/mm/memcontrol.c b/mm/memcontrol.c index a393f1399a2b..9a586893bd3e 100644 --- a/mm/memcontrol.c +++ b/mm/memcontrol.c @@ -627,6 +627,9 @@ struct memcg_vmstats_percpu { /* Cgroup1: threshold notifications & softlimit tree updates */ unsigned long nr_page_events; unsigned long targets[MEM_CGROUP_NTARGETS]; + + /* Stats updates since the last flush */ + unsigned int stats_updates; }; =20 struct memcg_vmstats { @@ -641,6 +644,9 @@ struct memcg_vmstats { /* Pending child counts during tree propagation */ long state_pending[MEMCG_NR_STAT]; unsigned long events_pending[NR_MEMCG_EVENTS]; + + /* Stats updates since the last flush */ + atomic64_t stats_updates; }; =20 /* @@ -660,9 +666,7 @@ struct memcg_vmstats { */ static void flush_memcg_stats_dwork(struct work_struct *w); static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork); -static DEFINE_PER_CPU(unsigned int, stats_updates); static atomic_t stats_flush_ongoing =3D ATOMIC_INIT(0); -static atomic_t stats_flush_threshold =3D ATOMIC_INIT(0); static u64 flush_last_time; =20 #define FLUSH_TIME (2UL*HZ) @@ -689,26 +693,37 @@ static void memcg_stats_unlock(void) preempt_enable_nested(); } =20 + +static bool memcg_should_flush_stats(struct mem_cgroup *memcg) +{ + return atomic64_read(&memcg->vmstats->stats_updates) > + MEMCG_CHARGE_BATCH * num_online_cpus(); +} + static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val) { + int cpu =3D smp_processor_id(); unsigned int x; =20 if (!val) return; =20 - cgroup_rstat_updated(memcg->css.cgroup, smp_processor_id()); + cgroup_rstat_updated(memcg->css.cgroup, cpu); + + for (; memcg; memcg =3D parent_mem_cgroup(memcg)) { + x =3D __this_cpu_add_return(memcg->vmstats_percpu->stats_updates, + abs(val)); + + if (x < MEMCG_CHARGE_BATCH) + continue; =20 - x =3D __this_cpu_add_return(stats_updates, abs(val)); - if (x > MEMCG_CHARGE_BATCH) { /* - * If stats_flush_threshold exceeds the threshold - * (>num_online_cpus()), cgroup stats update will be triggered - * in __mem_cgroup_flush_stats(). Increasing this var further - * is redundant and simply adds overhead in atomic update. + * If @memcg is already flush-able, increasing stats_updates is + * redundant. Avoid the overhead of the atomic update. */ - if (atomic_read(&stats_flush_threshold) <=3D num_online_cpus()) - atomic_add(x / MEMCG_CHARGE_BATCH, &stats_flush_threshold); - __this_cpu_write(stats_updates, 0); + if (!memcg_should_flush_stats(memcg)) + atomic64_add(x, &memcg->vmstats->stats_updates); + __this_cpu_write(memcg->vmstats_percpu->stats_updates, 0); } } =20 @@ -727,13 +742,12 @@ static void do_flush_stats(void) =20 cgroup_rstat_flush(root_mem_cgroup->css.cgroup); =20 - atomic_set(&stats_flush_threshold, 0); atomic_set(&stats_flush_ongoing, 0); } =20 void mem_cgroup_flush_stats(void) { - if (atomic_read(&stats_flush_threshold) > num_online_cpus()) + if (memcg_should_flush_stats(root_mem_cgroup)) do_flush_stats(); } =20 @@ -747,8 +761,8 @@ void mem_cgroup_flush_stats_ratelimited(void) static void flush_memcg_stats_dwork(struct work_struct *w) { /* - * Always flush here so that flushing in latency-sensitive paths is - * as cheap as possible. + * Deliberately ignore memcg_should_flush_stats() here so that flushing + * in latency-sensitive paths is as cheap as possible. */ do_flush_stats(); queue_delayed_work(system_unbound_wq, &stats_flush_dwork, FLUSH_TIME); @@ -5803,6 +5817,9 @@ static void mem_cgroup_css_rstat_flush(struct cgroup_= subsys_state *css, int cpu) } } } + /* We are in a per-cpu loop here, only do the atomic write once */ + if (atomic64_read(&memcg->vmstats->stats_updates)) + atomic64_set(&memcg->vmstats->stats_updates, 0); } =20 #ifdef CONFIG_MMU --=20 2.42.0.609.gbb76f46606-goog From nobody Fri Jan 2 17:11:02 2026 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id C3EEACD68E3 for ; Tue, 10 Oct 2023 03:21:46 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1441961AbjJJDVn (ORCPT ); Mon, 9 Oct 2023 23:21:43 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:37738 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1441979AbjJJDVb (ORCPT ); Mon, 9 Oct 2023 23:21:31 -0400 Received: from mail-yw1-x1149.google.com (mail-yw1-x1149.google.com [IPv6:2607:f8b0:4864:20::1149]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 0E168B0 for ; Mon, 9 Oct 2023 20:21:28 -0700 (PDT) Received: by mail-yw1-x1149.google.com with SMTP id 00721157ae682-5a21c283542so89924587b3.3 for ; Mon, 09 Oct 2023 20:21:28 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1696908087; x=1697512887; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=2uIMTmtGdqUKunPgdDdu073V0kaqxVUtvtbHday0wrc=; b=Wlih9CQgTOSvCKOUzBNw+I6e5fdxI5H5mgw3wf4O4qOlCsNqIz8xShIwVneez9K8RU 74SQf01um+Dyv4V+JsZUgP72iakse/Girf5eZ3AyQAqUCgZYYWOyZ1pLcDzl5H9e3N7d qlDN3G1NI7pyW1HNBmelKPSYtNtXbUGTE9LNIhOS2TQ86BPdXUrc2UCTOuY4EzjFyQVg c+dFBYyoZ1/juzjX7gfMx3UHqGyVGLE7nPI2xNmZm0qkCJ70i0JTNjbWwLIGLNbRU940 QBg6TsdP29BH15jEjNz3jejJYb0BmZK/swihy6HmGBlS0XzZU4tPqhtXM7ZSMQUHhexa Vz7A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1696908087; x=1697512887; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=2uIMTmtGdqUKunPgdDdu073V0kaqxVUtvtbHday0wrc=; b=CMUQmCsmNvvSFeaer6R6rVkJHs71eKuWtyfRqSJgLfXvq6LrE2jYP4000MACX4vcSN jzLjaRmUGLGOe6sWY1tAbkD32myLoToA32vqKq7W4ugZST9cslXH7ThFBVuyF1Vk7ku7 iHMEEcjRVoTNDEYn0VliVw3J+1meC5A4IrJ+TWDAhhAmcJsnjUlbMV9oyxJ7LKJx43b0 NvT5BrsspUtWGKBbCGeqiajVwx22WnsH9MdzgBlMnK9rA7tNtMl4f4pUj2tozEQlHI1H di1HZO0ZJuRfXvZOtMuwumpMArR2hvKn7zUBupoFpwYdkWQTSvjHLHnj04Pa3O85wtYY IdiA== X-Gm-Message-State: AOJu0YzWOg+yYKaFbTlNS4fRww62IReuGplLfsVRSlFga0+lrk5PESXD kjyiumRcLjJyG6jA3DLQEnWucwpx+mZDSNh4 X-Google-Smtp-Source: AGHT+IH27StA7m2woHqh/tcnCp3uYnoxUCBEP5s+DN8GVWI1rrXovlh8AYsn+eA2pINcXrMN7noHvFZw+UL9M22y X-Received: from yosry.c.googlers.com ([fda3:e722:ac3:cc00:20:ed76:c0a8:29b4]) (user=yosryahmed job=sendgmr) by 2002:a81:c44c:0:b0:586:50cf:e13f with SMTP id s12-20020a81c44c000000b0058650cfe13fmr286393ywj.1.1696908087335; Mon, 09 Oct 2023 20:21:27 -0700 (PDT) Date: Tue, 10 Oct 2023 03:21:15 +0000 In-Reply-To: <20231010032117.1577496-1-yosryahmed@google.com> Mime-Version: 1.0 References: <20231010032117.1577496-1-yosryahmed@google.com> X-Mailer: git-send-email 2.42.0.609.gbb76f46606-goog Message-ID: <20231010032117.1577496-5-yosryahmed@google.com> Subject: [PATCH v2 4/5] mm: workingset: move the stats flush into workingset_test_recent() From: Yosry Ahmed To: Andrew Morton Cc: Johannes Weiner , Michal Hocko , Roman Gushchin , Shakeel Butt , Muchun Song , Ivan Babrou , Tejun Heo , "=?UTF-8?q?Michal=20Koutn=C3=BD?=" , Waiman Long , kernel-team@cloudflare.com, Wei Xu , Greg Thelen , linux-mm@kvack.org, cgroups@vger.kernel.org, linux-kernel@vger.kernel.org, Yosry Ahmed Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" The workingset code flushes the stats in workingset_refault() to get accurate stats of the eviction memcg. In preparation for more scoped flushed and passing the eviction memcg to the flush call, move the call to workingset_test_recent() where we have a pointer to the eviction memcg. The flush call is sleepable, and cannot be made in an rcu read section. Hence, minimize the rcu read section by also moving it into workingset_test_recent(). Furthermore, instead of holding the rcu read lock throughout workingset_test_recent(), only hold it briefly to get a ref on the eviction memcg. This allows us to make the flush call after we get the eviction memcg. As for workingset_refault(), nothing else there appears to be protected by rcu. The memcg of the faulted folio (which is not necessarily the same as the eviction memcg) is protected by the folio lock, which is held from all callsites. Add a VM_BUG_ON() to make sure this doesn't change from under us. No functional change intended. Signed-off-by: Yosry Ahmed Tested-by: Domenico Cerasuolo --- mm/workingset.c | 36 ++++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/mm/workingset.c b/mm/workingset.c index b192e44a0e7c..a573be6c59fd 100644 --- a/mm/workingset.c +++ b/mm/workingset.c @@ -425,8 +425,16 @@ bool workingset_test_recent(void *shadow, bool file, b= ool *workingset) struct pglist_data *pgdat; unsigned long eviction; =20 - if (lru_gen_enabled()) - return lru_gen_test_recent(shadow, file, &eviction_lruvec, &eviction, wo= rkingset); + rcu_read_lock(); + + if (lru_gen_enabled()) { + bool recent =3D lru_gen_test_recent(shadow, file, + &eviction_lruvec, &eviction, workingset); + + rcu_read_unlock(); + return recent; + } + =20 unpack_shadow(shadow, &memcgid, &pgdat, &eviction, workingset); eviction <<=3D bucket_order; @@ -448,8 +456,16 @@ bool workingset_test_recent(void *shadow, bool file, b= ool *workingset) * configurations instead. */ eviction_memcg =3D mem_cgroup_from_id(memcgid); - if (!mem_cgroup_disabled() && !eviction_memcg) + if (!mem_cgroup_disabled() && + (!eviction_memcg || !mem_cgroup_tryget(eviction_memcg))) { + rcu_read_unlock(); return false; + } + + rcu_read_unlock(); + + /* Flush stats (and potentially sleep) outside the RCU read section */ + mem_cgroup_flush_stats_ratelimited(); =20 eviction_lruvec =3D mem_cgroup_lruvec(eviction_memcg, pgdat); refault =3D atomic_long_read(&eviction_lruvec->nonresident_age); @@ -493,6 +509,7 @@ bool workingset_test_recent(void *shadow, bool file, bo= ol *workingset) } } =20 + mem_cgroup_put(eviction_memcg); return refault_distance <=3D workingset_size; } =20 @@ -519,19 +536,16 @@ void workingset_refault(struct folio *folio, void *sh= adow) return; } =20 - /* Flush stats (and potentially sleep) before holding RCU read lock */ - mem_cgroup_flush_stats_ratelimited(); - - rcu_read_lock(); - /* * The activation decision for this folio is made at the level * where the eviction occurred, as that is where the LRU order * during folio reclaim is being determined. * * However, the cgroup that will own the folio is the one that - * is actually experiencing the refault event. + * is actually experiencing the refault event. Make sure the folio is + * locked to guarantee folio_memcg() stability throughout. */ + VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); nr =3D folio_nr_pages(folio); memcg =3D folio_memcg(folio); pgdat =3D folio_pgdat(folio); @@ -540,7 +554,7 @@ void workingset_refault(struct folio *folio, void *shad= ow) mod_lruvec_state(lruvec, WORKINGSET_REFAULT_BASE + file, nr); =20 if (!workingset_test_recent(shadow, file, &workingset)) - goto out; + return; =20 folio_set_active(folio); workingset_age_nonresident(lruvec, nr); @@ -556,8 +570,6 @@ void workingset_refault(struct folio *folio, void *shad= ow) lru_note_cost_refault(folio); mod_lruvec_state(lruvec, WORKINGSET_RESTORE_BASE + file, nr); } -out: - rcu_read_unlock(); } =20 /** --=20 2.42.0.609.gbb76f46606-goog From nobody Fri Jan 2 17:11:02 2026 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id E212DCD68E3 for ; Tue, 10 Oct 2023 03:21:51 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1441989AbjJJDVu (ORCPT ); Mon, 9 Oct 2023 23:21:50 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:37708 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1441984AbjJJDVc (ORCPT ); Mon, 9 Oct 2023 23:21:32 -0400 Received: from mail-yw1-x1149.google.com (mail-yw1-x1149.google.com [IPv6:2607:f8b0:4864:20::1149]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 84695BA for ; Mon, 9 Oct 2023 20:21:29 -0700 (PDT) Received: by mail-yw1-x1149.google.com with SMTP id 00721157ae682-59b5a586da6so42309907b3.1 for ; Mon, 09 Oct 2023 20:21:29 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1696908088; x=1697512888; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=/7pubW/PIkdb48xbcDVraC66arnzXQVqiP5CbuKjtvs=; b=TZ1/OsmbNCOpwFn+Q2edzU3B6v0uSQasTsn1jtcMcO8dEWSZkp0i6q4g53X2dJuhY5 v4gglfmttAXYn+O4mH3hse3o+YVmUWF+LR86+UAdfPX/fczDjNSpMxS6s89lyk53pm2I o/Yf0QzXLu9yJaEaivuSUYXDx+VFY8aDxUTW9G5EQFd8NgbB2xEFPu58/2HJVUlRRd2n eckhKPNBan6uEJaSxLPwesLnRUski1S++vOu74EcVTe6vPoruwLlskoCnMOfTDh612jk Lp99cwVB9imbyAastzTgJf+c55VBhpPg/C/+9NOaBmUAWVpApd/3m328qgprAdq/m8AG nniQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1696908088; x=1697512888; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=/7pubW/PIkdb48xbcDVraC66arnzXQVqiP5CbuKjtvs=; b=fQZrdwJOBGGX3qLLnk/tcZdRrH81vcsJakyn4WaVO2A0f0WabcguCz0MEBEXuBTa3G mBojy//lBFQS6romkXOUdMveufaYiFWTr3DT+5G1R0NqaFEDrdK/SDeHwnaS5Myohk8U pqA3cQnwmiTsybw6QbrWmBmFnPdSELuZstNfBoRn+dNZyBjUxYnTfta+KdCPhpcpO6MF DYLkNMOjbw+dsYzZxPAJTZQnNLmcdVP5S0WgM0/DXxy/qjLA0yto+eUw2QgaTxEl7FeR wmgmYPq4/c5W4GFrVUPeaAUEsG3Ud5qUrntyUgdtCslxYZtvp395oSNVSHH0zIaZdAMy QD4Q== X-Gm-Message-State: AOJu0Yz1VrAD/yJkM+b76jn4UDX8eyfme43y5l3VtAK3mRdXg8nhS170 nIQLkVPA0Z4qML4wZ7HkAJ3w90xvKZE9avD/ X-Google-Smtp-Source: AGHT+IGZZZH3XMFz9Y1SUioLqXwa9WuvTjduHQeZqULDOWCJSsAn3ByEEvhnBldRhKwmLPtnt2IlTigbq67SFmDv X-Received: from yosry.c.googlers.com ([fda3:e722:ac3:cc00:20:ed76:c0a8:29b4]) (user=yosryahmed job=sendgmr) by 2002:a81:760d:0:b0:595:8166:7be with SMTP id r13-20020a81760d000000b00595816607bemr329711ywc.0.1696908088781; Mon, 09 Oct 2023 20:21:28 -0700 (PDT) Date: Tue, 10 Oct 2023 03:21:16 +0000 In-Reply-To: <20231010032117.1577496-1-yosryahmed@google.com> Mime-Version: 1.0 References: <20231010032117.1577496-1-yosryahmed@google.com> X-Mailer: git-send-email 2.42.0.609.gbb76f46606-goog Message-ID: <20231010032117.1577496-6-yosryahmed@google.com> Subject: [PATCH v2 5/5] mm: memcg: restore subtree stats flushing From: Yosry Ahmed To: Andrew Morton Cc: Johannes Weiner , Michal Hocko , Roman Gushchin , Shakeel Butt , Muchun Song , Ivan Babrou , Tejun Heo , "=?UTF-8?q?Michal=20Koutn=C3=BD?=" , Waiman Long , kernel-team@cloudflare.com, Wei Xu , Greg Thelen , linux-mm@kvack.org, cgroups@vger.kernel.org, linux-kernel@vger.kernel.org, Yosry Ahmed Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Stats flushing for memcg currently follows the following rules: - Always flush the entire memcg hierarchy (i.e. flush the root). - Only one flusher is allowed at a time. If someone else tries to flush concurrently, they skip and return immediately. - A periodic flusher flushes all the stats every 2 seconds. The reason this approach is followed is because all flushes are serialized by a global rstat spinlock. On the memcg side, flushing is invoked from userspace reads as well as in-kernel flushers (e.g. reclaim, refault, etc). This approach aims to avoid serializing all flushers on the global lock, which can cause a significant performance hit under high concurrency. This approach has the following problems: - Occasionally a userspace read of the stats of a non-root cgroup will be too expensive as it has to flush the entire hierarchy [1]. - Sometimes the stats accuracy are compromised if there is an ongoing flush, and we skip and return before the subtree of interest is actually flushed, yielding stale stats (by up to 2s due to periodic flushing). This is more visible when reading stats from userspace, but can also affect in-kernel flushers. The latter problem is particulary a concern when userspace reads stats after an event occurs, but gets stats from before the event. Examples: - When memory usage / pressure spikes, a userspace OOM handler may look at the stats of different memcgs to select a victim based on various heuristics (e.g. how much private memory will be freed by killing this). Reading stale stats from before the usage spike in this case may cause a wrongful OOM kill. - A proactive reclaimer may read the stats after writing to memory.reclaim to measure the success of the reclaim operation. Stale stats from before reclaim may give a false negative. - Reading the stats of a parent and a child memcg may be inconsistent (child larger than parent), if the flush doesn't happen when the parent is read, but happens when the child is read. As for in-kernel flushers, they will occasionally get stale stats. No regressions are currently known from this, but if there are regressions, they would be very difficult to debug and link to the source of the problem. This patch aims to fix these problems by restoring subtree flushing, and removing the unified/coalesced flushing logic that skips flushing if there is an ongoing flush. This change would introduce a significant regression with global stats flushing thresholds. With per-memcg stats flushing thresholds, this seems to perform really well. The thresholds protect the underlying lock from unnecessary contention. Add a mutex to protect the underlying rstat lock from excessive memcg flushing. The thresholds are re-checked after the mutex is grabbed to make sure that a concurrent flush did not already get the subtree we are trying to flush. A call to cgroup_rstat_flush() is not cheap, even if there are no pending updates. This patch was tested in two ways to ensure the latency of flushing is up to bar, on a machine with 384 cpus: - A synthetic test with 5000 concurrent workers in 500 cgroups doing allocations and reclaim, as well as 1000 readers for memory.stat (variation of [2]). No regressions were noticed in the total runtime. Note that significant regressions in this test are observed with global stats thresholds, but not with per-memcg thresholds. - A synthetic stress test for concurrently reading memcg stats while memory allocation/freeing workers are running in the background, provided by Wei Xu [3]. With 250k threads reading the stats every 100ms in 50k cgroups, 99.9% of reads take <=3D 50us. Less than 0.01% of reads take more than 1ms, and no reads take more than 100ms. [1] https://lore.kernel.org/lkml/CABWYdi0c6__rh-K7dcM_pkf9BJdTRtAU08M43KO9M= E4-dsgfoQ@mail.gmail.com/ [2] https://lore.kernel.org/lkml/CAJD7tka13M-zVZTyQJYL1iUAYvuQ1fcHbCjcOBZcz= 6POYTV-4g@mail.gmail.com/ [3] https://lore.kernel.org/lkml/CAAPL-u9D2b=3DiF5Lf_cRnKxUfkiEe0AMDTu6yhrU= AzX0b6a6rDg@mail.gmail.com/ Signed-off-by: Yosry Ahmed Tested-by: Domenico Cerasuolo --- include/linux/memcontrol.h | 8 ++--- mm/memcontrol.c | 73 +++++++++++++++++++++++--------------- mm/vmscan.c | 2 +- mm/workingset.c | 10 ++++-- 4 files changed, 56 insertions(+), 37 deletions(-) diff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h index 41790e18bf3b..f64ac140083e 100644 --- a/include/linux/memcontrol.h +++ b/include/linux/memcontrol.h @@ -1057,8 +1057,8 @@ static inline unsigned long lruvec_page_state_local(s= truct lruvec *lruvec, return x; } =20 -void mem_cgroup_flush_stats(void); -void mem_cgroup_flush_stats_ratelimited(void); +void mem_cgroup_flush_stats(struct mem_cgroup *memcg); +void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg); =20 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item i= dx, int val); @@ -1573,11 +1573,11 @@ static inline unsigned long lruvec_page_state_local= (struct lruvec *lruvec, return node_page_state(lruvec_pgdat(lruvec), idx); } =20 -static inline void mem_cgroup_flush_stats(void) +static inline void mem_cgroup_flush_stats(struct mem_cgroup *memcg) { } =20 -static inline void mem_cgroup_flush_stats_ratelimited(void) +static inline void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *m= emcg) { } =20 diff --git a/mm/memcontrol.c b/mm/memcontrol.c index 9a586893bd3e..182b4f215fc6 100644 --- a/mm/memcontrol.c +++ b/mm/memcontrol.c @@ -666,7 +666,6 @@ struct memcg_vmstats { */ static void flush_memcg_stats_dwork(struct work_struct *w); static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork); -static atomic_t stats_flush_ongoing =3D ATOMIC_INIT(0); static u64 flush_last_time; =20 #define FLUSH_TIME (2UL*HZ) @@ -727,35 +726,45 @@ static inline void memcg_rstat_updated(struct mem_cgr= oup *memcg, int val) } } =20 -static void do_flush_stats(void) +static void do_flush_stats(struct mem_cgroup *memcg) { - /* - * We always flush the entire tree, so concurrent flushers can just - * skip. This avoids a thundering herd problem on the rstat global lock - * from memcg flushers (e.g. reclaim, refault, etc). - */ - if (atomic_read(&stats_flush_ongoing) || - atomic_xchg(&stats_flush_ongoing, 1)) - return; - - WRITE_ONCE(flush_last_time, jiffies_64); - - cgroup_rstat_flush(root_mem_cgroup->css.cgroup); + if (mem_cgroup_is_root(memcg)) + WRITE_ONCE(flush_last_time, jiffies_64); =20 - atomic_set(&stats_flush_ongoing, 0); + cgroup_rstat_flush(memcg->css.cgroup); } =20 -void mem_cgroup_flush_stats(void) +/* + * mem_cgroup_flush_stats - flush the stats of a memory cgroup subtree + * @memcg: root of the subtree to flush + * + * Flushing is serialized by the underlying global rstat lock. There is al= so a + * minimum amount of work to be done even if there are no stat updates to = flush. + * Hence, we only flush the stats if the updates delta exceeds a threshold= . This + * avoids unnecessary work and contention on the underlying lock. + */ +void mem_cgroup_flush_stats(struct mem_cgroup *memcg) { - if (memcg_should_flush_stats(root_mem_cgroup)) - do_flush_stats(); + static DEFINE_MUTEX(memcg_stats_flush_mutex); + + if (!memcg) + memcg =3D root_mem_cgroup; + + if (!memcg_should_flush_stats(memcg)) + return; + + mutex_lock(&memcg_stats_flush_mutex); + /* An overlapping flush may have occurred, check again after locking */ + if (memcg_should_flush_stats(memcg)) + do_flush_stats(memcg); + mutex_unlock(&memcg_stats_flush_mutex); } =20 -void mem_cgroup_flush_stats_ratelimited(void) +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(); + mem_cgroup_flush_stats(memcg); } =20 static void flush_memcg_stats_dwork(struct work_struct *w) @@ -764,7 +773,7 @@ static void flush_memcg_stats_dwork(struct work_struct = *w) * Deliberately ignore memcg_should_flush_stats() here so that flushing * in latency-sensitive paths is as cheap as possible. */ - do_flush_stats(); + do_flush_stats(root_mem_cgroup); queue_delayed_work(system_unbound_wq, &stats_flush_dwork, FLUSH_TIME); } =20 @@ -1639,7 +1648,7 @@ static void memcg_stat_format(struct mem_cgroup *memc= g, struct seq_buf *s) * * Current memory state: */ - mem_cgroup_flush_stats(); + mem_cgroup_flush_stats(memcg); =20 for (i =3D 0; i < ARRAY_SIZE(memory_stats); i++) { u64 size; @@ -4208,7 +4217,7 @@ static int memcg_numa_stat_show(struct seq_file *m, v= oid *v) int nid; struct mem_cgroup *memcg =3D mem_cgroup_from_seq(m); =20 - mem_cgroup_flush_stats(); + mem_cgroup_flush_stats(memcg); =20 for (stat =3D stats; stat < stats + ARRAY_SIZE(stats); stat++) { seq_printf(m, "%s=3D%lu", stat->name, @@ -4289,7 +4298,7 @@ static void memcg1_stat_format(struct mem_cgroup *mem= cg, struct seq_buf *s) =20 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) !=3D ARRAY_SIZE(memcg1_stats)); =20 - mem_cgroup_flush_stats(); + mem_cgroup_flush_stats(memcg); =20 for (i =3D 0; i < ARRAY_SIZE(memcg1_stats); i++) { unsigned long nr; @@ -4785,7 +4794,7 @@ void mem_cgroup_wb_stats(struct bdi_writeback *wb, un= signed long *pfilepages, struct mem_cgroup *memcg =3D mem_cgroup_from_css(wb->memcg_css); struct mem_cgroup *parent; =20 - mem_cgroup_flush_stats(); + mem_cgroup_flush_stats(memcg); =20 *pdirty =3D memcg_page_state(memcg, NR_FILE_DIRTY); *pwriteback =3D memcg_page_state(memcg, NR_WRITEBACK); @@ -6861,7 +6870,7 @@ static int memory_numa_stat_show(struct seq_file *m, = void *v) int i; struct mem_cgroup *memcg =3D mem_cgroup_from_seq(m); =20 - mem_cgroup_flush_stats(); + mem_cgroup_flush_stats(memcg); =20 for (i =3D 0; i < ARRAY_SIZE(memory_stats); i++) { int nid; @@ -8100,7 +8109,11 @@ bool obj_cgroup_may_zswap(struct obj_cgroup *objcg) break; } =20 - cgroup_rstat_flush(memcg->css.cgroup); + /* + * mem_cgroup_flush_stats() ignores small changes. Use + * do_flush_stats() directly to get accurate stats for charging. + */ + do_flush_stats(memcg); pages =3D memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE; if (pages < max) continue; @@ -8165,8 +8178,10 @@ void obj_cgroup_uncharge_zswap(struct obj_cgroup *ob= jcg, size_t size) static u64 zswap_current_read(struct cgroup_subsys_state *css, struct cftype *cft) { - cgroup_rstat_flush(css->cgroup); - return memcg_page_state(mem_cgroup_from_css(css), MEMCG_ZSWAP_B); + struct mem_cgroup *memcg =3D mem_cgroup_from_css(css); + + mem_cgroup_flush_stats(memcg); + return memcg_page_state(memcg, MEMCG_ZSWAP_B); } =20 static int zswap_max_show(struct seq_file *m, void *v) diff --git a/mm/vmscan.c b/mm/vmscan.c index c16e2b1ea8ae..2cc0cb41fb32 100644 --- a/mm/vmscan.c +++ b/mm/vmscan.c @@ -2246,7 +2246,7 @@ static void prepare_scan_control(pg_data_t *pgdat, st= ruct scan_control *sc) * Flush the memory cgroup stats, so that we read accurate per-memcg * lruvec stats for heuristics. */ - mem_cgroup_flush_stats(); + mem_cgroup_flush_stats(sc->target_mem_cgroup); =20 /* * Determine the scan balance between anon and file LRUs. diff --git a/mm/workingset.c b/mm/workingset.c index a573be6c59fd..11045febc383 100644 --- a/mm/workingset.c +++ b/mm/workingset.c @@ -464,8 +464,12 @@ bool workingset_test_recent(void *shadow, bool file, b= ool *workingset) =20 rcu_read_unlock(); =20 - /* Flush stats (and potentially sleep) outside the RCU read section */ - mem_cgroup_flush_stats_ratelimited(); + /* + * Flush stats (and potentially sleep) outside the RCU read section. + * XXX: With per-memcg flushing and thresholding, is ratelimiting + * still needed here? + */ + mem_cgroup_flush_stats_ratelimited(eviction_memcg); =20 eviction_lruvec =3D mem_cgroup_lruvec(eviction_memcg, pgdat); refault =3D atomic_long_read(&eviction_lruvec->nonresident_age); @@ -676,7 +680,7 @@ static unsigned long count_shadow_nodes(struct shrinker= *shrinker, struct lruvec *lruvec; int i; =20 - mem_cgroup_flush_stats(); + mem_cgroup_flush_stats(sc->memcg); lruvec =3D mem_cgroup_lruvec(sc->memcg, NODE_DATA(sc->nid)); for (pages =3D 0, i =3D 0; i < NR_LRU_LISTS; i++) pages +=3D lruvec_page_state_local(lruvec, --=20 2.42.0.609.gbb76f46606-goog