From nobody Tue Dec 30 11:23:25 2025 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 4B1F6C5ACB2 for ; Thu, 16 Nov 2023 02:24:26 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1344500AbjKPCY1 (ORCPT ); Wed, 15 Nov 2023 21:24:27 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:55268 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232310AbjKPCYT (ORCPT ); Wed, 15 Nov 2023 21:24:19 -0500 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 EBD3C1A5 for ; Wed, 15 Nov 2023 18:24:16 -0800 (PST) Received: by mail-yb1-xb49.google.com with SMTP id 3f1490d57ef6-d9ab79816a9so401617276.3 for ; Wed, 15 Nov 2023 18:24:16 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1700101456; x=1700706256; 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=BcE9vJD0hOv2TBpe3ivca8OUmRQ1FOEoUuzJXTFrwQU=; b=xe5MtW0wJjFy8d59ZlUsqx91/pLiIvBH1MJeyaAasPiwtQqJCd6jwX49qQ1h70vghI 3WCKs5vPHO9p3WE74yGqXixldwo7ea3GX2j/zYG63t8sgV4D8TCM41oN1ILr5opRDq05 A2r2XGny+xev5ka+WgAXc4fyD4cCDVXkRzly3bMvHTmaQWfKTxOMRWbWoBZAbmeljHrK tsGAx4oLV/mEj0u5BGWis4ET1stjBpfvgpUIxFqm5JdjEe+d+glwpLcHgosogA9yVU8/ bHDwB4H58NI2/8xBxNYoOzjZEkLVLApzAnk2NzeqtC9RpE5oCQom99LKC68s/eVGDwS0 7JIw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1700101456; x=1700706256; 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=BcE9vJD0hOv2TBpe3ivca8OUmRQ1FOEoUuzJXTFrwQU=; b=O2DszXs/9K4LGM3IGnTxTluBI+O/Z8AXzFZ3Bb8Qx5ARrz/nr9KfXxVtDZpSDSLV47 iMI1FEsjLNzEIb5AuXKX+jgWEuW0loGk/Y+ZahUbKJfqaYZnbx2pm36tASjCrM6qAJSy fo7nfNAZPXwqCnAlqMjsoOZ3KZXIvGPvhxbQ4ak2bzEUfJWf5+SiFTl8Wb/G5Mf5H4FH 3gJk+iOg3fguFV31JBilgTqWw44wq2eeeM95vBl2uAMYjYb5YQbSiN/FrCM8EykPRhQ+ ehgbZjN1j0wfafkzNVpMrzeEQRirhlxu36acdfBV2uCnjqoGOPBawMtYPTFwlqU3e2ey HnvQ== X-Gm-Message-State: AOJu0YyvnZH77kXiymOZzaIyMrgdTFT+aK4cpDSvwc5tfS/VMJO60kxb JNOQMKNZwheDLEaNAd2YKvb8Ik8c0LPPVF3R X-Google-Smtp-Source: AGHT+IFy97x2nQDJgIiWGH9dEF3svZisBvzaosL7zloYt6xMQ4EjhERYd/7GmdSfHzW6U7mYn8R6aavP5vLCYx6D X-Received: from yosry.c.googlers.com ([fda3:e722:ac3:cc00:20:ed76:c0a8:29b4]) (user=yosryahmed job=sendgmr) by 2002:a05:6902:285:b0:d9a:d272:ee58 with SMTP id v5-20020a056902028500b00d9ad272ee58mr402081ybh.9.1700101456166; Wed, 15 Nov 2023 18:24:16 -0800 (PST) Date: Thu, 16 Nov 2023 02:24:06 +0000 In-Reply-To: <20231116022411.2250072-1-yosryahmed@google.com> Mime-Version: 1.0 References: <20231116022411.2250072-1-yosryahmed@google.com> X-Mailer: git-send-email 2.43.0.rc0.421.g78406f8d94-goog Message-ID: <20231116022411.2250072-2-yosryahmed@google.com> Subject: [PATCH v3 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 , Domenico Cerasuolo , 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 Acked-by: Chris Li (Google) --- mm/memcontrol.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/mm/memcontrol.c b/mm/memcontrol.c index 774bd6e21e278..18931d82f108f 100644 --- a/mm/memcontrol.c +++ b/mm/memcontrol.c @@ -593,7 +593,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 @@ -653,7 +653,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 @@ -669,7 +669,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.43.0.rc0.421.g78406f8d94-goog From nobody Tue Dec 30 11:23:25 2025 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 ED9B0C2BB3F for ; Thu, 16 Nov 2023 02:24:28 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S235620AbjKPCY3 (ORCPT ); Wed, 15 Nov 2023 21:24:29 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:42942 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1344483AbjKPCYV (ORCPT ); Wed, 15 Nov 2023 21:24:21 -0500 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 8B54B127 for ; Wed, 15 Nov 2023 18:24:18 -0800 (PST) Received: by mail-yw1-x1149.google.com with SMTP id 00721157ae682-5a90d6ab944so4518917b3.2 for ; Wed, 15 Nov 2023 18:24:18 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1700101458; x=1700706258; 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=CsQgPePmMbwkmYg1tT46kxvFflY+DocB+A/S3VGDzrg=; b=SSq1gjJGYKByfSc1ezcEZl5ZLzu+0Gp49FDvhZLXMmMAZiEzYmtiwWHY9lp5sxFhfN ED2X1gOJrbfkbLJpx8GZv/6TfkAOaCaxPdiLOWOzdsyL/YMcCovMr1MS6xWLMuUWgjZ0 fwtN68iG7IfCfdUGyMD04z+JM8GRrdmSiqE5ajmCC68UCqbQU3MmWQ8r3KgmZjzy+MUL AWu40HmAP3acYhQ8bRvC3JvcDGnTTyepgs5en4aSS1s9g62t7PbCqtGp+S7CN1UJ41kg WapT3sabVpYTmaQOPOmrrt/m+sFQlvKV1Dar6DQ7H+mzaZoF3Q8TWR/PSDYwFW2NlZW0 /agg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1700101458; x=1700706258; 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=CsQgPePmMbwkmYg1tT46kxvFflY+DocB+A/S3VGDzrg=; b=S66DvckMf6f7NiBZi+K0ipHmLZgaLIDfrh781AE9DBmRui3hKjkuBlK77/WAPEye4p pd2gNgJAhIJQ2aWV2aH1FKoOUXUdWjxwqe6/wOKQ9RzhY0vwK/GGU89T8KaXeCGLgLc9 FDS78pTLl8no840pDyY1aTX8WPkzA55u9Hn5+4PtnCsOL2xTIVZTUNus/G6WYMXrnEim 8JeWy9/GmieJH60iLrg/cW5PAn9+ALOB8mTm/MZnjJwGeOyhlV+N1Br/VOCydU1E05dy MlQxAGtito49gvDcOTIr2pvxzycTvv5fXq2/+yKsOQZ/KtLS80nBz7ULWTTaqm3ShAVC DZEw== X-Gm-Message-State: AOJu0YzVnmhAwLm5T0ulVAoW+STB2ctgAT34V7yIIgCyWWzKXuqgqCIv 5MsoMLWQWHN2eVzRAfi3qPNmruX//qzSwD2Q X-Google-Smtp-Source: AGHT+IFLy40NOoa1rb6dZOa2HGVCBZYSVTkHt6esqpaY9lO76idIWli3bPfPKtfXVxgT/7MwnEla17Q3y28TlYUG X-Received: from yosry.c.googlers.com ([fda3:e722:ac3:cc00:20:ed76:c0a8:29b4]) (user=yosryahmed job=sendgmr) by 2002:a0d:d747:0:b0:5a7:a929:5b1d with SMTP id z68-20020a0dd747000000b005a7a9295b1dmr375983ywd.4.1700101457790; Wed, 15 Nov 2023 18:24:17 -0800 (PST) Date: Thu, 16 Nov 2023 02:24:07 +0000 In-Reply-To: <20231116022411.2250072-1-yosryahmed@google.com> Mime-Version: 1.0 References: <20231116022411.2250072-1-yosryahmed@google.com> X-Mailer: git-send-email 2.43.0.rc0.421.g78406f8d94-goog Message-ID: <20231116022411.2250072-3-yosryahmed@google.com> Subject: [PATCH v3 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 , Domenico Cerasuolo , 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 Acked-by: Shakeel Butt --- mm/memcontrol.c | 146 ++++++++++++++++++++++++------------------------ 1 file changed, 73 insertions(+), 73 deletions(-) diff --git a/mm/memcontrol.c b/mm/memcontrol.c index 18931d82f108f..5ae2a8f04be45 100644 --- a/mm/memcontrol.c +++ b/mm/memcontrol.c @@ -573,6 +573,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 * @@ -684,79 +757,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.43.0.rc0.421.g78406f8d94-goog From nobody Tue Dec 30 11:23:25 2025 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 6F5B1C2BB3F for ; Thu, 16 Nov 2023 02:24:32 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1344513AbjKPCYd (ORCPT ); Wed, 15 Nov 2023 21:24:33 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:42962 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1344508AbjKPCYX (ORCPT ); Wed, 15 Nov 2023 21:24:23 -0500 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 37833127 for ; Wed, 15 Nov 2023 18:24:20 -0800 (PST) Received: by mail-yw1-x1149.google.com with SMTP id 00721157ae682-5b02ed0f886so4228327b3.0 for ; Wed, 15 Nov 2023 18:24:20 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1700101459; x=1700706259; 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=LSZ+R0SqSzDzKoZBVcJ1mA+eTEuDRTwjKPgQcB0rBEk=; b=q4zPeLVMeDHerqDEMZdDflEzHOPf/yZKpaMP3vGbaXuLxaFWDQeWWH5Msi1f8ZcSNh Kd6yt7kxCfLz3DAMSs9GbuS+PPURtCRhzd0G1rEO7NxdVLo2BYAdggAb+cjpHlGgIalr eNpeySySiBDX8NJNPukGPTNH1Hwo8NElCEP5QrmppOw/ioThNXaP+t5Lua8/OSHigG3W LQcr7gCgMxxfrujvHut78PkGubayrDNRgU4aIfu0Zr492mUkRCn7EWMHDW1d1qn132xg v/l9oquV/EkrVUx/DUtFc2l92iF1oPfU0PrIM5SYeVfaK2Z8sMncG6Ptx6Im3/NkPccC M6jw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1700101459; x=1700706259; 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=LSZ+R0SqSzDzKoZBVcJ1mA+eTEuDRTwjKPgQcB0rBEk=; b=mhXGP/YYmasiMJ3RNqOT8FXuCKmH4qMZb7DSPNnwwn4G5mijg/s6waVuhKoOy1fZsK CGoSR8mF6rmlfMu8RpsxXQwrRzvDJoF9F5juvwqzbOuRNv26oiHQSYjOA0S9CbcO3QR+ YwS+67UFuR2ht9fjAGsqkuVWNbc8ySi4t0nSuFQOcQaqxfgOEgKxCQjhM2qc74e/fDZI he8xGpOdq5wzFi0/LYcMY2LDzcj9r8QdOt4tMTHSeZxbFNQpNvXR9f1uRWq5Eni8Q5bB t5jxrA53+QuE6Q6/so6mCJgg2MdP2XTrGU8iiC3ozf/hJOD5xP1QrY+m287OQPDQMsSy 2B4Q== X-Gm-Message-State: AOJu0Yxz2nrFQRI2EV+h0Zry+XB7/HqW5p/Ugbk+SMs/vNweOIIeZvyA pXD+pZOSNE8hWg5qDgturbIOz4uhbQE6HL5Z X-Google-Smtp-Source: AGHT+IEFkRjPRA+t8bnXs4r4alzEC6UzKUxHSRyn9fc3Cf7ttKBPYuT2Hd+c68LlEN9cCFYG3gXViVMxsm4UDLTD X-Received: from yosry.c.googlers.com ([fda3:e722:ac3:cc00:20:ed76:c0a8:29b4]) (user=yosryahmed job=sendgmr) by 2002:a81:4f90:0:b0:5a7:b543:7f0c with SMTP id d138-20020a814f90000000b005a7b5437f0cmr404902ywb.10.1700101459465; Wed, 15 Nov 2023 18:24:19 -0800 (PST) Date: Thu, 16 Nov 2023 02:24:08 +0000 In-Reply-To: <20231116022411.2250072-1-yosryahmed@google.com> Mime-Version: 1.0 References: <20231116022411.2250072-1-yosryahmed@google.com> X-Mailer: git-send-email 2.43.0.rc0.421.g78406f8d94-goog Message-ID: <20231116022411.2250072-4-yosryahmed@google.com> Subject: [PATCH v3 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 , Domenico Cerasuolo , 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 2 levels deep (/sys/fs/cgroup/a/b/): (1) Running 22 instances of netperf on a 44 cpu machine with hyperthreading disabled. All instances are run in a level 2 cgroup, as well as netserver: # netserver -6 # netperf -6 -H ::1 -l 60 -t TCP_SENDFILE -- -m 10K Averaging 20 runs, the numbers are as follows: Base: 40198.0 mbps Patched: 38629.7 mbps (-3.9%) The regression is minimal, especially for 22 instances in the same cgroup sharing all ancestors (so updating the same atomics). (2) 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 [1]. These are the numbers from 10 runs (+ is good) on a machine with 256 cpus: LABEL | MEAN | MEDIAN | STDDEV | Suggested-by: Johannes Weiner Tested-by: Domenico Cerasuolo ------------------------------+-------------+-------------+------------- page_fault1_per_process_ops | | | | (A) base | 270249.164 | 265437.000 | 13451.836 | (B) patched | 261368.709 | 255725.000 | 13394.767 | | -3.29% | -3.66% | | page_fault1_per_thread_ops | | | | (A) base | 242111.345 | 239737.000 | 10026.031 | (B) patched | 237057.109 | 235305.000 | 9769.687 | | -2.09% | -1.85% | | page_fault1_scalability | | | (A) base | 0.034387 | 0.035168 | 0.0018283 | (B) patched | 0.033988 | 0.034573 | 0.0018056 | | -1.16% | -1.69% | | page_fault2_per_process_ops | | | (A) base | 203561.836 | 203301.000 | 2550.764 | (B) patched | 197195.945 | 197746.000 | 2264.263 | | -3.13% | -2.73% | | page_fault2_per_thread_ops | | | (A) base | 171046.473 | 170776.000 | 1509.679 | (B) patched | 166626.327 | 166406.000 | 768.753 | | -2.58% | -2.56% | | page_fault2_scalability | | | (A) base | 0.054026 | 0.053821 | 0.00062121 | (B) patched | 0.053329 | 0.05306 | 0.00048394 | | -1.29% | -1.41% | | page_fault3_per_process_ops | | | (A) base | 1295807.782 | 1297550.000 | 5907.585 | (B) patched | 1275579.873 | 1273359.000 | 8759.160 | | -1.56% | -1.86% | | page_fault3_per_thread_ops | | | (A) base | 391234.164 | 390860.000 | 1760.720 | (B) patched | 377231.273 | 376369.000 | 1874.971 | | -3.58% | -3.71% | | page_fault3_scalability | | | (A) base | 0.60369 | 0.60072 | 0.0083029 | (B) patched | 0.61733 | 0.61544 | 0.009855 | | +2.26% | +2.45% | | All regressions seem to be minimal, and within the normal variance for the benchmark. The fix for [1] 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. (3) I also ran stress-ng in a nested cgroup and did not observe any obvious regressions. [1]https://lore.kernel.org/all/20190520063534.GB19312@shao2-debian/ Suggested-by: Johannes Weiner Signed-off-by: Yosry Ahmed Tested-by: Domenico Cerasuolo --- mm/memcontrol.c | 50 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 34 insertions(+), 16 deletions(-) diff --git a/mm/memcontrol.c b/mm/memcontrol.c index 5ae2a8f04be45..74db05237775d 100644 --- a/mm/memcontrol.c +++ b/mm/memcontrol.c @@ -630,6 +630,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 { @@ -644,6 +647,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 /* @@ -663,9 +669,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) @@ -692,26 +696,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 @@ -730,13 +745,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 @@ -750,8 +764,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); @@ -5784,6 +5798,10 @@ static void mem_cgroup_css_rstat_flush(struct cgroup= _subsys_state *css, int cpu) } } } + statc->stats_updates =3D 0; + /* 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.43.0.rc0.421.g78406f8d94-goog From nobody Tue Dec 30 11:23:25 2025 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 64879C072A2 for ; Thu, 16 Nov 2023 02:24:34 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1344516AbjKPCYf (ORCPT ); Wed, 15 Nov 2023 21:24:35 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:43004 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1344511AbjKPCYZ (ORCPT ); Wed, 15 Nov 2023 21:24:25 -0500 Received: from mail-yw1-x114a.google.com (mail-yw1-x114a.google.com [IPv6:2607:f8b0:4864:20::114a]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id C95371A1 for ; Wed, 15 Nov 2023 18:24:21 -0800 (PST) Received: by mail-yw1-x114a.google.com with SMTP id 00721157ae682-5a7b9e83b70so2727857b3.0 for ; Wed, 15 Nov 2023 18:24:21 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1700101461; x=1700706261; 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=hOK1UyBshtkV5dW8DFB6ZrNswsHIuDTjDTN/Td8b6tw=; b=BtLeQoZOY6gplEYKT8GsxkS/HMmtbYqTAqkTPUYtN4ZZ8qc9kZEcRwXXcGXjMr7iiw K65RwDcE8mVY9CIrbDPkNAQxw5dlRLOpy36Zv8LhW/sx1ZIyngRWETOlBm9teHKMorXj IpJP+dVuFRm+E8bs9a6LcSQhietVMOlvvFh/DgIbEniCY0oGCwX5b0Z3ndjqdnQJIWjm paGm4VfQnc9OAsIzE85KCRMpHGFN/JqEOlPE8SxIiogKfOcjg12J3WClyqAOZXIFn2ag rPVUXRKjT1wX2l9MtP5nU4IRcQ245oqZtSU5CnPTln8IDy7BbWByTyAczWdNvP8U8SzD NWCw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1700101461; x=1700706261; 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=hOK1UyBshtkV5dW8DFB6ZrNswsHIuDTjDTN/Td8b6tw=; b=DH7GSjQLDDW3LoJ/rVYLiW9oT9cZUt8ltn+1hob3e4sw6l1YEOIH4As/qPJ1I8Y4lO 30JLFljnvNMhNPrSyyX5KOnoI06Vp8BGuKhX/AstDFcim/xRi8cZkYuXzLX4hkhRRcEH s4JkYwuFpBz3OHec2EhBeXn9pm0f+iUQ/en6B9k8Y01H0PhldWY5iY/aJHf6WQjkIoN+ QPReB2jx9Cr9jq05JeOVHVua9v7hBsXvpZnFfgPKkf+BH7/NKTtrang01YhbAy8CysxH Ol5GipblWrFo+kfTtpw6axVk8NkmSTsjmVSxtKYIPWz2asaDQes8sAEwdGIeNSYksNCT laHA== X-Gm-Message-State: AOJu0Yyl2HHso/1IoUAFb6IITA/XciGmzPq/0UaTcIinpWBZ3ljo8fyQ osI75BcHw0vKqqfkko1hxKWPjGuhlbJ8tvYY X-Google-Smtp-Source: AGHT+IEQtgXmf9iSCqMERLu3YFDRxYLIfFN9r8bkSUo7k+VLrtBcNBEUIUl5/rQbpV2uMfGCYzqdDt8J6V5tLAR0 X-Received: from yosry.c.googlers.com ([fda3:e722:ac3:cc00:20:ed76:c0a8:29b4]) (user=yosryahmed job=sendgmr) by 2002:a0d:d716:0:b0:5ae:75db:92c5 with SMTP id z22-20020a0dd716000000b005ae75db92c5mr12091ywd.2.1700101461069; Wed, 15 Nov 2023 18:24:21 -0800 (PST) Date: Thu, 16 Nov 2023 02:24:09 +0000 In-Reply-To: <20231116022411.2250072-1-yosryahmed@google.com> Mime-Version: 1.0 References: <20231116022411.2250072-1-yosryahmed@google.com> X-Mailer: git-send-email 2.43.0.rc0.421.g78406f8d94-goog Message-ID: <20231116022411.2250072-5-yosryahmed@google.com> Subject: [PATCH v3 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 , Domenico Cerasuolo , 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 b192e44a0e7cc..a573be6c59fd9 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.43.0.rc0.421.g78406f8d94-goog From nobody Tue Dec 30 11:23:25 2025 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 BF204C072A2 for ; Thu, 16 Nov 2023 02:24:43 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1344541AbjKPCYp (ORCPT ); Wed, 15 Nov 2023 21:24:45 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:43096 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1344548AbjKPCYf (ORCPT ); Wed, 15 Nov 2023 21:24:35 -0500 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 7CB141BF for ; Wed, 15 Nov 2023 18:24:23 -0800 (PST) Received: by mail-yb1-xb49.google.com with SMTP id 3f1490d57ef6-da03c5ae220so1344825276.1 for ; Wed, 15 Nov 2023 18:24:23 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1700101462; x=1700706262; 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=sYfIbMCcjOcaMk8XkEVZkKdIKTJOO/34lFccln3zlF4=; b=OlIExH1nKH4VI7fecpvuE+ivYyrVPXnXjLPWBMQtZ+jIheEIFSgr7GIrFWMccyUMLP nUhCW8tJ24OI7fDg9/6b3iCZrP5jsiWqU8kjCYyMB2OIOQjMDDdmczuZajV/p/WnWeb/ aiJOeyd1bRRgz87l6/HEgGgoQlagK8u/kgvDG26KCcHS4af06cFj4O9EsJ+V6CHi3ukC NpteF49/ckJObAhW5TOKcBnBCCxZ9Bepn2wQD9C8kZUekDLnY1UTScypKEhp3C7OZaFv MkG/+kxo4jMi9a+J2fAoOlkqd8nsXpIobUzaES+9lV7oce7oLPN2D0fGurH/3B1cxfYu jdZg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1700101462; x=1700706262; 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=sYfIbMCcjOcaMk8XkEVZkKdIKTJOO/34lFccln3zlF4=; b=GTt0dgXzG3vEVrk4fjMDhDAVMg05c92pYUdCkX1AOXNdssd0KoLbTZnJlbwKPBZleY bIK0i0SKwEXFRH8txRVw/J3w58I7WeNZex89g/StGTRnqxYQUwamYJGadGtcbLOSIoWJ DiUV0b5Vuuq1uMytwj+tSHFbsRcWEuOh0n21iKbTAI2scENW+N3JDwLAb1f7cht76x+I QlqKvSzZWlC6K2+9Kjft/gyTSUcnSPzjQ4sq/m6vYiFaDipVRecUAEUBsmO3cwOGRLMc YeTkCF2cy/JIicHHZjES6fALLwoEFuzXpcc4n+XS4Tyw1HkGU1iq8eVjT5tBwvlEIsr6 c8qQ== X-Gm-Message-State: AOJu0Yx/sowsEZ9Y6WyU1Y2fYfXeUekCpJBkdcGd91MiUr/GFAC0dYu7 jmsNn7IKic8Q3+kF5w70A1/62NavRd1BtzeT X-Google-Smtp-Source: AGHT+IHOmB/fbH5s+WhrMo6La77w650Dx8voIzjIjTB3e9zO2veYErgpI8gmC3H0bM7gCxpZ7clqVyysog00UpE/ X-Received: from yosry.c.googlers.com ([fda3:e722:ac3:cc00:20:ed76:c0a8:29b4]) (user=yosryahmed job=sendgmr) by 2002:a25:ac9b:0:b0:d9a:4cc1:b59a with SMTP id x27-20020a25ac9b000000b00d9a4cc1b59amr11173ybi.1.1700101462675; Wed, 15 Nov 2023 18:24:22 -0800 (PST) Date: Thu, 16 Nov 2023 02:24:10 +0000 In-Reply-To: <20231116022411.2250072-1-yosryahmed@google.com> Mime-Version: 1.0 References: <20231116022411.2250072-1-yosryahmed@google.com> X-Mailer: git-send-email 2.43.0.rc0.421.g78406f8d94-goog Message-ID: <20231116022411.2250072-6-yosryahmed@google.com> Subject: [PATCH v3 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 , Domenico Cerasuolo , 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 | 75 +++++++++++++++++++++++--------------- mm/vmscan.c | 2 +- mm/workingset.c | 10 +++-- 4 files changed, 58 insertions(+), 37 deletions(-) diff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h index 7bdcf3020d7a3..6edd3ec4d8d54 100644 --- a/include/linux/memcontrol.h +++ b/include/linux/memcontrol.h @@ -1046,8 +1046,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); @@ -1548,11 +1548,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 74db05237775d..2baa9349d1590 100644 --- a/mm/memcontrol.c +++ b/mm/memcontrol.c @@ -669,7 +669,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) @@ -730,35 +729,47 @@ 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 (mem_cgroup_disabled()) + return; + + if (!memcg) + memcg =3D root_mem_cgroup; + + if (memcg_should_flush_stats(memcg)) { + mutex_lock(&memcg_stats_flush_mutex); + /* Check again after locking, another flush may have occurred */ + 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) @@ -767,7 +778,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 @@ -1642,7 +1653,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; @@ -4191,7 +4202,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, @@ -4272,7 +4283,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; @@ -4768,7 +4779,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); @@ -6857,7 +6868,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; @@ -8088,7 +8099,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; @@ -8153,8 +8168,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 506f8220c5fe5..f93c989d7b387 100644 --- a/mm/vmscan.c +++ b/mm/vmscan.c @@ -2222,7 +2222,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 a573be6c59fd9..11045febc3838 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.43.0.rc0.421.g78406f8d94-goog