From nobody Fri Feb 13 19:29:34 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 650DEE7D0B6 for ; Thu, 21 Sep 2023 23:01:08 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S232039AbjIUXBL (ORCPT ); Thu, 21 Sep 2023 19:01:11 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:33002 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S231827AbjIUXA7 (ORCPT ); Thu, 21 Sep 2023 19:00:59 -0400 Received: from mail-io1-xd4a.google.com (mail-io1-xd4a.google.com [IPv6:2607:f8b0:4864:20::d4a]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 730C28ED7A for ; Thu, 21 Sep 2023 10:45:23 -0700 (PDT) Received: by mail-io1-xd4a.google.com with SMTP id ca18e2360f4ac-7954a4f80fbso84732639f.3 for ; Thu, 21 Sep 2023 10:45:23 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1695318322; x=1695923122; 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=FIm0UyACNB+n/akQREWxQWjORl9GVEfiVT/RezLXAow=; b=uR9Fv440HlOILRKBfEnyjwVRS9vHA8Z3MjwutpA1uOL86dhb/zVn4SGqQIolWU1OwK KhlmpPc0R02vgoX/thYrAlPZudlDrrICmoo2u8FjUzY7unSqBv+CBZxpeezareQQ3DmT Z8Z9fCdhNkXPxe1BqnJGtrwCxX/LFn8TQc0ZkYzqfmNw6ncBVaSOMq34cwNsY9spcVYT lZDEORwSL1X+ANYRFJTrRE8GyJhvdiLQBFUCfJM2dX0WTOeznh/m0ZB3mBmGGADgVPM0 bVajlGr3/aINZdenXVgTQXt6CWijPyq2OAmSJR8DIvirWggGrtc64ZIM6CEmUaDga4n8 JBmQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1695318322; x=1695923122; 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=FIm0UyACNB+n/akQREWxQWjORl9GVEfiVT/RezLXAow=; b=v3BNXau0TfMl9J8UH3VFTtocb6nsng0H68eEu2OV8N3ZCiGWJnhI5z2poXmF417Uf3 xnzrhUB6SBByoum5JTMZMFKVNIv/ZqQh7wE5a2AjyDkGN/YJDvbmneVRNkrVrLfAiNEh mjACXyEP3fR5MraZ0nlaPdz3hzBmp1xYdfw5jHxlNU5o6LVObXKf8bRGNll8PhJQh6PG 7U0P5TmzAdoH55wO590ZP3OW7FTRZec7lVquz7URAlwm/3p5aDx8uOIsqzpdLPEYSq3e IU0F+IciwyXomwysafPpVLt0wMK5jUT2gG7V27gANumBXdeH8KruforZSRGwGkKKqbRI f51Q== X-Gm-Message-State: AOJu0Yy44J/H0yxwUU2DGVcIRJhhZlmLR51vibZWy+6w1W0bqfAoJoK6 orX2m85knvKQPmd64ECdlqVoRUZV1mFtEMDh X-Google-Smtp-Source: AGHT+IFPrnsBcOBrlhPC5hJYwVV2PE3AiCfsgKWx3CsvgDAaTduMINork77xXDD5F6NyG97FAk+4bBmhLTyqQlsm X-Received: from yosry.c.googlers.com ([fda3:e722:ac3:cc00:20:ed76:c0a8:29b4]) (user=yosryahmed job=sendgmr) by 2002:a25:4c8:0:b0:d0e:d67d:6617 with SMTP id 191-20020a2504c8000000b00d0ed67d6617mr67400ybe.4.1695283863247; Thu, 21 Sep 2023 01:11:03 -0700 (PDT) Date: Thu, 21 Sep 2023 08:10:53 +0000 In-Reply-To: <20230921081057.3440885-1-yosryahmed@google.com> Mime-Version: 1.0 References: <20230921081057.3440885-1-yosryahmed@google.com> X-Mailer: git-send-email 2.42.0.459.ge4e396fd5e-goog Message-ID: <20230921081057.3440885-2-yosryahmed@google.com> Subject: [PATCH 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 --- mm/memcontrol.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/mm/memcontrol.c b/mm/memcontrol.c index 927c64d3cbcb..49562dfdeab2 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.459.ge4e396fd5e-goog From nobody Fri Feb 13 19:29:34 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 6401EE71096 for ; Thu, 21 Sep 2023 17:05:37 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S230063AbjIURFh (ORCPT ); Thu, 21 Sep 2023 13:05:37 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:39342 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S230247AbjIURFD (ORCPT ); Thu, 21 Sep 2023 13:05:03 -0400 Received: from mail-qt1-x849.google.com (mail-qt1-x849.google.com [IPv6:2607:f8b0:4864:20::849]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 7263346BE for ; Thu, 21 Sep 2023 10:04:21 -0700 (PDT) Received: by mail-qt1-x849.google.com with SMTP id d75a77b69052e-414bbfbdf37so11508421cf.1 for ; Thu, 21 Sep 2023 10:04:21 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1695315762; x=1695920562; 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=VUfaq4QWGo6Pgq9+Gc0pYjCdwcXd4ikm64XsTJ+V7zI=; b=QuBq6sLql1/NQJP//6nMgyiuHs7KLNNKfCjPoe+v5RXfTahnNrGFoHfMMGrfNhUSsS IATnEC5YqgIjG725bI0tgy2ZXJ8JdM7tXXEwfEKocJLA3ZmkvowCebsyN8CCMGFuY99+ bPFkrkeW0Z/n0zwKouaRPySRMvRKLH5MH47Zy8oCt1x6I0/43q4j7ru6NgLN8dnAxuTA X4QTEhH4SPzvDqrjBeGCIPkzUIR6GxDlod2ZZ2rnbA3PpJ08+UFePCVSuotCf0h0DnlE zLbfpbdZb31hrFpWFSLDl5XuNMb14E/iPjWD68Q1rL3nQLO1WTj7BCBph8adegaqow6S 1evA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1695315762; x=1695920562; 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=VUfaq4QWGo6Pgq9+Gc0pYjCdwcXd4ikm64XsTJ+V7zI=; b=xDfxJ6L5WpgG7jzZVXylShxEezof0gqPSxv+Uga2lkgvf38bp6bHSn2rdvrXEKrFgu SLtZ6KuwVE1gEPXId4eRu9Ppy9vWIU++fRzJKvWOCsiFAeezuZAJ53wFkVjXaoOW3cSD iRy6FFe46wuX9hkubLQRlkhm2v+08Od9s6aQZkTkYnGcRUFGy2E5mbiWJjViNk20EXoQ D1CxF/Aq6m7crHPJ6pwyO2zX4iLSRszW2b2qCvkxSn1n2u6+MwJkbz2LUt9i5Tdq3cMM 2EP0ut2PbtjebmlWDsT9Edp/iXn+3m7YiMDk4UQgIWwiWBcndAWuG8WX3GCAXJYy7fnu QZlw== X-Gm-Message-State: AOJu0YwhcN2The9ONsovie+7+pUPfgGuZ6f9Am8Tc5OmmsYpdDOU1hLL oLQpk4ppealwglU8MToZde9tZyF/eqTLiKj0 X-Google-Smtp-Source: AGHT+IFBE/oPIuCJlO97tHApRysO3VNA0vvMKpAee95h86ybMubWU1dHAIDYmvCWr5CQMyHTNET+SuyM9GansnHQ X-Received: from yosry.c.googlers.com ([fda3:e722:ac3:cc00:20:ed76:c0a8:29b4]) (user=yosryahmed job=sendgmr) by 2002:a81:b656:0:b0:59b:f493:813c with SMTP id h22-20020a81b656000000b0059bf493813cmr74625ywk.9.1695283865279; Thu, 21 Sep 2023 01:11:05 -0700 (PDT) Date: Thu, 21 Sep 2023 08:10:54 +0000 In-Reply-To: <20230921081057.3440885-1-yosryahmed@google.com> Mime-Version: 1.0 References: <20230921081057.3440885-1-yosryahmed@google.com> X-Mailer: git-send-email 2.42.0.459.ge4e396fd5e-goog Message-ID: <20230921081057.3440885-3-yosryahmed@google.com> Subject: [PATCH 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 --- mm/memcontrol.c | 146 ++++++++++++++++++++++++------------------------ 1 file changed, 73 insertions(+), 73 deletions(-) diff --git a/mm/memcontrol.c b/mm/memcontrol.c index 49562dfdeab2..ef7ad66a9e4c 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.459.ge4e396fd5e-goog From nobody Fri Feb 13 19:29:34 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 2CB2BE7D0A2 for ; Thu, 21 Sep 2023 18:16:51 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S229819AbjIUSQz (ORCPT ); Thu, 21 Sep 2023 14:16:55 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:52880 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S230344AbjIUSQc (ORCPT ); Thu, 21 Sep 2023 14:16: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 266ED12444 for ; Thu, 21 Sep 2023 10:06:53 -0700 (PDT) Received: by mail-yw1-x1149.google.com with SMTP id 00721157ae682-59beea5ce93so21695677b3.0 for ; Thu, 21 Sep 2023 10:06:53 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1695316012; x=1695920812; 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=DUC4W/ANoWKKbgrvdNHuDLy6cXEfVkGWJByczmAAxsQ=; b=of8xIAvy04KX7vfX19z8Hv6MC21KEr9NsizuDoNKHpXVj1Kre5XTK/0Da+7CYJklTZ s3BJZhhlY0dSNfUVR+TiFSJ7y9gGmIcaFP4FCFrdy9ctXrOdGEdtk0EH8lvf5V/xlWRx MwWATm0KcVPwl0b5UdUhWLXv1NgiI8dIo0yTRqEaze/0KjcS6jMPj3ofRpxzByq9+LUm awLHsDXk7fdmNIgCX2GY9MrOQXNqInSOPoU2N4Z6pfU689gGnaDhb3uAiKkfu/HJKnRF rHuRf/tHfuvY63VBXPgj42fd97hUBvQogLz4GrWVbVxr9YiHO1WsGP2+2YkSDdyD7v1Q 99aw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1695316012; x=1695920812; 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=DUC4W/ANoWKKbgrvdNHuDLy6cXEfVkGWJByczmAAxsQ=; b=MH3TvXqprhT5Bu7CQTBX9knqPgTO1gfX+KtZQTBKgqVBPkDbSSPONAk+FsY9UCy8Jj di/wLAQkyU08wIW1pRJkQAaL1gIp9E/qmrzlKzREPlVlW2EV64BB0wx8Rl4m5clXNczA Ev3IkVGr3lDN++bxTsTdhGU6jM8ZhRpSVt6aqY63t7QeoslVWk/8Glffv5SPf6/rn/Es a2gVn2KFZzEyk/97fU/aCORNOuNpavWVhMVMbKeFjkCRTM7hfUBf2r0jrvJ4qnvSlDvR ZHN4amt6amxJWqMBNwEjfDO2MYbessJ4o/wxxWKisEJncFrb4YQPiuy8S23uVOSpUUsz Id0A== X-Gm-Message-State: AOJu0YwHv0F71G3suxZkZ2M8ukB1bLoX3sMDV5QN5Xqijh4gCr71GIEw L2d/yYfqRKpZwCnDNlvgqRjJ6aeVMoKS1T0I X-Google-Smtp-Source: AGHT+IHWB2c9Yqrg5vaJ7T2d28Eo6cRgxwGr6tDusahnEBtVkRUK94znckmkqrIayxEXBXBNswuh+j1RV0RnYbJb X-Received: from yosry.c.googlers.com ([fda3:e722:ac3:cc00:20:ed76:c0a8:29b4]) (user=yosryahmed job=sendgmr) by 2002:a05:6830:ca:b0:6bc:ac3d:2b77 with SMTP id x10-20020a05683000ca00b006bcac3d2b77mr1588187oto.2.1695283866981; Thu, 21 Sep 2023 01:11:06 -0700 (PDT) Date: Thu, 21 Sep 2023 08:10:55 +0000 In-Reply-To: <20230921081057.3440885-1-yosryahmed@google.com> Mime-Version: 1.0 References: <20230921081057.3440885-1-yosryahmed@google.com> X-Mailer: git-send-email 2.42.0.459.ge4e396fd5e-goog Message-ID: <20230921081057.3440885-4-yosryahmed@google.com> Subject: [PATCH 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. (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 in a later patch shows this doesn't introduce 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. In a cgroup that is 4 levels deep (/sys/fs/cgroup/a/b/c/d), the following benchmarks were ran: (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) Running "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. [1]https://github.com/google/neper 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 ef7ad66a9e4c..c273c65bb642 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); @@ -5622,6 +5636,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.459.ge4e396fd5e-goog From nobody Fri Feb 13 19:29:34 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 2A475E7D0A6 for ; Thu, 21 Sep 2023 20:03:09 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S231493AbjIUUDN (ORCPT ); Thu, 21 Sep 2023 16:03:13 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:52100 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S231552AbjIUUCk (ORCPT ); Thu, 21 Sep 2023 16:02:40 -0400 Received: from mail-ot1-x349.google.com (mail-ot1-x349.google.com [IPv6:2607:f8b0:4864:20::349]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 5AF5E51023 for ; Thu, 21 Sep 2023 10:15:31 -0700 (PDT) Received: by mail-ot1-x349.google.com with SMTP id 46e09a7af769-6c49f8a445aso766342a34.0 for ; Thu, 21 Sep 2023 10:15:31 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1695316530; x=1695921330; 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=ap3WQf9RL9Y6q/AtYDIGLhJT98YcDdn8KWtOOFcbuqo=; b=C5y0XD+vi7QSz3yEnCzQjmt4g2pWnWb2cYXwIERC1F7l7KRclYhu/pPpGBk2BXmmvf nqXkvWTtpMJsjuYoh8JpRQecU29VIqVTEUzLjghan1J7X5LNyI8iQEeLSs6htPmCzoCb Y/dVOs14pEjSDrUkGE33jaNVsPq0l9YFasadR0mKn8zhfTft379+rCeXkr2U90vPzkQQ 96fkv79aEOp/lUebsKcrlJYT9JwQS1g/ccT1Cg+PVxMANVXTJhTQJAZL/wpjIj2als1M 106b6nuPDS8ZxuF68Qt2oFMQyZmDaAp2Skumqy8POABdgfoh+J4hh21gK2yGRlKHbae3 SrsA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1695316530; x=1695921330; 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=ap3WQf9RL9Y6q/AtYDIGLhJT98YcDdn8KWtOOFcbuqo=; b=W1KNwPFk//yB/ySbKvBREyUyGQ8bMbbhDrJVnVcn24ycNvy0SeFcnrzcn9pvePp7SR fz/65JmmdfsuljLJm4JiIhkbwozF2vLVHTK6h8+55o0iz6t+lhD7UJJ61BvUomPbB6wz Z0yRQrbQ0V42cIQDFM52NuuhVeD5sLtlqv4dlA7O4Stn2sa5+uBUv65fbMXBcACLNG7t 73VUB8vDRlMVrTU6vbmjMQ/N5chW5Ri+C8UC5OlqGA2gs6Qcsl2peS7e1qbbAE3n7LEJ GYyI1a0xWfrIPYKTe8F6BE9nzLmnZoMo8m+JV/gXFqnF1KbbcxQlkZYJZOFKA8uBVrLQ DQEA== X-Gm-Message-State: AOJu0YxnXk3+PlRgjWT83vBgdd5W5nBFzlL2ZXLwdlQ0enXEkXV0Op2P h9O87++9/vaV0jLMxj7FGe4P36IzZlJByl2Y X-Google-Smtp-Source: AGHT+IEctDDQF0RHmq3JRn62J6oQCd8whI4eyWsA+THF8MJIpkdXC4/+HB3bqA3JcJDKn3Dhk9UKpKL30JXlgF3v X-Received: from yosry.c.googlers.com ([fda3:e722:ac3:cc00:20:ed76:c0a8:29b4]) (user=yosryahmed job=sendgmr) by 2002:a25:504d:0:b0:d62:7f3f:621d with SMTP id e74-20020a25504d000000b00d627f3f621dmr75596ybb.11.1695283868835; Thu, 21 Sep 2023 01:11:08 -0700 (PDT) Date: Thu, 21 Sep 2023 08:10:56 +0000 In-Reply-To: <20230921081057.3440885-1-yosryahmed@google.com> Mime-Version: 1.0 References: <20230921081057.3440885-1-yosryahmed@google.com> X-Mailer: git-send-email 2.42.0.459.ge4e396fd5e-goog Message-ID: <20230921081057.3440885-5-yosryahmed@google.com> Subject: [PATCH 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 --- mm/workingset.c | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/mm/workingset.c b/mm/workingset.c index b192e44a0e7c..79b338996088 100644 --- a/mm/workingset.c +++ b/mm/workingset.c @@ -425,8 +425,15 @@ 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; @@ -451,6 +458,12 @@ bool workingset_test_recent(void *shadow, bool file, b= ool *workingset) if (!mem_cgroup_disabled() && !eviction_memcg) return false; =20 + css_get(&eviction_memcg->css); + rcu_read_unlock(); + + /* Flush stats (and potentially sleep) outside the RCU read section */ + mem_cgroup_flush_stats_ratelimited(); + eviction_lruvec =3D mem_cgroup_lruvec(eviction_memcg, pgdat); refault =3D atomic_long_read(&eviction_lruvec->nonresident_age); =20 @@ -493,6 +506,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 +533,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 +551,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 +567,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.459.ge4e396fd5e-goog From nobody Fri Feb 13 19:29:34 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 78F43E7D0A3 for ; Thu, 21 Sep 2023 17:25:09 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S229629AbjIURZM (ORCPT ); Thu, 21 Sep 2023 13:25:12 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40324 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S229870AbjIURYm (ORCPT ); Thu, 21 Sep 2023 13:24:42 -0400 Received: from mail-ot1-x34a.google.com (mail-ot1-x34a.google.com [IPv6:2607:f8b0:4864:20::34a]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 8DBE337BFD for ; Thu, 21 Sep 2023 10:13:26 -0700 (PDT) Received: by mail-ot1-x34a.google.com with SMTP id 46e09a7af769-6c0cb43abc4so1433522a34.1 for ; Thu, 21 Sep 2023 10:13:26 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1695316403; x=1695921203; 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=3167ObCwuPGy0ykS2mGpCnZZz/lnDX5wo2e/FWfZcMc=; b=3bJacgBp4Te45COTN/63YnwW2ThWDUiUSqS68AkJMwx0SnL4g9teCVUUJfOACEIzLJ UgtbNCB8IBx/KoOCG4gwe0E//Mdtg/1RpE8Xp3wZBNBimpJNkxqV3jO7FjJtsjHDrZXs 83LY8klGUy3u0UPAxhQqPC+PO/P+Q1TZpZtFeDHhN5WZRUt1gtWYIqB6P3Zh8JE96pI0 8VJ8RA7JXB0NjTqcdfKrdYvZZB/JdcxtNi7U3J6bQGB1MHEHEY7q0qcNEH1pPvVIyxNC VRFjI+xsM/uodmpl7kGuf18z+yq9kODcV91SJKP+TC8F0jNSC1by+liMjbCBU+BXS6OM P83g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1695316403; x=1695921203; 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=3167ObCwuPGy0ykS2mGpCnZZz/lnDX5wo2e/FWfZcMc=; b=XM0ZT8E/jvG9moIJXk4g7HQabLwCfd3kgSBJkwTHnHyPJ+6DQZ4cPWfODGtgWLajW+ 4nuJSdBZZmrCwMNy2pnL0INNmgjcH8blq0W3HQQ3qFvkxZ8ocnmFz8kV5OlgP0Xjt8/c CcYc8S4+SxB4vrpbk7FM7lWAzycEQEZ+9sf0yl6YBrQVdj1d6JIrc6FgnX0rpQjkeoJS Tce8TkCUmXsV/1zr+XVDmqNqNH0tWkDaBRyYDSqboIR4aAMBZkj+KJYuqvbBba6tjkic /aLGgl8BI2Pn6N5hzEtSFkJ8S0RG2nY3rx7Refb+eNca72hZQPLAswel/ZBweUwjEfLs w30w== X-Gm-Message-State: AOJu0YwBOL/FOReaw5bp98Fe/SF68j2JT9aPSOnEzRHDUE1yKsWeYJU6 e/5n305zq9rgA8AWcRz0BpBSGHZOmTeuRMuF X-Google-Smtp-Source: AGHT+IEJ4fcoyEGYjUXnEO4k8S62qHUkVPnBwaKgs95Sypxteexrw0RSMgrAyDrgXkVHLcy4yrd/Nrxvhz1akcJT X-Received: from yosry.c.googlers.com ([fda3:e722:ac3:cc00:20:ed76:c0a8:29b4]) (user=yosryahmed job=sendgmr) by 2002:a25:e0c5:0:b0:d78:28d0:15bc with SMTP id x188-20020a25e0c5000000b00d7828d015bcmr99461ybg.4.1695283870798; Thu, 21 Sep 2023 01:11:10 -0700 (PDT) Date: Thu, 21 Sep 2023 08:10:57 +0000 In-Reply-To: <20230921081057.3440885-1-yosryahmed@google.com> Mime-Version: 1.0 References: <20230921081057.3440885-1-yosryahmed@google.com> X-Mailer: git-send-email 2.42.0.459.ge4e396fd5e-goog Message-ID: <20230921081057.3440885-6-yosryahmed@google.com> Subject: [PATCH 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 --- 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 45d0c10e86cc..1b61a2707307 100644 --- a/include/linux/memcontrol.h +++ b/include/linux/memcontrol.h @@ -1030,8 +1030,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); @@ -1520,11 +1520,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 c273c65bb642..99cfba81684f 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 @@ -1593,7 +1602,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; @@ -4035,7 +4044,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, @@ -4116,7 +4125,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; @@ -4613,7 +4622,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); @@ -6640,7 +6649,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; @@ -7806,7 +7815,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; @@ -7871,8 +7884,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 a4e44f1c97c1..60bead17b1f7 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 79b338996088..141defbe3da2 100644 --- a/mm/workingset.c +++ b/mm/workingset.c @@ -461,8 +461,12 @@ bool workingset_test_recent(void *shadow, bool file, b= ool *workingset) css_get(&eviction_memcg->css); 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); @@ -673,7 +677,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.459.ge4e396fd5e-goog