blob: 46ad252e6d6aa62c09bffac5a5fffdd0bd641f83 [file] [log] [blame]
Thomas Gleixnerc942fdd2019-05-27 08:55:06 +02001// SPDX-License-Identifier: GPL-2.0-or-later
Balbir Singh8cdea7c2008-02-07 00:13:50 -08002/* memcontrol.c - Memory Controller
3 *
4 * Copyright IBM Corporation, 2007
5 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
6 *
Pavel Emelianov78fb7462008-02-07 00:13:51 -08007 * Copyright 2007 OpenVZ SWsoft Inc
8 * Author: Pavel Emelianov <xemul@openvz.org>
9 *
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -080010 * Memory thresholds
11 * Copyright (C) 2009 Nokia Corporation
12 * Author: Kirill A. Shutemov
13 *
Glauber Costa7ae1e1d2012-12-18 14:21:56 -080014 * Kernel Memory Controller
15 * Copyright (C) 2012 Parallels Inc. and Google Inc.
16 * Authors: Glauber Costa and Suleiman Souhlal
17 *
Johannes Weiner1575e682015-04-14 15:44:51 -070018 * Native page reclaim
19 * Charge lifetime sanitation
20 * Lockless page tracking & accounting
21 * Unified hierarchy configuration model
22 * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
Balbir Singh8cdea7c2008-02-07 00:13:50 -080023 */
24
Johannes Weiner3e32cb22014-12-10 15:42:31 -080025#include <linux/page_counter.h>
Balbir Singh8cdea7c2008-02-07 00:13:50 -080026#include <linux/memcontrol.h>
27#include <linux/cgroup.h>
Christoph Hellwiga5201102019-08-28 16:19:53 +020028#include <linux/pagewalk.h>
Ingo Molnar6e84f312017-02-08 18:51:29 +010029#include <linux/sched/mm.h>
Hugh Dickins3a4f8a02017-02-24 14:59:36 -080030#include <linux/shmem_fs.h>
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -080031#include <linux/hugetlb.h>
KAMEZAWA Hiroyukid13d1442009-01-07 18:07:56 -080032#include <linux/pagemap.h>
Chris Down1ff9e6e2019-03-05 15:48:09 -080033#include <linux/vm_event_item.h>
KAMEZAWA Hiroyukid52aa412008-02-07 00:14:24 -080034#include <linux/smp.h>
Balbir Singh8a9f3cc2008-02-07 00:13:53 -080035#include <linux/page-flags.h>
Balbir Singh66e17072008-02-07 00:13:56 -080036#include <linux/backing-dev.h>
Balbir Singh8a9f3cc2008-02-07 00:13:53 -080037#include <linux/bit_spinlock.h>
38#include <linux/rcupdate.h>
Balbir Singhe2224322009-04-02 16:57:39 -070039#include <linux/limits.h>
Paul Gortmakerb9e15ba2011-05-26 16:00:52 -040040#include <linux/export.h>
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -080041#include <linux/mutex.h>
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -070042#include <linux/rbtree.h>
Balbir Singhb6ac57d2008-04-29 01:00:19 -070043#include <linux/slab.h>
Balbir Singh66e17072008-02-07 00:13:56 -080044#include <linux/swap.h>
Daisuke Nishimura02491442010-03-10 15:22:17 -080045#include <linux/swapops.h>
Balbir Singh66e17072008-02-07 00:13:56 -080046#include <linux/spinlock.h>
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -080047#include <linux/eventfd.h>
Tejun Heo79bd9812013-11-22 18:20:42 -050048#include <linux/poll.h>
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -080049#include <linux/sort.h>
Balbir Singh66e17072008-02-07 00:13:56 -080050#include <linux/fs.h>
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -080051#include <linux/seq_file.h>
Anton Vorontsov70ddf632013-04-29 15:08:31 -070052#include <linux/vmpressure.h>
Christoph Lameterb69408e2008-10-18 20:26:14 -070053#include <linux/mm_inline.h>
Johannes Weiner5d1ea482014-12-10 15:44:55 -080054#include <linux/swap_cgroup.h>
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -080055#include <linux/cpu.h>
KAMEZAWA Hiroyuki158e0a22010-08-10 18:03:00 -070056#include <linux/oom.h>
Johannes Weiner0056f4e2013-10-31 16:34:14 -070057#include <linux/lockdep.h>
Tejun Heo79bd9812013-11-22 18:20:42 -050058#include <linux/file.h>
Tejun Heob23afb92015-11-05 18:46:11 -080059#include <linux/tracehook.h>
Chris Down0e4b01d2019-09-23 15:34:55 -070060#include <linux/psi.h>
Johannes Weinerc8713d02019-07-11 20:55:59 -070061#include <linux/seq_buf.h>
KAMEZAWA Hiroyuki08e552c2009-01-07 18:08:01 -080062#include "internal.h"
Glauber Costad1a4c0b2011-12-11 21:47:04 +000063#include <net/sock.h>
Michal Hocko4bd2c1e2012-10-08 16:33:10 -070064#include <net/ip.h>
Qiang Huangf35c3a82013-11-12 15:08:22 -080065#include "slab.h"
Balbir Singh8cdea7c2008-02-07 00:13:50 -080066
Linus Torvalds7c0f6ba2016-12-24 11:46:01 -080067#include <linux/uaccess.h>
Balbir Singh8697d332008-02-07 00:13:59 -080068
KOSAKI Motohirocc8e9702010-08-09 17:19:57 -070069#include <trace/events/vmscan.h>
70
Tejun Heo073219e2014-02-08 10:36:58 -050071struct cgroup_subsys memory_cgrp_subsys __read_mostly;
72EXPORT_SYMBOL(memory_cgrp_subsys);
David Rientjes68ae5642012-12-12 13:51:57 -080073
Johannes Weiner7d828602016-01-14 15:20:56 -080074struct mem_cgroup *root_mem_cgroup __read_mostly;
75
KAMEZAWA Hiroyukia181b0e2008-07-25 01:47:08 -070076#define MEM_CGROUP_RECLAIM_RETRIES 5
Balbir Singh8cdea7c2008-02-07 00:13:50 -080077
Johannes Weinerf7e1cb62016-01-14 15:21:29 -080078/* Socket memory accounting disabled? */
79static bool cgroup_memory_nosocket;
80
Vladimir Davydov04823c82016-01-20 15:02:38 -080081/* Kernel memory accounting disabled? */
82static bool cgroup_memory_nokmem;
83
Johannes Weiner21afa382015-02-11 15:26:36 -080084/* Whether the swap controller is active */
Andrew Mortonc255a452012-07-31 16:43:02 -070085#ifdef CONFIG_MEMCG_SWAP
KAMEZAWA Hiroyukic0777192009-01-07 18:07:57 -080086int do_swap_account __read_mostly;
KAMEZAWA Hiroyukic0777192009-01-07 18:07:57 -080087#else
Kirill A. Shutemova0db00f2012-05-29 15:06:56 -070088#define do_swap_account 0
KAMEZAWA Hiroyukic0777192009-01-07 18:07:57 -080089#endif
90
Tejun Heo97b27822019-08-26 09:06:56 -070091#ifdef CONFIG_CGROUP_WRITEBACK
92static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
93#endif
94
Johannes Weiner7941d212016-01-14 15:21:23 -080095/* Whether legacy memory+swap accounting is active */
96static bool do_memsw_account(void)
97{
98 return !cgroup_subsys_on_dfl(memory_cgrp_subsys) && do_swap_account;
99}
100
Johannes Weiner71cd3112017-05-03 14:55:13 -0700101static const char *const mem_cgroup_lru_names[] = {
Sha Zhengju58cf1882013-02-22 16:32:05 -0800102 "inactive_anon",
103 "active_anon",
104 "inactive_file",
105 "active_file",
106 "unevictable",
107};
108
Kirill A. Shutemova0db00f2012-05-29 15:06:56 -0700109#define THRESHOLDS_EVENTS_TARGET 128
110#define SOFTLIMIT_EVENTS_TARGET 1024
111#define NUMAINFO_EVENTS_TARGET 1024
Johannes Weinere9f89742011-03-23 16:42:37 -0700112
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700113/*
114 * Cgroups above their limits are maintained in a RB-Tree, independent of
115 * their hierarchy representation
116 */
117
Mel Gormanef8f2322016-07-28 15:46:05 -0700118struct mem_cgroup_tree_per_node {
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700119 struct rb_root rb_root;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700120 struct rb_node *rb_rightmost;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700121 spinlock_t lock;
122};
123
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700124struct mem_cgroup_tree {
125 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
126};
127
128static struct mem_cgroup_tree soft_limit_tree __read_mostly;
129
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -0700130/* for OOM */
131struct mem_cgroup_eventfd_list {
132 struct list_head list;
133 struct eventfd_ctx *eventfd;
134};
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -0800135
Tejun Heo79bd9812013-11-22 18:20:42 -0500136/*
137 * cgroup_event represents events which userspace want to receive.
138 */
Tejun Heo3bc942f2013-11-22 18:20:44 -0500139struct mem_cgroup_event {
Tejun Heo79bd9812013-11-22 18:20:42 -0500140 /*
Tejun Heo59b6f872013-11-22 18:20:43 -0500141 * memcg which the event belongs to.
Tejun Heo79bd9812013-11-22 18:20:42 -0500142 */
Tejun Heo59b6f872013-11-22 18:20:43 -0500143 struct mem_cgroup *memcg;
Tejun Heo79bd9812013-11-22 18:20:42 -0500144 /*
Tejun Heo79bd9812013-11-22 18:20:42 -0500145 * eventfd to signal userspace about the event.
146 */
147 struct eventfd_ctx *eventfd;
148 /*
149 * Each of these stored in a list by the cgroup.
150 */
151 struct list_head list;
152 /*
Tejun Heofba94802013-11-22 18:20:43 -0500153 * register_event() callback will be used to add new userspace
154 * waiter for changes related to this event. Use eventfd_signal()
155 * on eventfd to send notification to userspace.
156 */
Tejun Heo59b6f872013-11-22 18:20:43 -0500157 int (*register_event)(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -0500158 struct eventfd_ctx *eventfd, const char *args);
Tejun Heofba94802013-11-22 18:20:43 -0500159 /*
160 * unregister_event() callback will be called when userspace closes
161 * the eventfd or on cgroup removing. This callback must be set,
162 * if you want provide notification functionality.
163 */
Tejun Heo59b6f872013-11-22 18:20:43 -0500164 void (*unregister_event)(struct mem_cgroup *memcg,
Tejun Heofba94802013-11-22 18:20:43 -0500165 struct eventfd_ctx *eventfd);
166 /*
Tejun Heo79bd9812013-11-22 18:20:42 -0500167 * All fields below needed to unregister event when
168 * userspace closes eventfd.
169 */
170 poll_table pt;
171 wait_queue_head_t *wqh;
Ingo Molnarac6424b2017-06-20 12:06:13 +0200172 wait_queue_entry_t wait;
Tejun Heo79bd9812013-11-22 18:20:42 -0500173 struct work_struct remove;
174};
175
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -0700176static void mem_cgroup_threshold(struct mem_cgroup *memcg);
177static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -0800178
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -0800179/* Stuffs for move charges at task migration. */
180/*
Johannes Weiner1dfab5a2015-02-11 15:26:09 -0800181 * Types of charges to be moved.
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -0800182 */
Johannes Weiner1dfab5a2015-02-11 15:26:09 -0800183#define MOVE_ANON 0x1U
184#define MOVE_FILE 0x2U
185#define MOVE_MASK (MOVE_ANON | MOVE_FILE)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -0800186
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -0800187/* "mc" and its members are protected by cgroup_mutex */
188static struct move_charge_struct {
Daisuke Nishimurab1dd6932010-11-24 12:57:06 -0800189 spinlock_t lock; /* for from, to */
Tejun Heo264a0ae2016-04-21 19:09:02 -0400190 struct mm_struct *mm;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -0800191 struct mem_cgroup *from;
192 struct mem_cgroup *to;
Johannes Weiner1dfab5a2015-02-11 15:26:09 -0800193 unsigned long flags;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -0800194 unsigned long precharge;
Daisuke Nishimura854ffa82010-03-10 15:22:15 -0800195 unsigned long moved_charge;
Daisuke Nishimura483c30b2010-03-10 15:22:18 -0800196 unsigned long moved_swap;
Daisuke Nishimura8033b972010-03-10 15:22:16 -0800197 struct task_struct *moving_task; /* a task moving charges */
198 wait_queue_head_t waitq; /* a waitq for other context */
199} mc = {
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -0700200 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
Daisuke Nishimura8033b972010-03-10 15:22:16 -0800201 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
202};
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -0800203
Balbir Singh4e416952009-09-23 15:56:39 -0700204/*
205 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
206 * limit reclaim to prevent infinite loops, if they ever occur.
207 */
Kirill A. Shutemova0db00f2012-05-29 15:06:56 -0700208#define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700209#define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
Balbir Singh4e416952009-09-23 15:56:39 -0700210
KAMEZAWA Hiroyuki217bc312008-02-07 00:14:17 -0800211enum charge_type {
212 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
Kamezawa Hiroyuki41326c12012-07-31 16:41:40 -0700213 MEM_CGROUP_CHARGE_TYPE_ANON,
KAMEZAWA Hiroyukid13d1442009-01-07 18:07:56 -0800214 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
KAMEZAWA Hiroyuki8a9478c2009-06-17 16:27:17 -0700215 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
KAMEZAWA Hiroyukic05555b2008-10-18 20:28:11 -0700216 NR_CHARGE_TYPE,
217};
218
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -0800219/* for encoding cft->private value on file */
Glauber Costa86ae53e2012-12-18 14:21:45 -0800220enum res_type {
221 _MEM,
222 _MEMSWAP,
223 _OOM_TYPE,
Glauber Costa510fc4e2012-12-18 14:21:47 -0800224 _KMEM,
Vladimir Davydovd55f90b2016-01-20 15:02:44 -0800225 _TCP,
Glauber Costa86ae53e2012-12-18 14:21:45 -0800226};
227
Kirill A. Shutemova0db00f2012-05-29 15:06:56 -0700228#define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
229#define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -0800230#define MEMFILE_ATTR(val) ((val) & 0xffff)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -0700231/* Used for OOM nofiier */
232#define OOM_CONTROL (0)
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -0800233
Kirill Tkhaib05706f2018-08-17 15:47:33 -0700234/*
235 * Iteration constructs for visiting all cgroups (under a tree). If
236 * loops are exited prematurely (break), mem_cgroup_iter_break() must
237 * be used for reference counting.
238 */
239#define for_each_mem_cgroup_tree(iter, root) \
240 for (iter = mem_cgroup_iter(root, NULL, NULL); \
241 iter != NULL; \
242 iter = mem_cgroup_iter(root, iter, NULL))
243
244#define for_each_mem_cgroup(iter) \
245 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
246 iter != NULL; \
247 iter = mem_cgroup_iter(NULL, iter, NULL))
248
Tetsuo Handa7775fac2019-03-05 15:46:47 -0800249static inline bool should_force_charge(void)
250{
251 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
252 (current->flags & PF_EXITING);
253}
254
Anton Vorontsov70ddf632013-04-29 15:08:31 -0700255/* Some nice accessors for the vmpressure. */
256struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
257{
258 if (!memcg)
259 memcg = root_mem_cgroup;
260 return &memcg->vmpressure;
261}
262
263struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
264{
265 return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
266}
267
Kirill Tkhai84c07d12018-08-17 15:47:25 -0700268#ifdef CONFIG_MEMCG_KMEM
Glauber Costa55007d82012-12-18 14:22:38 -0800269/*
Vladimir Davydovf7ce3192015-02-12 14:59:20 -0800270 * This will be the memcg's index in each cache's ->memcg_params.memcg_caches.
Li Zefanb8627832013-09-23 16:56:47 +0800271 * The main reason for not using cgroup id for this:
272 * this works better in sparse environments, where we have a lot of memcgs,
273 * but only a few kmem-limited. Or also, if we have, for instance, 200
274 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
275 * 200 entry array for that.
Glauber Costa55007d82012-12-18 14:22:38 -0800276 *
Vladimir Davydovdbcf73e2015-02-12 14:58:57 -0800277 * The current size of the caches array is stored in memcg_nr_cache_ids. It
278 * will double each time we have to increase it.
Glauber Costa55007d82012-12-18 14:22:38 -0800279 */
Vladimir Davydovdbcf73e2015-02-12 14:58:57 -0800280static DEFINE_IDA(memcg_cache_ida);
281int memcg_nr_cache_ids;
Glauber Costa749c5412012-12-18 14:23:01 -0800282
Vladimir Davydov05257a12015-02-12 14:59:01 -0800283/* Protects memcg_nr_cache_ids */
284static DECLARE_RWSEM(memcg_cache_ids_sem);
285
286void memcg_get_cache_ids(void)
287{
288 down_read(&memcg_cache_ids_sem);
289}
290
291void memcg_put_cache_ids(void)
292{
293 up_read(&memcg_cache_ids_sem);
294}
295
Glauber Costa55007d82012-12-18 14:22:38 -0800296/*
297 * MIN_SIZE is different than 1, because we would like to avoid going through
298 * the alloc/free process all the time. In a small machine, 4 kmem-limited
299 * cgroups is a reasonable guess. In the future, it could be a parameter or
300 * tunable, but that is strictly not necessary.
301 *
Li Zefanb8627832013-09-23 16:56:47 +0800302 * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
Glauber Costa55007d82012-12-18 14:22:38 -0800303 * this constant directly from cgroup, but it is understandable that this is
304 * better kept as an internal representation in cgroup.c. In any case, the
Li Zefanb8627832013-09-23 16:56:47 +0800305 * cgrp_id space is not getting any smaller, and we don't have to necessarily
Glauber Costa55007d82012-12-18 14:22:38 -0800306 * increase ours as well if it increases.
307 */
308#define MEMCG_CACHES_MIN_SIZE 4
Li Zefanb8627832013-09-23 16:56:47 +0800309#define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
Glauber Costa55007d82012-12-18 14:22:38 -0800310
Glauber Costad7f25f82012-12-18 14:22:40 -0800311/*
312 * A lot of the calls to the cache allocation functions are expected to be
313 * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
314 * conditional to this static branch, we'll have to allow modules that does
315 * kmem_cache_alloc and the such to see this symbol as well
316 */
Johannes Weineref129472016-01-14 15:21:34 -0800317DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
Glauber Costad7f25f82012-12-18 14:22:40 -0800318EXPORT_SYMBOL(memcg_kmem_enabled_key);
Glauber Costaa8964b92012-12-18 14:22:09 -0800319
Tejun Heo17cc4df2017-02-22 15:41:36 -0800320struct workqueue_struct *memcg_kmem_cache_wq;
Yang Shi0a432dc2019-09-23 15:38:12 -0700321#endif
Tejun Heo17cc4df2017-02-22 15:41:36 -0800322
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700323static int memcg_shrinker_map_size;
324static DEFINE_MUTEX(memcg_shrinker_map_mutex);
325
326static void memcg_free_shrinker_map_rcu(struct rcu_head *head)
327{
328 kvfree(container_of(head, struct memcg_shrinker_map, rcu));
329}
330
331static int memcg_expand_one_shrinker_map(struct mem_cgroup *memcg,
332 int size, int old_size)
333{
334 struct memcg_shrinker_map *new, *old;
335 int nid;
336
337 lockdep_assert_held(&memcg_shrinker_map_mutex);
338
339 for_each_node(nid) {
340 old = rcu_dereference_protected(
341 mem_cgroup_nodeinfo(memcg, nid)->shrinker_map, true);
342 /* Not yet online memcg */
343 if (!old)
344 return 0;
345
346 new = kvmalloc(sizeof(*new) + size, GFP_KERNEL);
347 if (!new)
348 return -ENOMEM;
349
350 /* Set all old bits, clear all new bits */
351 memset(new->map, (int)0xff, old_size);
352 memset((void *)new->map + old_size, 0, size - old_size);
353
354 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, new);
355 call_rcu(&old->rcu, memcg_free_shrinker_map_rcu);
356 }
357
358 return 0;
359}
360
361static void memcg_free_shrinker_maps(struct mem_cgroup *memcg)
362{
363 struct mem_cgroup_per_node *pn;
364 struct memcg_shrinker_map *map;
365 int nid;
366
367 if (mem_cgroup_is_root(memcg))
368 return;
369
370 for_each_node(nid) {
371 pn = mem_cgroup_nodeinfo(memcg, nid);
372 map = rcu_dereference_protected(pn->shrinker_map, true);
373 if (map)
374 kvfree(map);
375 rcu_assign_pointer(pn->shrinker_map, NULL);
376 }
377}
378
379static int memcg_alloc_shrinker_maps(struct mem_cgroup *memcg)
380{
381 struct memcg_shrinker_map *map;
382 int nid, size, ret = 0;
383
384 if (mem_cgroup_is_root(memcg))
385 return 0;
386
387 mutex_lock(&memcg_shrinker_map_mutex);
388 size = memcg_shrinker_map_size;
389 for_each_node(nid) {
390 map = kvzalloc(sizeof(*map) + size, GFP_KERNEL);
391 if (!map) {
392 memcg_free_shrinker_maps(memcg);
393 ret = -ENOMEM;
394 break;
395 }
396 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, map);
397 }
398 mutex_unlock(&memcg_shrinker_map_mutex);
399
400 return ret;
401}
402
403int memcg_expand_shrinker_maps(int new_id)
404{
405 int size, old_size, ret = 0;
406 struct mem_cgroup *memcg;
407
408 size = DIV_ROUND_UP(new_id + 1, BITS_PER_LONG) * sizeof(unsigned long);
409 old_size = memcg_shrinker_map_size;
410 if (size <= old_size)
411 return 0;
412
413 mutex_lock(&memcg_shrinker_map_mutex);
414 if (!root_mem_cgroup)
415 goto unlock;
416
417 for_each_mem_cgroup(memcg) {
418 if (mem_cgroup_is_root(memcg))
419 continue;
420 ret = memcg_expand_one_shrinker_map(memcg, size, old_size);
421 if (ret)
422 goto unlock;
423 }
424unlock:
425 if (!ret)
426 memcg_shrinker_map_size = size;
427 mutex_unlock(&memcg_shrinker_map_mutex);
428 return ret;
429}
Kirill Tkhaifae91d62018-08-17 15:48:10 -0700430
431void memcg_set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
432{
433 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
434 struct memcg_shrinker_map *map;
435
436 rcu_read_lock();
437 map = rcu_dereference(memcg->nodeinfo[nid]->shrinker_map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700438 /* Pairs with smp mb in shrink_slab() */
439 smp_mb__before_atomic();
Kirill Tkhaifae91d62018-08-17 15:48:10 -0700440 set_bit(shrinker_id, map->map);
441 rcu_read_unlock();
442 }
443}
444
Tejun Heoad7fa852015-05-27 20:00:02 -0400445/**
446 * mem_cgroup_css_from_page - css of the memcg associated with a page
447 * @page: page of interest
448 *
449 * If memcg is bound to the default hierarchy, css of the memcg associated
450 * with @page is returned. The returned css remains associated with @page
451 * until it is released.
452 *
453 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
454 * is returned.
Tejun Heoad7fa852015-05-27 20:00:02 -0400455 */
456struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
457{
458 struct mem_cgroup *memcg;
459
Tejun Heoad7fa852015-05-27 20:00:02 -0400460 memcg = page->mem_cgroup;
461
Tejun Heo9e10a132015-09-18 11:56:28 -0400462 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heoad7fa852015-05-27 20:00:02 -0400463 memcg = root_mem_cgroup;
464
Tejun Heoad7fa852015-05-27 20:00:02 -0400465 return &memcg->css;
466}
467
Vladimir Davydov2fc04522015-09-09 15:35:28 -0700468/**
469 * page_cgroup_ino - return inode number of the memcg a page is charged to
470 * @page: the page
471 *
472 * Look up the closest online ancestor of the memory cgroup @page is charged to
473 * and return its inode number or 0 if @page is not charged to any cgroup. It
474 * is safe to call this function without holding a reference to @page.
475 *
476 * Note, this function is inherently racy, because there is nothing to prevent
477 * the cgroup inode from getting torn down and potentially reallocated a moment
478 * after page_cgroup_ino() returns, so it only should be used by callers that
479 * do not care (such as procfs interfaces).
480 */
481ino_t page_cgroup_ino(struct page *page)
482{
483 struct mem_cgroup *memcg;
484 unsigned long ino = 0;
485
486 rcu_read_lock();
Roman Gushchin221ec5c2019-11-05 21:17:03 -0800487 if (PageSlab(page) && !PageTail(page))
Roman Gushchin4d96ba32019-07-11 20:56:31 -0700488 memcg = memcg_from_slab_page(page);
489 else
490 memcg = READ_ONCE(page->mem_cgroup);
Vladimir Davydov2fc04522015-09-09 15:35:28 -0700491 while (memcg && !(memcg->css.flags & CSS_ONLINE))
492 memcg = parent_mem_cgroup(memcg);
493 if (memcg)
494 ino = cgroup_ino(memcg->css.cgroup);
495 rcu_read_unlock();
496 return ino;
497}
498
Mel Gormanef8f2322016-07-28 15:46:05 -0700499static struct mem_cgroup_per_node *
500mem_cgroup_page_nodeinfo(struct mem_cgroup *memcg, struct page *page)
Balbir Singhf64c3f52009-09-23 15:56:37 -0700501{
Johannes Weiner97a6c372011-03-23 16:42:27 -0700502 int nid = page_to_nid(page);
Balbir Singhf64c3f52009-09-23 15:56:37 -0700503
Mel Gormanef8f2322016-07-28 15:46:05 -0700504 return memcg->nodeinfo[nid];
Balbir Singhf64c3f52009-09-23 15:56:37 -0700505}
506
Mel Gormanef8f2322016-07-28 15:46:05 -0700507static struct mem_cgroup_tree_per_node *
508soft_limit_tree_node(int nid)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700509{
Mel Gormanef8f2322016-07-28 15:46:05 -0700510 return soft_limit_tree.rb_tree_per_node[nid];
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700511}
512
Mel Gormanef8f2322016-07-28 15:46:05 -0700513static struct mem_cgroup_tree_per_node *
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700514soft_limit_tree_from_page(struct page *page)
515{
516 int nid = page_to_nid(page);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700517
Mel Gormanef8f2322016-07-28 15:46:05 -0700518 return soft_limit_tree.rb_tree_per_node[nid];
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700519}
520
Mel Gormanef8f2322016-07-28 15:46:05 -0700521static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
522 struct mem_cgroup_tree_per_node *mctz,
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800523 unsigned long new_usage_in_excess)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700524{
525 struct rb_node **p = &mctz->rb_root.rb_node;
526 struct rb_node *parent = NULL;
Mel Gormanef8f2322016-07-28 15:46:05 -0700527 struct mem_cgroup_per_node *mz_node;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700528 bool rightmost = true;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700529
530 if (mz->on_tree)
531 return;
532
533 mz->usage_in_excess = new_usage_in_excess;
534 if (!mz->usage_in_excess)
535 return;
536 while (*p) {
537 parent = *p;
Mel Gormanef8f2322016-07-28 15:46:05 -0700538 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700539 tree_node);
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700540 if (mz->usage_in_excess < mz_node->usage_in_excess) {
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700541 p = &(*p)->rb_left;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700542 rightmost = false;
543 }
544
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700545 /*
546 * We can't avoid mem cgroups that are over their soft
547 * limit by the same amount
548 */
549 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
550 p = &(*p)->rb_right;
551 }
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700552
553 if (rightmost)
554 mctz->rb_rightmost = &mz->tree_node;
555
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700556 rb_link_node(&mz->tree_node, parent, p);
557 rb_insert_color(&mz->tree_node, &mctz->rb_root);
558 mz->on_tree = true;
559}
560
Mel Gormanef8f2322016-07-28 15:46:05 -0700561static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
562 struct mem_cgroup_tree_per_node *mctz)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700563{
564 if (!mz->on_tree)
565 return;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700566
567 if (&mz->tree_node == mctz->rb_rightmost)
568 mctz->rb_rightmost = rb_prev(&mz->tree_node);
569
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700570 rb_erase(&mz->tree_node, &mctz->rb_root);
571 mz->on_tree = false;
572}
573
Mel Gormanef8f2322016-07-28 15:46:05 -0700574static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
575 struct mem_cgroup_tree_per_node *mctz)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700576{
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700577 unsigned long flags;
578
579 spin_lock_irqsave(&mctz->lock, flags);
Johannes Weinercf2c8122014-06-06 14:38:21 -0700580 __mem_cgroup_remove_exceeded(mz, mctz);
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700581 spin_unlock_irqrestore(&mctz->lock, flags);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700582}
583
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800584static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
585{
586 unsigned long nr_pages = page_counter_read(&memcg->memory);
Jason Low4db0c3c2015-04-15 16:14:08 -0700587 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800588 unsigned long excess = 0;
589
590 if (nr_pages > soft_limit)
591 excess = nr_pages - soft_limit;
592
593 return excess;
594}
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700595
596static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
597{
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800598 unsigned long excess;
Mel Gormanef8f2322016-07-28 15:46:05 -0700599 struct mem_cgroup_per_node *mz;
600 struct mem_cgroup_tree_per_node *mctz;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700601
Jianyu Zhane2318752014-06-06 14:38:20 -0700602 mctz = soft_limit_tree_from_page(page);
Laurent Dufourbfc72282017-03-09 16:17:06 -0800603 if (!mctz)
604 return;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700605 /*
606 * Necessary to update all ancestors when hierarchy is used.
607 * because their event counter is not touched.
608 */
609 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
Mel Gormanef8f2322016-07-28 15:46:05 -0700610 mz = mem_cgroup_page_nodeinfo(memcg, page);
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800611 excess = soft_limit_excess(memcg);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700612 /*
613 * We have to update the tree if mz is on RB-tree or
614 * mem is over its softlimit.
615 */
616 if (excess || mz->on_tree) {
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700617 unsigned long flags;
618
619 spin_lock_irqsave(&mctz->lock, flags);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700620 /* if on-tree, remove it */
621 if (mz->on_tree)
Johannes Weinercf2c8122014-06-06 14:38:21 -0700622 __mem_cgroup_remove_exceeded(mz, mctz);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700623 /*
624 * Insert again. mz->usage_in_excess will be updated.
625 * If excess is 0, no tree ops.
626 */
Johannes Weinercf2c8122014-06-06 14:38:21 -0700627 __mem_cgroup_insert_exceeded(mz, mctz, excess);
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700628 spin_unlock_irqrestore(&mctz->lock, flags);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700629 }
630 }
631}
632
633static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
634{
Mel Gormanef8f2322016-07-28 15:46:05 -0700635 struct mem_cgroup_tree_per_node *mctz;
636 struct mem_cgroup_per_node *mz;
637 int nid;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700638
Jianyu Zhane2318752014-06-06 14:38:20 -0700639 for_each_node(nid) {
Mel Gormanef8f2322016-07-28 15:46:05 -0700640 mz = mem_cgroup_nodeinfo(memcg, nid);
641 mctz = soft_limit_tree_node(nid);
Laurent Dufourbfc72282017-03-09 16:17:06 -0800642 if (mctz)
643 mem_cgroup_remove_exceeded(mz, mctz);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700644 }
645}
646
Mel Gormanef8f2322016-07-28 15:46:05 -0700647static struct mem_cgroup_per_node *
648__mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700649{
Mel Gormanef8f2322016-07-28 15:46:05 -0700650 struct mem_cgroup_per_node *mz;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700651
652retry:
653 mz = NULL;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700654 if (!mctz->rb_rightmost)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700655 goto done; /* Nothing to reclaim from */
656
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700657 mz = rb_entry(mctz->rb_rightmost,
658 struct mem_cgroup_per_node, tree_node);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700659 /*
660 * Remove the node now but someone else can add it back,
661 * we will to add it back at the end of reclaim to its correct
662 * position in the tree.
663 */
Johannes Weinercf2c8122014-06-06 14:38:21 -0700664 __mem_cgroup_remove_exceeded(mz, mctz);
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800665 if (!soft_limit_excess(mz->memcg) ||
Tejun Heoec903c02014-05-13 12:11:01 -0400666 !css_tryget_online(&mz->memcg->css))
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700667 goto retry;
668done:
669 return mz;
670}
671
Mel Gormanef8f2322016-07-28 15:46:05 -0700672static struct mem_cgroup_per_node *
673mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700674{
Mel Gormanef8f2322016-07-28 15:46:05 -0700675 struct mem_cgroup_per_node *mz;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700676
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700677 spin_lock_irq(&mctz->lock);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700678 mz = __mem_cgroup_largest_soft_limit_node(mctz);
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700679 spin_unlock_irq(&mctz->lock);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700680 return mz;
681}
682
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700683/**
684 * __mod_memcg_state - update cgroup memory statistics
685 * @memcg: the memory cgroup
686 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
687 * @val: delta to add to the counter, can be negative
688 */
689void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
690{
691 long x;
692
693 if (mem_cgroup_disabled())
694 return;
695
696 x = val + __this_cpu_read(memcg->vmstats_percpu->stat[idx]);
697 if (unlikely(abs(x) > MEMCG_CHARGE_BATCH)) {
Johannes Weiner42a30032019-05-14 15:47:12 -0700698 struct mem_cgroup *mi;
699
Yafang Shao766a4c12019-07-16 16:26:06 -0700700 /*
701 * Batch local counters to keep them in sync with
702 * the hierarchical ones.
703 */
704 __this_cpu_add(memcg->vmstats_local->stat[idx], x);
Johannes Weiner42a30032019-05-14 15:47:12 -0700705 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
706 atomic_long_add(x, &mi->vmstats[idx]);
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700707 x = 0;
708 }
709 __this_cpu_write(memcg->vmstats_percpu->stat[idx], x);
710}
711
Johannes Weiner42a30032019-05-14 15:47:12 -0700712static struct mem_cgroup_per_node *
713parent_nodeinfo(struct mem_cgroup_per_node *pn, int nid)
714{
715 struct mem_cgroup *parent;
716
717 parent = parent_mem_cgroup(pn->memcg);
718 if (!parent)
719 return NULL;
720 return mem_cgroup_nodeinfo(parent, nid);
721}
722
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700723/**
724 * __mod_lruvec_state - update lruvec memory statistics
725 * @lruvec: the lruvec
726 * @idx: the stat item
727 * @val: delta to add to the counter, can be negative
728 *
729 * The lruvec is the intersection of the NUMA node and a cgroup. This
730 * function updates the all three counters that are affected by a
731 * change of state at this level: per-node, per-cgroup, per-lruvec.
732 */
733void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
734 int val)
735{
Johannes Weiner42a30032019-05-14 15:47:12 -0700736 pg_data_t *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700737 struct mem_cgroup_per_node *pn;
Johannes Weiner42a30032019-05-14 15:47:12 -0700738 struct mem_cgroup *memcg;
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700739 long x;
740
741 /* Update node */
Johannes Weiner42a30032019-05-14 15:47:12 -0700742 __mod_node_page_state(pgdat, idx, val);
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700743
744 if (mem_cgroup_disabled())
745 return;
746
747 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
Johannes Weiner42a30032019-05-14 15:47:12 -0700748 memcg = pn->memcg;
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700749
750 /* Update memcg */
Johannes Weiner42a30032019-05-14 15:47:12 -0700751 __mod_memcg_state(memcg, idx, val);
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700752
Roman Gushchinb4c46482019-08-30 16:04:39 -0700753 /* Update lruvec */
754 __this_cpu_add(pn->lruvec_stat_local->count[idx], val);
755
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700756 x = val + __this_cpu_read(pn->lruvec_stat_cpu->count[idx]);
757 if (unlikely(abs(x) > MEMCG_CHARGE_BATCH)) {
Johannes Weiner42a30032019-05-14 15:47:12 -0700758 struct mem_cgroup_per_node *pi;
759
Johannes Weiner42a30032019-05-14 15:47:12 -0700760 for (pi = pn; pi; pi = parent_nodeinfo(pi, pgdat->node_id))
761 atomic_long_add(x, &pi->lruvec_stat[idx]);
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700762 x = 0;
763 }
764 __this_cpu_write(pn->lruvec_stat_cpu->count[idx], x);
765}
766
Roman Gushchinec9f0232019-08-13 15:37:41 -0700767void __mod_lruvec_slab_state(void *p, enum node_stat_item idx, int val)
768{
769 struct page *page = virt_to_head_page(p);
770 pg_data_t *pgdat = page_pgdat(page);
771 struct mem_cgroup *memcg;
772 struct lruvec *lruvec;
773
774 rcu_read_lock();
775 memcg = memcg_from_slab_page(page);
776
777 /* Untracked pages have no memcg, no lruvec. Update only the node */
778 if (!memcg || memcg == root_mem_cgroup) {
779 __mod_node_page_state(pgdat, idx, val);
780 } else {
781 lruvec = mem_cgroup_lruvec(pgdat, memcg);
782 __mod_lruvec_state(lruvec, idx, val);
783 }
784 rcu_read_unlock();
785}
786
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700787/**
788 * __count_memcg_events - account VM events in a cgroup
789 * @memcg: the memory cgroup
790 * @idx: the event item
791 * @count: the number of events that occured
792 */
793void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
794 unsigned long count)
795{
796 unsigned long x;
797
798 if (mem_cgroup_disabled())
799 return;
800
801 x = count + __this_cpu_read(memcg->vmstats_percpu->events[idx]);
802 if (unlikely(x > MEMCG_CHARGE_BATCH)) {
Johannes Weiner42a30032019-05-14 15:47:12 -0700803 struct mem_cgroup *mi;
804
Yafang Shao766a4c12019-07-16 16:26:06 -0700805 /*
806 * Batch local counters to keep them in sync with
807 * the hierarchical ones.
808 */
809 __this_cpu_add(memcg->vmstats_local->events[idx], x);
Johannes Weiner42a30032019-05-14 15:47:12 -0700810 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
811 atomic_long_add(x, &mi->vmevents[idx]);
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700812 x = 0;
813 }
814 __this_cpu_write(memcg->vmstats_percpu->events[idx], x);
815}
816
Johannes Weiner42a30032019-05-14 15:47:12 -0700817static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
Johannes Weinere9f89742011-03-23 16:42:37 -0700818{
Chris Down871789d2019-05-14 15:46:57 -0700819 return atomic_long_read(&memcg->vmevents[event]);
Johannes Weinere9f89742011-03-23 16:42:37 -0700820}
821
Johannes Weiner42a30032019-05-14 15:47:12 -0700822static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
823{
Johannes Weiner815744d2019-06-13 15:55:46 -0700824 long x = 0;
825 int cpu;
826
827 for_each_possible_cpu(cpu)
828 x += per_cpu(memcg->vmstats_local->events[event], cpu);
829 return x;
Johannes Weiner42a30032019-05-14 15:47:12 -0700830}
831
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -0700832static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
David Rientjesb070e652013-05-07 16:18:09 -0700833 struct page *page,
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -0800834 bool compound, int nr_pages)
KAMEZAWA Hiroyukid52aa412008-02-07 00:14:24 -0800835{
KAMEZAWA Hiroyukib24028572012-03-21 16:34:22 -0700836 /*
837 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
838 * counted as CACHE even if it's on ANON LRU.
839 */
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700840 if (PageAnon(page))
Johannes Weinerc9019e92018-01-31 16:16:37 -0800841 __mod_memcg_state(memcg, MEMCG_RSS, nr_pages);
Johannes Weiner9a4caf12017-05-03 14:52:45 -0700842 else {
Johannes Weinerc9019e92018-01-31 16:16:37 -0800843 __mod_memcg_state(memcg, MEMCG_CACHE, nr_pages);
Johannes Weiner9a4caf12017-05-03 14:52:45 -0700844 if (PageSwapBacked(page))
Johannes Weinerc9019e92018-01-31 16:16:37 -0800845 __mod_memcg_state(memcg, NR_SHMEM, nr_pages);
Johannes Weiner9a4caf12017-05-03 14:52:45 -0700846 }
Balaji Rao55e462b2008-05-01 04:35:12 -0700847
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -0800848 if (compound) {
849 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
Johannes Weinerc9019e92018-01-31 16:16:37 -0800850 __mod_memcg_state(memcg, MEMCG_RSS_HUGE, nr_pages);
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -0800851 }
David Rientjesb070e652013-05-07 16:18:09 -0700852
KAMEZAWA Hiroyukie401f172011-01-20 14:44:23 -0800853 /* pagein of a big page is an event. So, ignore page size */
854 if (nr_pages > 0)
Johannes Weinerc9019e92018-01-31 16:16:37 -0800855 __count_memcg_events(memcg, PGPGIN, 1);
KAMEZAWA Hiroyuki3751d602011-02-01 15:52:45 -0800856 else {
Johannes Weinerc9019e92018-01-31 16:16:37 -0800857 __count_memcg_events(memcg, PGPGOUT, 1);
KAMEZAWA Hiroyuki3751d602011-02-01 15:52:45 -0800858 nr_pages = -nr_pages; /* for event */
859 }
KAMEZAWA Hiroyukie401f172011-01-20 14:44:23 -0800860
Chris Down871789d2019-05-14 15:46:57 -0700861 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -0800862}
KAMEZAWA Hiroyukid52aa412008-02-07 00:14:24 -0800863
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800864static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
865 enum mem_cgroup_events_target target)
KAMEZAWA Hiroyukid2265e62010-03-10 15:22:31 -0800866{
Johannes Weiner7a159cc2011-03-23 16:42:38 -0700867 unsigned long val, next;
868
Chris Down871789d2019-05-14 15:46:57 -0700869 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
870 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
Johannes Weiner7a159cc2011-03-23 16:42:38 -0700871 /* from time_after() in jiffies.h */
Michal Hocko6a1a8b82017-07-10 15:48:53 -0700872 if ((long)(next - val) < 0) {
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800873 switch (target) {
874 case MEM_CGROUP_TARGET_THRESH:
875 next = val + THRESHOLDS_EVENTS_TARGET;
876 break;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700877 case MEM_CGROUP_TARGET_SOFTLIMIT:
878 next = val + SOFTLIMIT_EVENTS_TARGET;
879 break;
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800880 case MEM_CGROUP_TARGET_NUMAINFO:
881 next = val + NUMAINFO_EVENTS_TARGET;
882 break;
883 default:
884 break;
885 }
Chris Down871789d2019-05-14 15:46:57 -0700886 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800887 return true;
Johannes Weiner7a159cc2011-03-23 16:42:38 -0700888 }
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800889 return false;
KAMEZAWA Hiroyukid2265e62010-03-10 15:22:31 -0800890}
891
892/*
893 * Check events in order.
894 *
895 */
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -0700896static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
KAMEZAWA Hiroyukid2265e62010-03-10 15:22:31 -0800897{
898 /* threshold event is triggered in finer grain than soft limit */
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800899 if (unlikely(mem_cgroup_event_ratelimit(memcg,
900 MEM_CGROUP_TARGET_THRESH))) {
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700901 bool do_softlimit;
Andrew Morton82b3f2a2012-02-03 15:37:14 -0800902 bool do_numainfo __maybe_unused;
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800903
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700904 do_softlimit = mem_cgroup_event_ratelimit(memcg,
905 MEM_CGROUP_TARGET_SOFTLIMIT);
KAMEZAWA Hiroyuki453a9bf32011-07-08 15:39:43 -0700906#if MAX_NUMNODES > 1
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800907 do_numainfo = mem_cgroup_event_ratelimit(memcg,
908 MEM_CGROUP_TARGET_NUMAINFO);
KAMEZAWA Hiroyuki453a9bf32011-07-08 15:39:43 -0700909#endif
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800910 mem_cgroup_threshold(memcg);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700911 if (unlikely(do_softlimit))
912 mem_cgroup_update_tree(memcg, page);
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800913#if MAX_NUMNODES > 1
914 if (unlikely(do_numainfo))
915 atomic_inc(&memcg->numainfo_events);
916#endif
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700917 }
KAMEZAWA Hiroyukid2265e62010-03-10 15:22:31 -0800918}
919
Balbir Singhcf475ad2008-04-29 01:00:16 -0700920struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
Pavel Emelianov78fb7462008-02-07 00:13:51 -0800921{
Balbir Singh31a78f22008-09-28 23:09:31 +0100922 /*
923 * mm_update_next_owner() may clear mm->owner to NULL
924 * if it races with swapoff, page migration, etc.
925 * So this can be called with p == NULL.
926 */
927 if (unlikely(!p))
928 return NULL;
929
Tejun Heo073219e2014-02-08 10:36:58 -0500930 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
Pavel Emelianov78fb7462008-02-07 00:13:51 -0800931}
Michal Hocko33398cf2015-09-08 15:01:02 -0700932EXPORT_SYMBOL(mem_cgroup_from_task);
Pavel Emelianov78fb7462008-02-07 00:13:51 -0800933
Shakeel Buttd46eb14b2018-08-17 15:46:39 -0700934/**
935 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
936 * @mm: mm from which memcg should be extracted. It can be NULL.
937 *
938 * Obtain a reference on mm->memcg and returns it if successful. Otherwise
939 * root_mem_cgroup is returned. However if mem_cgroup is disabled, NULL is
940 * returned.
941 */
942struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
KAMEZAWA Hiroyuki54595fe2009-01-07 18:08:33 -0800943{
Shakeel Buttd46eb14b2018-08-17 15:46:39 -0700944 struct mem_cgroup *memcg;
945
946 if (mem_cgroup_disabled())
947 return NULL;
KAMEZAWA Hiroyuki0b7f5692009-04-02 16:57:38 -0700948
KAMEZAWA Hiroyuki54595fe2009-01-07 18:08:33 -0800949 rcu_read_lock();
950 do {
Michal Hocko6f6acb02014-05-22 11:54:19 -0700951 /*
952 * Page cache insertions can happen withou an
953 * actual mm context, e.g. during disk probing
954 * on boot, loopback IO, acct() writes etc.
955 */
956 if (unlikely(!mm))
Johannes Weinerdf381972014-04-07 15:37:43 -0700957 memcg = root_mem_cgroup;
Michal Hocko6f6acb02014-05-22 11:54:19 -0700958 else {
959 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
960 if (unlikely(!memcg))
961 memcg = root_mem_cgroup;
962 }
Roman Gushchin00d484f2019-11-15 17:34:43 -0800963 } while (!css_tryget(&memcg->css));
KAMEZAWA Hiroyuki54595fe2009-01-07 18:08:33 -0800964 rcu_read_unlock();
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -0700965 return memcg;
KAMEZAWA Hiroyuki54595fe2009-01-07 18:08:33 -0800966}
Shakeel Buttd46eb14b2018-08-17 15:46:39 -0700967EXPORT_SYMBOL(get_mem_cgroup_from_mm);
968
969/**
Shakeel Buttf745c6f2018-08-17 15:46:44 -0700970 * get_mem_cgroup_from_page: Obtain a reference on given page's memcg.
971 * @page: page from which memcg should be extracted.
972 *
973 * Obtain a reference on page->memcg and returns it if successful. Otherwise
974 * root_mem_cgroup is returned.
975 */
976struct mem_cgroup *get_mem_cgroup_from_page(struct page *page)
977{
978 struct mem_cgroup *memcg = page->mem_cgroup;
979
980 if (mem_cgroup_disabled())
981 return NULL;
982
983 rcu_read_lock();
984 if (!memcg || !css_tryget_online(&memcg->css))
985 memcg = root_mem_cgroup;
986 rcu_read_unlock();
987 return memcg;
988}
989EXPORT_SYMBOL(get_mem_cgroup_from_page);
990
991/**
Shakeel Buttd46eb14b2018-08-17 15:46:39 -0700992 * If current->active_memcg is non-NULL, do not fallback to current->mm->memcg.
993 */
994static __always_inline struct mem_cgroup *get_mem_cgroup_from_current(void)
995{
996 if (unlikely(current->active_memcg)) {
997 struct mem_cgroup *memcg = root_mem_cgroup;
998
999 rcu_read_lock();
1000 if (css_tryget_online(&current->active_memcg->css))
1001 memcg = current->active_memcg;
1002 rcu_read_unlock();
1003 return memcg;
1004 }
1005 return get_mem_cgroup_from_mm(current->mm);
1006}
KAMEZAWA Hiroyuki54595fe2009-01-07 18:08:33 -08001007
Johannes Weiner56600482012-01-12 17:17:59 -08001008/**
1009 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1010 * @root: hierarchy root
1011 * @prev: previously returned memcg, NULL on first invocation
1012 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1013 *
1014 * Returns references to children of the hierarchy below @root, or
1015 * @root itself, or %NULL after a full round-trip.
1016 *
1017 * Caller must pass the return value in @prev on subsequent
1018 * invocations for reference counting, or use mem_cgroup_iter_break()
1019 * to cancel a hierarchy walk before the round-trip is complete.
1020 *
Honglei Wangb213b542018-03-28 16:01:12 -07001021 * Reclaimers can specify a node and a priority level in @reclaim to
Johannes Weiner56600482012-01-12 17:17:59 -08001022 * divide up the memcgs in the hierarchy among all concurrent
Honglei Wangb213b542018-03-28 16:01:12 -07001023 * reclaimers operating on the same node and priority.
Johannes Weiner56600482012-01-12 17:17:59 -08001024 */
Andrew Morton694fbc02013-09-24 15:27:37 -07001025struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
Johannes Weiner56600482012-01-12 17:17:59 -08001026 struct mem_cgroup *prev,
Andrew Morton694fbc02013-09-24 15:27:37 -07001027 struct mem_cgroup_reclaim_cookie *reclaim)
KAMEZAWA Hiroyuki14067bb2009-04-02 16:57:35 -07001028{
Michal Hocko33398cf2015-09-08 15:01:02 -07001029 struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001030 struct cgroup_subsys_state *css = NULL;
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001031 struct mem_cgroup *memcg = NULL;
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001032 struct mem_cgroup *pos = NULL;
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07001033
Andrew Morton694fbc02013-09-24 15:27:37 -07001034 if (mem_cgroup_disabled())
1035 return NULL;
Johannes Weiner56600482012-01-12 17:17:59 -08001036
KAMEZAWA Hiroyuki711d3d22010-10-27 15:33:42 -07001037 if (!root)
1038 root = root_mem_cgroup;
1039
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001040 if (prev && !reclaim)
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001041 pos = prev;
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001042
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001043 if (!root->use_hierarchy && root != root_mem_cgroup) {
1044 if (prev)
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001045 goto out;
Andrew Morton694fbc02013-09-24 15:27:37 -07001046 return root;
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001047 }
1048
Michal Hocko542f85f2013-04-29 15:07:15 -07001049 rcu_read_lock();
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001050
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001051 if (reclaim) {
Mel Gormanef8f2322016-07-28 15:46:05 -07001052 struct mem_cgroup_per_node *mz;
Johannes Weiner527a5ec2012-01-12 17:17:55 -08001053
Mel Gormanef8f2322016-07-28 15:46:05 -07001054 mz = mem_cgroup_nodeinfo(root, reclaim->pgdat->node_id);
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001055 iter = &mz->iter[reclaim->priority];
Michal Hocko5f578162013-04-29 15:07:17 -07001056
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001057 if (prev && reclaim->generation != iter->generation)
Michal Hocko542f85f2013-04-29 15:07:15 -07001058 goto out_unlock;
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001059
Vladimir Davydov6df38682015-12-29 14:54:10 -08001060 while (1) {
Jason Low4db0c3c2015-04-15 16:14:08 -07001061 pos = READ_ONCE(iter->position);
Vladimir Davydov6df38682015-12-29 14:54:10 -08001062 if (!pos || css_tryget(&pos->css))
1063 break;
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001064 /*
Vladimir Davydov6df38682015-12-29 14:54:10 -08001065 * css reference reached zero, so iter->position will
1066 * be cleared by ->css_released. However, we should not
1067 * rely on this happening soon, because ->css_released
1068 * is called from a work queue, and by busy-waiting we
1069 * might block it. So we clear iter->position right
1070 * away.
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001071 */
Vladimir Davydov6df38682015-12-29 14:54:10 -08001072 (void)cmpxchg(&iter->position, pos, NULL);
1073 }
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001074 }
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001075
1076 if (pos)
1077 css = &pos->css;
1078
1079 for (;;) {
1080 css = css_next_descendant_pre(css, &root->css);
1081 if (!css) {
1082 /*
1083 * Reclaimers share the hierarchy walk, and a
1084 * new one might jump in right at the end of
1085 * the hierarchy - make sure they see at least
1086 * one group and restart from the beginning.
1087 */
1088 if (!prev)
1089 continue;
1090 break;
1091 }
1092
1093 /*
1094 * Verify the css and acquire a reference. The root
1095 * is provided by the caller, so we know it's alive
1096 * and kicking, and don't take an extra reference.
1097 */
1098 memcg = mem_cgroup_from_css(css);
1099
1100 if (css == &root->css)
1101 break;
1102
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08001103 if (css_tryget(css))
1104 break;
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001105
1106 memcg = NULL;
1107 }
1108
1109 if (reclaim) {
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001110 /*
Vladimir Davydov6df38682015-12-29 14:54:10 -08001111 * The position could have already been updated by a competing
1112 * thread, so check that the value hasn't changed since we read
1113 * it to avoid reclaiming from the same cgroup twice.
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001114 */
Vladimir Davydov6df38682015-12-29 14:54:10 -08001115 (void)cmpxchg(&iter->position, pos, memcg);
1116
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001117 if (pos)
1118 css_put(&pos->css);
1119
1120 if (!memcg)
1121 iter->generation++;
1122 else if (!prev)
1123 reclaim->generation = iter->generation;
1124 }
1125
Michal Hocko542f85f2013-04-29 15:07:15 -07001126out_unlock:
1127 rcu_read_unlock();
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001128out:
Michal Hockoc40046f2013-04-29 15:07:14 -07001129 if (prev && prev != root)
1130 css_put(&prev->css);
1131
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001132 return memcg;
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07001133}
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001134
Johannes Weiner56600482012-01-12 17:17:59 -08001135/**
1136 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1137 * @root: hierarchy root
1138 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1139 */
1140void mem_cgroup_iter_break(struct mem_cgroup *root,
1141 struct mem_cgroup *prev)
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001142{
1143 if (!root)
1144 root = root_mem_cgroup;
1145 if (prev && prev != root)
1146 css_put(&prev->css);
1147}
1148
Miles Chen54a83d62019-08-13 15:37:28 -07001149static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1150 struct mem_cgroup *dead_memcg)
Vladimir Davydov6df38682015-12-29 14:54:10 -08001151{
Vladimir Davydov6df38682015-12-29 14:54:10 -08001152 struct mem_cgroup_reclaim_iter *iter;
Mel Gormanef8f2322016-07-28 15:46:05 -07001153 struct mem_cgroup_per_node *mz;
1154 int nid;
Vladimir Davydov6df38682015-12-29 14:54:10 -08001155 int i;
1156
Miles Chen54a83d62019-08-13 15:37:28 -07001157 for_each_node(nid) {
1158 mz = mem_cgroup_nodeinfo(from, nid);
1159 for (i = 0; i <= DEF_PRIORITY; i++) {
1160 iter = &mz->iter[i];
1161 cmpxchg(&iter->position,
1162 dead_memcg, NULL);
Vladimir Davydov6df38682015-12-29 14:54:10 -08001163 }
1164 }
1165}
1166
Miles Chen54a83d62019-08-13 15:37:28 -07001167static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1168{
1169 struct mem_cgroup *memcg = dead_memcg;
1170 struct mem_cgroup *last;
1171
1172 do {
1173 __invalidate_reclaim_iterators(memcg, dead_memcg);
1174 last = memcg;
1175 } while ((memcg = parent_mem_cgroup(memcg)));
1176
1177 /*
1178 * When cgruop1 non-hierarchy mode is used,
1179 * parent_mem_cgroup() does not walk all the way up to the
1180 * cgroup root (root_mem_cgroup). So we have to handle
1181 * dead_memcg from cgroup root separately.
1182 */
1183 if (last != root_mem_cgroup)
1184 __invalidate_reclaim_iterators(root_mem_cgroup,
1185 dead_memcg);
1186}
1187
Johannes Weiner925b7672012-01-12 17:18:15 -08001188/**
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001189 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1190 * @memcg: hierarchy root
1191 * @fn: function to call for each task
1192 * @arg: argument passed to @fn
1193 *
1194 * This function iterates over tasks attached to @memcg or to any of its
1195 * descendants and calls @fn for each task. If @fn returns a non-zero
1196 * value, the function breaks the iteration loop and returns the value.
1197 * Otherwise, it will iterate over all tasks and return 0.
1198 *
1199 * This function must not be called for the root memory cgroup.
1200 */
1201int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1202 int (*fn)(struct task_struct *, void *), void *arg)
1203{
1204 struct mem_cgroup *iter;
1205 int ret = 0;
1206
1207 BUG_ON(memcg == root_mem_cgroup);
1208
1209 for_each_mem_cgroup_tree(iter, memcg) {
1210 struct css_task_iter it;
1211 struct task_struct *task;
1212
Tetsuo Handaf168a9a2019-07-11 21:00:20 -07001213 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001214 while (!ret && (task = css_task_iter_next(&it)))
1215 ret = fn(task, arg);
1216 css_task_iter_end(&it);
1217 if (ret) {
1218 mem_cgroup_iter_break(memcg, iter);
1219 break;
1220 }
1221 }
1222 return ret;
1223}
1224
1225/**
Johannes Weinerdfe0e772014-12-10 15:43:43 -08001226 * mem_cgroup_page_lruvec - return lruvec for isolating/putting an LRU page
Johannes Weiner925b7672012-01-12 17:18:15 -08001227 * @page: the page
Mike Rapoportf144c392018-02-06 15:42:16 -08001228 * @pgdat: pgdat of the page
Johannes Weinerdfe0e772014-12-10 15:43:43 -08001229 *
1230 * This function is only safe when following the LRU page isolation
1231 * and putback protocol: the LRU lock must be held, and the page must
1232 * either be PageLRU() or the caller must have isolated/allocated it.
Minchan Kim3f58a822011-03-22 16:32:53 -07001233 */
Mel Gorman599d0c92016-07-28 15:45:31 -07001234struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct pglist_data *pgdat)
Minchan Kim3f58a822011-03-22 16:32:53 -07001235{
Mel Gormanef8f2322016-07-28 15:46:05 -07001236 struct mem_cgroup_per_node *mz;
Johannes Weiner925b7672012-01-12 17:18:15 -08001237 struct mem_cgroup *memcg;
Hugh Dickinsbea8c152012-11-16 14:14:54 -08001238 struct lruvec *lruvec;
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08001239
Hugh Dickinsbea8c152012-11-16 14:14:54 -08001240 if (mem_cgroup_disabled()) {
Mel Gorman599d0c92016-07-28 15:45:31 -07001241 lruvec = &pgdat->lruvec;
Hugh Dickinsbea8c152012-11-16 14:14:54 -08001242 goto out;
1243 }
Christoph Lameterb69408e2008-10-18 20:26:14 -07001244
Johannes Weiner1306a852014-12-10 15:44:52 -08001245 memcg = page->mem_cgroup;
Hugh Dickins75121022012-03-05 14:59:18 -08001246 /*
Johannes Weinerdfe0e772014-12-10 15:43:43 -08001247 * Swapcache readahead pages are added to the LRU - and
Johannes Weiner29833312014-12-10 15:44:02 -08001248 * possibly migrated - before they are charged.
Hugh Dickins75121022012-03-05 14:59:18 -08001249 */
Johannes Weiner29833312014-12-10 15:44:02 -08001250 if (!memcg)
1251 memcg = root_mem_cgroup;
Hugh Dickins75121022012-03-05 14:59:18 -08001252
Mel Gormanef8f2322016-07-28 15:46:05 -07001253 mz = mem_cgroup_page_nodeinfo(memcg, page);
Hugh Dickinsbea8c152012-11-16 14:14:54 -08001254 lruvec = &mz->lruvec;
1255out:
1256 /*
1257 * Since a node can be onlined after the mem_cgroup was created,
1258 * we have to be prepared to initialize lruvec->zone here;
1259 * and if offlined then reonlined, we need to reinitialize it.
1260 */
Mel Gorman599d0c92016-07-28 15:45:31 -07001261 if (unlikely(lruvec->pgdat != pgdat))
1262 lruvec->pgdat = pgdat;
Hugh Dickinsbea8c152012-11-16 14:14:54 -08001263 return lruvec;
Johannes Weiner925b7672012-01-12 17:18:15 -08001264}
1265
1266/**
Hugh Dickinsfa9add62012-05-29 15:07:09 -07001267 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1268 * @lruvec: mem_cgroup per zone lru vector
1269 * @lru: index of lru list the page is sitting on
Michal Hockob4536f0c82017-01-10 16:58:04 -08001270 * @zid: zone id of the accounted pages
Hugh Dickinsfa9add62012-05-29 15:07:09 -07001271 * @nr_pages: positive when adding or negative when removing
Johannes Weiner925b7672012-01-12 17:18:15 -08001272 *
Hugh Dickinsca707232016-05-19 17:12:35 -07001273 * This function must be called under lru_lock, just before a page is added
1274 * to or just after a page is removed from an lru list (that ordering being
1275 * so as to allow it to check that lru_size 0 is consistent with list_empty).
Johannes Weiner925b7672012-01-12 17:18:15 -08001276 */
Hugh Dickinsfa9add62012-05-29 15:07:09 -07001277void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001278 int zid, int nr_pages)
Johannes Weiner925b7672012-01-12 17:18:15 -08001279{
Mel Gormanef8f2322016-07-28 15:46:05 -07001280 struct mem_cgroup_per_node *mz;
Hugh Dickinsfa9add62012-05-29 15:07:09 -07001281 unsigned long *lru_size;
Hugh Dickinsca707232016-05-19 17:12:35 -07001282 long size;
Johannes Weiner925b7672012-01-12 17:18:15 -08001283
1284 if (mem_cgroup_disabled())
1285 return;
1286
Mel Gormanef8f2322016-07-28 15:46:05 -07001287 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
Michal Hockob4536f0c82017-01-10 16:58:04 -08001288 lru_size = &mz->lru_zone_size[zid][lru];
Hugh Dickinsca707232016-05-19 17:12:35 -07001289
1290 if (nr_pages < 0)
1291 *lru_size += nr_pages;
1292
1293 size = *lru_size;
Michal Hockob4536f0c82017-01-10 16:58:04 -08001294 if (WARN_ONCE(size < 0,
1295 "%s(%p, %d, %d): lru_size %ld\n",
1296 __func__, lruvec, lru, nr_pages, size)) {
Hugh Dickinsca707232016-05-19 17:12:35 -07001297 VM_BUG_ON(1);
1298 *lru_size = 0;
1299 }
1300
1301 if (nr_pages > 0)
1302 *lru_size += nr_pages;
KAMEZAWA Hiroyuki08e552c2009-01-07 18:08:01 -08001303}
KAMEZAWA Hiroyuki544122e2009-01-07 18:08:34 -08001304
Johannes Weiner19942822011-02-01 15:52:43 -08001305/**
Johannes Weiner9d11ea92011-03-23 16:42:21 -07001306 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
Wanpeng Lidad75572012-06-20 12:53:01 -07001307 * @memcg: the memory cgroup
Johannes Weiner19942822011-02-01 15:52:43 -08001308 *
Johannes Weiner9d11ea92011-03-23 16:42:21 -07001309 * Returns the maximum amount of memory @mem can be charged with, in
Johannes Weiner7ec99d62011-03-23 16:42:36 -07001310 * pages.
Johannes Weiner19942822011-02-01 15:52:43 -08001311 */
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001312static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
Johannes Weiner19942822011-02-01 15:52:43 -08001313{
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001314 unsigned long margin = 0;
1315 unsigned long count;
1316 unsigned long limit;
Johannes Weiner9d11ea92011-03-23 16:42:21 -07001317
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001318 count = page_counter_read(&memcg->memory);
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001319 limit = READ_ONCE(memcg->memory.max);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001320 if (count < limit)
1321 margin = limit - count;
1322
Johannes Weiner7941d212016-01-14 15:21:23 -08001323 if (do_memsw_account()) {
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001324 count = page_counter_read(&memcg->memsw);
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001325 limit = READ_ONCE(memcg->memsw.max);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001326 if (count <= limit)
1327 margin = min(margin, limit - count);
Li RongQingcbedbac2016-05-27 14:27:43 -07001328 else
1329 margin = 0;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001330 }
1331
1332 return margin;
Johannes Weiner19942822011-02-01 15:52:43 -08001333}
1334
KAMEZAWA Hiroyuki619d0942012-03-21 16:34:23 -07001335/*
Qiang Huangbdcbb652014-06-04 16:08:21 -07001336 * A routine for checking "mem" is under move_account() or not.
KAMEZAWA Hiroyuki32047e22010-10-27 15:33:40 -07001337 *
Qiang Huangbdcbb652014-06-04 16:08:21 -07001338 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1339 * moving cgroups. This is for waiting at high-memory pressure
1340 * caused by "move".
KAMEZAWA Hiroyuki32047e22010-10-27 15:33:40 -07001341 */
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001342static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07001343{
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07001344 struct mem_cgroup *from;
1345 struct mem_cgroup *to;
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07001346 bool ret = false;
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07001347 /*
1348 * Unlike task_move routines, we access mc.to, mc.from not under
1349 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1350 */
1351 spin_lock(&mc.lock);
1352 from = mc.from;
1353 to = mc.to;
1354 if (!from)
1355 goto unlock;
Michal Hocko3e920412011-07-26 16:08:29 -07001356
Johannes Weiner2314b422014-12-10 15:44:33 -08001357 ret = mem_cgroup_is_descendant(from, memcg) ||
1358 mem_cgroup_is_descendant(to, memcg);
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07001359unlock:
1360 spin_unlock(&mc.lock);
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07001361 return ret;
1362}
1363
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001364static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07001365{
1366 if (mc.moving_task && current != mc.moving_task) {
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001367 if (mem_cgroup_under_move(memcg)) {
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07001368 DEFINE_WAIT(wait);
1369 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1370 /* moving charge context might have finished. */
1371 if (mc.moving_task)
1372 schedule();
1373 finish_wait(&mc.waitq, &wait);
1374 return true;
1375 }
1376 }
1377 return false;
1378}
1379
Johannes Weinerc8713d02019-07-11 20:55:59 -07001380static char *memory_stat_format(struct mem_cgroup *memcg)
1381{
1382 struct seq_buf s;
1383 int i;
Johannes Weiner71cd3112017-05-03 14:55:13 -07001384
Johannes Weinerc8713d02019-07-11 20:55:59 -07001385 seq_buf_init(&s, kmalloc(PAGE_SIZE, GFP_KERNEL), PAGE_SIZE);
1386 if (!s.buffer)
1387 return NULL;
1388
1389 /*
1390 * Provide statistics on the state of the memory subsystem as
1391 * well as cumulative event counters that show past behavior.
1392 *
1393 * This list is ordered following a combination of these gradients:
1394 * 1) generic big picture -> specifics and details
1395 * 2) reflecting userspace activity -> reflecting kernel heuristics
1396 *
1397 * Current memory state:
1398 */
1399
1400 seq_buf_printf(&s, "anon %llu\n",
1401 (u64)memcg_page_state(memcg, MEMCG_RSS) *
1402 PAGE_SIZE);
1403 seq_buf_printf(&s, "file %llu\n",
1404 (u64)memcg_page_state(memcg, MEMCG_CACHE) *
1405 PAGE_SIZE);
1406 seq_buf_printf(&s, "kernel_stack %llu\n",
1407 (u64)memcg_page_state(memcg, MEMCG_KERNEL_STACK_KB) *
1408 1024);
1409 seq_buf_printf(&s, "slab %llu\n",
1410 (u64)(memcg_page_state(memcg, NR_SLAB_RECLAIMABLE) +
1411 memcg_page_state(memcg, NR_SLAB_UNRECLAIMABLE)) *
1412 PAGE_SIZE);
1413 seq_buf_printf(&s, "sock %llu\n",
1414 (u64)memcg_page_state(memcg, MEMCG_SOCK) *
1415 PAGE_SIZE);
1416
1417 seq_buf_printf(&s, "shmem %llu\n",
1418 (u64)memcg_page_state(memcg, NR_SHMEM) *
1419 PAGE_SIZE);
1420 seq_buf_printf(&s, "file_mapped %llu\n",
1421 (u64)memcg_page_state(memcg, NR_FILE_MAPPED) *
1422 PAGE_SIZE);
1423 seq_buf_printf(&s, "file_dirty %llu\n",
1424 (u64)memcg_page_state(memcg, NR_FILE_DIRTY) *
1425 PAGE_SIZE);
1426 seq_buf_printf(&s, "file_writeback %llu\n",
1427 (u64)memcg_page_state(memcg, NR_WRITEBACK) *
1428 PAGE_SIZE);
1429
1430 /*
1431 * TODO: We should eventually replace our own MEMCG_RSS_HUGE counter
1432 * with the NR_ANON_THP vm counter, but right now it's a pain in the
1433 * arse because it requires migrating the work out of rmap to a place
1434 * where the page->mem_cgroup is set up and stable.
1435 */
1436 seq_buf_printf(&s, "anon_thp %llu\n",
1437 (u64)memcg_page_state(memcg, MEMCG_RSS_HUGE) *
1438 PAGE_SIZE);
1439
1440 for (i = 0; i < NR_LRU_LISTS; i++)
1441 seq_buf_printf(&s, "%s %llu\n", mem_cgroup_lru_names[i],
1442 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
1443 PAGE_SIZE);
1444
1445 seq_buf_printf(&s, "slab_reclaimable %llu\n",
1446 (u64)memcg_page_state(memcg, NR_SLAB_RECLAIMABLE) *
1447 PAGE_SIZE);
1448 seq_buf_printf(&s, "slab_unreclaimable %llu\n",
1449 (u64)memcg_page_state(memcg, NR_SLAB_UNRECLAIMABLE) *
1450 PAGE_SIZE);
1451
1452 /* Accumulated memory events */
1453
1454 seq_buf_printf(&s, "pgfault %lu\n", memcg_events(memcg, PGFAULT));
1455 seq_buf_printf(&s, "pgmajfault %lu\n", memcg_events(memcg, PGMAJFAULT));
1456
1457 seq_buf_printf(&s, "workingset_refault %lu\n",
1458 memcg_page_state(memcg, WORKINGSET_REFAULT));
1459 seq_buf_printf(&s, "workingset_activate %lu\n",
1460 memcg_page_state(memcg, WORKINGSET_ACTIVATE));
1461 seq_buf_printf(&s, "workingset_nodereclaim %lu\n",
1462 memcg_page_state(memcg, WORKINGSET_NODERECLAIM));
1463
1464 seq_buf_printf(&s, "pgrefill %lu\n", memcg_events(memcg, PGREFILL));
1465 seq_buf_printf(&s, "pgscan %lu\n",
1466 memcg_events(memcg, PGSCAN_KSWAPD) +
1467 memcg_events(memcg, PGSCAN_DIRECT));
1468 seq_buf_printf(&s, "pgsteal %lu\n",
1469 memcg_events(memcg, PGSTEAL_KSWAPD) +
1470 memcg_events(memcg, PGSTEAL_DIRECT));
1471 seq_buf_printf(&s, "pgactivate %lu\n", memcg_events(memcg, PGACTIVATE));
1472 seq_buf_printf(&s, "pgdeactivate %lu\n", memcg_events(memcg, PGDEACTIVATE));
1473 seq_buf_printf(&s, "pglazyfree %lu\n", memcg_events(memcg, PGLAZYFREE));
1474 seq_buf_printf(&s, "pglazyfreed %lu\n", memcg_events(memcg, PGLAZYFREED));
1475
1476#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1477 seq_buf_printf(&s, "thp_fault_alloc %lu\n",
1478 memcg_events(memcg, THP_FAULT_ALLOC));
1479 seq_buf_printf(&s, "thp_collapse_alloc %lu\n",
1480 memcg_events(memcg, THP_COLLAPSE_ALLOC));
1481#endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1482
1483 /* The above should easily fit into one page */
1484 WARN_ON_ONCE(seq_buf_has_overflowed(&s));
1485
1486 return s.buffer;
1487}
Johannes Weiner71cd3112017-05-03 14:55:13 -07001488
Sha Zhengju58cf1882013-02-22 16:32:05 -08001489#define K(x) ((x) << (PAGE_SHIFT-10))
Balbir Singhe2224322009-04-02 16:57:39 -07001490/**
yuzhoujianf0c867d2018-12-28 00:36:10 -08001491 * mem_cgroup_print_oom_context: Print OOM information relevant to
1492 * memory controller.
Balbir Singhe2224322009-04-02 16:57:39 -07001493 * @memcg: The memory cgroup that went over limit
1494 * @p: Task that is going to be killed
1495 *
1496 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1497 * enabled
1498 */
yuzhoujianf0c867d2018-12-28 00:36:10 -08001499void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1500{
1501 rcu_read_lock();
1502
1503 if (memcg) {
1504 pr_cont(",oom_memcg=");
1505 pr_cont_cgroup_path(memcg->css.cgroup);
1506 } else
1507 pr_cont(",global_oom");
1508 if (p) {
1509 pr_cont(",task_memcg=");
1510 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1511 }
1512 rcu_read_unlock();
1513}
1514
1515/**
1516 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1517 * memory controller.
1518 * @memcg: The memory cgroup that went over limit
1519 */
1520void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
Balbir Singhe2224322009-04-02 16:57:39 -07001521{
Johannes Weinerc8713d02019-07-11 20:55:59 -07001522 char *buf;
Balbir Singhe2224322009-04-02 16:57:39 -07001523
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001524 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1525 K((u64)page_counter_read(&memcg->memory)),
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001526 K((u64)memcg->memory.max), memcg->memory.failcnt);
Johannes Weinerc8713d02019-07-11 20:55:59 -07001527 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1528 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1529 K((u64)page_counter_read(&memcg->swap)),
1530 K((u64)memcg->swap.max), memcg->swap.failcnt);
1531 else {
1532 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1533 K((u64)page_counter_read(&memcg->memsw)),
1534 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1535 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1536 K((u64)page_counter_read(&memcg->kmem)),
1537 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
Sha Zhengju58cf1882013-02-22 16:32:05 -08001538 }
Johannes Weinerc8713d02019-07-11 20:55:59 -07001539
1540 pr_info("Memory cgroup stats for ");
1541 pr_cont_cgroup_path(memcg->css.cgroup);
1542 pr_cont(":");
1543 buf = memory_stat_format(memcg);
1544 if (!buf)
1545 return;
1546 pr_info("%s", buf);
1547 kfree(buf);
Balbir Singhe2224322009-04-02 16:57:39 -07001548}
1549
KAMEZAWA Hiroyuki81d39c22009-04-02 16:57:36 -07001550/*
David Rientjesa63d83f2010-08-09 17:19:46 -07001551 * Return the memory (and swap, if configured) limit for a memcg.
1552 */
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001553unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
David Rientjesa63d83f2010-08-09 17:19:46 -07001554{
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001555 unsigned long max;
David Rientjesa63d83f2010-08-09 17:19:46 -07001556
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001557 max = memcg->memory.max;
Michal Hocko9a5a8f12012-11-16 14:14:49 -08001558 if (mem_cgroup_swappiness(memcg)) {
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001559 unsigned long memsw_max;
1560 unsigned long swap_max;
Michal Hocko9a5a8f12012-11-16 14:14:49 -08001561
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001562 memsw_max = memcg->memsw.max;
1563 swap_max = memcg->swap.max;
1564 swap_max = min(swap_max, (unsigned long)total_swap_pages);
1565 max = min(max + swap_max, memsw_max);
Michal Hocko9a5a8f12012-11-16 14:14:49 -08001566 }
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001567 return max;
David Rientjesa63d83f2010-08-09 17:19:46 -07001568}
1569
Chris Down9783aa92019-10-06 17:58:32 -07001570unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1571{
1572 return page_counter_read(&memcg->memory);
1573}
1574
Johannes Weinerb6e6edc2016-03-17 14:20:28 -07001575static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
David Rientjes19965462012-12-11 16:00:26 -08001576 int order)
David Rientjes9cbb78b2012-07-31 16:43:44 -07001577{
David Rientjes6e0fc462015-09-08 15:00:36 -07001578 struct oom_control oc = {
1579 .zonelist = NULL,
1580 .nodemask = NULL,
Vladimir Davydov2a966b72016-07-26 15:22:33 -07001581 .memcg = memcg,
David Rientjes6e0fc462015-09-08 15:00:36 -07001582 .gfp_mask = gfp_mask,
1583 .order = order,
David Rientjes6e0fc462015-09-08 15:00:36 -07001584 };
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001585 bool ret;
David Rientjes9cbb78b2012-07-31 16:43:44 -07001586
Tetsuo Handa7775fac2019-03-05 15:46:47 -08001587 if (mutex_lock_killable(&oom_lock))
1588 return true;
1589 /*
1590 * A few threads which were not waiting at mutex_lock_killable() can
1591 * fail to bail out. Therefore, check again after holding oom_lock.
1592 */
1593 ret = should_force_charge() || out_of_memory(&oc);
Johannes Weinerdc564012015-06-24 16:57:19 -07001594 mutex_unlock(&oom_lock);
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001595 return ret;
David Rientjes9cbb78b2012-07-31 16:43:44 -07001596}
1597
Michele Curtiae6e71d2014-12-12 16:56:35 -08001598#if MAX_NUMNODES > 1
1599
KAMEZAWA Hiroyuki4d0c0662011-07-08 15:39:42 -07001600/**
1601 * test_mem_cgroup_node_reclaimable
Wanpeng Lidad75572012-06-20 12:53:01 -07001602 * @memcg: the target memcg
KAMEZAWA Hiroyuki4d0c0662011-07-08 15:39:42 -07001603 * @nid: the node ID to be checked.
1604 * @noswap : specify true here if the user wants flle only information.
1605 *
1606 * This function returns whether the specified memcg contains any
1607 * reclaimable pages on a node. Returns true if there are any reclaimable
1608 * pages in the node.
1609 */
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001610static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
KAMEZAWA Hiroyuki4d0c0662011-07-08 15:39:42 -07001611 int nid, bool noswap)
1612{
Johannes Weiner2b487e52019-05-13 17:18:05 -07001613 struct lruvec *lruvec = mem_cgroup_lruvec(NODE_DATA(nid), memcg);
1614
Johannes Weinerdef0fda2019-05-14 15:47:15 -07001615 if (lruvec_page_state(lruvec, NR_INACTIVE_FILE) ||
1616 lruvec_page_state(lruvec, NR_ACTIVE_FILE))
KAMEZAWA Hiroyuki4d0c0662011-07-08 15:39:42 -07001617 return true;
1618 if (noswap || !total_swap_pages)
1619 return false;
Johannes Weinerdef0fda2019-05-14 15:47:15 -07001620 if (lruvec_page_state(lruvec, NR_INACTIVE_ANON) ||
1621 lruvec_page_state(lruvec, NR_ACTIVE_ANON))
KAMEZAWA Hiroyuki4d0c0662011-07-08 15:39:42 -07001622 return true;
1623 return false;
1624
1625}
Ying Han889976d2011-05-26 16:25:33 -07001626
1627/*
1628 * Always updating the nodemask is not very good - even if we have an empty
1629 * list or the wrong list here, we can start from some node and traverse all
1630 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1631 *
1632 */
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001633static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
Ying Han889976d2011-05-26 16:25:33 -07001634{
1635 int nid;
KAMEZAWA Hiroyuki453a9bf32011-07-08 15:39:43 -07001636 /*
1637 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1638 * pagein/pageout changes since the last update.
1639 */
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001640 if (!atomic_read(&memcg->numainfo_events))
KAMEZAWA Hiroyuki453a9bf32011-07-08 15:39:43 -07001641 return;
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001642 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
Ying Han889976d2011-05-26 16:25:33 -07001643 return;
1644
Ying Han889976d2011-05-26 16:25:33 -07001645 /* make a nodemask where this memcg uses memory from */
Lai Jiangshan31aaea42012-12-12 13:51:27 -08001646 memcg->scan_nodes = node_states[N_MEMORY];
Ying Han889976d2011-05-26 16:25:33 -07001647
Lai Jiangshan31aaea42012-12-12 13:51:27 -08001648 for_each_node_mask(nid, node_states[N_MEMORY]) {
Ying Han889976d2011-05-26 16:25:33 -07001649
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001650 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1651 node_clear(nid, memcg->scan_nodes);
Ying Han889976d2011-05-26 16:25:33 -07001652 }
KAMEZAWA Hiroyuki453a9bf32011-07-08 15:39:43 -07001653
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001654 atomic_set(&memcg->numainfo_events, 0);
1655 atomic_set(&memcg->numainfo_updating, 0);
Ying Han889976d2011-05-26 16:25:33 -07001656}
1657
1658/*
1659 * Selecting a node where we start reclaim from. Because what we need is just
1660 * reducing usage counter, start from anywhere is O,K. Considering
1661 * memory reclaim from current node, there are pros. and cons.
1662 *
1663 * Freeing memory from current node means freeing memory from a node which
1664 * we'll use or we've used. So, it may make LRU bad. And if several threads
1665 * hit limits, it will see a contention on a node. But freeing from remote
1666 * node means more costs for memory reclaim because of memory latency.
1667 *
1668 * Now, we use round-robin. Better algorithm is welcomed.
1669 */
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001670int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
Ying Han889976d2011-05-26 16:25:33 -07001671{
1672 int node;
1673
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001674 mem_cgroup_may_update_nodemask(memcg);
1675 node = memcg->last_scanned_node;
Ying Han889976d2011-05-26 16:25:33 -07001676
Andrew Morton0edaf862016-05-19 17:10:58 -07001677 node = next_node_in(node, memcg->scan_nodes);
Ying Han889976d2011-05-26 16:25:33 -07001678 /*
Michal Hockofda3d692016-05-19 17:11:34 -07001679 * mem_cgroup_may_update_nodemask might have seen no reclaimmable pages
1680 * last time it really checked all the LRUs due to rate limiting.
1681 * Fallback to the current node in that case for simplicity.
Ying Han889976d2011-05-26 16:25:33 -07001682 */
1683 if (unlikely(node == MAX_NUMNODES))
1684 node = numa_node_id();
1685
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001686 memcg->last_scanned_node = node;
Ying Han889976d2011-05-26 16:25:33 -07001687 return node;
1688}
Ying Han889976d2011-05-26 16:25:33 -07001689#else
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001690int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
Ying Han889976d2011-05-26 16:25:33 -07001691{
1692 return 0;
1693}
1694#endif
1695
Andrew Morton0608f432013-09-24 15:27:41 -07001696static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
Mel Gormanef8f2322016-07-28 15:46:05 -07001697 pg_data_t *pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07001698 gfp_t gfp_mask,
1699 unsigned long *total_scanned)
Balbir Singh6d61ef42009-01-07 18:08:06 -08001700{
Andrew Morton0608f432013-09-24 15:27:41 -07001701 struct mem_cgroup *victim = NULL;
1702 int total = 0;
1703 int loop = 0;
1704 unsigned long excess;
1705 unsigned long nr_scanned;
1706 struct mem_cgroup_reclaim_cookie reclaim = {
Mel Gormanef8f2322016-07-28 15:46:05 -07001707 .pgdat = pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07001708 .priority = 0,
1709 };
Johannes Weiner9d11ea92011-03-23 16:42:21 -07001710
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001711 excess = soft_limit_excess(root_memcg);
Balbir Singh6d61ef42009-01-07 18:08:06 -08001712
Andrew Morton0608f432013-09-24 15:27:41 -07001713 while (1) {
1714 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1715 if (!victim) {
1716 loop++;
1717 if (loop >= 2) {
1718 /*
1719 * If we have not been able to reclaim
1720 * anything, it might because there are
1721 * no reclaimable pages under this hierarchy
1722 */
1723 if (!total)
1724 break;
1725 /*
1726 * We want to do more targeted reclaim.
1727 * excess >> 2 is not to excessive so as to
1728 * reclaim too much, nor too less that we keep
1729 * coming back to reclaim from this cgroup
1730 */
1731 if (total >= (excess >> 2) ||
1732 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1733 break;
1734 }
1735 continue;
1736 }
Mel Gormana9dd0a82016-07-28 15:46:02 -07001737 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
Mel Gormanef8f2322016-07-28 15:46:05 -07001738 pgdat, &nr_scanned);
Andrew Morton0608f432013-09-24 15:27:41 -07001739 *total_scanned += nr_scanned;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001740 if (!soft_limit_excess(root_memcg))
Andrew Morton0608f432013-09-24 15:27:41 -07001741 break;
Balbir Singh6d61ef42009-01-07 18:08:06 -08001742 }
Andrew Morton0608f432013-09-24 15:27:41 -07001743 mem_cgroup_iter_break(root_memcg, victim);
1744 return total;
Balbir Singh6d61ef42009-01-07 18:08:06 -08001745}
1746
Johannes Weiner0056f4e2013-10-31 16:34:14 -07001747#ifdef CONFIG_LOCKDEP
1748static struct lockdep_map memcg_oom_lock_dep_map = {
1749 .name = "memcg_oom_lock",
1750};
1751#endif
1752
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001753static DEFINE_SPINLOCK(memcg_oom_lock);
1754
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001755/*
1756 * Check OOM-Killer is already running under our hierarchy.
1757 * If someone is running, return false.
1758 */
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001759static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001760{
Michal Hocko79dfdac2011-07-26 16:08:23 -07001761 struct mem_cgroup *iter, *failed = NULL;
KAMEZAWA Hiroyukia636b322009-01-07 18:08:08 -08001762
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001763 spin_lock(&memcg_oom_lock);
1764
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001765 for_each_mem_cgroup_tree(iter, memcg) {
Johannes Weiner23751be2011-08-25 15:59:16 -07001766 if (iter->oom_lock) {
Michal Hocko79dfdac2011-07-26 16:08:23 -07001767 /*
1768 * this subtree of our hierarchy is already locked
1769 * so we cannot give a lock.
1770 */
Michal Hocko79dfdac2011-07-26 16:08:23 -07001771 failed = iter;
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001772 mem_cgroup_iter_break(memcg, iter);
1773 break;
Johannes Weiner23751be2011-08-25 15:59:16 -07001774 } else
1775 iter->oom_lock = true;
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07001776 }
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001777
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001778 if (failed) {
1779 /*
1780 * OK, we failed to lock the whole subtree so we have
1781 * to clean up what we set up to the failing subtree
1782 */
1783 for_each_mem_cgroup_tree(iter, memcg) {
1784 if (iter == failed) {
1785 mem_cgroup_iter_break(memcg, iter);
1786 break;
1787 }
1788 iter->oom_lock = false;
Michal Hocko79dfdac2011-07-26 16:08:23 -07001789 }
Johannes Weiner0056f4e2013-10-31 16:34:14 -07001790 } else
1791 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001792
1793 spin_unlock(&memcg_oom_lock);
1794
1795 return !failed;
KAMEZAWA Hiroyukia636b322009-01-07 18:08:08 -08001796}
KAMEZAWA Hiroyuki0b7f5692009-04-02 16:57:38 -07001797
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001798static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki0b7f5692009-04-02 16:57:38 -07001799{
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07001800 struct mem_cgroup *iter;
1801
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001802 spin_lock(&memcg_oom_lock);
Johannes Weiner0056f4e2013-10-31 16:34:14 -07001803 mutex_release(&memcg_oom_lock_dep_map, 1, _RET_IP_);
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001804 for_each_mem_cgroup_tree(iter, memcg)
Michal Hocko79dfdac2011-07-26 16:08:23 -07001805 iter->oom_lock = false;
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001806 spin_unlock(&memcg_oom_lock);
Michal Hocko79dfdac2011-07-26 16:08:23 -07001807}
1808
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001809static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
Michal Hocko79dfdac2011-07-26 16:08:23 -07001810{
1811 struct mem_cgroup *iter;
1812
Tejun Heoc2b42d32015-06-24 16:58:23 -07001813 spin_lock(&memcg_oom_lock);
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001814 for_each_mem_cgroup_tree(iter, memcg)
Tejun Heoc2b42d32015-06-24 16:58:23 -07001815 iter->under_oom++;
1816 spin_unlock(&memcg_oom_lock);
Michal Hocko79dfdac2011-07-26 16:08:23 -07001817}
1818
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001819static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
Michal Hocko79dfdac2011-07-26 16:08:23 -07001820{
1821 struct mem_cgroup *iter;
1822
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001823 /*
1824 * When a new child is created while the hierarchy is under oom,
Tejun Heoc2b42d32015-06-24 16:58:23 -07001825 * mem_cgroup_oom_lock() may not be called. Watch for underflow.
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001826 */
Tejun Heoc2b42d32015-06-24 16:58:23 -07001827 spin_lock(&memcg_oom_lock);
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001828 for_each_mem_cgroup_tree(iter, memcg)
Tejun Heoc2b42d32015-06-24 16:58:23 -07001829 if (iter->under_oom > 0)
1830 iter->under_oom--;
1831 spin_unlock(&memcg_oom_lock);
KAMEZAWA Hiroyuki0b7f5692009-04-02 16:57:38 -07001832}
1833
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001834static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1835
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07001836struct oom_wait_info {
Hugh Dickinsd79154b2012-03-21 16:34:18 -07001837 struct mem_cgroup *memcg;
Ingo Molnarac6424b2017-06-20 12:06:13 +02001838 wait_queue_entry_t wait;
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07001839};
1840
Ingo Molnarac6424b2017-06-20 12:06:13 +02001841static int memcg_oom_wake_function(wait_queue_entry_t *wait,
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07001842 unsigned mode, int sync, void *arg)
1843{
Hugh Dickinsd79154b2012-03-21 16:34:18 -07001844 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1845 struct mem_cgroup *oom_wait_memcg;
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07001846 struct oom_wait_info *oom_wait_info;
1847
1848 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
Hugh Dickinsd79154b2012-03-21 16:34:18 -07001849 oom_wait_memcg = oom_wait_info->memcg;
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07001850
Johannes Weiner2314b422014-12-10 15:44:33 -08001851 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1852 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07001853 return 0;
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07001854 return autoremove_wake_function(wait, mode, sync, arg);
1855}
1856
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001857static void memcg_oom_recover(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07001858{
Tejun Heoc2b42d32015-06-24 16:58:23 -07001859 /*
1860 * For the following lockless ->under_oom test, the only required
1861 * guarantee is that it must see the state asserted by an OOM when
1862 * this function is called as a result of userland actions
1863 * triggered by the notification of the OOM. This is trivially
1864 * achieved by invoking mem_cgroup_mark_under_oom() before
1865 * triggering notification.
1866 */
1867 if (memcg && memcg->under_oom)
Tejun Heof4b90b702015-06-24 16:58:21 -07001868 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07001869}
1870
Michal Hocko29ef6802018-08-17 15:47:11 -07001871enum oom_status {
1872 OOM_SUCCESS,
1873 OOM_FAILED,
1874 OOM_ASYNC,
1875 OOM_SKIPPED
1876};
1877
1878static enum oom_status mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001879{
Michal Hocko7056d3a2018-12-28 00:39:57 -08001880 enum oom_status ret;
1881 bool locked;
1882
Michal Hocko29ef6802018-08-17 15:47:11 -07001883 if (order > PAGE_ALLOC_COSTLY_ORDER)
1884 return OOM_SKIPPED;
1885
Roman Gushchin7a1adfd2018-10-26 15:09:48 -07001886 memcg_memory_event(memcg, MEMCG_OOM);
1887
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001888 /*
Johannes Weiner49426422013-10-16 13:46:59 -07001889 * We are in the middle of the charge context here, so we
1890 * don't want to block when potentially sitting on a callstack
1891 * that holds all kinds of filesystem and mm locks.
1892 *
Michal Hocko29ef6802018-08-17 15:47:11 -07001893 * cgroup1 allows disabling the OOM killer and waiting for outside
1894 * handling until the charge can succeed; remember the context and put
1895 * the task to sleep at the end of the page fault when all locks are
1896 * released.
Johannes Weiner49426422013-10-16 13:46:59 -07001897 *
Michal Hocko29ef6802018-08-17 15:47:11 -07001898 * On the other hand, in-kernel OOM killer allows for an async victim
1899 * memory reclaim (oom_reaper) and that means that we are not solely
1900 * relying on the oom victim to make a forward progress and we can
1901 * invoke the oom killer here.
1902 *
1903 * Please note that mem_cgroup_out_of_memory might fail to find a
1904 * victim and then we have to bail out from the charge path.
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001905 */
Michal Hocko29ef6802018-08-17 15:47:11 -07001906 if (memcg->oom_kill_disable) {
1907 if (!current->in_user_fault)
1908 return OOM_SKIPPED;
1909 css_get(&memcg->css);
1910 current->memcg_in_oom = memcg;
1911 current->memcg_oom_gfp_mask = mask;
1912 current->memcg_oom_order = order;
1913
1914 return OOM_ASYNC;
1915 }
1916
Michal Hocko7056d3a2018-12-28 00:39:57 -08001917 mem_cgroup_mark_under_oom(memcg);
Michal Hocko29ef6802018-08-17 15:47:11 -07001918
Michal Hocko7056d3a2018-12-28 00:39:57 -08001919 locked = mem_cgroup_oom_trylock(memcg);
1920
1921 if (locked)
1922 mem_cgroup_oom_notify(memcg);
1923
1924 mem_cgroup_unmark_under_oom(memcg);
1925 if (mem_cgroup_out_of_memory(memcg, mask, order))
1926 ret = OOM_SUCCESS;
1927 else
1928 ret = OOM_FAILED;
1929
1930 if (locked)
1931 mem_cgroup_oom_unlock(memcg);
1932
1933 return ret;
Johannes Weiner49426422013-10-16 13:46:59 -07001934}
1935
1936/**
1937 * mem_cgroup_oom_synchronize - complete memcg OOM handling
1938 * @handle: actually kill/wait or just clean up the OOM state
1939 *
1940 * This has to be called at the end of a page fault if the memcg OOM
1941 * handler was enabled.
1942 *
1943 * Memcg supports userspace OOM handling where failed allocations must
1944 * sleep on a waitqueue until the userspace task resolves the
1945 * situation. Sleeping directly in the charge context with all kinds
1946 * of locks held is not a good idea, instead we remember an OOM state
1947 * in the task and mem_cgroup_oom_synchronize() has to be called at
1948 * the end of the page fault to complete the OOM handling.
1949 *
1950 * Returns %true if an ongoing memcg OOM situation was detected and
1951 * completed, %false otherwise.
1952 */
1953bool mem_cgroup_oom_synchronize(bool handle)
1954{
Tejun Heo626ebc42015-11-05 18:46:09 -08001955 struct mem_cgroup *memcg = current->memcg_in_oom;
Johannes Weiner49426422013-10-16 13:46:59 -07001956 struct oom_wait_info owait;
1957 bool locked;
1958
1959 /* OOM is global, do not handle */
1960 if (!memcg)
1961 return false;
1962
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001963 if (!handle)
Johannes Weiner49426422013-10-16 13:46:59 -07001964 goto cleanup;
1965
1966 owait.memcg = memcg;
1967 owait.wait.flags = 0;
1968 owait.wait.func = memcg_oom_wake_function;
1969 owait.wait.private = current;
Ingo Molnar2055da92017-06-20 12:06:46 +02001970 INIT_LIST_HEAD(&owait.wait.entry);
Johannes Weiner49426422013-10-16 13:46:59 -07001971
1972 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001973 mem_cgroup_mark_under_oom(memcg);
1974
1975 locked = mem_cgroup_oom_trylock(memcg);
1976
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07001977 if (locked)
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001978 mem_cgroup_oom_notify(memcg);
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001979
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001980 if (locked && !memcg->oom_kill_disable) {
1981 mem_cgroup_unmark_under_oom(memcg);
Johannes Weiner49426422013-10-16 13:46:59 -07001982 finish_wait(&memcg_oom_waitq, &owait.wait);
Tejun Heo626ebc42015-11-05 18:46:09 -08001983 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
1984 current->memcg_oom_order);
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07001985 } else {
Johannes Weiner3812c8c2013-09-12 15:13:44 -07001986 schedule();
Johannes Weiner49426422013-10-16 13:46:59 -07001987 mem_cgroup_unmark_under_oom(memcg);
1988 finish_wait(&memcg_oom_waitq, &owait.wait);
1989 }
1990
1991 if (locked) {
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001992 mem_cgroup_oom_unlock(memcg);
1993 /*
1994 * There is no guarantee that an OOM-lock contender
1995 * sees the wakeups triggered by the OOM kill
1996 * uncharges. Wake any sleepers explicitely.
1997 */
1998 memcg_oom_recover(memcg);
1999 }
Johannes Weiner49426422013-10-16 13:46:59 -07002000cleanup:
Tejun Heo626ebc42015-11-05 18:46:09 -08002001 current->memcg_in_oom = NULL;
Johannes Weiner3812c8c2013-09-12 15:13:44 -07002002 css_put(&memcg->css);
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08002003 return true;
KAMEZAWA Hiroyuki0b7f5692009-04-02 16:57:38 -07002004}
2005
Johannes Weinerd7365e72014-10-29 14:50:48 -07002006/**
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07002007 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
2008 * @victim: task to be killed by the OOM killer
2009 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
2010 *
2011 * Returns a pointer to a memory cgroup, which has to be cleaned up
2012 * by killing all belonging OOM-killable tasks.
2013 *
2014 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
2015 */
2016struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
2017 struct mem_cgroup *oom_domain)
2018{
2019 struct mem_cgroup *oom_group = NULL;
2020 struct mem_cgroup *memcg;
2021
2022 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2023 return NULL;
2024
2025 if (!oom_domain)
2026 oom_domain = root_mem_cgroup;
2027
2028 rcu_read_lock();
2029
2030 memcg = mem_cgroup_from_task(victim);
2031 if (memcg == root_mem_cgroup)
2032 goto out;
2033
2034 /*
2035 * Traverse the memory cgroup hierarchy from the victim task's
2036 * cgroup up to the OOMing cgroup (or root) to find the
2037 * highest-level memory cgroup with oom.group set.
2038 */
2039 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2040 if (memcg->oom_group)
2041 oom_group = memcg;
2042
2043 if (memcg == oom_domain)
2044 break;
2045 }
2046
2047 if (oom_group)
2048 css_get(&oom_group->css);
2049out:
2050 rcu_read_unlock();
2051
2052 return oom_group;
2053}
2054
2055void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2056{
2057 pr_info("Tasks in ");
2058 pr_cont_cgroup_path(memcg->css.cgroup);
2059 pr_cont(" are going to be killed due to memory.oom.group set\n");
2060}
2061
2062/**
Johannes Weiner81f8c3a2016-03-15 14:57:04 -07002063 * lock_page_memcg - lock a page->mem_cgroup binding
2064 * @page: the page
KAMEZAWA Hiroyuki32047e22010-10-27 15:33:40 -07002065 *
Johannes Weiner81f8c3a2016-03-15 14:57:04 -07002066 * This function protects unlocked LRU pages from being moved to
Johannes Weiner739f79f2017-08-18 15:15:48 -07002067 * another cgroup.
2068 *
2069 * It ensures lifetime of the returned memcg. Caller is responsible
2070 * for the lifetime of the page; __unlock_page_memcg() is available
2071 * when @page might get freed inside the locked section.
Balbir Singhd69b0422009-06-17 16:26:34 -07002072 */
Johannes Weiner739f79f2017-08-18 15:15:48 -07002073struct mem_cgroup *lock_page_memcg(struct page *page)
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002074{
2075 struct mem_cgroup *memcg;
Johannes Weiner6de22612015-02-11 15:25:01 -08002076 unsigned long flags;
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002077
Johannes Weiner6de22612015-02-11 15:25:01 -08002078 /*
2079 * The RCU lock is held throughout the transaction. The fast
2080 * path can get away without acquiring the memcg->move_lock
2081 * because page moving starts with an RCU grace period.
Johannes Weiner739f79f2017-08-18 15:15:48 -07002082 *
2083 * The RCU lock also protects the memcg from being freed when
2084 * the page state that is going to change is the only thing
2085 * preventing the page itself from being freed. E.g. writeback
2086 * doesn't hold a page reference and relies on PG_writeback to
2087 * keep off truncation, migration and so forth.
2088 */
Johannes Weinerd7365e72014-10-29 14:50:48 -07002089 rcu_read_lock();
2090
2091 if (mem_cgroup_disabled())
Johannes Weiner739f79f2017-08-18 15:15:48 -07002092 return NULL;
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002093again:
Johannes Weiner1306a852014-12-10 15:44:52 -08002094 memcg = page->mem_cgroup;
Johannes Weiner29833312014-12-10 15:44:02 -08002095 if (unlikely(!memcg))
Johannes Weiner739f79f2017-08-18 15:15:48 -07002096 return NULL;
Johannes Weinerd7365e72014-10-29 14:50:48 -07002097
Qiang Huangbdcbb652014-06-04 16:08:21 -07002098 if (atomic_read(&memcg->moving_account) <= 0)
Johannes Weiner739f79f2017-08-18 15:15:48 -07002099 return memcg;
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002100
Johannes Weiner6de22612015-02-11 15:25:01 -08002101 spin_lock_irqsave(&memcg->move_lock, flags);
Johannes Weiner1306a852014-12-10 15:44:52 -08002102 if (memcg != page->mem_cgroup) {
Johannes Weiner6de22612015-02-11 15:25:01 -08002103 spin_unlock_irqrestore(&memcg->move_lock, flags);
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002104 goto again;
2105 }
Johannes Weiner6de22612015-02-11 15:25:01 -08002106
2107 /*
2108 * When charge migration first begins, we can have locked and
2109 * unlocked page stat updates happening concurrently. Track
Johannes Weiner81f8c3a2016-03-15 14:57:04 -07002110 * the task who has the lock for unlock_page_memcg().
Johannes Weiner6de22612015-02-11 15:25:01 -08002111 */
2112 memcg->move_lock_task = current;
2113 memcg->move_lock_flags = flags;
Johannes Weinerd7365e72014-10-29 14:50:48 -07002114
Johannes Weiner739f79f2017-08-18 15:15:48 -07002115 return memcg;
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002116}
Johannes Weiner81f8c3a2016-03-15 14:57:04 -07002117EXPORT_SYMBOL(lock_page_memcg);
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002118
Johannes Weinerd7365e72014-10-29 14:50:48 -07002119/**
Johannes Weiner739f79f2017-08-18 15:15:48 -07002120 * __unlock_page_memcg - unlock and unpin a memcg
2121 * @memcg: the memcg
2122 *
2123 * Unlock and unpin a memcg returned by lock_page_memcg().
Johannes Weinerd7365e72014-10-29 14:50:48 -07002124 */
Johannes Weiner739f79f2017-08-18 15:15:48 -07002125void __unlock_page_memcg(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002126{
Johannes Weiner6de22612015-02-11 15:25:01 -08002127 if (memcg && memcg->move_lock_task == current) {
2128 unsigned long flags = memcg->move_lock_flags;
2129
2130 memcg->move_lock_task = NULL;
2131 memcg->move_lock_flags = 0;
2132
2133 spin_unlock_irqrestore(&memcg->move_lock, flags);
2134 }
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002135
Johannes Weinerd7365e72014-10-29 14:50:48 -07002136 rcu_read_unlock();
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002137}
Johannes Weiner739f79f2017-08-18 15:15:48 -07002138
2139/**
2140 * unlock_page_memcg - unlock a page->mem_cgroup binding
2141 * @page: the page
2142 */
2143void unlock_page_memcg(struct page *page)
2144{
2145 __unlock_page_memcg(page->mem_cgroup);
2146}
Johannes Weiner81f8c3a2016-03-15 14:57:04 -07002147EXPORT_SYMBOL(unlock_page_memcg);
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002148
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002149struct memcg_stock_pcp {
2150 struct mem_cgroup *cached; /* this never be root cgroup */
Johannes Weiner11c9ea42011-03-23 16:42:34 -07002151 unsigned int nr_pages;
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002152 struct work_struct work;
KAMEZAWA Hiroyuki26fe6162011-06-15 15:08:45 -07002153 unsigned long flags;
Kirill A. Shutemova0db00f2012-05-29 15:06:56 -07002154#define FLUSHING_CACHED_CHARGE 0
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002155};
2156static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
Michal Hocko9f50fad2011-08-09 11:56:26 +02002157static DEFINE_MUTEX(percpu_charge_mutex);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002158
Suleiman Souhlala0956d52012-12-18 14:21:36 -08002159/**
2160 * consume_stock: Try to consume stocked charge on this cpu.
2161 * @memcg: memcg to consume from.
2162 * @nr_pages: how many pages to charge.
2163 *
2164 * The charges will only happen if @memcg matches the current cpu's memcg
2165 * stock, and at least @nr_pages are available in that stock. Failure to
2166 * service an allocation will refill the stock.
2167 *
2168 * returns true if successful, false otherwise.
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002169 */
Suleiman Souhlala0956d52012-12-18 14:21:36 -08002170static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002171{
2172 struct memcg_stock_pcp *stock;
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002173 unsigned long flags;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002174 bool ret = false;
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002175
Johannes Weinera983b5e2018-01-31 16:16:45 -08002176 if (nr_pages > MEMCG_CHARGE_BATCH)
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002177 return ret;
Suleiman Souhlala0956d52012-12-18 14:21:36 -08002178
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002179 local_irq_save(flags);
2180
2181 stock = this_cpu_ptr(&memcg_stock);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002182 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
Suleiman Souhlala0956d52012-12-18 14:21:36 -08002183 stock->nr_pages -= nr_pages;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002184 ret = true;
2185 }
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002186
2187 local_irq_restore(flags);
2188
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002189 return ret;
2190}
2191
2192/*
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002193 * Returns stocks cached in percpu and reset cached information.
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002194 */
2195static void drain_stock(struct memcg_stock_pcp *stock)
2196{
2197 struct mem_cgroup *old = stock->cached;
2198
Johannes Weiner11c9ea42011-03-23 16:42:34 -07002199 if (stock->nr_pages) {
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002200 page_counter_uncharge(&old->memory, stock->nr_pages);
Johannes Weiner7941d212016-01-14 15:21:23 -08002201 if (do_memsw_account())
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002202 page_counter_uncharge(&old->memsw, stock->nr_pages);
Johannes Weinere8ea14c2014-12-10 15:42:42 -08002203 css_put_many(&old->css, stock->nr_pages);
Johannes Weiner11c9ea42011-03-23 16:42:34 -07002204 stock->nr_pages = 0;
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002205 }
2206 stock->cached = NULL;
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002207}
2208
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002209static void drain_local_stock(struct work_struct *dummy)
2210{
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002211 struct memcg_stock_pcp *stock;
2212 unsigned long flags;
2213
Michal Hocko72f01842017-10-03 16:14:53 -07002214 /*
2215 * The only protection from memory hotplug vs. drain_stock races is
2216 * that we always operate on local CPU stock here with IRQ disabled
2217 */
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002218 local_irq_save(flags);
2219
2220 stock = this_cpu_ptr(&memcg_stock);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002221 drain_stock(stock);
KAMEZAWA Hiroyuki26fe6162011-06-15 15:08:45 -07002222 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002223
2224 local_irq_restore(flags);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002225}
2226
2227/*
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002228 * Cache charges(val) to local per_cpu area.
Greg Thelen320cc512010-03-15 15:27:28 +01002229 * This will be consumed by consume_stock() function, later.
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002230 */
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002231static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002232{
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002233 struct memcg_stock_pcp *stock;
2234 unsigned long flags;
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002235
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002236 local_irq_save(flags);
2237
2238 stock = this_cpu_ptr(&memcg_stock);
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002239 if (stock->cached != memcg) { /* reset if necessary */
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002240 drain_stock(stock);
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002241 stock->cached = memcg;
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002242 }
Johannes Weiner11c9ea42011-03-23 16:42:34 -07002243 stock->nr_pages += nr_pages;
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002244
Johannes Weinera983b5e2018-01-31 16:16:45 -08002245 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
Roman Gushchin475d0482017-09-08 16:13:09 -07002246 drain_stock(stock);
2247
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002248 local_irq_restore(flags);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002249}
2250
2251/*
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002252 * Drains all per-CPU charge caches for given root_memcg resp. subtree
Johannes Weiner6d3d6aa2014-12-10 15:42:50 -08002253 * of the hierarchy under it.
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002254 */
Johannes Weiner6d3d6aa2014-12-10 15:42:50 -08002255static void drain_all_stock(struct mem_cgroup *root_memcg)
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002256{
KAMEZAWA Hiroyuki26fe6162011-06-15 15:08:45 -07002257 int cpu, curcpu;
Michal Hockod38144b2011-07-26 16:08:28 -07002258
Johannes Weiner6d3d6aa2014-12-10 15:42:50 -08002259 /* If someone's already draining, avoid adding running more workers. */
2260 if (!mutex_trylock(&percpu_charge_mutex))
2261 return;
Michal Hocko72f01842017-10-03 16:14:53 -07002262 /*
2263 * Notify other cpus that system-wide "drain" is running
2264 * We do not care about races with the cpu hotplug because cpu down
2265 * as well as workers from this path always operate on the local
2266 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2267 */
Johannes Weiner5af12d02011-08-25 15:59:07 -07002268 curcpu = get_cpu();
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002269 for_each_online_cpu(cpu) {
2270 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002271 struct mem_cgroup *memcg;
Roman Gushchine1a366b2019-09-23 15:34:58 -07002272 bool flush = false;
KAMEZAWA Hiroyuki26fe6162011-06-15 15:08:45 -07002273
Roman Gushchine1a366b2019-09-23 15:34:58 -07002274 rcu_read_lock();
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002275 memcg = stock->cached;
Roman Gushchine1a366b2019-09-23 15:34:58 -07002276 if (memcg && stock->nr_pages &&
2277 mem_cgroup_is_descendant(memcg, root_memcg))
2278 flush = true;
2279 rcu_read_unlock();
2280
2281 if (flush &&
2282 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
Michal Hockod1a05b62011-07-26 16:08:27 -07002283 if (cpu == curcpu)
2284 drain_local_stock(&stock->work);
2285 else
2286 schedule_work_on(cpu, &stock->work);
2287 }
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002288 }
Johannes Weiner5af12d02011-08-25 15:59:07 -07002289 put_cpu();
Michal Hocko9f50fad2011-08-09 11:56:26 +02002290 mutex_unlock(&percpu_charge_mutex);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002291}
2292
Sebastian Andrzej Siewior308167f2016-11-03 15:49:59 +01002293static int memcg_hotplug_cpu_dead(unsigned int cpu)
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002294{
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002295 struct memcg_stock_pcp *stock;
Johannes Weiner42a30032019-05-14 15:47:12 -07002296 struct mem_cgroup *memcg, *mi;
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002297
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002298 stock = &per_cpu(memcg_stock, cpu);
2299 drain_stock(stock);
Johannes Weinera983b5e2018-01-31 16:16:45 -08002300
2301 for_each_mem_cgroup(memcg) {
2302 int i;
2303
2304 for (i = 0; i < MEMCG_NR_STAT; i++) {
2305 int nid;
2306 long x;
2307
Chris Down871789d2019-05-14 15:46:57 -07002308 x = this_cpu_xchg(memcg->vmstats_percpu->stat[i], 0);
Johannes Weiner815744d2019-06-13 15:55:46 -07002309 if (x)
Johannes Weiner42a30032019-05-14 15:47:12 -07002310 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2311 atomic_long_add(x, &memcg->vmstats[i]);
Johannes Weinera983b5e2018-01-31 16:16:45 -08002312
2313 if (i >= NR_VM_NODE_STAT_ITEMS)
2314 continue;
2315
2316 for_each_node(nid) {
2317 struct mem_cgroup_per_node *pn;
2318
2319 pn = mem_cgroup_nodeinfo(memcg, nid);
2320 x = this_cpu_xchg(pn->lruvec_stat_cpu->count[i], 0);
Johannes Weiner815744d2019-06-13 15:55:46 -07002321 if (x)
Johannes Weiner42a30032019-05-14 15:47:12 -07002322 do {
2323 atomic_long_add(x, &pn->lruvec_stat[i]);
2324 } while ((pn = parent_nodeinfo(pn, nid)));
Johannes Weinera983b5e2018-01-31 16:16:45 -08002325 }
2326 }
2327
Johannes Weinere27be242018-04-10 16:29:45 -07002328 for (i = 0; i < NR_VM_EVENT_ITEMS; i++) {
Johannes Weinera983b5e2018-01-31 16:16:45 -08002329 long x;
2330
Chris Down871789d2019-05-14 15:46:57 -07002331 x = this_cpu_xchg(memcg->vmstats_percpu->events[i], 0);
Johannes Weiner815744d2019-06-13 15:55:46 -07002332 if (x)
Johannes Weiner42a30032019-05-14 15:47:12 -07002333 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2334 atomic_long_add(x, &memcg->vmevents[i]);
Johannes Weinera983b5e2018-01-31 16:16:45 -08002335 }
2336 }
2337
Sebastian Andrzej Siewior308167f2016-11-03 15:49:59 +01002338 return 0;
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002339}
2340
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08002341static void reclaim_high(struct mem_cgroup *memcg,
2342 unsigned int nr_pages,
2343 gfp_t gfp_mask)
2344{
2345 do {
2346 if (page_counter_read(&memcg->memory) <= memcg->high)
2347 continue;
Johannes Weinere27be242018-04-10 16:29:45 -07002348 memcg_memory_event(memcg, MEMCG_HIGH);
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08002349 try_to_free_mem_cgroup_pages(memcg, nr_pages, gfp_mask, true);
2350 } while ((memcg = parent_mem_cgroup(memcg)));
2351}
2352
2353static void high_work_func(struct work_struct *work)
2354{
2355 struct mem_cgroup *memcg;
2356
2357 memcg = container_of(work, struct mem_cgroup, high_work);
Johannes Weinera983b5e2018-01-31 16:16:45 -08002358 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08002359}
2360
Tejun Heob23afb92015-11-05 18:46:11 -08002361/*
Chris Down0e4b01d2019-09-23 15:34:55 -07002362 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2363 * enough to still cause a significant slowdown in most cases, while still
2364 * allowing diagnostics and tracing to proceed without becoming stuck.
2365 */
2366#define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2367
2368/*
2369 * When calculating the delay, we use these either side of the exponentiation to
2370 * maintain precision and scale to a reasonable number of jiffies (see the table
2371 * below.
2372 *
2373 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2374 * overage ratio to a delay.
2375 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down down the
2376 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2377 * to produce a reasonable delay curve.
2378 *
2379 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2380 * reasonable delay curve compared to precision-adjusted overage, not
2381 * penalising heavily at first, but still making sure that growth beyond the
2382 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2383 * example, with a high of 100 megabytes:
2384 *
2385 * +-------+------------------------+
2386 * | usage | time to allocate in ms |
2387 * +-------+------------------------+
2388 * | 100M | 0 |
2389 * | 101M | 6 |
2390 * | 102M | 25 |
2391 * | 103M | 57 |
2392 * | 104M | 102 |
2393 * | 105M | 159 |
2394 * | 106M | 230 |
2395 * | 107M | 313 |
2396 * | 108M | 409 |
2397 * | 109M | 518 |
2398 * | 110M | 639 |
2399 * | 111M | 774 |
2400 * | 112M | 921 |
2401 * | 113M | 1081 |
2402 * | 114M | 1254 |
2403 * | 115M | 1439 |
2404 * | 116M | 1638 |
2405 * | 117M | 1849 |
2406 * | 118M | 2000 |
2407 * | 119M | 2000 |
2408 * | 120M | 2000 |
2409 * +-------+------------------------+
2410 */
2411 #define MEMCG_DELAY_PRECISION_SHIFT 20
2412 #define MEMCG_DELAY_SCALING_SHIFT 14
2413
2414/*
Tejun Heob23afb92015-11-05 18:46:11 -08002415 * Scheduled by try_charge() to be executed from the userland return path
2416 * and reclaims memory over the high limit.
2417 */
2418void mem_cgroup_handle_over_high(void)
2419{
Chris Down0e4b01d2019-09-23 15:34:55 -07002420 unsigned long usage, high, clamped_high;
2421 unsigned long pflags;
2422 unsigned long penalty_jiffies, overage;
Tejun Heob23afb92015-11-05 18:46:11 -08002423 unsigned int nr_pages = current->memcg_nr_pages_over_high;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08002424 struct mem_cgroup *memcg;
Tejun Heob23afb92015-11-05 18:46:11 -08002425
2426 if (likely(!nr_pages))
2427 return;
2428
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08002429 memcg = get_mem_cgroup_from_mm(current->mm);
2430 reclaim_high(memcg, nr_pages, GFP_KERNEL);
Tejun Heob23afb92015-11-05 18:46:11 -08002431 current->memcg_nr_pages_over_high = 0;
Chris Down0e4b01d2019-09-23 15:34:55 -07002432
2433 /*
2434 * memory.high is breached and reclaim is unable to keep up. Throttle
2435 * allocators proactively to slow down excessive growth.
2436 *
2437 * We use overage compared to memory.high to calculate the number of
2438 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2439 * fairly lenient on small overages, and increasingly harsh when the
2440 * memcg in question makes it clear that it has no intention of stopping
2441 * its crazy behaviour, so we exponentially increase the delay based on
2442 * overage amount.
2443 */
2444
2445 usage = page_counter_read(&memcg->memory);
2446 high = READ_ONCE(memcg->high);
2447
2448 if (usage <= high)
2449 goto out;
2450
2451 /*
2452 * Prevent division by 0 in overage calculation by acting as if it was a
2453 * threshold of 1 page
2454 */
2455 clamped_high = max(high, 1UL);
2456
2457 overage = div_u64((u64)(usage - high) << MEMCG_DELAY_PRECISION_SHIFT,
2458 clamped_high);
2459
2460 penalty_jiffies = ((u64)overage * overage * HZ)
2461 >> (MEMCG_DELAY_PRECISION_SHIFT + MEMCG_DELAY_SCALING_SHIFT);
2462
2463 /*
2464 * Factor in the task's own contribution to the overage, such that four
2465 * N-sized allocations are throttled approximately the same as one
2466 * 4N-sized allocation.
2467 *
2468 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2469 * larger the current charge patch is than that.
2470 */
2471 penalty_jiffies = penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2472
2473 /*
2474 * Clamp the max delay per usermode return so as to still keep the
2475 * application moving forwards and also permit diagnostics, albeit
2476 * extremely slowly.
2477 */
2478 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2479
2480 /*
2481 * Don't sleep if the amount of jiffies this memcg owes us is so low
2482 * that it's not even worth doing, in an attempt to be nice to those who
2483 * go only a small amount over their memory.high value and maybe haven't
2484 * been aggressively reclaimed enough yet.
2485 */
2486 if (penalty_jiffies <= HZ / 100)
2487 goto out;
2488
2489 /*
2490 * If we exit early, we're guaranteed to die (since
2491 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2492 * need to account for any ill-begotten jiffies to pay them off later.
2493 */
2494 psi_memstall_enter(&pflags);
2495 schedule_timeout_killable(penalty_jiffies);
2496 psi_memstall_leave(&pflags);
2497
2498out:
2499 css_put(&memcg->css);
Tejun Heob23afb92015-11-05 18:46:11 -08002500}
2501
Johannes Weiner00501b52014-08-08 14:19:20 -07002502static int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2503 unsigned int nr_pages)
Balbir Singh8a9f3cc2008-02-07 00:13:53 -08002504{
Johannes Weinera983b5e2018-01-31 16:16:45 -08002505 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
Johannes Weiner9b130612014-08-06 16:05:51 -07002506 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
Johannes Weiner6539cc02014-08-06 16:05:42 -07002507 struct mem_cgroup *mem_over_limit;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002508 struct page_counter *counter;
Johannes Weiner6539cc02014-08-06 16:05:42 -07002509 unsigned long nr_reclaimed;
Johannes Weinerb70a2a22014-10-09 15:28:56 -07002510 bool may_swap = true;
2511 bool drained = false;
Michal Hocko29ef6802018-08-17 15:47:11 -07002512 enum oom_status oom_status;
KAMEZAWA Hiroyukia636b322009-01-07 18:08:08 -08002513
Johannes Weinerce00a962014-09-05 08:43:57 -04002514 if (mem_cgroup_is_root(memcg))
Tejun Heo10d53c72015-11-05 18:46:17 -08002515 return 0;
Johannes Weiner6539cc02014-08-06 16:05:42 -07002516retry:
Michal Hockob6b6cc72014-04-07 15:37:44 -07002517 if (consume_stock(memcg, nr_pages))
Tejun Heo10d53c72015-11-05 18:46:17 -08002518 return 0;
Balbir Singh8a9f3cc2008-02-07 00:13:53 -08002519
Johannes Weiner7941d212016-01-14 15:21:23 -08002520 if (!do_memsw_account() ||
Johannes Weiner6071ca52015-11-05 18:50:26 -08002521 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2522 if (page_counter_try_charge(&memcg->memory, batch, &counter))
Johannes Weiner6539cc02014-08-06 16:05:42 -07002523 goto done_restock;
Johannes Weiner7941d212016-01-14 15:21:23 -08002524 if (do_memsw_account())
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002525 page_counter_uncharge(&memcg->memsw, batch);
2526 mem_over_limit = mem_cgroup_from_counter(counter, memory);
Johannes Weiner3fbe7242014-10-09 15:28:54 -07002527 } else {
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002528 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
Johannes Weinerb70a2a22014-10-09 15:28:56 -07002529 may_swap = false;
Johannes Weiner3fbe7242014-10-09 15:28:54 -07002530 }
KAMEZAWA Hiroyuki7a81b882009-01-07 18:07:48 -08002531
Johannes Weiner6539cc02014-08-06 16:05:42 -07002532 if (batch > nr_pages) {
2533 batch = nr_pages;
2534 goto retry;
2535 }
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002536
Johannes Weiner06b078f2014-08-06 16:05:44 -07002537 /*
Johannes Weiner869712f2019-11-05 21:17:13 -08002538 * Memcg doesn't have a dedicated reserve for atomic
2539 * allocations. But like the global atomic pool, we need to
2540 * put the burden of reclaim on regular allocation requests
2541 * and let these go through as privileged allocations.
2542 */
2543 if (gfp_mask & __GFP_ATOMIC)
2544 goto force;
2545
2546 /*
Johannes Weiner06b078f2014-08-06 16:05:44 -07002547 * Unlike in global OOM situations, memcg is not in a physical
2548 * memory shortage. Allow dying and OOM-killed tasks to
2549 * bypass the last charges so that they can exit quickly and
2550 * free their memory.
2551 */
Tetsuo Handa7775fac2019-03-05 15:46:47 -08002552 if (unlikely(should_force_charge()))
Tejun Heo10d53c72015-11-05 18:46:17 -08002553 goto force;
Johannes Weiner06b078f2014-08-06 16:05:44 -07002554
Johannes Weiner89a28482016-10-27 17:46:56 -07002555 /*
2556 * Prevent unbounded recursion when reclaim operations need to
2557 * allocate memory. This might exceed the limits temporarily,
2558 * but we prefer facilitating memory reclaim and getting back
2559 * under the limit over triggering OOM kills in these cases.
2560 */
2561 if (unlikely(current->flags & PF_MEMALLOC))
2562 goto force;
2563
Johannes Weiner06b078f2014-08-06 16:05:44 -07002564 if (unlikely(task_in_memcg_oom(current)))
2565 goto nomem;
2566
Mel Gormand0164ad2015-11-06 16:28:21 -08002567 if (!gfpflags_allow_blocking(gfp_mask))
Johannes Weiner6539cc02014-08-06 16:05:42 -07002568 goto nomem;
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07002569
Johannes Weinere27be242018-04-10 16:29:45 -07002570 memcg_memory_event(mem_over_limit, MEMCG_MAX);
Johannes Weiner241994ed2015-02-11 15:26:06 -08002571
Johannes Weinerb70a2a22014-10-09 15:28:56 -07002572 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2573 gfp_mask, may_swap);
Johannes Weiner6539cc02014-08-06 16:05:42 -07002574
Johannes Weiner61e02c72014-08-06 16:08:16 -07002575 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
Johannes Weiner6539cc02014-08-06 16:05:42 -07002576 goto retry;
Johannes Weiner28c34c22014-08-06 16:05:47 -07002577
Johannes Weinerb70a2a22014-10-09 15:28:56 -07002578 if (!drained) {
Johannes Weiner6d3d6aa2014-12-10 15:42:50 -08002579 drain_all_stock(mem_over_limit);
Johannes Weinerb70a2a22014-10-09 15:28:56 -07002580 drained = true;
2581 goto retry;
2582 }
2583
Johannes Weiner28c34c22014-08-06 16:05:47 -07002584 if (gfp_mask & __GFP_NORETRY)
2585 goto nomem;
Johannes Weiner6539cc02014-08-06 16:05:42 -07002586 /*
2587 * Even though the limit is exceeded at this point, reclaim
2588 * may have been able to free some pages. Retry the charge
2589 * before killing the task.
2590 *
2591 * Only for regular pages, though: huge pages are rather
2592 * unlikely to succeed so close to the limit, and we fall back
2593 * to regular pages anyway in case of failure.
2594 */
Johannes Weiner61e02c72014-08-06 16:08:16 -07002595 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
Johannes Weiner6539cc02014-08-06 16:05:42 -07002596 goto retry;
2597 /*
2598 * At task move, charge accounts can be doubly counted. So, it's
2599 * better to wait until the end of task_move if something is going on.
2600 */
2601 if (mem_cgroup_wait_acct_move(mem_over_limit))
2602 goto retry;
2603
Johannes Weiner9b130612014-08-06 16:05:51 -07002604 if (nr_retries--)
2605 goto retry;
2606
Shakeel Butt38d38492019-07-11 20:55:48 -07002607 if (gfp_mask & __GFP_RETRY_MAYFAIL)
Michal Hocko29ef6802018-08-17 15:47:11 -07002608 goto nomem;
2609
Johannes Weiner06b078f2014-08-06 16:05:44 -07002610 if (gfp_mask & __GFP_NOFAIL)
Tejun Heo10d53c72015-11-05 18:46:17 -08002611 goto force;
Johannes Weiner06b078f2014-08-06 16:05:44 -07002612
Johannes Weiner6539cc02014-08-06 16:05:42 -07002613 if (fatal_signal_pending(current))
Tejun Heo10d53c72015-11-05 18:46:17 -08002614 goto force;
Johannes Weiner6539cc02014-08-06 16:05:42 -07002615
Michal Hocko29ef6802018-08-17 15:47:11 -07002616 /*
2617 * keep retrying as long as the memcg oom killer is able to make
2618 * a forward progress or bypass the charge if the oom killer
2619 * couldn't make any progress.
2620 */
2621 oom_status = mem_cgroup_oom(mem_over_limit, gfp_mask,
Jerome Marchand3608de02015-11-05 18:47:29 -08002622 get_order(nr_pages * PAGE_SIZE));
Michal Hocko29ef6802018-08-17 15:47:11 -07002623 switch (oom_status) {
2624 case OOM_SUCCESS:
2625 nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
Michal Hocko29ef6802018-08-17 15:47:11 -07002626 goto retry;
2627 case OOM_FAILED:
2628 goto force;
2629 default:
2630 goto nomem;
2631 }
KAMEZAWA Hiroyuki7a81b882009-01-07 18:07:48 -08002632nomem:
Johannes Weiner6d1fdc42014-04-07 15:37:45 -07002633 if (!(gfp_mask & __GFP_NOFAIL))
Johannes Weiner3168ecb2013-10-31 16:34:13 -07002634 return -ENOMEM;
Tejun Heo10d53c72015-11-05 18:46:17 -08002635force:
2636 /*
2637 * The allocation either can't fail or will lead to more memory
2638 * being freed very soon. Allow memory usage go over the limit
2639 * temporarily by force charging it.
2640 */
2641 page_counter_charge(&memcg->memory, nr_pages);
Johannes Weiner7941d212016-01-14 15:21:23 -08002642 if (do_memsw_account())
Tejun Heo10d53c72015-11-05 18:46:17 -08002643 page_counter_charge(&memcg->memsw, nr_pages);
2644 css_get_many(&memcg->css, nr_pages);
2645
2646 return 0;
Johannes Weiner6539cc02014-08-06 16:05:42 -07002647
2648done_restock:
Johannes Weinere8ea14c2014-12-10 15:42:42 -08002649 css_get_many(&memcg->css, batch);
Johannes Weiner6539cc02014-08-06 16:05:42 -07002650 if (batch > nr_pages)
2651 refill_stock(memcg, batch - nr_pages);
Tejun Heob23afb92015-11-05 18:46:11 -08002652
Johannes Weiner241994ed2015-02-11 15:26:06 -08002653 /*
Tejun Heob23afb92015-11-05 18:46:11 -08002654 * If the hierarchy is above the normal consumption range, schedule
2655 * reclaim on returning to userland. We can perform reclaim here
Mel Gorman71baba42015-11-06 16:28:28 -08002656 * if __GFP_RECLAIM but let's always punt for simplicity and so that
Tejun Heob23afb92015-11-05 18:46:11 -08002657 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2658 * not recorded as it most likely matches current's and won't
2659 * change in the meantime. As high limit is checked again before
2660 * reclaim, the cost of mismatch is negligible.
Johannes Weiner241994ed2015-02-11 15:26:06 -08002661 */
2662 do {
Tejun Heob23afb92015-11-05 18:46:11 -08002663 if (page_counter_read(&memcg->memory) > memcg->high) {
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08002664 /* Don't bother a random interrupted task */
2665 if (in_interrupt()) {
2666 schedule_work(&memcg->high_work);
2667 break;
2668 }
Vladimir Davydov9516a182015-12-11 13:40:24 -08002669 current->memcg_nr_pages_over_high += batch;
Tejun Heob23afb92015-11-05 18:46:11 -08002670 set_notify_resume(current);
2671 break;
2672 }
Johannes Weiner241994ed2015-02-11 15:26:06 -08002673 } while ((memcg = parent_mem_cgroup(memcg)));
Tejun Heo10d53c72015-11-05 18:46:17 -08002674
2675 return 0;
KAMEZAWA Hiroyuki7a81b882009-01-07 18:07:48 -08002676}
Balbir Singh8a9f3cc2008-02-07 00:13:53 -08002677
Johannes Weiner00501b52014-08-08 14:19:20 -07002678static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
Daisuke Nishimuraa3032a22009-12-15 16:47:10 -08002679{
Johannes Weinerce00a962014-09-05 08:43:57 -04002680 if (mem_cgroup_is_root(memcg))
2681 return;
2682
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002683 page_counter_uncharge(&memcg->memory, nr_pages);
Johannes Weiner7941d212016-01-14 15:21:23 -08002684 if (do_memsw_account())
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002685 page_counter_uncharge(&memcg->memsw, nr_pages);
Daisuke Nishimuraa3032a22009-12-15 16:47:10 -08002686
Johannes Weinere8ea14c2014-12-10 15:42:42 -08002687 css_put_many(&memcg->css, nr_pages);
KAMEZAWA Hiroyukid01dd172012-05-29 15:07:03 -07002688}
2689
Johannes Weiner0a31bc92014-08-08 14:19:22 -07002690static void lock_page_lru(struct page *page, int *isolated)
2691{
Andrey Ryabininf4b7e272019-03-05 15:49:39 -08002692 pg_data_t *pgdat = page_pgdat(page);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07002693
Andrey Ryabininf4b7e272019-03-05 15:49:39 -08002694 spin_lock_irq(&pgdat->lru_lock);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07002695 if (PageLRU(page)) {
2696 struct lruvec *lruvec;
2697
Andrey Ryabininf4b7e272019-03-05 15:49:39 -08002698 lruvec = mem_cgroup_page_lruvec(page, pgdat);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07002699 ClearPageLRU(page);
2700 del_page_from_lru_list(page, lruvec, page_lru(page));
2701 *isolated = 1;
2702 } else
2703 *isolated = 0;
2704}
2705
2706static void unlock_page_lru(struct page *page, int isolated)
2707{
Andrey Ryabininf4b7e272019-03-05 15:49:39 -08002708 pg_data_t *pgdat = page_pgdat(page);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07002709
2710 if (isolated) {
2711 struct lruvec *lruvec;
2712
Andrey Ryabininf4b7e272019-03-05 15:49:39 -08002713 lruvec = mem_cgroup_page_lruvec(page, pgdat);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07002714 VM_BUG_ON_PAGE(PageLRU(page), page);
2715 SetPageLRU(page);
2716 add_page_to_lru_list(page, lruvec, page_lru(page));
2717 }
Andrey Ryabininf4b7e272019-03-05 15:49:39 -08002718 spin_unlock_irq(&pgdat->lru_lock);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07002719}
2720
Johannes Weiner00501b52014-08-08 14:19:20 -07002721static void commit_charge(struct page *page, struct mem_cgroup *memcg,
Johannes Weiner6abb5a82014-08-08 14:19:33 -07002722 bool lrucare)
KAMEZAWA Hiroyuki7a81b882009-01-07 18:07:48 -08002723{
Johannes Weiner0a31bc92014-08-08 14:19:22 -07002724 int isolated;
Hugh Dickins9ce70c02012-03-05 14:59:16 -08002725
Johannes Weiner1306a852014-12-10 15:44:52 -08002726 VM_BUG_ON_PAGE(page->mem_cgroup, page);
Hugh Dickins9ce70c02012-03-05 14:59:16 -08002727
2728 /*
2729 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2730 * may already be on some other mem_cgroup's LRU. Take care of it.
2731 */
Johannes Weiner0a31bc92014-08-08 14:19:22 -07002732 if (lrucare)
2733 lock_page_lru(page, &isolated);
Hugh Dickins9ce70c02012-03-05 14:59:16 -08002734
Johannes Weiner0a31bc92014-08-08 14:19:22 -07002735 /*
2736 * Nobody should be changing or seriously looking at
Johannes Weiner1306a852014-12-10 15:44:52 -08002737 * page->mem_cgroup at this point:
Johannes Weiner0a31bc92014-08-08 14:19:22 -07002738 *
2739 * - the page is uncharged
2740 *
2741 * - the page is off-LRU
2742 *
2743 * - an anonymous fault has exclusive page access, except for
2744 * a locked page table
2745 *
2746 * - a page cache insertion, a swapin fault, or a migration
2747 * have the page locked
2748 */
Johannes Weiner1306a852014-12-10 15:44:52 -08002749 page->mem_cgroup = memcg;
Hugh Dickins3be912772008-02-07 00:14:19 -08002750
Johannes Weiner0a31bc92014-08-08 14:19:22 -07002751 if (lrucare)
2752 unlock_page_lru(page, isolated);
Balbir Singh8a9f3cc2008-02-07 00:13:53 -08002753}
2754
Kirill Tkhai84c07d12018-08-17 15:47:25 -07002755#ifdef CONFIG_MEMCG_KMEM
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07002756static int memcg_alloc_cache_id(void)
Glauber Costa55007d82012-12-18 14:22:38 -08002757{
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07002758 int id, size;
2759 int err;
Glauber Costa55007d82012-12-18 14:22:38 -08002760
Vladimir Davydovdbcf73e2015-02-12 14:58:57 -08002761 id = ida_simple_get(&memcg_cache_ida,
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07002762 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2763 if (id < 0)
2764 return id;
2765
Vladimir Davydovdbcf73e2015-02-12 14:58:57 -08002766 if (id < memcg_nr_cache_ids)
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07002767 return id;
2768
2769 /*
2770 * There's no space for the new id in memcg_caches arrays,
2771 * so we have to grow them.
2772 */
Vladimir Davydov05257a12015-02-12 14:59:01 -08002773 down_write(&memcg_cache_ids_sem);
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07002774
2775 size = 2 * (id + 1);
Glauber Costa55007d82012-12-18 14:22:38 -08002776 if (size < MEMCG_CACHES_MIN_SIZE)
2777 size = MEMCG_CACHES_MIN_SIZE;
2778 else if (size > MEMCG_CACHES_MAX_SIZE)
2779 size = MEMCG_CACHES_MAX_SIZE;
2780
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07002781 err = memcg_update_all_caches(size);
Vladimir Davydov05257a12015-02-12 14:59:01 -08002782 if (!err)
Vladimir Davydov60d3fd32015-02-12 14:59:10 -08002783 err = memcg_update_all_list_lrus(size);
2784 if (!err)
Vladimir Davydov05257a12015-02-12 14:59:01 -08002785 memcg_nr_cache_ids = size;
2786
2787 up_write(&memcg_cache_ids_sem);
2788
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07002789 if (err) {
Vladimir Davydovdbcf73e2015-02-12 14:58:57 -08002790 ida_simple_remove(&memcg_cache_ida, id);
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07002791 return err;
2792 }
2793 return id;
2794}
2795
2796static void memcg_free_cache_id(int id)
2797{
Vladimir Davydovdbcf73e2015-02-12 14:58:57 -08002798 ida_simple_remove(&memcg_cache_ida, id);
Glauber Costa55007d82012-12-18 14:22:38 -08002799}
2800
Vladimir Davydovd5b3cf72015-02-10 14:11:47 -08002801struct memcg_kmem_cache_create_work {
Vladimir Davydov5722d092014-04-07 15:39:24 -07002802 struct mem_cgroup *memcg;
2803 struct kmem_cache *cachep;
2804 struct work_struct work;
2805};
2806
Vladimir Davydovd5b3cf72015-02-10 14:11:47 -08002807static void memcg_kmem_cache_create_func(struct work_struct *w)
Glauber Costad7f25f82012-12-18 14:22:40 -08002808{
Vladimir Davydovd5b3cf72015-02-10 14:11:47 -08002809 struct memcg_kmem_cache_create_work *cw =
2810 container_of(w, struct memcg_kmem_cache_create_work, work);
Vladimir Davydov5722d092014-04-07 15:39:24 -07002811 struct mem_cgroup *memcg = cw->memcg;
2812 struct kmem_cache *cachep = cw->cachep;
Glauber Costad7f25f82012-12-18 14:22:40 -08002813
Vladimir Davydovd5b3cf72015-02-10 14:11:47 -08002814 memcg_create_kmem_cache(memcg, cachep);
Vladimir Davydovbd673142014-06-04 16:07:40 -07002815
Vladimir Davydov5722d092014-04-07 15:39:24 -07002816 css_put(&memcg->css);
Glauber Costad7f25f82012-12-18 14:22:40 -08002817 kfree(cw);
2818}
2819
2820/*
2821 * Enqueue the creation of a per-memcg kmem_cache.
Glauber Costad7f25f82012-12-18 14:22:40 -08002822 */
Shakeel Butt85cfb242018-10-26 15:07:41 -07002823static void memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
Vladimir Davydovd5b3cf72015-02-10 14:11:47 -08002824 struct kmem_cache *cachep)
Glauber Costad7f25f82012-12-18 14:22:40 -08002825{
Vladimir Davydovd5b3cf72015-02-10 14:11:47 -08002826 struct memcg_kmem_cache_create_work *cw;
Glauber Costad7f25f82012-12-18 14:22:40 -08002827
Roman Gushchinf0a3a242019-07-11 20:56:27 -07002828 if (!css_tryget_online(&memcg->css))
2829 return;
2830
Minchan Kimc892fd82018-04-20 14:56:17 -07002831 cw = kmalloc(sizeof(*cw), GFP_NOWAIT | __GFP_NOWARN);
Vladimir Davydov8135be52014-12-12 16:56:38 -08002832 if (!cw)
Glauber Costad7f25f82012-12-18 14:22:40 -08002833 return;
Vladimir Davydov8135be52014-12-12 16:56:38 -08002834
Glauber Costad7f25f82012-12-18 14:22:40 -08002835 cw->memcg = memcg;
2836 cw->cachep = cachep;
Vladimir Davydovd5b3cf72015-02-10 14:11:47 -08002837 INIT_WORK(&cw->work, memcg_kmem_cache_create_func);
Glauber Costad7f25f82012-12-18 14:22:40 -08002838
Tejun Heo17cc4df2017-02-22 15:41:36 -08002839 queue_work(memcg_kmem_cache_wq, &cw->work);
Glauber Costad7f25f82012-12-18 14:22:40 -08002840}
2841
Vladimir Davydov45264772016-07-26 15:24:21 -07002842static inline bool memcg_kmem_bypass(void)
2843{
2844 if (in_interrupt() || !current->mm || (current->flags & PF_KTHREAD))
2845 return true;
2846 return false;
2847}
2848
2849/**
2850 * memcg_kmem_get_cache: select the correct per-memcg cache for allocation
2851 * @cachep: the original global kmem cache
2852 *
Glauber Costad7f25f82012-12-18 14:22:40 -08002853 * Return the kmem_cache we're supposed to use for a slab allocation.
2854 * We try to use the current memcg's version of the cache.
2855 *
Vladimir Davydov45264772016-07-26 15:24:21 -07002856 * If the cache does not exist yet, if we are the first user of it, we
2857 * create it asynchronously in a workqueue and let the current allocation
2858 * go through with the original cache.
Glauber Costad7f25f82012-12-18 14:22:40 -08002859 *
Vladimir Davydov45264772016-07-26 15:24:21 -07002860 * This function takes a reference to the cache it returns to assure it
2861 * won't get destroyed while we are working with it. Once the caller is
2862 * done with it, memcg_kmem_put_cache() must be called to release the
2863 * reference.
Glauber Costad7f25f82012-12-18 14:22:40 -08002864 */
Vladimir Davydov45264772016-07-26 15:24:21 -07002865struct kmem_cache *memcg_kmem_get_cache(struct kmem_cache *cachep)
Glauber Costad7f25f82012-12-18 14:22:40 -08002866{
2867 struct mem_cgroup *memcg;
Vladimir Davydov959c8962014-01-23 15:52:59 -08002868 struct kmem_cache *memcg_cachep;
Roman Gushchinf0a3a242019-07-11 20:56:27 -07002869 struct memcg_cache_array *arr;
Vladimir Davydov2a4db7e2015-02-12 14:59:32 -08002870 int kmemcg_id;
Glauber Costad7f25f82012-12-18 14:22:40 -08002871
Vladimir Davydovf7ce3192015-02-12 14:59:20 -08002872 VM_BUG_ON(!is_root_cache(cachep));
Glauber Costad7f25f82012-12-18 14:22:40 -08002873
Vladimir Davydov45264772016-07-26 15:24:21 -07002874 if (memcg_kmem_bypass())
Vladimir Davydov230e9fc2016-01-14 15:18:15 -08002875 return cachep;
2876
Roman Gushchinf0a3a242019-07-11 20:56:27 -07002877 rcu_read_lock();
2878
2879 if (unlikely(current->active_memcg))
2880 memcg = current->active_memcg;
2881 else
2882 memcg = mem_cgroup_from_task(current);
2883
2884 if (!memcg || memcg == root_mem_cgroup)
2885 goto out_unlock;
2886
Jason Low4db0c3c2015-04-15 16:14:08 -07002887 kmemcg_id = READ_ONCE(memcg->kmemcg_id);
Vladimir Davydov2a4db7e2015-02-12 14:59:32 -08002888 if (kmemcg_id < 0)
Roman Gushchinf0a3a242019-07-11 20:56:27 -07002889 goto out_unlock;
Glauber Costad7f25f82012-12-18 14:22:40 -08002890
Roman Gushchinf0a3a242019-07-11 20:56:27 -07002891 arr = rcu_dereference(cachep->memcg_params.memcg_caches);
2892
2893 /*
2894 * Make sure we will access the up-to-date value. The code updating
2895 * memcg_caches issues a write barrier to match the data dependency
2896 * barrier inside READ_ONCE() (see memcg_create_kmem_cache()).
2897 */
2898 memcg_cachep = READ_ONCE(arr->entries[kmemcg_id]);
Li Zefanca0dde92013-04-29 15:08:57 -07002899
2900 /*
2901 * If we are in a safe context (can wait, and not in interrupt
2902 * context), we could be be predictable and return right away.
2903 * This would guarantee that the allocation being performed
2904 * already belongs in the new cache.
2905 *
2906 * However, there are some clashes that can arrive from locking.
2907 * For instance, because we acquire the slab_mutex while doing
Vladimir Davydov776ed0f2014-06-04 16:10:02 -07002908 * memcg_create_kmem_cache, this means no further allocation
2909 * could happen with the slab_mutex held. So it's better to
2910 * defer everything.
Roman Gushchinf0a3a242019-07-11 20:56:27 -07002911 *
2912 * If the memcg is dying or memcg_cache is about to be released,
2913 * don't bother creating new kmem_caches. Because memcg_cachep
2914 * is ZEROed as the fist step of kmem offlining, we don't need
2915 * percpu_ref_tryget_live() here. css_tryget_online() check in
2916 * memcg_schedule_kmem_cache_create() will prevent us from
2917 * creation of a new kmem_cache.
Li Zefanca0dde92013-04-29 15:08:57 -07002918 */
Roman Gushchinf0a3a242019-07-11 20:56:27 -07002919 if (unlikely(!memcg_cachep))
2920 memcg_schedule_kmem_cache_create(memcg, cachep);
2921 else if (percpu_ref_tryget(&memcg_cachep->memcg_params.refcnt))
2922 cachep = memcg_cachep;
2923out_unlock:
2924 rcu_read_unlock();
Li Zefanca0dde92013-04-29 15:08:57 -07002925 return cachep;
Glauber Costad7f25f82012-12-18 14:22:40 -08002926}
Glauber Costad7f25f82012-12-18 14:22:40 -08002927
Vladimir Davydov45264772016-07-26 15:24:21 -07002928/**
2929 * memcg_kmem_put_cache: drop reference taken by memcg_kmem_get_cache
2930 * @cachep: the cache returned by memcg_kmem_get_cache
2931 */
2932void memcg_kmem_put_cache(struct kmem_cache *cachep)
Vladimir Davydov8135be52014-12-12 16:56:38 -08002933{
2934 if (!is_root_cache(cachep))
Roman Gushchinf0a3a242019-07-11 20:56:27 -07002935 percpu_ref_put(&cachep->memcg_params.refcnt);
Vladimir Davydov8135be52014-12-12 16:56:38 -08002936}
2937
Vladimir Davydov45264772016-07-26 15:24:21 -07002938/**
Shakeel Butt60cd4bc2019-03-05 15:43:13 -08002939 * __memcg_kmem_charge_memcg: charge a kmem page
Vladimir Davydov45264772016-07-26 15:24:21 -07002940 * @page: page to charge
2941 * @gfp: reclaim mode
2942 * @order: allocation order
2943 * @memcg: memory cgroup to charge
2944 *
2945 * Returns 0 on success, an error code on failure.
2946 */
Shakeel Butt60cd4bc2019-03-05 15:43:13 -08002947int __memcg_kmem_charge_memcg(struct page *page, gfp_t gfp, int order,
Vladimir Davydov45264772016-07-26 15:24:21 -07002948 struct mem_cgroup *memcg)
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08002949{
2950 unsigned int nr_pages = 1 << order;
2951 struct page_counter *counter;
Johannes Weiner6071ca52015-11-05 18:50:26 -08002952 int ret;
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08002953
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08002954 ret = try_charge(memcg, gfp, nr_pages);
Johannes Weiner52c29b02016-01-20 15:02:35 -08002955 if (ret)
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08002956 return ret;
Johannes Weiner52c29b02016-01-20 15:02:35 -08002957
2958 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) &&
2959 !page_counter_try_charge(&memcg->kmem, nr_pages, &counter)) {
Michal Hockoe55d9d92019-09-25 16:45:53 -07002960
2961 /*
2962 * Enforce __GFP_NOFAIL allocation because callers are not
2963 * prepared to see failures and likely do not have any failure
2964 * handling code.
2965 */
2966 if (gfp & __GFP_NOFAIL) {
2967 page_counter_charge(&memcg->kmem, nr_pages);
2968 return 0;
2969 }
Johannes Weiner52c29b02016-01-20 15:02:35 -08002970 cancel_charge(memcg, nr_pages);
2971 return -ENOMEM;
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08002972 }
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08002973 return 0;
2974}
2975
Vladimir Davydov45264772016-07-26 15:24:21 -07002976/**
Shakeel Butt60cd4bc2019-03-05 15:43:13 -08002977 * __memcg_kmem_charge: charge a kmem page to the current memory cgroup
Vladimir Davydov45264772016-07-26 15:24:21 -07002978 * @page: page to charge
2979 * @gfp: reclaim mode
2980 * @order: allocation order
2981 *
2982 * Returns 0 on success, an error code on failure.
2983 */
Shakeel Butt60cd4bc2019-03-05 15:43:13 -08002984int __memcg_kmem_charge(struct page *page, gfp_t gfp, int order)
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08002985{
2986 struct mem_cgroup *memcg;
Vladimir Davydovfcff7d72016-03-17 14:17:29 -07002987 int ret = 0;
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08002988
Shakeel Butt60cd4bc2019-03-05 15:43:13 -08002989 if (memcg_kmem_bypass())
Vladimir Davydov45264772016-07-26 15:24:21 -07002990 return 0;
2991
Shakeel Buttd46eb14b2018-08-17 15:46:39 -07002992 memcg = get_mem_cgroup_from_current();
Vladimir Davydovc4159a72016-08-08 23:03:12 +03002993 if (!mem_cgroup_is_root(memcg)) {
Shakeel Butt60cd4bc2019-03-05 15:43:13 -08002994 ret = __memcg_kmem_charge_memcg(page, gfp, order, memcg);
Roman Gushchin4d96ba32019-07-11 20:56:31 -07002995 if (!ret) {
2996 page->mem_cgroup = memcg;
Vladimir Davydovc4159a72016-08-08 23:03:12 +03002997 __SetPageKmemcg(page);
Roman Gushchin4d96ba32019-07-11 20:56:31 -07002998 }
Vladimir Davydovc4159a72016-08-08 23:03:12 +03002999 }
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003000 css_put(&memcg->css);
Vladimir Davydovd05e83a2015-11-05 18:48:59 -08003001 return ret;
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003002}
Roman Gushchin49a18ea2019-07-11 20:56:13 -07003003
3004/**
3005 * __memcg_kmem_uncharge_memcg: uncharge a kmem page
3006 * @memcg: memcg to uncharge
3007 * @nr_pages: number of pages to uncharge
3008 */
3009void __memcg_kmem_uncharge_memcg(struct mem_cgroup *memcg,
3010 unsigned int nr_pages)
3011{
3012 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
3013 page_counter_uncharge(&memcg->kmem, nr_pages);
3014
3015 page_counter_uncharge(&memcg->memory, nr_pages);
3016 if (do_memsw_account())
3017 page_counter_uncharge(&memcg->memsw, nr_pages);
3018}
Vladimir Davydov45264772016-07-26 15:24:21 -07003019/**
Shakeel Butt60cd4bc2019-03-05 15:43:13 -08003020 * __memcg_kmem_uncharge: uncharge a kmem page
Vladimir Davydov45264772016-07-26 15:24:21 -07003021 * @page: page to uncharge
3022 * @order: allocation order
3023 */
Shakeel Butt60cd4bc2019-03-05 15:43:13 -08003024void __memcg_kmem_uncharge(struct page *page, int order)
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003025{
Johannes Weiner1306a852014-12-10 15:44:52 -08003026 struct mem_cgroup *memcg = page->mem_cgroup;
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08003027 unsigned int nr_pages = 1 << order;
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003028
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003029 if (!memcg)
3030 return;
3031
Sasha Levin309381fea2014-01-23 15:52:54 -08003032 VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
Roman Gushchin49a18ea2019-07-11 20:56:13 -07003033 __memcg_kmem_uncharge_memcg(memcg, nr_pages);
Johannes Weiner1306a852014-12-10 15:44:52 -08003034 page->mem_cgroup = NULL;
Vladimir Davydovc4159a72016-08-08 23:03:12 +03003035
3036 /* slab pages do not have PageKmemcg flag set */
3037 if (PageKmemcg(page))
3038 __ClearPageKmemcg(page);
3039
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08003040 css_put_many(&memcg->css, nr_pages);
Vladimir Davydov60d3fd32015-02-12 14:59:10 -08003041}
Kirill Tkhai84c07d12018-08-17 15:47:25 -07003042#endif /* CONFIG_MEMCG_KMEM */
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003043
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003044#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3045
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003046/*
3047 * Because tail pages are not marked as "used", set it. We're under
Andrey Ryabininf4b7e272019-03-05 15:49:39 -08003048 * pgdat->lru_lock and migration entries setup in all page mappings.
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003049 */
KAMEZAWA Hiroyukie94c8a92012-01-12 17:18:20 -08003050void mem_cgroup_split_huge_fixup(struct page *head)
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003051{
KAMEZAWA Hiroyukie94c8a92012-01-12 17:18:20 -08003052 int i;
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003053
KAMEZAWA Hiroyuki3d37c4a2011-01-25 15:07:28 -08003054 if (mem_cgroup_disabled())
3055 return;
David Rientjesb070e652013-05-07 16:18:09 -07003056
Johannes Weiner29833312014-12-10 15:44:02 -08003057 for (i = 1; i < HPAGE_PMD_NR; i++)
Johannes Weiner1306a852014-12-10 15:44:52 -08003058 head[i].mem_cgroup = head->mem_cgroup;
Michal Hockob9982f82014-12-10 15:43:51 -08003059
Johannes Weinerc9019e92018-01-31 16:16:37 -08003060 __mod_memcg_state(head->mem_cgroup, MEMCG_RSS_HUGE, -HPAGE_PMD_NR);
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003061}
Hugh Dickins12d27102012-01-12 17:19:52 -08003062#endif /* CONFIG_TRANSPARENT_HUGEPAGE */
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003063
Andrew Mortonc255a452012-07-31 16:43:02 -07003064#ifdef CONFIG_MEMCG_SWAP
Daisuke Nishimura02491442010-03-10 15:22:17 -08003065/**
3066 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3067 * @entry: swap entry to be moved
3068 * @from: mem_cgroup which the entry is moved from
3069 * @to: mem_cgroup which the entry is moved to
3070 *
3071 * It succeeds only when the swap_cgroup's record for this entry is the same
3072 * as the mem_cgroup's id of @from.
3073 *
3074 * Returns 0 on success, -EINVAL on failure.
3075 *
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003076 * The caller must have charged to @to, IOW, called page_counter_charge() about
Daisuke Nishimura02491442010-03-10 15:22:17 -08003077 * both res and memsw, and called css_get().
3078 */
3079static int mem_cgroup_move_swap_account(swp_entry_t entry,
Hugh Dickinse91cbb42012-05-29 15:06:51 -07003080 struct mem_cgroup *from, struct mem_cgroup *to)
Daisuke Nishimura02491442010-03-10 15:22:17 -08003081{
3082 unsigned short old_id, new_id;
3083
Li Zefan34c00c32013-09-23 16:56:01 +08003084 old_id = mem_cgroup_id(from);
3085 new_id = mem_cgroup_id(to);
Daisuke Nishimura02491442010-03-10 15:22:17 -08003086
3087 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
Johannes Weinerc9019e92018-01-31 16:16:37 -08003088 mod_memcg_state(from, MEMCG_SWAP, -1);
3089 mod_memcg_state(to, MEMCG_SWAP, 1);
Daisuke Nishimura02491442010-03-10 15:22:17 -08003090 return 0;
3091 }
3092 return -EINVAL;
3093}
3094#else
3095static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
Hugh Dickinse91cbb42012-05-29 15:06:51 -07003096 struct mem_cgroup *from, struct mem_cgroup *to)
Daisuke Nishimura02491442010-03-10 15:22:17 -08003097{
3098 return -EINVAL;
3099}
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08003100#endif
3101
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003102static DEFINE_MUTEX(memcg_max_mutex);
Daisuke Nishimuraf212ad72011-03-23 16:42:25 -07003103
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003104static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3105 unsigned long max, bool memsw)
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003106{
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003107 bool enlarge = false;
Shakeel Buttbb4a7ea2018-06-07 17:07:27 -07003108 bool drained = false;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003109 int ret;
Yu Zhaoc054a782018-01-31 16:20:02 -08003110 bool limits_invariant;
3111 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
KAMEZAWA Hiroyuki81d39c22009-04-02 16:57:36 -07003112
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003113 do {
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003114 if (signal_pending(current)) {
3115 ret = -EINTR;
3116 break;
3117 }
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003118
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003119 mutex_lock(&memcg_max_mutex);
Yu Zhaoc054a782018-01-31 16:20:02 -08003120 /*
3121 * Make sure that the new limit (memsw or memory limit) doesn't
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003122 * break our basic invariant rule memory.max <= memsw.max.
Yu Zhaoc054a782018-01-31 16:20:02 -08003123 */
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003124 limits_invariant = memsw ? max >= memcg->memory.max :
3125 max <= memcg->memsw.max;
Yu Zhaoc054a782018-01-31 16:20:02 -08003126 if (!limits_invariant) {
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003127 mutex_unlock(&memcg_max_mutex);
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08003128 ret = -EINVAL;
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003129 break;
3130 }
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003131 if (max > counter->max)
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003132 enlarge = true;
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003133 ret = page_counter_set_max(counter, max);
3134 mutex_unlock(&memcg_max_mutex);
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08003135
3136 if (!ret)
3137 break;
3138
Shakeel Buttbb4a7ea2018-06-07 17:07:27 -07003139 if (!drained) {
3140 drain_all_stock(memcg);
3141 drained = true;
3142 continue;
3143 }
3144
Andrey Ryabinin1ab5c052018-01-31 16:20:37 -08003145 if (!try_to_free_mem_cgroup_pages(memcg, 1,
3146 GFP_KERNEL, !memsw)) {
3147 ret = -EBUSY;
3148 break;
3149 }
3150 } while (true);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003151
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07003152 if (!ret && enlarge)
3153 memcg_oom_recover(memcg);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003154
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003155 return ret;
3156}
3157
Mel Gormanef8f2322016-07-28 15:46:05 -07003158unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
Andrew Morton0608f432013-09-24 15:27:41 -07003159 gfp_t gfp_mask,
3160 unsigned long *total_scanned)
3161{
3162 unsigned long nr_reclaimed = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07003163 struct mem_cgroup_per_node *mz, *next_mz = NULL;
Andrew Morton0608f432013-09-24 15:27:41 -07003164 unsigned long reclaimed;
3165 int loop = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07003166 struct mem_cgroup_tree_per_node *mctz;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003167 unsigned long excess;
Andrew Morton0608f432013-09-24 15:27:41 -07003168 unsigned long nr_scanned;
3169
3170 if (order > 0)
3171 return 0;
3172
Mel Gormanef8f2322016-07-28 15:46:05 -07003173 mctz = soft_limit_tree_node(pgdat->node_id);
Michal Hockod6507ff2016-08-02 14:02:37 -07003174
3175 /*
3176 * Do not even bother to check the largest node if the root
3177 * is empty. Do it lockless to prevent lock bouncing. Races
3178 * are acceptable as soft limit is best effort anyway.
3179 */
Laurent Dufourbfc72282017-03-09 16:17:06 -08003180 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
Michal Hockod6507ff2016-08-02 14:02:37 -07003181 return 0;
3182
Andrew Morton0608f432013-09-24 15:27:41 -07003183 /*
3184 * This loop can run a while, specially if mem_cgroup's continuously
3185 * keep exceeding their soft limit and putting the system under
3186 * pressure
3187 */
3188 do {
3189 if (next_mz)
3190 mz = next_mz;
3191 else
3192 mz = mem_cgroup_largest_soft_limit_node(mctz);
3193 if (!mz)
3194 break;
3195
3196 nr_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07003197 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07003198 gfp_mask, &nr_scanned);
3199 nr_reclaimed += reclaimed;
3200 *total_scanned += nr_scanned;
Johannes Weiner0a31bc92014-08-08 14:19:22 -07003201 spin_lock_irq(&mctz->lock);
Vladimir Davydovbc2f2e72014-12-10 15:43:40 -08003202 __mem_cgroup_remove_exceeded(mz, mctz);
Andrew Morton0608f432013-09-24 15:27:41 -07003203
3204 /*
3205 * If we failed to reclaim anything from this memory cgroup
3206 * it is time to move on to the next cgroup
3207 */
3208 next_mz = NULL;
Vladimir Davydovbc2f2e72014-12-10 15:43:40 -08003209 if (!reclaimed)
3210 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3211
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003212 excess = soft_limit_excess(mz->memcg);
Andrew Morton0608f432013-09-24 15:27:41 -07003213 /*
3214 * One school of thought says that we should not add
3215 * back the node to the tree if reclaim returns 0.
3216 * But our reclaim could return 0, simply because due
3217 * to priority we are exposing a smaller subset of
3218 * memory to reclaim from. Consider this as a longer
3219 * term TODO.
3220 */
3221 /* If excess == 0, no tree ops */
Johannes Weinercf2c8122014-06-06 14:38:21 -07003222 __mem_cgroup_insert_exceeded(mz, mctz, excess);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07003223 spin_unlock_irq(&mctz->lock);
Andrew Morton0608f432013-09-24 15:27:41 -07003224 css_put(&mz->memcg->css);
3225 loop++;
3226 /*
3227 * Could not reclaim anything and there are no more
3228 * mem cgroups to try or we seem to be looping without
3229 * reclaiming anything.
3230 */
3231 if (!nr_reclaimed &&
3232 (next_mz == NULL ||
3233 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3234 break;
3235 } while (!nr_reclaimed);
3236 if (next_mz)
3237 css_put(&next_mz->memcg->css);
3238 return nr_reclaimed;
3239}
3240
Tejun Heoea280e72014-05-16 13:22:48 -04003241/*
3242 * Test whether @memcg has children, dead or alive. Note that this
3243 * function doesn't care whether @memcg has use_hierarchy enabled and
3244 * returns %true if there are child csses according to the cgroup
3245 * hierarchy. Testing use_hierarchy is the caller's responsiblity.
3246 */
Glauber Costab5f99b52013-02-22 16:34:53 -08003247static inline bool memcg_has_children(struct mem_cgroup *memcg)
3248{
Tejun Heoea280e72014-05-16 13:22:48 -04003249 bool ret;
3250
Tejun Heoea280e72014-05-16 13:22:48 -04003251 rcu_read_lock();
3252 ret = css_next_child(NULL, &memcg->css);
3253 rcu_read_unlock();
3254 return ret;
Glauber Costab5f99b52013-02-22 16:34:53 -08003255}
3256
3257/*
Greg Thelen51038172016-05-20 16:58:18 -07003258 * Reclaims as many pages from the given memcg as possible.
Michal Hockoc26251f2012-10-26 13:37:28 +02003259 *
3260 * Caller is responsible for holding css reference for memcg.
3261 */
3262static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3263{
3264 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
Michal Hockoc26251f2012-10-26 13:37:28 +02003265
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08003266 /* we call try-to-free pages for make this cgroup empty */
3267 lru_add_drain_all();
Junaid Shahidd12c60f2018-06-07 17:07:31 -07003268
3269 drain_all_stock(memcg);
3270
KAMEZAWA Hiroyukif817ed42009-01-07 18:07:53 -08003271 /* try to free all pages in this cgroup */
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003272 while (nr_retries && page_counter_read(&memcg->memory)) {
KAMEZAWA Hiroyukif817ed42009-01-07 18:07:53 -08003273 int progress;
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08003274
Michal Hockoc26251f2012-10-26 13:37:28 +02003275 if (signal_pending(current))
3276 return -EINTR;
3277
Johannes Weinerb70a2a22014-10-09 15:28:56 -07003278 progress = try_to_free_mem_cgroup_pages(memcg, 1,
3279 GFP_KERNEL, true);
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08003280 if (!progress) {
KAMEZAWA Hiroyukif817ed42009-01-07 18:07:53 -08003281 nr_retries--;
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08003282 /* maybe some writeback is necessary */
Jens Axboe8aa7e842009-07-09 14:52:32 +02003283 congestion_wait(BLK_RW_ASYNC, HZ/10);
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08003284 }
KAMEZAWA Hiroyukif817ed42009-01-07 18:07:53 -08003285
3286 }
Michal Hockoab5196c2012-10-26 13:37:32 +02003287
3288 return 0;
KAMEZAWA Hiroyukicc847582008-02-07 00:14:16 -08003289}
3290
Tejun Heo6770c642014-05-13 12:16:21 -04003291static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3292 char *buf, size_t nbytes,
3293 loff_t off)
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08003294{
Tejun Heo6770c642014-05-13 12:16:21 -04003295 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
Michal Hockoc26251f2012-10-26 13:37:28 +02003296
Michal Hockod8423012012-10-26 13:37:29 +02003297 if (mem_cgroup_is_root(memcg))
3298 return -EINVAL;
Tejun Heo6770c642014-05-13 12:16:21 -04003299 return mem_cgroup_force_empty(memcg) ?: nbytes;
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08003300}
3301
Tejun Heo182446d2013-08-08 20:11:24 -04003302static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3303 struct cftype *cft)
Balbir Singh18f59ea2009-01-07 18:08:07 -08003304{
Tejun Heo182446d2013-08-08 20:11:24 -04003305 return mem_cgroup_from_css(css)->use_hierarchy;
Balbir Singh18f59ea2009-01-07 18:08:07 -08003306}
3307
Tejun Heo182446d2013-08-08 20:11:24 -04003308static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3309 struct cftype *cft, u64 val)
Balbir Singh18f59ea2009-01-07 18:08:07 -08003310{
3311 int retval = 0;
Tejun Heo182446d2013-08-08 20:11:24 -04003312 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Tejun Heo5c9d5352014-05-16 13:22:48 -04003313 struct mem_cgroup *parent_memcg = mem_cgroup_from_css(memcg->css.parent);
Balbir Singh18f59ea2009-01-07 18:08:07 -08003314
Glauber Costa567fb432012-07-31 16:43:07 -07003315 if (memcg->use_hierarchy == val)
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08003316 return 0;
Glauber Costa567fb432012-07-31 16:43:07 -07003317
Balbir Singh18f59ea2009-01-07 18:08:07 -08003318 /*
André Goddard Rosaaf901ca2009-11-14 13:09:05 -02003319 * If parent's use_hierarchy is set, we can't make any modifications
Balbir Singh18f59ea2009-01-07 18:08:07 -08003320 * in the child subtrees. If it is unset, then the change can
3321 * occur, provided the current cgroup has no children.
3322 *
3323 * For the root cgroup, parent_mem is NULL, we allow value to be
3324 * set if there are no children.
3325 */
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07003326 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
Balbir Singh18f59ea2009-01-07 18:08:07 -08003327 (val == 1 || val == 0)) {
Tejun Heoea280e72014-05-16 13:22:48 -04003328 if (!memcg_has_children(memcg))
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07003329 memcg->use_hierarchy = val;
Balbir Singh18f59ea2009-01-07 18:08:07 -08003330 else
3331 retval = -EBUSY;
3332 } else
3333 retval = -EINVAL;
Glauber Costa567fb432012-07-31 16:43:07 -07003334
Balbir Singh18f59ea2009-01-07 18:08:07 -08003335 return retval;
3336}
3337
Andrew Morton6f646152015-11-06 16:28:58 -08003338static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
Johannes Weinerce00a962014-09-05 08:43:57 -04003339{
Johannes Weiner42a30032019-05-14 15:47:12 -07003340 unsigned long val;
Johannes Weinerce00a962014-09-05 08:43:57 -04003341
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003342 if (mem_cgroup_is_root(memcg)) {
Johannes Weiner42a30032019-05-14 15:47:12 -07003343 val = memcg_page_state(memcg, MEMCG_CACHE) +
3344 memcg_page_state(memcg, MEMCG_RSS);
3345 if (swap)
3346 val += memcg_page_state(memcg, MEMCG_SWAP);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003347 } else {
Johannes Weinerce00a962014-09-05 08:43:57 -04003348 if (!swap)
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003349 val = page_counter_read(&memcg->memory);
Johannes Weinerce00a962014-09-05 08:43:57 -04003350 else
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003351 val = page_counter_read(&memcg->memsw);
Johannes Weinerce00a962014-09-05 08:43:57 -04003352 }
Michal Hockoc12176d2015-11-05 18:50:29 -08003353 return val;
Johannes Weinerce00a962014-09-05 08:43:57 -04003354}
3355
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003356enum {
3357 RES_USAGE,
3358 RES_LIMIT,
3359 RES_MAX_USAGE,
3360 RES_FAILCNT,
3361 RES_SOFT_LIMIT,
3362};
Johannes Weinerce00a962014-09-05 08:43:57 -04003363
Tejun Heo791badb2013-12-05 12:28:02 -05003364static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
Johannes Weiner05b84302014-08-06 16:05:59 -07003365 struct cftype *cft)
Balbir Singh8cdea7c2008-02-07 00:13:50 -08003366{
Tejun Heo182446d2013-08-08 20:11:24 -04003367 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003368 struct page_counter *counter;
Tejun Heoaf36f902012-04-01 12:09:55 -07003369
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003370 switch (MEMFILE_TYPE(cft->private)) {
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08003371 case _MEM:
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003372 counter = &memcg->memory;
Glauber Costa510fc4e2012-12-18 14:21:47 -08003373 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003374 case _MEMSWAP:
3375 counter = &memcg->memsw;
3376 break;
3377 case _KMEM:
3378 counter = &memcg->kmem;
3379 break;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003380 case _TCP:
Johannes Weiner0db15292016-01-20 15:02:50 -08003381 counter = &memcg->tcpmem;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003382 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003383 default:
3384 BUG();
3385 }
3386
3387 switch (MEMFILE_ATTR(cft->private)) {
3388 case RES_USAGE:
3389 if (counter == &memcg->memory)
Michal Hockoc12176d2015-11-05 18:50:29 -08003390 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003391 if (counter == &memcg->memsw)
Michal Hockoc12176d2015-11-05 18:50:29 -08003392 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003393 return (u64)page_counter_read(counter) * PAGE_SIZE;
3394 case RES_LIMIT:
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003395 return (u64)counter->max * PAGE_SIZE;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003396 case RES_MAX_USAGE:
3397 return (u64)counter->watermark * PAGE_SIZE;
3398 case RES_FAILCNT:
3399 return counter->failcnt;
3400 case RES_SOFT_LIMIT:
3401 return (u64)memcg->soft_limit * PAGE_SIZE;
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08003402 default:
3403 BUG();
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08003404 }
Balbir Singh8cdea7c2008-02-07 00:13:50 -08003405}
Glauber Costa510fc4e2012-12-18 14:21:47 -08003406
Roman Gushchinbee07b32019-08-30 16:04:32 -07003407static void memcg_flush_percpu_vmstats(struct mem_cgroup *memcg, bool slab_only)
Roman Gushchinc350a992019-08-24 17:54:47 -07003408{
3409 unsigned long stat[MEMCG_NR_STAT];
3410 struct mem_cgroup *mi;
3411 int node, cpu, i;
Roman Gushchinbee07b32019-08-30 16:04:32 -07003412 int min_idx, max_idx;
Roman Gushchinc350a992019-08-24 17:54:47 -07003413
Roman Gushchinbee07b32019-08-30 16:04:32 -07003414 if (slab_only) {
3415 min_idx = NR_SLAB_RECLAIMABLE;
3416 max_idx = NR_SLAB_UNRECLAIMABLE;
3417 } else {
3418 min_idx = 0;
3419 max_idx = MEMCG_NR_STAT;
3420 }
3421
3422 for (i = min_idx; i < max_idx; i++)
Roman Gushchinc350a992019-08-24 17:54:47 -07003423 stat[i] = 0;
3424
3425 for_each_online_cpu(cpu)
Roman Gushchinbee07b32019-08-30 16:04:32 -07003426 for (i = min_idx; i < max_idx; i++)
Shakeel Butt6c1c2802019-08-30 16:04:53 -07003427 stat[i] += per_cpu(memcg->vmstats_percpu->stat[i], cpu);
Roman Gushchinc350a992019-08-24 17:54:47 -07003428
3429 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
Roman Gushchinbee07b32019-08-30 16:04:32 -07003430 for (i = min_idx; i < max_idx; i++)
Roman Gushchinc350a992019-08-24 17:54:47 -07003431 atomic_long_add(stat[i], &mi->vmstats[i]);
3432
Roman Gushchinbee07b32019-08-30 16:04:32 -07003433 if (!slab_only)
3434 max_idx = NR_VM_NODE_STAT_ITEMS;
3435
Roman Gushchinc350a992019-08-24 17:54:47 -07003436 for_each_node(node) {
3437 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
3438 struct mem_cgroup_per_node *pi;
3439
Roman Gushchinbee07b32019-08-30 16:04:32 -07003440 for (i = min_idx; i < max_idx; i++)
Roman Gushchinc350a992019-08-24 17:54:47 -07003441 stat[i] = 0;
3442
3443 for_each_online_cpu(cpu)
Roman Gushchinbee07b32019-08-30 16:04:32 -07003444 for (i = min_idx; i < max_idx; i++)
Shakeel Butt6c1c2802019-08-30 16:04:53 -07003445 stat[i] += per_cpu(
3446 pn->lruvec_stat_cpu->count[i], cpu);
Roman Gushchinc350a992019-08-24 17:54:47 -07003447
3448 for (pi = pn; pi; pi = parent_nodeinfo(pi, node))
Roman Gushchinbee07b32019-08-30 16:04:32 -07003449 for (i = min_idx; i < max_idx; i++)
Roman Gushchinc350a992019-08-24 17:54:47 -07003450 atomic_long_add(stat[i], &pi->lruvec_stat[i]);
3451 }
3452}
3453
Roman Gushchinbb65f892019-08-24 17:54:50 -07003454static void memcg_flush_percpu_vmevents(struct mem_cgroup *memcg)
3455{
3456 unsigned long events[NR_VM_EVENT_ITEMS];
3457 struct mem_cgroup *mi;
3458 int cpu, i;
3459
3460 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3461 events[i] = 0;
3462
3463 for_each_online_cpu(cpu)
3464 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
Shakeel Butt6c1c2802019-08-30 16:04:53 -07003465 events[i] += per_cpu(memcg->vmstats_percpu->events[i],
3466 cpu);
Roman Gushchinbb65f892019-08-24 17:54:50 -07003467
3468 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
3469 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3470 atomic_long_add(events[i], &mi->vmevents[i]);
3471}
3472
Kirill Tkhai84c07d12018-08-17 15:47:25 -07003473#ifdef CONFIG_MEMCG_KMEM
Johannes Weiner567e9ab2016-01-20 15:02:24 -08003474static int memcg_online_kmem(struct mem_cgroup *memcg)
Vladimir Davydovd6441632014-01-23 15:53:09 -08003475{
Vladimir Davydovd6441632014-01-23 15:53:09 -08003476 int memcg_id;
3477
Vladimir Davydovb313aee2016-03-17 14:18:27 -07003478 if (cgroup_memory_nokmem)
3479 return 0;
3480
Vladimir Davydov2a4db7e2015-02-12 14:59:32 -08003481 BUG_ON(memcg->kmemcg_id >= 0);
Johannes Weiner567e9ab2016-01-20 15:02:24 -08003482 BUG_ON(memcg->kmem_state);
Vladimir Davydovd6441632014-01-23 15:53:09 -08003483
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07003484 memcg_id = memcg_alloc_cache_id();
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08003485 if (memcg_id < 0)
3486 return memcg_id;
Vladimir Davydovd6441632014-01-23 15:53:09 -08003487
Johannes Weineref129472016-01-14 15:21:34 -08003488 static_branch_inc(&memcg_kmem_enabled_key);
Vladimir Davydovd6441632014-01-23 15:53:09 -08003489 /*
Johannes Weiner567e9ab2016-01-20 15:02:24 -08003490 * A memory cgroup is considered kmem-online as soon as it gets
Vladimir Davydov900a38f2014-12-12 16:55:10 -08003491 * kmemcg_id. Setting the id after enabling static branching will
Vladimir Davydovd6441632014-01-23 15:53:09 -08003492 * guarantee no one starts accounting before all call sites are
3493 * patched.
3494 */
Vladimir Davydov900a38f2014-12-12 16:55:10 -08003495 memcg->kmemcg_id = memcg_id;
Johannes Weiner567e9ab2016-01-20 15:02:24 -08003496 memcg->kmem_state = KMEM_ONLINE;
Tejun Heobc2791f2017-02-22 15:41:21 -08003497 INIT_LIST_HEAD(&memcg->kmem_caches);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08003498
3499 return 0;
Vladimir Davydovd6441632014-01-23 15:53:09 -08003500}
3501
Johannes Weiner8e0a8912016-01-20 15:02:26 -08003502static void memcg_offline_kmem(struct mem_cgroup *memcg)
3503{
3504 struct cgroup_subsys_state *css;
3505 struct mem_cgroup *parent, *child;
3506 int kmemcg_id;
3507
3508 if (memcg->kmem_state != KMEM_ONLINE)
3509 return;
3510 /*
3511 * Clear the online state before clearing memcg_caches array
3512 * entries. The slab_mutex in memcg_deactivate_kmem_caches()
3513 * guarantees that no cache will be created for this cgroup
3514 * after we are done (see memcg_create_kmem_cache()).
3515 */
3516 memcg->kmem_state = KMEM_ALLOCATED;
3517
Johannes Weiner8e0a8912016-01-20 15:02:26 -08003518 parent = parent_mem_cgroup(memcg);
3519 if (!parent)
3520 parent = root_mem_cgroup;
3521
Roman Gushchinbee07b32019-08-30 16:04:32 -07003522 /*
3523 * Deactivate and reparent kmem_caches. Then flush percpu
3524 * slab statistics to have precise values at the parent and
3525 * all ancestor levels. It's required to keep slab stats
3526 * accurate after the reparenting of kmem_caches.
3527 */
Roman Gushchinfb2f2b02019-07-11 20:56:34 -07003528 memcg_deactivate_kmem_caches(memcg, parent);
Roman Gushchinbee07b32019-08-30 16:04:32 -07003529 memcg_flush_percpu_vmstats(memcg, true);
Roman Gushchinfb2f2b02019-07-11 20:56:34 -07003530
3531 kmemcg_id = memcg->kmemcg_id;
3532 BUG_ON(kmemcg_id < 0);
3533
Johannes Weiner8e0a8912016-01-20 15:02:26 -08003534 /*
3535 * Change kmemcg_id of this cgroup and all its descendants to the
3536 * parent's id, and then move all entries from this cgroup's list_lrus
3537 * to ones of the parent. After we have finished, all list_lrus
3538 * corresponding to this cgroup are guaranteed to remain empty. The
3539 * ordering is imposed by list_lru_node->lock taken by
3540 * memcg_drain_all_list_lrus().
3541 */
Tejun Heo3a06bb72016-06-03 14:55:44 -07003542 rcu_read_lock(); /* can be called from css_free w/o cgroup_mutex */
Johannes Weiner8e0a8912016-01-20 15:02:26 -08003543 css_for_each_descendant_pre(css, &memcg->css) {
3544 child = mem_cgroup_from_css(css);
3545 BUG_ON(child->kmemcg_id != kmemcg_id);
3546 child->kmemcg_id = parent->kmemcg_id;
3547 if (!memcg->use_hierarchy)
3548 break;
3549 }
Tejun Heo3a06bb72016-06-03 14:55:44 -07003550 rcu_read_unlock();
3551
Kirill Tkhai9bec5c32018-08-17 15:47:58 -07003552 memcg_drain_all_list_lrus(kmemcg_id, parent);
Johannes Weiner8e0a8912016-01-20 15:02:26 -08003553
3554 memcg_free_cache_id(kmemcg_id);
3555}
3556
3557static void memcg_free_kmem(struct mem_cgroup *memcg)
3558{
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08003559 /* css_alloc() failed, offlining didn't happen */
3560 if (unlikely(memcg->kmem_state == KMEM_ONLINE))
3561 memcg_offline_kmem(memcg);
3562
Johannes Weiner8e0a8912016-01-20 15:02:26 -08003563 if (memcg->kmem_state == KMEM_ALLOCATED) {
Roman Gushchinf0a3a242019-07-11 20:56:27 -07003564 WARN_ON(!list_empty(&memcg->kmem_caches));
Johannes Weiner8e0a8912016-01-20 15:02:26 -08003565 static_branch_dec(&memcg_kmem_enabled_key);
Johannes Weiner8e0a8912016-01-20 15:02:26 -08003566 }
Johannes Weiner8e0a8912016-01-20 15:02:26 -08003567}
Vladimir Davydovd6441632014-01-23 15:53:09 -08003568#else
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08003569static int memcg_online_kmem(struct mem_cgroup *memcg)
Johannes Weiner127424c2016-01-20 15:02:32 -08003570{
3571 return 0;
3572}
3573static void memcg_offline_kmem(struct mem_cgroup *memcg)
3574{
3575}
3576static void memcg_free_kmem(struct mem_cgroup *memcg)
3577{
3578}
Kirill Tkhai84c07d12018-08-17 15:47:25 -07003579#endif /* CONFIG_MEMCG_KMEM */
Johannes Weiner127424c2016-01-20 15:02:32 -08003580
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003581static int memcg_update_kmem_max(struct mem_cgroup *memcg,
3582 unsigned long max)
Johannes Weiner127424c2016-01-20 15:02:32 -08003583{
Vladimir Davydovb313aee2016-03-17 14:18:27 -07003584 int ret;
Johannes Weiner127424c2016-01-20 15:02:32 -08003585
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003586 mutex_lock(&memcg_max_mutex);
3587 ret = page_counter_set_max(&memcg->kmem, max);
3588 mutex_unlock(&memcg_max_mutex);
Johannes Weiner127424c2016-01-20 15:02:32 -08003589 return ret;
3590}
Glauber Costa510fc4e2012-12-18 14:21:47 -08003591
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003592static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003593{
3594 int ret;
3595
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003596 mutex_lock(&memcg_max_mutex);
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003597
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003598 ret = page_counter_set_max(&memcg->tcpmem, max);
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003599 if (ret)
3600 goto out;
3601
Johannes Weiner0db15292016-01-20 15:02:50 -08003602 if (!memcg->tcpmem_active) {
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003603 /*
3604 * The active flag needs to be written after the static_key
3605 * update. This is what guarantees that the socket activation
Johannes Weiner2d758072016-10-07 17:00:58 -07003606 * function is the last one to run. See mem_cgroup_sk_alloc()
3607 * for details, and note that we don't mark any socket as
3608 * belonging to this memcg until that flag is up.
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003609 *
3610 * We need to do this, because static_keys will span multiple
3611 * sites, but we can't control their order. If we mark a socket
3612 * as accounted, but the accounting functions are not patched in
3613 * yet, we'll lose accounting.
3614 *
Johannes Weiner2d758072016-10-07 17:00:58 -07003615 * We never race with the readers in mem_cgroup_sk_alloc(),
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003616 * because when this value change, the code to process it is not
3617 * patched in yet.
3618 */
3619 static_branch_inc(&memcg_sockets_enabled_key);
Johannes Weiner0db15292016-01-20 15:02:50 -08003620 memcg->tcpmem_active = true;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003621 }
3622out:
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003623 mutex_unlock(&memcg_max_mutex);
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003624 return ret;
3625}
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003626
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003627/*
3628 * The user of this function is...
3629 * RES_LIMIT.
3630 */
Tejun Heo451af502014-05-13 12:16:21 -04003631static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3632 char *buf, size_t nbytes, loff_t off)
Balbir Singh8cdea7c2008-02-07 00:13:50 -08003633{
Tejun Heo451af502014-05-13 12:16:21 -04003634 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003635 unsigned long nr_pages;
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003636 int ret;
3637
Tejun Heo451af502014-05-13 12:16:21 -04003638 buf = strstrip(buf);
Johannes Weiner650c5e52015-02-11 15:26:03 -08003639 ret = page_counter_memparse(buf, "-1", &nr_pages);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003640 if (ret)
3641 return ret;
Tejun Heoaf36f902012-04-01 12:09:55 -07003642
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003643 switch (MEMFILE_ATTR(of_cft(of)->private)) {
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003644 case RES_LIMIT:
Balbir Singh4b3bde42009-09-23 15:56:32 -07003645 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3646 ret = -EINVAL;
3647 break;
3648 }
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003649 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3650 case _MEM:
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003651 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08003652 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003653 case _MEMSWAP:
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003654 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003655 break;
3656 case _KMEM:
Michal Hocko01581152019-09-23 15:37:22 -07003657 pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
3658 "Please report your usecase to linux-mm@kvack.org if you "
3659 "depend on this functionality.\n");
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003660 ret = memcg_update_kmem_max(memcg, nr_pages);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003661 break;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003662 case _TCP:
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003663 ret = memcg_update_tcp_max(memcg, nr_pages);
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003664 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003665 }
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003666 break;
Balbir Singh296c81d2009-09-23 15:56:36 -07003667 case RES_SOFT_LIMIT:
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003668 memcg->soft_limit = nr_pages;
3669 ret = 0;
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003670 break;
3671 }
Tejun Heo451af502014-05-13 12:16:21 -04003672 return ret ?: nbytes;
Balbir Singh8cdea7c2008-02-07 00:13:50 -08003673}
3674
Tejun Heo6770c642014-05-13 12:16:21 -04003675static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3676 size_t nbytes, loff_t off)
Pavel Emelyanovc84872e2008-04-29 01:00:17 -07003677{
Tejun Heo6770c642014-05-13 12:16:21 -04003678 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003679 struct page_counter *counter;
Pavel Emelyanovc84872e2008-04-29 01:00:17 -07003680
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003681 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3682 case _MEM:
3683 counter = &memcg->memory;
3684 break;
3685 case _MEMSWAP:
3686 counter = &memcg->memsw;
3687 break;
3688 case _KMEM:
3689 counter = &memcg->kmem;
3690 break;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003691 case _TCP:
Johannes Weiner0db15292016-01-20 15:02:50 -08003692 counter = &memcg->tcpmem;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003693 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003694 default:
3695 BUG();
3696 }
Tejun Heoaf36f902012-04-01 12:09:55 -07003697
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003698 switch (MEMFILE_ATTR(of_cft(of)->private)) {
Pavel Emelyanov29f2a4d2008-04-29 01:00:21 -07003699 case RES_MAX_USAGE:
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003700 page_counter_reset_watermark(counter);
Pavel Emelyanov29f2a4d2008-04-29 01:00:21 -07003701 break;
3702 case RES_FAILCNT:
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003703 counter->failcnt = 0;
Pavel Emelyanov29f2a4d2008-04-29 01:00:21 -07003704 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003705 default:
3706 BUG();
Pavel Emelyanov29f2a4d2008-04-29 01:00:21 -07003707 }
Balbir Singhf64c3f52009-09-23 15:56:37 -07003708
Tejun Heo6770c642014-05-13 12:16:21 -04003709 return nbytes;
Pavel Emelyanovc84872e2008-04-29 01:00:17 -07003710}
3711
Tejun Heo182446d2013-08-08 20:11:24 -04003712static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08003713 struct cftype *cft)
3714{
Tejun Heo182446d2013-08-08 20:11:24 -04003715 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08003716}
3717
Daisuke Nishimura02491442010-03-10 15:22:17 -08003718#ifdef CONFIG_MMU
Tejun Heo182446d2013-08-08 20:11:24 -04003719static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08003720 struct cftype *cft, u64 val)
3721{
Tejun Heo182446d2013-08-08 20:11:24 -04003722 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08003723
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08003724 if (val & ~MOVE_MASK)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08003725 return -EINVAL;
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08003726
Glauber Costaee5e8472013-02-22 16:34:50 -08003727 /*
3728 * No kind of locking is needed in here, because ->can_attach() will
3729 * check this value once in the beginning of the process, and then carry
3730 * on with stale data. This means that changes to this value will only
3731 * affect task migrations starting after the change.
3732 */
3733 memcg->move_charge_at_immigrate = val;
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08003734 return 0;
3735}
Daisuke Nishimura02491442010-03-10 15:22:17 -08003736#else
Tejun Heo182446d2013-08-08 20:11:24 -04003737static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
Daisuke Nishimura02491442010-03-10 15:22:17 -08003738 struct cftype *cft, u64 val)
3739{
3740 return -ENOSYS;
3741}
3742#endif
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08003743
Ying Han406eb0c2011-05-26 16:25:37 -07003744#ifdef CONFIG_NUMA
Johannes Weiner113b7df2019-05-13 17:18:11 -07003745
3746#define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3747#define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3748#define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3749
3750static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
3751 int nid, unsigned int lru_mask)
3752{
3753 struct lruvec *lruvec = mem_cgroup_lruvec(NODE_DATA(nid), memcg);
3754 unsigned long nr = 0;
3755 enum lru_list lru;
3756
3757 VM_BUG_ON((unsigned)nid >= nr_node_ids);
3758
3759 for_each_lru(lru) {
3760 if (!(BIT(lru) & lru_mask))
3761 continue;
Johannes Weiner205b20c2019-05-14 15:47:06 -07003762 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
Johannes Weiner113b7df2019-05-13 17:18:11 -07003763 }
3764 return nr;
3765}
3766
3767static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
3768 unsigned int lru_mask)
3769{
3770 unsigned long nr = 0;
3771 enum lru_list lru;
3772
3773 for_each_lru(lru) {
3774 if (!(BIT(lru) & lru_mask))
3775 continue;
Johannes Weiner205b20c2019-05-14 15:47:06 -07003776 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
Johannes Weiner113b7df2019-05-13 17:18:11 -07003777 }
3778 return nr;
3779}
3780
Tejun Heo2da8ca82013-12-05 12:28:04 -05003781static int memcg_numa_stat_show(struct seq_file *m, void *v)
Ying Han406eb0c2011-05-26 16:25:37 -07003782{
Greg Thelen25485de2013-11-12 15:07:40 -08003783 struct numa_stat {
3784 const char *name;
3785 unsigned int lru_mask;
3786 };
3787
3788 static const struct numa_stat stats[] = {
3789 { "total", LRU_ALL },
3790 { "file", LRU_ALL_FILE },
3791 { "anon", LRU_ALL_ANON },
3792 { "unevictable", BIT(LRU_UNEVICTABLE) },
3793 };
3794 const struct numa_stat *stat;
Ying Han406eb0c2011-05-26 16:25:37 -07003795 int nid;
Greg Thelen25485de2013-11-12 15:07:40 -08003796 unsigned long nr;
Chris Downaa9694b2019-03-05 15:45:52 -08003797 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
Ying Han406eb0c2011-05-26 16:25:37 -07003798
Greg Thelen25485de2013-11-12 15:07:40 -08003799 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3800 nr = mem_cgroup_nr_lru_pages(memcg, stat->lru_mask);
3801 seq_printf(m, "%s=%lu", stat->name, nr);
3802 for_each_node_state(nid, N_MEMORY) {
3803 nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
3804 stat->lru_mask);
3805 seq_printf(m, " N%d=%lu", nid, nr);
3806 }
3807 seq_putc(m, '\n');
Ying Han406eb0c2011-05-26 16:25:37 -07003808 }
Ying Han406eb0c2011-05-26 16:25:37 -07003809
Ying Han071aee12013-11-12 15:07:41 -08003810 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3811 struct mem_cgroup *iter;
Ying Han406eb0c2011-05-26 16:25:37 -07003812
Ying Han071aee12013-11-12 15:07:41 -08003813 nr = 0;
3814 for_each_mem_cgroup_tree(iter, memcg)
3815 nr += mem_cgroup_nr_lru_pages(iter, stat->lru_mask);
3816 seq_printf(m, "hierarchical_%s=%lu", stat->name, nr);
3817 for_each_node_state(nid, N_MEMORY) {
3818 nr = 0;
3819 for_each_mem_cgroup_tree(iter, memcg)
3820 nr += mem_cgroup_node_nr_lru_pages(
3821 iter, nid, stat->lru_mask);
3822 seq_printf(m, " N%d=%lu", nid, nr);
3823 }
3824 seq_putc(m, '\n');
Ying Han406eb0c2011-05-26 16:25:37 -07003825 }
Ying Han406eb0c2011-05-26 16:25:37 -07003826
Ying Han406eb0c2011-05-26 16:25:37 -07003827 return 0;
3828}
3829#endif /* CONFIG_NUMA */
3830
Johannes Weinerc8713d02019-07-11 20:55:59 -07003831static const unsigned int memcg1_stats[] = {
3832 MEMCG_CACHE,
3833 MEMCG_RSS,
3834 MEMCG_RSS_HUGE,
3835 NR_SHMEM,
3836 NR_FILE_MAPPED,
3837 NR_FILE_DIRTY,
3838 NR_WRITEBACK,
3839 MEMCG_SWAP,
3840};
3841
3842static const char *const memcg1_stat_names[] = {
3843 "cache",
3844 "rss",
3845 "rss_huge",
3846 "shmem",
3847 "mapped_file",
3848 "dirty",
3849 "writeback",
3850 "swap",
3851};
3852
Johannes Weinerdf0e53d2017-05-03 14:55:10 -07003853/* Universal VM events cgroup1 shows, original sort order */
Greg Thelen8dd53fd2018-06-07 17:07:23 -07003854static const unsigned int memcg1_events[] = {
Johannes Weinerdf0e53d2017-05-03 14:55:10 -07003855 PGPGIN,
3856 PGPGOUT,
3857 PGFAULT,
3858 PGMAJFAULT,
3859};
3860
3861static const char *const memcg1_event_names[] = {
3862 "pgpgin",
3863 "pgpgout",
3864 "pgfault",
3865 "pgmajfault",
3866};
3867
Tejun Heo2da8ca82013-12-05 12:28:04 -05003868static int memcg_stat_show(struct seq_file *m, void *v)
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -08003869{
Chris Downaa9694b2019-03-05 15:45:52 -08003870 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003871 unsigned long memory, memsw;
Johannes Weineraf7c4b02012-05-29 15:07:08 -07003872 struct mem_cgroup *mi;
3873 unsigned int i;
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -08003874
Johannes Weiner71cd3112017-05-03 14:55:13 -07003875 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
Rickard Strandqvist70bc0682014-12-12 16:56:41 -08003876 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
3877
Johannes Weiner71cd3112017-05-03 14:55:13 -07003878 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
3879 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
Daisuke Nishimura1dd3a272009-09-23 15:56:43 -07003880 continue;
Johannes Weiner71cd3112017-05-03 14:55:13 -07003881 seq_printf(m, "%s %lu\n", memcg1_stat_names[i],
Johannes Weiner205b20c2019-05-14 15:47:06 -07003882 memcg_page_state_local(memcg, memcg1_stats[i]) *
Johannes Weiner71cd3112017-05-03 14:55:13 -07003883 PAGE_SIZE);
Daisuke Nishimura1dd3a272009-09-23 15:56:43 -07003884 }
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08003885
Johannes Weinerdf0e53d2017-05-03 14:55:10 -07003886 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3887 seq_printf(m, "%s %lu\n", memcg1_event_names[i],
Johannes Weiner205b20c2019-05-14 15:47:06 -07003888 memcg_events_local(memcg, memcg1_events[i]));
Johannes Weineraf7c4b02012-05-29 15:07:08 -07003889
3890 for (i = 0; i < NR_LRU_LISTS; i++)
3891 seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
Johannes Weiner205b20c2019-05-14 15:47:06 -07003892 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
Johannes Weiner21d89d12019-05-13 17:18:08 -07003893 PAGE_SIZE);
Johannes Weineraf7c4b02012-05-29 15:07:08 -07003894
KAMEZAWA Hiroyuki14067bb2009-04-02 16:57:35 -07003895 /* Hierarchical information */
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003896 memory = memsw = PAGE_COUNTER_MAX;
3897 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003898 memory = min(memory, mi->memory.max);
3899 memsw = min(memsw, mi->memsw.max);
KAMEZAWA Hiroyukifee7b542009-01-07 18:08:26 -08003900 }
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003901 seq_printf(m, "hierarchical_memory_limit %llu\n",
3902 (u64)memory * PAGE_SIZE);
Johannes Weiner7941d212016-01-14 15:21:23 -08003903 if (do_memsw_account())
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003904 seq_printf(m, "hierarchical_memsw_limit %llu\n",
3905 (u64)memsw * PAGE_SIZE);
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08003906
Shakeel Butt8de7ecc62018-08-21 21:53:17 -07003907 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
Johannes Weiner71cd3112017-05-03 14:55:13 -07003908 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
Daisuke Nishimura1dd3a272009-09-23 15:56:43 -07003909 continue;
Shakeel Butt8de7ecc62018-08-21 21:53:17 -07003910 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
Yafang Shaodd923992019-07-11 20:52:11 -07003911 (u64)memcg_page_state(memcg, memcg1_stats[i]) *
3912 PAGE_SIZE);
Johannes Weineraf7c4b02012-05-29 15:07:08 -07003913 }
3914
Shakeel Butt8de7ecc62018-08-21 21:53:17 -07003915 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3916 seq_printf(m, "total_%s %llu\n", memcg1_event_names[i],
Yafang Shaodd923992019-07-11 20:52:11 -07003917 (u64)memcg_events(memcg, memcg1_events[i]));
Johannes Weineraf7c4b02012-05-29 15:07:08 -07003918
Shakeel Butt8de7ecc62018-08-21 21:53:17 -07003919 for (i = 0; i < NR_LRU_LISTS; i++)
3920 seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i],
Johannes Weiner42a30032019-05-14 15:47:12 -07003921 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
3922 PAGE_SIZE);
KAMEZAWA Hiroyuki14067bb2009-04-02 16:57:35 -07003923
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08003924#ifdef CONFIG_DEBUG_VM
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08003925 {
Mel Gormanef8f2322016-07-28 15:46:05 -07003926 pg_data_t *pgdat;
3927 struct mem_cgroup_per_node *mz;
Hugh Dickins89abfab2012-05-29 15:06:53 -07003928 struct zone_reclaim_stat *rstat;
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08003929 unsigned long recent_rotated[2] = {0, 0};
3930 unsigned long recent_scanned[2] = {0, 0};
3931
Mel Gormanef8f2322016-07-28 15:46:05 -07003932 for_each_online_pgdat(pgdat) {
3933 mz = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
3934 rstat = &mz->lruvec.reclaim_stat;
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08003935
Mel Gormanef8f2322016-07-28 15:46:05 -07003936 recent_rotated[0] += rstat->recent_rotated[0];
3937 recent_rotated[1] += rstat->recent_rotated[1];
3938 recent_scanned[0] += rstat->recent_scanned[0];
3939 recent_scanned[1] += rstat->recent_scanned[1];
3940 }
Johannes Weiner78ccf5b2012-05-29 15:07:06 -07003941 seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
3942 seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
3943 seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
3944 seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08003945 }
3946#endif
3947
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -08003948 return 0;
3949}
3950
Tejun Heo182446d2013-08-08 20:11:24 -04003951static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
3952 struct cftype *cft)
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08003953{
Tejun Heo182446d2013-08-08 20:11:24 -04003954 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08003955
KAMEZAWA Hiroyuki1f4c0252011-07-26 16:08:21 -07003956 return mem_cgroup_swappiness(memcg);
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08003957}
3958
Tejun Heo182446d2013-08-08 20:11:24 -04003959static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
3960 struct cftype *cft, u64 val)
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08003961{
Tejun Heo182446d2013-08-08 20:11:24 -04003962 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Li Zefan068b38c2009-01-15 13:51:26 -08003963
Johannes Weiner3dae7fe2014-06-04 16:07:01 -07003964 if (val > 100)
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08003965 return -EINVAL;
3966
Linus Torvalds14208b02014-06-09 15:03:33 -07003967 if (css->parent)
Johannes Weiner3dae7fe2014-06-04 16:07:01 -07003968 memcg->swappiness = val;
3969 else
3970 vm_swappiness = val;
Li Zefan068b38c2009-01-15 13:51:26 -08003971
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08003972 return 0;
3973}
3974
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08003975static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
3976{
3977 struct mem_cgroup_threshold_ary *t;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003978 unsigned long usage;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08003979 int i;
3980
3981 rcu_read_lock();
3982 if (!swap)
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07003983 t = rcu_dereference(memcg->thresholds.primary);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08003984 else
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07003985 t = rcu_dereference(memcg->memsw_thresholds.primary);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08003986
3987 if (!t)
3988 goto unlock;
3989
Johannes Weinerce00a962014-09-05 08:43:57 -04003990 usage = mem_cgroup_usage(memcg, swap);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08003991
3992 /*
Sha Zhengju748dad32012-05-29 15:06:57 -07003993 * current_threshold points to threshold just below or equal to usage.
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08003994 * If it's not true, a threshold was crossed after last
3995 * call of __mem_cgroup_threshold().
3996 */
Phil Carmody5407a562010-05-26 14:42:42 -07003997 i = t->current_threshold;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08003998
3999 /*
4000 * Iterate backward over array of thresholds starting from
4001 * current_threshold and check if a threshold is crossed.
4002 * If none of thresholds below usage is crossed, we read
4003 * only one element of the array here.
4004 */
4005 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4006 eventfd_signal(t->entries[i].eventfd, 1);
4007
4008 /* i = current_threshold + 1 */
4009 i++;
4010
4011 /*
4012 * Iterate forward over array of thresholds starting from
4013 * current_threshold+1 and check if a threshold is crossed.
4014 * If none of thresholds above usage is crossed, we read
4015 * only one element of the array here.
4016 */
4017 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4018 eventfd_signal(t->entries[i].eventfd, 1);
4019
4020 /* Update current_threshold */
Phil Carmody5407a562010-05-26 14:42:42 -07004021 t->current_threshold = i - 1;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004022unlock:
4023 rcu_read_unlock();
4024}
4025
4026static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4027{
Kirill A. Shutemovad4ca5f2010-10-07 12:59:27 -07004028 while (memcg) {
4029 __mem_cgroup_threshold(memcg, false);
Johannes Weiner7941d212016-01-14 15:21:23 -08004030 if (do_memsw_account())
Kirill A. Shutemovad4ca5f2010-10-07 12:59:27 -07004031 __mem_cgroup_threshold(memcg, true);
4032
4033 memcg = parent_mem_cgroup(memcg);
4034 }
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004035}
4036
4037static int compare_thresholds(const void *a, const void *b)
4038{
4039 const struct mem_cgroup_threshold *_a = a;
4040 const struct mem_cgroup_threshold *_b = b;
4041
Greg Thelen2bff24a2013-09-11 14:23:08 -07004042 if (_a->threshold > _b->threshold)
4043 return 1;
4044
4045 if (_a->threshold < _b->threshold)
4046 return -1;
4047
4048 return 0;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004049}
4050
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004051static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004052{
4053 struct mem_cgroup_eventfd_list *ev;
4054
Michal Hocko2bcf2e92014-07-30 16:08:33 -07004055 spin_lock(&memcg_oom_lock);
4056
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004057 list_for_each_entry(ev, &memcg->oom_notify, list)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004058 eventfd_signal(ev->eventfd, 1);
Michal Hocko2bcf2e92014-07-30 16:08:33 -07004059
4060 spin_unlock(&memcg_oom_lock);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004061 return 0;
4062}
4063
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004064static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004065{
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07004066 struct mem_cgroup *iter;
4067
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004068 for_each_mem_cgroup_tree(iter, memcg)
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07004069 mem_cgroup_oom_notify_cb(iter);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004070}
4071
Tejun Heo59b6f872013-11-22 18:20:43 -05004072static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004073 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004074{
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004075 struct mem_cgroup_thresholds *thresholds;
4076 struct mem_cgroup_threshold_ary *new;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004077 unsigned long threshold;
4078 unsigned long usage;
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004079 int i, size, ret;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004080
Johannes Weiner650c5e52015-02-11 15:26:03 -08004081 ret = page_counter_memparse(args, "-1", &threshold);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004082 if (ret)
4083 return ret;
4084
4085 mutex_lock(&memcg->thresholds_lock);
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004086
Johannes Weiner05b84302014-08-06 16:05:59 -07004087 if (type == _MEM) {
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004088 thresholds = &memcg->thresholds;
Johannes Weinerce00a962014-09-05 08:43:57 -04004089 usage = mem_cgroup_usage(memcg, false);
Johannes Weiner05b84302014-08-06 16:05:59 -07004090 } else if (type == _MEMSWAP) {
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004091 thresholds = &memcg->memsw_thresholds;
Johannes Weinerce00a962014-09-05 08:43:57 -04004092 usage = mem_cgroup_usage(memcg, true);
Johannes Weiner05b84302014-08-06 16:05:59 -07004093 } else
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004094 BUG();
4095
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004096 /* Check if a threshold crossed before adding a new one */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004097 if (thresholds->primary)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004098 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4099
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004100 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004101
4102 /* Allocate memory for new array of thresholds */
Gustavo A. R. Silva67b80462019-03-05 15:44:05 -08004103 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004104 if (!new) {
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004105 ret = -ENOMEM;
4106 goto unlock;
4107 }
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004108 new->size = size;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004109
4110 /* Copy thresholds (if any) to new array */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004111 if (thresholds->primary) {
4112 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004113 sizeof(struct mem_cgroup_threshold));
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004114 }
4115
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004116 /* Add new threshold */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004117 new->entries[size - 1].eventfd = eventfd;
4118 new->entries[size - 1].threshold = threshold;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004119
4120 /* Sort thresholds. Registering of new threshold isn't time-critical */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004121 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004122 compare_thresholds, NULL);
4123
4124 /* Find current threshold */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004125 new->current_threshold = -1;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004126 for (i = 0; i < size; i++) {
Sha Zhengju748dad32012-05-29 15:06:57 -07004127 if (new->entries[i].threshold <= usage) {
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004128 /*
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004129 * new->current_threshold will not be used until
4130 * rcu_assign_pointer(), so it's safe to increment
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004131 * it here.
4132 */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004133 ++new->current_threshold;
Sha Zhengju748dad32012-05-29 15:06:57 -07004134 } else
4135 break;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004136 }
4137
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004138 /* Free old spare buffer and save old primary buffer as spare */
4139 kfree(thresholds->spare);
4140 thresholds->spare = thresholds->primary;
4141
4142 rcu_assign_pointer(thresholds->primary, new);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004143
Kirill A. Shutemov907860e2010-05-26 14:42:46 -07004144 /* To be sure that nobody uses thresholds */
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004145 synchronize_rcu();
4146
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004147unlock:
4148 mutex_unlock(&memcg->thresholds_lock);
4149
4150 return ret;
4151}
4152
Tejun Heo59b6f872013-11-22 18:20:43 -05004153static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004154 struct eventfd_ctx *eventfd, const char *args)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004155{
Tejun Heo59b6f872013-11-22 18:20:43 -05004156 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
Tejun Heo347c4a82013-11-22 18:20:43 -05004157}
4158
Tejun Heo59b6f872013-11-22 18:20:43 -05004159static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004160 struct eventfd_ctx *eventfd, const char *args)
4161{
Tejun Heo59b6f872013-11-22 18:20:43 -05004162 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
Tejun Heo347c4a82013-11-22 18:20:43 -05004163}
4164
Tejun Heo59b6f872013-11-22 18:20:43 -05004165static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004166 struct eventfd_ctx *eventfd, enum res_type type)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004167{
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004168 struct mem_cgroup_thresholds *thresholds;
4169 struct mem_cgroup_threshold_ary *new;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004170 unsigned long usage;
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004171 int i, j, size;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004172
4173 mutex_lock(&memcg->thresholds_lock);
Johannes Weiner05b84302014-08-06 16:05:59 -07004174
4175 if (type == _MEM) {
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004176 thresholds = &memcg->thresholds;
Johannes Weinerce00a962014-09-05 08:43:57 -04004177 usage = mem_cgroup_usage(memcg, false);
Johannes Weiner05b84302014-08-06 16:05:59 -07004178 } else if (type == _MEMSWAP) {
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004179 thresholds = &memcg->memsw_thresholds;
Johannes Weinerce00a962014-09-05 08:43:57 -04004180 usage = mem_cgroup_usage(memcg, true);
Johannes Weiner05b84302014-08-06 16:05:59 -07004181 } else
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004182 BUG();
4183
Anton Vorontsov371528c2012-02-24 05:14:46 +04004184 if (!thresholds->primary)
4185 goto unlock;
4186
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004187 /* Check if a threshold crossed before removing */
4188 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4189
4190 /* Calculate new number of threshold */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004191 size = 0;
4192 for (i = 0; i < thresholds->primary->size; i++) {
4193 if (thresholds->primary->entries[i].eventfd != eventfd)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004194 size++;
4195 }
4196
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004197 new = thresholds->spare;
Kirill A. Shutemov907860e2010-05-26 14:42:46 -07004198
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004199 /* Set thresholds array to NULL if we don't have thresholds */
4200 if (!size) {
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004201 kfree(new);
4202 new = NULL;
Kirill A. Shutemov907860e2010-05-26 14:42:46 -07004203 goto swap_buffers;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004204 }
4205
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004206 new->size = size;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004207
4208 /* Copy thresholds and find current threshold */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004209 new->current_threshold = -1;
4210 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4211 if (thresholds->primary->entries[i].eventfd == eventfd)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004212 continue;
4213
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004214 new->entries[j] = thresholds->primary->entries[i];
Sha Zhengju748dad32012-05-29 15:06:57 -07004215 if (new->entries[j].threshold <= usage) {
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004216 /*
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004217 * new->current_threshold will not be used
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004218 * until rcu_assign_pointer(), so it's safe to increment
4219 * it here.
4220 */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004221 ++new->current_threshold;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004222 }
4223 j++;
4224 }
4225
Kirill A. Shutemov907860e2010-05-26 14:42:46 -07004226swap_buffers:
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004227 /* Swap primary and spare array */
4228 thresholds->spare = thresholds->primary;
Sha Zhengju8c757762012-05-10 13:01:45 -07004229
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004230 rcu_assign_pointer(thresholds->primary, new);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004231
Kirill A. Shutemov907860e2010-05-26 14:42:46 -07004232 /* To be sure that nobody uses thresholds */
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004233 synchronize_rcu();
Martijn Coenen6611d8d2016-01-15 16:57:49 -08004234
4235 /* If all events are unregistered, free the spare array */
4236 if (!new) {
4237 kfree(thresholds->spare);
4238 thresholds->spare = NULL;
4239 }
Anton Vorontsov371528c2012-02-24 05:14:46 +04004240unlock:
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004241 mutex_unlock(&memcg->thresholds_lock);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004242}
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08004243
Tejun Heo59b6f872013-11-22 18:20:43 -05004244static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004245 struct eventfd_ctx *eventfd)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004246{
Tejun Heo59b6f872013-11-22 18:20:43 -05004247 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
Tejun Heo347c4a82013-11-22 18:20:43 -05004248}
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004249
Tejun Heo59b6f872013-11-22 18:20:43 -05004250static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004251 struct eventfd_ctx *eventfd)
4252{
Tejun Heo59b6f872013-11-22 18:20:43 -05004253 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
Tejun Heo347c4a82013-11-22 18:20:43 -05004254}
4255
Tejun Heo59b6f872013-11-22 18:20:43 -05004256static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004257 struct eventfd_ctx *eventfd, const char *args)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004258{
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004259 struct mem_cgroup_eventfd_list *event;
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004260
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004261 event = kmalloc(sizeof(*event), GFP_KERNEL);
4262 if (!event)
4263 return -ENOMEM;
4264
Michal Hocko1af8efe2011-07-26 16:08:24 -07004265 spin_lock(&memcg_oom_lock);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004266
4267 event->eventfd = eventfd;
4268 list_add(&event->list, &memcg->oom_notify);
4269
4270 /* already in OOM ? */
Tejun Heoc2b42d32015-06-24 16:58:23 -07004271 if (memcg->under_oom)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004272 eventfd_signal(eventfd, 1);
Michal Hocko1af8efe2011-07-26 16:08:24 -07004273 spin_unlock(&memcg_oom_lock);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004274
4275 return 0;
4276}
4277
Tejun Heo59b6f872013-11-22 18:20:43 -05004278static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004279 struct eventfd_ctx *eventfd)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004280{
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004281 struct mem_cgroup_eventfd_list *ev, *tmp;
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004282
Michal Hocko1af8efe2011-07-26 16:08:24 -07004283 spin_lock(&memcg_oom_lock);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004284
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004285 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004286 if (ev->eventfd == eventfd) {
4287 list_del(&ev->list);
4288 kfree(ev);
4289 }
4290 }
4291
Michal Hocko1af8efe2011-07-26 16:08:24 -07004292 spin_unlock(&memcg_oom_lock);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004293}
4294
Tejun Heo2da8ca82013-12-05 12:28:04 -05004295static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004296{
Chris Downaa9694b2019-03-05 15:45:52 -08004297 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004298
Tejun Heo791badb2013-12-05 12:28:02 -05004299 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
Tejun Heoc2b42d32015-06-24 16:58:23 -07004300 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
Roman Gushchinfe6bdfc2018-06-14 15:28:05 -07004301 seq_printf(sf, "oom_kill %lu\n",
4302 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004303 return 0;
4304}
4305
Tejun Heo182446d2013-08-08 20:11:24 -04004306static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004307 struct cftype *cft, u64 val)
4308{
Tejun Heo182446d2013-08-08 20:11:24 -04004309 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004310
4311 /* cannot set to root cgroup and only 0 and 1 are allowed */
Linus Torvalds14208b02014-06-09 15:03:33 -07004312 if (!css->parent || !((val == 0) || (val == 1)))
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004313 return -EINVAL;
4314
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004315 memcg->oom_kill_disable = val;
KAMEZAWA Hiroyuki4d845eb2010-06-29 15:05:18 -07004316 if (!val)
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004317 memcg_oom_recover(memcg);
Johannes Weiner3dae7fe2014-06-04 16:07:01 -07004318
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004319 return 0;
4320}
4321
Tejun Heo52ebea72015-05-22 17:13:37 -04004322#ifdef CONFIG_CGROUP_WRITEBACK
4323
Tejun Heo3a8e9ac2019-08-29 15:47:19 -07004324#include <trace/events/writeback.h>
4325
Tejun Heo841710a2015-05-22 18:23:33 -04004326static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4327{
4328 return wb_domain_init(&memcg->cgwb_domain, gfp);
4329}
4330
4331static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4332{
4333 wb_domain_exit(&memcg->cgwb_domain);
4334}
4335
Tejun Heo2529bb32015-05-22 18:23:34 -04004336static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4337{
4338 wb_domain_size_changed(&memcg->cgwb_domain);
4339}
4340
Tejun Heo841710a2015-05-22 18:23:33 -04004341struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4342{
4343 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4344
4345 if (!memcg->css.parent)
4346 return NULL;
4347
4348 return &memcg->cgwb_domain;
4349}
4350
Greg Thelen0b3d6e62019-04-05 18:39:18 -07004351/*
4352 * idx can be of type enum memcg_stat_item or node_stat_item.
4353 * Keep in sync with memcg_exact_page().
4354 */
4355static unsigned long memcg_exact_page_state(struct mem_cgroup *memcg, int idx)
4356{
Chris Down871789d2019-05-14 15:46:57 -07004357 long x = atomic_long_read(&memcg->vmstats[idx]);
Greg Thelen0b3d6e62019-04-05 18:39:18 -07004358 int cpu;
4359
4360 for_each_online_cpu(cpu)
Chris Down871789d2019-05-14 15:46:57 -07004361 x += per_cpu_ptr(memcg->vmstats_percpu, cpu)->stat[idx];
Greg Thelen0b3d6e62019-04-05 18:39:18 -07004362 if (x < 0)
4363 x = 0;
4364 return x;
4365}
4366
Tejun Heoc2aa7232015-05-22 18:23:35 -04004367/**
4368 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4369 * @wb: bdi_writeback in question
Tejun Heoc5edf9c2015-09-29 13:04:26 -04004370 * @pfilepages: out parameter for number of file pages
4371 * @pheadroom: out parameter for number of allocatable pages according to memcg
Tejun Heoc2aa7232015-05-22 18:23:35 -04004372 * @pdirty: out parameter for number of dirty pages
4373 * @pwriteback: out parameter for number of pages under writeback
4374 *
Tejun Heoc5edf9c2015-09-29 13:04:26 -04004375 * Determine the numbers of file, headroom, dirty, and writeback pages in
4376 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4377 * is a bit more involved.
Tejun Heoc2aa7232015-05-22 18:23:35 -04004378 *
Tejun Heoc5edf9c2015-09-29 13:04:26 -04004379 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4380 * headroom is calculated as the lowest headroom of itself and the
4381 * ancestors. Note that this doesn't consider the actual amount of
4382 * available memory in the system. The caller should further cap
4383 * *@pheadroom accordingly.
Tejun Heoc2aa7232015-05-22 18:23:35 -04004384 */
Tejun Heoc5edf9c2015-09-29 13:04:26 -04004385void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4386 unsigned long *pheadroom, unsigned long *pdirty,
4387 unsigned long *pwriteback)
Tejun Heoc2aa7232015-05-22 18:23:35 -04004388{
4389 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4390 struct mem_cgroup *parent;
Tejun Heoc2aa7232015-05-22 18:23:35 -04004391
Greg Thelen0b3d6e62019-04-05 18:39:18 -07004392 *pdirty = memcg_exact_page_state(memcg, NR_FILE_DIRTY);
Tejun Heoc2aa7232015-05-22 18:23:35 -04004393
4394 /* this should eventually include NR_UNSTABLE_NFS */
Greg Thelen0b3d6e62019-04-05 18:39:18 -07004395 *pwriteback = memcg_exact_page_state(memcg, NR_WRITEBACK);
Johannes Weiner21d89d12019-05-13 17:18:08 -07004396 *pfilepages = memcg_exact_page_state(memcg, NR_INACTIVE_FILE) +
4397 memcg_exact_page_state(memcg, NR_ACTIVE_FILE);
Tejun Heoc5edf9c2015-09-29 13:04:26 -04004398 *pheadroom = PAGE_COUNTER_MAX;
Tejun Heoc2aa7232015-05-22 18:23:35 -04004399
Tejun Heoc2aa7232015-05-22 18:23:35 -04004400 while ((parent = parent_mem_cgroup(memcg))) {
Roman Gushchinbbec2e12018-06-07 17:06:18 -07004401 unsigned long ceiling = min(memcg->memory.max, memcg->high);
Tejun Heoc2aa7232015-05-22 18:23:35 -04004402 unsigned long used = page_counter_read(&memcg->memory);
4403
Tejun Heoc5edf9c2015-09-29 13:04:26 -04004404 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
Tejun Heoc2aa7232015-05-22 18:23:35 -04004405 memcg = parent;
4406 }
Tejun Heoc2aa7232015-05-22 18:23:35 -04004407}
4408
Tejun Heo97b27822019-08-26 09:06:56 -07004409/*
4410 * Foreign dirty flushing
4411 *
4412 * There's an inherent mismatch between memcg and writeback. The former
4413 * trackes ownership per-page while the latter per-inode. This was a
4414 * deliberate design decision because honoring per-page ownership in the
4415 * writeback path is complicated, may lead to higher CPU and IO overheads
4416 * and deemed unnecessary given that write-sharing an inode across
4417 * different cgroups isn't a common use-case.
4418 *
4419 * Combined with inode majority-writer ownership switching, this works well
4420 * enough in most cases but there are some pathological cases. For
4421 * example, let's say there are two cgroups A and B which keep writing to
4422 * different but confined parts of the same inode. B owns the inode and
4423 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4424 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4425 * triggering background writeback. A will be slowed down without a way to
4426 * make writeback of the dirty pages happen.
4427 *
4428 * Conditions like the above can lead to a cgroup getting repatedly and
4429 * severely throttled after making some progress after each
4430 * dirty_expire_interval while the underyling IO device is almost
4431 * completely idle.
4432 *
4433 * Solving this problem completely requires matching the ownership tracking
4434 * granularities between memcg and writeback in either direction. However,
4435 * the more egregious behaviors can be avoided by simply remembering the
4436 * most recent foreign dirtying events and initiating remote flushes on
4437 * them when local writeback isn't enough to keep the memory clean enough.
4438 *
4439 * The following two functions implement such mechanism. When a foreign
4440 * page - a page whose memcg and writeback ownerships don't match - is
4441 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4442 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4443 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4444 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4445 * foreign bdi_writebacks which haven't expired. Both the numbers of
4446 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4447 * limited to MEMCG_CGWB_FRN_CNT.
4448 *
4449 * The mechanism only remembers IDs and doesn't hold any object references.
4450 * As being wrong occasionally doesn't matter, updates and accesses to the
4451 * records are lockless and racy.
4452 */
4453void mem_cgroup_track_foreign_dirty_slowpath(struct page *page,
4454 struct bdi_writeback *wb)
4455{
4456 struct mem_cgroup *memcg = page->mem_cgroup;
4457 struct memcg_cgwb_frn *frn;
4458 u64 now = get_jiffies_64();
4459 u64 oldest_at = now;
4460 int oldest = -1;
4461 int i;
4462
Tejun Heo3a8e9ac2019-08-29 15:47:19 -07004463 trace_track_foreign_dirty(page, wb);
4464
Tejun Heo97b27822019-08-26 09:06:56 -07004465 /*
4466 * Pick the slot to use. If there is already a slot for @wb, keep
4467 * using it. If not replace the oldest one which isn't being
4468 * written out.
4469 */
4470 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4471 frn = &memcg->cgwb_frn[i];
4472 if (frn->bdi_id == wb->bdi->id &&
4473 frn->memcg_id == wb->memcg_css->id)
4474 break;
4475 if (time_before64(frn->at, oldest_at) &&
4476 atomic_read(&frn->done.cnt) == 1) {
4477 oldest = i;
4478 oldest_at = frn->at;
4479 }
4480 }
4481
4482 if (i < MEMCG_CGWB_FRN_CNT) {
4483 /*
4484 * Re-using an existing one. Update timestamp lazily to
4485 * avoid making the cacheline hot. We want them to be
4486 * reasonably up-to-date and significantly shorter than
4487 * dirty_expire_interval as that's what expires the record.
4488 * Use the shorter of 1s and dirty_expire_interval / 8.
4489 */
4490 unsigned long update_intv =
4491 min_t(unsigned long, HZ,
4492 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4493
4494 if (time_before64(frn->at, now - update_intv))
4495 frn->at = now;
4496 } else if (oldest >= 0) {
4497 /* replace the oldest free one */
4498 frn = &memcg->cgwb_frn[oldest];
4499 frn->bdi_id = wb->bdi->id;
4500 frn->memcg_id = wb->memcg_css->id;
4501 frn->at = now;
4502 }
4503}
4504
4505/* issue foreign writeback flushes for recorded foreign dirtying events */
4506void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4507{
4508 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4509 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4510 u64 now = jiffies_64;
4511 int i;
4512
4513 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4514 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4515
4516 /*
4517 * If the record is older than dirty_expire_interval,
4518 * writeback on it has already started. No need to kick it
4519 * off again. Also, don't start a new one if there's
4520 * already one in flight.
4521 */
4522 if (time_after64(frn->at, now - intv) &&
4523 atomic_read(&frn->done.cnt) == 1) {
4524 frn->at = 0;
Tejun Heo3a8e9ac2019-08-29 15:47:19 -07004525 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
Tejun Heo97b27822019-08-26 09:06:56 -07004526 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id, 0,
4527 WB_REASON_FOREIGN_FLUSH,
4528 &frn->done);
4529 }
4530 }
4531}
4532
Tejun Heo841710a2015-05-22 18:23:33 -04004533#else /* CONFIG_CGROUP_WRITEBACK */
4534
4535static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4536{
4537 return 0;
4538}
4539
4540static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4541{
4542}
4543
Tejun Heo2529bb32015-05-22 18:23:34 -04004544static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4545{
4546}
4547
Tejun Heo52ebea72015-05-22 17:13:37 -04004548#endif /* CONFIG_CGROUP_WRITEBACK */
4549
Tejun Heo79bd9812013-11-22 18:20:42 -05004550/*
Tejun Heo3bc942f2013-11-22 18:20:44 -05004551 * DO NOT USE IN NEW FILES.
4552 *
4553 * "cgroup.event_control" implementation.
4554 *
4555 * This is way over-engineered. It tries to support fully configurable
4556 * events for each user. Such level of flexibility is completely
4557 * unnecessary especially in the light of the planned unified hierarchy.
4558 *
4559 * Please deprecate this and replace with something simpler if at all
4560 * possible.
4561 */
4562
4563/*
Tejun Heo79bd9812013-11-22 18:20:42 -05004564 * Unregister event and free resources.
4565 *
4566 * Gets called from workqueue.
4567 */
Tejun Heo3bc942f2013-11-22 18:20:44 -05004568static void memcg_event_remove(struct work_struct *work)
Tejun Heo79bd9812013-11-22 18:20:42 -05004569{
Tejun Heo3bc942f2013-11-22 18:20:44 -05004570 struct mem_cgroup_event *event =
4571 container_of(work, struct mem_cgroup_event, remove);
Tejun Heo59b6f872013-11-22 18:20:43 -05004572 struct mem_cgroup *memcg = event->memcg;
Tejun Heo79bd9812013-11-22 18:20:42 -05004573
4574 remove_wait_queue(event->wqh, &event->wait);
4575
Tejun Heo59b6f872013-11-22 18:20:43 -05004576 event->unregister_event(memcg, event->eventfd);
Tejun Heo79bd9812013-11-22 18:20:42 -05004577
4578 /* Notify userspace the event is going away. */
4579 eventfd_signal(event->eventfd, 1);
4580
4581 eventfd_ctx_put(event->eventfd);
4582 kfree(event);
Tejun Heo59b6f872013-11-22 18:20:43 -05004583 css_put(&memcg->css);
Tejun Heo79bd9812013-11-22 18:20:42 -05004584}
4585
4586/*
Linus Torvaldsa9a08842018-02-11 14:34:03 -08004587 * Gets called on EPOLLHUP on eventfd when user closes it.
Tejun Heo79bd9812013-11-22 18:20:42 -05004588 *
4589 * Called with wqh->lock held and interrupts disabled.
4590 */
Ingo Molnarac6424b2017-06-20 12:06:13 +02004591static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
Tejun Heo3bc942f2013-11-22 18:20:44 -05004592 int sync, void *key)
Tejun Heo79bd9812013-11-22 18:20:42 -05004593{
Tejun Heo3bc942f2013-11-22 18:20:44 -05004594 struct mem_cgroup_event *event =
4595 container_of(wait, struct mem_cgroup_event, wait);
Tejun Heo59b6f872013-11-22 18:20:43 -05004596 struct mem_cgroup *memcg = event->memcg;
Al Viro3ad6f932017-07-03 20:14:56 -04004597 __poll_t flags = key_to_poll(key);
Tejun Heo79bd9812013-11-22 18:20:42 -05004598
Linus Torvaldsa9a08842018-02-11 14:34:03 -08004599 if (flags & EPOLLHUP) {
Tejun Heo79bd9812013-11-22 18:20:42 -05004600 /*
4601 * If the event has been detached at cgroup removal, we
4602 * can simply return knowing the other side will cleanup
4603 * for us.
4604 *
4605 * We can't race against event freeing since the other
4606 * side will require wqh->lock via remove_wait_queue(),
4607 * which we hold.
4608 */
Tejun Heofba94802013-11-22 18:20:43 -05004609 spin_lock(&memcg->event_list_lock);
Tejun Heo79bd9812013-11-22 18:20:42 -05004610 if (!list_empty(&event->list)) {
4611 list_del_init(&event->list);
4612 /*
4613 * We are in atomic context, but cgroup_event_remove()
4614 * may sleep, so we have to call it in workqueue.
4615 */
4616 schedule_work(&event->remove);
4617 }
Tejun Heofba94802013-11-22 18:20:43 -05004618 spin_unlock(&memcg->event_list_lock);
Tejun Heo79bd9812013-11-22 18:20:42 -05004619 }
4620
4621 return 0;
4622}
4623
Tejun Heo3bc942f2013-11-22 18:20:44 -05004624static void memcg_event_ptable_queue_proc(struct file *file,
Tejun Heo79bd9812013-11-22 18:20:42 -05004625 wait_queue_head_t *wqh, poll_table *pt)
4626{
Tejun Heo3bc942f2013-11-22 18:20:44 -05004627 struct mem_cgroup_event *event =
4628 container_of(pt, struct mem_cgroup_event, pt);
Tejun Heo79bd9812013-11-22 18:20:42 -05004629
4630 event->wqh = wqh;
4631 add_wait_queue(wqh, &event->wait);
4632}
4633
4634/*
Tejun Heo3bc942f2013-11-22 18:20:44 -05004635 * DO NOT USE IN NEW FILES.
4636 *
Tejun Heo79bd9812013-11-22 18:20:42 -05004637 * Parse input and register new cgroup event handler.
4638 *
4639 * Input must be in format '<event_fd> <control_fd> <args>'.
4640 * Interpretation of args is defined by control file implementation.
4641 */
Tejun Heo451af502014-05-13 12:16:21 -04004642static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4643 char *buf, size_t nbytes, loff_t off)
Tejun Heo79bd9812013-11-22 18:20:42 -05004644{
Tejun Heo451af502014-05-13 12:16:21 -04004645 struct cgroup_subsys_state *css = of_css(of);
Tejun Heofba94802013-11-22 18:20:43 -05004646 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Tejun Heo3bc942f2013-11-22 18:20:44 -05004647 struct mem_cgroup_event *event;
Tejun Heo79bd9812013-11-22 18:20:42 -05004648 struct cgroup_subsys_state *cfile_css;
4649 unsigned int efd, cfd;
4650 struct fd efile;
4651 struct fd cfile;
Tejun Heofba94802013-11-22 18:20:43 -05004652 const char *name;
Tejun Heo79bd9812013-11-22 18:20:42 -05004653 char *endp;
4654 int ret;
4655
Tejun Heo451af502014-05-13 12:16:21 -04004656 buf = strstrip(buf);
4657
4658 efd = simple_strtoul(buf, &endp, 10);
Tejun Heo79bd9812013-11-22 18:20:42 -05004659 if (*endp != ' ')
4660 return -EINVAL;
Tejun Heo451af502014-05-13 12:16:21 -04004661 buf = endp + 1;
Tejun Heo79bd9812013-11-22 18:20:42 -05004662
Tejun Heo451af502014-05-13 12:16:21 -04004663 cfd = simple_strtoul(buf, &endp, 10);
Tejun Heo79bd9812013-11-22 18:20:42 -05004664 if ((*endp != ' ') && (*endp != '\0'))
4665 return -EINVAL;
Tejun Heo451af502014-05-13 12:16:21 -04004666 buf = endp + 1;
Tejun Heo79bd9812013-11-22 18:20:42 -05004667
4668 event = kzalloc(sizeof(*event), GFP_KERNEL);
4669 if (!event)
4670 return -ENOMEM;
4671
Tejun Heo59b6f872013-11-22 18:20:43 -05004672 event->memcg = memcg;
Tejun Heo79bd9812013-11-22 18:20:42 -05004673 INIT_LIST_HEAD(&event->list);
Tejun Heo3bc942f2013-11-22 18:20:44 -05004674 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4675 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4676 INIT_WORK(&event->remove, memcg_event_remove);
Tejun Heo79bd9812013-11-22 18:20:42 -05004677
4678 efile = fdget(efd);
4679 if (!efile.file) {
4680 ret = -EBADF;
4681 goto out_kfree;
4682 }
4683
4684 event->eventfd = eventfd_ctx_fileget(efile.file);
4685 if (IS_ERR(event->eventfd)) {
4686 ret = PTR_ERR(event->eventfd);
4687 goto out_put_efile;
4688 }
4689
4690 cfile = fdget(cfd);
4691 if (!cfile.file) {
4692 ret = -EBADF;
4693 goto out_put_eventfd;
4694 }
4695
4696 /* the process need read permission on control file */
4697 /* AV: shouldn't we check that it's been opened for read instead? */
4698 ret = inode_permission(file_inode(cfile.file), MAY_READ);
4699 if (ret < 0)
4700 goto out_put_cfile;
4701
Tejun Heo79bd9812013-11-22 18:20:42 -05004702 /*
Tejun Heofba94802013-11-22 18:20:43 -05004703 * Determine the event callbacks and set them in @event. This used
4704 * to be done via struct cftype but cgroup core no longer knows
4705 * about these events. The following is crude but the whole thing
4706 * is for compatibility anyway.
Tejun Heo3bc942f2013-11-22 18:20:44 -05004707 *
4708 * DO NOT ADD NEW FILES.
Tejun Heofba94802013-11-22 18:20:43 -05004709 */
Al Virob5830432014-10-31 01:22:04 -04004710 name = cfile.file->f_path.dentry->d_name.name;
Tejun Heofba94802013-11-22 18:20:43 -05004711
4712 if (!strcmp(name, "memory.usage_in_bytes")) {
4713 event->register_event = mem_cgroup_usage_register_event;
4714 event->unregister_event = mem_cgroup_usage_unregister_event;
4715 } else if (!strcmp(name, "memory.oom_control")) {
4716 event->register_event = mem_cgroup_oom_register_event;
4717 event->unregister_event = mem_cgroup_oom_unregister_event;
4718 } else if (!strcmp(name, "memory.pressure_level")) {
4719 event->register_event = vmpressure_register_event;
4720 event->unregister_event = vmpressure_unregister_event;
4721 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
Tejun Heo347c4a82013-11-22 18:20:43 -05004722 event->register_event = memsw_cgroup_usage_register_event;
4723 event->unregister_event = memsw_cgroup_usage_unregister_event;
Tejun Heofba94802013-11-22 18:20:43 -05004724 } else {
4725 ret = -EINVAL;
4726 goto out_put_cfile;
4727 }
4728
4729 /*
Tejun Heob5557c42013-11-22 18:20:42 -05004730 * Verify @cfile should belong to @css. Also, remaining events are
4731 * automatically removed on cgroup destruction but the removal is
4732 * asynchronous, so take an extra ref on @css.
Tejun Heo79bd9812013-11-22 18:20:42 -05004733 */
Al Virob5830432014-10-31 01:22:04 -04004734 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
Tejun Heoec903c02014-05-13 12:11:01 -04004735 &memory_cgrp_subsys);
Tejun Heo79bd9812013-11-22 18:20:42 -05004736 ret = -EINVAL;
Tejun Heo5a17f542014-02-11 11:52:47 -05004737 if (IS_ERR(cfile_css))
Tejun Heo79bd9812013-11-22 18:20:42 -05004738 goto out_put_cfile;
Tejun Heo5a17f542014-02-11 11:52:47 -05004739 if (cfile_css != css) {
4740 css_put(cfile_css);
4741 goto out_put_cfile;
4742 }
Tejun Heo79bd9812013-11-22 18:20:42 -05004743
Tejun Heo451af502014-05-13 12:16:21 -04004744 ret = event->register_event(memcg, event->eventfd, buf);
Tejun Heo79bd9812013-11-22 18:20:42 -05004745 if (ret)
4746 goto out_put_css;
4747
Christoph Hellwig9965ed172018-03-05 07:26:05 -08004748 vfs_poll(efile.file, &event->pt);
Tejun Heo79bd9812013-11-22 18:20:42 -05004749
Tejun Heofba94802013-11-22 18:20:43 -05004750 spin_lock(&memcg->event_list_lock);
4751 list_add(&event->list, &memcg->event_list);
4752 spin_unlock(&memcg->event_list_lock);
Tejun Heo79bd9812013-11-22 18:20:42 -05004753
4754 fdput(cfile);
4755 fdput(efile);
4756
Tejun Heo451af502014-05-13 12:16:21 -04004757 return nbytes;
Tejun Heo79bd9812013-11-22 18:20:42 -05004758
4759out_put_css:
Tejun Heob5557c42013-11-22 18:20:42 -05004760 css_put(css);
Tejun Heo79bd9812013-11-22 18:20:42 -05004761out_put_cfile:
4762 fdput(cfile);
4763out_put_eventfd:
4764 eventfd_ctx_put(event->eventfd);
4765out_put_efile:
4766 fdput(efile);
4767out_kfree:
4768 kfree(event);
4769
4770 return ret;
4771}
4772
Johannes Weiner241994ed2015-02-11 15:26:06 -08004773static struct cftype mem_cgroup_legacy_files[] = {
Balbir Singh8cdea7c2008-02-07 00:13:50 -08004774 {
Balbir Singh0eea1032008-02-07 00:13:57 -08004775 .name = "usage_in_bytes",
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08004776 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
Tejun Heo791badb2013-12-05 12:28:02 -05004777 .read_u64 = mem_cgroup_read_u64,
Balbir Singh8cdea7c2008-02-07 00:13:50 -08004778 },
4779 {
Pavel Emelyanovc84872e2008-04-29 01:00:17 -07004780 .name = "max_usage_in_bytes",
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08004781 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
Tejun Heo6770c642014-05-13 12:16:21 -04004782 .write = mem_cgroup_reset,
Tejun Heo791badb2013-12-05 12:28:02 -05004783 .read_u64 = mem_cgroup_read_u64,
Pavel Emelyanovc84872e2008-04-29 01:00:17 -07004784 },
4785 {
Balbir Singh0eea1032008-02-07 00:13:57 -08004786 .name = "limit_in_bytes",
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08004787 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
Tejun Heo451af502014-05-13 12:16:21 -04004788 .write = mem_cgroup_write,
Tejun Heo791badb2013-12-05 12:28:02 -05004789 .read_u64 = mem_cgroup_read_u64,
Balbir Singh8cdea7c2008-02-07 00:13:50 -08004790 },
4791 {
Balbir Singh296c81d2009-09-23 15:56:36 -07004792 .name = "soft_limit_in_bytes",
4793 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
Tejun Heo451af502014-05-13 12:16:21 -04004794 .write = mem_cgroup_write,
Tejun Heo791badb2013-12-05 12:28:02 -05004795 .read_u64 = mem_cgroup_read_u64,
Balbir Singh296c81d2009-09-23 15:56:36 -07004796 },
4797 {
Balbir Singh8cdea7c2008-02-07 00:13:50 -08004798 .name = "failcnt",
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08004799 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
Tejun Heo6770c642014-05-13 12:16:21 -04004800 .write = mem_cgroup_reset,
Tejun Heo791badb2013-12-05 12:28:02 -05004801 .read_u64 = mem_cgroup_read_u64,
Balbir Singh8cdea7c2008-02-07 00:13:50 -08004802 },
Balbir Singh8697d332008-02-07 00:13:59 -08004803 {
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -08004804 .name = "stat",
Tejun Heo2da8ca82013-12-05 12:28:04 -05004805 .seq_show = memcg_stat_show,
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -08004806 },
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08004807 {
4808 .name = "force_empty",
Tejun Heo6770c642014-05-13 12:16:21 -04004809 .write = mem_cgroup_force_empty_write,
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08004810 },
Balbir Singh18f59ea2009-01-07 18:08:07 -08004811 {
4812 .name = "use_hierarchy",
4813 .write_u64 = mem_cgroup_hierarchy_write,
4814 .read_u64 = mem_cgroup_hierarchy_read,
4815 },
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08004816 {
Tejun Heo3bc942f2013-11-22 18:20:44 -05004817 .name = "cgroup.event_control", /* XXX: for compat */
Tejun Heo451af502014-05-13 12:16:21 -04004818 .write = memcg_write_event_control,
Tejun Heo7dbdb192015-09-18 17:54:23 -04004819 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
Tejun Heo79bd9812013-11-22 18:20:42 -05004820 },
4821 {
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08004822 .name = "swappiness",
4823 .read_u64 = mem_cgroup_swappiness_read,
4824 .write_u64 = mem_cgroup_swappiness_write,
4825 },
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08004826 {
4827 .name = "move_charge_at_immigrate",
4828 .read_u64 = mem_cgroup_move_charge_read,
4829 .write_u64 = mem_cgroup_move_charge_write,
4830 },
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004831 {
4832 .name = "oom_control",
Tejun Heo2da8ca82013-12-05 12:28:04 -05004833 .seq_show = mem_cgroup_oom_control_read,
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004834 .write_u64 = mem_cgroup_oom_control_write,
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004835 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4836 },
Anton Vorontsov70ddf632013-04-29 15:08:31 -07004837 {
4838 .name = "pressure_level",
Anton Vorontsov70ddf632013-04-29 15:08:31 -07004839 },
Ying Han406eb0c2011-05-26 16:25:37 -07004840#ifdef CONFIG_NUMA
4841 {
4842 .name = "numa_stat",
Tejun Heo2da8ca82013-12-05 12:28:04 -05004843 .seq_show = memcg_numa_stat_show,
Ying Han406eb0c2011-05-26 16:25:37 -07004844 },
4845#endif
Glauber Costa510fc4e2012-12-18 14:21:47 -08004846 {
4847 .name = "kmem.limit_in_bytes",
4848 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
Tejun Heo451af502014-05-13 12:16:21 -04004849 .write = mem_cgroup_write,
Tejun Heo791badb2013-12-05 12:28:02 -05004850 .read_u64 = mem_cgroup_read_u64,
Glauber Costa510fc4e2012-12-18 14:21:47 -08004851 },
4852 {
4853 .name = "kmem.usage_in_bytes",
4854 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
Tejun Heo791badb2013-12-05 12:28:02 -05004855 .read_u64 = mem_cgroup_read_u64,
Glauber Costa510fc4e2012-12-18 14:21:47 -08004856 },
4857 {
4858 .name = "kmem.failcnt",
4859 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
Tejun Heo6770c642014-05-13 12:16:21 -04004860 .write = mem_cgroup_reset,
Tejun Heo791badb2013-12-05 12:28:02 -05004861 .read_u64 = mem_cgroup_read_u64,
Glauber Costa510fc4e2012-12-18 14:21:47 -08004862 },
4863 {
4864 .name = "kmem.max_usage_in_bytes",
4865 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
Tejun Heo6770c642014-05-13 12:16:21 -04004866 .write = mem_cgroup_reset,
Tejun Heo791badb2013-12-05 12:28:02 -05004867 .read_u64 = mem_cgroup_read_u64,
Glauber Costa510fc4e2012-12-18 14:21:47 -08004868 },
Yang Shi5b365772017-11-15 17:32:03 -08004869#if defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)
Glauber Costa749c5412012-12-18 14:23:01 -08004870 {
4871 .name = "kmem.slabinfo",
Tejun Heobc2791f2017-02-22 15:41:21 -08004872 .seq_start = memcg_slab_start,
4873 .seq_next = memcg_slab_next,
4874 .seq_stop = memcg_slab_stop,
Vladimir Davydovb0475012014-12-10 15:44:19 -08004875 .seq_show = memcg_slab_show,
Glauber Costa749c5412012-12-18 14:23:01 -08004876 },
4877#endif
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08004878 {
4879 .name = "kmem.tcp.limit_in_bytes",
4880 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
4881 .write = mem_cgroup_write,
4882 .read_u64 = mem_cgroup_read_u64,
4883 },
4884 {
4885 .name = "kmem.tcp.usage_in_bytes",
4886 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
4887 .read_u64 = mem_cgroup_read_u64,
4888 },
4889 {
4890 .name = "kmem.tcp.failcnt",
4891 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
4892 .write = mem_cgroup_reset,
4893 .read_u64 = mem_cgroup_read_u64,
4894 },
4895 {
4896 .name = "kmem.tcp.max_usage_in_bytes",
4897 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
4898 .write = mem_cgroup_reset,
4899 .read_u64 = mem_cgroup_read_u64,
4900 },
Tejun Heo6bc10342012-04-01 12:09:55 -07004901 { }, /* terminate */
Tejun Heoaf36f902012-04-01 12:09:55 -07004902};
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08004903
Johannes Weiner73f576c2016-07-20 15:44:57 -07004904/*
4905 * Private memory cgroup IDR
4906 *
4907 * Swap-out records and page cache shadow entries need to store memcg
4908 * references in constrained space, so we maintain an ID space that is
4909 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
4910 * memory-controlled cgroups to 64k.
4911 *
4912 * However, there usually are many references to the oflline CSS after
4913 * the cgroup has been destroyed, such as page cache or reclaimable
4914 * slab objects, that don't need to hang on to the ID. We want to keep
4915 * those dead CSS from occupying IDs, or we might quickly exhaust the
4916 * relatively small ID space and prevent the creation of new cgroups
4917 * even when there are much fewer than 64k cgroups - possibly none.
4918 *
4919 * Maintain a private 16-bit ID space for memcg, and allow the ID to
4920 * be freed and recycled when it's no longer needed, which is usually
4921 * when the CSS is offlined.
4922 *
4923 * The only exception to that are records of swapped out tmpfs/shmem
4924 * pages that need to be attributed to live ancestors on swapin. But
4925 * those references are manageable from userspace.
4926 */
4927
4928static DEFINE_IDR(mem_cgroup_idr);
4929
Kirill Tkhai7e97de02018-08-02 15:36:01 -07004930static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
4931{
4932 if (memcg->id.id > 0) {
4933 idr_remove(&mem_cgroup_idr, memcg->id.id);
4934 memcg->id.id = 0;
4935 }
4936}
4937
Vladimir Davydov615d66c2016-08-11 15:33:03 -07004938static void mem_cgroup_id_get_many(struct mem_cgroup *memcg, unsigned int n)
Johannes Weiner73f576c2016-07-20 15:44:57 -07004939{
Kirill Tkhai1c2d4792018-10-26 15:09:28 -07004940 refcount_add(n, &memcg->id.ref);
Johannes Weiner73f576c2016-07-20 15:44:57 -07004941}
4942
Vladimir Davydov615d66c2016-08-11 15:33:03 -07004943static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
Johannes Weiner73f576c2016-07-20 15:44:57 -07004944{
Kirill Tkhai1c2d4792018-10-26 15:09:28 -07004945 if (refcount_sub_and_test(n, &memcg->id.ref)) {
Kirill Tkhai7e97de02018-08-02 15:36:01 -07004946 mem_cgroup_id_remove(memcg);
Johannes Weiner73f576c2016-07-20 15:44:57 -07004947
4948 /* Memcg ID pins CSS */
4949 css_put(&memcg->css);
4950 }
4951}
4952
Vladimir Davydov615d66c2016-08-11 15:33:03 -07004953static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
4954{
4955 mem_cgroup_id_put_many(memcg, 1);
4956}
4957
Johannes Weiner73f576c2016-07-20 15:44:57 -07004958/**
4959 * mem_cgroup_from_id - look up a memcg from a memcg id
4960 * @id: the memcg id to look up
4961 *
4962 * Caller must hold rcu_read_lock().
4963 */
4964struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
4965{
4966 WARN_ON_ONCE(!rcu_read_lock_held());
4967 return idr_find(&mem_cgroup_idr, id);
4968}
4969
Mel Gormanef8f2322016-07-28 15:46:05 -07004970static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08004971{
4972 struct mem_cgroup_per_node *pn;
Mel Gormanef8f2322016-07-28 15:46:05 -07004973 int tmp = node;
KAMEZAWA Hiroyuki1ecaab22008-02-07 00:14:38 -08004974 /*
4975 * This routine is called against possible nodes.
4976 * But it's BUG to call kmalloc() against offline node.
4977 *
4978 * TODO: this routine can waste much memory for nodes which will
4979 * never be onlined. It's better to use memory hotplug callback
4980 * function.
4981 */
KAMEZAWA Hiroyuki41e33552008-04-08 17:41:54 -07004982 if (!node_state(node, N_NORMAL_MEMORY))
4983 tmp = -1;
Jesper Juhl17295c82011-01-13 15:47:42 -08004984 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08004985 if (!pn)
4986 return 1;
KAMEZAWA Hiroyuki1ecaab22008-02-07 00:14:38 -08004987
Johannes Weiner815744d2019-06-13 15:55:46 -07004988 pn->lruvec_stat_local = alloc_percpu(struct lruvec_stat);
4989 if (!pn->lruvec_stat_local) {
4990 kfree(pn);
4991 return 1;
4992 }
4993
Johannes Weinera983b5e2018-01-31 16:16:45 -08004994 pn->lruvec_stat_cpu = alloc_percpu(struct lruvec_stat);
4995 if (!pn->lruvec_stat_cpu) {
Johannes Weiner815744d2019-06-13 15:55:46 -07004996 free_percpu(pn->lruvec_stat_local);
Johannes Weiner00f3ca22017-07-06 15:40:52 -07004997 kfree(pn);
4998 return 1;
4999 }
5000
Mel Gormanef8f2322016-07-28 15:46:05 -07005001 lruvec_init(&pn->lruvec);
5002 pn->usage_in_excess = 0;
5003 pn->on_tree = false;
5004 pn->memcg = memcg;
5005
Johannes Weiner54f72fe2013-07-08 15:59:49 -07005006 memcg->nodeinfo[node] = pn;
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08005007 return 0;
5008}
5009
Mel Gormanef8f2322016-07-28 15:46:05 -07005010static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
KAMEZAWA Hiroyuki1ecaab22008-02-07 00:14:38 -08005011{
Johannes Weiner00f3ca22017-07-06 15:40:52 -07005012 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5013
Michal Hocko4eaf4312018-04-10 16:29:52 -07005014 if (!pn)
5015 return;
5016
Johannes Weinera983b5e2018-01-31 16:16:45 -08005017 free_percpu(pn->lruvec_stat_cpu);
Johannes Weiner815744d2019-06-13 15:55:46 -07005018 free_percpu(pn->lruvec_stat_local);
Johannes Weiner00f3ca22017-07-06 15:40:52 -07005019 kfree(pn);
KAMEZAWA Hiroyuki1ecaab22008-02-07 00:14:38 -08005020}
5021
Tahsin Erdogan40e952f2017-03-09 16:17:26 -08005022static void __mem_cgroup_free(struct mem_cgroup *memcg)
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005023{
5024 int node;
5025
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005026 for_each_node(node)
Mel Gormanef8f2322016-07-28 15:46:05 -07005027 free_mem_cgroup_per_node_info(memcg, node);
Chris Down871789d2019-05-14 15:46:57 -07005028 free_percpu(memcg->vmstats_percpu);
Johannes Weiner815744d2019-06-13 15:55:46 -07005029 free_percpu(memcg->vmstats_local);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005030 kfree(memcg);
5031}
5032
Tahsin Erdogan40e952f2017-03-09 16:17:26 -08005033static void mem_cgroup_free(struct mem_cgroup *memcg)
5034{
5035 memcg_wb_domain_exit(memcg);
Shakeel Butt7961eee2019-11-05 21:16:21 -08005036 /*
5037 * Flush percpu vmstats and vmevents to guarantee the value correctness
5038 * on parent's and all ancestor levels.
5039 */
5040 memcg_flush_percpu_vmstats(memcg, false);
5041 memcg_flush_percpu_vmevents(memcg);
Tahsin Erdogan40e952f2017-03-09 16:17:26 -08005042 __mem_cgroup_free(memcg);
5043}
5044
KAMEZAWA Hiroyuki33327942008-04-29 01:00:24 -07005045static struct mem_cgroup *mem_cgroup_alloc(void)
5046{
Hugh Dickinsd79154b2012-03-21 16:34:18 -07005047 struct mem_cgroup *memcg;
Alexey Dobriyanb9726c22019-03-05 15:48:26 -08005048 unsigned int size;
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005049 int node;
Tejun Heo97b27822019-08-26 09:06:56 -07005050 int __maybe_unused i;
KAMEZAWA Hiroyuki33327942008-04-29 01:00:24 -07005051
Vladimir Davydov8ff69e22014-01-23 15:52:52 -08005052 size = sizeof(struct mem_cgroup);
5053 size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
KAMEZAWA Hiroyuki33327942008-04-29 01:00:24 -07005054
Vladimir Davydov8ff69e22014-01-23 15:52:52 -08005055 memcg = kzalloc(size, GFP_KERNEL);
Hugh Dickinsd79154b2012-03-21 16:34:18 -07005056 if (!memcg)
Dan Carpentere7bbcdf2010-03-23 13:35:12 -07005057 return NULL;
5058
Johannes Weiner73f576c2016-07-20 15:44:57 -07005059 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5060 1, MEM_CGROUP_ID_MAX,
5061 GFP_KERNEL);
5062 if (memcg->id.id < 0)
5063 goto fail;
5064
Johannes Weiner815744d2019-06-13 15:55:46 -07005065 memcg->vmstats_local = alloc_percpu(struct memcg_vmstats_percpu);
5066 if (!memcg->vmstats_local)
5067 goto fail;
5068
Chris Down871789d2019-05-14 15:46:57 -07005069 memcg->vmstats_percpu = alloc_percpu(struct memcg_vmstats_percpu);
5070 if (!memcg->vmstats_percpu)
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005071 goto fail;
Pavel Emelianov78fb7462008-02-07 00:13:51 -08005072
Bob Liu3ed28fa2012-01-12 17:19:04 -08005073 for_each_node(node)
Mel Gormanef8f2322016-07-28 15:46:05 -07005074 if (alloc_mem_cgroup_per_node_info(memcg, node))
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005075 goto fail;
Balbir Singhf64c3f52009-09-23 15:56:37 -07005076
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005077 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5078 goto fail;
Balbir Singh28dbc4b2009-01-07 18:08:05 -08005079
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08005080 INIT_WORK(&memcg->high_work, high_work_func);
Glauber Costad142e3e2013-02-22 16:34:52 -08005081 memcg->last_scanned_node = MAX_NUMNODES;
5082 INIT_LIST_HEAD(&memcg->oom_notify);
Glauber Costad142e3e2013-02-22 16:34:52 -08005083 mutex_init(&memcg->thresholds_lock);
5084 spin_lock_init(&memcg->move_lock);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005085 vmpressure_init(&memcg->vmpressure);
Tejun Heofba94802013-11-22 18:20:43 -05005086 INIT_LIST_HEAD(&memcg->event_list);
5087 spin_lock_init(&memcg->event_list_lock);
Johannes Weinerd886f4e2016-01-20 15:02:47 -08005088 memcg->socket_pressure = jiffies;
Kirill Tkhai84c07d12018-08-17 15:47:25 -07005089#ifdef CONFIG_MEMCG_KMEM
Vladimir Davydov900a38f2014-12-12 16:55:10 -08005090 memcg->kmemcg_id = -1;
Vladimir Davydov900a38f2014-12-12 16:55:10 -08005091#endif
Tejun Heo52ebea72015-05-22 17:13:37 -04005092#ifdef CONFIG_CGROUP_WRITEBACK
5093 INIT_LIST_HEAD(&memcg->cgwb_list);
Tejun Heo97b27822019-08-26 09:06:56 -07005094 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5095 memcg->cgwb_frn[i].done =
5096 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
Tejun Heo52ebea72015-05-22 17:13:37 -04005097#endif
Yang Shi87eaceb2019-09-23 15:38:15 -07005098#ifdef CONFIG_TRANSPARENT_HUGEPAGE
5099 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5100 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5101 memcg->deferred_split_queue.split_queue_len = 0;
5102#endif
Johannes Weiner73f576c2016-07-20 15:44:57 -07005103 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005104 return memcg;
5105fail:
Kirill Tkhai7e97de02018-08-02 15:36:01 -07005106 mem_cgroup_id_remove(memcg);
Tahsin Erdogan40e952f2017-03-09 16:17:26 -08005107 __mem_cgroup_free(memcg);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005108 return NULL;
Glauber Costad142e3e2013-02-22 16:34:52 -08005109}
5110
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005111static struct cgroup_subsys_state * __ref
5112mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
Glauber Costad142e3e2013-02-22 16:34:52 -08005113{
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005114 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5115 struct mem_cgroup *memcg;
5116 long error = -ENOMEM;
Glauber Costad142e3e2013-02-22 16:34:52 -08005117
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005118 memcg = mem_cgroup_alloc();
5119 if (!memcg)
5120 return ERR_PTR(error);
Li Zefan4219b2d2013-09-23 16:56:29 +08005121
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005122 memcg->high = PAGE_COUNTER_MAX;
5123 memcg->soft_limit = PAGE_COUNTER_MAX;
5124 if (parent) {
5125 memcg->swappiness = mem_cgroup_swappiness(parent);
5126 memcg->oom_kill_disable = parent->oom_kill_disable;
5127 }
5128 if (parent && parent->use_hierarchy) {
5129 memcg->use_hierarchy = true;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08005130 page_counter_init(&memcg->memory, &parent->memory);
Vladimir Davydov37e84352016-01-20 15:02:56 -08005131 page_counter_init(&memcg->swap, &parent->swap);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08005132 page_counter_init(&memcg->memsw, &parent->memsw);
5133 page_counter_init(&memcg->kmem, &parent->kmem);
Johannes Weiner0db15292016-01-20 15:02:50 -08005134 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
Balbir Singh18f59ea2009-01-07 18:08:07 -08005135 } else {
Johannes Weiner3e32cb22014-12-10 15:42:31 -08005136 page_counter_init(&memcg->memory, NULL);
Vladimir Davydov37e84352016-01-20 15:02:56 -08005137 page_counter_init(&memcg->swap, NULL);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08005138 page_counter_init(&memcg->memsw, NULL);
5139 page_counter_init(&memcg->kmem, NULL);
Johannes Weiner0db15292016-01-20 15:02:50 -08005140 page_counter_init(&memcg->tcpmem, NULL);
Tejun Heo8c7f6ed2012-09-13 12:20:58 -07005141 /*
5142 * Deeper hierachy with use_hierarchy == false doesn't make
5143 * much sense so let cgroup subsystem know about this
5144 * unfortunate state in our controller.
5145 */
Glauber Costad142e3e2013-02-22 16:34:52 -08005146 if (parent != root_mem_cgroup)
Tejun Heo073219e2014-02-08 10:36:58 -05005147 memory_cgrp_subsys.broken_hierarchy = true;
Balbir Singh18f59ea2009-01-07 18:08:07 -08005148 }
Vladimir Davydovd6441632014-01-23 15:53:09 -08005149
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005150 /* The following stuff does not apply to the root */
5151 if (!parent) {
Roman Gushchinfb2f2b02019-07-11 20:56:34 -07005152#ifdef CONFIG_MEMCG_KMEM
5153 INIT_LIST_HEAD(&memcg->kmem_caches);
5154#endif
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005155 root_mem_cgroup = memcg;
5156 return &memcg->css;
5157 }
5158
Vladimir Davydovb313aee2016-03-17 14:18:27 -07005159 error = memcg_online_kmem(memcg);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005160 if (error)
5161 goto fail;
Johannes Weiner127424c2016-01-20 15:02:32 -08005162
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08005163 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
Johannes Weineref129472016-01-14 15:21:34 -08005164 static_branch_inc(&memcg_sockets_enabled_key);
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08005165
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005166 return &memcg->css;
5167fail:
Kirill Tkhai7e97de02018-08-02 15:36:01 -07005168 mem_cgroup_id_remove(memcg);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005169 mem_cgroup_free(memcg);
Tejun Heoea3a9642016-06-24 14:49:58 -07005170 return ERR_PTR(-ENOMEM);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005171}
5172
Johannes Weiner73f576c2016-07-20 15:44:57 -07005173static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005174{
Vladimir Davydov58fa2a52016-10-07 16:57:29 -07005175 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5176
Kirill Tkhai0a4465d2018-08-17 15:47:37 -07005177 /*
5178 * A memcg must be visible for memcg_expand_shrinker_maps()
5179 * by the time the maps are allocated. So, we allocate maps
5180 * here, when for_each_mem_cgroup() can't skip it.
5181 */
5182 if (memcg_alloc_shrinker_maps(memcg)) {
5183 mem_cgroup_id_remove(memcg);
5184 return -ENOMEM;
5185 }
5186
Johannes Weiner73f576c2016-07-20 15:44:57 -07005187 /* Online state pins memcg ID, memcg ID pins CSS */
Kirill Tkhai1c2d4792018-10-26 15:09:28 -07005188 refcount_set(&memcg->id.ref, 1);
Johannes Weiner73f576c2016-07-20 15:44:57 -07005189 css_get(css);
Johannes Weiner2f7dd7a2014-10-02 16:16:57 -07005190 return 0;
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005191}
5192
Tejun Heoeb954192013-08-08 20:11:23 -04005193static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
KAMEZAWA Hiroyukidf878fb2008-02-07 00:14:28 -08005194{
Tejun Heoeb954192013-08-08 20:11:23 -04005195 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Tejun Heo3bc942f2013-11-22 18:20:44 -05005196 struct mem_cgroup_event *event, *tmp;
Tejun Heo79bd9812013-11-22 18:20:42 -05005197
5198 /*
5199 * Unregister events and notify userspace.
5200 * Notify userspace about cgroup removing only after rmdir of cgroup
5201 * directory to avoid race between userspace and kernelspace.
5202 */
Tejun Heofba94802013-11-22 18:20:43 -05005203 spin_lock(&memcg->event_list_lock);
5204 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
Tejun Heo79bd9812013-11-22 18:20:42 -05005205 list_del_init(&event->list);
5206 schedule_work(&event->remove);
5207 }
Tejun Heofba94802013-11-22 18:20:43 -05005208 spin_unlock(&memcg->event_list_lock);
KAMEZAWA Hiroyukiec64f512009-04-02 16:57:26 -07005209
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005210 page_counter_set_min(&memcg->memory, 0);
Roman Gushchin23067152018-06-07 17:06:22 -07005211 page_counter_set_low(&memcg->memory, 0);
Roman Gushchin63677c742017-09-06 16:21:47 -07005212
Johannes Weiner567e9ab2016-01-20 15:02:24 -08005213 memcg_offline_kmem(memcg);
Tejun Heo52ebea72015-05-22 17:13:37 -04005214 wb_memcg_offline(memcg);
Johannes Weiner73f576c2016-07-20 15:44:57 -07005215
Roman Gushchin591edfb2018-10-26 15:03:23 -07005216 drain_all_stock(memcg);
5217
Johannes Weiner73f576c2016-07-20 15:44:57 -07005218 mem_cgroup_id_put(memcg);
KAMEZAWA Hiroyukidf878fb2008-02-07 00:14:28 -08005219}
5220
Vladimir Davydov6df38682015-12-29 14:54:10 -08005221static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5222{
5223 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5224
5225 invalidate_reclaim_iterators(memcg);
5226}
5227
Tejun Heoeb954192013-08-08 20:11:23 -04005228static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005229{
Tejun Heoeb954192013-08-08 20:11:23 -04005230 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Tejun Heo97b27822019-08-26 09:06:56 -07005231 int __maybe_unused i;
Daisuke Nishimurac268e992009-01-15 13:51:13 -08005232
Tejun Heo97b27822019-08-26 09:06:56 -07005233#ifdef CONFIG_CGROUP_WRITEBACK
5234 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5235 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5236#endif
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08005237 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
Johannes Weineref129472016-01-14 15:21:34 -08005238 static_branch_dec(&memcg_sockets_enabled_key);
Johannes Weiner3893e302016-01-20 15:02:29 -08005239
Johannes Weiner0db15292016-01-20 15:02:50 -08005240 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08005241 static_branch_dec(&memcg_sockets_enabled_key);
Johannes Weiner3893e302016-01-20 15:02:29 -08005242
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005243 vmpressure_cleanup(&memcg->vmpressure);
5244 cancel_work_sync(&memcg->high_work);
5245 mem_cgroup_remove_from_trees(memcg);
Kirill Tkhai0a4465d2018-08-17 15:47:37 -07005246 memcg_free_shrinker_maps(memcg);
Johannes Weinerd886f4e2016-01-20 15:02:47 -08005247 memcg_free_kmem(memcg);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005248 mem_cgroup_free(memcg);
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005249}
5250
Tejun Heo1ced9532014-07-08 18:02:57 -04005251/**
5252 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5253 * @css: the target css
5254 *
5255 * Reset the states of the mem_cgroup associated with @css. This is
5256 * invoked when the userland requests disabling on the default hierarchy
5257 * but the memcg is pinned through dependency. The memcg should stop
5258 * applying policies and should revert to the vanilla state as it may be
5259 * made visible again.
5260 *
5261 * The current implementation only resets the essential configurations.
5262 * This needs to be expanded to cover all the visible parts.
5263 */
5264static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5265{
5266 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5267
Roman Gushchinbbec2e12018-06-07 17:06:18 -07005268 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5269 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5270 page_counter_set_max(&memcg->memsw, PAGE_COUNTER_MAX);
5271 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5272 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005273 page_counter_set_min(&memcg->memory, 0);
Roman Gushchin23067152018-06-07 17:06:22 -07005274 page_counter_set_low(&memcg->memory, 0);
Johannes Weiner241994ed2015-02-11 15:26:06 -08005275 memcg->high = PAGE_COUNTER_MAX;
Johannes Weiner24d404d2015-01-08 14:32:35 -08005276 memcg->soft_limit = PAGE_COUNTER_MAX;
Tejun Heo2529bb32015-05-22 18:23:34 -04005277 memcg_wb_domain_size_changed(memcg);
Tejun Heo1ced9532014-07-08 18:02:57 -04005278}
5279
Daisuke Nishimura02491442010-03-10 15:22:17 -08005280#ifdef CONFIG_MMU
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005281/* Handlers for move charge at task migration. */
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005282static int mem_cgroup_do_precharge(unsigned long count)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005283{
Johannes Weiner05b84302014-08-06 16:05:59 -07005284 int ret;
Johannes Weiner9476db92014-08-06 16:05:55 -07005285
Mel Gormand0164ad2015-11-06 16:28:21 -08005286 /* Try a single bulk charge without reclaim first, kswapd may wake */
5287 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
Johannes Weiner9476db92014-08-06 16:05:55 -07005288 if (!ret) {
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005289 mc.precharge += count;
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005290 return ret;
5291 }
Johannes Weiner9476db92014-08-06 16:05:55 -07005292
David Rientjes36745342017-01-24 15:18:10 -08005293 /* Try charges one by one with reclaim, but do not retry */
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005294 while (count--) {
David Rientjes36745342017-01-24 15:18:10 -08005295 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
KAMEZAWA Hiroyuki38c5d722012-01-12 17:19:01 -08005296 if (ret)
KAMEZAWA Hiroyuki38c5d722012-01-12 17:19:01 -08005297 return ret;
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005298 mc.precharge++;
Johannes Weiner9476db92014-08-06 16:05:55 -07005299 cond_resched();
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005300 }
Johannes Weiner9476db92014-08-06 16:05:55 -07005301 return 0;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005302}
5303
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005304union mc_target {
5305 struct page *page;
Daisuke Nishimura02491442010-03-10 15:22:17 -08005306 swp_entry_t ent;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005307};
5308
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005309enum mc_target_type {
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07005310 MC_TARGET_NONE = 0,
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005311 MC_TARGET_PAGE,
Daisuke Nishimura02491442010-03-10 15:22:17 -08005312 MC_TARGET_SWAP,
Jérôme Glissec733a822017-09-08 16:11:54 -07005313 MC_TARGET_DEVICE,
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005314};
5315
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005316static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5317 unsigned long addr, pte_t ptent)
5318{
Christoph Hellwig25b29952019-06-13 22:50:49 +02005319 struct page *page = vm_normal_page(vma, addr, ptent);
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005320
5321 if (!page || !page_mapped(page))
5322 return NULL;
5323 if (PageAnon(page)) {
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08005324 if (!(mc.flags & MOVE_ANON))
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005325 return NULL;
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08005326 } else {
5327 if (!(mc.flags & MOVE_FILE))
5328 return NULL;
5329 }
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005330 if (!get_page_unless_zero(page))
5331 return NULL;
5332
5333 return page;
5334}
5335
Jérôme Glissec733a822017-09-08 16:11:54 -07005336#if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005337static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
Li RongQing48406ef2016-07-26 15:22:14 -07005338 pte_t ptent, swp_entry_t *entry)
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005339{
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005340 struct page *page = NULL;
5341 swp_entry_t ent = pte_to_swp_entry(ptent);
5342
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08005343 if (!(mc.flags & MOVE_ANON) || non_swap_entry(ent))
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005344 return NULL;
Jérôme Glissec733a822017-09-08 16:11:54 -07005345
5346 /*
5347 * Handle MEMORY_DEVICE_PRIVATE which are ZONE_DEVICE page belonging to
5348 * a device and because they are not accessible by CPU they are store
5349 * as special swap entry in the CPU page table.
5350 */
5351 if (is_device_private_entry(ent)) {
5352 page = device_private_entry_to_page(ent);
5353 /*
5354 * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have
5355 * a refcount of 1 when free (unlike normal page)
5356 */
5357 if (!page_ref_add_unless(page, 1, 1))
5358 return NULL;
5359 return page;
5360 }
5361
KAMEZAWA Hiroyuki4b913552012-05-29 15:06:51 -07005362 /*
5363 * Because lookup_swap_cache() updates some statistics counter,
5364 * we call find_get_page() with swapper_space directly.
5365 */
Huang Yingf6ab1f72016-10-07 17:00:21 -07005366 page = find_get_page(swap_address_space(ent), swp_offset(ent));
Johannes Weiner7941d212016-01-14 15:21:23 -08005367 if (do_memsw_account())
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005368 entry->val = ent.val;
5369
5370 return page;
5371}
KAMEZAWA Hiroyuki4b913552012-05-29 15:06:51 -07005372#else
5373static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
Li RongQing48406ef2016-07-26 15:22:14 -07005374 pte_t ptent, swp_entry_t *entry)
KAMEZAWA Hiroyuki4b913552012-05-29 15:06:51 -07005375{
5376 return NULL;
5377}
5378#endif
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005379
Daisuke Nishimura87946a72010-05-26 14:42:39 -07005380static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5381 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5382{
5383 struct page *page = NULL;
Daisuke Nishimura87946a72010-05-26 14:42:39 -07005384 struct address_space *mapping;
5385 pgoff_t pgoff;
5386
5387 if (!vma->vm_file) /* anonymous vma */
5388 return NULL;
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08005389 if (!(mc.flags & MOVE_FILE))
Daisuke Nishimura87946a72010-05-26 14:42:39 -07005390 return NULL;
5391
Daisuke Nishimura87946a72010-05-26 14:42:39 -07005392 mapping = vma->vm_file->f_mapping;
Kirill A. Shutemov0661a332015-02-10 14:10:04 -08005393 pgoff = linear_page_index(vma, addr);
Daisuke Nishimura87946a72010-05-26 14:42:39 -07005394
5395 /* page is moved even if it's not RSS of this task(page-faulted). */
Hugh Dickinsaa3b1892011-08-03 16:21:24 -07005396#ifdef CONFIG_SWAP
5397 /* shmem/tmpfs may report page out on swap: account for that too. */
Johannes Weiner139b6a62014-05-06 12:50:05 -07005398 if (shmem_mapping(mapping)) {
5399 page = find_get_entry(mapping, pgoff);
Matthew Wilcox3159f942017-11-03 13:30:42 -04005400 if (xa_is_value(page)) {
Johannes Weiner139b6a62014-05-06 12:50:05 -07005401 swp_entry_t swp = radix_to_swp_entry(page);
Johannes Weiner7941d212016-01-14 15:21:23 -08005402 if (do_memsw_account())
Johannes Weiner139b6a62014-05-06 12:50:05 -07005403 *entry = swp;
Huang Yingf6ab1f72016-10-07 17:00:21 -07005404 page = find_get_page(swap_address_space(swp),
5405 swp_offset(swp));
Johannes Weiner139b6a62014-05-06 12:50:05 -07005406 }
5407 } else
5408 page = find_get_page(mapping, pgoff);
5409#else
5410 page = find_get_page(mapping, pgoff);
Hugh Dickinsaa3b1892011-08-03 16:21:24 -07005411#endif
Daisuke Nishimura87946a72010-05-26 14:42:39 -07005412 return page;
5413}
5414
Chen Gangb1b0dea2015-04-14 15:47:35 -07005415/**
5416 * mem_cgroup_move_account - move account of the page
5417 * @page: the page
Li RongQing25843c22016-07-26 15:26:56 -07005418 * @compound: charge the page as compound or small page
Chen Gangb1b0dea2015-04-14 15:47:35 -07005419 * @from: mem_cgroup which the page is moved from.
5420 * @to: mem_cgroup which the page is moved to. @from != @to.
5421 *
Kirill A. Shutemov3ac808f2016-01-15 16:53:07 -08005422 * The caller must make sure the page is not on LRU (isolate_page() is useful.)
Chen Gangb1b0dea2015-04-14 15:47:35 -07005423 *
5424 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5425 * from old cgroup.
5426 */
5427static int mem_cgroup_move_account(struct page *page,
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08005428 bool compound,
Chen Gangb1b0dea2015-04-14 15:47:35 -07005429 struct mem_cgroup *from,
5430 struct mem_cgroup *to)
5431{
Konstantin Khlebnikovae8af432019-10-18 20:20:11 -07005432 struct lruvec *from_vec, *to_vec;
5433 struct pglist_data *pgdat;
Chen Gangb1b0dea2015-04-14 15:47:35 -07005434 unsigned long flags;
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08005435 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
Chen Gangb1b0dea2015-04-14 15:47:35 -07005436 int ret;
Greg Thelenc4843a72015-05-22 17:13:16 -04005437 bool anon;
Chen Gangb1b0dea2015-04-14 15:47:35 -07005438
5439 VM_BUG_ON(from == to);
5440 VM_BUG_ON_PAGE(PageLRU(page), page);
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08005441 VM_BUG_ON(compound && !PageTransHuge(page));
Chen Gangb1b0dea2015-04-14 15:47:35 -07005442
5443 /*
Johannes Weiner6a93ca82016-03-15 14:57:19 -07005444 * Prevent mem_cgroup_migrate() from looking at
Hugh Dickins45637ba2015-11-05 18:49:40 -08005445 * page->mem_cgroup of its source page while we change it.
Chen Gangb1b0dea2015-04-14 15:47:35 -07005446 */
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08005447 ret = -EBUSY;
Chen Gangb1b0dea2015-04-14 15:47:35 -07005448 if (!trylock_page(page))
5449 goto out;
5450
5451 ret = -EINVAL;
5452 if (page->mem_cgroup != from)
5453 goto out_unlock;
5454
Greg Thelenc4843a72015-05-22 17:13:16 -04005455 anon = PageAnon(page);
5456
Konstantin Khlebnikovae8af432019-10-18 20:20:11 -07005457 pgdat = page_pgdat(page);
5458 from_vec = mem_cgroup_lruvec(pgdat, from);
5459 to_vec = mem_cgroup_lruvec(pgdat, to);
5460
Chen Gangb1b0dea2015-04-14 15:47:35 -07005461 spin_lock_irqsave(&from->move_lock, flags);
5462
Greg Thelenc4843a72015-05-22 17:13:16 -04005463 if (!anon && page_mapped(page)) {
Konstantin Khlebnikovae8af432019-10-18 20:20:11 -07005464 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5465 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
Chen Gangb1b0dea2015-04-14 15:47:35 -07005466 }
5467
Greg Thelenc4843a72015-05-22 17:13:16 -04005468 /*
5469 * move_lock grabbed above and caller set from->moving_account, so
Johannes Weinerccda7f42017-05-03 14:55:16 -07005470 * mod_memcg_page_state will serialize updates to PageDirty.
Greg Thelenc4843a72015-05-22 17:13:16 -04005471 * So mapping should be stable for dirty pages.
5472 */
5473 if (!anon && PageDirty(page)) {
5474 struct address_space *mapping = page_mapping(page);
5475
5476 if (mapping_cap_account_dirty(mapping)) {
Konstantin Khlebnikovae8af432019-10-18 20:20:11 -07005477 __mod_lruvec_state(from_vec, NR_FILE_DIRTY, -nr_pages);
5478 __mod_lruvec_state(to_vec, NR_FILE_DIRTY, nr_pages);
Greg Thelenc4843a72015-05-22 17:13:16 -04005479 }
5480 }
5481
Chen Gangb1b0dea2015-04-14 15:47:35 -07005482 if (PageWriteback(page)) {
Konstantin Khlebnikovae8af432019-10-18 20:20:11 -07005483 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5484 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
Chen Gangb1b0dea2015-04-14 15:47:35 -07005485 }
5486
Yang Shi87eaceb2019-09-23 15:38:15 -07005487#ifdef CONFIG_TRANSPARENT_HUGEPAGE
5488 if (compound && !list_empty(page_deferred_list(page))) {
5489 spin_lock(&from->deferred_split_queue.split_queue_lock);
5490 list_del_init(page_deferred_list(page));
5491 from->deferred_split_queue.split_queue_len--;
5492 spin_unlock(&from->deferred_split_queue.split_queue_lock);
5493 }
5494#endif
Chen Gangb1b0dea2015-04-14 15:47:35 -07005495 /*
5496 * It is safe to change page->mem_cgroup here because the page
5497 * is referenced, charged, and isolated - we can't race with
5498 * uncharging, charging, migration, or LRU putback.
5499 */
5500
5501 /* caller should have done css_get */
5502 page->mem_cgroup = to;
Yang Shi87eaceb2019-09-23 15:38:15 -07005503
5504#ifdef CONFIG_TRANSPARENT_HUGEPAGE
5505 if (compound && list_empty(page_deferred_list(page))) {
5506 spin_lock(&to->deferred_split_queue.split_queue_lock);
5507 list_add_tail(page_deferred_list(page),
5508 &to->deferred_split_queue.split_queue);
5509 to->deferred_split_queue.split_queue_len++;
5510 spin_unlock(&to->deferred_split_queue.split_queue_lock);
5511 }
5512#endif
5513
Chen Gangb1b0dea2015-04-14 15:47:35 -07005514 spin_unlock_irqrestore(&from->move_lock, flags);
5515
5516 ret = 0;
5517
5518 local_irq_disable();
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08005519 mem_cgroup_charge_statistics(to, page, compound, nr_pages);
Chen Gangb1b0dea2015-04-14 15:47:35 -07005520 memcg_check_events(to, page);
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08005521 mem_cgroup_charge_statistics(from, page, compound, -nr_pages);
Chen Gangb1b0dea2015-04-14 15:47:35 -07005522 memcg_check_events(from, page);
5523 local_irq_enable();
5524out_unlock:
5525 unlock_page(page);
5526out:
5527 return ret;
5528}
5529
Li RongQing7cf78062016-05-27 14:27:46 -07005530/**
5531 * get_mctgt_type - get target type of moving charge
5532 * @vma: the vma the pte to be checked belongs
5533 * @addr: the address corresponding to the pte to be checked
5534 * @ptent: the pte to be checked
5535 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5536 *
5537 * Returns
5538 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5539 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5540 * move charge. if @target is not NULL, the page is stored in target->page
5541 * with extra refcnt got(Callers should handle it).
5542 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5543 * target for charge migration. if @target is not NULL, the entry is stored
5544 * in target->ent.
Christoph Hellwig25b29952019-06-13 22:50:49 +02005545 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is MEMORY_DEVICE_PRIVATE
5546 * (so ZONE_DEVICE page and thus not on the lru).
Jérôme Glissedf6ad692017-09-08 16:12:24 -07005547 * For now we such page is charge like a regular page would be as for all
5548 * intent and purposes it is just special memory taking the place of a
5549 * regular page.
Jérôme Glissec733a822017-09-08 16:11:54 -07005550 *
5551 * See Documentations/vm/hmm.txt and include/linux/hmm.h
Li RongQing7cf78062016-05-27 14:27:46 -07005552 *
5553 * Called with pte lock held.
5554 */
5555
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07005556static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005557 unsigned long addr, pte_t ptent, union mc_target *target)
5558{
Daisuke Nishimura02491442010-03-10 15:22:17 -08005559 struct page *page = NULL;
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07005560 enum mc_target_type ret = MC_TARGET_NONE;
Daisuke Nishimura02491442010-03-10 15:22:17 -08005561 swp_entry_t ent = { .val = 0 };
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005562
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005563 if (pte_present(ptent))
5564 page = mc_handle_present_pte(vma, addr, ptent);
5565 else if (is_swap_pte(ptent))
Li RongQing48406ef2016-07-26 15:22:14 -07005566 page = mc_handle_swap_pte(vma, ptent, &ent);
Kirill A. Shutemov0661a332015-02-10 14:10:04 -08005567 else if (pte_none(ptent))
Daisuke Nishimura87946a72010-05-26 14:42:39 -07005568 page = mc_handle_file_pte(vma, addr, ptent, &ent);
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005569
5570 if (!page && !ent.val)
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07005571 return ret;
Daisuke Nishimura02491442010-03-10 15:22:17 -08005572 if (page) {
Daisuke Nishimura02491442010-03-10 15:22:17 -08005573 /*
Johannes Weiner0a31bc92014-08-08 14:19:22 -07005574 * Do only loose check w/o serialization.
Johannes Weiner1306a852014-12-10 15:44:52 -08005575 * mem_cgroup_move_account() checks the page is valid or
Johannes Weiner0a31bc92014-08-08 14:19:22 -07005576 * not under LRU exclusion.
Daisuke Nishimura02491442010-03-10 15:22:17 -08005577 */
Johannes Weiner1306a852014-12-10 15:44:52 -08005578 if (page->mem_cgroup == mc.from) {
Daisuke Nishimura02491442010-03-10 15:22:17 -08005579 ret = MC_TARGET_PAGE;
Christoph Hellwig25b29952019-06-13 22:50:49 +02005580 if (is_device_private_page(page))
Jérôme Glissec733a822017-09-08 16:11:54 -07005581 ret = MC_TARGET_DEVICE;
Daisuke Nishimura02491442010-03-10 15:22:17 -08005582 if (target)
5583 target->page = page;
5584 }
5585 if (!ret || !target)
5586 put_page(page);
5587 }
Huang Ying3e14a572017-09-06 16:22:37 -07005588 /*
5589 * There is a swap entry and a page doesn't exist or isn't charged.
5590 * But we cannot move a tail-page in a THP.
5591 */
5592 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
Li Zefan34c00c32013-09-23 16:56:01 +08005593 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
KAMEZAWA Hiroyuki7f0f1542010-05-11 14:06:58 -07005594 ret = MC_TARGET_SWAP;
5595 if (target)
5596 target->ent = ent;
Daisuke Nishimura02491442010-03-10 15:22:17 -08005597 }
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005598 return ret;
5599}
5600
Naoya Horiguchi12724852012-03-21 16:34:28 -07005601#ifdef CONFIG_TRANSPARENT_HUGEPAGE
5602/*
Huang Yingd6810d72017-09-06 16:22:45 -07005603 * We don't consider PMD mapped swapping or file mapped pages because THP does
5604 * not support them for now.
Naoya Horiguchi12724852012-03-21 16:34:28 -07005605 * Caller should make sure that pmd_trans_huge(pmd) is true.
5606 */
5607static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5608 unsigned long addr, pmd_t pmd, union mc_target *target)
5609{
5610 struct page *page = NULL;
Naoya Horiguchi12724852012-03-21 16:34:28 -07005611 enum mc_target_type ret = MC_TARGET_NONE;
5612
Zi Yan84c3fc42017-09-08 16:11:01 -07005613 if (unlikely(is_swap_pmd(pmd))) {
5614 VM_BUG_ON(thp_migration_supported() &&
5615 !is_pmd_migration_entry(pmd));
5616 return ret;
5617 }
Naoya Horiguchi12724852012-03-21 16:34:28 -07005618 page = pmd_page(pmd);
Sasha Levin309381fea2014-01-23 15:52:54 -08005619 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08005620 if (!(mc.flags & MOVE_ANON))
Naoya Horiguchi12724852012-03-21 16:34:28 -07005621 return ret;
Johannes Weiner1306a852014-12-10 15:44:52 -08005622 if (page->mem_cgroup == mc.from) {
Naoya Horiguchi12724852012-03-21 16:34:28 -07005623 ret = MC_TARGET_PAGE;
5624 if (target) {
5625 get_page(page);
5626 target->page = page;
5627 }
5628 }
5629 return ret;
5630}
5631#else
5632static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5633 unsigned long addr, pmd_t pmd, union mc_target *target)
5634{
5635 return MC_TARGET_NONE;
5636}
5637#endif
5638
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005639static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5640 unsigned long addr, unsigned long end,
5641 struct mm_walk *walk)
5642{
Naoya Horiguchi26bcd642015-02-11 15:27:57 -08005643 struct vm_area_struct *vma = walk->vma;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005644 pte_t *pte;
5645 spinlock_t *ptl;
5646
Kirill A. Shutemovb6ec57f2016-01-21 16:40:25 -08005647 ptl = pmd_trans_huge_lock(pmd, vma);
5648 if (ptl) {
Jérôme Glissec733a822017-09-08 16:11:54 -07005649 /*
5650 * Note their can not be MC_TARGET_DEVICE for now as we do not
Christoph Hellwig25b29952019-06-13 22:50:49 +02005651 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5652 * this might change.
Jérôme Glissec733a822017-09-08 16:11:54 -07005653 */
Naoya Horiguchi12724852012-03-21 16:34:28 -07005654 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5655 mc.precharge += HPAGE_PMD_NR;
Kirill A. Shutemovbf929152013-11-14 14:30:54 -08005656 spin_unlock(ptl);
Andrea Arcangeli1a5a9902012-03-21 16:33:42 -07005657 return 0;
Naoya Horiguchi12724852012-03-21 16:34:28 -07005658 }
Dave Hansen03319322011-03-22 16:32:56 -07005659
Andrea Arcangeli45f83ce2012-03-28 14:42:40 -07005660 if (pmd_trans_unstable(pmd))
5661 return 0;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005662 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5663 for (; addr != end; pte++, addr += PAGE_SIZE)
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07005664 if (get_mctgt_type(vma, addr, *pte, NULL))
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005665 mc.precharge++; /* increment precharge temporarily */
5666 pte_unmap_unlock(pte - 1, ptl);
5667 cond_resched();
5668
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005669 return 0;
5670}
5671
Christoph Hellwig7b86ac32019-08-28 16:19:54 +02005672static const struct mm_walk_ops precharge_walk_ops = {
5673 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5674};
5675
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005676static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5677{
5678 unsigned long precharge;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005679
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08005680 down_read(&mm->mmap_sem);
Christoph Hellwig7b86ac32019-08-28 16:19:54 +02005681 walk_page_range(mm, 0, mm->highest_vm_end, &precharge_walk_ops, NULL);
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08005682 up_read(&mm->mmap_sem);
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005683
5684 precharge = mc.precharge;
5685 mc.precharge = 0;
5686
5687 return precharge;
5688}
5689
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005690static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5691{
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08005692 unsigned long precharge = mem_cgroup_count_precharge(mm);
5693
5694 VM_BUG_ON(mc.moving_task);
5695 mc.moving_task = current;
5696 return mem_cgroup_do_precharge(precharge);
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005697}
5698
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08005699/* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5700static void __mem_cgroup_clear_mc(void)
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005701{
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07005702 struct mem_cgroup *from = mc.from;
5703 struct mem_cgroup *to = mc.to;
5704
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005705 /* we must uncharge all the leftover precharges from mc.to */
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005706 if (mc.precharge) {
Johannes Weiner00501b52014-08-08 14:19:20 -07005707 cancel_charge(mc.to, mc.precharge);
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005708 mc.precharge = 0;
5709 }
5710 /*
5711 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5712 * we must uncharge here.
5713 */
5714 if (mc.moved_charge) {
Johannes Weiner00501b52014-08-08 14:19:20 -07005715 cancel_charge(mc.from, mc.moved_charge);
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005716 mc.moved_charge = 0;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005717 }
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08005718 /* we must fixup refcnts and charges */
5719 if (mc.moved_swap) {
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08005720 /* uncharge swap account from the old cgroup */
Johannes Weinerce00a962014-09-05 08:43:57 -04005721 if (!mem_cgroup_is_root(mc.from))
Johannes Weiner3e32cb22014-12-10 15:42:31 -08005722 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08005723
Vladimir Davydov615d66c2016-08-11 15:33:03 -07005724 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
5725
Johannes Weiner05b84302014-08-06 16:05:59 -07005726 /*
Johannes Weiner3e32cb22014-12-10 15:42:31 -08005727 * we charged both to->memory and to->memsw, so we
5728 * should uncharge to->memory.
Johannes Weiner05b84302014-08-06 16:05:59 -07005729 */
Johannes Weinerce00a962014-09-05 08:43:57 -04005730 if (!mem_cgroup_is_root(mc.to))
Johannes Weiner3e32cb22014-12-10 15:42:31 -08005731 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08005732
Vladimir Davydov615d66c2016-08-11 15:33:03 -07005733 mem_cgroup_id_get_many(mc.to, mc.moved_swap);
5734 css_put_many(&mc.to->css, mc.moved_swap);
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08005735
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08005736 mc.moved_swap = 0;
5737 }
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08005738 memcg_oom_recover(from);
5739 memcg_oom_recover(to);
5740 wake_up_all(&mc.waitq);
5741}
5742
5743static void mem_cgroup_clear_mc(void)
5744{
Tejun Heo264a0ae2016-04-21 19:09:02 -04005745 struct mm_struct *mm = mc.mm;
5746
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08005747 /*
5748 * we must clear moving_task before waking up waiters at the end of
5749 * task migration.
5750 */
5751 mc.moving_task = NULL;
5752 __mem_cgroup_clear_mc();
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07005753 spin_lock(&mc.lock);
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005754 mc.from = NULL;
5755 mc.to = NULL;
Tejun Heo264a0ae2016-04-21 19:09:02 -04005756 mc.mm = NULL;
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07005757 spin_unlock(&mc.lock);
Tejun Heo264a0ae2016-04-21 19:09:02 -04005758
5759 mmput(mm);
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005760}
5761
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05005762static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005763{
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05005764 struct cgroup_subsys_state *css;
Ross Zwislereed67d72015-12-23 14:53:27 -07005765 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
Tejun Heo9f2115f2015-09-08 15:01:10 -07005766 struct mem_cgroup *from;
Tejun Heo4530edd2015-09-11 15:00:19 -04005767 struct task_struct *leader, *p;
Tejun Heo9f2115f2015-09-08 15:01:10 -07005768 struct mm_struct *mm;
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08005769 unsigned long move_flags;
Tejun Heo9f2115f2015-09-08 15:01:10 -07005770 int ret = 0;
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005771
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05005772 /* charge immigration isn't supported on the default hierarchy */
5773 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo9f2115f2015-09-08 15:01:10 -07005774 return 0;
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005775
Tejun Heo4530edd2015-09-11 15:00:19 -04005776 /*
5777 * Multi-process migrations only happen on the default hierarchy
5778 * where charge immigration is not used. Perform charge
5779 * immigration if @tset contains a leader and whine if there are
5780 * multiple.
5781 */
5782 p = NULL;
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05005783 cgroup_taskset_for_each_leader(leader, css, tset) {
Tejun Heo4530edd2015-09-11 15:00:19 -04005784 WARN_ON_ONCE(p);
5785 p = leader;
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05005786 memcg = mem_cgroup_from_css(css);
Tejun Heo4530edd2015-09-11 15:00:19 -04005787 }
5788 if (!p)
5789 return 0;
5790
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05005791 /*
5792 * We are now commited to this value whatever it is. Changes in this
5793 * tunable will only affect upcoming migrations, not the current one.
5794 * So we need to save it, and keep it going.
5795 */
5796 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
5797 if (!move_flags)
5798 return 0;
5799
Tejun Heo9f2115f2015-09-08 15:01:10 -07005800 from = mem_cgroup_from_task(p);
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005801
Tejun Heo9f2115f2015-09-08 15:01:10 -07005802 VM_BUG_ON(from == memcg);
Johannes Weiner247b1442014-12-10 15:44:11 -08005803
Tejun Heo9f2115f2015-09-08 15:01:10 -07005804 mm = get_task_mm(p);
5805 if (!mm)
5806 return 0;
5807 /* We move charges only when we move a owner of the mm */
5808 if (mm->owner == p) {
5809 VM_BUG_ON(mc.from);
5810 VM_BUG_ON(mc.to);
5811 VM_BUG_ON(mc.precharge);
5812 VM_BUG_ON(mc.moved_charge);
5813 VM_BUG_ON(mc.moved_swap);
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005814
Tejun Heo9f2115f2015-09-08 15:01:10 -07005815 spin_lock(&mc.lock);
Tejun Heo264a0ae2016-04-21 19:09:02 -04005816 mc.mm = mm;
Tejun Heo9f2115f2015-09-08 15:01:10 -07005817 mc.from = from;
5818 mc.to = memcg;
5819 mc.flags = move_flags;
5820 spin_unlock(&mc.lock);
5821 /* We set mc.moving_task later */
5822
5823 ret = mem_cgroup_precharge_mc(mm);
5824 if (ret)
5825 mem_cgroup_clear_mc();
Tejun Heo264a0ae2016-04-21 19:09:02 -04005826 } else {
5827 mmput(mm);
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005828 }
5829 return ret;
5830}
5831
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05005832static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005833{
Johannes Weiner4e2f2452014-12-10 15:44:08 -08005834 if (mc.to)
5835 mem_cgroup_clear_mc();
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005836}
5837
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005838static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5839 unsigned long addr, unsigned long end,
5840 struct mm_walk *walk)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005841{
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005842 int ret = 0;
Naoya Horiguchi26bcd642015-02-11 15:27:57 -08005843 struct vm_area_struct *vma = walk->vma;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005844 pte_t *pte;
5845 spinlock_t *ptl;
Naoya Horiguchi12724852012-03-21 16:34:28 -07005846 enum mc_target_type target_type;
5847 union mc_target target;
5848 struct page *page;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005849
Kirill A. Shutemovb6ec57f2016-01-21 16:40:25 -08005850 ptl = pmd_trans_huge_lock(pmd, vma);
5851 if (ptl) {
Hugh Dickins62ade862012-05-18 11:28:34 -07005852 if (mc.precharge < HPAGE_PMD_NR) {
Kirill A. Shutemovbf929152013-11-14 14:30:54 -08005853 spin_unlock(ptl);
Naoya Horiguchi12724852012-03-21 16:34:28 -07005854 return 0;
5855 }
5856 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
5857 if (target_type == MC_TARGET_PAGE) {
5858 page = target.page;
5859 if (!isolate_lru_page(page)) {
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08005860 if (!mem_cgroup_move_account(page, true,
Johannes Weiner1306a852014-12-10 15:44:52 -08005861 mc.from, mc.to)) {
Naoya Horiguchi12724852012-03-21 16:34:28 -07005862 mc.precharge -= HPAGE_PMD_NR;
5863 mc.moved_charge += HPAGE_PMD_NR;
5864 }
5865 putback_lru_page(page);
5866 }
5867 put_page(page);
Jérôme Glissec733a822017-09-08 16:11:54 -07005868 } else if (target_type == MC_TARGET_DEVICE) {
5869 page = target.page;
5870 if (!mem_cgroup_move_account(page, true,
5871 mc.from, mc.to)) {
5872 mc.precharge -= HPAGE_PMD_NR;
5873 mc.moved_charge += HPAGE_PMD_NR;
5874 }
5875 put_page(page);
Naoya Horiguchi12724852012-03-21 16:34:28 -07005876 }
Kirill A. Shutemovbf929152013-11-14 14:30:54 -08005877 spin_unlock(ptl);
Andrea Arcangeli1a5a9902012-03-21 16:33:42 -07005878 return 0;
Naoya Horiguchi12724852012-03-21 16:34:28 -07005879 }
5880
Andrea Arcangeli45f83ce2012-03-28 14:42:40 -07005881 if (pmd_trans_unstable(pmd))
5882 return 0;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005883retry:
5884 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5885 for (; addr != end; addr += PAGE_SIZE) {
5886 pte_t ptent = *(pte++);
Jérôme Glissec733a822017-09-08 16:11:54 -07005887 bool device = false;
Daisuke Nishimura02491442010-03-10 15:22:17 -08005888 swp_entry_t ent;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005889
5890 if (!mc.precharge)
5891 break;
5892
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07005893 switch (get_mctgt_type(vma, addr, ptent, &target)) {
Jérôme Glissec733a822017-09-08 16:11:54 -07005894 case MC_TARGET_DEVICE:
5895 device = true;
5896 /* fall through */
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005897 case MC_TARGET_PAGE:
5898 page = target.page;
Kirill A. Shutemov53f92632016-01-15 16:53:42 -08005899 /*
5900 * We can have a part of the split pmd here. Moving it
5901 * can be done but it would be too convoluted so simply
5902 * ignore such a partial THP and keep it in original
5903 * memcg. There should be somebody mapping the head.
5904 */
5905 if (PageTransCompound(page))
5906 goto put;
Jérôme Glissec733a822017-09-08 16:11:54 -07005907 if (!device && isolate_lru_page(page))
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005908 goto put;
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08005909 if (!mem_cgroup_move_account(page, false,
5910 mc.from, mc.to)) {
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005911 mc.precharge--;
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005912 /* we uncharge from mc.from later. */
5913 mc.moved_charge++;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005914 }
Jérôme Glissec733a822017-09-08 16:11:54 -07005915 if (!device)
5916 putback_lru_page(page);
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07005917put: /* get_mctgt_type() gets the page */
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005918 put_page(page);
5919 break;
Daisuke Nishimura02491442010-03-10 15:22:17 -08005920 case MC_TARGET_SWAP:
5921 ent = target.ent;
Hugh Dickinse91cbb42012-05-29 15:06:51 -07005922 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
Daisuke Nishimura02491442010-03-10 15:22:17 -08005923 mc.precharge--;
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08005924 /* we fixup refcnts and charges later. */
5925 mc.moved_swap++;
5926 }
Daisuke Nishimura02491442010-03-10 15:22:17 -08005927 break;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005928 default:
5929 break;
5930 }
5931 }
5932 pte_unmap_unlock(pte - 1, ptl);
5933 cond_resched();
5934
5935 if (addr != end) {
5936 /*
5937 * We have consumed all precharges we got in can_attach().
5938 * We try charge one by one, but don't do any additional
5939 * charges to mc.to if we have failed in charge once in attach()
5940 * phase.
5941 */
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005942 ret = mem_cgroup_do_precharge(1);
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005943 if (!ret)
5944 goto retry;
5945 }
5946
5947 return ret;
5948}
5949
Christoph Hellwig7b86ac32019-08-28 16:19:54 +02005950static const struct mm_walk_ops charge_walk_ops = {
5951 .pmd_entry = mem_cgroup_move_charge_pte_range,
5952};
5953
Tejun Heo264a0ae2016-04-21 19:09:02 -04005954static void mem_cgroup_move_charge(void)
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005955{
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005956 lru_add_drain_all();
Johannes Weiner312722c2014-12-10 15:44:25 -08005957 /*
Johannes Weiner81f8c3a2016-03-15 14:57:04 -07005958 * Signal lock_page_memcg() to take the memcg's move_lock
5959 * while we're moving its pages to another memcg. Then wait
5960 * for already started RCU-only updates to finish.
Johannes Weiner312722c2014-12-10 15:44:25 -08005961 */
5962 atomic_inc(&mc.from->moving_account);
5963 synchronize_rcu();
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08005964retry:
Tejun Heo264a0ae2016-04-21 19:09:02 -04005965 if (unlikely(!down_read_trylock(&mc.mm->mmap_sem))) {
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08005966 /*
5967 * Someone who are holding the mmap_sem might be waiting in
5968 * waitq. So we cancel all extra charges, wake up all waiters,
5969 * and retry. Because we cancel precharges, we might not be able
5970 * to move enough charges, but moving charge is a best-effort
5971 * feature anyway, so it wouldn't be a big problem.
5972 */
5973 __mem_cgroup_clear_mc();
5974 cond_resched();
5975 goto retry;
5976 }
Naoya Horiguchi26bcd642015-02-11 15:27:57 -08005977 /*
5978 * When we have consumed all precharges and failed in doing
5979 * additional charge, the page walk just aborts.
5980 */
Christoph Hellwig7b86ac32019-08-28 16:19:54 +02005981 walk_page_range(mc.mm, 0, mc.mm->highest_vm_end, &charge_walk_ops,
5982 NULL);
James Morse0247f3f2016-10-07 17:00:12 -07005983
Tejun Heo264a0ae2016-04-21 19:09:02 -04005984 up_read(&mc.mm->mmap_sem);
Johannes Weiner312722c2014-12-10 15:44:25 -08005985 atomic_dec(&mc.from->moving_account);
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005986}
5987
Tejun Heo264a0ae2016-04-21 19:09:02 -04005988static void mem_cgroup_move_task(void)
Balbir Singh67e465a2008-02-07 00:13:54 -08005989{
Tejun Heo264a0ae2016-04-21 19:09:02 -04005990 if (mc.to) {
5991 mem_cgroup_move_charge();
KOSAKI Motohiroa4336582011-06-15 15:08:13 -07005992 mem_cgroup_clear_mc();
Tejun Heo264a0ae2016-04-21 19:09:02 -04005993 }
Balbir Singh67e465a2008-02-07 00:13:54 -08005994}
Daisuke Nishimura5cfb80a2010-03-23 13:35:11 -07005995#else /* !CONFIG_MMU */
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05005996static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
Daisuke Nishimura5cfb80a2010-03-23 13:35:11 -07005997{
5998 return 0;
5999}
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006000static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
Daisuke Nishimura5cfb80a2010-03-23 13:35:11 -07006001{
6002}
Tejun Heo264a0ae2016-04-21 19:09:02 -04006003static void mem_cgroup_move_task(void)
Daisuke Nishimura5cfb80a2010-03-23 13:35:11 -07006004{
6005}
6006#endif
Balbir Singh67e465a2008-02-07 00:13:54 -08006007
Tejun Heof00baae2013-04-15 13:41:15 -07006008/*
6009 * Cgroup retains root cgroups across [un]mount cycles making it necessary
Tejun Heoaa6ec292014-07-09 10:08:08 -04006010 * to verify whether we're attached to the default hierarchy on each mount
6011 * attempt.
Tejun Heof00baae2013-04-15 13:41:15 -07006012 */
Tejun Heoeb954192013-08-08 20:11:23 -04006013static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
Tejun Heof00baae2013-04-15 13:41:15 -07006014{
6015 /*
Tejun Heoaa6ec292014-07-09 10:08:08 -04006016 * use_hierarchy is forced on the default hierarchy. cgroup core
Tejun Heof00baae2013-04-15 13:41:15 -07006017 * guarantees that @root doesn't have any children, so turning it
6018 * on for the root memcg is enough.
6019 */
Tejun Heo9e10a132015-09-18 11:56:28 -04006020 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Vladimir Davydov7feee5902015-03-12 16:26:19 -07006021 root_mem_cgroup->use_hierarchy = true;
6022 else
6023 root_mem_cgroup->use_hierarchy = false;
Tejun Heof00baae2013-04-15 13:41:15 -07006024}
6025
Chris Down677dc972019-03-05 15:45:55 -08006026static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6027{
6028 if (value == PAGE_COUNTER_MAX)
6029 seq_puts(m, "max\n");
6030 else
6031 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6032
6033 return 0;
6034}
6035
Johannes Weiner241994ed2015-02-11 15:26:06 -08006036static u64 memory_current_read(struct cgroup_subsys_state *css,
6037 struct cftype *cft)
6038{
Johannes Weinerf5fc3c5d2015-11-05 18:50:23 -08006039 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6040
6041 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006042}
6043
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006044static int memory_min_show(struct seq_file *m, void *v)
6045{
Chris Down677dc972019-03-05 15:45:55 -08006046 return seq_puts_memcg_tunable(m,
6047 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006048}
6049
6050static ssize_t memory_min_write(struct kernfs_open_file *of,
6051 char *buf, size_t nbytes, loff_t off)
6052{
6053 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6054 unsigned long min;
6055 int err;
6056
6057 buf = strstrip(buf);
6058 err = page_counter_memparse(buf, "max", &min);
6059 if (err)
6060 return err;
6061
6062 page_counter_set_min(&memcg->memory, min);
6063
6064 return nbytes;
6065}
6066
Johannes Weiner241994ed2015-02-11 15:26:06 -08006067static int memory_low_show(struct seq_file *m, void *v)
6068{
Chris Down677dc972019-03-05 15:45:55 -08006069 return seq_puts_memcg_tunable(m,
6070 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
Johannes Weiner241994ed2015-02-11 15:26:06 -08006071}
6072
6073static ssize_t memory_low_write(struct kernfs_open_file *of,
6074 char *buf, size_t nbytes, loff_t off)
6075{
6076 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6077 unsigned long low;
6078 int err;
6079
6080 buf = strstrip(buf);
Johannes Weinerd2973692015-02-27 15:52:04 -08006081 err = page_counter_memparse(buf, "max", &low);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006082 if (err)
6083 return err;
6084
Roman Gushchin23067152018-06-07 17:06:22 -07006085 page_counter_set_low(&memcg->memory, low);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006086
6087 return nbytes;
6088}
6089
6090static int memory_high_show(struct seq_file *m, void *v)
6091{
Chris Down677dc972019-03-05 15:45:55 -08006092 return seq_puts_memcg_tunable(m, READ_ONCE(mem_cgroup_from_seq(m)->high));
Johannes Weiner241994ed2015-02-11 15:26:06 -08006093}
6094
6095static ssize_t memory_high_write(struct kernfs_open_file *of,
6096 char *buf, size_t nbytes, loff_t off)
6097{
6098 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
Johannes Weiner588083b2016-03-17 14:20:25 -07006099 unsigned long nr_pages;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006100 unsigned long high;
6101 int err;
6102
6103 buf = strstrip(buf);
Johannes Weinerd2973692015-02-27 15:52:04 -08006104 err = page_counter_memparse(buf, "max", &high);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006105 if (err)
6106 return err;
6107
6108 memcg->high = high;
6109
Johannes Weiner588083b2016-03-17 14:20:25 -07006110 nr_pages = page_counter_read(&memcg->memory);
6111 if (nr_pages > high)
6112 try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6113 GFP_KERNEL, true);
6114
Tejun Heo2529bb32015-05-22 18:23:34 -04006115 memcg_wb_domain_size_changed(memcg);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006116 return nbytes;
6117}
6118
6119static int memory_max_show(struct seq_file *m, void *v)
6120{
Chris Down677dc972019-03-05 15:45:55 -08006121 return seq_puts_memcg_tunable(m,
6122 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
Johannes Weiner241994ed2015-02-11 15:26:06 -08006123}
6124
6125static ssize_t memory_max_write(struct kernfs_open_file *of,
6126 char *buf, size_t nbytes, loff_t off)
6127{
6128 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
Johannes Weinerb6e6edc2016-03-17 14:20:28 -07006129 unsigned int nr_reclaims = MEM_CGROUP_RECLAIM_RETRIES;
6130 bool drained = false;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006131 unsigned long max;
6132 int err;
6133
6134 buf = strstrip(buf);
Johannes Weinerd2973692015-02-27 15:52:04 -08006135 err = page_counter_memparse(buf, "max", &max);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006136 if (err)
6137 return err;
6138
Roman Gushchinbbec2e12018-06-07 17:06:18 -07006139 xchg(&memcg->memory.max, max);
Johannes Weinerb6e6edc2016-03-17 14:20:28 -07006140
6141 for (;;) {
6142 unsigned long nr_pages = page_counter_read(&memcg->memory);
6143
6144 if (nr_pages <= max)
6145 break;
6146
6147 if (signal_pending(current)) {
6148 err = -EINTR;
6149 break;
6150 }
6151
6152 if (!drained) {
6153 drain_all_stock(memcg);
6154 drained = true;
6155 continue;
6156 }
6157
6158 if (nr_reclaims) {
6159 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6160 GFP_KERNEL, true))
6161 nr_reclaims--;
6162 continue;
6163 }
6164
Johannes Weinere27be242018-04-10 16:29:45 -07006165 memcg_memory_event(memcg, MEMCG_OOM);
Johannes Weinerb6e6edc2016-03-17 14:20:28 -07006166 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6167 break;
6168 }
Johannes Weiner241994ed2015-02-11 15:26:06 -08006169
Tejun Heo2529bb32015-05-22 18:23:34 -04006170 memcg_wb_domain_size_changed(memcg);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006171 return nbytes;
6172}
6173
Shakeel Butt1e577f92019-07-11 20:55:55 -07006174static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6175{
6176 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6177 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6178 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6179 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6180 seq_printf(m, "oom_kill %lu\n",
6181 atomic_long_read(&events[MEMCG_OOM_KILL]));
6182}
6183
Johannes Weiner241994ed2015-02-11 15:26:06 -08006184static int memory_events_show(struct seq_file *m, void *v)
6185{
Chris Downaa9694b2019-03-05 15:45:52 -08006186 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006187
Shakeel Butt1e577f92019-07-11 20:55:55 -07006188 __memory_events_show(m, memcg->memory_events);
6189 return 0;
6190}
Johannes Weiner241994ed2015-02-11 15:26:06 -08006191
Shakeel Butt1e577f92019-07-11 20:55:55 -07006192static int memory_events_local_show(struct seq_file *m, void *v)
6193{
6194 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6195
6196 __memory_events_show(m, memcg->memory_events_local);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006197 return 0;
6198}
6199
Johannes Weiner587d9f72016-01-20 15:03:19 -08006200static int memory_stat_show(struct seq_file *m, void *v)
6201{
Chris Downaa9694b2019-03-05 15:45:52 -08006202 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
Johannes Weinerc8713d02019-07-11 20:55:59 -07006203 char *buf;
Johannes Weiner587d9f72016-01-20 15:03:19 -08006204
Johannes Weinerc8713d02019-07-11 20:55:59 -07006205 buf = memory_stat_format(memcg);
6206 if (!buf)
6207 return -ENOMEM;
6208 seq_puts(m, buf);
6209 kfree(buf);
Johannes Weiner587d9f72016-01-20 15:03:19 -08006210 return 0;
6211}
6212
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07006213static int memory_oom_group_show(struct seq_file *m, void *v)
6214{
Chris Downaa9694b2019-03-05 15:45:52 -08006215 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07006216
6217 seq_printf(m, "%d\n", memcg->oom_group);
6218
6219 return 0;
6220}
6221
6222static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6223 char *buf, size_t nbytes, loff_t off)
6224{
6225 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6226 int ret, oom_group;
6227
6228 buf = strstrip(buf);
6229 if (!buf)
6230 return -EINVAL;
6231
6232 ret = kstrtoint(buf, 0, &oom_group);
6233 if (ret)
6234 return ret;
6235
6236 if (oom_group != 0 && oom_group != 1)
6237 return -EINVAL;
6238
6239 memcg->oom_group = oom_group;
6240
6241 return nbytes;
6242}
6243
Johannes Weiner241994ed2015-02-11 15:26:06 -08006244static struct cftype memory_files[] = {
6245 {
6246 .name = "current",
Johannes Weinerf5fc3c5d2015-11-05 18:50:23 -08006247 .flags = CFTYPE_NOT_ON_ROOT,
Johannes Weiner241994ed2015-02-11 15:26:06 -08006248 .read_u64 = memory_current_read,
6249 },
6250 {
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006251 .name = "min",
6252 .flags = CFTYPE_NOT_ON_ROOT,
6253 .seq_show = memory_min_show,
6254 .write = memory_min_write,
6255 },
6256 {
Johannes Weiner241994ed2015-02-11 15:26:06 -08006257 .name = "low",
6258 .flags = CFTYPE_NOT_ON_ROOT,
6259 .seq_show = memory_low_show,
6260 .write = memory_low_write,
6261 },
6262 {
6263 .name = "high",
6264 .flags = CFTYPE_NOT_ON_ROOT,
6265 .seq_show = memory_high_show,
6266 .write = memory_high_write,
6267 },
6268 {
6269 .name = "max",
6270 .flags = CFTYPE_NOT_ON_ROOT,
6271 .seq_show = memory_max_show,
6272 .write = memory_max_write,
6273 },
6274 {
6275 .name = "events",
6276 .flags = CFTYPE_NOT_ON_ROOT,
Tejun Heo472912a2015-09-18 18:01:59 -04006277 .file_offset = offsetof(struct mem_cgroup, events_file),
Johannes Weiner241994ed2015-02-11 15:26:06 -08006278 .seq_show = memory_events_show,
6279 },
Johannes Weiner587d9f72016-01-20 15:03:19 -08006280 {
Shakeel Butt1e577f92019-07-11 20:55:55 -07006281 .name = "events.local",
6282 .flags = CFTYPE_NOT_ON_ROOT,
6283 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6284 .seq_show = memory_events_local_show,
6285 },
6286 {
Johannes Weiner587d9f72016-01-20 15:03:19 -08006287 .name = "stat",
6288 .flags = CFTYPE_NOT_ON_ROOT,
6289 .seq_show = memory_stat_show,
6290 },
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07006291 {
6292 .name = "oom.group",
6293 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6294 .seq_show = memory_oom_group_show,
6295 .write = memory_oom_group_write,
6296 },
Johannes Weiner241994ed2015-02-11 15:26:06 -08006297 { } /* terminate */
6298};
6299
Tejun Heo073219e2014-02-08 10:36:58 -05006300struct cgroup_subsys memory_cgrp_subsys = {
Tejun Heo92fb9742012-11-19 08:13:38 -08006301 .css_alloc = mem_cgroup_css_alloc,
Glauber Costad142e3e2013-02-22 16:34:52 -08006302 .css_online = mem_cgroup_css_online,
Tejun Heo92fb9742012-11-19 08:13:38 -08006303 .css_offline = mem_cgroup_css_offline,
Vladimir Davydov6df38682015-12-29 14:54:10 -08006304 .css_released = mem_cgroup_css_released,
Tejun Heo92fb9742012-11-19 08:13:38 -08006305 .css_free = mem_cgroup_css_free,
Tejun Heo1ced9532014-07-08 18:02:57 -04006306 .css_reset = mem_cgroup_css_reset,
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006307 .can_attach = mem_cgroup_can_attach,
6308 .cancel_attach = mem_cgroup_cancel_attach,
Tejun Heo264a0ae2016-04-21 19:09:02 -04006309 .post_attach = mem_cgroup_move_task,
Tejun Heof00baae2013-04-15 13:41:15 -07006310 .bind = mem_cgroup_bind,
Johannes Weiner241994ed2015-02-11 15:26:06 -08006311 .dfl_cftypes = memory_files,
6312 .legacy_cftypes = mem_cgroup_legacy_files,
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08006313 .early_init = 0,
Balbir Singh8cdea7c2008-02-07 00:13:50 -08006314};
KAMEZAWA Hiroyukic0777192009-01-07 18:07:57 -08006315
Johannes Weiner241994ed2015-02-11 15:26:06 -08006316/**
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006317 * mem_cgroup_protected - check if memory consumption is in the normal range
Sean Christopherson34c81052017-07-10 15:48:05 -07006318 * @root: the top ancestor of the sub-tree being checked
Johannes Weiner241994ed2015-02-11 15:26:06 -08006319 * @memcg: the memory cgroup to check
6320 *
Roman Gushchin23067152018-06-07 17:06:22 -07006321 * WARNING: This function is not stateless! It can only be used as part
6322 * of a top-down tree iteration, not for isolated queries.
Sean Christopherson34c81052017-07-10 15:48:05 -07006323 *
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006324 * Returns one of the following:
6325 * MEMCG_PROT_NONE: cgroup memory is not protected
6326 * MEMCG_PROT_LOW: cgroup memory is protected as long there is
6327 * an unprotected supply of reclaimable memory from other cgroups.
6328 * MEMCG_PROT_MIN: cgroup memory is protected
Sean Christopherson34c81052017-07-10 15:48:05 -07006329 *
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006330 * @root is exclusive; it is never protected when looked at directly
Sean Christopherson34c81052017-07-10 15:48:05 -07006331 *
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006332 * To provide a proper hierarchical behavior, effective memory.min/low values
6333 * are used. Below is the description of how effective memory.low is calculated.
6334 * Effective memory.min values is calculated in the same way.
Sean Christopherson34c81052017-07-10 15:48:05 -07006335 *
Roman Gushchin23067152018-06-07 17:06:22 -07006336 * Effective memory.low is always equal or less than the original memory.low.
6337 * If there is no memory.low overcommittment (which is always true for
6338 * top-level memory cgroups), these two values are equal.
6339 * Otherwise, it's a part of parent's effective memory.low,
6340 * calculated as a cgroup's memory.low usage divided by sum of sibling's
6341 * memory.low usages, where memory.low usage is the size of actually
6342 * protected memory.
Sean Christopherson34c81052017-07-10 15:48:05 -07006343 *
Roman Gushchin23067152018-06-07 17:06:22 -07006344 * low_usage
6345 * elow = min( memory.low, parent->elow * ------------------ ),
6346 * siblings_low_usage
Sean Christopherson34c81052017-07-10 15:48:05 -07006347 *
Roman Gushchin23067152018-06-07 17:06:22 -07006348 * | memory.current, if memory.current < memory.low
6349 * low_usage = |
Qian Cai82ede7e2019-03-05 15:49:53 -08006350 * | 0, otherwise.
Sean Christopherson34c81052017-07-10 15:48:05 -07006351 *
Roman Gushchin23067152018-06-07 17:06:22 -07006352 *
6353 * Such definition of the effective memory.low provides the expected
6354 * hierarchical behavior: parent's memory.low value is limiting
6355 * children, unprotected memory is reclaimed first and cgroups,
6356 * which are not using their guarantee do not affect actual memory
6357 * distribution.
6358 *
6359 * For example, if there are memcgs A, A/B, A/C, A/D and A/E:
6360 *
6361 * A A/memory.low = 2G, A/memory.current = 6G
6362 * //\\
6363 * BC DE B/memory.low = 3G B/memory.current = 2G
6364 * C/memory.low = 1G C/memory.current = 2G
6365 * D/memory.low = 0 D/memory.current = 2G
6366 * E/memory.low = 10G E/memory.current = 0
6367 *
6368 * and the memory pressure is applied, the following memory distribution
6369 * is expected (approximately):
6370 *
6371 * A/memory.current = 2G
6372 *
6373 * B/memory.current = 1.3G
6374 * C/memory.current = 0.6G
6375 * D/memory.current = 0
6376 * E/memory.current = 0
6377 *
6378 * These calculations require constant tracking of the actual low usages
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006379 * (see propagate_protected_usage()), as well as recursive calculation of
6380 * effective memory.low values. But as we do call mem_cgroup_protected()
Roman Gushchin23067152018-06-07 17:06:22 -07006381 * path for each memory cgroup top-down from the reclaim,
6382 * it's possible to optimize this part, and save calculated elow
6383 * for next usage. This part is intentionally racy, but it's ok,
6384 * as memory.low is a best-effort mechanism.
Johannes Weiner241994ed2015-02-11 15:26:06 -08006385 */
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006386enum mem_cgroup_protection mem_cgroup_protected(struct mem_cgroup *root,
6387 struct mem_cgroup *memcg)
Johannes Weiner241994ed2015-02-11 15:26:06 -08006388{
Roman Gushchin23067152018-06-07 17:06:22 -07006389 struct mem_cgroup *parent;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006390 unsigned long emin, parent_emin;
6391 unsigned long elow, parent_elow;
6392 unsigned long usage;
Roman Gushchin23067152018-06-07 17:06:22 -07006393
Johannes Weiner241994ed2015-02-11 15:26:06 -08006394 if (mem_cgroup_disabled())
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006395 return MEMCG_PROT_NONE;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006396
Sean Christopherson34c81052017-07-10 15:48:05 -07006397 if (!root)
6398 root = root_mem_cgroup;
6399 if (memcg == root)
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006400 return MEMCG_PROT_NONE;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006401
Roman Gushchin23067152018-06-07 17:06:22 -07006402 usage = page_counter_read(&memcg->memory);
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006403 if (!usage)
6404 return MEMCG_PROT_NONE;
Sean Christopherson34c81052017-07-10 15:48:05 -07006405
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006406 emin = memcg->memory.min;
6407 elow = memcg->memory.low;
6408
6409 parent = parent_mem_cgroup(memcg);
Roman Gushchindf2a4192018-06-14 15:26:17 -07006410 /* No parent means a non-hierarchical mode on v1 memcg */
6411 if (!parent)
6412 return MEMCG_PROT_NONE;
6413
Roman Gushchin23067152018-06-07 17:06:22 -07006414 if (parent == root)
6415 goto exit;
6416
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006417 parent_emin = READ_ONCE(parent->memory.emin);
6418 emin = min(emin, parent_emin);
6419 if (emin && parent_emin) {
6420 unsigned long min_usage, siblings_min_usage;
6421
6422 min_usage = min(usage, memcg->memory.min);
6423 siblings_min_usage = atomic_long_read(
6424 &parent->memory.children_min_usage);
6425
6426 if (min_usage && siblings_min_usage)
6427 emin = min(emin, parent_emin * min_usage /
6428 siblings_min_usage);
6429 }
6430
Roman Gushchin23067152018-06-07 17:06:22 -07006431 parent_elow = READ_ONCE(parent->memory.elow);
6432 elow = min(elow, parent_elow);
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006433 if (elow && parent_elow) {
6434 unsigned long low_usage, siblings_low_usage;
Roman Gushchin23067152018-06-07 17:06:22 -07006435
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006436 low_usage = min(usage, memcg->memory.low);
6437 siblings_low_usage = atomic_long_read(
6438 &parent->memory.children_low_usage);
Roman Gushchin23067152018-06-07 17:06:22 -07006439
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006440 if (low_usage && siblings_low_usage)
6441 elow = min(elow, parent_elow * low_usage /
6442 siblings_low_usage);
6443 }
Roman Gushchin23067152018-06-07 17:06:22 -07006444
Roman Gushchin23067152018-06-07 17:06:22 -07006445exit:
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006446 memcg->memory.emin = emin;
Roman Gushchin23067152018-06-07 17:06:22 -07006447 memcg->memory.elow = elow;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006448
6449 if (usage <= emin)
6450 return MEMCG_PROT_MIN;
6451 else if (usage <= elow)
6452 return MEMCG_PROT_LOW;
6453 else
6454 return MEMCG_PROT_NONE;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006455}
6456
Johannes Weiner00501b52014-08-08 14:19:20 -07006457/**
6458 * mem_cgroup_try_charge - try charging a page
6459 * @page: page to charge
6460 * @mm: mm context of the victim
6461 * @gfp_mask: reclaim mode
6462 * @memcgp: charged memcg return
Li RongQing25843c22016-07-26 15:26:56 -07006463 * @compound: charge the page as compound or small page
Johannes Weiner00501b52014-08-08 14:19:20 -07006464 *
6465 * Try to charge @page to the memcg that @mm belongs to, reclaiming
6466 * pages according to @gfp_mask if necessary.
6467 *
6468 * Returns 0 on success, with *@memcgp pointing to the charged memcg.
6469 * Otherwise, an error code is returned.
6470 *
6471 * After page->mapping has been set up, the caller must finalize the
6472 * charge with mem_cgroup_commit_charge(). Or abort the transaction
6473 * with mem_cgroup_cancel_charge() in case page instantiation fails.
6474 */
6475int mem_cgroup_try_charge(struct page *page, struct mm_struct *mm,
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08006476 gfp_t gfp_mask, struct mem_cgroup **memcgp,
6477 bool compound)
Johannes Weiner00501b52014-08-08 14:19:20 -07006478{
6479 struct mem_cgroup *memcg = NULL;
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08006480 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
Johannes Weiner00501b52014-08-08 14:19:20 -07006481 int ret = 0;
6482
6483 if (mem_cgroup_disabled())
6484 goto out;
6485
6486 if (PageSwapCache(page)) {
Johannes Weiner00501b52014-08-08 14:19:20 -07006487 /*
6488 * Every swap fault against a single page tries to charge the
6489 * page, bail as early as possible. shmem_unuse() encounters
6490 * already charged pages, too. The USED bit is protected by
6491 * the page lock, which serializes swap cache removal, which
6492 * in turn serializes uncharging.
6493 */
Vladimir Davydove993d902015-09-09 15:35:35 -07006494 VM_BUG_ON_PAGE(!PageLocked(page), page);
Huang Yingabe28952017-09-06 16:22:41 -07006495 if (compound_head(page)->mem_cgroup)
Johannes Weiner00501b52014-08-08 14:19:20 -07006496 goto out;
Vladimir Davydove993d902015-09-09 15:35:35 -07006497
Vladimir Davydov37e84352016-01-20 15:02:56 -08006498 if (do_swap_account) {
Vladimir Davydove993d902015-09-09 15:35:35 -07006499 swp_entry_t ent = { .val = page_private(page), };
6500 unsigned short id = lookup_swap_cgroup_id(ent);
6501
6502 rcu_read_lock();
6503 memcg = mem_cgroup_from_id(id);
6504 if (memcg && !css_tryget_online(&memcg->css))
6505 memcg = NULL;
6506 rcu_read_unlock();
6507 }
Johannes Weiner00501b52014-08-08 14:19:20 -07006508 }
6509
Johannes Weiner00501b52014-08-08 14:19:20 -07006510 if (!memcg)
6511 memcg = get_mem_cgroup_from_mm(mm);
6512
6513 ret = try_charge(memcg, gfp_mask, nr_pages);
6514
6515 css_put(&memcg->css);
Johannes Weiner00501b52014-08-08 14:19:20 -07006516out:
6517 *memcgp = memcg;
6518 return ret;
6519}
6520
Tejun Heo2cf85582018-07-03 11:14:56 -04006521int mem_cgroup_try_charge_delay(struct page *page, struct mm_struct *mm,
6522 gfp_t gfp_mask, struct mem_cgroup **memcgp,
6523 bool compound)
6524{
6525 struct mem_cgroup *memcg;
6526 int ret;
6527
6528 ret = mem_cgroup_try_charge(page, mm, gfp_mask, memcgp, compound);
6529 memcg = *memcgp;
6530 mem_cgroup_throttle_swaprate(memcg, page_to_nid(page), gfp_mask);
6531 return ret;
6532}
6533
Johannes Weiner00501b52014-08-08 14:19:20 -07006534/**
6535 * mem_cgroup_commit_charge - commit a page charge
6536 * @page: page to charge
6537 * @memcg: memcg to charge the page to
6538 * @lrucare: page might be on LRU already
Li RongQing25843c22016-07-26 15:26:56 -07006539 * @compound: charge the page as compound or small page
Johannes Weiner00501b52014-08-08 14:19:20 -07006540 *
6541 * Finalize a charge transaction started by mem_cgroup_try_charge(),
6542 * after page->mapping has been set up. This must happen atomically
6543 * as part of the page instantiation, i.e. under the page table lock
6544 * for anonymous pages, under the page lock for page and swap cache.
6545 *
6546 * In addition, the page must not be on the LRU during the commit, to
6547 * prevent racing with task migration. If it might be, use @lrucare.
6548 *
6549 * Use mem_cgroup_cancel_charge() to cancel the transaction instead.
6550 */
6551void mem_cgroup_commit_charge(struct page *page, struct mem_cgroup *memcg,
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08006552 bool lrucare, bool compound)
Johannes Weiner00501b52014-08-08 14:19:20 -07006553{
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08006554 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
Johannes Weiner00501b52014-08-08 14:19:20 -07006555
6556 VM_BUG_ON_PAGE(!page->mapping, page);
6557 VM_BUG_ON_PAGE(PageLRU(page) && !lrucare, page);
6558
6559 if (mem_cgroup_disabled())
6560 return;
6561 /*
6562 * Swap faults will attempt to charge the same page multiple
6563 * times. But reuse_swap_page() might have removed the page
6564 * from swapcache already, so we can't check PageSwapCache().
6565 */
6566 if (!memcg)
6567 return;
6568
Johannes Weiner6abb5a82014-08-08 14:19:33 -07006569 commit_charge(page, memcg, lrucare);
6570
Johannes Weiner6abb5a82014-08-08 14:19:33 -07006571 local_irq_disable();
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08006572 mem_cgroup_charge_statistics(memcg, page, compound, nr_pages);
Johannes Weiner6abb5a82014-08-08 14:19:33 -07006573 memcg_check_events(memcg, page);
6574 local_irq_enable();
Johannes Weiner00501b52014-08-08 14:19:20 -07006575
Johannes Weiner7941d212016-01-14 15:21:23 -08006576 if (do_memsw_account() && PageSwapCache(page)) {
Johannes Weiner00501b52014-08-08 14:19:20 -07006577 swp_entry_t entry = { .val = page_private(page) };
6578 /*
6579 * The swap entry might not get freed for a long time,
6580 * let's not wait for it. The page already received a
6581 * memory+swap charge, drop the swap entry duplicate.
6582 */
Huang Ying38d8b4e2017-07-06 15:37:18 -07006583 mem_cgroup_uncharge_swap(entry, nr_pages);
Johannes Weiner00501b52014-08-08 14:19:20 -07006584 }
6585}
6586
6587/**
6588 * mem_cgroup_cancel_charge - cancel a page charge
6589 * @page: page to charge
6590 * @memcg: memcg to charge the page to
Li RongQing25843c22016-07-26 15:26:56 -07006591 * @compound: charge the page as compound or small page
Johannes Weiner00501b52014-08-08 14:19:20 -07006592 *
6593 * Cancel a charge transaction started by mem_cgroup_try_charge().
6594 */
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08006595void mem_cgroup_cancel_charge(struct page *page, struct mem_cgroup *memcg,
6596 bool compound)
Johannes Weiner00501b52014-08-08 14:19:20 -07006597{
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08006598 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
Johannes Weiner00501b52014-08-08 14:19:20 -07006599
6600 if (mem_cgroup_disabled())
6601 return;
6602 /*
6603 * Swap faults will attempt to charge the same page multiple
6604 * times. But reuse_swap_page() might have removed the page
6605 * from swapcache already, so we can't check PageSwapCache().
6606 */
6607 if (!memcg)
6608 return;
6609
Johannes Weiner00501b52014-08-08 14:19:20 -07006610 cancel_charge(memcg, nr_pages);
6611}
6612
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006613struct uncharge_gather {
6614 struct mem_cgroup *memcg;
6615 unsigned long pgpgout;
6616 unsigned long nr_anon;
6617 unsigned long nr_file;
6618 unsigned long nr_kmem;
6619 unsigned long nr_huge;
6620 unsigned long nr_shmem;
6621 struct page *dummy_page;
6622};
6623
6624static inline void uncharge_gather_clear(struct uncharge_gather *ug)
Johannes Weiner747db952014-08-08 14:19:24 -07006625{
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006626 memset(ug, 0, sizeof(*ug));
6627}
6628
6629static void uncharge_batch(const struct uncharge_gather *ug)
6630{
6631 unsigned long nr_pages = ug->nr_anon + ug->nr_file + ug->nr_kmem;
Johannes Weiner747db952014-08-08 14:19:24 -07006632 unsigned long flags;
6633
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006634 if (!mem_cgroup_is_root(ug->memcg)) {
6635 page_counter_uncharge(&ug->memcg->memory, nr_pages);
Johannes Weiner7941d212016-01-14 15:21:23 -08006636 if (do_memsw_account())
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006637 page_counter_uncharge(&ug->memcg->memsw, nr_pages);
6638 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && ug->nr_kmem)
6639 page_counter_uncharge(&ug->memcg->kmem, ug->nr_kmem);
6640 memcg_oom_recover(ug->memcg);
Johannes Weinerce00a962014-09-05 08:43:57 -04006641 }
Johannes Weiner747db952014-08-08 14:19:24 -07006642
6643 local_irq_save(flags);
Johannes Weinerc9019e92018-01-31 16:16:37 -08006644 __mod_memcg_state(ug->memcg, MEMCG_RSS, -ug->nr_anon);
6645 __mod_memcg_state(ug->memcg, MEMCG_CACHE, -ug->nr_file);
6646 __mod_memcg_state(ug->memcg, MEMCG_RSS_HUGE, -ug->nr_huge);
6647 __mod_memcg_state(ug->memcg, NR_SHMEM, -ug->nr_shmem);
6648 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
Chris Down871789d2019-05-14 15:46:57 -07006649 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, nr_pages);
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006650 memcg_check_events(ug->memcg, ug->dummy_page);
Johannes Weiner747db952014-08-08 14:19:24 -07006651 local_irq_restore(flags);
Johannes Weinere8ea14c2014-12-10 15:42:42 -08006652
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006653 if (!mem_cgroup_is_root(ug->memcg))
6654 css_put_many(&ug->memcg->css, nr_pages);
6655}
6656
6657static void uncharge_page(struct page *page, struct uncharge_gather *ug)
6658{
6659 VM_BUG_ON_PAGE(PageLRU(page), page);
Jérôme Glisse3f2eb022017-10-03 16:14:57 -07006660 VM_BUG_ON_PAGE(page_count(page) && !is_zone_device_page(page) &&
6661 !PageHWPoison(page) , page);
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006662
6663 if (!page->mem_cgroup)
6664 return;
6665
6666 /*
6667 * Nobody should be changing or seriously looking at
6668 * page->mem_cgroup at this point, we have fully
6669 * exclusive access to the page.
6670 */
6671
6672 if (ug->memcg != page->mem_cgroup) {
6673 if (ug->memcg) {
6674 uncharge_batch(ug);
6675 uncharge_gather_clear(ug);
6676 }
6677 ug->memcg = page->mem_cgroup;
6678 }
6679
6680 if (!PageKmemcg(page)) {
6681 unsigned int nr_pages = 1;
6682
6683 if (PageTransHuge(page)) {
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07006684 nr_pages = compound_nr(page);
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006685 ug->nr_huge += nr_pages;
6686 }
6687 if (PageAnon(page))
6688 ug->nr_anon += nr_pages;
6689 else {
6690 ug->nr_file += nr_pages;
6691 if (PageSwapBacked(page))
6692 ug->nr_shmem += nr_pages;
6693 }
6694 ug->pgpgout++;
6695 } else {
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07006696 ug->nr_kmem += compound_nr(page);
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006697 __ClearPageKmemcg(page);
6698 }
6699
6700 ug->dummy_page = page;
6701 page->mem_cgroup = NULL;
Johannes Weiner747db952014-08-08 14:19:24 -07006702}
6703
6704static void uncharge_list(struct list_head *page_list)
6705{
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006706 struct uncharge_gather ug;
Johannes Weiner747db952014-08-08 14:19:24 -07006707 struct list_head *next;
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006708
6709 uncharge_gather_clear(&ug);
Johannes Weiner747db952014-08-08 14:19:24 -07006710
Johannes Weiner8b592652016-03-17 14:20:31 -07006711 /*
6712 * Note that the list can be a single page->lru; hence the
6713 * do-while loop instead of a simple list_for_each_entry().
6714 */
Johannes Weiner747db952014-08-08 14:19:24 -07006715 next = page_list->next;
6716 do {
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006717 struct page *page;
6718
Johannes Weiner747db952014-08-08 14:19:24 -07006719 page = list_entry(next, struct page, lru);
6720 next = page->lru.next;
6721
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006722 uncharge_page(page, &ug);
Johannes Weiner747db952014-08-08 14:19:24 -07006723 } while (next != page_list);
6724
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006725 if (ug.memcg)
6726 uncharge_batch(&ug);
Johannes Weiner747db952014-08-08 14:19:24 -07006727}
6728
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006729/**
6730 * mem_cgroup_uncharge - uncharge a page
6731 * @page: page to uncharge
6732 *
6733 * Uncharge a page previously charged with mem_cgroup_try_charge() and
6734 * mem_cgroup_commit_charge().
6735 */
6736void mem_cgroup_uncharge(struct page *page)
6737{
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006738 struct uncharge_gather ug;
6739
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006740 if (mem_cgroup_disabled())
6741 return;
6742
Johannes Weiner747db952014-08-08 14:19:24 -07006743 /* Don't touch page->lru of any random page, pre-check: */
Johannes Weiner1306a852014-12-10 15:44:52 -08006744 if (!page->mem_cgroup)
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006745 return;
6746
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006747 uncharge_gather_clear(&ug);
6748 uncharge_page(page, &ug);
6749 uncharge_batch(&ug);
Johannes Weiner747db952014-08-08 14:19:24 -07006750}
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006751
Johannes Weiner747db952014-08-08 14:19:24 -07006752/**
6753 * mem_cgroup_uncharge_list - uncharge a list of page
6754 * @page_list: list of pages to uncharge
6755 *
6756 * Uncharge a list of pages previously charged with
6757 * mem_cgroup_try_charge() and mem_cgroup_commit_charge().
6758 */
6759void mem_cgroup_uncharge_list(struct list_head *page_list)
6760{
6761 if (mem_cgroup_disabled())
6762 return;
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006763
Johannes Weiner747db952014-08-08 14:19:24 -07006764 if (!list_empty(page_list))
6765 uncharge_list(page_list);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006766}
6767
6768/**
Johannes Weiner6a93ca82016-03-15 14:57:19 -07006769 * mem_cgroup_migrate - charge a page's replacement
6770 * @oldpage: currently circulating page
6771 * @newpage: replacement page
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006772 *
Johannes Weiner6a93ca82016-03-15 14:57:19 -07006773 * Charge @newpage as a replacement page for @oldpage. @oldpage will
6774 * be uncharged upon free.
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006775 *
6776 * Both pages must be locked, @newpage->mapping must be set up.
6777 */
Johannes Weiner6a93ca82016-03-15 14:57:19 -07006778void mem_cgroup_migrate(struct page *oldpage, struct page *newpage)
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006779{
Johannes Weiner29833312014-12-10 15:44:02 -08006780 struct mem_cgroup *memcg;
Johannes Weiner44b7a8d2016-01-20 15:03:16 -08006781 unsigned int nr_pages;
6782 bool compound;
Tejun Heod93c4132016-06-24 14:49:54 -07006783 unsigned long flags;
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006784
6785 VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
6786 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006787 VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
Johannes Weiner6abb5a82014-08-08 14:19:33 -07006788 VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
6789 newpage);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006790
6791 if (mem_cgroup_disabled())
6792 return;
6793
6794 /* Page cache replacement: new page already charged? */
Johannes Weiner1306a852014-12-10 15:44:52 -08006795 if (newpage->mem_cgroup)
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006796 return;
6797
Hugh Dickins45637ba2015-11-05 18:49:40 -08006798 /* Swapcache readahead pages can get replaced before being charged */
Johannes Weiner1306a852014-12-10 15:44:52 -08006799 memcg = oldpage->mem_cgroup;
Johannes Weiner29833312014-12-10 15:44:02 -08006800 if (!memcg)
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006801 return;
6802
Johannes Weiner44b7a8d2016-01-20 15:03:16 -08006803 /* Force-charge the new page. The old one will be freed soon */
6804 compound = PageTransHuge(newpage);
6805 nr_pages = compound ? hpage_nr_pages(newpage) : 1;
6806
6807 page_counter_charge(&memcg->memory, nr_pages);
6808 if (do_memsw_account())
6809 page_counter_charge(&memcg->memsw, nr_pages);
6810 css_get_many(&memcg->css, nr_pages);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006811
Johannes Weiner9cf76662016-03-15 14:57:58 -07006812 commit_charge(newpage, memcg, false);
Johannes Weiner44b7a8d2016-01-20 15:03:16 -08006813
Tejun Heod93c4132016-06-24 14:49:54 -07006814 local_irq_save(flags);
Johannes Weiner44b7a8d2016-01-20 15:03:16 -08006815 mem_cgroup_charge_statistics(memcg, newpage, compound, nr_pages);
6816 memcg_check_events(memcg, newpage);
Tejun Heod93c4132016-06-24 14:49:54 -07006817 local_irq_restore(flags);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006818}
6819
Johannes Weineref129472016-01-14 15:21:34 -08006820DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
Johannes Weiner11092082016-01-14 15:21:26 -08006821EXPORT_SYMBOL(memcg_sockets_enabled_key);
6822
Johannes Weiner2d758072016-10-07 17:00:58 -07006823void mem_cgroup_sk_alloc(struct sock *sk)
Johannes Weiner11092082016-01-14 15:21:26 -08006824{
6825 struct mem_cgroup *memcg;
6826
Johannes Weiner2d758072016-10-07 17:00:58 -07006827 if (!mem_cgroup_sockets_enabled)
6828 return;
6829
Roman Gushchinedbe69e2018-02-02 15:26:57 +00006830 /*
6831 * Socket cloning can throw us here with sk_memcg already
6832 * filled. It won't however, necessarily happen from
6833 * process context. So the test for root memcg given
6834 * the current task's memcg won't help us in this case.
6835 *
6836 * Respecting the original socket's memcg is a better
6837 * decision in this case.
6838 */
6839 if (sk->sk_memcg) {
6840 css_get(&sk->sk_memcg->css);
6841 return;
6842 }
6843
Johannes Weiner11092082016-01-14 15:21:26 -08006844 rcu_read_lock();
6845 memcg = mem_cgroup_from_task(current);
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08006846 if (memcg == root_mem_cgroup)
6847 goto out;
Johannes Weiner0db15292016-01-20 15:02:50 -08006848 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08006849 goto out;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08006850 if (css_tryget_online(&memcg->css))
Johannes Weiner11092082016-01-14 15:21:26 -08006851 sk->sk_memcg = memcg;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08006852out:
Johannes Weiner11092082016-01-14 15:21:26 -08006853 rcu_read_unlock();
6854}
Johannes Weiner11092082016-01-14 15:21:26 -08006855
Johannes Weiner2d758072016-10-07 17:00:58 -07006856void mem_cgroup_sk_free(struct sock *sk)
Johannes Weiner11092082016-01-14 15:21:26 -08006857{
Johannes Weiner2d758072016-10-07 17:00:58 -07006858 if (sk->sk_memcg)
6859 css_put(&sk->sk_memcg->css);
Johannes Weiner11092082016-01-14 15:21:26 -08006860}
6861
6862/**
6863 * mem_cgroup_charge_skmem - charge socket memory
6864 * @memcg: memcg to charge
6865 * @nr_pages: number of pages to charge
6866 *
6867 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
6868 * @memcg's configured limit, %false if the charge had to be forced.
6869 */
6870bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
6871{
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08006872 gfp_t gfp_mask = GFP_KERNEL;
Johannes Weiner11092082016-01-14 15:21:26 -08006873
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08006874 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
Johannes Weiner0db15292016-01-20 15:02:50 -08006875 struct page_counter *fail;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08006876
Johannes Weiner0db15292016-01-20 15:02:50 -08006877 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
6878 memcg->tcpmem_pressure = 0;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08006879 return true;
6880 }
Johannes Weiner0db15292016-01-20 15:02:50 -08006881 page_counter_charge(&memcg->tcpmem, nr_pages);
6882 memcg->tcpmem_pressure = 1;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08006883 return false;
Johannes Weiner11092082016-01-14 15:21:26 -08006884 }
Johannes Weinerd886f4e2016-01-20 15:02:47 -08006885
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08006886 /* Don't block in the packet receive path */
6887 if (in_softirq())
6888 gfp_mask = GFP_NOWAIT;
6889
Johannes Weinerc9019e92018-01-31 16:16:37 -08006890 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
Johannes Weinerb2807f02016-01-20 15:03:22 -08006891
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08006892 if (try_charge(memcg, gfp_mask, nr_pages) == 0)
6893 return true;
6894
6895 try_charge(memcg, gfp_mask|__GFP_NOFAIL, nr_pages);
Johannes Weiner11092082016-01-14 15:21:26 -08006896 return false;
6897}
6898
6899/**
6900 * mem_cgroup_uncharge_skmem - uncharge socket memory
Mike Rapoportb7701a52018-02-06 15:42:13 -08006901 * @memcg: memcg to uncharge
6902 * @nr_pages: number of pages to uncharge
Johannes Weiner11092082016-01-14 15:21:26 -08006903 */
6904void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
6905{
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08006906 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
Johannes Weiner0db15292016-01-20 15:02:50 -08006907 page_counter_uncharge(&memcg->tcpmem, nr_pages);
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08006908 return;
6909 }
Johannes Weinerd886f4e2016-01-20 15:02:47 -08006910
Johannes Weinerc9019e92018-01-31 16:16:37 -08006911 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
Johannes Weinerb2807f02016-01-20 15:03:22 -08006912
Roman Gushchin475d0482017-09-08 16:13:09 -07006913 refill_stock(memcg, nr_pages);
Johannes Weiner11092082016-01-14 15:21:26 -08006914}
6915
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08006916static int __init cgroup_memory(char *s)
6917{
6918 char *token;
6919
6920 while ((token = strsep(&s, ",")) != NULL) {
6921 if (!*token)
6922 continue;
6923 if (!strcmp(token, "nosocket"))
6924 cgroup_memory_nosocket = true;
Vladimir Davydov04823c82016-01-20 15:02:38 -08006925 if (!strcmp(token, "nokmem"))
6926 cgroup_memory_nokmem = true;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08006927 }
6928 return 0;
6929}
6930__setup("cgroup.memory=", cgroup_memory);
Johannes Weiner11092082016-01-14 15:21:26 -08006931
Michal Hocko2d110852013-02-22 16:34:43 -08006932/*
Michal Hocko10813122013-02-22 16:35:41 -08006933 * subsys_initcall() for memory controller.
6934 *
Sebastian Andrzej Siewior308167f2016-11-03 15:49:59 +01006935 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
6936 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
6937 * basically everything that doesn't depend on a specific mem_cgroup structure
6938 * should be initialized from here.
Michal Hocko2d110852013-02-22 16:34:43 -08006939 */
6940static int __init mem_cgroup_init(void)
6941{
Johannes Weiner95a045f2015-02-11 15:26:33 -08006942 int cpu, node;
6943
Kirill Tkhai84c07d12018-08-17 15:47:25 -07006944#ifdef CONFIG_MEMCG_KMEM
Vladimir Davydov13583c32016-12-12 16:41:29 -08006945 /*
6946 * Kmem cache creation is mostly done with the slab_mutex held,
Tejun Heo17cc4df2017-02-22 15:41:36 -08006947 * so use a workqueue with limited concurrency to avoid stalling
6948 * all worker threads in case lots of cgroups are created and
6949 * destroyed simultaneously.
Vladimir Davydov13583c32016-12-12 16:41:29 -08006950 */
Tejun Heo17cc4df2017-02-22 15:41:36 -08006951 memcg_kmem_cache_wq = alloc_workqueue("memcg_kmem_cache", 0, 1);
6952 BUG_ON(!memcg_kmem_cache_wq);
Vladimir Davydov13583c32016-12-12 16:41:29 -08006953#endif
6954
Sebastian Andrzej Siewior308167f2016-11-03 15:49:59 +01006955 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
6956 memcg_hotplug_cpu_dead);
Johannes Weiner95a045f2015-02-11 15:26:33 -08006957
6958 for_each_possible_cpu(cpu)
6959 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
6960 drain_local_stock);
6961
6962 for_each_node(node) {
6963 struct mem_cgroup_tree_per_node *rtpn;
Johannes Weiner95a045f2015-02-11 15:26:33 -08006964
6965 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
6966 node_online(node) ? node : NUMA_NO_NODE);
6967
Mel Gormanef8f2322016-07-28 15:46:05 -07006968 rtpn->rb_root = RB_ROOT;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -07006969 rtpn->rb_rightmost = NULL;
Mel Gormanef8f2322016-07-28 15:46:05 -07006970 spin_lock_init(&rtpn->lock);
Johannes Weiner95a045f2015-02-11 15:26:33 -08006971 soft_limit_tree.rb_tree_per_node[node] = rtpn;
6972 }
6973
Michal Hocko2d110852013-02-22 16:34:43 -08006974 return 0;
6975}
6976subsys_initcall(mem_cgroup_init);
Johannes Weiner21afa382015-02-11 15:26:36 -08006977
6978#ifdef CONFIG_MEMCG_SWAP
Arnd Bergmann358c07f2016-08-25 15:17:08 -07006979static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
6980{
Kirill Tkhai1c2d4792018-10-26 15:09:28 -07006981 while (!refcount_inc_not_zero(&memcg->id.ref)) {
Arnd Bergmann358c07f2016-08-25 15:17:08 -07006982 /*
6983 * The root cgroup cannot be destroyed, so it's refcount must
6984 * always be >= 1.
6985 */
6986 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
6987 VM_BUG_ON(1);
6988 break;
6989 }
6990 memcg = parent_mem_cgroup(memcg);
6991 if (!memcg)
6992 memcg = root_mem_cgroup;
6993 }
6994 return memcg;
6995}
6996
Johannes Weiner21afa382015-02-11 15:26:36 -08006997/**
6998 * mem_cgroup_swapout - transfer a memsw charge to swap
6999 * @page: page whose memsw charge to transfer
7000 * @entry: swap entry to move the charge to
7001 *
7002 * Transfer the memsw charge of @page to @entry.
7003 */
7004void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
7005{
Vladimir Davydov1f47b612016-08-11 15:33:00 -07007006 struct mem_cgroup *memcg, *swap_memcg;
Huang Yingd6810d72017-09-06 16:22:45 -07007007 unsigned int nr_entries;
Johannes Weiner21afa382015-02-11 15:26:36 -08007008 unsigned short oldid;
7009
7010 VM_BUG_ON_PAGE(PageLRU(page), page);
7011 VM_BUG_ON_PAGE(page_count(page), page);
7012
Johannes Weiner7941d212016-01-14 15:21:23 -08007013 if (!do_memsw_account())
Johannes Weiner21afa382015-02-11 15:26:36 -08007014 return;
7015
7016 memcg = page->mem_cgroup;
7017
7018 /* Readahead page, never charged */
7019 if (!memcg)
7020 return;
7021
Vladimir Davydov1f47b612016-08-11 15:33:00 -07007022 /*
7023 * In case the memcg owning these pages has been offlined and doesn't
7024 * have an ID allocated to it anymore, charge the closest online
7025 * ancestor for the swap instead and transfer the memory+swap charge.
7026 */
7027 swap_memcg = mem_cgroup_id_get_online(memcg);
Huang Yingd6810d72017-09-06 16:22:45 -07007028 nr_entries = hpage_nr_pages(page);
7029 /* Get references for the tail pages, too */
7030 if (nr_entries > 1)
7031 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7032 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7033 nr_entries);
Johannes Weiner21afa382015-02-11 15:26:36 -08007034 VM_BUG_ON_PAGE(oldid, page);
Johannes Weinerc9019e92018-01-31 16:16:37 -08007035 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
Johannes Weiner21afa382015-02-11 15:26:36 -08007036
7037 page->mem_cgroup = NULL;
7038
7039 if (!mem_cgroup_is_root(memcg))
Huang Yingd6810d72017-09-06 16:22:45 -07007040 page_counter_uncharge(&memcg->memory, nr_entries);
Johannes Weiner21afa382015-02-11 15:26:36 -08007041
Vladimir Davydov1f47b612016-08-11 15:33:00 -07007042 if (memcg != swap_memcg) {
7043 if (!mem_cgroup_is_root(swap_memcg))
Huang Yingd6810d72017-09-06 16:22:45 -07007044 page_counter_charge(&swap_memcg->memsw, nr_entries);
7045 page_counter_uncharge(&memcg->memsw, nr_entries);
Vladimir Davydov1f47b612016-08-11 15:33:00 -07007046 }
7047
Sebastian Andrzej Siewiorce9ce662015-09-04 15:47:50 -07007048 /*
7049 * Interrupts should be disabled here because the caller holds the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07007050 * i_pages lock which is taken with interrupts-off. It is
Sebastian Andrzej Siewiorce9ce662015-09-04 15:47:50 -07007051 * important here to have the interrupts disabled because it is the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07007052 * only synchronisation we have for updating the per-CPU variables.
Sebastian Andrzej Siewiorce9ce662015-09-04 15:47:50 -07007053 */
7054 VM_BUG_ON(!irqs_disabled());
Huang Yingd6810d72017-09-06 16:22:45 -07007055 mem_cgroup_charge_statistics(memcg, page, PageTransHuge(page),
7056 -nr_entries);
Johannes Weiner21afa382015-02-11 15:26:36 -08007057 memcg_check_events(memcg, page);
Johannes Weiner73f576c2016-07-20 15:44:57 -07007058
7059 if (!mem_cgroup_is_root(memcg))
Shakeel Buttd08afa142017-11-29 16:11:15 -08007060 css_put_many(&memcg->css, nr_entries);
Johannes Weiner21afa382015-02-11 15:26:36 -08007061}
7062
Huang Ying38d8b4e2017-07-06 15:37:18 -07007063/**
7064 * mem_cgroup_try_charge_swap - try charging swap space for a page
Vladimir Davydov37e84352016-01-20 15:02:56 -08007065 * @page: page being added to swap
7066 * @entry: swap entry to charge
7067 *
Huang Ying38d8b4e2017-07-06 15:37:18 -07007068 * Try to charge @page's memcg for the swap space at @entry.
Vladimir Davydov37e84352016-01-20 15:02:56 -08007069 *
7070 * Returns 0 on success, -ENOMEM on failure.
7071 */
7072int mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry)
7073{
Huang Ying38d8b4e2017-07-06 15:37:18 -07007074 unsigned int nr_pages = hpage_nr_pages(page);
Vladimir Davydov37e84352016-01-20 15:02:56 -08007075 struct page_counter *counter;
Huang Ying38d8b4e2017-07-06 15:37:18 -07007076 struct mem_cgroup *memcg;
Vladimir Davydov37e84352016-01-20 15:02:56 -08007077 unsigned short oldid;
7078
7079 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) || !do_swap_account)
7080 return 0;
7081
7082 memcg = page->mem_cgroup;
7083
7084 /* Readahead page, never charged */
7085 if (!memcg)
7086 return 0;
7087
Tejun Heof3a53a32018-06-07 17:05:35 -07007088 if (!entry.val) {
7089 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
Tejun Heobb98f2c2018-06-07 17:05:31 -07007090 return 0;
Tejun Heof3a53a32018-06-07 17:05:35 -07007091 }
Tejun Heobb98f2c2018-06-07 17:05:31 -07007092
Vladimir Davydov1f47b612016-08-11 15:33:00 -07007093 memcg = mem_cgroup_id_get_online(memcg);
Vladimir Davydov37e84352016-01-20 15:02:56 -08007094
Vladimir Davydov1f47b612016-08-11 15:33:00 -07007095 if (!mem_cgroup_is_root(memcg) &&
Huang Ying38d8b4e2017-07-06 15:37:18 -07007096 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
Tejun Heof3a53a32018-06-07 17:05:35 -07007097 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7098 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
Vladimir Davydov1f47b612016-08-11 15:33:00 -07007099 mem_cgroup_id_put(memcg);
7100 return -ENOMEM;
7101 }
7102
Huang Ying38d8b4e2017-07-06 15:37:18 -07007103 /* Get references for the tail pages, too */
7104 if (nr_pages > 1)
7105 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7106 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
Vladimir Davydov37e84352016-01-20 15:02:56 -08007107 VM_BUG_ON_PAGE(oldid, page);
Johannes Weinerc9019e92018-01-31 16:16:37 -08007108 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
Vladimir Davydov37e84352016-01-20 15:02:56 -08007109
Vladimir Davydov37e84352016-01-20 15:02:56 -08007110 return 0;
7111}
7112
Johannes Weiner21afa382015-02-11 15:26:36 -08007113/**
Huang Ying38d8b4e2017-07-06 15:37:18 -07007114 * mem_cgroup_uncharge_swap - uncharge swap space
Johannes Weiner21afa382015-02-11 15:26:36 -08007115 * @entry: swap entry to uncharge
Huang Ying38d8b4e2017-07-06 15:37:18 -07007116 * @nr_pages: the amount of swap space to uncharge
Johannes Weiner21afa382015-02-11 15:26:36 -08007117 */
Huang Ying38d8b4e2017-07-06 15:37:18 -07007118void mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
Johannes Weiner21afa382015-02-11 15:26:36 -08007119{
7120 struct mem_cgroup *memcg;
7121 unsigned short id;
7122
Vladimir Davydov37e84352016-01-20 15:02:56 -08007123 if (!do_swap_account)
Johannes Weiner21afa382015-02-11 15:26:36 -08007124 return;
7125
Huang Ying38d8b4e2017-07-06 15:37:18 -07007126 id = swap_cgroup_record(entry, 0, nr_pages);
Johannes Weiner21afa382015-02-11 15:26:36 -08007127 rcu_read_lock();
Vladimir Davydovadbe4272015-04-15 16:13:00 -07007128 memcg = mem_cgroup_from_id(id);
Johannes Weiner21afa382015-02-11 15:26:36 -08007129 if (memcg) {
Vladimir Davydov37e84352016-01-20 15:02:56 -08007130 if (!mem_cgroup_is_root(memcg)) {
7131 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Huang Ying38d8b4e2017-07-06 15:37:18 -07007132 page_counter_uncharge(&memcg->swap, nr_pages);
Vladimir Davydov37e84352016-01-20 15:02:56 -08007133 else
Huang Ying38d8b4e2017-07-06 15:37:18 -07007134 page_counter_uncharge(&memcg->memsw, nr_pages);
Vladimir Davydov37e84352016-01-20 15:02:56 -08007135 }
Johannes Weinerc9019e92018-01-31 16:16:37 -08007136 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
Huang Ying38d8b4e2017-07-06 15:37:18 -07007137 mem_cgroup_id_put_many(memcg, nr_pages);
Johannes Weiner21afa382015-02-11 15:26:36 -08007138 }
7139 rcu_read_unlock();
7140}
7141
Vladimir Davydovd8b38432016-01-20 15:03:07 -08007142long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7143{
7144 long nr_swap_pages = get_nr_swap_pages();
7145
7146 if (!do_swap_account || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7147 return nr_swap_pages;
7148 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7149 nr_swap_pages = min_t(long, nr_swap_pages,
Roman Gushchinbbec2e12018-06-07 17:06:18 -07007150 READ_ONCE(memcg->swap.max) -
Vladimir Davydovd8b38432016-01-20 15:03:07 -08007151 page_counter_read(&memcg->swap));
7152 return nr_swap_pages;
7153}
7154
Vladimir Davydov5ccc5ab2016-01-20 15:03:10 -08007155bool mem_cgroup_swap_full(struct page *page)
7156{
7157 struct mem_cgroup *memcg;
7158
7159 VM_BUG_ON_PAGE(!PageLocked(page), page);
7160
7161 if (vm_swap_full())
7162 return true;
7163 if (!do_swap_account || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7164 return false;
7165
7166 memcg = page->mem_cgroup;
7167 if (!memcg)
7168 return false;
7169
7170 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
Roman Gushchinbbec2e12018-06-07 17:06:18 -07007171 if (page_counter_read(&memcg->swap) * 2 >= memcg->swap.max)
Vladimir Davydov5ccc5ab2016-01-20 15:03:10 -08007172 return true;
7173
7174 return false;
7175}
7176
Johannes Weiner21afa382015-02-11 15:26:36 -08007177/* for remember boot option*/
7178#ifdef CONFIG_MEMCG_SWAP_ENABLED
7179static int really_do_swap_account __initdata = 1;
7180#else
7181static int really_do_swap_account __initdata;
7182#endif
7183
7184static int __init enable_swap_account(char *s)
7185{
7186 if (!strcmp(s, "1"))
7187 really_do_swap_account = 1;
7188 else if (!strcmp(s, "0"))
7189 really_do_swap_account = 0;
7190 return 1;
7191}
7192__setup("swapaccount=", enable_swap_account);
7193
Vladimir Davydov37e84352016-01-20 15:02:56 -08007194static u64 swap_current_read(struct cgroup_subsys_state *css,
7195 struct cftype *cft)
7196{
7197 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7198
7199 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7200}
7201
7202static int swap_max_show(struct seq_file *m, void *v)
7203{
Chris Down677dc972019-03-05 15:45:55 -08007204 return seq_puts_memcg_tunable(m,
7205 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
Vladimir Davydov37e84352016-01-20 15:02:56 -08007206}
7207
7208static ssize_t swap_max_write(struct kernfs_open_file *of,
7209 char *buf, size_t nbytes, loff_t off)
7210{
7211 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7212 unsigned long max;
7213 int err;
7214
7215 buf = strstrip(buf);
7216 err = page_counter_memparse(buf, "max", &max);
7217 if (err)
7218 return err;
7219
Tejun Heobe091022018-06-07 17:09:21 -07007220 xchg(&memcg->swap.max, max);
Vladimir Davydov37e84352016-01-20 15:02:56 -08007221
7222 return nbytes;
7223}
7224
Tejun Heof3a53a32018-06-07 17:05:35 -07007225static int swap_events_show(struct seq_file *m, void *v)
7226{
Chris Downaa9694b2019-03-05 15:45:52 -08007227 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
Tejun Heof3a53a32018-06-07 17:05:35 -07007228
7229 seq_printf(m, "max %lu\n",
7230 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7231 seq_printf(m, "fail %lu\n",
7232 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7233
7234 return 0;
7235}
7236
Vladimir Davydov37e84352016-01-20 15:02:56 -08007237static struct cftype swap_files[] = {
7238 {
7239 .name = "swap.current",
7240 .flags = CFTYPE_NOT_ON_ROOT,
7241 .read_u64 = swap_current_read,
7242 },
7243 {
7244 .name = "swap.max",
7245 .flags = CFTYPE_NOT_ON_ROOT,
7246 .seq_show = swap_max_show,
7247 .write = swap_max_write,
7248 },
Tejun Heof3a53a32018-06-07 17:05:35 -07007249 {
7250 .name = "swap.events",
7251 .flags = CFTYPE_NOT_ON_ROOT,
7252 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7253 .seq_show = swap_events_show,
7254 },
Vladimir Davydov37e84352016-01-20 15:02:56 -08007255 { } /* terminate */
7256};
7257
Johannes Weiner21afa382015-02-11 15:26:36 -08007258static struct cftype memsw_cgroup_files[] = {
7259 {
7260 .name = "memsw.usage_in_bytes",
7261 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7262 .read_u64 = mem_cgroup_read_u64,
7263 },
7264 {
7265 .name = "memsw.max_usage_in_bytes",
7266 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7267 .write = mem_cgroup_reset,
7268 .read_u64 = mem_cgroup_read_u64,
7269 },
7270 {
7271 .name = "memsw.limit_in_bytes",
7272 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7273 .write = mem_cgroup_write,
7274 .read_u64 = mem_cgroup_read_u64,
7275 },
7276 {
7277 .name = "memsw.failcnt",
7278 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7279 .write = mem_cgroup_reset,
7280 .read_u64 = mem_cgroup_read_u64,
7281 },
7282 { }, /* terminate */
7283};
7284
7285static int __init mem_cgroup_swap_init(void)
7286{
7287 if (!mem_cgroup_disabled() && really_do_swap_account) {
7288 do_swap_account = 1;
Vladimir Davydov37e84352016-01-20 15:02:56 -08007289 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys,
7290 swap_files));
Johannes Weiner21afa382015-02-11 15:26:36 -08007291 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys,
7292 memsw_cgroup_files));
7293 }
7294 return 0;
7295}
7296subsys_initcall(mem_cgroup_swap_init);
7297
7298#endif /* CONFIG_MEMCG_SWAP */