]> git.proxmox.com Git - mirror_ubuntu-focal-kernel.git/blame - mm/memcontrol.c
mm/memcontrol.c: fix a -Wunused-function warning
[mirror_ubuntu-focal-kernel.git] / mm / memcontrol.c
CommitLineData
c942fddf 1// SPDX-License-Identifier: GPL-2.0-or-later
8cdea7c0
BS
2/* memcontrol.c - Memory Controller
3 *
4 * Copyright IBM Corporation, 2007
5 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
6 *
78fb7466
PE
7 * Copyright 2007 OpenVZ SWsoft Inc
8 * Author: Pavel Emelianov <xemul@openvz.org>
9 *
2e72b634
KS
10 * Memory thresholds
11 * Copyright (C) 2009 Nokia Corporation
12 * Author: Kirill A. Shutemov
13 *
7ae1e1d0
GC
14 * Kernel Memory Controller
15 * Copyright (C) 2012 Parallels Inc. and Google Inc.
16 * Authors: Glauber Costa and Suleiman Souhlal
17 *
1575e68b
JW
18 * 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
8cdea7c0
BS
23 */
24
3e32cb2e 25#include <linux/page_counter.h>
8cdea7c0
BS
26#include <linux/memcontrol.h>
27#include <linux/cgroup.h>
a520110e 28#include <linux/pagewalk.h>
6e84f315 29#include <linux/sched/mm.h>
3a4f8a0b 30#include <linux/shmem_fs.h>
4ffef5fe 31#include <linux/hugetlb.h>
d13d1443 32#include <linux/pagemap.h>
1ff9e6e1 33#include <linux/vm_event_item.h>
d52aa412 34#include <linux/smp.h>
8a9f3ccd 35#include <linux/page-flags.h>
66e1707b 36#include <linux/backing-dev.h>
8a9f3ccd
BS
37#include <linux/bit_spinlock.h>
38#include <linux/rcupdate.h>
e222432b 39#include <linux/limits.h>
b9e15baf 40#include <linux/export.h>
8c7c6e34 41#include <linux/mutex.h>
bb4cc1a8 42#include <linux/rbtree.h>
b6ac57d5 43#include <linux/slab.h>
66e1707b 44#include <linux/swap.h>
02491447 45#include <linux/swapops.h>
66e1707b 46#include <linux/spinlock.h>
2e72b634 47#include <linux/eventfd.h>
79bd9814 48#include <linux/poll.h>
2e72b634 49#include <linux/sort.h>
66e1707b 50#include <linux/fs.h>
d2ceb9b7 51#include <linux/seq_file.h>
70ddf637 52#include <linux/vmpressure.h>
b69408e8 53#include <linux/mm_inline.h>
5d1ea48b 54#include <linux/swap_cgroup.h>
cdec2e42 55#include <linux/cpu.h>
158e0a2d 56#include <linux/oom.h>
0056f4e6 57#include <linux/lockdep.h>
79bd9814 58#include <linux/file.h>
b23afb93 59#include <linux/tracehook.h>
0e4b01df 60#include <linux/psi.h>
c8713d0b 61#include <linux/seq_buf.h>
08e552c6 62#include "internal.h"
d1a4c0b3 63#include <net/sock.h>
4bd2c1ee 64#include <net/ip.h>
f35c3a8e 65#include "slab.h"
8cdea7c0 66
7c0f6ba6 67#include <linux/uaccess.h>
8697d331 68
cc8e970c
KM
69#include <trace/events/vmscan.h>
70
073219e9
TH
71struct cgroup_subsys memory_cgrp_subsys __read_mostly;
72EXPORT_SYMBOL(memory_cgrp_subsys);
68ae564b 73
7d828602
JW
74struct mem_cgroup *root_mem_cgroup __read_mostly;
75
a181b0e8 76#define MEM_CGROUP_RECLAIM_RETRIES 5
8cdea7c0 77
f7e1cb6e
JW
78/* Socket memory accounting disabled? */
79static bool cgroup_memory_nosocket;
80
04823c83
VD
81/* Kernel memory accounting disabled? */
82static bool cgroup_memory_nokmem;
83
21afa38e 84/* Whether the swap controller is active */
c255a458 85#ifdef CONFIG_MEMCG_SWAP
c077719b 86int do_swap_account __read_mostly;
c077719b 87#else
a0db00fc 88#define do_swap_account 0
c077719b
KH
89#endif
90
97b27821
TH
91#ifdef CONFIG_CGROUP_WRITEBACK
92static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
93#endif
94
7941d214
JW
95/* 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
71cd3113 101static const char *const mem_cgroup_lru_names[] = {
58cf188e
SZ
102 "inactive_anon",
103 "active_anon",
104 "inactive_file",
105 "active_file",
106 "unevictable",
107};
108
a0db00fc
KS
109#define THRESHOLDS_EVENTS_TARGET 128
110#define SOFTLIMIT_EVENTS_TARGET 1024
111#define NUMAINFO_EVENTS_TARGET 1024
e9f8974f 112
bb4cc1a8
AM
113/*
114 * Cgroups above their limits are maintained in a RB-Tree, independent of
115 * their hierarchy representation
116 */
117
ef8f2327 118struct mem_cgroup_tree_per_node {
bb4cc1a8 119 struct rb_root rb_root;
fa90b2fd 120 struct rb_node *rb_rightmost;
bb4cc1a8
AM
121 spinlock_t lock;
122};
123
bb4cc1a8
AM
124struct 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
9490ff27
KH
130/* for OOM */
131struct mem_cgroup_eventfd_list {
132 struct list_head list;
133 struct eventfd_ctx *eventfd;
134};
2e72b634 135
79bd9814
TH
136/*
137 * cgroup_event represents events which userspace want to receive.
138 */
3bc942f3 139struct mem_cgroup_event {
79bd9814 140 /*
59b6f873 141 * memcg which the event belongs to.
79bd9814 142 */
59b6f873 143 struct mem_cgroup *memcg;
79bd9814
TH
144 /*
145 * 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;
fba94807
TH
152 /*
153 * 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 */
59b6f873 157 int (*register_event)(struct mem_cgroup *memcg,
347c4a87 158 struct eventfd_ctx *eventfd, const char *args);
fba94807
TH
159 /*
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 */
59b6f873 164 void (*unregister_event)(struct mem_cgroup *memcg,
fba94807 165 struct eventfd_ctx *eventfd);
79bd9814
TH
166 /*
167 * All fields below needed to unregister event when
168 * userspace closes eventfd.
169 */
170 poll_table pt;
171 wait_queue_head_t *wqh;
ac6424b9 172 wait_queue_entry_t wait;
79bd9814
TH
173 struct work_struct remove;
174};
175
c0ff4b85
R
176static void mem_cgroup_threshold(struct mem_cgroup *memcg);
177static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
2e72b634 178
7dc74be0
DN
179/* Stuffs for move charges at task migration. */
180/*
1dfab5ab 181 * Types of charges to be moved.
7dc74be0 182 */
1dfab5ab
JW
183#define MOVE_ANON 0x1U
184#define MOVE_FILE 0x2U
185#define MOVE_MASK (MOVE_ANON | MOVE_FILE)
7dc74be0 186
4ffef5fe
DN
187/* "mc" and its members are protected by cgroup_mutex */
188static struct move_charge_struct {
b1dd693e 189 spinlock_t lock; /* for from, to */
264a0ae1 190 struct mm_struct *mm;
4ffef5fe
DN
191 struct mem_cgroup *from;
192 struct mem_cgroup *to;
1dfab5ab 193 unsigned long flags;
4ffef5fe 194 unsigned long precharge;
854ffa8d 195 unsigned long moved_charge;
483c30b5 196 unsigned long moved_swap;
8033b97c
DN
197 struct task_struct *moving_task; /* a task moving charges */
198 wait_queue_head_t waitq; /* a waitq for other context */
199} mc = {
2bd9bb20 200 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
8033b97c
DN
201 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
202};
4ffef5fe 203
4e416953
BS
204/*
205 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
206 * limit reclaim to prevent infinite loops, if they ever occur.
207 */
a0db00fc 208#define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
bb4cc1a8 209#define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
4e416953 210
217bc319
KH
211enum charge_type {
212 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
41326c17 213 MEM_CGROUP_CHARGE_TYPE_ANON,
d13d1443 214 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
8a9478ca 215 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
c05555b5
KH
216 NR_CHARGE_TYPE,
217};
218
8c7c6e34 219/* for encoding cft->private value on file */
86ae53e1
GC
220enum res_type {
221 _MEM,
222 _MEMSWAP,
223 _OOM_TYPE,
510fc4e1 224 _KMEM,
d55f90bf 225 _TCP,
86ae53e1
GC
226};
227
a0db00fc
KS
228#define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
229#define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
8c7c6e34 230#define MEMFILE_ATTR(val) ((val) & 0xffff)
9490ff27
KH
231/* Used for OOM nofiier */
232#define OOM_CONTROL (0)
8c7c6e34 233
b05706f1
KT
234/*
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
7775face
TH
249static 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
70ddf637
AV
255/* 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
84c07d11 268#ifdef CONFIG_MEMCG_KMEM
55007d84 269/*
f7ce3190 270 * This will be the memcg's index in each cache's ->memcg_params.memcg_caches.
b8627835
LZ
271 * 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.
55007d84 276 *
dbcf73e2
VD
277 * 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.
55007d84 279 */
dbcf73e2
VD
280static DEFINE_IDA(memcg_cache_ida);
281int memcg_nr_cache_ids;
749c5415 282
05257a1a
VD
283/* 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
55007d84
GC
296/*
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 *
b8627835 302 * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
55007d84
GC
303 * 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
b8627835 305 * cgrp_id space is not getting any smaller, and we don't have to necessarily
55007d84
GC
306 * increase ours as well if it increases.
307 */
308#define MEMCG_CACHES_MIN_SIZE 4
b8627835 309#define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
55007d84 310
d7f25f8a
GC
311/*
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 */
ef12947c 317DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
d7f25f8a 318EXPORT_SYMBOL(memcg_kmem_enabled_key);
a8964b9b 319
17cc4dfe
TH
320struct workqueue_struct *memcg_kmem_cache_wq;
321
0a4465d3
KT
322static int memcg_shrinker_map_size;
323static DEFINE_MUTEX(memcg_shrinker_map_mutex);
324
325static void memcg_free_shrinker_map_rcu(struct rcu_head *head)
326{
327 kvfree(container_of(head, struct memcg_shrinker_map, rcu));
328}
329
330static int memcg_expand_one_shrinker_map(struct mem_cgroup *memcg,
331 int size, int old_size)
332{
333 struct memcg_shrinker_map *new, *old;
334 int nid;
335
336 lockdep_assert_held(&memcg_shrinker_map_mutex);
337
338 for_each_node(nid) {
339 old = rcu_dereference_protected(
340 mem_cgroup_nodeinfo(memcg, nid)->shrinker_map, true);
341 /* Not yet online memcg */
342 if (!old)
343 return 0;
344
345 new = kvmalloc(sizeof(*new) + size, GFP_KERNEL);
346 if (!new)
347 return -ENOMEM;
348
349 /* Set all old bits, clear all new bits */
350 memset(new->map, (int)0xff, old_size);
351 memset((void *)new->map + old_size, 0, size - old_size);
352
353 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, new);
354 call_rcu(&old->rcu, memcg_free_shrinker_map_rcu);
355 }
356
357 return 0;
358}
359
360static void memcg_free_shrinker_maps(struct mem_cgroup *memcg)
361{
362 struct mem_cgroup_per_node *pn;
363 struct memcg_shrinker_map *map;
364 int nid;
365
366 if (mem_cgroup_is_root(memcg))
367 return;
368
369 for_each_node(nid) {
370 pn = mem_cgroup_nodeinfo(memcg, nid);
371 map = rcu_dereference_protected(pn->shrinker_map, true);
372 if (map)
373 kvfree(map);
374 rcu_assign_pointer(pn->shrinker_map, NULL);
375 }
376}
377
378static int memcg_alloc_shrinker_maps(struct mem_cgroup *memcg)
379{
380 struct memcg_shrinker_map *map;
381 int nid, size, ret = 0;
382
383 if (mem_cgroup_is_root(memcg))
384 return 0;
385
386 mutex_lock(&memcg_shrinker_map_mutex);
387 size = memcg_shrinker_map_size;
388 for_each_node(nid) {
389 map = kvzalloc(sizeof(*map) + size, GFP_KERNEL);
390 if (!map) {
391 memcg_free_shrinker_maps(memcg);
392 ret = -ENOMEM;
393 break;
394 }
395 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, map);
396 }
397 mutex_unlock(&memcg_shrinker_map_mutex);
398
399 return ret;
400}
401
402int memcg_expand_shrinker_maps(int new_id)
403{
404 int size, old_size, ret = 0;
405 struct mem_cgroup *memcg;
406
407 size = DIV_ROUND_UP(new_id + 1, BITS_PER_LONG) * sizeof(unsigned long);
408 old_size = memcg_shrinker_map_size;
409 if (size <= old_size)
410 return 0;
411
412 mutex_lock(&memcg_shrinker_map_mutex);
413 if (!root_mem_cgroup)
414 goto unlock;
415
416 for_each_mem_cgroup(memcg) {
417 if (mem_cgroup_is_root(memcg))
418 continue;
419 ret = memcg_expand_one_shrinker_map(memcg, size, old_size);
420 if (ret)
421 goto unlock;
422 }
423unlock:
424 if (!ret)
425 memcg_shrinker_map_size = size;
426 mutex_unlock(&memcg_shrinker_map_mutex);
427 return ret;
428}
fae91d6d
KT
429
430void memcg_set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
431{
432 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
433 struct memcg_shrinker_map *map;
434
435 rcu_read_lock();
436 map = rcu_dereference(memcg->nodeinfo[nid]->shrinker_map);
f90280d6
KT
437 /* Pairs with smp mb in shrink_slab() */
438 smp_mb__before_atomic();
fae91d6d
KT
439 set_bit(shrinker_id, map->map);
440 rcu_read_unlock();
441 }
442}
443
0a4465d3
KT
444#else /* CONFIG_MEMCG_KMEM */
445static int memcg_alloc_shrinker_maps(struct mem_cgroup *memcg)
446{
447 return 0;
448}
449static void memcg_free_shrinker_maps(struct mem_cgroup *memcg) { }
84c07d11 450#endif /* CONFIG_MEMCG_KMEM */
a8964b9b 451
ad7fa852
TH
452/**
453 * mem_cgroup_css_from_page - css of the memcg associated with a page
454 * @page: page of interest
455 *
456 * If memcg is bound to the default hierarchy, css of the memcg associated
457 * with @page is returned. The returned css remains associated with @page
458 * until it is released.
459 *
460 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
461 * is returned.
ad7fa852
TH
462 */
463struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
464{
465 struct mem_cgroup *memcg;
466
ad7fa852
TH
467 memcg = page->mem_cgroup;
468
9e10a130 469 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
ad7fa852
TH
470 memcg = root_mem_cgroup;
471
ad7fa852
TH
472 return &memcg->css;
473}
474
2fc04524
VD
475/**
476 * page_cgroup_ino - return inode number of the memcg a page is charged to
477 * @page: the page
478 *
479 * Look up the closest online ancestor of the memory cgroup @page is charged to
480 * and return its inode number or 0 if @page is not charged to any cgroup. It
481 * is safe to call this function without holding a reference to @page.
482 *
483 * Note, this function is inherently racy, because there is nothing to prevent
484 * the cgroup inode from getting torn down and potentially reallocated a moment
485 * after page_cgroup_ino() returns, so it only should be used by callers that
486 * do not care (such as procfs interfaces).
487 */
488ino_t page_cgroup_ino(struct page *page)
489{
490 struct mem_cgroup *memcg;
491 unsigned long ino = 0;
492
493 rcu_read_lock();
4d96ba35
RG
494 if (PageHead(page) && PageSlab(page))
495 memcg = memcg_from_slab_page(page);
496 else
497 memcg = READ_ONCE(page->mem_cgroup);
2fc04524
VD
498 while (memcg && !(memcg->css.flags & CSS_ONLINE))
499 memcg = parent_mem_cgroup(memcg);
500 if (memcg)
501 ino = cgroup_ino(memcg->css.cgroup);
502 rcu_read_unlock();
503 return ino;
504}
505
ef8f2327
MG
506static struct mem_cgroup_per_node *
507mem_cgroup_page_nodeinfo(struct mem_cgroup *memcg, struct page *page)
f64c3f54 508{
97a6c37b 509 int nid = page_to_nid(page);
f64c3f54 510
ef8f2327 511 return memcg->nodeinfo[nid];
f64c3f54
BS
512}
513
ef8f2327
MG
514static struct mem_cgroup_tree_per_node *
515soft_limit_tree_node(int nid)
bb4cc1a8 516{
ef8f2327 517 return soft_limit_tree.rb_tree_per_node[nid];
bb4cc1a8
AM
518}
519
ef8f2327 520static struct mem_cgroup_tree_per_node *
bb4cc1a8
AM
521soft_limit_tree_from_page(struct page *page)
522{
523 int nid = page_to_nid(page);
bb4cc1a8 524
ef8f2327 525 return soft_limit_tree.rb_tree_per_node[nid];
bb4cc1a8
AM
526}
527
ef8f2327
MG
528static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
529 struct mem_cgroup_tree_per_node *mctz,
3e32cb2e 530 unsigned long new_usage_in_excess)
bb4cc1a8
AM
531{
532 struct rb_node **p = &mctz->rb_root.rb_node;
533 struct rb_node *parent = NULL;
ef8f2327 534 struct mem_cgroup_per_node *mz_node;
fa90b2fd 535 bool rightmost = true;
bb4cc1a8
AM
536
537 if (mz->on_tree)
538 return;
539
540 mz->usage_in_excess = new_usage_in_excess;
541 if (!mz->usage_in_excess)
542 return;
543 while (*p) {
544 parent = *p;
ef8f2327 545 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
bb4cc1a8 546 tree_node);
fa90b2fd 547 if (mz->usage_in_excess < mz_node->usage_in_excess) {
bb4cc1a8 548 p = &(*p)->rb_left;
fa90b2fd
DB
549 rightmost = false;
550 }
551
bb4cc1a8
AM
552 /*
553 * We can't avoid mem cgroups that are over their soft
554 * limit by the same amount
555 */
556 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
557 p = &(*p)->rb_right;
558 }
fa90b2fd
DB
559
560 if (rightmost)
561 mctz->rb_rightmost = &mz->tree_node;
562
bb4cc1a8
AM
563 rb_link_node(&mz->tree_node, parent, p);
564 rb_insert_color(&mz->tree_node, &mctz->rb_root);
565 mz->on_tree = true;
566}
567
ef8f2327
MG
568static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
569 struct mem_cgroup_tree_per_node *mctz)
bb4cc1a8
AM
570{
571 if (!mz->on_tree)
572 return;
fa90b2fd
DB
573
574 if (&mz->tree_node == mctz->rb_rightmost)
575 mctz->rb_rightmost = rb_prev(&mz->tree_node);
576
bb4cc1a8
AM
577 rb_erase(&mz->tree_node, &mctz->rb_root);
578 mz->on_tree = false;
579}
580
ef8f2327
MG
581static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
582 struct mem_cgroup_tree_per_node *mctz)
bb4cc1a8 583{
0a31bc97
JW
584 unsigned long flags;
585
586 spin_lock_irqsave(&mctz->lock, flags);
cf2c8127 587 __mem_cgroup_remove_exceeded(mz, mctz);
0a31bc97 588 spin_unlock_irqrestore(&mctz->lock, flags);
bb4cc1a8
AM
589}
590
3e32cb2e
JW
591static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
592{
593 unsigned long nr_pages = page_counter_read(&memcg->memory);
4db0c3c2 594 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
3e32cb2e
JW
595 unsigned long excess = 0;
596
597 if (nr_pages > soft_limit)
598 excess = nr_pages - soft_limit;
599
600 return excess;
601}
bb4cc1a8
AM
602
603static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
604{
3e32cb2e 605 unsigned long excess;
ef8f2327
MG
606 struct mem_cgroup_per_node *mz;
607 struct mem_cgroup_tree_per_node *mctz;
bb4cc1a8 608
e231875b 609 mctz = soft_limit_tree_from_page(page);
bfc7228b
LD
610 if (!mctz)
611 return;
bb4cc1a8
AM
612 /*
613 * Necessary to update all ancestors when hierarchy is used.
614 * because their event counter is not touched.
615 */
616 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
ef8f2327 617 mz = mem_cgroup_page_nodeinfo(memcg, page);
3e32cb2e 618 excess = soft_limit_excess(memcg);
bb4cc1a8
AM
619 /*
620 * We have to update the tree if mz is on RB-tree or
621 * mem is over its softlimit.
622 */
623 if (excess || mz->on_tree) {
0a31bc97
JW
624 unsigned long flags;
625
626 spin_lock_irqsave(&mctz->lock, flags);
bb4cc1a8
AM
627 /* if on-tree, remove it */
628 if (mz->on_tree)
cf2c8127 629 __mem_cgroup_remove_exceeded(mz, mctz);
bb4cc1a8
AM
630 /*
631 * Insert again. mz->usage_in_excess will be updated.
632 * If excess is 0, no tree ops.
633 */
cf2c8127 634 __mem_cgroup_insert_exceeded(mz, mctz, excess);
0a31bc97 635 spin_unlock_irqrestore(&mctz->lock, flags);
bb4cc1a8
AM
636 }
637 }
638}
639
640static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
641{
ef8f2327
MG
642 struct mem_cgroup_tree_per_node *mctz;
643 struct mem_cgroup_per_node *mz;
644 int nid;
bb4cc1a8 645
e231875b 646 for_each_node(nid) {
ef8f2327
MG
647 mz = mem_cgroup_nodeinfo(memcg, nid);
648 mctz = soft_limit_tree_node(nid);
bfc7228b
LD
649 if (mctz)
650 mem_cgroup_remove_exceeded(mz, mctz);
bb4cc1a8
AM
651 }
652}
653
ef8f2327
MG
654static struct mem_cgroup_per_node *
655__mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
bb4cc1a8 656{
ef8f2327 657 struct mem_cgroup_per_node *mz;
bb4cc1a8
AM
658
659retry:
660 mz = NULL;
fa90b2fd 661 if (!mctz->rb_rightmost)
bb4cc1a8
AM
662 goto done; /* Nothing to reclaim from */
663
fa90b2fd
DB
664 mz = rb_entry(mctz->rb_rightmost,
665 struct mem_cgroup_per_node, tree_node);
bb4cc1a8
AM
666 /*
667 * Remove the node now but someone else can add it back,
668 * we will to add it back at the end of reclaim to its correct
669 * position in the tree.
670 */
cf2c8127 671 __mem_cgroup_remove_exceeded(mz, mctz);
3e32cb2e 672 if (!soft_limit_excess(mz->memcg) ||
ec903c0c 673 !css_tryget_online(&mz->memcg->css))
bb4cc1a8
AM
674 goto retry;
675done:
676 return mz;
677}
678
ef8f2327
MG
679static struct mem_cgroup_per_node *
680mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
bb4cc1a8 681{
ef8f2327 682 struct mem_cgroup_per_node *mz;
bb4cc1a8 683
0a31bc97 684 spin_lock_irq(&mctz->lock);
bb4cc1a8 685 mz = __mem_cgroup_largest_soft_limit_node(mctz);
0a31bc97 686 spin_unlock_irq(&mctz->lock);
bb4cc1a8
AM
687 return mz;
688}
689
db9adbcb
JW
690/**
691 * __mod_memcg_state - update cgroup memory statistics
692 * @memcg: the memory cgroup
693 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
694 * @val: delta to add to the counter, can be negative
695 */
696void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
697{
698 long x;
699
700 if (mem_cgroup_disabled())
701 return;
702
703 x = val + __this_cpu_read(memcg->vmstats_percpu->stat[idx]);
704 if (unlikely(abs(x) > MEMCG_CHARGE_BATCH)) {
42a30035
JW
705 struct mem_cgroup *mi;
706
766a4c19
YS
707 /*
708 * Batch local counters to keep them in sync with
709 * the hierarchical ones.
710 */
711 __this_cpu_add(memcg->vmstats_local->stat[idx], x);
42a30035
JW
712 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
713 atomic_long_add(x, &mi->vmstats[idx]);
db9adbcb
JW
714 x = 0;
715 }
716 __this_cpu_write(memcg->vmstats_percpu->stat[idx], x);
717}
718
42a30035
JW
719static struct mem_cgroup_per_node *
720parent_nodeinfo(struct mem_cgroup_per_node *pn, int nid)
721{
722 struct mem_cgroup *parent;
723
724 parent = parent_mem_cgroup(pn->memcg);
725 if (!parent)
726 return NULL;
727 return mem_cgroup_nodeinfo(parent, nid);
728}
729
db9adbcb
JW
730/**
731 * __mod_lruvec_state - update lruvec memory statistics
732 * @lruvec: the lruvec
733 * @idx: the stat item
734 * @val: delta to add to the counter, can be negative
735 *
736 * The lruvec is the intersection of the NUMA node and a cgroup. This
737 * function updates the all three counters that are affected by a
738 * change of state at this level: per-node, per-cgroup, per-lruvec.
739 */
740void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
741 int val)
742{
42a30035 743 pg_data_t *pgdat = lruvec_pgdat(lruvec);
db9adbcb 744 struct mem_cgroup_per_node *pn;
42a30035 745 struct mem_cgroup *memcg;
db9adbcb
JW
746 long x;
747
748 /* Update node */
42a30035 749 __mod_node_page_state(pgdat, idx, val);
db9adbcb
JW
750
751 if (mem_cgroup_disabled())
752 return;
753
754 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
42a30035 755 memcg = pn->memcg;
db9adbcb
JW
756
757 /* Update memcg */
42a30035 758 __mod_memcg_state(memcg, idx, val);
db9adbcb 759
b4c46484
RG
760 /* Update lruvec */
761 __this_cpu_add(pn->lruvec_stat_local->count[idx], val);
762
db9adbcb
JW
763 x = val + __this_cpu_read(pn->lruvec_stat_cpu->count[idx]);
764 if (unlikely(abs(x) > MEMCG_CHARGE_BATCH)) {
42a30035
JW
765 struct mem_cgroup_per_node *pi;
766
42a30035
JW
767 for (pi = pn; pi; pi = parent_nodeinfo(pi, pgdat->node_id))
768 atomic_long_add(x, &pi->lruvec_stat[idx]);
db9adbcb
JW
769 x = 0;
770 }
771 __this_cpu_write(pn->lruvec_stat_cpu->count[idx], x);
772}
773
ec9f0238
RG
774void __mod_lruvec_slab_state(void *p, enum node_stat_item idx, int val)
775{
776 struct page *page = virt_to_head_page(p);
777 pg_data_t *pgdat = page_pgdat(page);
778 struct mem_cgroup *memcg;
779 struct lruvec *lruvec;
780
781 rcu_read_lock();
782 memcg = memcg_from_slab_page(page);
783
784 /* Untracked pages have no memcg, no lruvec. Update only the node */
785 if (!memcg || memcg == root_mem_cgroup) {
786 __mod_node_page_state(pgdat, idx, val);
787 } else {
788 lruvec = mem_cgroup_lruvec(pgdat, memcg);
789 __mod_lruvec_state(lruvec, idx, val);
790 }
791 rcu_read_unlock();
792}
793
db9adbcb
JW
794/**
795 * __count_memcg_events - account VM events in a cgroup
796 * @memcg: the memory cgroup
797 * @idx: the event item
798 * @count: the number of events that occured
799 */
800void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
801 unsigned long count)
802{
803 unsigned long x;
804
805 if (mem_cgroup_disabled())
806 return;
807
808 x = count + __this_cpu_read(memcg->vmstats_percpu->events[idx]);
809 if (unlikely(x > MEMCG_CHARGE_BATCH)) {
42a30035
JW
810 struct mem_cgroup *mi;
811
766a4c19
YS
812 /*
813 * Batch local counters to keep them in sync with
814 * the hierarchical ones.
815 */
816 __this_cpu_add(memcg->vmstats_local->events[idx], x);
42a30035
JW
817 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
818 atomic_long_add(x, &mi->vmevents[idx]);
db9adbcb
JW
819 x = 0;
820 }
821 __this_cpu_write(memcg->vmstats_percpu->events[idx], x);
822}
823
42a30035 824static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
e9f8974f 825{
871789d4 826 return atomic_long_read(&memcg->vmevents[event]);
e9f8974f
JW
827}
828
42a30035
JW
829static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
830{
815744d7
JW
831 long x = 0;
832 int cpu;
833
834 for_each_possible_cpu(cpu)
835 x += per_cpu(memcg->vmstats_local->events[event], cpu);
836 return x;
42a30035
JW
837}
838
c0ff4b85 839static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
b070e65c 840 struct page *page,
f627c2f5 841 bool compound, int nr_pages)
d52aa412 842{
b2402857
KH
843 /*
844 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
845 * counted as CACHE even if it's on ANON LRU.
846 */
0a31bc97 847 if (PageAnon(page))
c9019e9b 848 __mod_memcg_state(memcg, MEMCG_RSS, nr_pages);
9a4caf1e 849 else {
c9019e9b 850 __mod_memcg_state(memcg, MEMCG_CACHE, nr_pages);
9a4caf1e 851 if (PageSwapBacked(page))
c9019e9b 852 __mod_memcg_state(memcg, NR_SHMEM, nr_pages);
9a4caf1e 853 }
55e462b0 854
f627c2f5
KS
855 if (compound) {
856 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
c9019e9b 857 __mod_memcg_state(memcg, MEMCG_RSS_HUGE, nr_pages);
f627c2f5 858 }
b070e65c 859
e401f176
KH
860 /* pagein of a big page is an event. So, ignore page size */
861 if (nr_pages > 0)
c9019e9b 862 __count_memcg_events(memcg, PGPGIN, 1);
3751d604 863 else {
c9019e9b 864 __count_memcg_events(memcg, PGPGOUT, 1);
3751d604
KH
865 nr_pages = -nr_pages; /* for event */
866 }
e401f176 867
871789d4 868 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
6d12e2d8
KH
869}
870
f53d7ce3
JW
871static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
872 enum mem_cgroup_events_target target)
7a159cc9
JW
873{
874 unsigned long val, next;
875
871789d4
CD
876 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
877 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
7a159cc9 878 /* from time_after() in jiffies.h */
6a1a8b80 879 if ((long)(next - val) < 0) {
f53d7ce3
JW
880 switch (target) {
881 case MEM_CGROUP_TARGET_THRESH:
882 next = val + THRESHOLDS_EVENTS_TARGET;
883 break;
bb4cc1a8
AM
884 case MEM_CGROUP_TARGET_SOFTLIMIT:
885 next = val + SOFTLIMIT_EVENTS_TARGET;
886 break;
f53d7ce3
JW
887 case MEM_CGROUP_TARGET_NUMAINFO:
888 next = val + NUMAINFO_EVENTS_TARGET;
889 break;
890 default:
891 break;
892 }
871789d4 893 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
f53d7ce3 894 return true;
7a159cc9 895 }
f53d7ce3 896 return false;
d2265e6f
KH
897}
898
899/*
900 * Check events in order.
901 *
902 */
c0ff4b85 903static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
d2265e6f
KH
904{
905 /* threshold event is triggered in finer grain than soft limit */
f53d7ce3
JW
906 if (unlikely(mem_cgroup_event_ratelimit(memcg,
907 MEM_CGROUP_TARGET_THRESH))) {
bb4cc1a8 908 bool do_softlimit;
82b3f2a7 909 bool do_numainfo __maybe_unused;
f53d7ce3 910
bb4cc1a8
AM
911 do_softlimit = mem_cgroup_event_ratelimit(memcg,
912 MEM_CGROUP_TARGET_SOFTLIMIT);
f53d7ce3
JW
913#if MAX_NUMNODES > 1
914 do_numainfo = mem_cgroup_event_ratelimit(memcg,
915 MEM_CGROUP_TARGET_NUMAINFO);
916#endif
c0ff4b85 917 mem_cgroup_threshold(memcg);
bb4cc1a8
AM
918 if (unlikely(do_softlimit))
919 mem_cgroup_update_tree(memcg, page);
453a9bf3 920#if MAX_NUMNODES > 1
f53d7ce3 921 if (unlikely(do_numainfo))
c0ff4b85 922 atomic_inc(&memcg->numainfo_events);
453a9bf3 923#endif
0a31bc97 924 }
d2265e6f
KH
925}
926
cf475ad2 927struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
78fb7466 928{
31a78f23
BS
929 /*
930 * mm_update_next_owner() may clear mm->owner to NULL
931 * if it races with swapoff, page migration, etc.
932 * So this can be called with p == NULL.
933 */
934 if (unlikely(!p))
935 return NULL;
936
073219e9 937 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
78fb7466 938}
33398cf2 939EXPORT_SYMBOL(mem_cgroup_from_task);
78fb7466 940
d46eb14b
SB
941/**
942 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
943 * @mm: mm from which memcg should be extracted. It can be NULL.
944 *
945 * Obtain a reference on mm->memcg and returns it if successful. Otherwise
946 * root_mem_cgroup is returned. However if mem_cgroup is disabled, NULL is
947 * returned.
948 */
949struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
54595fe2 950{
d46eb14b
SB
951 struct mem_cgroup *memcg;
952
953 if (mem_cgroup_disabled())
954 return NULL;
0b7f569e 955
54595fe2
KH
956 rcu_read_lock();
957 do {
6f6acb00
MH
958 /*
959 * Page cache insertions can happen withou an
960 * actual mm context, e.g. during disk probing
961 * on boot, loopback IO, acct() writes etc.
962 */
963 if (unlikely(!mm))
df381975 964 memcg = root_mem_cgroup;
6f6acb00
MH
965 else {
966 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
967 if (unlikely(!memcg))
968 memcg = root_mem_cgroup;
969 }
ec903c0c 970 } while (!css_tryget_online(&memcg->css));
54595fe2 971 rcu_read_unlock();
c0ff4b85 972 return memcg;
54595fe2 973}
d46eb14b
SB
974EXPORT_SYMBOL(get_mem_cgroup_from_mm);
975
f745c6f5
SB
976/**
977 * get_mem_cgroup_from_page: Obtain a reference on given page's memcg.
978 * @page: page from which memcg should be extracted.
979 *
980 * Obtain a reference on page->memcg and returns it if successful. Otherwise
981 * root_mem_cgroup is returned.
982 */
983struct mem_cgroup *get_mem_cgroup_from_page(struct page *page)
984{
985 struct mem_cgroup *memcg = page->mem_cgroup;
986
987 if (mem_cgroup_disabled())
988 return NULL;
989
990 rcu_read_lock();
991 if (!memcg || !css_tryget_online(&memcg->css))
992 memcg = root_mem_cgroup;
993 rcu_read_unlock();
994 return memcg;
995}
996EXPORT_SYMBOL(get_mem_cgroup_from_page);
997
d46eb14b
SB
998/**
999 * If current->active_memcg is non-NULL, do not fallback to current->mm->memcg.
1000 */
1001static __always_inline struct mem_cgroup *get_mem_cgroup_from_current(void)
1002{
1003 if (unlikely(current->active_memcg)) {
1004 struct mem_cgroup *memcg = root_mem_cgroup;
1005
1006 rcu_read_lock();
1007 if (css_tryget_online(&current->active_memcg->css))
1008 memcg = current->active_memcg;
1009 rcu_read_unlock();
1010 return memcg;
1011 }
1012 return get_mem_cgroup_from_mm(current->mm);
1013}
54595fe2 1014
5660048c
JW
1015/**
1016 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1017 * @root: hierarchy root
1018 * @prev: previously returned memcg, NULL on first invocation
1019 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1020 *
1021 * Returns references to children of the hierarchy below @root, or
1022 * @root itself, or %NULL after a full round-trip.
1023 *
1024 * Caller must pass the return value in @prev on subsequent
1025 * invocations for reference counting, or use mem_cgroup_iter_break()
1026 * to cancel a hierarchy walk before the round-trip is complete.
1027 *
b213b54f 1028 * Reclaimers can specify a node and a priority level in @reclaim to
5660048c 1029 * divide up the memcgs in the hierarchy among all concurrent
b213b54f 1030 * reclaimers operating on the same node and priority.
5660048c 1031 */
694fbc0f 1032struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
5660048c 1033 struct mem_cgroup *prev,
694fbc0f 1034 struct mem_cgroup_reclaim_cookie *reclaim)
14067bb3 1035{
33398cf2 1036 struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
5ac8fb31 1037 struct cgroup_subsys_state *css = NULL;
9f3a0d09 1038 struct mem_cgroup *memcg = NULL;
5ac8fb31 1039 struct mem_cgroup *pos = NULL;
711d3d2c 1040
694fbc0f
AM
1041 if (mem_cgroup_disabled())
1042 return NULL;
5660048c 1043
9f3a0d09
JW
1044 if (!root)
1045 root = root_mem_cgroup;
7d74b06f 1046
9f3a0d09 1047 if (prev && !reclaim)
5ac8fb31 1048 pos = prev;
14067bb3 1049
9f3a0d09
JW
1050 if (!root->use_hierarchy && root != root_mem_cgroup) {
1051 if (prev)
5ac8fb31 1052 goto out;
694fbc0f 1053 return root;
9f3a0d09 1054 }
14067bb3 1055
542f85f9 1056 rcu_read_lock();
5f578161 1057
5ac8fb31 1058 if (reclaim) {
ef8f2327 1059 struct mem_cgroup_per_node *mz;
5ac8fb31 1060
ef8f2327 1061 mz = mem_cgroup_nodeinfo(root, reclaim->pgdat->node_id);
5ac8fb31
JW
1062 iter = &mz->iter[reclaim->priority];
1063
1064 if (prev && reclaim->generation != iter->generation)
1065 goto out_unlock;
1066
6df38689 1067 while (1) {
4db0c3c2 1068 pos = READ_ONCE(iter->position);
6df38689
VD
1069 if (!pos || css_tryget(&pos->css))
1070 break;
5ac8fb31 1071 /*
6df38689
VD
1072 * css reference reached zero, so iter->position will
1073 * be cleared by ->css_released. However, we should not
1074 * rely on this happening soon, because ->css_released
1075 * is called from a work queue, and by busy-waiting we
1076 * might block it. So we clear iter->position right
1077 * away.
5ac8fb31 1078 */
6df38689
VD
1079 (void)cmpxchg(&iter->position, pos, NULL);
1080 }
5ac8fb31
JW
1081 }
1082
1083 if (pos)
1084 css = &pos->css;
1085
1086 for (;;) {
1087 css = css_next_descendant_pre(css, &root->css);
1088 if (!css) {
1089 /*
1090 * Reclaimers share the hierarchy walk, and a
1091 * new one might jump in right at the end of
1092 * the hierarchy - make sure they see at least
1093 * one group and restart from the beginning.
1094 */
1095 if (!prev)
1096 continue;
1097 break;
527a5ec9 1098 }
7d74b06f 1099
5ac8fb31
JW
1100 /*
1101 * Verify the css and acquire a reference. The root
1102 * is provided by the caller, so we know it's alive
1103 * and kicking, and don't take an extra reference.
1104 */
1105 memcg = mem_cgroup_from_css(css);
14067bb3 1106
5ac8fb31
JW
1107 if (css == &root->css)
1108 break;
14067bb3 1109
0b8f73e1
JW
1110 if (css_tryget(css))
1111 break;
9f3a0d09 1112
5ac8fb31 1113 memcg = NULL;
9f3a0d09 1114 }
5ac8fb31
JW
1115
1116 if (reclaim) {
5ac8fb31 1117 /*
6df38689
VD
1118 * The position could have already been updated by a competing
1119 * thread, so check that the value hasn't changed since we read
1120 * it to avoid reclaiming from the same cgroup twice.
5ac8fb31 1121 */
6df38689
VD
1122 (void)cmpxchg(&iter->position, pos, memcg);
1123
5ac8fb31
JW
1124 if (pos)
1125 css_put(&pos->css);
1126
1127 if (!memcg)
1128 iter->generation++;
1129 else if (!prev)
1130 reclaim->generation = iter->generation;
9f3a0d09 1131 }
5ac8fb31 1132
542f85f9
MH
1133out_unlock:
1134 rcu_read_unlock();
5ac8fb31 1135out:
c40046f3
MH
1136 if (prev && prev != root)
1137 css_put(&prev->css);
1138
9f3a0d09 1139 return memcg;
14067bb3 1140}
7d74b06f 1141
5660048c
JW
1142/**
1143 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1144 * @root: hierarchy root
1145 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1146 */
1147void mem_cgroup_iter_break(struct mem_cgroup *root,
1148 struct mem_cgroup *prev)
9f3a0d09
JW
1149{
1150 if (!root)
1151 root = root_mem_cgroup;
1152 if (prev && prev != root)
1153 css_put(&prev->css);
1154}
7d74b06f 1155
54a83d6b
MC
1156static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1157 struct mem_cgroup *dead_memcg)
6df38689 1158{
6df38689 1159 struct mem_cgroup_reclaim_iter *iter;
ef8f2327
MG
1160 struct mem_cgroup_per_node *mz;
1161 int nid;
6df38689
VD
1162 int i;
1163
54a83d6b
MC
1164 for_each_node(nid) {
1165 mz = mem_cgroup_nodeinfo(from, nid);
1166 for (i = 0; i <= DEF_PRIORITY; i++) {
1167 iter = &mz->iter[i];
1168 cmpxchg(&iter->position,
1169 dead_memcg, NULL);
6df38689
VD
1170 }
1171 }
1172}
1173
54a83d6b
MC
1174static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1175{
1176 struct mem_cgroup *memcg = dead_memcg;
1177 struct mem_cgroup *last;
1178
1179 do {
1180 __invalidate_reclaim_iterators(memcg, dead_memcg);
1181 last = memcg;
1182 } while ((memcg = parent_mem_cgroup(memcg)));
1183
1184 /*
1185 * When cgruop1 non-hierarchy mode is used,
1186 * parent_mem_cgroup() does not walk all the way up to the
1187 * cgroup root (root_mem_cgroup). So we have to handle
1188 * dead_memcg from cgroup root separately.
1189 */
1190 if (last != root_mem_cgroup)
1191 __invalidate_reclaim_iterators(root_mem_cgroup,
1192 dead_memcg);
1193}
1194
7c5f64f8
VD
1195/**
1196 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1197 * @memcg: hierarchy root
1198 * @fn: function to call for each task
1199 * @arg: argument passed to @fn
1200 *
1201 * This function iterates over tasks attached to @memcg or to any of its
1202 * descendants and calls @fn for each task. If @fn returns a non-zero
1203 * value, the function breaks the iteration loop and returns the value.
1204 * Otherwise, it will iterate over all tasks and return 0.
1205 *
1206 * This function must not be called for the root memory cgroup.
1207 */
1208int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1209 int (*fn)(struct task_struct *, void *), void *arg)
1210{
1211 struct mem_cgroup *iter;
1212 int ret = 0;
1213
1214 BUG_ON(memcg == root_mem_cgroup);
1215
1216 for_each_mem_cgroup_tree(iter, memcg) {
1217 struct css_task_iter it;
1218 struct task_struct *task;
1219
f168a9a5 1220 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
7c5f64f8
VD
1221 while (!ret && (task = css_task_iter_next(&it)))
1222 ret = fn(task, arg);
1223 css_task_iter_end(&it);
1224 if (ret) {
1225 mem_cgroup_iter_break(memcg, iter);
1226 break;
1227 }
1228 }
1229 return ret;
1230}
1231
925b7673 1232/**
dfe0e773 1233 * mem_cgroup_page_lruvec - return lruvec for isolating/putting an LRU page
925b7673 1234 * @page: the page
f144c390 1235 * @pgdat: pgdat of the page
dfe0e773
JW
1236 *
1237 * This function is only safe when following the LRU page isolation
1238 * and putback protocol: the LRU lock must be held, and the page must
1239 * either be PageLRU() or the caller must have isolated/allocated it.
925b7673 1240 */
599d0c95 1241struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct pglist_data *pgdat)
08e552c6 1242{
ef8f2327 1243 struct mem_cgroup_per_node *mz;
925b7673 1244 struct mem_cgroup *memcg;
bea8c150 1245 struct lruvec *lruvec;
6d12e2d8 1246
bea8c150 1247 if (mem_cgroup_disabled()) {
599d0c95 1248 lruvec = &pgdat->lruvec;
bea8c150
HD
1249 goto out;
1250 }
925b7673 1251
1306a85a 1252 memcg = page->mem_cgroup;
7512102c 1253 /*
dfe0e773 1254 * Swapcache readahead pages are added to the LRU - and
29833315 1255 * possibly migrated - before they are charged.
7512102c 1256 */
29833315
JW
1257 if (!memcg)
1258 memcg = root_mem_cgroup;
7512102c 1259
ef8f2327 1260 mz = mem_cgroup_page_nodeinfo(memcg, page);
bea8c150
HD
1261 lruvec = &mz->lruvec;
1262out:
1263 /*
1264 * Since a node can be onlined after the mem_cgroup was created,
1265 * we have to be prepared to initialize lruvec->zone here;
1266 * and if offlined then reonlined, we need to reinitialize it.
1267 */
599d0c95
MG
1268 if (unlikely(lruvec->pgdat != pgdat))
1269 lruvec->pgdat = pgdat;
bea8c150 1270 return lruvec;
08e552c6 1271}
b69408e8 1272
925b7673 1273/**
fa9add64
HD
1274 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1275 * @lruvec: mem_cgroup per zone lru vector
1276 * @lru: index of lru list the page is sitting on
b4536f0c 1277 * @zid: zone id of the accounted pages
fa9add64 1278 * @nr_pages: positive when adding or negative when removing
925b7673 1279 *
ca707239
HD
1280 * This function must be called under lru_lock, just before a page is added
1281 * to or just after a page is removed from an lru list (that ordering being
1282 * so as to allow it to check that lru_size 0 is consistent with list_empty).
3f58a829 1283 */
fa9add64 1284void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
b4536f0c 1285 int zid, int nr_pages)
3f58a829 1286{
ef8f2327 1287 struct mem_cgroup_per_node *mz;
fa9add64 1288 unsigned long *lru_size;
ca707239 1289 long size;
3f58a829
MK
1290
1291 if (mem_cgroup_disabled())
1292 return;
1293
ef8f2327 1294 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
b4536f0c 1295 lru_size = &mz->lru_zone_size[zid][lru];
ca707239
HD
1296
1297 if (nr_pages < 0)
1298 *lru_size += nr_pages;
1299
1300 size = *lru_size;
b4536f0c
MH
1301 if (WARN_ONCE(size < 0,
1302 "%s(%p, %d, %d): lru_size %ld\n",
1303 __func__, lruvec, lru, nr_pages, size)) {
ca707239
HD
1304 VM_BUG_ON(1);
1305 *lru_size = 0;
1306 }
1307
1308 if (nr_pages > 0)
1309 *lru_size += nr_pages;
08e552c6 1310}
544122e5 1311
19942822 1312/**
9d11ea9f 1313 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
dad7557e 1314 * @memcg: the memory cgroup
19942822 1315 *
9d11ea9f 1316 * Returns the maximum amount of memory @mem can be charged with, in
7ec99d62 1317 * pages.
19942822 1318 */
c0ff4b85 1319static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
19942822 1320{
3e32cb2e
JW
1321 unsigned long margin = 0;
1322 unsigned long count;
1323 unsigned long limit;
9d11ea9f 1324
3e32cb2e 1325 count = page_counter_read(&memcg->memory);
bbec2e15 1326 limit = READ_ONCE(memcg->memory.max);
3e32cb2e
JW
1327 if (count < limit)
1328 margin = limit - count;
1329
7941d214 1330 if (do_memsw_account()) {
3e32cb2e 1331 count = page_counter_read(&memcg->memsw);
bbec2e15 1332 limit = READ_ONCE(memcg->memsw.max);
3e32cb2e
JW
1333 if (count <= limit)
1334 margin = min(margin, limit - count);
cbedbac3
LR
1335 else
1336 margin = 0;
3e32cb2e
JW
1337 }
1338
1339 return margin;
19942822
JW
1340}
1341
32047e2a 1342/*
bdcbb659 1343 * A routine for checking "mem" is under move_account() or not.
32047e2a 1344 *
bdcbb659
QH
1345 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1346 * moving cgroups. This is for waiting at high-memory pressure
1347 * caused by "move".
32047e2a 1348 */
c0ff4b85 1349static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
4b534334 1350{
2bd9bb20
KH
1351 struct mem_cgroup *from;
1352 struct mem_cgroup *to;
4b534334 1353 bool ret = false;
2bd9bb20
KH
1354 /*
1355 * Unlike task_move routines, we access mc.to, mc.from not under
1356 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1357 */
1358 spin_lock(&mc.lock);
1359 from = mc.from;
1360 to = mc.to;
1361 if (!from)
1362 goto unlock;
3e92041d 1363
2314b42d
JW
1364 ret = mem_cgroup_is_descendant(from, memcg) ||
1365 mem_cgroup_is_descendant(to, memcg);
2bd9bb20
KH
1366unlock:
1367 spin_unlock(&mc.lock);
4b534334
KH
1368 return ret;
1369}
1370
c0ff4b85 1371static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
4b534334
KH
1372{
1373 if (mc.moving_task && current != mc.moving_task) {
c0ff4b85 1374 if (mem_cgroup_under_move(memcg)) {
4b534334
KH
1375 DEFINE_WAIT(wait);
1376 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1377 /* moving charge context might have finished. */
1378 if (mc.moving_task)
1379 schedule();
1380 finish_wait(&mc.waitq, &wait);
1381 return true;
1382 }
1383 }
1384 return false;
1385}
1386
c8713d0b
JW
1387static char *memory_stat_format(struct mem_cgroup *memcg)
1388{
1389 struct seq_buf s;
1390 int i;
71cd3113 1391
c8713d0b
JW
1392 seq_buf_init(&s, kmalloc(PAGE_SIZE, GFP_KERNEL), PAGE_SIZE);
1393 if (!s.buffer)
1394 return NULL;
1395
1396 /*
1397 * Provide statistics on the state of the memory subsystem as
1398 * well as cumulative event counters that show past behavior.
1399 *
1400 * This list is ordered following a combination of these gradients:
1401 * 1) generic big picture -> specifics and details
1402 * 2) reflecting userspace activity -> reflecting kernel heuristics
1403 *
1404 * Current memory state:
1405 */
1406
1407 seq_buf_printf(&s, "anon %llu\n",
1408 (u64)memcg_page_state(memcg, MEMCG_RSS) *
1409 PAGE_SIZE);
1410 seq_buf_printf(&s, "file %llu\n",
1411 (u64)memcg_page_state(memcg, MEMCG_CACHE) *
1412 PAGE_SIZE);
1413 seq_buf_printf(&s, "kernel_stack %llu\n",
1414 (u64)memcg_page_state(memcg, MEMCG_KERNEL_STACK_KB) *
1415 1024);
1416 seq_buf_printf(&s, "slab %llu\n",
1417 (u64)(memcg_page_state(memcg, NR_SLAB_RECLAIMABLE) +
1418 memcg_page_state(memcg, NR_SLAB_UNRECLAIMABLE)) *
1419 PAGE_SIZE);
1420 seq_buf_printf(&s, "sock %llu\n",
1421 (u64)memcg_page_state(memcg, MEMCG_SOCK) *
1422 PAGE_SIZE);
1423
1424 seq_buf_printf(&s, "shmem %llu\n",
1425 (u64)memcg_page_state(memcg, NR_SHMEM) *
1426 PAGE_SIZE);
1427 seq_buf_printf(&s, "file_mapped %llu\n",
1428 (u64)memcg_page_state(memcg, NR_FILE_MAPPED) *
1429 PAGE_SIZE);
1430 seq_buf_printf(&s, "file_dirty %llu\n",
1431 (u64)memcg_page_state(memcg, NR_FILE_DIRTY) *
1432 PAGE_SIZE);
1433 seq_buf_printf(&s, "file_writeback %llu\n",
1434 (u64)memcg_page_state(memcg, NR_WRITEBACK) *
1435 PAGE_SIZE);
1436
1437 /*
1438 * TODO: We should eventually replace our own MEMCG_RSS_HUGE counter
1439 * with the NR_ANON_THP vm counter, but right now it's a pain in the
1440 * arse because it requires migrating the work out of rmap to a place
1441 * where the page->mem_cgroup is set up and stable.
1442 */
1443 seq_buf_printf(&s, "anon_thp %llu\n",
1444 (u64)memcg_page_state(memcg, MEMCG_RSS_HUGE) *
1445 PAGE_SIZE);
1446
1447 for (i = 0; i < NR_LRU_LISTS; i++)
1448 seq_buf_printf(&s, "%s %llu\n", mem_cgroup_lru_names[i],
1449 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
1450 PAGE_SIZE);
1451
1452 seq_buf_printf(&s, "slab_reclaimable %llu\n",
1453 (u64)memcg_page_state(memcg, NR_SLAB_RECLAIMABLE) *
1454 PAGE_SIZE);
1455 seq_buf_printf(&s, "slab_unreclaimable %llu\n",
1456 (u64)memcg_page_state(memcg, NR_SLAB_UNRECLAIMABLE) *
1457 PAGE_SIZE);
1458
1459 /* Accumulated memory events */
1460
1461 seq_buf_printf(&s, "pgfault %lu\n", memcg_events(memcg, PGFAULT));
1462 seq_buf_printf(&s, "pgmajfault %lu\n", memcg_events(memcg, PGMAJFAULT));
1463
1464 seq_buf_printf(&s, "workingset_refault %lu\n",
1465 memcg_page_state(memcg, WORKINGSET_REFAULT));
1466 seq_buf_printf(&s, "workingset_activate %lu\n",
1467 memcg_page_state(memcg, WORKINGSET_ACTIVATE));
1468 seq_buf_printf(&s, "workingset_nodereclaim %lu\n",
1469 memcg_page_state(memcg, WORKINGSET_NODERECLAIM));
1470
1471 seq_buf_printf(&s, "pgrefill %lu\n", memcg_events(memcg, PGREFILL));
1472 seq_buf_printf(&s, "pgscan %lu\n",
1473 memcg_events(memcg, PGSCAN_KSWAPD) +
1474 memcg_events(memcg, PGSCAN_DIRECT));
1475 seq_buf_printf(&s, "pgsteal %lu\n",
1476 memcg_events(memcg, PGSTEAL_KSWAPD) +
1477 memcg_events(memcg, PGSTEAL_DIRECT));
1478 seq_buf_printf(&s, "pgactivate %lu\n", memcg_events(memcg, PGACTIVATE));
1479 seq_buf_printf(&s, "pgdeactivate %lu\n", memcg_events(memcg, PGDEACTIVATE));
1480 seq_buf_printf(&s, "pglazyfree %lu\n", memcg_events(memcg, PGLAZYFREE));
1481 seq_buf_printf(&s, "pglazyfreed %lu\n", memcg_events(memcg, PGLAZYFREED));
1482
1483#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1484 seq_buf_printf(&s, "thp_fault_alloc %lu\n",
1485 memcg_events(memcg, THP_FAULT_ALLOC));
1486 seq_buf_printf(&s, "thp_collapse_alloc %lu\n",
1487 memcg_events(memcg, THP_COLLAPSE_ALLOC));
1488#endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1489
1490 /* The above should easily fit into one page */
1491 WARN_ON_ONCE(seq_buf_has_overflowed(&s));
1492
1493 return s.buffer;
1494}
71cd3113 1495
58cf188e 1496#define K(x) ((x) << (PAGE_SHIFT-10))
e222432b 1497/**
f0c867d9 1498 * mem_cgroup_print_oom_context: Print OOM information relevant to
1499 * memory controller.
e222432b
BS
1500 * @memcg: The memory cgroup that went over limit
1501 * @p: Task that is going to be killed
1502 *
1503 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1504 * enabled
1505 */
f0c867d9 1506void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
e222432b 1507{
e222432b
BS
1508 rcu_read_lock();
1509
f0c867d9 1510 if (memcg) {
1511 pr_cont(",oom_memcg=");
1512 pr_cont_cgroup_path(memcg->css.cgroup);
1513 } else
1514 pr_cont(",global_oom");
2415b9f5 1515 if (p) {
f0c867d9 1516 pr_cont(",task_memcg=");
2415b9f5 1517 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
2415b9f5 1518 }
e222432b 1519 rcu_read_unlock();
f0c867d9 1520}
1521
1522/**
1523 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1524 * memory controller.
1525 * @memcg: The memory cgroup that went over limit
1526 */
1527void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1528{
c8713d0b 1529 char *buf;
e222432b 1530
3e32cb2e
JW
1531 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1532 K((u64)page_counter_read(&memcg->memory)),
bbec2e15 1533 K((u64)memcg->memory.max), memcg->memory.failcnt);
c8713d0b
JW
1534 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1535 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1536 K((u64)page_counter_read(&memcg->swap)),
1537 K((u64)memcg->swap.max), memcg->swap.failcnt);
1538 else {
1539 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1540 K((u64)page_counter_read(&memcg->memsw)),
1541 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1542 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1543 K((u64)page_counter_read(&memcg->kmem)),
1544 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
58cf188e 1545 }
c8713d0b
JW
1546
1547 pr_info("Memory cgroup stats for ");
1548 pr_cont_cgroup_path(memcg->css.cgroup);
1549 pr_cont(":");
1550 buf = memory_stat_format(memcg);
1551 if (!buf)
1552 return;
1553 pr_info("%s", buf);
1554 kfree(buf);
e222432b
BS
1555}
1556
a63d83f4
DR
1557/*
1558 * Return the memory (and swap, if configured) limit for a memcg.
1559 */
bbec2e15 1560unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
a63d83f4 1561{
bbec2e15 1562 unsigned long max;
f3e8eb70 1563
bbec2e15 1564 max = memcg->memory.max;
9a5a8f19 1565 if (mem_cgroup_swappiness(memcg)) {
bbec2e15
RG
1566 unsigned long memsw_max;
1567 unsigned long swap_max;
9a5a8f19 1568
bbec2e15
RG
1569 memsw_max = memcg->memsw.max;
1570 swap_max = memcg->swap.max;
1571 swap_max = min(swap_max, (unsigned long)total_swap_pages);
1572 max = min(max + swap_max, memsw_max);
9a5a8f19 1573 }
bbec2e15 1574 return max;
a63d83f4
DR
1575}
1576
b6e6edcf 1577static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
19965460 1578 int order)
9cbb78bb 1579{
6e0fc46d
DR
1580 struct oom_control oc = {
1581 .zonelist = NULL,
1582 .nodemask = NULL,
2a966b77 1583 .memcg = memcg,
6e0fc46d
DR
1584 .gfp_mask = gfp_mask,
1585 .order = order,
6e0fc46d 1586 };
7c5f64f8 1587 bool ret;
9cbb78bb 1588
7775face
TH
1589 if (mutex_lock_killable(&oom_lock))
1590 return true;
1591 /*
1592 * A few threads which were not waiting at mutex_lock_killable() can
1593 * fail to bail out. Therefore, check again after holding oom_lock.
1594 */
1595 ret = should_force_charge() || out_of_memory(&oc);
dc56401f 1596 mutex_unlock(&oom_lock);
7c5f64f8 1597 return ret;
9cbb78bb
DR
1598}
1599
ae6e71d3
MC
1600#if MAX_NUMNODES > 1
1601
4d0c066d
KH
1602/**
1603 * test_mem_cgroup_node_reclaimable
dad7557e 1604 * @memcg: the target memcg
4d0c066d
KH
1605 * @nid: the node ID to be checked.
1606 * @noswap : specify true here if the user wants flle only information.
1607 *
1608 * This function returns whether the specified memcg contains any
1609 * reclaimable pages on a node. Returns true if there are any reclaimable
1610 * pages in the node.
1611 */
c0ff4b85 1612static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
4d0c066d
KH
1613 int nid, bool noswap)
1614{
2b487e59
JW
1615 struct lruvec *lruvec = mem_cgroup_lruvec(NODE_DATA(nid), memcg);
1616
def0fdae
JW
1617 if (lruvec_page_state(lruvec, NR_INACTIVE_FILE) ||
1618 lruvec_page_state(lruvec, NR_ACTIVE_FILE))
4d0c066d
KH
1619 return true;
1620 if (noswap || !total_swap_pages)
1621 return false;
def0fdae
JW
1622 if (lruvec_page_state(lruvec, NR_INACTIVE_ANON) ||
1623 lruvec_page_state(lruvec, NR_ACTIVE_ANON))
4d0c066d
KH
1624 return true;
1625 return false;
1626
1627}
889976db
YH
1628
1629/*
1630 * Always updating the nodemask is not very good - even if we have an empty
1631 * list or the wrong list here, we can start from some node and traverse all
1632 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1633 *
1634 */
c0ff4b85 1635static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
889976db
YH
1636{
1637 int nid;
453a9bf3
KH
1638 /*
1639 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1640 * pagein/pageout changes since the last update.
1641 */
c0ff4b85 1642 if (!atomic_read(&memcg->numainfo_events))
453a9bf3 1643 return;
c0ff4b85 1644 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
889976db
YH
1645 return;
1646
889976db 1647 /* make a nodemask where this memcg uses memory from */
31aaea4a 1648 memcg->scan_nodes = node_states[N_MEMORY];
889976db 1649
31aaea4a 1650 for_each_node_mask(nid, node_states[N_MEMORY]) {
889976db 1651
c0ff4b85
R
1652 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1653 node_clear(nid, memcg->scan_nodes);
889976db 1654 }
453a9bf3 1655
c0ff4b85
R
1656 atomic_set(&memcg->numainfo_events, 0);
1657 atomic_set(&memcg->numainfo_updating, 0);
889976db
YH
1658}
1659
1660/*
1661 * Selecting a node where we start reclaim from. Because what we need is just
1662 * reducing usage counter, start from anywhere is O,K. Considering
1663 * memory reclaim from current node, there are pros. and cons.
1664 *
1665 * Freeing memory from current node means freeing memory from a node which
1666 * we'll use or we've used. So, it may make LRU bad. And if several threads
1667 * hit limits, it will see a contention on a node. But freeing from remote
1668 * node means more costs for memory reclaim because of memory latency.
1669 *
1670 * Now, we use round-robin. Better algorithm is welcomed.
1671 */
c0ff4b85 1672int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
889976db
YH
1673{
1674 int node;
1675
c0ff4b85
R
1676 mem_cgroup_may_update_nodemask(memcg);
1677 node = memcg->last_scanned_node;
889976db 1678
0edaf86c 1679 node = next_node_in(node, memcg->scan_nodes);
889976db 1680 /*
fda3d69b
MH
1681 * mem_cgroup_may_update_nodemask might have seen no reclaimmable pages
1682 * last time it really checked all the LRUs due to rate limiting.
1683 * Fallback to the current node in that case for simplicity.
889976db
YH
1684 */
1685 if (unlikely(node == MAX_NUMNODES))
1686 node = numa_node_id();
1687
c0ff4b85 1688 memcg->last_scanned_node = node;
889976db
YH
1689 return node;
1690}
889976db 1691#else
c0ff4b85 1692int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
889976db
YH
1693{
1694 return 0;
1695}
1696#endif
1697
0608f43d 1698static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
ef8f2327 1699 pg_data_t *pgdat,
0608f43d
AM
1700 gfp_t gfp_mask,
1701 unsigned long *total_scanned)
1702{
1703 struct mem_cgroup *victim = NULL;
1704 int total = 0;
1705 int loop = 0;
1706 unsigned long excess;
1707 unsigned long nr_scanned;
1708 struct mem_cgroup_reclaim_cookie reclaim = {
ef8f2327 1709 .pgdat = pgdat,
0608f43d
AM
1710 .priority = 0,
1711 };
1712
3e32cb2e 1713 excess = soft_limit_excess(root_memcg);
0608f43d
AM
1714
1715 while (1) {
1716 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1717 if (!victim) {
1718 loop++;
1719 if (loop >= 2) {
1720 /*
1721 * If we have not been able to reclaim
1722 * anything, it might because there are
1723 * no reclaimable pages under this hierarchy
1724 */
1725 if (!total)
1726 break;
1727 /*
1728 * We want to do more targeted reclaim.
1729 * excess >> 2 is not to excessive so as to
1730 * reclaim too much, nor too less that we keep
1731 * coming back to reclaim from this cgroup
1732 */
1733 if (total >= (excess >> 2) ||
1734 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1735 break;
1736 }
1737 continue;
1738 }
a9dd0a83 1739 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
ef8f2327 1740 pgdat, &nr_scanned);
0608f43d 1741 *total_scanned += nr_scanned;
3e32cb2e 1742 if (!soft_limit_excess(root_memcg))
0608f43d 1743 break;
6d61ef40 1744 }
0608f43d
AM
1745 mem_cgroup_iter_break(root_memcg, victim);
1746 return total;
6d61ef40
BS
1747}
1748
0056f4e6
JW
1749#ifdef CONFIG_LOCKDEP
1750static struct lockdep_map memcg_oom_lock_dep_map = {
1751 .name = "memcg_oom_lock",
1752};
1753#endif
1754
fb2a6fc5
JW
1755static DEFINE_SPINLOCK(memcg_oom_lock);
1756
867578cb
KH
1757/*
1758 * Check OOM-Killer is already running under our hierarchy.
1759 * If someone is running, return false.
1760 */
fb2a6fc5 1761static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
867578cb 1762{
79dfdacc 1763 struct mem_cgroup *iter, *failed = NULL;
a636b327 1764
fb2a6fc5
JW
1765 spin_lock(&memcg_oom_lock);
1766
9f3a0d09 1767 for_each_mem_cgroup_tree(iter, memcg) {
23751be0 1768 if (iter->oom_lock) {
79dfdacc
MH
1769 /*
1770 * this subtree of our hierarchy is already locked
1771 * so we cannot give a lock.
1772 */
79dfdacc 1773 failed = iter;
9f3a0d09
JW
1774 mem_cgroup_iter_break(memcg, iter);
1775 break;
23751be0
JW
1776 } else
1777 iter->oom_lock = true;
7d74b06f 1778 }
867578cb 1779
fb2a6fc5
JW
1780 if (failed) {
1781 /*
1782 * OK, we failed to lock the whole subtree so we have
1783 * to clean up what we set up to the failing subtree
1784 */
1785 for_each_mem_cgroup_tree(iter, memcg) {
1786 if (iter == failed) {
1787 mem_cgroup_iter_break(memcg, iter);
1788 break;
1789 }
1790 iter->oom_lock = false;
79dfdacc 1791 }
0056f4e6
JW
1792 } else
1793 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
fb2a6fc5
JW
1794
1795 spin_unlock(&memcg_oom_lock);
1796
1797 return !failed;
a636b327 1798}
0b7f569e 1799
fb2a6fc5 1800static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
0b7f569e 1801{
7d74b06f
KH
1802 struct mem_cgroup *iter;
1803
fb2a6fc5 1804 spin_lock(&memcg_oom_lock);
0056f4e6 1805 mutex_release(&memcg_oom_lock_dep_map, 1, _RET_IP_);
c0ff4b85 1806 for_each_mem_cgroup_tree(iter, memcg)
79dfdacc 1807 iter->oom_lock = false;
fb2a6fc5 1808 spin_unlock(&memcg_oom_lock);
79dfdacc
MH
1809}
1810
c0ff4b85 1811static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
79dfdacc
MH
1812{
1813 struct mem_cgroup *iter;
1814
c2b42d3c 1815 spin_lock(&memcg_oom_lock);
c0ff4b85 1816 for_each_mem_cgroup_tree(iter, memcg)
c2b42d3c
TH
1817 iter->under_oom++;
1818 spin_unlock(&memcg_oom_lock);
79dfdacc
MH
1819}
1820
c0ff4b85 1821static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
79dfdacc
MH
1822{
1823 struct mem_cgroup *iter;
1824
867578cb
KH
1825 /*
1826 * When a new child is created while the hierarchy is under oom,
c2b42d3c 1827 * mem_cgroup_oom_lock() may not be called. Watch for underflow.
867578cb 1828 */
c2b42d3c 1829 spin_lock(&memcg_oom_lock);
c0ff4b85 1830 for_each_mem_cgroup_tree(iter, memcg)
c2b42d3c
TH
1831 if (iter->under_oom > 0)
1832 iter->under_oom--;
1833 spin_unlock(&memcg_oom_lock);
0b7f569e
KH
1834}
1835
867578cb
KH
1836static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1837
dc98df5a 1838struct oom_wait_info {
d79154bb 1839 struct mem_cgroup *memcg;
ac6424b9 1840 wait_queue_entry_t wait;
dc98df5a
KH
1841};
1842
ac6424b9 1843static int memcg_oom_wake_function(wait_queue_entry_t *wait,
dc98df5a
KH
1844 unsigned mode, int sync, void *arg)
1845{
d79154bb
HD
1846 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1847 struct mem_cgroup *oom_wait_memcg;
dc98df5a
KH
1848 struct oom_wait_info *oom_wait_info;
1849
1850 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
d79154bb 1851 oom_wait_memcg = oom_wait_info->memcg;
dc98df5a 1852
2314b42d
JW
1853 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1854 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
dc98df5a 1855 return 0;
dc98df5a
KH
1856 return autoremove_wake_function(wait, mode, sync, arg);
1857}
1858
c0ff4b85 1859static void memcg_oom_recover(struct mem_cgroup *memcg)
3c11ecf4 1860{
c2b42d3c
TH
1861 /*
1862 * For the following lockless ->under_oom test, the only required
1863 * guarantee is that it must see the state asserted by an OOM when
1864 * this function is called as a result of userland actions
1865 * triggered by the notification of the OOM. This is trivially
1866 * achieved by invoking mem_cgroup_mark_under_oom() before
1867 * triggering notification.
1868 */
1869 if (memcg && memcg->under_oom)
f4b90b70 1870 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
3c11ecf4
KH
1871}
1872
29ef680a
MH
1873enum oom_status {
1874 OOM_SUCCESS,
1875 OOM_FAILED,
1876 OOM_ASYNC,
1877 OOM_SKIPPED
1878};
1879
1880static enum oom_status mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
0b7f569e 1881{
7056d3a3
MH
1882 enum oom_status ret;
1883 bool locked;
1884
29ef680a
MH
1885 if (order > PAGE_ALLOC_COSTLY_ORDER)
1886 return OOM_SKIPPED;
1887
7a1adfdd
RG
1888 memcg_memory_event(memcg, MEMCG_OOM);
1889
867578cb 1890 /*
49426420
JW
1891 * We are in the middle of the charge context here, so we
1892 * don't want to block when potentially sitting on a callstack
1893 * that holds all kinds of filesystem and mm locks.
1894 *
29ef680a
MH
1895 * cgroup1 allows disabling the OOM killer and waiting for outside
1896 * handling until the charge can succeed; remember the context and put
1897 * the task to sleep at the end of the page fault when all locks are
1898 * released.
49426420 1899 *
29ef680a
MH
1900 * On the other hand, in-kernel OOM killer allows for an async victim
1901 * memory reclaim (oom_reaper) and that means that we are not solely
1902 * relying on the oom victim to make a forward progress and we can
1903 * invoke the oom killer here.
1904 *
1905 * Please note that mem_cgroup_out_of_memory might fail to find a
1906 * victim and then we have to bail out from the charge path.
867578cb 1907 */
29ef680a
MH
1908 if (memcg->oom_kill_disable) {
1909 if (!current->in_user_fault)
1910 return OOM_SKIPPED;
1911 css_get(&memcg->css);
1912 current->memcg_in_oom = memcg;
1913 current->memcg_oom_gfp_mask = mask;
1914 current->memcg_oom_order = order;
1915
1916 return OOM_ASYNC;
1917 }
1918
7056d3a3
MH
1919 mem_cgroup_mark_under_oom(memcg);
1920
1921 locked = mem_cgroup_oom_trylock(memcg);
1922
1923 if (locked)
1924 mem_cgroup_oom_notify(memcg);
1925
1926 mem_cgroup_unmark_under_oom(memcg);
29ef680a 1927 if (mem_cgroup_out_of_memory(memcg, mask, order))
7056d3a3
MH
1928 ret = OOM_SUCCESS;
1929 else
1930 ret = OOM_FAILED;
1931
1932 if (locked)
1933 mem_cgroup_oom_unlock(memcg);
29ef680a 1934
7056d3a3 1935 return ret;
3812c8c8
JW
1936}
1937
1938/**
1939 * mem_cgroup_oom_synchronize - complete memcg OOM handling
49426420 1940 * @handle: actually kill/wait or just clean up the OOM state
3812c8c8 1941 *
49426420
JW
1942 * This has to be called at the end of a page fault if the memcg OOM
1943 * handler was enabled.
3812c8c8 1944 *
49426420 1945 * Memcg supports userspace OOM handling where failed allocations must
3812c8c8
JW
1946 * sleep on a waitqueue until the userspace task resolves the
1947 * situation. Sleeping directly in the charge context with all kinds
1948 * of locks held is not a good idea, instead we remember an OOM state
1949 * in the task and mem_cgroup_oom_synchronize() has to be called at
49426420 1950 * the end of the page fault to complete the OOM handling.
3812c8c8
JW
1951 *
1952 * Returns %true if an ongoing memcg OOM situation was detected and
49426420 1953 * completed, %false otherwise.
3812c8c8 1954 */
49426420 1955bool mem_cgroup_oom_synchronize(bool handle)
3812c8c8 1956{
626ebc41 1957 struct mem_cgroup *memcg = current->memcg_in_oom;
3812c8c8 1958 struct oom_wait_info owait;
49426420 1959 bool locked;
3812c8c8
JW
1960
1961 /* OOM is global, do not handle */
3812c8c8 1962 if (!memcg)
49426420 1963 return false;
3812c8c8 1964
7c5f64f8 1965 if (!handle)
49426420 1966 goto cleanup;
3812c8c8
JW
1967
1968 owait.memcg = memcg;
1969 owait.wait.flags = 0;
1970 owait.wait.func = memcg_oom_wake_function;
1971 owait.wait.private = current;
2055da97 1972 INIT_LIST_HEAD(&owait.wait.entry);
867578cb 1973
3812c8c8 1974 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
49426420
JW
1975 mem_cgroup_mark_under_oom(memcg);
1976
1977 locked = mem_cgroup_oom_trylock(memcg);
1978
1979 if (locked)
1980 mem_cgroup_oom_notify(memcg);
1981
1982 if (locked && !memcg->oom_kill_disable) {
1983 mem_cgroup_unmark_under_oom(memcg);
1984 finish_wait(&memcg_oom_waitq, &owait.wait);
626ebc41
TH
1985 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
1986 current->memcg_oom_order);
49426420 1987 } else {
3812c8c8 1988 schedule();
49426420
JW
1989 mem_cgroup_unmark_under_oom(memcg);
1990 finish_wait(&memcg_oom_waitq, &owait.wait);
1991 }
1992
1993 if (locked) {
fb2a6fc5
JW
1994 mem_cgroup_oom_unlock(memcg);
1995 /*
1996 * There is no guarantee that an OOM-lock contender
1997 * sees the wakeups triggered by the OOM kill
1998 * uncharges. Wake any sleepers explicitely.
1999 */
2000 memcg_oom_recover(memcg);
2001 }
49426420 2002cleanup:
626ebc41 2003 current->memcg_in_oom = NULL;
3812c8c8 2004 css_put(&memcg->css);
867578cb 2005 return true;
0b7f569e
KH
2006}
2007
3d8b38eb
RG
2008/**
2009 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
2010 * @victim: task to be killed by the OOM killer
2011 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
2012 *
2013 * Returns a pointer to a memory cgroup, which has to be cleaned up
2014 * by killing all belonging OOM-killable tasks.
2015 *
2016 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
2017 */
2018struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
2019 struct mem_cgroup *oom_domain)
2020{
2021 struct mem_cgroup *oom_group = NULL;
2022 struct mem_cgroup *memcg;
2023
2024 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2025 return NULL;
2026
2027 if (!oom_domain)
2028 oom_domain = root_mem_cgroup;
2029
2030 rcu_read_lock();
2031
2032 memcg = mem_cgroup_from_task(victim);
2033 if (memcg == root_mem_cgroup)
2034 goto out;
2035
2036 /*
2037 * Traverse the memory cgroup hierarchy from the victim task's
2038 * cgroup up to the OOMing cgroup (or root) to find the
2039 * highest-level memory cgroup with oom.group set.
2040 */
2041 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2042 if (memcg->oom_group)
2043 oom_group = memcg;
2044
2045 if (memcg == oom_domain)
2046 break;
2047 }
2048
2049 if (oom_group)
2050 css_get(&oom_group->css);
2051out:
2052 rcu_read_unlock();
2053
2054 return oom_group;
2055}
2056
2057void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2058{
2059 pr_info("Tasks in ");
2060 pr_cont_cgroup_path(memcg->css.cgroup);
2061 pr_cont(" are going to be killed due to memory.oom.group set\n");
2062}
2063
d7365e78 2064/**
81f8c3a4
JW
2065 * lock_page_memcg - lock a page->mem_cgroup binding
2066 * @page: the page
32047e2a 2067 *
81f8c3a4 2068 * This function protects unlocked LRU pages from being moved to
739f79fc
JW
2069 * another cgroup.
2070 *
2071 * It ensures lifetime of the returned memcg. Caller is responsible
2072 * for the lifetime of the page; __unlock_page_memcg() is available
2073 * when @page might get freed inside the locked section.
d69b042f 2074 */
739f79fc 2075struct mem_cgroup *lock_page_memcg(struct page *page)
89c06bd5
KH
2076{
2077 struct mem_cgroup *memcg;
6de22619 2078 unsigned long flags;
89c06bd5 2079
6de22619
JW
2080 /*
2081 * The RCU lock is held throughout the transaction. The fast
2082 * path can get away without acquiring the memcg->move_lock
2083 * because page moving starts with an RCU grace period.
739f79fc
JW
2084 *
2085 * The RCU lock also protects the memcg from being freed when
2086 * the page state that is going to change is the only thing
2087 * preventing the page itself from being freed. E.g. writeback
2088 * doesn't hold a page reference and relies on PG_writeback to
2089 * keep off truncation, migration and so forth.
2090 */
d7365e78
JW
2091 rcu_read_lock();
2092
2093 if (mem_cgroup_disabled())
739f79fc 2094 return NULL;
89c06bd5 2095again:
1306a85a 2096 memcg = page->mem_cgroup;
29833315 2097 if (unlikely(!memcg))
739f79fc 2098 return NULL;
d7365e78 2099
bdcbb659 2100 if (atomic_read(&memcg->moving_account) <= 0)
739f79fc 2101 return memcg;
89c06bd5 2102
6de22619 2103 spin_lock_irqsave(&memcg->move_lock, flags);
1306a85a 2104 if (memcg != page->mem_cgroup) {
6de22619 2105 spin_unlock_irqrestore(&memcg->move_lock, flags);
89c06bd5
KH
2106 goto again;
2107 }
6de22619
JW
2108
2109 /*
2110 * When charge migration first begins, we can have locked and
2111 * unlocked page stat updates happening concurrently. Track
81f8c3a4 2112 * the task who has the lock for unlock_page_memcg().
6de22619
JW
2113 */
2114 memcg->move_lock_task = current;
2115 memcg->move_lock_flags = flags;
d7365e78 2116
739f79fc 2117 return memcg;
89c06bd5 2118}
81f8c3a4 2119EXPORT_SYMBOL(lock_page_memcg);
89c06bd5 2120
d7365e78 2121/**
739f79fc
JW
2122 * __unlock_page_memcg - unlock and unpin a memcg
2123 * @memcg: the memcg
2124 *
2125 * Unlock and unpin a memcg returned by lock_page_memcg().
d7365e78 2126 */
739f79fc 2127void __unlock_page_memcg(struct mem_cgroup *memcg)
89c06bd5 2128{
6de22619
JW
2129 if (memcg && memcg->move_lock_task == current) {
2130 unsigned long flags = memcg->move_lock_flags;
2131
2132 memcg->move_lock_task = NULL;
2133 memcg->move_lock_flags = 0;
2134
2135 spin_unlock_irqrestore(&memcg->move_lock, flags);
2136 }
89c06bd5 2137
d7365e78 2138 rcu_read_unlock();
89c06bd5 2139}
739f79fc
JW
2140
2141/**
2142 * unlock_page_memcg - unlock a page->mem_cgroup binding
2143 * @page: the page
2144 */
2145void unlock_page_memcg(struct page *page)
2146{
2147 __unlock_page_memcg(page->mem_cgroup);
2148}
81f8c3a4 2149EXPORT_SYMBOL(unlock_page_memcg);
89c06bd5 2150
cdec2e42
KH
2151struct memcg_stock_pcp {
2152 struct mem_cgroup *cached; /* this never be root cgroup */
11c9ea4e 2153 unsigned int nr_pages;
cdec2e42 2154 struct work_struct work;
26fe6168 2155 unsigned long flags;
a0db00fc 2156#define FLUSHING_CACHED_CHARGE 0
cdec2e42
KH
2157};
2158static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
9f50fad6 2159static DEFINE_MUTEX(percpu_charge_mutex);
cdec2e42 2160
a0956d54
SS
2161/**
2162 * consume_stock: Try to consume stocked charge on this cpu.
2163 * @memcg: memcg to consume from.
2164 * @nr_pages: how many pages to charge.
2165 *
2166 * The charges will only happen if @memcg matches the current cpu's memcg
2167 * stock, and at least @nr_pages are available in that stock. Failure to
2168 * service an allocation will refill the stock.
2169 *
2170 * returns true if successful, false otherwise.
cdec2e42 2171 */
a0956d54 2172static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
cdec2e42
KH
2173{
2174 struct memcg_stock_pcp *stock;
db2ba40c 2175 unsigned long flags;
3e32cb2e 2176 bool ret = false;
cdec2e42 2177
a983b5eb 2178 if (nr_pages > MEMCG_CHARGE_BATCH)
3e32cb2e 2179 return ret;
a0956d54 2180
db2ba40c
JW
2181 local_irq_save(flags);
2182
2183 stock = this_cpu_ptr(&memcg_stock);
3e32cb2e 2184 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
a0956d54 2185 stock->nr_pages -= nr_pages;
3e32cb2e
JW
2186 ret = true;
2187 }
db2ba40c
JW
2188
2189 local_irq_restore(flags);
2190
cdec2e42
KH
2191 return ret;
2192}
2193
2194/*
3e32cb2e 2195 * Returns stocks cached in percpu and reset cached information.
cdec2e42
KH
2196 */
2197static void drain_stock(struct memcg_stock_pcp *stock)
2198{
2199 struct mem_cgroup *old = stock->cached;
2200
11c9ea4e 2201 if (stock->nr_pages) {
3e32cb2e 2202 page_counter_uncharge(&old->memory, stock->nr_pages);
7941d214 2203 if (do_memsw_account())
3e32cb2e 2204 page_counter_uncharge(&old->memsw, stock->nr_pages);
e8ea14cc 2205 css_put_many(&old->css, stock->nr_pages);
11c9ea4e 2206 stock->nr_pages = 0;
cdec2e42
KH
2207 }
2208 stock->cached = NULL;
cdec2e42
KH
2209}
2210
cdec2e42
KH
2211static void drain_local_stock(struct work_struct *dummy)
2212{
db2ba40c
JW
2213 struct memcg_stock_pcp *stock;
2214 unsigned long flags;
2215
72f0184c
MH
2216 /*
2217 * The only protection from memory hotplug vs. drain_stock races is
2218 * that we always operate on local CPU stock here with IRQ disabled
2219 */
db2ba40c
JW
2220 local_irq_save(flags);
2221
2222 stock = this_cpu_ptr(&memcg_stock);
cdec2e42 2223 drain_stock(stock);
26fe6168 2224 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
db2ba40c
JW
2225
2226 local_irq_restore(flags);
cdec2e42
KH
2227}
2228
2229/*
3e32cb2e 2230 * Cache charges(val) to local per_cpu area.
320cc51d 2231 * This will be consumed by consume_stock() function, later.
cdec2e42 2232 */
c0ff4b85 2233static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
cdec2e42 2234{
db2ba40c
JW
2235 struct memcg_stock_pcp *stock;
2236 unsigned long flags;
2237
2238 local_irq_save(flags);
cdec2e42 2239
db2ba40c 2240 stock = this_cpu_ptr(&memcg_stock);
c0ff4b85 2241 if (stock->cached != memcg) { /* reset if necessary */
cdec2e42 2242 drain_stock(stock);
c0ff4b85 2243 stock->cached = memcg;
cdec2e42 2244 }
11c9ea4e 2245 stock->nr_pages += nr_pages;
db2ba40c 2246
a983b5eb 2247 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
475d0487
RG
2248 drain_stock(stock);
2249
db2ba40c 2250 local_irq_restore(flags);
cdec2e42
KH
2251}
2252
2253/*
c0ff4b85 2254 * Drains all per-CPU charge caches for given root_memcg resp. subtree
6d3d6aa2 2255 * of the hierarchy under it.
cdec2e42 2256 */
6d3d6aa2 2257static void drain_all_stock(struct mem_cgroup *root_memcg)
cdec2e42 2258{
26fe6168 2259 int cpu, curcpu;
d38144b7 2260
6d3d6aa2
JW
2261 /* If someone's already draining, avoid adding running more workers. */
2262 if (!mutex_trylock(&percpu_charge_mutex))
2263 return;
72f0184c
MH
2264 /*
2265 * Notify other cpus that system-wide "drain" is running
2266 * We do not care about races with the cpu hotplug because cpu down
2267 * as well as workers from this path always operate on the local
2268 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2269 */
5af12d0e 2270 curcpu = get_cpu();
cdec2e42
KH
2271 for_each_online_cpu(cpu) {
2272 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
c0ff4b85 2273 struct mem_cgroup *memcg;
e1a366be 2274 bool flush = false;
26fe6168 2275
e1a366be 2276 rcu_read_lock();
c0ff4b85 2277 memcg = stock->cached;
e1a366be
RG
2278 if (memcg && stock->nr_pages &&
2279 mem_cgroup_is_descendant(memcg, root_memcg))
2280 flush = true;
2281 rcu_read_unlock();
2282
2283 if (flush &&
2284 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
d1a05b69
MH
2285 if (cpu == curcpu)
2286 drain_local_stock(&stock->work);
2287 else
2288 schedule_work_on(cpu, &stock->work);
2289 }
cdec2e42 2290 }
5af12d0e 2291 put_cpu();
9f50fad6 2292 mutex_unlock(&percpu_charge_mutex);
cdec2e42
KH
2293}
2294
308167fc 2295static int memcg_hotplug_cpu_dead(unsigned int cpu)
cdec2e42 2296{
cdec2e42 2297 struct memcg_stock_pcp *stock;
42a30035 2298 struct mem_cgroup *memcg, *mi;
cdec2e42 2299
cdec2e42
KH
2300 stock = &per_cpu(memcg_stock, cpu);
2301 drain_stock(stock);
a983b5eb
JW
2302
2303 for_each_mem_cgroup(memcg) {
2304 int i;
2305
2306 for (i = 0; i < MEMCG_NR_STAT; i++) {
2307 int nid;
2308 long x;
2309
871789d4 2310 x = this_cpu_xchg(memcg->vmstats_percpu->stat[i], 0);
815744d7 2311 if (x)
42a30035
JW
2312 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2313 atomic_long_add(x, &memcg->vmstats[i]);
a983b5eb
JW
2314
2315 if (i >= NR_VM_NODE_STAT_ITEMS)
2316 continue;
2317
2318 for_each_node(nid) {
2319 struct mem_cgroup_per_node *pn;
2320
2321 pn = mem_cgroup_nodeinfo(memcg, nid);
2322 x = this_cpu_xchg(pn->lruvec_stat_cpu->count[i], 0);
815744d7 2323 if (x)
42a30035
JW
2324 do {
2325 atomic_long_add(x, &pn->lruvec_stat[i]);
2326 } while ((pn = parent_nodeinfo(pn, nid)));
a983b5eb
JW
2327 }
2328 }
2329
e27be240 2330 for (i = 0; i < NR_VM_EVENT_ITEMS; i++) {
a983b5eb
JW
2331 long x;
2332
871789d4 2333 x = this_cpu_xchg(memcg->vmstats_percpu->events[i], 0);
815744d7 2334 if (x)
42a30035
JW
2335 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2336 atomic_long_add(x, &memcg->vmevents[i]);
a983b5eb
JW
2337 }
2338 }
2339
308167fc 2340 return 0;
cdec2e42
KH
2341}
2342
f7e1cb6e
JW
2343static void reclaim_high(struct mem_cgroup *memcg,
2344 unsigned int nr_pages,
2345 gfp_t gfp_mask)
2346{
2347 do {
2348 if (page_counter_read(&memcg->memory) <= memcg->high)
2349 continue;
e27be240 2350 memcg_memory_event(memcg, MEMCG_HIGH);
f7e1cb6e
JW
2351 try_to_free_mem_cgroup_pages(memcg, nr_pages, gfp_mask, true);
2352 } while ((memcg = parent_mem_cgroup(memcg)));
2353}
2354
2355static void high_work_func(struct work_struct *work)
2356{
2357 struct mem_cgroup *memcg;
2358
2359 memcg = container_of(work, struct mem_cgroup, high_work);
a983b5eb 2360 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
f7e1cb6e
JW
2361}
2362
0e4b01df
CD
2363/*
2364 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2365 * enough to still cause a significant slowdown in most cases, while still
2366 * allowing diagnostics and tracing to proceed without becoming stuck.
2367 */
2368#define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2369
2370/*
2371 * When calculating the delay, we use these either side of the exponentiation to
2372 * maintain precision and scale to a reasonable number of jiffies (see the table
2373 * below.
2374 *
2375 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2376 * overage ratio to a delay.
2377 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down down the
2378 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2379 * to produce a reasonable delay curve.
2380 *
2381 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2382 * reasonable delay curve compared to precision-adjusted overage, not
2383 * penalising heavily at first, but still making sure that growth beyond the
2384 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2385 * example, with a high of 100 megabytes:
2386 *
2387 * +-------+------------------------+
2388 * | usage | time to allocate in ms |
2389 * +-------+------------------------+
2390 * | 100M | 0 |
2391 * | 101M | 6 |
2392 * | 102M | 25 |
2393 * | 103M | 57 |
2394 * | 104M | 102 |
2395 * | 105M | 159 |
2396 * | 106M | 230 |
2397 * | 107M | 313 |
2398 * | 108M | 409 |
2399 * | 109M | 518 |
2400 * | 110M | 639 |
2401 * | 111M | 774 |
2402 * | 112M | 921 |
2403 * | 113M | 1081 |
2404 * | 114M | 1254 |
2405 * | 115M | 1439 |
2406 * | 116M | 1638 |
2407 * | 117M | 1849 |
2408 * | 118M | 2000 |
2409 * | 119M | 2000 |
2410 * | 120M | 2000 |
2411 * +-------+------------------------+
2412 */
2413 #define MEMCG_DELAY_PRECISION_SHIFT 20
2414 #define MEMCG_DELAY_SCALING_SHIFT 14
2415
b23afb93
TH
2416/*
2417 * Scheduled by try_charge() to be executed from the userland return path
2418 * and reclaims memory over the high limit.
2419 */
2420void mem_cgroup_handle_over_high(void)
2421{
0e4b01df
CD
2422 unsigned long usage, high, clamped_high;
2423 unsigned long pflags;
2424 unsigned long penalty_jiffies, overage;
b23afb93 2425 unsigned int nr_pages = current->memcg_nr_pages_over_high;
f7e1cb6e 2426 struct mem_cgroup *memcg;
b23afb93
TH
2427
2428 if (likely(!nr_pages))
2429 return;
2430
f7e1cb6e
JW
2431 memcg = get_mem_cgroup_from_mm(current->mm);
2432 reclaim_high(memcg, nr_pages, GFP_KERNEL);
b23afb93 2433 current->memcg_nr_pages_over_high = 0;
0e4b01df
CD
2434
2435 /*
2436 * memory.high is breached and reclaim is unable to keep up. Throttle
2437 * allocators proactively to slow down excessive growth.
2438 *
2439 * We use overage compared to memory.high to calculate the number of
2440 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2441 * fairly lenient on small overages, and increasingly harsh when the
2442 * memcg in question makes it clear that it has no intention of stopping
2443 * its crazy behaviour, so we exponentially increase the delay based on
2444 * overage amount.
2445 */
2446
2447 usage = page_counter_read(&memcg->memory);
2448 high = READ_ONCE(memcg->high);
2449
2450 if (usage <= high)
2451 goto out;
2452
2453 /*
2454 * Prevent division by 0 in overage calculation by acting as if it was a
2455 * threshold of 1 page
2456 */
2457 clamped_high = max(high, 1UL);
2458
2459 overage = div_u64((u64)(usage - high) << MEMCG_DELAY_PRECISION_SHIFT,
2460 clamped_high);
2461
2462 penalty_jiffies = ((u64)overage * overage * HZ)
2463 >> (MEMCG_DELAY_PRECISION_SHIFT + MEMCG_DELAY_SCALING_SHIFT);
2464
2465 /*
2466 * Factor in the task's own contribution to the overage, such that four
2467 * N-sized allocations are throttled approximately the same as one
2468 * 4N-sized allocation.
2469 *
2470 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2471 * larger the current charge patch is than that.
2472 */
2473 penalty_jiffies = penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2474
2475 /*
2476 * Clamp the max delay per usermode return so as to still keep the
2477 * application moving forwards and also permit diagnostics, albeit
2478 * extremely slowly.
2479 */
2480 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2481
2482 /*
2483 * Don't sleep if the amount of jiffies this memcg owes us is so low
2484 * that it's not even worth doing, in an attempt to be nice to those who
2485 * go only a small amount over their memory.high value and maybe haven't
2486 * been aggressively reclaimed enough yet.
2487 */
2488 if (penalty_jiffies <= HZ / 100)
2489 goto out;
2490
2491 /*
2492 * If we exit early, we're guaranteed to die (since
2493 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2494 * need to account for any ill-begotten jiffies to pay them off later.
2495 */
2496 psi_memstall_enter(&pflags);
2497 schedule_timeout_killable(penalty_jiffies);
2498 psi_memstall_leave(&pflags);
2499
2500out:
2501 css_put(&memcg->css);
b23afb93
TH
2502}
2503
00501b53
JW
2504static int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2505 unsigned int nr_pages)
8a9f3ccd 2506{
a983b5eb 2507 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
9b130619 2508 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
6539cc05 2509 struct mem_cgroup *mem_over_limit;
3e32cb2e 2510 struct page_counter *counter;
6539cc05 2511 unsigned long nr_reclaimed;
b70a2a21
JW
2512 bool may_swap = true;
2513 bool drained = false;
29ef680a 2514 enum oom_status oom_status;
a636b327 2515
ce00a967 2516 if (mem_cgroup_is_root(memcg))
10d53c74 2517 return 0;
6539cc05 2518retry:
b6b6cc72 2519 if (consume_stock(memcg, nr_pages))
10d53c74 2520 return 0;
8a9f3ccd 2521
7941d214 2522 if (!do_memsw_account() ||
6071ca52
JW
2523 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2524 if (page_counter_try_charge(&memcg->memory, batch, &counter))
6539cc05 2525 goto done_restock;
7941d214 2526 if (do_memsw_account())
3e32cb2e
JW
2527 page_counter_uncharge(&memcg->memsw, batch);
2528 mem_over_limit = mem_cgroup_from_counter(counter, memory);
3fbe7244 2529 } else {
3e32cb2e 2530 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
b70a2a21 2531 may_swap = false;
3fbe7244 2532 }
7a81b88c 2533
6539cc05
JW
2534 if (batch > nr_pages) {
2535 batch = nr_pages;
2536 goto retry;
2537 }
6d61ef40 2538
06b078fc
JW
2539 /*
2540 * Unlike in global OOM situations, memcg is not in a physical
2541 * memory shortage. Allow dying and OOM-killed tasks to
2542 * bypass the last charges so that they can exit quickly and
2543 * free their memory.
2544 */
7775face 2545 if (unlikely(should_force_charge()))
10d53c74 2546 goto force;
06b078fc 2547
89a28483
JW
2548 /*
2549 * Prevent unbounded recursion when reclaim operations need to
2550 * allocate memory. This might exceed the limits temporarily,
2551 * but we prefer facilitating memory reclaim and getting back
2552 * under the limit over triggering OOM kills in these cases.
2553 */
2554 if (unlikely(current->flags & PF_MEMALLOC))
2555 goto force;
2556
06b078fc
JW
2557 if (unlikely(task_in_memcg_oom(current)))
2558 goto nomem;
2559
d0164adc 2560 if (!gfpflags_allow_blocking(gfp_mask))
6539cc05 2561 goto nomem;
4b534334 2562
e27be240 2563 memcg_memory_event(mem_over_limit, MEMCG_MAX);
241994ed 2564
b70a2a21
JW
2565 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2566 gfp_mask, may_swap);
6539cc05 2567
61e02c74 2568 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
6539cc05 2569 goto retry;
28c34c29 2570
b70a2a21 2571 if (!drained) {
6d3d6aa2 2572 drain_all_stock(mem_over_limit);
b70a2a21
JW
2573 drained = true;
2574 goto retry;
2575 }
2576
28c34c29
JW
2577 if (gfp_mask & __GFP_NORETRY)
2578 goto nomem;
6539cc05
JW
2579 /*
2580 * Even though the limit is exceeded at this point, reclaim
2581 * may have been able to free some pages. Retry the charge
2582 * before killing the task.
2583 *
2584 * Only for regular pages, though: huge pages are rather
2585 * unlikely to succeed so close to the limit, and we fall back
2586 * to regular pages anyway in case of failure.
2587 */
61e02c74 2588 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
6539cc05
JW
2589 goto retry;
2590 /*
2591 * At task move, charge accounts can be doubly counted. So, it's
2592 * better to wait until the end of task_move if something is going on.
2593 */
2594 if (mem_cgroup_wait_acct_move(mem_over_limit))
2595 goto retry;
2596
9b130619
JW
2597 if (nr_retries--)
2598 goto retry;
2599
38d38493 2600 if (gfp_mask & __GFP_RETRY_MAYFAIL)
29ef680a
MH
2601 goto nomem;
2602
06b078fc 2603 if (gfp_mask & __GFP_NOFAIL)
10d53c74 2604 goto force;
06b078fc 2605
6539cc05 2606 if (fatal_signal_pending(current))
10d53c74 2607 goto force;
6539cc05 2608
29ef680a
MH
2609 /*
2610 * keep retrying as long as the memcg oom killer is able to make
2611 * a forward progress or bypass the charge if the oom killer
2612 * couldn't make any progress.
2613 */
2614 oom_status = mem_cgroup_oom(mem_over_limit, gfp_mask,
3608de07 2615 get_order(nr_pages * PAGE_SIZE));
29ef680a
MH
2616 switch (oom_status) {
2617 case OOM_SUCCESS:
2618 nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
29ef680a
MH
2619 goto retry;
2620 case OOM_FAILED:
2621 goto force;
2622 default:
2623 goto nomem;
2624 }
7a81b88c 2625nomem:
6d1fdc48 2626 if (!(gfp_mask & __GFP_NOFAIL))
3168ecbe 2627 return -ENOMEM;
10d53c74
TH
2628force:
2629 /*
2630 * The allocation either can't fail or will lead to more memory
2631 * being freed very soon. Allow memory usage go over the limit
2632 * temporarily by force charging it.
2633 */
2634 page_counter_charge(&memcg->memory, nr_pages);
7941d214 2635 if (do_memsw_account())
10d53c74
TH
2636 page_counter_charge(&memcg->memsw, nr_pages);
2637 css_get_many(&memcg->css, nr_pages);
2638
2639 return 0;
6539cc05
JW
2640
2641done_restock:
e8ea14cc 2642 css_get_many(&memcg->css, batch);
6539cc05
JW
2643 if (batch > nr_pages)
2644 refill_stock(memcg, batch - nr_pages);
b23afb93 2645
241994ed 2646 /*
b23afb93
TH
2647 * If the hierarchy is above the normal consumption range, schedule
2648 * reclaim on returning to userland. We can perform reclaim here
71baba4b 2649 * if __GFP_RECLAIM but let's always punt for simplicity and so that
b23afb93
TH
2650 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2651 * not recorded as it most likely matches current's and won't
2652 * change in the meantime. As high limit is checked again before
2653 * reclaim, the cost of mismatch is negligible.
241994ed
JW
2654 */
2655 do {
b23afb93 2656 if (page_counter_read(&memcg->memory) > memcg->high) {
f7e1cb6e
JW
2657 /* Don't bother a random interrupted task */
2658 if (in_interrupt()) {
2659 schedule_work(&memcg->high_work);
2660 break;
2661 }
9516a18a 2662 current->memcg_nr_pages_over_high += batch;
b23afb93
TH
2663 set_notify_resume(current);
2664 break;
2665 }
241994ed 2666 } while ((memcg = parent_mem_cgroup(memcg)));
10d53c74
TH
2667
2668 return 0;
7a81b88c 2669}
8a9f3ccd 2670
00501b53 2671static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
a3032a2c 2672{
ce00a967
JW
2673 if (mem_cgroup_is_root(memcg))
2674 return;
2675
3e32cb2e 2676 page_counter_uncharge(&memcg->memory, nr_pages);
7941d214 2677 if (do_memsw_account())
3e32cb2e 2678 page_counter_uncharge(&memcg->memsw, nr_pages);
ce00a967 2679
e8ea14cc 2680 css_put_many(&memcg->css, nr_pages);
d01dd17f
KH
2681}
2682
0a31bc97
JW
2683static void lock_page_lru(struct page *page, int *isolated)
2684{
f4b7e272 2685 pg_data_t *pgdat = page_pgdat(page);
0a31bc97 2686
f4b7e272 2687 spin_lock_irq(&pgdat->lru_lock);
0a31bc97
JW
2688 if (PageLRU(page)) {
2689 struct lruvec *lruvec;
2690
f4b7e272 2691 lruvec = mem_cgroup_page_lruvec(page, pgdat);
0a31bc97
JW
2692 ClearPageLRU(page);
2693 del_page_from_lru_list(page, lruvec, page_lru(page));
2694 *isolated = 1;
2695 } else
2696 *isolated = 0;
2697}
2698
2699static void unlock_page_lru(struct page *page, int isolated)
2700{
f4b7e272 2701 pg_data_t *pgdat = page_pgdat(page);
0a31bc97
JW
2702
2703 if (isolated) {
2704 struct lruvec *lruvec;
2705
f4b7e272 2706 lruvec = mem_cgroup_page_lruvec(page, pgdat);
0a31bc97
JW
2707 VM_BUG_ON_PAGE(PageLRU(page), page);
2708 SetPageLRU(page);
2709 add_page_to_lru_list(page, lruvec, page_lru(page));
2710 }
f4b7e272 2711 spin_unlock_irq(&pgdat->lru_lock);
0a31bc97
JW
2712}
2713
00501b53 2714static void commit_charge(struct page *page, struct mem_cgroup *memcg,
6abb5a86 2715 bool lrucare)
7a81b88c 2716{
0a31bc97 2717 int isolated;
9ce70c02 2718
1306a85a 2719 VM_BUG_ON_PAGE(page->mem_cgroup, page);
9ce70c02
HD
2720
2721 /*
2722 * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2723 * may already be on some other mem_cgroup's LRU. Take care of it.
2724 */
0a31bc97
JW
2725 if (lrucare)
2726 lock_page_lru(page, &isolated);
9ce70c02 2727
0a31bc97
JW
2728 /*
2729 * Nobody should be changing or seriously looking at
1306a85a 2730 * page->mem_cgroup at this point:
0a31bc97
JW
2731 *
2732 * - the page is uncharged
2733 *
2734 * - the page is off-LRU
2735 *
2736 * - an anonymous fault has exclusive page access, except for
2737 * a locked page table
2738 *
2739 * - a page cache insertion, a swapin fault, or a migration
2740 * have the page locked
2741 */
1306a85a 2742 page->mem_cgroup = memcg;
9ce70c02 2743
0a31bc97
JW
2744 if (lrucare)
2745 unlock_page_lru(page, isolated);
7a81b88c 2746}
66e1707b 2747
84c07d11 2748#ifdef CONFIG_MEMCG_KMEM
f3bb3043 2749static int memcg_alloc_cache_id(void)
55007d84 2750{
f3bb3043
VD
2751 int id, size;
2752 int err;
2753
dbcf73e2 2754 id = ida_simple_get(&memcg_cache_ida,
f3bb3043
VD
2755 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2756 if (id < 0)
2757 return id;
55007d84 2758
dbcf73e2 2759 if (id < memcg_nr_cache_ids)
f3bb3043
VD
2760 return id;
2761
2762 /*
2763 * There's no space for the new id in memcg_caches arrays,
2764 * so we have to grow them.
2765 */
05257a1a 2766 down_write(&memcg_cache_ids_sem);
f3bb3043
VD
2767
2768 size = 2 * (id + 1);
55007d84
GC
2769 if (size < MEMCG_CACHES_MIN_SIZE)
2770 size = MEMCG_CACHES_MIN_SIZE;
2771 else if (size > MEMCG_CACHES_MAX_SIZE)
2772 size = MEMCG_CACHES_MAX_SIZE;
2773
f3bb3043 2774 err = memcg_update_all_caches(size);
60d3fd32
VD
2775 if (!err)
2776 err = memcg_update_all_list_lrus(size);
05257a1a
VD
2777 if (!err)
2778 memcg_nr_cache_ids = size;
2779
2780 up_write(&memcg_cache_ids_sem);
2781
f3bb3043 2782 if (err) {
dbcf73e2 2783 ida_simple_remove(&memcg_cache_ida, id);
f3bb3043
VD
2784 return err;
2785 }
2786 return id;
2787}
2788
2789static void memcg_free_cache_id(int id)
2790{
dbcf73e2 2791 ida_simple_remove(&memcg_cache_ida, id);
55007d84
GC
2792}
2793
d5b3cf71 2794struct memcg_kmem_cache_create_work {
5722d094
VD
2795 struct mem_cgroup *memcg;
2796 struct kmem_cache *cachep;
2797 struct work_struct work;
2798};
2799
d5b3cf71 2800static void memcg_kmem_cache_create_func(struct work_struct *w)
d7f25f8a 2801{
d5b3cf71
VD
2802 struct memcg_kmem_cache_create_work *cw =
2803 container_of(w, struct memcg_kmem_cache_create_work, work);
5722d094
VD
2804 struct mem_cgroup *memcg = cw->memcg;
2805 struct kmem_cache *cachep = cw->cachep;
d7f25f8a 2806
d5b3cf71 2807 memcg_create_kmem_cache(memcg, cachep);
bd673145 2808
5722d094 2809 css_put(&memcg->css);
d7f25f8a
GC
2810 kfree(cw);
2811}
2812
2813/*
2814 * Enqueue the creation of a per-memcg kmem_cache.
d7f25f8a 2815 */
85cfb245 2816static void memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
d5b3cf71 2817 struct kmem_cache *cachep)
d7f25f8a 2818{
d5b3cf71 2819 struct memcg_kmem_cache_create_work *cw;
d7f25f8a 2820
f0a3a24b
RG
2821 if (!css_tryget_online(&memcg->css))
2822 return;
2823
c892fd82 2824 cw = kmalloc(sizeof(*cw), GFP_NOWAIT | __GFP_NOWARN);
8135be5a 2825 if (!cw)
d7f25f8a 2826 return;
8135be5a 2827
d7f25f8a
GC
2828 cw->memcg = memcg;
2829 cw->cachep = cachep;
d5b3cf71 2830 INIT_WORK(&cw->work, memcg_kmem_cache_create_func);
d7f25f8a 2831
17cc4dfe 2832 queue_work(memcg_kmem_cache_wq, &cw->work);
d7f25f8a
GC
2833}
2834
45264778
VD
2835static inline bool memcg_kmem_bypass(void)
2836{
2837 if (in_interrupt() || !current->mm || (current->flags & PF_KTHREAD))
2838 return true;
2839 return false;
2840}
2841
2842/**
2843 * memcg_kmem_get_cache: select the correct per-memcg cache for allocation
2844 * @cachep: the original global kmem cache
2845 *
d7f25f8a
GC
2846 * Return the kmem_cache we're supposed to use for a slab allocation.
2847 * We try to use the current memcg's version of the cache.
2848 *
45264778
VD
2849 * If the cache does not exist yet, if we are the first user of it, we
2850 * create it asynchronously in a workqueue and let the current allocation
2851 * go through with the original cache.
d7f25f8a 2852 *
45264778
VD
2853 * This function takes a reference to the cache it returns to assure it
2854 * won't get destroyed while we are working with it. Once the caller is
2855 * done with it, memcg_kmem_put_cache() must be called to release the
2856 * reference.
d7f25f8a 2857 */
45264778 2858struct kmem_cache *memcg_kmem_get_cache(struct kmem_cache *cachep)
d7f25f8a
GC
2859{
2860 struct mem_cgroup *memcg;
959c8963 2861 struct kmem_cache *memcg_cachep;
f0a3a24b 2862 struct memcg_cache_array *arr;
2a4db7eb 2863 int kmemcg_id;
d7f25f8a 2864
f7ce3190 2865 VM_BUG_ON(!is_root_cache(cachep));
d7f25f8a 2866
45264778 2867 if (memcg_kmem_bypass())
230e9fc2
VD
2868 return cachep;
2869
f0a3a24b
RG
2870 rcu_read_lock();
2871
2872 if (unlikely(current->active_memcg))
2873 memcg = current->active_memcg;
2874 else
2875 memcg = mem_cgroup_from_task(current);
2876
2877 if (!memcg || memcg == root_mem_cgroup)
2878 goto out_unlock;
2879
4db0c3c2 2880 kmemcg_id = READ_ONCE(memcg->kmemcg_id);
2a4db7eb 2881 if (kmemcg_id < 0)
f0a3a24b 2882 goto out_unlock;
d7f25f8a 2883
f0a3a24b
RG
2884 arr = rcu_dereference(cachep->memcg_params.memcg_caches);
2885
2886 /*
2887 * Make sure we will access the up-to-date value. The code updating
2888 * memcg_caches issues a write barrier to match the data dependency
2889 * barrier inside READ_ONCE() (see memcg_create_kmem_cache()).
2890 */
2891 memcg_cachep = READ_ONCE(arr->entries[kmemcg_id]);
ca0dde97
LZ
2892
2893 /*
2894 * If we are in a safe context (can wait, and not in interrupt
2895 * context), we could be be predictable and return right away.
2896 * This would guarantee that the allocation being performed
2897 * already belongs in the new cache.
2898 *
2899 * However, there are some clashes that can arrive from locking.
2900 * For instance, because we acquire the slab_mutex while doing
776ed0f0
VD
2901 * memcg_create_kmem_cache, this means no further allocation
2902 * could happen with the slab_mutex held. So it's better to
2903 * defer everything.
f0a3a24b
RG
2904 *
2905 * If the memcg is dying or memcg_cache is about to be released,
2906 * don't bother creating new kmem_caches. Because memcg_cachep
2907 * is ZEROed as the fist step of kmem offlining, we don't need
2908 * percpu_ref_tryget_live() here. css_tryget_online() check in
2909 * memcg_schedule_kmem_cache_create() will prevent us from
2910 * creation of a new kmem_cache.
ca0dde97 2911 */
f0a3a24b
RG
2912 if (unlikely(!memcg_cachep))
2913 memcg_schedule_kmem_cache_create(memcg, cachep);
2914 else if (percpu_ref_tryget(&memcg_cachep->memcg_params.refcnt))
2915 cachep = memcg_cachep;
2916out_unlock:
2917 rcu_read_unlock();
ca0dde97 2918 return cachep;
d7f25f8a 2919}
d7f25f8a 2920
45264778
VD
2921/**
2922 * memcg_kmem_put_cache: drop reference taken by memcg_kmem_get_cache
2923 * @cachep: the cache returned by memcg_kmem_get_cache
2924 */
2925void memcg_kmem_put_cache(struct kmem_cache *cachep)
8135be5a
VD
2926{
2927 if (!is_root_cache(cachep))
f0a3a24b 2928 percpu_ref_put(&cachep->memcg_params.refcnt);
8135be5a
VD
2929}
2930
45264778 2931/**
60cd4bcd 2932 * __memcg_kmem_charge_memcg: charge a kmem page
45264778
VD
2933 * @page: page to charge
2934 * @gfp: reclaim mode
2935 * @order: allocation order
2936 * @memcg: memory cgroup to charge
2937 *
2938 * Returns 0 on success, an error code on failure.
2939 */
60cd4bcd 2940int __memcg_kmem_charge_memcg(struct page *page, gfp_t gfp, int order,
45264778 2941 struct mem_cgroup *memcg)
7ae1e1d0 2942{
f3ccb2c4
VD
2943 unsigned int nr_pages = 1 << order;
2944 struct page_counter *counter;
7ae1e1d0
GC
2945 int ret;
2946
f3ccb2c4 2947 ret = try_charge(memcg, gfp, nr_pages);
52c29b04 2948 if (ret)
f3ccb2c4 2949 return ret;
52c29b04
JW
2950
2951 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) &&
2952 !page_counter_try_charge(&memcg->kmem, nr_pages, &counter)) {
2953 cancel_charge(memcg, nr_pages);
2954 return -ENOMEM;
7ae1e1d0 2955 }
f3ccb2c4 2956 return 0;
7ae1e1d0
GC
2957}
2958
45264778 2959/**
60cd4bcd 2960 * __memcg_kmem_charge: charge a kmem page to the current memory cgroup
45264778
VD
2961 * @page: page to charge
2962 * @gfp: reclaim mode
2963 * @order: allocation order
2964 *
2965 * Returns 0 on success, an error code on failure.
2966 */
60cd4bcd 2967int __memcg_kmem_charge(struct page *page, gfp_t gfp, int order)
7ae1e1d0 2968{
f3ccb2c4 2969 struct mem_cgroup *memcg;
fcff7d7e 2970 int ret = 0;
7ae1e1d0 2971
60cd4bcd 2972 if (memcg_kmem_bypass())
45264778
VD
2973 return 0;
2974
d46eb14b 2975 memcg = get_mem_cgroup_from_current();
c4159a75 2976 if (!mem_cgroup_is_root(memcg)) {
60cd4bcd 2977 ret = __memcg_kmem_charge_memcg(page, gfp, order, memcg);
4d96ba35
RG
2978 if (!ret) {
2979 page->mem_cgroup = memcg;
c4159a75 2980 __SetPageKmemcg(page);
4d96ba35 2981 }
c4159a75 2982 }
7ae1e1d0 2983 css_put(&memcg->css);
d05e83a6 2984 return ret;
7ae1e1d0 2985}
49a18eae
RG
2986
2987/**
2988 * __memcg_kmem_uncharge_memcg: uncharge a kmem page
2989 * @memcg: memcg to uncharge
2990 * @nr_pages: number of pages to uncharge
2991 */
2992void __memcg_kmem_uncharge_memcg(struct mem_cgroup *memcg,
2993 unsigned int nr_pages)
2994{
2995 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2996 page_counter_uncharge(&memcg->kmem, nr_pages);
2997
2998 page_counter_uncharge(&memcg->memory, nr_pages);
2999 if (do_memsw_account())
3000 page_counter_uncharge(&memcg->memsw, nr_pages);
3001}
45264778 3002/**
60cd4bcd 3003 * __memcg_kmem_uncharge: uncharge a kmem page
45264778
VD
3004 * @page: page to uncharge
3005 * @order: allocation order
3006 */
60cd4bcd 3007void __memcg_kmem_uncharge(struct page *page, int order)
7ae1e1d0 3008{
1306a85a 3009 struct mem_cgroup *memcg = page->mem_cgroup;
f3ccb2c4 3010 unsigned int nr_pages = 1 << order;
7ae1e1d0 3011
7ae1e1d0
GC
3012 if (!memcg)
3013 return;
3014
309381fe 3015 VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
49a18eae 3016 __memcg_kmem_uncharge_memcg(memcg, nr_pages);
1306a85a 3017 page->mem_cgroup = NULL;
c4159a75
VD
3018
3019 /* slab pages do not have PageKmemcg flag set */
3020 if (PageKmemcg(page))
3021 __ClearPageKmemcg(page);
3022
f3ccb2c4 3023 css_put_many(&memcg->css, nr_pages);
60d3fd32 3024}
84c07d11 3025#endif /* CONFIG_MEMCG_KMEM */
7ae1e1d0 3026
ca3e0214
KH
3027#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3028
ca3e0214
KH
3029/*
3030 * Because tail pages are not marked as "used", set it. We're under
f4b7e272 3031 * pgdat->lru_lock and migration entries setup in all page mappings.
ca3e0214 3032 */
e94c8a9c 3033void mem_cgroup_split_huge_fixup(struct page *head)
ca3e0214 3034{
e94c8a9c 3035 int i;
ca3e0214 3036
3d37c4a9
KH
3037 if (mem_cgroup_disabled())
3038 return;
b070e65c 3039
29833315 3040 for (i = 1; i < HPAGE_PMD_NR; i++)
1306a85a 3041 head[i].mem_cgroup = head->mem_cgroup;
b9982f8d 3042
c9019e9b 3043 __mod_memcg_state(head->mem_cgroup, MEMCG_RSS_HUGE, -HPAGE_PMD_NR);
ca3e0214 3044}
12d27107 3045#endif /* CONFIG_TRANSPARENT_HUGEPAGE */
ca3e0214 3046
c255a458 3047#ifdef CONFIG_MEMCG_SWAP
02491447
DN
3048/**
3049 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3050 * @entry: swap entry to be moved
3051 * @from: mem_cgroup which the entry is moved from
3052 * @to: mem_cgroup which the entry is moved to
3053 *
3054 * It succeeds only when the swap_cgroup's record for this entry is the same
3055 * as the mem_cgroup's id of @from.
3056 *
3057 * Returns 0 on success, -EINVAL on failure.
3058 *
3e32cb2e 3059 * The caller must have charged to @to, IOW, called page_counter_charge() about
02491447
DN
3060 * both res and memsw, and called css_get().
3061 */
3062static int mem_cgroup_move_swap_account(swp_entry_t entry,
e91cbb42 3063 struct mem_cgroup *from, struct mem_cgroup *to)
02491447
DN
3064{
3065 unsigned short old_id, new_id;
3066
34c00c31
LZ
3067 old_id = mem_cgroup_id(from);
3068 new_id = mem_cgroup_id(to);
02491447
DN
3069
3070 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
c9019e9b
JW
3071 mod_memcg_state(from, MEMCG_SWAP, -1);
3072 mod_memcg_state(to, MEMCG_SWAP, 1);
02491447
DN
3073 return 0;
3074 }
3075 return -EINVAL;
3076}
3077#else
3078static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
e91cbb42 3079 struct mem_cgroup *from, struct mem_cgroup *to)
02491447
DN
3080{
3081 return -EINVAL;
3082}
8c7c6e34 3083#endif
d13d1443 3084
bbec2e15 3085static DEFINE_MUTEX(memcg_max_mutex);
f212ad7c 3086
bbec2e15
RG
3087static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3088 unsigned long max, bool memsw)
628f4235 3089{
3e32cb2e 3090 bool enlarge = false;
bb4a7ea2 3091 bool drained = false;
3e32cb2e 3092 int ret;
c054a78c
YZ
3093 bool limits_invariant;
3094 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
81d39c20 3095
3e32cb2e 3096 do {
628f4235
KH
3097 if (signal_pending(current)) {
3098 ret = -EINTR;
3099 break;
3100 }
3e32cb2e 3101
bbec2e15 3102 mutex_lock(&memcg_max_mutex);
c054a78c
YZ
3103 /*
3104 * Make sure that the new limit (memsw or memory limit) doesn't
bbec2e15 3105 * break our basic invariant rule memory.max <= memsw.max.
c054a78c 3106 */
bbec2e15
RG
3107 limits_invariant = memsw ? max >= memcg->memory.max :
3108 max <= memcg->memsw.max;
c054a78c 3109 if (!limits_invariant) {
bbec2e15 3110 mutex_unlock(&memcg_max_mutex);
8c7c6e34 3111 ret = -EINVAL;
8c7c6e34
KH
3112 break;
3113 }
bbec2e15 3114 if (max > counter->max)
3e32cb2e 3115 enlarge = true;
bbec2e15
RG
3116 ret = page_counter_set_max(counter, max);
3117 mutex_unlock(&memcg_max_mutex);
8c7c6e34
KH
3118
3119 if (!ret)
3120 break;
3121
bb4a7ea2
SB
3122 if (!drained) {
3123 drain_all_stock(memcg);
3124 drained = true;
3125 continue;
3126 }
3127
1ab5c056
AR
3128 if (!try_to_free_mem_cgroup_pages(memcg, 1,
3129 GFP_KERNEL, !memsw)) {
3130 ret = -EBUSY;
3131 break;
3132 }
3133 } while (true);
3e32cb2e 3134
3c11ecf4
KH
3135 if (!ret && enlarge)
3136 memcg_oom_recover(memcg);
3e32cb2e 3137
628f4235
KH
3138 return ret;
3139}
3140
ef8f2327 3141unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
0608f43d
AM
3142 gfp_t gfp_mask,
3143 unsigned long *total_scanned)
3144{
3145 unsigned long nr_reclaimed = 0;
ef8f2327 3146 struct mem_cgroup_per_node *mz, *next_mz = NULL;
0608f43d
AM
3147 unsigned long reclaimed;
3148 int loop = 0;
ef8f2327 3149 struct mem_cgroup_tree_per_node *mctz;
3e32cb2e 3150 unsigned long excess;
0608f43d
AM
3151 unsigned long nr_scanned;
3152
3153 if (order > 0)
3154 return 0;
3155
ef8f2327 3156 mctz = soft_limit_tree_node(pgdat->node_id);
d6507ff5
MH
3157
3158 /*
3159 * Do not even bother to check the largest node if the root
3160 * is empty. Do it lockless to prevent lock bouncing. Races
3161 * are acceptable as soft limit is best effort anyway.
3162 */
bfc7228b 3163 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
d6507ff5
MH
3164 return 0;
3165
0608f43d
AM
3166 /*
3167 * This loop can run a while, specially if mem_cgroup's continuously
3168 * keep exceeding their soft limit and putting the system under
3169 * pressure
3170 */
3171 do {
3172 if (next_mz)
3173 mz = next_mz;
3174 else
3175 mz = mem_cgroup_largest_soft_limit_node(mctz);
3176 if (!mz)
3177 break;
3178
3179 nr_scanned = 0;
ef8f2327 3180 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
0608f43d
AM
3181 gfp_mask, &nr_scanned);
3182 nr_reclaimed += reclaimed;
3183 *total_scanned += nr_scanned;
0a31bc97 3184 spin_lock_irq(&mctz->lock);
bc2f2e7f 3185 __mem_cgroup_remove_exceeded(mz, mctz);
0608f43d
AM
3186
3187 /*
3188 * If we failed to reclaim anything from this memory cgroup
3189 * it is time to move on to the next cgroup
3190 */
3191 next_mz = NULL;
bc2f2e7f
VD
3192 if (!reclaimed)
3193 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3194
3e32cb2e 3195 excess = soft_limit_excess(mz->memcg);
0608f43d
AM
3196 /*
3197 * One school of thought says that we should not add
3198 * back the node to the tree if reclaim returns 0.
3199 * But our reclaim could return 0, simply because due
3200 * to priority we are exposing a smaller subset of
3201 * memory to reclaim from. Consider this as a longer
3202 * term TODO.
3203 */
3204 /* If excess == 0, no tree ops */
cf2c8127 3205 __mem_cgroup_insert_exceeded(mz, mctz, excess);
0a31bc97 3206 spin_unlock_irq(&mctz->lock);
0608f43d
AM
3207 css_put(&mz->memcg->css);
3208 loop++;
3209 /*
3210 * Could not reclaim anything and there are no more
3211 * mem cgroups to try or we seem to be looping without
3212 * reclaiming anything.
3213 */
3214 if (!nr_reclaimed &&
3215 (next_mz == NULL ||
3216 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3217 break;
3218 } while (!nr_reclaimed);
3219 if (next_mz)
3220 css_put(&next_mz->memcg->css);
3221 return nr_reclaimed;
3222}
3223
ea280e7b
TH
3224/*
3225 * Test whether @memcg has children, dead or alive. Note that this
3226 * function doesn't care whether @memcg has use_hierarchy enabled and
3227 * returns %true if there are child csses according to the cgroup
3228 * hierarchy. Testing use_hierarchy is the caller's responsiblity.
3229 */
b5f99b53
GC
3230static inline bool memcg_has_children(struct mem_cgroup *memcg)
3231{
ea280e7b
TH
3232 bool ret;
3233
ea280e7b
TH
3234 rcu_read_lock();
3235 ret = css_next_child(NULL, &memcg->css);
3236 rcu_read_unlock();
3237 return ret;
b5f99b53
GC
3238}
3239
c26251f9 3240/*
51038171 3241 * Reclaims as many pages from the given memcg as possible.
c26251f9
MH
3242 *
3243 * Caller is responsible for holding css reference for memcg.
3244 */
3245static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3246{
3247 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
c26251f9 3248
c1e862c1
KH
3249 /* we call try-to-free pages for make this cgroup empty */
3250 lru_add_drain_all();
d12c60f6
JS
3251
3252 drain_all_stock(memcg);
3253
f817ed48 3254 /* try to free all pages in this cgroup */
3e32cb2e 3255 while (nr_retries && page_counter_read(&memcg->memory)) {
f817ed48 3256 int progress;
c1e862c1 3257
c26251f9
MH
3258 if (signal_pending(current))
3259 return -EINTR;
3260
b70a2a21
JW
3261 progress = try_to_free_mem_cgroup_pages(memcg, 1,
3262 GFP_KERNEL, true);
c1e862c1 3263 if (!progress) {
f817ed48 3264 nr_retries--;
c1e862c1 3265 /* maybe some writeback is necessary */
8aa7e847 3266 congestion_wait(BLK_RW_ASYNC, HZ/10);
c1e862c1 3267 }
f817ed48
KH
3268
3269 }
ab5196c2
MH
3270
3271 return 0;
cc847582
KH
3272}
3273
6770c64e
TH
3274static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3275 char *buf, size_t nbytes,
3276 loff_t off)
c1e862c1 3277{
6770c64e 3278 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
c26251f9 3279
d8423011
MH
3280 if (mem_cgroup_is_root(memcg))
3281 return -EINVAL;
6770c64e 3282 return mem_cgroup_force_empty(memcg) ?: nbytes;
c1e862c1
KH
3283}
3284
182446d0
TH
3285static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3286 struct cftype *cft)
18f59ea7 3287{
182446d0 3288 return mem_cgroup_from_css(css)->use_hierarchy;
18f59ea7
BS
3289}
3290
182446d0
TH
3291static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3292 struct cftype *cft, u64 val)
18f59ea7
BS
3293{
3294 int retval = 0;
182446d0 3295 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5c9d535b 3296 struct mem_cgroup *parent_memcg = mem_cgroup_from_css(memcg->css.parent);
18f59ea7 3297
567fb435 3298 if (memcg->use_hierarchy == val)
0b8f73e1 3299 return 0;
567fb435 3300
18f59ea7 3301 /*
af901ca1 3302 * If parent's use_hierarchy is set, we can't make any modifications
18f59ea7
BS
3303 * in the child subtrees. If it is unset, then the change can
3304 * occur, provided the current cgroup has no children.
3305 *
3306 * For the root cgroup, parent_mem is NULL, we allow value to be
3307 * set if there are no children.
3308 */
c0ff4b85 3309 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
18f59ea7 3310 (val == 1 || val == 0)) {
ea280e7b 3311 if (!memcg_has_children(memcg))
c0ff4b85 3312 memcg->use_hierarchy = val;
18f59ea7
BS
3313 else
3314 retval = -EBUSY;
3315 } else
3316 retval = -EINVAL;
567fb435 3317
18f59ea7
BS
3318 return retval;
3319}
3320
6f646156 3321static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
ce00a967 3322{
42a30035 3323 unsigned long val;
ce00a967 3324
3e32cb2e 3325 if (mem_cgroup_is_root(memcg)) {
42a30035
JW
3326 val = memcg_page_state(memcg, MEMCG_CACHE) +
3327 memcg_page_state(memcg, MEMCG_RSS);
3328 if (swap)
3329 val += memcg_page_state(memcg, MEMCG_SWAP);
3e32cb2e 3330 } else {
ce00a967 3331 if (!swap)
3e32cb2e 3332 val = page_counter_read(&memcg->memory);
ce00a967 3333 else
3e32cb2e 3334 val = page_counter_read(&memcg->memsw);
ce00a967 3335 }
c12176d3 3336 return val;
ce00a967
JW
3337}
3338
3e32cb2e
JW
3339enum {
3340 RES_USAGE,
3341 RES_LIMIT,
3342 RES_MAX_USAGE,
3343 RES_FAILCNT,
3344 RES_SOFT_LIMIT,
3345};
ce00a967 3346
791badbd 3347static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
05b84301 3348 struct cftype *cft)
8cdea7c0 3349{
182446d0 3350 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3e32cb2e 3351 struct page_counter *counter;
af36f906 3352
3e32cb2e 3353 switch (MEMFILE_TYPE(cft->private)) {
8c7c6e34 3354 case _MEM:
3e32cb2e
JW
3355 counter = &memcg->memory;
3356 break;
8c7c6e34 3357 case _MEMSWAP:
3e32cb2e
JW
3358 counter = &memcg->memsw;
3359 break;
510fc4e1 3360 case _KMEM:
3e32cb2e 3361 counter = &memcg->kmem;
510fc4e1 3362 break;
d55f90bf 3363 case _TCP:
0db15298 3364 counter = &memcg->tcpmem;
d55f90bf 3365 break;
8c7c6e34
KH
3366 default:
3367 BUG();
8c7c6e34 3368 }
3e32cb2e
JW
3369
3370 switch (MEMFILE_ATTR(cft->private)) {
3371 case RES_USAGE:
3372 if (counter == &memcg->memory)
c12176d3 3373 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3e32cb2e 3374 if (counter == &memcg->memsw)
c12176d3 3375 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3e32cb2e
JW
3376 return (u64)page_counter_read(counter) * PAGE_SIZE;
3377 case RES_LIMIT:
bbec2e15 3378 return (u64)counter->max * PAGE_SIZE;
3e32cb2e
JW
3379 case RES_MAX_USAGE:
3380 return (u64)counter->watermark * PAGE_SIZE;
3381 case RES_FAILCNT:
3382 return counter->failcnt;
3383 case RES_SOFT_LIMIT:
3384 return (u64)memcg->soft_limit * PAGE_SIZE;
3385 default:
3386 BUG();
3387 }
8cdea7c0 3388}
510fc4e1 3389
bee07b33 3390static void memcg_flush_percpu_vmstats(struct mem_cgroup *memcg, bool slab_only)
c350a99e
RG
3391{
3392 unsigned long stat[MEMCG_NR_STAT];
3393 struct mem_cgroup *mi;
3394 int node, cpu, i;
bee07b33 3395 int min_idx, max_idx;
c350a99e 3396
bee07b33
RG
3397 if (slab_only) {
3398 min_idx = NR_SLAB_RECLAIMABLE;
3399 max_idx = NR_SLAB_UNRECLAIMABLE;
3400 } else {
3401 min_idx = 0;
3402 max_idx = MEMCG_NR_STAT;
3403 }
3404
3405 for (i = min_idx; i < max_idx; i++)
c350a99e
RG
3406 stat[i] = 0;
3407
3408 for_each_online_cpu(cpu)
bee07b33 3409 for (i = min_idx; i < max_idx; i++)
6c1c2808 3410 stat[i] += per_cpu(memcg->vmstats_percpu->stat[i], cpu);
c350a99e
RG
3411
3412 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
bee07b33 3413 for (i = min_idx; i < max_idx; i++)
c350a99e
RG
3414 atomic_long_add(stat[i], &mi->vmstats[i]);
3415
bee07b33
RG
3416 if (!slab_only)
3417 max_idx = NR_VM_NODE_STAT_ITEMS;
3418
c350a99e
RG
3419 for_each_node(node) {
3420 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
3421 struct mem_cgroup_per_node *pi;
3422
bee07b33 3423 for (i = min_idx; i < max_idx; i++)
c350a99e
RG
3424 stat[i] = 0;
3425
3426 for_each_online_cpu(cpu)
bee07b33 3427 for (i = min_idx; i < max_idx; i++)
6c1c2808
SB
3428 stat[i] += per_cpu(
3429 pn->lruvec_stat_cpu->count[i], cpu);
c350a99e
RG
3430
3431 for (pi = pn; pi; pi = parent_nodeinfo(pi, node))
bee07b33 3432 for (i = min_idx; i < max_idx; i++)
c350a99e
RG
3433 atomic_long_add(stat[i], &pi->lruvec_stat[i]);
3434 }
3435}
3436
bb65f89b
RG
3437static void memcg_flush_percpu_vmevents(struct mem_cgroup *memcg)
3438{
3439 unsigned long events[NR_VM_EVENT_ITEMS];
3440 struct mem_cgroup *mi;
3441 int cpu, i;
3442
3443 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3444 events[i] = 0;
3445
3446 for_each_online_cpu(cpu)
3447 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
6c1c2808
SB
3448 events[i] += per_cpu(memcg->vmstats_percpu->events[i],
3449 cpu);
bb65f89b
RG
3450
3451 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
3452 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3453 atomic_long_add(events[i], &mi->vmevents[i]);
3454}
3455
84c07d11 3456#ifdef CONFIG_MEMCG_KMEM
567e9ab2 3457static int memcg_online_kmem(struct mem_cgroup *memcg)
d6441637 3458{
d6441637
VD
3459 int memcg_id;
3460
b313aeee
VD
3461 if (cgroup_memory_nokmem)
3462 return 0;
3463
2a4db7eb 3464 BUG_ON(memcg->kmemcg_id >= 0);
567e9ab2 3465 BUG_ON(memcg->kmem_state);
d6441637 3466
f3bb3043 3467 memcg_id = memcg_alloc_cache_id();
0b8f73e1
JW
3468 if (memcg_id < 0)
3469 return memcg_id;
d6441637 3470
ef12947c 3471 static_branch_inc(&memcg_kmem_enabled_key);
d6441637 3472 /*
567e9ab2 3473 * A memory cgroup is considered kmem-online as soon as it gets
900a38f0 3474 * kmemcg_id. Setting the id after enabling static branching will
d6441637
VD
3475 * guarantee no one starts accounting before all call sites are
3476 * patched.
3477 */
900a38f0 3478 memcg->kmemcg_id = memcg_id;
567e9ab2 3479 memcg->kmem_state = KMEM_ONLINE;
bc2791f8 3480 INIT_LIST_HEAD(&memcg->kmem_caches);
0b8f73e1
JW
3481
3482 return 0;
d6441637
VD
3483}
3484
8e0a8912
JW
3485static void memcg_offline_kmem(struct mem_cgroup *memcg)
3486{
3487 struct cgroup_subsys_state *css;
3488 struct mem_cgroup *parent, *child;
3489 int kmemcg_id;
3490
3491 if (memcg->kmem_state != KMEM_ONLINE)
3492 return;
3493 /*
3494 * Clear the online state before clearing memcg_caches array
3495 * entries. The slab_mutex in memcg_deactivate_kmem_caches()
3496 * guarantees that no cache will be created for this cgroup
3497 * after we are done (see memcg_create_kmem_cache()).
3498 */
3499 memcg->kmem_state = KMEM_ALLOCATED;
3500
8e0a8912
JW
3501 parent = parent_mem_cgroup(memcg);
3502 if (!parent)
3503 parent = root_mem_cgroup;
3504
bee07b33
RG
3505 /*
3506 * Deactivate and reparent kmem_caches. Then flush percpu
3507 * slab statistics to have precise values at the parent and
3508 * all ancestor levels. It's required to keep slab stats
3509 * accurate after the reparenting of kmem_caches.
3510 */
fb2f2b0a 3511 memcg_deactivate_kmem_caches(memcg, parent);
bee07b33 3512 memcg_flush_percpu_vmstats(memcg, true);
fb2f2b0a
RG
3513
3514 kmemcg_id = memcg->kmemcg_id;
3515 BUG_ON(kmemcg_id < 0);
3516
8e0a8912
JW
3517 /*
3518 * Change kmemcg_id of this cgroup and all its descendants to the
3519 * parent's id, and then move all entries from this cgroup's list_lrus
3520 * to ones of the parent. After we have finished, all list_lrus
3521 * corresponding to this cgroup are guaranteed to remain empty. The
3522 * ordering is imposed by list_lru_node->lock taken by
3523 * memcg_drain_all_list_lrus().
3524 */
3a06bb78 3525 rcu_read_lock(); /* can be called from css_free w/o cgroup_mutex */
8e0a8912
JW
3526 css_for_each_descendant_pre(css, &memcg->css) {
3527 child = mem_cgroup_from_css(css);
3528 BUG_ON(child->kmemcg_id != kmemcg_id);
3529 child->kmemcg_id = parent->kmemcg_id;
3530 if (!memcg->use_hierarchy)
3531 break;
3532 }
3a06bb78
TH
3533 rcu_read_unlock();
3534
9bec5c35 3535 memcg_drain_all_list_lrus(kmemcg_id, parent);
8e0a8912
JW
3536
3537 memcg_free_cache_id(kmemcg_id);
3538}
3539
3540static void memcg_free_kmem(struct mem_cgroup *memcg)
3541{
0b8f73e1
JW
3542 /* css_alloc() failed, offlining didn't happen */
3543 if (unlikely(memcg->kmem_state == KMEM_ONLINE))
3544 memcg_offline_kmem(memcg);
3545
8e0a8912 3546 if (memcg->kmem_state == KMEM_ALLOCATED) {
f0a3a24b 3547 WARN_ON(!list_empty(&memcg->kmem_caches));
8e0a8912 3548 static_branch_dec(&memcg_kmem_enabled_key);
8e0a8912 3549 }
8e0a8912 3550}
d6441637 3551#else
0b8f73e1 3552static int memcg_online_kmem(struct mem_cgroup *memcg)
127424c8
JW
3553{
3554 return 0;
3555}
3556static void memcg_offline_kmem(struct mem_cgroup *memcg)
3557{
3558}
3559static void memcg_free_kmem(struct mem_cgroup *memcg)
3560{
3561}
84c07d11 3562#endif /* CONFIG_MEMCG_KMEM */
127424c8 3563
bbec2e15
RG
3564static int memcg_update_kmem_max(struct mem_cgroup *memcg,
3565 unsigned long max)
d6441637 3566{
b313aeee 3567 int ret;
127424c8 3568
bbec2e15
RG
3569 mutex_lock(&memcg_max_mutex);
3570 ret = page_counter_set_max(&memcg->kmem, max);
3571 mutex_unlock(&memcg_max_mutex);
127424c8 3572 return ret;
d6441637 3573}
510fc4e1 3574
bbec2e15 3575static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
d55f90bf
VD
3576{
3577 int ret;
3578
bbec2e15 3579 mutex_lock(&memcg_max_mutex);
d55f90bf 3580
bbec2e15 3581 ret = page_counter_set_max(&memcg->tcpmem, max);
d55f90bf
VD
3582 if (ret)
3583 goto out;
3584
0db15298 3585 if (!memcg->tcpmem_active) {
d55f90bf
VD
3586 /*
3587 * The active flag needs to be written after the static_key
3588 * update. This is what guarantees that the socket activation
2d758073
JW
3589 * function is the last one to run. See mem_cgroup_sk_alloc()
3590 * for details, and note that we don't mark any socket as
3591 * belonging to this memcg until that flag is up.
d55f90bf
VD
3592 *
3593 * We need to do this, because static_keys will span multiple
3594 * sites, but we can't control their order. If we mark a socket
3595 * as accounted, but the accounting functions are not patched in
3596 * yet, we'll lose accounting.
3597 *
2d758073 3598 * We never race with the readers in mem_cgroup_sk_alloc(),
d55f90bf
VD
3599 * because when this value change, the code to process it is not
3600 * patched in yet.
3601 */
3602 static_branch_inc(&memcg_sockets_enabled_key);
0db15298 3603 memcg->tcpmem_active = true;
d55f90bf
VD
3604 }
3605out:
bbec2e15 3606 mutex_unlock(&memcg_max_mutex);
d55f90bf
VD
3607 return ret;
3608}
d55f90bf 3609
628f4235
KH
3610/*
3611 * The user of this function is...
3612 * RES_LIMIT.
3613 */
451af504
TH
3614static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3615 char *buf, size_t nbytes, loff_t off)
8cdea7c0 3616{
451af504 3617 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3e32cb2e 3618 unsigned long nr_pages;
628f4235
KH
3619 int ret;
3620
451af504 3621 buf = strstrip(buf);
650c5e56 3622 ret = page_counter_memparse(buf, "-1", &nr_pages);
3e32cb2e
JW
3623 if (ret)
3624 return ret;
af36f906 3625
3e32cb2e 3626 switch (MEMFILE_ATTR(of_cft(of)->private)) {
628f4235 3627 case RES_LIMIT:
4b3bde4c
BS
3628 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3629 ret = -EINVAL;
3630 break;
3631 }
3e32cb2e
JW
3632 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3633 case _MEM:
bbec2e15 3634 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
8c7c6e34 3635 break;
3e32cb2e 3636 case _MEMSWAP:
bbec2e15 3637 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
296c81d8 3638 break;
3e32cb2e 3639 case _KMEM:
bbec2e15 3640 ret = memcg_update_kmem_max(memcg, nr_pages);
3e32cb2e 3641 break;
d55f90bf 3642 case _TCP:
bbec2e15 3643 ret = memcg_update_tcp_max(memcg, nr_pages);
d55f90bf 3644 break;
3e32cb2e 3645 }
296c81d8 3646 break;
3e32cb2e
JW
3647 case RES_SOFT_LIMIT:
3648 memcg->soft_limit = nr_pages;
3649 ret = 0;
628f4235
KH
3650 break;
3651 }
451af504 3652 return ret ?: nbytes;
8cdea7c0
BS
3653}
3654
6770c64e
TH
3655static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3656 size_t nbytes, loff_t off)
c84872e1 3657{
6770c64e 3658 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3e32cb2e 3659 struct page_counter *counter;
c84872e1 3660
3e32cb2e
JW
3661 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3662 case _MEM:
3663 counter = &memcg->memory;
3664 break;
3665 case _MEMSWAP:
3666 counter = &memcg->memsw;
3667 break;
3668 case _KMEM:
3669 counter = &memcg->kmem;
3670 break;
d55f90bf 3671 case _TCP:
0db15298 3672 counter = &memcg->tcpmem;
d55f90bf 3673 break;
3e32cb2e
JW
3674 default:
3675 BUG();
3676 }
af36f906 3677
3e32cb2e 3678 switch (MEMFILE_ATTR(of_cft(of)->private)) {
29f2a4da 3679 case RES_MAX_USAGE:
3e32cb2e 3680 page_counter_reset_watermark(counter);
29f2a4da
PE
3681 break;
3682 case RES_FAILCNT:
3e32cb2e 3683 counter->failcnt = 0;
29f2a4da 3684 break;
3e32cb2e
JW
3685 default:
3686 BUG();
29f2a4da 3687 }
f64c3f54 3688
6770c64e 3689 return nbytes;
c84872e1
PE
3690}
3691
182446d0 3692static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
7dc74be0
DN
3693 struct cftype *cft)
3694{
182446d0 3695 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
7dc74be0
DN
3696}
3697
02491447 3698#ifdef CONFIG_MMU
182446d0 3699static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
7dc74be0
DN
3700 struct cftype *cft, u64 val)
3701{
182446d0 3702 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7dc74be0 3703
1dfab5ab 3704 if (val & ~MOVE_MASK)
7dc74be0 3705 return -EINVAL;
ee5e8472 3706
7dc74be0 3707 /*
ee5e8472
GC
3708 * No kind of locking is needed in here, because ->can_attach() will
3709 * check this value once in the beginning of the process, and then carry
3710 * on with stale data. This means that changes to this value will only
3711 * affect task migrations starting after the change.
7dc74be0 3712 */
c0ff4b85 3713 memcg->move_charge_at_immigrate = val;
7dc74be0
DN
3714 return 0;
3715}
02491447 3716#else
182446d0 3717static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
02491447
DN
3718 struct cftype *cft, u64 val)
3719{
3720 return -ENOSYS;
3721}
3722#endif
7dc74be0 3723
406eb0c9 3724#ifdef CONFIG_NUMA
113b7dfd
JW
3725
3726#define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3727#define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3728#define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3729
3730static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
3731 int nid, unsigned int lru_mask)
3732{
3733 struct lruvec *lruvec = mem_cgroup_lruvec(NODE_DATA(nid), memcg);
3734 unsigned long nr = 0;
3735 enum lru_list lru;
3736
3737 VM_BUG_ON((unsigned)nid >= nr_node_ids);
3738
3739 for_each_lru(lru) {
3740 if (!(BIT(lru) & lru_mask))
3741 continue;
205b20cc 3742 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
113b7dfd
JW
3743 }
3744 return nr;
3745}
3746
3747static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
3748 unsigned int lru_mask)
3749{
3750 unsigned long nr = 0;
3751 enum lru_list lru;
3752
3753 for_each_lru(lru) {
3754 if (!(BIT(lru) & lru_mask))
3755 continue;
205b20cc 3756 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
113b7dfd
JW
3757 }
3758 return nr;
3759}
3760
2da8ca82 3761static int memcg_numa_stat_show(struct seq_file *m, void *v)
406eb0c9 3762{
25485de6
GT
3763 struct numa_stat {
3764 const char *name;
3765 unsigned int lru_mask;
3766 };
3767
3768 static const struct numa_stat stats[] = {
3769 { "total", LRU_ALL },
3770 { "file", LRU_ALL_FILE },
3771 { "anon", LRU_ALL_ANON },
3772 { "unevictable", BIT(LRU_UNEVICTABLE) },
3773 };
3774 const struct numa_stat *stat;
406eb0c9 3775 int nid;
25485de6 3776 unsigned long nr;
aa9694bb 3777 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
406eb0c9 3778
25485de6
GT
3779 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3780 nr = mem_cgroup_nr_lru_pages(memcg, stat->lru_mask);
3781 seq_printf(m, "%s=%lu", stat->name, nr);
3782 for_each_node_state(nid, N_MEMORY) {
3783 nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
3784 stat->lru_mask);
3785 seq_printf(m, " N%d=%lu", nid, nr);
3786 }
3787 seq_putc(m, '\n');
406eb0c9 3788 }
406eb0c9 3789
071aee13
YH
3790 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3791 struct mem_cgroup *iter;
3792
3793 nr = 0;
3794 for_each_mem_cgroup_tree(iter, memcg)
3795 nr += mem_cgroup_nr_lru_pages(iter, stat->lru_mask);
3796 seq_printf(m, "hierarchical_%s=%lu", stat->name, nr);
3797 for_each_node_state(nid, N_MEMORY) {
3798 nr = 0;
3799 for_each_mem_cgroup_tree(iter, memcg)
3800 nr += mem_cgroup_node_nr_lru_pages(
3801 iter, nid, stat->lru_mask);
3802 seq_printf(m, " N%d=%lu", nid, nr);
3803 }
3804 seq_putc(m, '\n');
406eb0c9 3805 }
406eb0c9 3806
406eb0c9
YH
3807 return 0;
3808}
3809#endif /* CONFIG_NUMA */
3810
c8713d0b
JW
3811static const unsigned int memcg1_stats[] = {
3812 MEMCG_CACHE,
3813 MEMCG_RSS,
3814 MEMCG_RSS_HUGE,
3815 NR_SHMEM,
3816 NR_FILE_MAPPED,
3817 NR_FILE_DIRTY,
3818 NR_WRITEBACK,
3819 MEMCG_SWAP,
3820};
3821
3822static const char *const memcg1_stat_names[] = {
3823 "cache",
3824 "rss",
3825 "rss_huge",
3826 "shmem",
3827 "mapped_file",
3828 "dirty",
3829 "writeback",
3830 "swap",
3831};
3832
df0e53d0 3833/* Universal VM events cgroup1 shows, original sort order */
8dd53fd3 3834static const unsigned int memcg1_events[] = {
df0e53d0
JW
3835 PGPGIN,
3836 PGPGOUT,
3837 PGFAULT,
3838 PGMAJFAULT,
3839};
3840
3841static const char *const memcg1_event_names[] = {
3842 "pgpgin",
3843 "pgpgout",
3844 "pgfault",
3845 "pgmajfault",
3846};
3847
2da8ca82 3848static int memcg_stat_show(struct seq_file *m, void *v)
d2ceb9b7 3849{
aa9694bb 3850 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3e32cb2e 3851 unsigned long memory, memsw;
af7c4b0e
JW
3852 struct mem_cgroup *mi;
3853 unsigned int i;
406eb0c9 3854
71cd3113 3855 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
70bc068c
RS
3856 BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
3857
71cd3113
JW
3858 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
3859 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
1dd3a273 3860 continue;
71cd3113 3861 seq_printf(m, "%s %lu\n", memcg1_stat_names[i],
205b20cc 3862 memcg_page_state_local(memcg, memcg1_stats[i]) *
71cd3113 3863 PAGE_SIZE);
1dd3a273 3864 }
7b854121 3865
df0e53d0
JW
3866 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3867 seq_printf(m, "%s %lu\n", memcg1_event_names[i],
205b20cc 3868 memcg_events_local(memcg, memcg1_events[i]));
af7c4b0e
JW
3869
3870 for (i = 0; i < NR_LRU_LISTS; i++)
3871 seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
205b20cc 3872 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
21d89d15 3873 PAGE_SIZE);
af7c4b0e 3874
14067bb3 3875 /* Hierarchical information */
3e32cb2e
JW
3876 memory = memsw = PAGE_COUNTER_MAX;
3877 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
bbec2e15
RG
3878 memory = min(memory, mi->memory.max);
3879 memsw = min(memsw, mi->memsw.max);
fee7b548 3880 }
3e32cb2e
JW
3881 seq_printf(m, "hierarchical_memory_limit %llu\n",
3882 (u64)memory * PAGE_SIZE);
7941d214 3883 if (do_memsw_account())
3e32cb2e
JW
3884 seq_printf(m, "hierarchical_memsw_limit %llu\n",
3885 (u64)memsw * PAGE_SIZE);
7f016ee8 3886
8de7ecc6 3887 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
71cd3113 3888 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
1dd3a273 3889 continue;
8de7ecc6 3890 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
dd923990
YS
3891 (u64)memcg_page_state(memcg, memcg1_stats[i]) *
3892 PAGE_SIZE);
af7c4b0e
JW
3893 }
3894
8de7ecc6
SB
3895 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3896 seq_printf(m, "total_%s %llu\n", memcg1_event_names[i],
dd923990 3897 (u64)memcg_events(memcg, memcg1_events[i]));
af7c4b0e 3898
8de7ecc6
SB
3899 for (i = 0; i < NR_LRU_LISTS; i++)
3900 seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i],
42a30035
JW
3901 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
3902 PAGE_SIZE);
14067bb3 3903
7f016ee8 3904#ifdef CONFIG_DEBUG_VM
7f016ee8 3905 {
ef8f2327
MG
3906 pg_data_t *pgdat;
3907 struct mem_cgroup_per_node *mz;
89abfab1 3908 struct zone_reclaim_stat *rstat;
7f016ee8
KM
3909 unsigned long recent_rotated[2] = {0, 0};
3910 unsigned long recent_scanned[2] = {0, 0};
3911
ef8f2327
MG
3912 for_each_online_pgdat(pgdat) {
3913 mz = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
3914 rstat = &mz->lruvec.reclaim_stat;
7f016ee8 3915
ef8f2327
MG
3916 recent_rotated[0] += rstat->recent_rotated[0];
3917 recent_rotated[1] += rstat->recent_rotated[1];
3918 recent_scanned[0] += rstat->recent_scanned[0];
3919 recent_scanned[1] += rstat->recent_scanned[1];
3920 }
78ccf5b5
JW
3921 seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
3922 seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
3923 seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
3924 seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
7f016ee8
KM
3925 }
3926#endif
3927
d2ceb9b7
KH
3928 return 0;
3929}
3930
182446d0
TH
3931static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
3932 struct cftype *cft)
a7885eb8 3933{
182446d0 3934 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
a7885eb8 3935
1f4c025b 3936 return mem_cgroup_swappiness(memcg);
a7885eb8
KM
3937}
3938
182446d0
TH
3939static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
3940 struct cftype *cft, u64 val)
a7885eb8 3941{
182446d0 3942 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
a7885eb8 3943
3dae7fec 3944 if (val > 100)
a7885eb8
KM
3945 return -EINVAL;
3946
14208b0e 3947 if (css->parent)
3dae7fec
JW
3948 memcg->swappiness = val;
3949 else
3950 vm_swappiness = val;
068b38c1 3951
a7885eb8
KM
3952 return 0;
3953}
3954
2e72b634
KS
3955static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
3956{
3957 struct mem_cgroup_threshold_ary *t;
3e32cb2e 3958 unsigned long usage;
2e72b634
KS
3959 int i;
3960
3961 rcu_read_lock();
3962 if (!swap)
2c488db2 3963 t = rcu_dereference(memcg->thresholds.primary);
2e72b634 3964 else
2c488db2 3965 t = rcu_dereference(memcg->memsw_thresholds.primary);
2e72b634
KS
3966
3967 if (!t)
3968 goto unlock;
3969
ce00a967 3970 usage = mem_cgroup_usage(memcg, swap);
2e72b634
KS
3971
3972 /*
748dad36 3973 * current_threshold points to threshold just below or equal to usage.
2e72b634
KS
3974 * If it's not true, a threshold was crossed after last
3975 * call of __mem_cgroup_threshold().
3976 */
5407a562 3977 i = t->current_threshold;
2e72b634
KS
3978
3979 /*
3980 * Iterate backward over array of thresholds starting from
3981 * current_threshold and check if a threshold is crossed.
3982 * If none of thresholds below usage is crossed, we read
3983 * only one element of the array here.
3984 */
3985 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
3986 eventfd_signal(t->entries[i].eventfd, 1);
3987
3988 /* i = current_threshold + 1 */
3989 i++;
3990
3991 /*
3992 * Iterate forward over array of thresholds starting from
3993 * current_threshold+1 and check if a threshold is crossed.
3994 * If none of thresholds above usage is crossed, we read
3995 * only one element of the array here.
3996 */
3997 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
3998 eventfd_signal(t->entries[i].eventfd, 1);
3999
4000 /* Update current_threshold */
5407a562 4001 t->current_threshold = i - 1;
2e72b634
KS
4002unlock:
4003 rcu_read_unlock();
4004}
4005
4006static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4007{
ad4ca5f4
KS
4008 while (memcg) {
4009 __mem_cgroup_threshold(memcg, false);
7941d214 4010 if (do_memsw_account())
ad4ca5f4
KS
4011 __mem_cgroup_threshold(memcg, true);
4012
4013 memcg = parent_mem_cgroup(memcg);
4014 }
2e72b634
KS
4015}
4016
4017static int compare_thresholds(const void *a, const void *b)
4018{
4019 const struct mem_cgroup_threshold *_a = a;
4020 const struct mem_cgroup_threshold *_b = b;
4021
2bff24a3
GT
4022 if (_a->threshold > _b->threshold)
4023 return 1;
4024
4025 if (_a->threshold < _b->threshold)
4026 return -1;
4027
4028 return 0;
2e72b634
KS
4029}
4030
c0ff4b85 4031static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
9490ff27
KH
4032{
4033 struct mem_cgroup_eventfd_list *ev;
4034
2bcf2e92
MH
4035 spin_lock(&memcg_oom_lock);
4036
c0ff4b85 4037 list_for_each_entry(ev, &memcg->oom_notify, list)
9490ff27 4038 eventfd_signal(ev->eventfd, 1);
2bcf2e92
MH
4039
4040 spin_unlock(&memcg_oom_lock);
9490ff27
KH
4041 return 0;
4042}
4043
c0ff4b85 4044static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
9490ff27 4045{
7d74b06f
KH
4046 struct mem_cgroup *iter;
4047
c0ff4b85 4048 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f 4049 mem_cgroup_oom_notify_cb(iter);
9490ff27
KH
4050}
4051
59b6f873 4052static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
347c4a87 4053 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
2e72b634 4054{
2c488db2
KS
4055 struct mem_cgroup_thresholds *thresholds;
4056 struct mem_cgroup_threshold_ary *new;
3e32cb2e
JW
4057 unsigned long threshold;
4058 unsigned long usage;
2c488db2 4059 int i, size, ret;
2e72b634 4060
650c5e56 4061 ret = page_counter_memparse(args, "-1", &threshold);
2e72b634
KS
4062 if (ret)
4063 return ret;
4064
4065 mutex_lock(&memcg->thresholds_lock);
2c488db2 4066
05b84301 4067 if (type == _MEM) {
2c488db2 4068 thresholds = &memcg->thresholds;
ce00a967 4069 usage = mem_cgroup_usage(memcg, false);
05b84301 4070 } else if (type == _MEMSWAP) {
2c488db2 4071 thresholds = &memcg->memsw_thresholds;
ce00a967 4072 usage = mem_cgroup_usage(memcg, true);
05b84301 4073 } else
2e72b634
KS
4074 BUG();
4075
2e72b634 4076 /* Check if a threshold crossed before adding a new one */
2c488db2 4077 if (thresholds->primary)
2e72b634
KS
4078 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4079
2c488db2 4080 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
2e72b634
KS
4081
4082 /* Allocate memory for new array of thresholds */
67b8046f 4083 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
2c488db2 4084 if (!new) {
2e72b634
KS
4085 ret = -ENOMEM;
4086 goto unlock;
4087 }
2c488db2 4088 new->size = size;
2e72b634
KS
4089
4090 /* Copy thresholds (if any) to new array */
2c488db2
KS
4091 if (thresholds->primary) {
4092 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
2e72b634 4093 sizeof(struct mem_cgroup_threshold));
2c488db2
KS
4094 }
4095
2e72b634 4096 /* Add new threshold */
2c488db2
KS
4097 new->entries[size - 1].eventfd = eventfd;
4098 new->entries[size - 1].threshold = threshold;
2e72b634
KS
4099
4100 /* Sort thresholds. Registering of new threshold isn't time-critical */
2c488db2 4101 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
2e72b634
KS
4102 compare_thresholds, NULL);
4103
4104 /* Find current threshold */
2c488db2 4105 new->current_threshold = -1;
2e72b634 4106 for (i = 0; i < size; i++) {
748dad36 4107 if (new->entries[i].threshold <= usage) {
2e72b634 4108 /*
2c488db2
KS
4109 * new->current_threshold will not be used until
4110 * rcu_assign_pointer(), so it's safe to increment
2e72b634
KS
4111 * it here.
4112 */
2c488db2 4113 ++new->current_threshold;
748dad36
SZ
4114 } else
4115 break;
2e72b634
KS
4116 }
4117
2c488db2
KS
4118 /* Free old spare buffer and save old primary buffer as spare */
4119 kfree(thresholds->spare);
4120 thresholds->spare = thresholds->primary;
4121
4122 rcu_assign_pointer(thresholds->primary, new);
2e72b634 4123
907860ed 4124 /* To be sure that nobody uses thresholds */
2e72b634
KS
4125 synchronize_rcu();
4126
2e72b634
KS
4127unlock:
4128 mutex_unlock(&memcg->thresholds_lock);
4129
4130 return ret;
4131}
4132
59b6f873 4133static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
347c4a87
TH
4134 struct eventfd_ctx *eventfd, const char *args)
4135{
59b6f873 4136 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
347c4a87
TH
4137}
4138
59b6f873 4139static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
347c4a87
TH
4140 struct eventfd_ctx *eventfd, const char *args)
4141{
59b6f873 4142 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
347c4a87
TH
4143}
4144
59b6f873 4145static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
347c4a87 4146 struct eventfd_ctx *eventfd, enum res_type type)
2e72b634 4147{
2c488db2
KS
4148 struct mem_cgroup_thresholds *thresholds;
4149 struct mem_cgroup_threshold_ary *new;
3e32cb2e 4150 unsigned long usage;
2c488db2 4151 int i, j, size;
2e72b634
KS
4152
4153 mutex_lock(&memcg->thresholds_lock);
05b84301
JW
4154
4155 if (type == _MEM) {
2c488db2 4156 thresholds = &memcg->thresholds;
ce00a967 4157 usage = mem_cgroup_usage(memcg, false);
05b84301 4158 } else if (type == _MEMSWAP) {
2c488db2 4159 thresholds = &memcg->memsw_thresholds;
ce00a967 4160 usage = mem_cgroup_usage(memcg, true);
05b84301 4161 } else
2e72b634
KS
4162 BUG();
4163
371528ca
AV
4164 if (!thresholds->primary)
4165 goto unlock;
4166
2e72b634
KS
4167 /* Check if a threshold crossed before removing */
4168 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4169
4170 /* Calculate new number of threshold */
2c488db2
KS
4171 size = 0;
4172 for (i = 0; i < thresholds->primary->size; i++) {
4173 if (thresholds->primary->entries[i].eventfd != eventfd)
2e72b634
KS
4174 size++;
4175 }
4176
2c488db2 4177 new = thresholds->spare;
907860ed 4178
2e72b634
KS
4179 /* Set thresholds array to NULL if we don't have thresholds */
4180 if (!size) {
2c488db2
KS
4181 kfree(new);
4182 new = NULL;
907860ed 4183 goto swap_buffers;
2e72b634
KS
4184 }
4185
2c488db2 4186 new->size = size;
2e72b634
KS
4187
4188 /* Copy thresholds and find current threshold */
2c488db2
KS
4189 new->current_threshold = -1;
4190 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4191 if (thresholds->primary->entries[i].eventfd == eventfd)
2e72b634
KS
4192 continue;
4193
2c488db2 4194 new->entries[j] = thresholds->primary->entries[i];
748dad36 4195 if (new->entries[j].threshold <= usage) {
2e72b634 4196 /*
2c488db2 4197 * new->current_threshold will not be used
2e72b634
KS
4198 * until rcu_assign_pointer(), so it's safe to increment
4199 * it here.
4200 */
2c488db2 4201 ++new->current_threshold;
2e72b634
KS
4202 }
4203 j++;
4204 }
4205
907860ed 4206swap_buffers:
2c488db2
KS
4207 /* Swap primary and spare array */
4208 thresholds->spare = thresholds->primary;
8c757763 4209
2c488db2 4210 rcu_assign_pointer(thresholds->primary, new);
2e72b634 4211
907860ed 4212 /* To be sure that nobody uses thresholds */
2e72b634 4213 synchronize_rcu();
6611d8d7
MC
4214
4215 /* If all events are unregistered, free the spare array */
4216 if (!new) {
4217 kfree(thresholds->spare);
4218 thresholds->spare = NULL;
4219 }
371528ca 4220unlock:
2e72b634 4221 mutex_unlock(&memcg->thresholds_lock);
2e72b634 4222}
c1e862c1 4223
59b6f873 4224static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
347c4a87
TH
4225 struct eventfd_ctx *eventfd)
4226{
59b6f873 4227 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
347c4a87
TH
4228}
4229
59b6f873 4230static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
347c4a87
TH
4231 struct eventfd_ctx *eventfd)
4232{
59b6f873 4233 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
347c4a87
TH
4234}
4235
59b6f873 4236static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
347c4a87 4237 struct eventfd_ctx *eventfd, const char *args)
9490ff27 4238{
9490ff27 4239 struct mem_cgroup_eventfd_list *event;
9490ff27 4240
9490ff27
KH
4241 event = kmalloc(sizeof(*event), GFP_KERNEL);
4242 if (!event)
4243 return -ENOMEM;
4244
1af8efe9 4245 spin_lock(&memcg_oom_lock);
9490ff27
KH
4246
4247 event->eventfd = eventfd;
4248 list_add(&event->list, &memcg->oom_notify);
4249
4250 /* already in OOM ? */
c2b42d3c 4251 if (memcg->under_oom)
9490ff27 4252 eventfd_signal(eventfd, 1);
1af8efe9 4253 spin_unlock(&memcg_oom_lock);
9490ff27
KH
4254
4255 return 0;
4256}
4257
59b6f873 4258static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
347c4a87 4259 struct eventfd_ctx *eventfd)
9490ff27 4260{
9490ff27 4261 struct mem_cgroup_eventfd_list *ev, *tmp;
9490ff27 4262
1af8efe9 4263 spin_lock(&memcg_oom_lock);
9490ff27 4264
c0ff4b85 4265 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
9490ff27
KH
4266 if (ev->eventfd == eventfd) {
4267 list_del(&ev->list);
4268 kfree(ev);
4269 }
4270 }
4271
1af8efe9 4272 spin_unlock(&memcg_oom_lock);
9490ff27
KH
4273}
4274
2da8ca82 4275static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
3c11ecf4 4276{
aa9694bb 4277 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
3c11ecf4 4278
791badbd 4279 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
c2b42d3c 4280 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
fe6bdfc8
RG
4281 seq_printf(sf, "oom_kill %lu\n",
4282 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
3c11ecf4
KH
4283 return 0;
4284}
4285
182446d0 4286static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
3c11ecf4
KH
4287 struct cftype *cft, u64 val)
4288{
182446d0 4289 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3c11ecf4
KH
4290
4291 /* cannot set to root cgroup and only 0 and 1 are allowed */
14208b0e 4292 if (!css->parent || !((val == 0) || (val == 1)))
3c11ecf4
KH
4293 return -EINVAL;
4294
c0ff4b85 4295 memcg->oom_kill_disable = val;
4d845ebf 4296 if (!val)
c0ff4b85 4297 memcg_oom_recover(memcg);
3dae7fec 4298
3c11ecf4
KH
4299 return 0;
4300}
4301
52ebea74
TH
4302#ifdef CONFIG_CGROUP_WRITEBACK
4303
3a8e9ac8
TH
4304#include <trace/events/writeback.h>
4305
841710aa
TH
4306static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4307{
4308 return wb_domain_init(&memcg->cgwb_domain, gfp);
4309}
4310
4311static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4312{
4313 wb_domain_exit(&memcg->cgwb_domain);
4314}
4315
2529bb3a
TH
4316static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4317{
4318 wb_domain_size_changed(&memcg->cgwb_domain);
4319}
4320
841710aa
TH
4321struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4322{
4323 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4324
4325 if (!memcg->css.parent)
4326 return NULL;
4327
4328 return &memcg->cgwb_domain;
4329}
4330
0b3d6e6f
GT
4331/*
4332 * idx can be of type enum memcg_stat_item or node_stat_item.
4333 * Keep in sync with memcg_exact_page().
4334 */
4335static unsigned long memcg_exact_page_state(struct mem_cgroup *memcg, int idx)
4336{
871789d4 4337 long x = atomic_long_read(&memcg->vmstats[idx]);
0b3d6e6f
GT
4338 int cpu;
4339
4340 for_each_online_cpu(cpu)
871789d4 4341 x += per_cpu_ptr(memcg->vmstats_percpu, cpu)->stat[idx];
0b3d6e6f
GT
4342 if (x < 0)
4343 x = 0;
4344 return x;
4345}
4346
c2aa723a
TH
4347/**
4348 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4349 * @wb: bdi_writeback in question
c5edf9cd
TH
4350 * @pfilepages: out parameter for number of file pages
4351 * @pheadroom: out parameter for number of allocatable pages according to memcg
c2aa723a
TH
4352 * @pdirty: out parameter for number of dirty pages
4353 * @pwriteback: out parameter for number of pages under writeback
4354 *
c5edf9cd
TH
4355 * Determine the numbers of file, headroom, dirty, and writeback pages in
4356 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4357 * is a bit more involved.
c2aa723a 4358 *
c5edf9cd
TH
4359 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4360 * headroom is calculated as the lowest headroom of itself and the
4361 * ancestors. Note that this doesn't consider the actual amount of
4362 * available memory in the system. The caller should further cap
4363 * *@pheadroom accordingly.
c2aa723a 4364 */
c5edf9cd
TH
4365void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4366 unsigned long *pheadroom, unsigned long *pdirty,
4367 unsigned long *pwriteback)
c2aa723a
TH
4368{
4369 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4370 struct mem_cgroup *parent;
c2aa723a 4371
0b3d6e6f 4372 *pdirty = memcg_exact_page_state(memcg, NR_FILE_DIRTY);
c2aa723a
TH
4373
4374 /* this should eventually include NR_UNSTABLE_NFS */
0b3d6e6f 4375 *pwriteback = memcg_exact_page_state(memcg, NR_WRITEBACK);
21d89d15
JW
4376 *pfilepages = memcg_exact_page_state(memcg, NR_INACTIVE_FILE) +
4377 memcg_exact_page_state(memcg, NR_ACTIVE_FILE);
c5edf9cd 4378 *pheadroom = PAGE_COUNTER_MAX;
c2aa723a 4379
c2aa723a 4380 while ((parent = parent_mem_cgroup(memcg))) {
bbec2e15 4381 unsigned long ceiling = min(memcg->memory.max, memcg->high);
c2aa723a
TH
4382 unsigned long used = page_counter_read(&memcg->memory);
4383
c5edf9cd 4384 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
c2aa723a
TH
4385 memcg = parent;
4386 }
c2aa723a
TH
4387}
4388
97b27821
TH
4389/*
4390 * Foreign dirty flushing
4391 *
4392 * There's an inherent mismatch between memcg and writeback. The former
4393 * trackes ownership per-page while the latter per-inode. This was a
4394 * deliberate design decision because honoring per-page ownership in the
4395 * writeback path is complicated, may lead to higher CPU and IO overheads
4396 * and deemed unnecessary given that write-sharing an inode across
4397 * different cgroups isn't a common use-case.
4398 *
4399 * Combined with inode majority-writer ownership switching, this works well
4400 * enough in most cases but there are some pathological cases. For
4401 * example, let's say there are two cgroups A and B which keep writing to
4402 * different but confined parts of the same inode. B owns the inode and
4403 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4404 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4405 * triggering background writeback. A will be slowed down without a way to
4406 * make writeback of the dirty pages happen.
4407 *
4408 * Conditions like the above can lead to a cgroup getting repatedly and
4409 * severely throttled after making some progress after each
4410 * dirty_expire_interval while the underyling IO device is almost
4411 * completely idle.
4412 *
4413 * Solving this problem completely requires matching the ownership tracking
4414 * granularities between memcg and writeback in either direction. However,
4415 * the more egregious behaviors can be avoided by simply remembering the
4416 * most recent foreign dirtying events and initiating remote flushes on
4417 * them when local writeback isn't enough to keep the memory clean enough.
4418 *
4419 * The following two functions implement such mechanism. When a foreign
4420 * page - a page whose memcg and writeback ownerships don't match - is
4421 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4422 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4423 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4424 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4425 * foreign bdi_writebacks which haven't expired. Both the numbers of
4426 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4427 * limited to MEMCG_CGWB_FRN_CNT.
4428 *
4429 * The mechanism only remembers IDs and doesn't hold any object references.
4430 * As being wrong occasionally doesn't matter, updates and accesses to the
4431 * records are lockless and racy.
4432 */
4433void mem_cgroup_track_foreign_dirty_slowpath(struct page *page,
4434 struct bdi_writeback *wb)
4435{
4436 struct mem_cgroup *memcg = page->mem_cgroup;
4437 struct memcg_cgwb_frn *frn;
4438 u64 now = get_jiffies_64();
4439 u64 oldest_at = now;
4440 int oldest = -1;
4441 int i;
4442
3a8e9ac8
TH
4443 trace_track_foreign_dirty(page, wb);
4444
97b27821
TH
4445 /*
4446 * Pick the slot to use. If there is already a slot for @wb, keep
4447 * using it. If not replace the oldest one which isn't being
4448 * written out.
4449 */
4450 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4451 frn = &memcg->cgwb_frn[i];
4452 if (frn->bdi_id == wb->bdi->id &&
4453 frn->memcg_id == wb->memcg_css->id)
4454 break;
4455 if (time_before64(frn->at, oldest_at) &&
4456 atomic_read(&frn->done.cnt) == 1) {
4457 oldest = i;
4458 oldest_at = frn->at;
4459 }
4460 }
4461
4462 if (i < MEMCG_CGWB_FRN_CNT) {
4463 /*
4464 * Re-using an existing one. Update timestamp lazily to
4465 * avoid making the cacheline hot. We want them to be
4466 * reasonably up-to-date and significantly shorter than
4467 * dirty_expire_interval as that's what expires the record.
4468 * Use the shorter of 1s and dirty_expire_interval / 8.
4469 */
4470 unsigned long update_intv =
4471 min_t(unsigned long, HZ,
4472 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4473
4474 if (time_before64(frn->at, now - update_intv))
4475 frn->at = now;
4476 } else if (oldest >= 0) {
4477 /* replace the oldest free one */
4478 frn = &memcg->cgwb_frn[oldest];
4479 frn->bdi_id = wb->bdi->id;
4480 frn->memcg_id = wb->memcg_css->id;
4481 frn->at = now;
4482 }
4483}
4484
4485/* issue foreign writeback flushes for recorded foreign dirtying events */
4486void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4487{
4488 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4489 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4490 u64 now = jiffies_64;
4491 int i;
4492
4493 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4494 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4495
4496 /*
4497 * If the record is older than dirty_expire_interval,
4498 * writeback on it has already started. No need to kick it
4499 * off again. Also, don't start a new one if there's
4500 * already one in flight.
4501 */
4502 if (time_after64(frn->at, now - intv) &&
4503 atomic_read(&frn->done.cnt) == 1) {
4504 frn->at = 0;
3a8e9ac8 4505 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
97b27821
TH
4506 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id, 0,
4507 WB_REASON_FOREIGN_FLUSH,
4508 &frn->done);
4509 }
4510 }
4511}
4512
841710aa
TH
4513#else /* CONFIG_CGROUP_WRITEBACK */
4514
4515static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4516{
4517 return 0;
4518}
4519
4520static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4521{
4522}
4523
2529bb3a
TH
4524static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4525{
4526}
4527
52ebea74
TH
4528#endif /* CONFIG_CGROUP_WRITEBACK */
4529
3bc942f3
TH
4530/*
4531 * DO NOT USE IN NEW FILES.
4532 *
4533 * "cgroup.event_control" implementation.
4534 *
4535 * This is way over-engineered. It tries to support fully configurable
4536 * events for each user. Such level of flexibility is completely
4537 * unnecessary especially in the light of the planned unified hierarchy.
4538 *
4539 * Please deprecate this and replace with something simpler if at all
4540 * possible.
4541 */
4542
79bd9814
TH
4543/*
4544 * Unregister event and free resources.
4545 *
4546 * Gets called from workqueue.
4547 */
3bc942f3 4548static void memcg_event_remove(struct work_struct *work)
79bd9814 4549{
3bc942f3
TH
4550 struct mem_cgroup_event *event =
4551 container_of(work, struct mem_cgroup_event, remove);
59b6f873 4552 struct mem_cgroup *memcg = event->memcg;
79bd9814
TH
4553
4554 remove_wait_queue(event->wqh, &event->wait);
4555
59b6f873 4556 event->unregister_event(memcg, event->eventfd);
79bd9814
TH
4557
4558 /* Notify userspace the event is going away. */
4559 eventfd_signal(event->eventfd, 1);
4560
4561 eventfd_ctx_put(event->eventfd);
4562 kfree(event);
59b6f873 4563 css_put(&memcg->css);
79bd9814
TH
4564}
4565
4566/*
a9a08845 4567 * Gets called on EPOLLHUP on eventfd when user closes it.
79bd9814
TH
4568 *
4569 * Called with wqh->lock held and interrupts disabled.
4570 */
ac6424b9 4571static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
3bc942f3 4572 int sync, void *key)
79bd9814 4573{
3bc942f3
TH
4574 struct mem_cgroup_event *event =
4575 container_of(wait, struct mem_cgroup_event, wait);
59b6f873 4576 struct mem_cgroup *memcg = event->memcg;
3ad6f93e 4577 __poll_t flags = key_to_poll(key);
79bd9814 4578
a9a08845 4579 if (flags & EPOLLHUP) {
79bd9814
TH
4580 /*
4581 * If the event has been detached at cgroup removal, we
4582 * can simply return knowing the other side will cleanup
4583 * for us.
4584 *
4585 * We can't race against event freeing since the other
4586 * side will require wqh->lock via remove_wait_queue(),
4587 * which we hold.
4588 */
fba94807 4589 spin_lock(&memcg->event_list_lock);
79bd9814
TH
4590 if (!list_empty(&event->list)) {
4591 list_del_init(&event->list);
4592 /*
4593 * We are in atomic context, but cgroup_event_remove()
4594 * may sleep, so we have to call it in workqueue.
4595 */
4596 schedule_work(&event->remove);
4597 }
fba94807 4598 spin_unlock(&memcg->event_list_lock);
79bd9814
TH
4599 }
4600
4601 return 0;
4602}
4603
3bc942f3 4604static void memcg_event_ptable_queue_proc(struct file *file,
79bd9814
TH
4605 wait_queue_head_t *wqh, poll_table *pt)
4606{
3bc942f3
TH
4607 struct mem_cgroup_event *event =
4608 container_of(pt, struct mem_cgroup_event, pt);
79bd9814
TH
4609
4610 event->wqh = wqh;
4611 add_wait_queue(wqh, &event->wait);
4612}
4613
4614/*
3bc942f3
TH
4615 * DO NOT USE IN NEW FILES.
4616 *
79bd9814
TH
4617 * Parse input and register new cgroup event handler.
4618 *
4619 * Input must be in format '<event_fd> <control_fd> <args>'.
4620 * Interpretation of args is defined by control file implementation.
4621 */
451af504
TH
4622static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4623 char *buf, size_t nbytes, loff_t off)
79bd9814 4624{
451af504 4625 struct cgroup_subsys_state *css = of_css(of);
fba94807 4626 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3bc942f3 4627 struct mem_cgroup_event *event;
79bd9814
TH
4628 struct cgroup_subsys_state *cfile_css;
4629 unsigned int efd, cfd;
4630 struct fd efile;
4631 struct fd cfile;
fba94807 4632 const char *name;
79bd9814
TH
4633 char *endp;
4634 int ret;
4635
451af504
TH
4636 buf = strstrip(buf);
4637
4638 efd = simple_strtoul(buf, &endp, 10);
79bd9814
TH
4639 if (*endp != ' ')
4640 return -EINVAL;
451af504 4641 buf = endp + 1;
79bd9814 4642
451af504 4643 cfd = simple_strtoul(buf, &endp, 10);
79bd9814
TH
4644 if ((*endp != ' ') && (*endp != '\0'))
4645 return -EINVAL;
451af504 4646 buf = endp + 1;
79bd9814
TH
4647
4648 event = kzalloc(sizeof(*event), GFP_KERNEL);
4649 if (!event)
4650 return -ENOMEM;
4651
59b6f873 4652 event->memcg = memcg;
79bd9814 4653 INIT_LIST_HEAD(&event->list);
3bc942f3
TH
4654 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4655 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4656 INIT_WORK(&event->remove, memcg_event_remove);
79bd9814
TH
4657
4658 efile = fdget(efd);
4659 if (!efile.file) {
4660 ret = -EBADF;
4661 goto out_kfree;
4662 }
4663
4664 event->eventfd = eventfd_ctx_fileget(efile.file);
4665 if (IS_ERR(event->eventfd)) {
4666 ret = PTR_ERR(event->eventfd);
4667 goto out_put_efile;
4668 }
4669
4670 cfile = fdget(cfd);
4671 if (!cfile.file) {
4672 ret = -EBADF;
4673 goto out_put_eventfd;
4674 }
4675
4676 /* the process need read permission on control file */
4677 /* AV: shouldn't we check that it's been opened for read instead? */
4678 ret = inode_permission(file_inode(cfile.file), MAY_READ);
4679 if (ret < 0)
4680 goto out_put_cfile;
4681
fba94807
TH
4682 /*
4683 * Determine the event callbacks and set them in @event. This used
4684 * to be done via struct cftype but cgroup core no longer knows
4685 * about these events. The following is crude but the whole thing
4686 * is for compatibility anyway.
3bc942f3
TH
4687 *
4688 * DO NOT ADD NEW FILES.
fba94807 4689 */
b583043e 4690 name = cfile.file->f_path.dentry->d_name.name;
fba94807
TH
4691
4692 if (!strcmp(name, "memory.usage_in_bytes")) {
4693 event->register_event = mem_cgroup_usage_register_event;
4694 event->unregister_event = mem_cgroup_usage_unregister_event;
4695 } else if (!strcmp(name, "memory.oom_control")) {
4696 event->register_event = mem_cgroup_oom_register_event;
4697 event->unregister_event = mem_cgroup_oom_unregister_event;
4698 } else if (!strcmp(name, "memory.pressure_level")) {
4699 event->register_event = vmpressure_register_event;
4700 event->unregister_event = vmpressure_unregister_event;
4701 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
347c4a87
TH
4702 event->register_event = memsw_cgroup_usage_register_event;
4703 event->unregister_event = memsw_cgroup_usage_unregister_event;
fba94807
TH
4704 } else {
4705 ret = -EINVAL;
4706 goto out_put_cfile;
4707 }
4708
79bd9814 4709 /*
b5557c4c
TH
4710 * Verify @cfile should belong to @css. Also, remaining events are
4711 * automatically removed on cgroup destruction but the removal is
4712 * asynchronous, so take an extra ref on @css.
79bd9814 4713 */
b583043e 4714 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
ec903c0c 4715 &memory_cgrp_subsys);
79bd9814 4716 ret = -EINVAL;
5a17f543 4717 if (IS_ERR(cfile_css))
79bd9814 4718 goto out_put_cfile;
5a17f543
TH
4719 if (cfile_css != css) {
4720 css_put(cfile_css);
79bd9814 4721 goto out_put_cfile;
5a17f543 4722 }
79bd9814 4723
451af504 4724 ret = event->register_event(memcg, event->eventfd, buf);
79bd9814
TH
4725 if (ret)
4726 goto out_put_css;
4727
9965ed17 4728 vfs_poll(efile.file, &event->pt);
79bd9814 4729
fba94807
TH
4730 spin_lock(&memcg->event_list_lock);
4731 list_add(&event->list, &memcg->event_list);
4732 spin_unlock(&memcg->event_list_lock);
79bd9814
TH
4733
4734 fdput(cfile);
4735 fdput(efile);
4736
451af504 4737 return nbytes;
79bd9814
TH
4738
4739out_put_css:
b5557c4c 4740 css_put(css);
79bd9814
TH
4741out_put_cfile:
4742 fdput(cfile);
4743out_put_eventfd:
4744 eventfd_ctx_put(event->eventfd);
4745out_put_efile:
4746 fdput(efile);
4747out_kfree:
4748 kfree(event);
4749
4750 return ret;
4751}
4752
241994ed 4753static struct cftype mem_cgroup_legacy_files[] = {
8cdea7c0 4754 {
0eea1030 4755 .name = "usage_in_bytes",
8c7c6e34 4756 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
791badbd 4757 .read_u64 = mem_cgroup_read_u64,
8cdea7c0 4758 },
c84872e1
PE
4759 {
4760 .name = "max_usage_in_bytes",
8c7c6e34 4761 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
6770c64e 4762 .write = mem_cgroup_reset,
791badbd 4763 .read_u64 = mem_cgroup_read_u64,
c84872e1 4764 },
8cdea7c0 4765 {
0eea1030 4766 .name = "limit_in_bytes",
8c7c6e34 4767 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
451af504 4768 .write = mem_cgroup_write,
791badbd 4769 .read_u64 = mem_cgroup_read_u64,
8cdea7c0 4770 },
296c81d8
BS
4771 {
4772 .name = "soft_limit_in_bytes",
4773 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
451af504 4774 .write = mem_cgroup_write,
791badbd 4775 .read_u64 = mem_cgroup_read_u64,
296c81d8 4776 },
8cdea7c0
BS
4777 {
4778 .name = "failcnt",
8c7c6e34 4779 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
6770c64e 4780 .write = mem_cgroup_reset,
791badbd 4781 .read_u64 = mem_cgroup_read_u64,
8cdea7c0 4782 },
d2ceb9b7
KH
4783 {
4784 .name = "stat",
2da8ca82 4785 .seq_show = memcg_stat_show,
d2ceb9b7 4786 },
c1e862c1
KH
4787 {
4788 .name = "force_empty",
6770c64e 4789 .write = mem_cgroup_force_empty_write,
c1e862c1 4790 },
18f59ea7
BS
4791 {
4792 .name = "use_hierarchy",
4793 .write_u64 = mem_cgroup_hierarchy_write,
4794 .read_u64 = mem_cgroup_hierarchy_read,
4795 },
79bd9814 4796 {
3bc942f3 4797 .name = "cgroup.event_control", /* XXX: for compat */
451af504 4798 .write = memcg_write_event_control,
7dbdb199 4799 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
79bd9814 4800 },
a7885eb8
KM
4801 {
4802 .name = "swappiness",
4803 .read_u64 = mem_cgroup_swappiness_read,
4804 .write_u64 = mem_cgroup_swappiness_write,
4805 },
7dc74be0
DN
4806 {
4807 .name = "move_charge_at_immigrate",
4808 .read_u64 = mem_cgroup_move_charge_read,
4809 .write_u64 = mem_cgroup_move_charge_write,
4810 },
9490ff27
KH
4811 {
4812 .name = "oom_control",
2da8ca82 4813 .seq_show = mem_cgroup_oom_control_read,
3c11ecf4 4814 .write_u64 = mem_cgroup_oom_control_write,
9490ff27
KH
4815 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4816 },
70ddf637
AV
4817 {
4818 .name = "pressure_level",
70ddf637 4819 },
406eb0c9
YH
4820#ifdef CONFIG_NUMA
4821 {
4822 .name = "numa_stat",
2da8ca82 4823 .seq_show = memcg_numa_stat_show,
406eb0c9
YH
4824 },
4825#endif
510fc4e1
GC
4826 {
4827 .name = "kmem.limit_in_bytes",
4828 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
451af504 4829 .write = mem_cgroup_write,
791badbd 4830 .read_u64 = mem_cgroup_read_u64,
510fc4e1
GC
4831 },
4832 {
4833 .name = "kmem.usage_in_bytes",
4834 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
791badbd 4835 .read_u64 = mem_cgroup_read_u64,
510fc4e1
GC
4836 },
4837 {
4838 .name = "kmem.failcnt",
4839 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
6770c64e 4840 .write = mem_cgroup_reset,
791badbd 4841 .read_u64 = mem_cgroup_read_u64,
510fc4e1
GC
4842 },
4843 {
4844 .name = "kmem.max_usage_in_bytes",
4845 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
6770c64e 4846 .write = mem_cgroup_reset,
791badbd 4847 .read_u64 = mem_cgroup_read_u64,
510fc4e1 4848 },
5b365771 4849#if defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)
749c5415
GC
4850 {
4851 .name = "kmem.slabinfo",
bc2791f8
TH
4852 .seq_start = memcg_slab_start,
4853 .seq_next = memcg_slab_next,
4854 .seq_stop = memcg_slab_stop,
b047501c 4855 .seq_show = memcg_slab_show,
749c5415
GC
4856 },
4857#endif
d55f90bf
VD
4858 {
4859 .name = "kmem.tcp.limit_in_bytes",
4860 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
4861 .write = mem_cgroup_write,
4862 .read_u64 = mem_cgroup_read_u64,
4863 },
4864 {
4865 .name = "kmem.tcp.usage_in_bytes",
4866 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
4867 .read_u64 = mem_cgroup_read_u64,
4868 },
4869 {
4870 .name = "kmem.tcp.failcnt",
4871 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
4872 .write = mem_cgroup_reset,
4873 .read_u64 = mem_cgroup_read_u64,
4874 },
4875 {
4876 .name = "kmem.tcp.max_usage_in_bytes",
4877 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
4878 .write = mem_cgroup_reset,
4879 .read_u64 = mem_cgroup_read_u64,
4880 },
6bc10349 4881 { }, /* terminate */
af36f906 4882};
8c7c6e34 4883
73f576c0
JW
4884/*
4885 * Private memory cgroup IDR
4886 *
4887 * Swap-out records and page cache shadow entries need to store memcg
4888 * references in constrained space, so we maintain an ID space that is
4889 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
4890 * memory-controlled cgroups to 64k.
4891 *
4892 * However, there usually are many references to the oflline CSS after
4893 * the cgroup has been destroyed, such as page cache or reclaimable
4894 * slab objects, that don't need to hang on to the ID. We want to keep
4895 * those dead CSS from occupying IDs, or we might quickly exhaust the
4896 * relatively small ID space and prevent the creation of new cgroups
4897 * even when there are much fewer than 64k cgroups - possibly none.
4898 *
4899 * Maintain a private 16-bit ID space for memcg, and allow the ID to
4900 * be freed and recycled when it's no longer needed, which is usually
4901 * when the CSS is offlined.
4902 *
4903 * The only exception to that are records of swapped out tmpfs/shmem
4904 * pages that need to be attributed to live ancestors on swapin. But
4905 * those references are manageable from userspace.
4906 */
4907
4908static DEFINE_IDR(mem_cgroup_idr);
4909
7e97de0b
KT
4910static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
4911{
4912 if (memcg->id.id > 0) {
4913 idr_remove(&mem_cgroup_idr, memcg->id.id);
4914 memcg->id.id = 0;
4915 }
4916}
4917
615d66c3 4918static void mem_cgroup_id_get_many(struct mem_cgroup *memcg, unsigned int n)
73f576c0 4919{
1c2d479a 4920 refcount_add(n, &memcg->id.ref);
73f576c0
JW
4921}
4922
615d66c3 4923static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
73f576c0 4924{
1c2d479a 4925 if (refcount_sub_and_test(n, &memcg->id.ref)) {
7e97de0b 4926 mem_cgroup_id_remove(memcg);
73f576c0
JW
4927
4928 /* Memcg ID pins CSS */
4929 css_put(&memcg->css);
4930 }
4931}
4932
615d66c3
VD
4933static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
4934{
4935 mem_cgroup_id_put_many(memcg, 1);
4936}
4937
73f576c0
JW
4938/**
4939 * mem_cgroup_from_id - look up a memcg from a memcg id
4940 * @id: the memcg id to look up
4941 *
4942 * Caller must hold rcu_read_lock().
4943 */
4944struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
4945{
4946 WARN_ON_ONCE(!rcu_read_lock_held());
4947 return idr_find(&mem_cgroup_idr, id);
4948}
4949
ef8f2327 4950static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
6d12e2d8
KH
4951{
4952 struct mem_cgroup_per_node *pn;
ef8f2327 4953 int tmp = node;
1ecaab2b
KH
4954 /*
4955 * This routine is called against possible nodes.
4956 * But it's BUG to call kmalloc() against offline node.
4957 *
4958 * TODO: this routine can waste much memory for nodes which will
4959 * never be onlined. It's better to use memory hotplug callback
4960 * function.
4961 */
41e3355d
KH
4962 if (!node_state(node, N_NORMAL_MEMORY))
4963 tmp = -1;
17295c88 4964 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
6d12e2d8
KH
4965 if (!pn)
4966 return 1;
1ecaab2b 4967
815744d7
JW
4968 pn->lruvec_stat_local = alloc_percpu(struct lruvec_stat);
4969 if (!pn->lruvec_stat_local) {
4970 kfree(pn);
4971 return 1;
4972 }
4973
a983b5eb
JW
4974 pn->lruvec_stat_cpu = alloc_percpu(struct lruvec_stat);
4975 if (!pn->lruvec_stat_cpu) {
815744d7 4976 free_percpu(pn->lruvec_stat_local);
00f3ca2c
JW
4977 kfree(pn);
4978 return 1;
4979 }
4980
ef8f2327
MG
4981 lruvec_init(&pn->lruvec);
4982 pn->usage_in_excess = 0;
4983 pn->on_tree = false;
4984 pn->memcg = memcg;
4985
54f72fe0 4986 memcg->nodeinfo[node] = pn;
6d12e2d8
KH
4987 return 0;
4988}
4989
ef8f2327 4990static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
1ecaab2b 4991{
00f3ca2c
JW
4992 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
4993
4eaf431f
MH
4994 if (!pn)
4995 return;
4996
a983b5eb 4997 free_percpu(pn->lruvec_stat_cpu);
815744d7 4998 free_percpu(pn->lruvec_stat_local);
00f3ca2c 4999 kfree(pn);
1ecaab2b
KH
5000}
5001
40e952f9 5002static void __mem_cgroup_free(struct mem_cgroup *memcg)
59927fb9 5003{
c8b2a36f 5004 int node;
59927fb9 5005
c350a99e 5006 /*
bb65f89b 5007 * Flush percpu vmstats and vmevents to guarantee the value correctness
c350a99e
RG
5008 * on parent's and all ancestor levels.
5009 */
bee07b33 5010 memcg_flush_percpu_vmstats(memcg, false);
bb65f89b 5011 memcg_flush_percpu_vmevents(memcg);
c8b2a36f 5012 for_each_node(node)
ef8f2327 5013 free_mem_cgroup_per_node_info(memcg, node);
871789d4 5014 free_percpu(memcg->vmstats_percpu);
815744d7 5015 free_percpu(memcg->vmstats_local);
8ff69e2c 5016 kfree(memcg);
59927fb9 5017}
3afe36b1 5018
40e952f9
TE
5019static void mem_cgroup_free(struct mem_cgroup *memcg)
5020{
5021 memcg_wb_domain_exit(memcg);
5022 __mem_cgroup_free(memcg);
5023}
5024
0b8f73e1 5025static struct mem_cgroup *mem_cgroup_alloc(void)
8cdea7c0 5026{
d142e3e6 5027 struct mem_cgroup *memcg;
b9726c26 5028 unsigned int size;
6d12e2d8 5029 int node;
97b27821 5030 int __maybe_unused i;
8cdea7c0 5031
0b8f73e1
JW
5032 size = sizeof(struct mem_cgroup);
5033 size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
5034
5035 memcg = kzalloc(size, GFP_KERNEL);
c0ff4b85 5036 if (!memcg)
0b8f73e1
JW
5037 return NULL;
5038
73f576c0
JW
5039 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5040 1, MEM_CGROUP_ID_MAX,
5041 GFP_KERNEL);
5042 if (memcg->id.id < 0)
5043 goto fail;
5044
815744d7
JW
5045 memcg->vmstats_local = alloc_percpu(struct memcg_vmstats_percpu);
5046 if (!memcg->vmstats_local)
5047 goto fail;
5048
871789d4
CD
5049 memcg->vmstats_percpu = alloc_percpu(struct memcg_vmstats_percpu);
5050 if (!memcg->vmstats_percpu)
0b8f73e1 5051 goto fail;
78fb7466 5052
3ed28fa1 5053 for_each_node(node)
ef8f2327 5054 if (alloc_mem_cgroup_per_node_info(memcg, node))
0b8f73e1 5055 goto fail;
f64c3f54 5056
0b8f73e1
JW
5057 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5058 goto fail;
28dbc4b6 5059
f7e1cb6e 5060 INIT_WORK(&memcg->high_work, high_work_func);
d142e3e6
GC
5061 memcg->last_scanned_node = MAX_NUMNODES;
5062 INIT_LIST_HEAD(&memcg->oom_notify);
d142e3e6
GC
5063 mutex_init(&memcg->thresholds_lock);
5064 spin_lock_init(&memcg->move_lock);
70ddf637 5065 vmpressure_init(&memcg->vmpressure);
fba94807
TH
5066 INIT_LIST_HEAD(&memcg->event_list);
5067 spin_lock_init(&memcg->event_list_lock);
d886f4e4 5068 memcg->socket_pressure = jiffies;
84c07d11 5069#ifdef CONFIG_MEMCG_KMEM
900a38f0 5070 memcg->kmemcg_id = -1;
900a38f0 5071#endif
52ebea74
TH
5072#ifdef CONFIG_CGROUP_WRITEBACK
5073 INIT_LIST_HEAD(&memcg->cgwb_list);
97b27821
TH
5074 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5075 memcg->cgwb_frn[i].done =
5076 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
52ebea74 5077#endif
73f576c0 5078 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
0b8f73e1
JW
5079 return memcg;
5080fail:
7e97de0b 5081 mem_cgroup_id_remove(memcg);
40e952f9 5082 __mem_cgroup_free(memcg);
0b8f73e1 5083 return NULL;
d142e3e6
GC
5084}
5085
0b8f73e1
JW
5086static struct cgroup_subsys_state * __ref
5087mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
d142e3e6 5088{
0b8f73e1
JW
5089 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5090 struct mem_cgroup *memcg;
5091 long error = -ENOMEM;
d142e3e6 5092
0b8f73e1
JW
5093 memcg = mem_cgroup_alloc();
5094 if (!memcg)
5095 return ERR_PTR(error);
d142e3e6 5096
0b8f73e1
JW
5097 memcg->high = PAGE_COUNTER_MAX;
5098 memcg->soft_limit = PAGE_COUNTER_MAX;
5099 if (parent) {
5100 memcg->swappiness = mem_cgroup_swappiness(parent);
5101 memcg->oom_kill_disable = parent->oom_kill_disable;
5102 }
5103 if (parent && parent->use_hierarchy) {
5104 memcg->use_hierarchy = true;
3e32cb2e 5105 page_counter_init(&memcg->memory, &parent->memory);
37e84351 5106 page_counter_init(&memcg->swap, &parent->swap);
3e32cb2e
JW
5107 page_counter_init(&memcg->memsw, &parent->memsw);
5108 page_counter_init(&memcg->kmem, &parent->kmem);
0db15298 5109 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
18f59ea7 5110 } else {
3e32cb2e 5111 page_counter_init(&memcg->memory, NULL);
37e84351 5112 page_counter_init(&memcg->swap, NULL);
3e32cb2e
JW
5113 page_counter_init(&memcg->memsw, NULL);
5114 page_counter_init(&memcg->kmem, NULL);
0db15298 5115 page_counter_init(&memcg->tcpmem, NULL);
8c7f6edb
TH
5116 /*
5117 * Deeper hierachy with use_hierarchy == false doesn't make
5118 * much sense so let cgroup subsystem know about this
5119 * unfortunate state in our controller.
5120 */
d142e3e6 5121 if (parent != root_mem_cgroup)
073219e9 5122 memory_cgrp_subsys.broken_hierarchy = true;
18f59ea7 5123 }
d6441637 5124
0b8f73e1
JW
5125 /* The following stuff does not apply to the root */
5126 if (!parent) {
fb2f2b0a
RG
5127#ifdef CONFIG_MEMCG_KMEM
5128 INIT_LIST_HEAD(&memcg->kmem_caches);
5129#endif
0b8f73e1
JW
5130 root_mem_cgroup = memcg;
5131 return &memcg->css;
5132 }
5133
b313aeee 5134 error = memcg_online_kmem(memcg);
0b8f73e1
JW
5135 if (error)
5136 goto fail;
127424c8 5137
f7e1cb6e 5138 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
ef12947c 5139 static_branch_inc(&memcg_sockets_enabled_key);
f7e1cb6e 5140
0b8f73e1
JW
5141 return &memcg->css;
5142fail:
7e97de0b 5143 mem_cgroup_id_remove(memcg);
0b8f73e1 5144 mem_cgroup_free(memcg);
ea3a9645 5145 return ERR_PTR(-ENOMEM);
0b8f73e1
JW
5146}
5147
73f576c0 5148static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
0b8f73e1 5149{
58fa2a55
VD
5150 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5151
0a4465d3
KT
5152 /*
5153 * A memcg must be visible for memcg_expand_shrinker_maps()
5154 * by the time the maps are allocated. So, we allocate maps
5155 * here, when for_each_mem_cgroup() can't skip it.
5156 */
5157 if (memcg_alloc_shrinker_maps(memcg)) {
5158 mem_cgroup_id_remove(memcg);
5159 return -ENOMEM;
5160 }
5161
73f576c0 5162 /* Online state pins memcg ID, memcg ID pins CSS */
1c2d479a 5163 refcount_set(&memcg->id.ref, 1);
73f576c0 5164 css_get(css);
2f7dd7a4 5165 return 0;
8cdea7c0
BS
5166}
5167
eb95419b 5168static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
df878fb0 5169{
eb95419b 5170 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3bc942f3 5171 struct mem_cgroup_event *event, *tmp;
79bd9814
TH
5172
5173 /*
5174 * Unregister events and notify userspace.
5175 * Notify userspace about cgroup removing only after rmdir of cgroup
5176 * directory to avoid race between userspace and kernelspace.
5177 */
fba94807
TH
5178 spin_lock(&memcg->event_list_lock);
5179 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
79bd9814
TH
5180 list_del_init(&event->list);
5181 schedule_work(&event->remove);
5182 }
fba94807 5183 spin_unlock(&memcg->event_list_lock);
ec64f515 5184
bf8d5d52 5185 page_counter_set_min(&memcg->memory, 0);
23067153 5186 page_counter_set_low(&memcg->memory, 0);
63677c74 5187
567e9ab2 5188 memcg_offline_kmem(memcg);
52ebea74 5189 wb_memcg_offline(memcg);
73f576c0 5190
591edfb1
RG
5191 drain_all_stock(memcg);
5192
73f576c0 5193 mem_cgroup_id_put(memcg);
df878fb0
KH
5194}
5195
6df38689
VD
5196static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5197{
5198 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5199
5200 invalidate_reclaim_iterators(memcg);
5201}
5202
eb95419b 5203static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
8cdea7c0 5204{
eb95419b 5205 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
97b27821 5206 int __maybe_unused i;
c268e994 5207
97b27821
TH
5208#ifdef CONFIG_CGROUP_WRITEBACK
5209 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5210 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5211#endif
f7e1cb6e 5212 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
ef12947c 5213 static_branch_dec(&memcg_sockets_enabled_key);
127424c8 5214
0db15298 5215 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
d55f90bf 5216 static_branch_dec(&memcg_sockets_enabled_key);
3893e302 5217
0b8f73e1
JW
5218 vmpressure_cleanup(&memcg->vmpressure);
5219 cancel_work_sync(&memcg->high_work);
5220 mem_cgroup_remove_from_trees(memcg);
0a4465d3 5221 memcg_free_shrinker_maps(memcg);
d886f4e4 5222 memcg_free_kmem(memcg);
0b8f73e1 5223 mem_cgroup_free(memcg);
8cdea7c0
BS
5224}
5225
1ced953b
TH
5226/**
5227 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5228 * @css: the target css
5229 *
5230 * Reset the states of the mem_cgroup associated with @css. This is
5231 * invoked when the userland requests disabling on the default hierarchy
5232 * but the memcg is pinned through dependency. The memcg should stop
5233 * applying policies and should revert to the vanilla state as it may be
5234 * made visible again.
5235 *
5236 * The current implementation only resets the essential configurations.
5237 * This needs to be expanded to cover all the visible parts.
5238 */
5239static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5240{
5241 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5242
bbec2e15
RG
5243 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5244 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5245 page_counter_set_max(&memcg->memsw, PAGE_COUNTER_MAX);
5246 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5247 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
bf8d5d52 5248 page_counter_set_min(&memcg->memory, 0);
23067153 5249 page_counter_set_low(&memcg->memory, 0);
241994ed 5250 memcg->high = PAGE_COUNTER_MAX;
24d404dc 5251 memcg->soft_limit = PAGE_COUNTER_MAX;
2529bb3a 5252 memcg_wb_domain_size_changed(memcg);
1ced953b
TH
5253}
5254
02491447 5255#ifdef CONFIG_MMU
7dc74be0 5256/* Handlers for move charge at task migration. */
854ffa8d 5257static int mem_cgroup_do_precharge(unsigned long count)
7dc74be0 5258{
05b84301 5259 int ret;
9476db97 5260
d0164adc
MG
5261 /* Try a single bulk charge without reclaim first, kswapd may wake */
5262 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
9476db97 5263 if (!ret) {
854ffa8d 5264 mc.precharge += count;
854ffa8d
DN
5265 return ret;
5266 }
9476db97 5267
3674534b 5268 /* Try charges one by one with reclaim, but do not retry */
854ffa8d 5269 while (count--) {
3674534b 5270 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
38c5d72f 5271 if (ret)
38c5d72f 5272 return ret;
854ffa8d 5273 mc.precharge++;
9476db97 5274 cond_resched();
854ffa8d 5275 }
9476db97 5276 return 0;
4ffef5fe
DN
5277}
5278
4ffef5fe
DN
5279union mc_target {
5280 struct page *page;
02491447 5281 swp_entry_t ent;
4ffef5fe
DN
5282};
5283
4ffef5fe 5284enum mc_target_type {
8d32ff84 5285 MC_TARGET_NONE = 0,
4ffef5fe 5286 MC_TARGET_PAGE,
02491447 5287 MC_TARGET_SWAP,
c733a828 5288 MC_TARGET_DEVICE,
4ffef5fe
DN
5289};
5290
90254a65
DN
5291static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5292 unsigned long addr, pte_t ptent)
4ffef5fe 5293{
25b2995a 5294 struct page *page = vm_normal_page(vma, addr, ptent);
4ffef5fe 5295
90254a65
DN
5296 if (!page || !page_mapped(page))
5297 return NULL;
5298 if (PageAnon(page)) {
1dfab5ab 5299 if (!(mc.flags & MOVE_ANON))
90254a65 5300 return NULL;
1dfab5ab
JW
5301 } else {
5302 if (!(mc.flags & MOVE_FILE))
5303 return NULL;
5304 }
90254a65
DN
5305 if (!get_page_unless_zero(page))
5306 return NULL;
5307
5308 return page;
5309}
5310
c733a828 5311#if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
90254a65 5312static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
48406ef8 5313 pte_t ptent, swp_entry_t *entry)
90254a65 5314{
90254a65
DN
5315 struct page *page = NULL;
5316 swp_entry_t ent = pte_to_swp_entry(ptent);
5317
1dfab5ab 5318 if (!(mc.flags & MOVE_ANON) || non_swap_entry(ent))
90254a65 5319 return NULL;
c733a828
JG
5320
5321 /*
5322 * Handle MEMORY_DEVICE_PRIVATE which are ZONE_DEVICE page belonging to
5323 * a device and because they are not accessible by CPU they are store
5324 * as special swap entry in the CPU page table.
5325 */
5326 if (is_device_private_entry(ent)) {
5327 page = device_private_entry_to_page(ent);
5328 /*
5329 * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have
5330 * a refcount of 1 when free (unlike normal page)
5331 */
5332 if (!page_ref_add_unless(page, 1, 1))
5333 return NULL;
5334 return page;
5335 }
5336
4b91355e
KH
5337 /*
5338 * Because lookup_swap_cache() updates some statistics counter,
5339 * we call find_get_page() with swapper_space directly.
5340 */
f6ab1f7f 5341 page = find_get_page(swap_address_space(ent), swp_offset(ent));
7941d214 5342 if (do_memsw_account())
90254a65
DN
5343 entry->val = ent.val;
5344
5345 return page;
5346}
4b91355e
KH
5347#else
5348static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
48406ef8 5349 pte_t ptent, swp_entry_t *entry)
4b91355e
KH
5350{
5351 return NULL;
5352}
5353#endif
90254a65 5354
87946a72
DN
5355static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5356 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5357{
5358 struct page *page = NULL;
87946a72
DN
5359 struct address_space *mapping;
5360 pgoff_t pgoff;
5361
5362 if (!vma->vm_file) /* anonymous vma */
5363 return NULL;
1dfab5ab 5364 if (!(mc.flags & MOVE_FILE))
87946a72
DN
5365 return NULL;
5366
87946a72 5367 mapping = vma->vm_file->f_mapping;
0661a336 5368 pgoff = linear_page_index(vma, addr);
87946a72
DN
5369
5370 /* page is moved even if it's not RSS of this task(page-faulted). */
aa3b1895
HD
5371#ifdef CONFIG_SWAP
5372 /* shmem/tmpfs may report page out on swap: account for that too. */
139b6a6f
JW
5373 if (shmem_mapping(mapping)) {
5374 page = find_get_entry(mapping, pgoff);
3159f943 5375 if (xa_is_value(page)) {
139b6a6f 5376 swp_entry_t swp = radix_to_swp_entry(page);
7941d214 5377 if (do_memsw_account())
139b6a6f 5378 *entry = swp;
f6ab1f7f
HY
5379 page = find_get_page(swap_address_space(swp),
5380 swp_offset(swp));
139b6a6f
JW
5381 }
5382 } else
5383 page = find_get_page(mapping, pgoff);
5384#else
5385 page = find_get_page(mapping, pgoff);
aa3b1895 5386#endif
87946a72
DN
5387 return page;
5388}
5389
b1b0deab
CG
5390/**
5391 * mem_cgroup_move_account - move account of the page
5392 * @page: the page
25843c2b 5393 * @compound: charge the page as compound or small page
b1b0deab
CG
5394 * @from: mem_cgroup which the page is moved from.
5395 * @to: mem_cgroup which the page is moved to. @from != @to.
5396 *
3ac808fd 5397 * The caller must make sure the page is not on LRU (isolate_page() is useful.)
b1b0deab
CG
5398 *
5399 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5400 * from old cgroup.
5401 */
5402static int mem_cgroup_move_account(struct page *page,
f627c2f5 5403 bool compound,
b1b0deab
CG
5404 struct mem_cgroup *from,
5405 struct mem_cgroup *to)
5406{
5407 unsigned long flags;
f627c2f5 5408 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
b1b0deab 5409 int ret;
c4843a75 5410 bool anon;
b1b0deab
CG
5411
5412 VM_BUG_ON(from == to);
5413 VM_BUG_ON_PAGE(PageLRU(page), page);
f627c2f5 5414 VM_BUG_ON(compound && !PageTransHuge(page));
b1b0deab
CG
5415
5416 /*
6a93ca8f 5417 * Prevent mem_cgroup_migrate() from looking at
45637bab 5418 * page->mem_cgroup of its source page while we change it.
b1b0deab 5419 */
f627c2f5 5420 ret = -EBUSY;
b1b0deab
CG
5421 if (!trylock_page(page))
5422 goto out;
5423
5424 ret = -EINVAL;
5425 if (page->mem_cgroup != from)
5426 goto out_unlock;
5427
c4843a75
GT
5428 anon = PageAnon(page);
5429
b1b0deab
CG
5430 spin_lock_irqsave(&from->move_lock, flags);
5431
c4843a75 5432 if (!anon && page_mapped(page)) {
c9019e9b
JW
5433 __mod_memcg_state(from, NR_FILE_MAPPED, -nr_pages);
5434 __mod_memcg_state(to, NR_FILE_MAPPED, nr_pages);
b1b0deab
CG
5435 }
5436
c4843a75
GT
5437 /*
5438 * move_lock grabbed above and caller set from->moving_account, so
ccda7f43 5439 * mod_memcg_page_state will serialize updates to PageDirty.
c4843a75
GT
5440 * So mapping should be stable for dirty pages.
5441 */
5442 if (!anon && PageDirty(page)) {
5443 struct address_space *mapping = page_mapping(page);
5444
5445 if (mapping_cap_account_dirty(mapping)) {
c9019e9b
JW
5446 __mod_memcg_state(from, NR_FILE_DIRTY, -nr_pages);
5447 __mod_memcg_state(to, NR_FILE_DIRTY, nr_pages);
c4843a75
GT
5448 }
5449 }
5450
b1b0deab 5451 if (PageWriteback(page)) {
c9019e9b
JW
5452 __mod_memcg_state(from, NR_WRITEBACK, -nr_pages);
5453 __mod_memcg_state(to, NR_WRITEBACK, nr_pages);
b1b0deab
CG
5454 }
5455
5456 /*
5457 * It is safe to change page->mem_cgroup here because the page
5458 * is referenced, charged, and isolated - we can't race with
5459 * uncharging, charging, migration, or LRU putback.
5460 */
5461
5462 /* caller should have done css_get */
5463 page->mem_cgroup = to;
5464 spin_unlock_irqrestore(&from->move_lock, flags);
5465
5466 ret = 0;
5467
5468 local_irq_disable();
f627c2f5 5469 mem_cgroup_charge_statistics(to, page, compound, nr_pages);
b1b0deab 5470 memcg_check_events(to, page);
f627c2f5 5471 mem_cgroup_charge_statistics(from, page, compound, -nr_pages);
b1b0deab
CG
5472 memcg_check_events(from, page);
5473 local_irq_enable();
5474out_unlock:
5475 unlock_page(page);
5476out:
5477 return ret;
5478}
5479
7cf7806c
LR
5480/**
5481 * get_mctgt_type - get target type of moving charge
5482 * @vma: the vma the pte to be checked belongs
5483 * @addr: the address corresponding to the pte to be checked
5484 * @ptent: the pte to be checked
5485 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5486 *
5487 * Returns
5488 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5489 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5490 * move charge. if @target is not NULL, the page is stored in target->page
5491 * with extra refcnt got(Callers should handle it).
5492 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5493 * target for charge migration. if @target is not NULL, the entry is stored
5494 * in target->ent.
25b2995a
CH
5495 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is MEMORY_DEVICE_PRIVATE
5496 * (so ZONE_DEVICE page and thus not on the lru).
df6ad698
JG
5497 * For now we such page is charge like a regular page would be as for all
5498 * intent and purposes it is just special memory taking the place of a
5499 * regular page.
c733a828
JG
5500 *
5501 * See Documentations/vm/hmm.txt and include/linux/hmm.h
7cf7806c
LR
5502 *
5503 * Called with pte lock held.
5504 */
5505
8d32ff84 5506static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
90254a65
DN
5507 unsigned long addr, pte_t ptent, union mc_target *target)
5508{
5509 struct page *page = NULL;
8d32ff84 5510 enum mc_target_type ret = MC_TARGET_NONE;
90254a65
DN
5511 swp_entry_t ent = { .val = 0 };
5512
5513 if (pte_present(ptent))
5514 page = mc_handle_present_pte(vma, addr, ptent);
5515 else if (is_swap_pte(ptent))
48406ef8 5516 page = mc_handle_swap_pte(vma, ptent, &ent);
0661a336 5517 else if (pte_none(ptent))
87946a72 5518 page = mc_handle_file_pte(vma, addr, ptent, &ent);
90254a65
DN
5519
5520 if (!page && !ent.val)
8d32ff84 5521 return ret;
02491447 5522 if (page) {
02491447 5523 /*
0a31bc97 5524 * Do only loose check w/o serialization.
1306a85a 5525 * mem_cgroup_move_account() checks the page is valid or
0a31bc97 5526 * not under LRU exclusion.
02491447 5527 */
1306a85a 5528 if (page->mem_cgroup == mc.from) {
02491447 5529 ret = MC_TARGET_PAGE;
25b2995a 5530 if (is_device_private_page(page))
c733a828 5531 ret = MC_TARGET_DEVICE;
02491447
DN
5532 if (target)
5533 target->page = page;
5534 }
5535 if (!ret || !target)
5536 put_page(page);
5537 }
3e14a57b
HY
5538 /*
5539 * There is a swap entry and a page doesn't exist or isn't charged.
5540 * But we cannot move a tail-page in a THP.
5541 */
5542 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
34c00c31 5543 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
7f0f1546
KH
5544 ret = MC_TARGET_SWAP;
5545 if (target)
5546 target->ent = ent;
4ffef5fe 5547 }
4ffef5fe
DN
5548 return ret;
5549}
5550
12724850
NH
5551#ifdef CONFIG_TRANSPARENT_HUGEPAGE
5552/*
d6810d73
HY
5553 * We don't consider PMD mapped swapping or file mapped pages because THP does
5554 * not support them for now.
12724850
NH
5555 * Caller should make sure that pmd_trans_huge(pmd) is true.
5556 */
5557static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5558 unsigned long addr, pmd_t pmd, union mc_target *target)
5559{
5560 struct page *page = NULL;
12724850
NH
5561 enum mc_target_type ret = MC_TARGET_NONE;
5562
84c3fc4e
ZY
5563 if (unlikely(is_swap_pmd(pmd))) {
5564 VM_BUG_ON(thp_migration_supported() &&
5565 !is_pmd_migration_entry(pmd));
5566 return ret;
5567 }
12724850 5568 page = pmd_page(pmd);
309381fe 5569 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
1dfab5ab 5570 if (!(mc.flags & MOVE_ANON))
12724850 5571 return ret;
1306a85a 5572 if (page->mem_cgroup == mc.from) {
12724850
NH
5573 ret = MC_TARGET_PAGE;
5574 if (target) {
5575 get_page(page);
5576 target->page = page;
5577 }
5578 }
5579 return ret;
5580}
5581#else
5582static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5583 unsigned long addr, pmd_t pmd, union mc_target *target)
5584{
5585 return MC_TARGET_NONE;
5586}
5587#endif
5588
4ffef5fe
DN
5589static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5590 unsigned long addr, unsigned long end,
5591 struct mm_walk *walk)
5592{
26bcd64a 5593 struct vm_area_struct *vma = walk->vma;
4ffef5fe
DN
5594 pte_t *pte;
5595 spinlock_t *ptl;
5596
b6ec57f4
KS
5597 ptl = pmd_trans_huge_lock(pmd, vma);
5598 if (ptl) {
c733a828
JG
5599 /*
5600 * Note their can not be MC_TARGET_DEVICE for now as we do not
25b2995a
CH
5601 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5602 * this might change.
c733a828 5603 */
12724850
NH
5604 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5605 mc.precharge += HPAGE_PMD_NR;
bf929152 5606 spin_unlock(ptl);
1a5a9906 5607 return 0;
12724850 5608 }
03319327 5609
45f83cef
AA
5610 if (pmd_trans_unstable(pmd))
5611 return 0;
4ffef5fe
DN
5612 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5613 for (; addr != end; pte++, addr += PAGE_SIZE)
8d32ff84 5614 if (get_mctgt_type(vma, addr, *pte, NULL))
4ffef5fe
DN
5615 mc.precharge++; /* increment precharge temporarily */
5616 pte_unmap_unlock(pte - 1, ptl);
5617 cond_resched();
5618
7dc74be0
DN
5619 return 0;
5620}
5621
7b86ac33
CH
5622static const struct mm_walk_ops precharge_walk_ops = {
5623 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5624};
5625
4ffef5fe
DN
5626static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5627{
5628 unsigned long precharge;
4ffef5fe 5629
dfe076b0 5630 down_read(&mm->mmap_sem);
7b86ac33 5631 walk_page_range(mm, 0, mm->highest_vm_end, &precharge_walk_ops, NULL);
dfe076b0 5632 up_read(&mm->mmap_sem);
4ffef5fe
DN
5633
5634 precharge = mc.precharge;
5635 mc.precharge = 0;
5636
5637 return precharge;
5638}
5639
4ffef5fe
DN
5640static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5641{
dfe076b0
DN
5642 unsigned long precharge = mem_cgroup_count_precharge(mm);
5643
5644 VM_BUG_ON(mc.moving_task);
5645 mc.moving_task = current;
5646 return mem_cgroup_do_precharge(precharge);
4ffef5fe
DN
5647}
5648
dfe076b0
DN
5649/* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5650static void __mem_cgroup_clear_mc(void)
4ffef5fe 5651{
2bd9bb20
KH
5652 struct mem_cgroup *from = mc.from;
5653 struct mem_cgroup *to = mc.to;
5654
4ffef5fe 5655 /* we must uncharge all the leftover precharges from mc.to */
854ffa8d 5656 if (mc.precharge) {
00501b53 5657 cancel_charge(mc.to, mc.precharge);
854ffa8d
DN
5658 mc.precharge = 0;
5659 }
5660 /*
5661 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5662 * we must uncharge here.
5663 */
5664 if (mc.moved_charge) {
00501b53 5665 cancel_charge(mc.from, mc.moved_charge);
854ffa8d 5666 mc.moved_charge = 0;
4ffef5fe 5667 }
483c30b5
DN
5668 /* we must fixup refcnts and charges */
5669 if (mc.moved_swap) {
483c30b5 5670 /* uncharge swap account from the old cgroup */
ce00a967 5671 if (!mem_cgroup_is_root(mc.from))
3e32cb2e 5672 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
483c30b5 5673
615d66c3
VD
5674 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
5675
05b84301 5676 /*
3e32cb2e
JW
5677 * we charged both to->memory and to->memsw, so we
5678 * should uncharge to->memory.
05b84301 5679 */
ce00a967 5680 if (!mem_cgroup_is_root(mc.to))
3e32cb2e
JW
5681 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
5682
615d66c3
VD
5683 mem_cgroup_id_get_many(mc.to, mc.moved_swap);
5684 css_put_many(&mc.to->css, mc.moved_swap);
3e32cb2e 5685
483c30b5
DN
5686 mc.moved_swap = 0;
5687 }
dfe076b0
DN
5688 memcg_oom_recover(from);
5689 memcg_oom_recover(to);
5690 wake_up_all(&mc.waitq);
5691}
5692
5693static void mem_cgroup_clear_mc(void)
5694{
264a0ae1
TH
5695 struct mm_struct *mm = mc.mm;
5696
dfe076b0
DN
5697 /*
5698 * we must clear moving_task before waking up waiters at the end of
5699 * task migration.
5700 */
5701 mc.moving_task = NULL;
5702 __mem_cgroup_clear_mc();
2bd9bb20 5703 spin_lock(&mc.lock);
4ffef5fe
DN
5704 mc.from = NULL;
5705 mc.to = NULL;
264a0ae1 5706 mc.mm = NULL;
2bd9bb20 5707 spin_unlock(&mc.lock);
264a0ae1
TH
5708
5709 mmput(mm);
4ffef5fe
DN
5710}
5711
1f7dd3e5 5712static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
7dc74be0 5713{
1f7dd3e5 5714 struct cgroup_subsys_state *css;
eed67d75 5715 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
9f2115f9 5716 struct mem_cgroup *from;
4530eddb 5717 struct task_struct *leader, *p;
9f2115f9 5718 struct mm_struct *mm;
1dfab5ab 5719 unsigned long move_flags;
9f2115f9 5720 int ret = 0;
7dc74be0 5721
1f7dd3e5
TH
5722 /* charge immigration isn't supported on the default hierarchy */
5723 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
9f2115f9
TH
5724 return 0;
5725
4530eddb
TH
5726 /*
5727 * Multi-process migrations only happen on the default hierarchy
5728 * where charge immigration is not used. Perform charge
5729 * immigration if @tset contains a leader and whine if there are
5730 * multiple.
5731 */
5732 p = NULL;
1f7dd3e5 5733 cgroup_taskset_for_each_leader(leader, css, tset) {
4530eddb
TH
5734 WARN_ON_ONCE(p);
5735 p = leader;
1f7dd3e5 5736 memcg = mem_cgroup_from_css(css);
4530eddb
TH
5737 }
5738 if (!p)
5739 return 0;
5740
1f7dd3e5
TH
5741 /*
5742 * We are now commited to this value whatever it is. Changes in this
5743 * tunable will only affect upcoming migrations, not the current one.
5744 * So we need to save it, and keep it going.
5745 */
5746 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
5747 if (!move_flags)
5748 return 0;
5749
9f2115f9
TH
5750 from = mem_cgroup_from_task(p);
5751
5752 VM_BUG_ON(from == memcg);
5753
5754 mm = get_task_mm(p);
5755 if (!mm)
5756 return 0;
5757 /* We move charges only when we move a owner of the mm */
5758 if (mm->owner == p) {
5759 VM_BUG_ON(mc.from);
5760 VM_BUG_ON(mc.to);
5761 VM_BUG_ON(mc.precharge);
5762 VM_BUG_ON(mc.moved_charge);
5763 VM_BUG_ON(mc.moved_swap);
5764
5765 spin_lock(&mc.lock);
264a0ae1 5766 mc.mm = mm;
9f2115f9
TH
5767 mc.from = from;
5768 mc.to = memcg;
5769 mc.flags = move_flags;
5770 spin_unlock(&mc.lock);
5771 /* We set mc.moving_task later */
5772
5773 ret = mem_cgroup_precharge_mc(mm);
5774 if (ret)
5775 mem_cgroup_clear_mc();
264a0ae1
TH
5776 } else {
5777 mmput(mm);
7dc74be0
DN
5778 }
5779 return ret;
5780}
5781
1f7dd3e5 5782static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
7dc74be0 5783{
4e2f245d
JW
5784 if (mc.to)
5785 mem_cgroup_clear_mc();
7dc74be0
DN
5786}
5787
4ffef5fe
DN
5788static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5789 unsigned long addr, unsigned long end,
5790 struct mm_walk *walk)
7dc74be0 5791{
4ffef5fe 5792 int ret = 0;
26bcd64a 5793 struct vm_area_struct *vma = walk->vma;
4ffef5fe
DN
5794 pte_t *pte;
5795 spinlock_t *ptl;
12724850
NH
5796 enum mc_target_type target_type;
5797 union mc_target target;
5798 struct page *page;
4ffef5fe 5799
b6ec57f4
KS
5800 ptl = pmd_trans_huge_lock(pmd, vma);
5801 if (ptl) {
62ade86a 5802 if (mc.precharge < HPAGE_PMD_NR) {
bf929152 5803 spin_unlock(ptl);
12724850
NH
5804 return 0;
5805 }
5806 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
5807 if (target_type == MC_TARGET_PAGE) {
5808 page = target.page;
5809 if (!isolate_lru_page(page)) {
f627c2f5 5810 if (!mem_cgroup_move_account(page, true,
1306a85a 5811 mc.from, mc.to)) {
12724850
NH
5812 mc.precharge -= HPAGE_PMD_NR;
5813 mc.moved_charge += HPAGE_PMD_NR;
5814 }
5815 putback_lru_page(page);
5816 }
5817 put_page(page);
c733a828
JG
5818 } else if (target_type == MC_TARGET_DEVICE) {
5819 page = target.page;
5820 if (!mem_cgroup_move_account(page, true,
5821 mc.from, mc.to)) {
5822 mc.precharge -= HPAGE_PMD_NR;
5823 mc.moved_charge += HPAGE_PMD_NR;
5824 }
5825 put_page(page);
12724850 5826 }
bf929152 5827 spin_unlock(ptl);
1a5a9906 5828 return 0;
12724850
NH
5829 }
5830
45f83cef
AA
5831 if (pmd_trans_unstable(pmd))
5832 return 0;
4ffef5fe
DN
5833retry:
5834 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5835 for (; addr != end; addr += PAGE_SIZE) {
5836 pte_t ptent = *(pte++);
c733a828 5837 bool device = false;
02491447 5838 swp_entry_t ent;
4ffef5fe
DN
5839
5840 if (!mc.precharge)
5841 break;
5842
8d32ff84 5843 switch (get_mctgt_type(vma, addr, ptent, &target)) {
c733a828
JG
5844 case MC_TARGET_DEVICE:
5845 device = true;
5846 /* fall through */
4ffef5fe
DN
5847 case MC_TARGET_PAGE:
5848 page = target.page;
53f9263b
KS
5849 /*
5850 * We can have a part of the split pmd here. Moving it
5851 * can be done but it would be too convoluted so simply
5852 * ignore such a partial THP and keep it in original
5853 * memcg. There should be somebody mapping the head.
5854 */
5855 if (PageTransCompound(page))
5856 goto put;
c733a828 5857 if (!device && isolate_lru_page(page))
4ffef5fe 5858 goto put;
f627c2f5
KS
5859 if (!mem_cgroup_move_account(page, false,
5860 mc.from, mc.to)) {
4ffef5fe 5861 mc.precharge--;
854ffa8d
DN
5862 /* we uncharge from mc.from later. */
5863 mc.moved_charge++;
4ffef5fe 5864 }
c733a828
JG
5865 if (!device)
5866 putback_lru_page(page);
8d32ff84 5867put: /* get_mctgt_type() gets the page */
4ffef5fe
DN
5868 put_page(page);
5869 break;
02491447
DN
5870 case MC_TARGET_SWAP:
5871 ent = target.ent;
e91cbb42 5872 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
02491447 5873 mc.precharge--;
483c30b5
DN
5874 /* we fixup refcnts and charges later. */
5875 mc.moved_swap++;
5876 }
02491447 5877 break;
4ffef5fe
DN
5878 default:
5879 break;
5880 }
5881 }
5882 pte_unmap_unlock(pte - 1, ptl);
5883 cond_resched();
5884
5885 if (addr != end) {
5886 /*
5887 * We have consumed all precharges we got in can_attach().
5888 * We try charge one by one, but don't do any additional
5889 * charges to mc.to if we have failed in charge once in attach()
5890 * phase.
5891 */
854ffa8d 5892 ret = mem_cgroup_do_precharge(1);
4ffef5fe
DN
5893 if (!ret)
5894 goto retry;
5895 }
5896
5897 return ret;
5898}
5899
7b86ac33
CH
5900static const struct mm_walk_ops charge_walk_ops = {
5901 .pmd_entry = mem_cgroup_move_charge_pte_range,
5902};
5903
264a0ae1 5904static void mem_cgroup_move_charge(void)
4ffef5fe 5905{
4ffef5fe 5906 lru_add_drain_all();
312722cb 5907 /*
81f8c3a4
JW
5908 * Signal lock_page_memcg() to take the memcg's move_lock
5909 * while we're moving its pages to another memcg. Then wait
5910 * for already started RCU-only updates to finish.
312722cb
JW
5911 */
5912 atomic_inc(&mc.from->moving_account);
5913 synchronize_rcu();
dfe076b0 5914retry:
264a0ae1 5915 if (unlikely(!down_read_trylock(&mc.mm->mmap_sem))) {
dfe076b0
DN
5916 /*
5917 * Someone who are holding the mmap_sem might be waiting in
5918 * waitq. So we cancel all extra charges, wake up all waiters,
5919 * and retry. Because we cancel precharges, we might not be able
5920 * to move enough charges, but moving charge is a best-effort
5921 * feature anyway, so it wouldn't be a big problem.
5922 */
5923 __mem_cgroup_clear_mc();
5924 cond_resched();
5925 goto retry;
5926 }
26bcd64a
NH
5927 /*
5928 * When we have consumed all precharges and failed in doing
5929 * additional charge, the page walk just aborts.
5930 */
7b86ac33
CH
5931 walk_page_range(mc.mm, 0, mc.mm->highest_vm_end, &charge_walk_ops,
5932 NULL);
0247f3f4 5933
264a0ae1 5934 up_read(&mc.mm->mmap_sem);
312722cb 5935 atomic_dec(&mc.from->moving_account);
7dc74be0
DN
5936}
5937
264a0ae1 5938static void mem_cgroup_move_task(void)
67e465a7 5939{
264a0ae1
TH
5940 if (mc.to) {
5941 mem_cgroup_move_charge();
a433658c 5942 mem_cgroup_clear_mc();
264a0ae1 5943 }
67e465a7 5944}
5cfb80a7 5945#else /* !CONFIG_MMU */
1f7dd3e5 5946static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5cfb80a7
DN
5947{
5948 return 0;
5949}
1f7dd3e5 5950static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
5cfb80a7
DN
5951{
5952}
264a0ae1 5953static void mem_cgroup_move_task(void)
5cfb80a7
DN
5954{
5955}
5956#endif
67e465a7 5957
f00baae7
TH
5958/*
5959 * Cgroup retains root cgroups across [un]mount cycles making it necessary
aa6ec29b
TH
5960 * to verify whether we're attached to the default hierarchy on each mount
5961 * attempt.
f00baae7 5962 */
eb95419b 5963static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
f00baae7
TH
5964{
5965 /*
aa6ec29b 5966 * use_hierarchy is forced on the default hierarchy. cgroup core
f00baae7
TH
5967 * guarantees that @root doesn't have any children, so turning it
5968 * on for the root memcg is enough.
5969 */
9e10a130 5970 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7feee590
VD
5971 root_mem_cgroup->use_hierarchy = true;
5972 else
5973 root_mem_cgroup->use_hierarchy = false;
f00baae7
TH
5974}
5975
677dc973
CD
5976static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
5977{
5978 if (value == PAGE_COUNTER_MAX)
5979 seq_puts(m, "max\n");
5980 else
5981 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
5982
5983 return 0;
5984}
5985
241994ed
JW
5986static u64 memory_current_read(struct cgroup_subsys_state *css,
5987 struct cftype *cft)
5988{
f5fc3c5d
JW
5989 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5990
5991 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
241994ed
JW
5992}
5993
bf8d5d52
RG
5994static int memory_min_show(struct seq_file *m, void *v)
5995{
677dc973
CD
5996 return seq_puts_memcg_tunable(m,
5997 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
bf8d5d52
RG
5998}
5999
6000static ssize_t memory_min_write(struct kernfs_open_file *of,
6001 char *buf, size_t nbytes, loff_t off)
6002{
6003 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6004 unsigned long min;
6005 int err;
6006
6007 buf = strstrip(buf);
6008 err = page_counter_memparse(buf, "max", &min);
6009 if (err)
6010 return err;
6011
6012 page_counter_set_min(&memcg->memory, min);
6013
6014 return nbytes;
6015}
6016
241994ed
JW
6017static int memory_low_show(struct seq_file *m, void *v)
6018{
677dc973
CD
6019 return seq_puts_memcg_tunable(m,
6020 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
241994ed
JW
6021}
6022
6023static ssize_t memory_low_write(struct kernfs_open_file *of,
6024 char *buf, size_t nbytes, loff_t off)
6025{
6026 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6027 unsigned long low;
6028 int err;
6029
6030 buf = strstrip(buf);
d2973697 6031 err = page_counter_memparse(buf, "max", &low);
241994ed
JW
6032 if (err)
6033 return err;
6034
23067153 6035 page_counter_set_low(&memcg->memory, low);
241994ed
JW
6036
6037 return nbytes;
6038}
6039
6040static int memory_high_show(struct seq_file *m, void *v)
6041{
677dc973 6042 return seq_puts_memcg_tunable(m, READ_ONCE(mem_cgroup_from_seq(m)->high));
241994ed
JW
6043}
6044
6045static ssize_t memory_high_write(struct kernfs_open_file *of,
6046 char *buf, size_t nbytes, loff_t off)
6047{
6048 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
588083bb 6049 unsigned long nr_pages;
241994ed
JW
6050 unsigned long high;
6051 int err;
6052
6053 buf = strstrip(buf);
d2973697 6054 err = page_counter_memparse(buf, "max", &high);
241994ed
JW
6055 if (err)
6056 return err;
6057
6058 memcg->high = high;
6059
588083bb
JW
6060 nr_pages = page_counter_read(&memcg->memory);
6061 if (nr_pages > high)
6062 try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6063 GFP_KERNEL, true);
6064
2529bb3a 6065 memcg_wb_domain_size_changed(memcg);
241994ed
JW
6066 return nbytes;
6067}
6068
6069static int memory_max_show(struct seq_file *m, void *v)
6070{
677dc973
CD
6071 return seq_puts_memcg_tunable(m,
6072 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
241994ed
JW
6073}
6074
6075static ssize_t memory_max_write(struct kernfs_open_file *of,
6076 char *buf, size_t nbytes, loff_t off)
6077{
6078 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
b6e6edcf
JW
6079 unsigned int nr_reclaims = MEM_CGROUP_RECLAIM_RETRIES;
6080 bool drained = false;
241994ed
JW
6081 unsigned long max;
6082 int err;
6083
6084 buf = strstrip(buf);
d2973697 6085 err = page_counter_memparse(buf, "max", &max);
241994ed
JW
6086 if (err)
6087 return err;
6088
bbec2e15 6089 xchg(&memcg->memory.max, max);
b6e6edcf
JW
6090
6091 for (;;) {
6092 unsigned long nr_pages = page_counter_read(&memcg->memory);
6093
6094 if (nr_pages <= max)
6095 break;
6096
6097 if (signal_pending(current)) {
6098 err = -EINTR;
6099 break;
6100 }
6101
6102 if (!drained) {
6103 drain_all_stock(memcg);
6104 drained = true;
6105 continue;
6106 }
6107
6108 if (nr_reclaims) {
6109 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6110 GFP_KERNEL, true))
6111 nr_reclaims--;
6112 continue;
6113 }
6114
e27be240 6115 memcg_memory_event(memcg, MEMCG_OOM);
b6e6edcf
JW
6116 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6117 break;
6118 }
241994ed 6119
2529bb3a 6120 memcg_wb_domain_size_changed(memcg);
241994ed
JW
6121 return nbytes;
6122}
6123
1e577f97
SB
6124static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6125{
6126 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6127 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6128 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6129 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6130 seq_printf(m, "oom_kill %lu\n",
6131 atomic_long_read(&events[MEMCG_OOM_KILL]));
6132}
6133
241994ed
JW
6134static int memory_events_show(struct seq_file *m, void *v)
6135{
aa9694bb 6136 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
241994ed 6137
1e577f97
SB
6138 __memory_events_show(m, memcg->memory_events);
6139 return 0;
6140}
6141
6142static int memory_events_local_show(struct seq_file *m, void *v)
6143{
6144 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
241994ed 6145
1e577f97 6146 __memory_events_show(m, memcg->memory_events_local);
241994ed
JW
6147 return 0;
6148}
6149
587d9f72
JW
6150static int memory_stat_show(struct seq_file *m, void *v)
6151{
aa9694bb 6152 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
c8713d0b 6153 char *buf;
1ff9e6e1 6154
c8713d0b
JW
6155 buf = memory_stat_format(memcg);
6156 if (!buf)
6157 return -ENOMEM;
6158 seq_puts(m, buf);
6159 kfree(buf);
587d9f72
JW
6160 return 0;
6161}
6162
3d8b38eb
RG
6163static int memory_oom_group_show(struct seq_file *m, void *v)
6164{
aa9694bb 6165 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3d8b38eb
RG
6166
6167 seq_printf(m, "%d\n", memcg->oom_group);
6168
6169 return 0;
6170}
6171
6172static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6173 char *buf, size_t nbytes, loff_t off)
6174{
6175 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6176 int ret, oom_group;
6177
6178 buf = strstrip(buf);
6179 if (!buf)
6180 return -EINVAL;
6181
6182 ret = kstrtoint(buf, 0, &oom_group);
6183 if (ret)
6184 return ret;
6185
6186 if (oom_group != 0 && oom_group != 1)
6187 return -EINVAL;
6188
6189 memcg->oom_group = oom_group;
6190
6191 return nbytes;
6192}
6193
241994ed
JW
6194static struct cftype memory_files[] = {
6195 {
6196 .name = "current",
f5fc3c5d 6197 .flags = CFTYPE_NOT_ON_ROOT,
241994ed
JW
6198 .read_u64 = memory_current_read,
6199 },
bf8d5d52
RG
6200 {
6201 .name = "min",
6202 .flags = CFTYPE_NOT_ON_ROOT,
6203 .seq_show = memory_min_show,
6204 .write = memory_min_write,
6205 },
241994ed
JW
6206 {
6207 .name = "low",
6208 .flags = CFTYPE_NOT_ON_ROOT,
6209 .seq_show = memory_low_show,
6210 .write = memory_low_write,
6211 },
6212 {
6213 .name = "high",
6214 .flags = CFTYPE_NOT_ON_ROOT,
6215 .seq_show = memory_high_show,
6216 .write = memory_high_write,
6217 },
6218 {
6219 .name = "max",
6220 .flags = CFTYPE_NOT_ON_ROOT,
6221 .seq_show = memory_max_show,
6222 .write = memory_max_write,
6223 },
6224 {
6225 .name = "events",
6226 .flags = CFTYPE_NOT_ON_ROOT,
472912a2 6227 .file_offset = offsetof(struct mem_cgroup, events_file),
241994ed
JW
6228 .seq_show = memory_events_show,
6229 },
1e577f97
SB
6230 {
6231 .name = "events.local",
6232 .flags = CFTYPE_NOT_ON_ROOT,
6233 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6234 .seq_show = memory_events_local_show,
6235 },
587d9f72
JW
6236 {
6237 .name = "stat",
6238 .flags = CFTYPE_NOT_ON_ROOT,
6239 .seq_show = memory_stat_show,
6240 },
3d8b38eb
RG
6241 {
6242 .name = "oom.group",
6243 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6244 .seq_show = memory_oom_group_show,
6245 .write = memory_oom_group_write,
6246 },
241994ed
JW
6247 { } /* terminate */
6248};
6249
073219e9 6250struct cgroup_subsys memory_cgrp_subsys = {
92fb9748 6251 .css_alloc = mem_cgroup_css_alloc,
d142e3e6 6252 .css_online = mem_cgroup_css_online,
92fb9748 6253 .css_offline = mem_cgroup_css_offline,
6df38689 6254 .css_released = mem_cgroup_css_released,
92fb9748 6255 .css_free = mem_cgroup_css_free,
1ced953b 6256 .css_reset = mem_cgroup_css_reset,
7dc74be0
DN
6257 .can_attach = mem_cgroup_can_attach,
6258 .cancel_attach = mem_cgroup_cancel_attach,
264a0ae1 6259 .post_attach = mem_cgroup_move_task,
f00baae7 6260 .bind = mem_cgroup_bind,
241994ed
JW
6261 .dfl_cftypes = memory_files,
6262 .legacy_cftypes = mem_cgroup_legacy_files,
6d12e2d8 6263 .early_init = 0,
8cdea7c0 6264};
c077719b 6265
241994ed 6266/**
bf8d5d52 6267 * mem_cgroup_protected - check if memory consumption is in the normal range
34c81057 6268 * @root: the top ancestor of the sub-tree being checked
241994ed
JW
6269 * @memcg: the memory cgroup to check
6270 *
23067153
RG
6271 * WARNING: This function is not stateless! It can only be used as part
6272 * of a top-down tree iteration, not for isolated queries.
34c81057 6273 *
bf8d5d52
RG
6274 * Returns one of the following:
6275 * MEMCG_PROT_NONE: cgroup memory is not protected
6276 * MEMCG_PROT_LOW: cgroup memory is protected as long there is
6277 * an unprotected supply of reclaimable memory from other cgroups.
6278 * MEMCG_PROT_MIN: cgroup memory is protected
34c81057 6279 *
bf8d5d52 6280 * @root is exclusive; it is never protected when looked at directly
34c81057 6281 *
bf8d5d52
RG
6282 * To provide a proper hierarchical behavior, effective memory.min/low values
6283 * are used. Below is the description of how effective memory.low is calculated.
6284 * Effective memory.min values is calculated in the same way.
34c81057 6285 *
23067153
RG
6286 * Effective memory.low is always equal or less than the original memory.low.
6287 * If there is no memory.low overcommittment (which is always true for
6288 * top-level memory cgroups), these two values are equal.
6289 * Otherwise, it's a part of parent's effective memory.low,
6290 * calculated as a cgroup's memory.low usage divided by sum of sibling's
6291 * memory.low usages, where memory.low usage is the size of actually
6292 * protected memory.
34c81057 6293 *
23067153
RG
6294 * low_usage
6295 * elow = min( memory.low, parent->elow * ------------------ ),
6296 * siblings_low_usage
34c81057 6297 *
23067153
RG
6298 * | memory.current, if memory.current < memory.low
6299 * low_usage = |
82ede7ee 6300 * | 0, otherwise.
34c81057 6301 *
23067153
RG
6302 *
6303 * Such definition of the effective memory.low provides the expected
6304 * hierarchical behavior: parent's memory.low value is limiting
6305 * children, unprotected memory is reclaimed first and cgroups,
6306 * which are not using their guarantee do not affect actual memory
6307 * distribution.
6308 *
6309 * For example, if there are memcgs A, A/B, A/C, A/D and A/E:
6310 *
6311 * A A/memory.low = 2G, A/memory.current = 6G
6312 * //\\
6313 * BC DE B/memory.low = 3G B/memory.current = 2G
6314 * C/memory.low = 1G C/memory.current = 2G
6315 * D/memory.low = 0 D/memory.current = 2G
6316 * E/memory.low = 10G E/memory.current = 0
6317 *
6318 * and the memory pressure is applied, the following memory distribution
6319 * is expected (approximately):
6320 *
6321 * A/memory.current = 2G
6322 *
6323 * B/memory.current = 1.3G
6324 * C/memory.current = 0.6G
6325 * D/memory.current = 0
6326 * E/memory.current = 0
6327 *
6328 * These calculations require constant tracking of the actual low usages
bf8d5d52
RG
6329 * (see propagate_protected_usage()), as well as recursive calculation of
6330 * effective memory.low values. But as we do call mem_cgroup_protected()
23067153
RG
6331 * path for each memory cgroup top-down from the reclaim,
6332 * it's possible to optimize this part, and save calculated elow
6333 * for next usage. This part is intentionally racy, but it's ok,
6334 * as memory.low is a best-effort mechanism.
241994ed 6335 */
bf8d5d52
RG
6336enum mem_cgroup_protection mem_cgroup_protected(struct mem_cgroup *root,
6337 struct mem_cgroup *memcg)
241994ed 6338{
23067153 6339 struct mem_cgroup *parent;
bf8d5d52
RG
6340 unsigned long emin, parent_emin;
6341 unsigned long elow, parent_elow;
6342 unsigned long usage;
23067153 6343
241994ed 6344 if (mem_cgroup_disabled())
bf8d5d52 6345 return MEMCG_PROT_NONE;
241994ed 6346
34c81057
SC
6347 if (!root)
6348 root = root_mem_cgroup;
6349 if (memcg == root)
bf8d5d52 6350 return MEMCG_PROT_NONE;
241994ed 6351
23067153 6352 usage = page_counter_read(&memcg->memory);
bf8d5d52
RG
6353 if (!usage)
6354 return MEMCG_PROT_NONE;
6355
6356 emin = memcg->memory.min;
6357 elow = memcg->memory.low;
34c81057 6358
bf8d5d52 6359 parent = parent_mem_cgroup(memcg);
df2a4196
RG
6360 /* No parent means a non-hierarchical mode on v1 memcg */
6361 if (!parent)
6362 return MEMCG_PROT_NONE;
6363
23067153
RG
6364 if (parent == root)
6365 goto exit;
6366
bf8d5d52
RG
6367 parent_emin = READ_ONCE(parent->memory.emin);
6368 emin = min(emin, parent_emin);
6369 if (emin && parent_emin) {
6370 unsigned long min_usage, siblings_min_usage;
6371
6372 min_usage = min(usage, memcg->memory.min);
6373 siblings_min_usage = atomic_long_read(
6374 &parent->memory.children_min_usage);
6375
6376 if (min_usage && siblings_min_usage)
6377 emin = min(emin, parent_emin * min_usage /
6378 siblings_min_usage);
6379 }
6380
23067153
RG
6381 parent_elow = READ_ONCE(parent->memory.elow);
6382 elow = min(elow, parent_elow);
bf8d5d52
RG
6383 if (elow && parent_elow) {
6384 unsigned long low_usage, siblings_low_usage;
23067153 6385
bf8d5d52
RG
6386 low_usage = min(usage, memcg->memory.low);
6387 siblings_low_usage = atomic_long_read(
6388 &parent->memory.children_low_usage);
23067153 6389
bf8d5d52
RG
6390 if (low_usage && siblings_low_usage)
6391 elow = min(elow, parent_elow * low_usage /
6392 siblings_low_usage);
6393 }
23067153 6394
23067153 6395exit:
bf8d5d52 6396 memcg->memory.emin = emin;
23067153 6397 memcg->memory.elow = elow;
bf8d5d52
RG
6398
6399 if (usage <= emin)
6400 return MEMCG_PROT_MIN;
6401 else if (usage <= elow)
6402 return MEMCG_PROT_LOW;
6403 else
6404 return MEMCG_PROT_NONE;
241994ed
JW
6405}
6406
00501b53
JW
6407/**
6408 * mem_cgroup_try_charge - try charging a page
6409 * @page: page to charge
6410 * @mm: mm context of the victim
6411 * @gfp_mask: reclaim mode
6412 * @memcgp: charged memcg return
25843c2b 6413 * @compound: charge the page as compound or small page
00501b53
JW
6414 *
6415 * Try to charge @page to the memcg that @mm belongs to, reclaiming
6416 * pages according to @gfp_mask if necessary.
6417 *
6418 * Returns 0 on success, with *@memcgp pointing to the charged memcg.
6419 * Otherwise, an error code is returned.
6420 *
6421 * After page->mapping has been set up, the caller must finalize the
6422 * charge with mem_cgroup_commit_charge(). Or abort the transaction
6423 * with mem_cgroup_cancel_charge() in case page instantiation fails.
6424 */
6425int mem_cgroup_try_charge(struct page *page, struct mm_struct *mm,
f627c2f5
KS
6426 gfp_t gfp_mask, struct mem_cgroup **memcgp,
6427 bool compound)
00501b53
JW
6428{
6429 struct mem_cgroup *memcg = NULL;
f627c2f5 6430 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
00501b53
JW
6431 int ret = 0;
6432
6433 if (mem_cgroup_disabled())
6434 goto out;
6435
6436 if (PageSwapCache(page)) {
00501b53
JW
6437 /*
6438 * Every swap fault against a single page tries to charge the
6439 * page, bail as early as possible. shmem_unuse() encounters
6440 * already charged pages, too. The USED bit is protected by
6441 * the page lock, which serializes swap cache removal, which
6442 * in turn serializes uncharging.
6443 */
e993d905 6444 VM_BUG_ON_PAGE(!PageLocked(page), page);
abe2895b 6445 if (compound_head(page)->mem_cgroup)
00501b53 6446 goto out;
e993d905 6447
37e84351 6448 if (do_swap_account) {
e993d905
VD
6449 swp_entry_t ent = { .val = page_private(page), };
6450 unsigned short id = lookup_swap_cgroup_id(ent);
6451
6452 rcu_read_lock();
6453 memcg = mem_cgroup_from_id(id);
6454 if (memcg && !css_tryget_online(&memcg->css))
6455 memcg = NULL;
6456 rcu_read_unlock();
6457 }
00501b53
JW
6458 }
6459
00501b53
JW
6460 if (!memcg)
6461 memcg = get_mem_cgroup_from_mm(mm);
6462
6463 ret = try_charge(memcg, gfp_mask, nr_pages);
6464
6465 css_put(&memcg->css);
00501b53
JW
6466out:
6467 *memcgp = memcg;
6468 return ret;
6469}
6470
2cf85583
TH
6471int mem_cgroup_try_charge_delay(struct page *page, struct mm_struct *mm,
6472 gfp_t gfp_mask, struct mem_cgroup **memcgp,
6473 bool compound)
6474{
6475 struct mem_cgroup *memcg;
6476 int ret;
6477
6478 ret = mem_cgroup_try_charge(page, mm, gfp_mask, memcgp, compound);
6479 memcg = *memcgp;
6480 mem_cgroup_throttle_swaprate(memcg, page_to_nid(page), gfp_mask);
6481 return ret;
6482}
6483
00501b53
JW
6484/**
6485 * mem_cgroup_commit_charge - commit a page charge
6486 * @page: page to charge
6487 * @memcg: memcg to charge the page to
6488 * @lrucare: page might be on LRU already
25843c2b 6489 * @compound: charge the page as compound or small page
00501b53
JW
6490 *
6491 * Finalize a charge transaction started by mem_cgroup_try_charge(),
6492 * after page->mapping has been set up. This must happen atomically
6493 * as part of the page instantiation, i.e. under the page table lock
6494 * for anonymous pages, under the page lock for page and swap cache.
6495 *
6496 * In addition, the page must not be on the LRU during the commit, to
6497 * prevent racing with task migration. If it might be, use @lrucare.
6498 *
6499 * Use mem_cgroup_cancel_charge() to cancel the transaction instead.
6500 */
6501void mem_cgroup_commit_charge(struct page *page, struct mem_cgroup *memcg,
f627c2f5 6502 bool lrucare, bool compound)
00501b53 6503{
f627c2f5 6504 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
00501b53
JW
6505
6506 VM_BUG_ON_PAGE(!page->mapping, page);
6507 VM_BUG_ON_PAGE(PageLRU(page) && !lrucare, page);
6508
6509 if (mem_cgroup_disabled())
6510 return;
6511 /*
6512 * Swap faults will attempt to charge the same page multiple
6513 * times. But reuse_swap_page() might have removed the page
6514 * from swapcache already, so we can't check PageSwapCache().
6515 */
6516 if (!memcg)
6517 return;
6518
6abb5a86
JW
6519 commit_charge(page, memcg, lrucare);
6520
6abb5a86 6521 local_irq_disable();
f627c2f5 6522 mem_cgroup_charge_statistics(memcg, page, compound, nr_pages);
6abb5a86
JW
6523 memcg_check_events(memcg, page);
6524 local_irq_enable();
00501b53 6525
7941d214 6526 if (do_memsw_account() && PageSwapCache(page)) {
00501b53
JW
6527 swp_entry_t entry = { .val = page_private(page) };
6528 /*
6529 * The swap entry might not get freed for a long time,
6530 * let's not wait for it. The page already received a
6531 * memory+swap charge, drop the swap entry duplicate.
6532 */
38d8b4e6 6533 mem_cgroup_uncharge_swap(entry, nr_pages);
00501b53
JW
6534 }
6535}
6536
6537/**
6538 * mem_cgroup_cancel_charge - cancel a page charge
6539 * @page: page to charge
6540 * @memcg: memcg to charge the page to
25843c2b 6541 * @compound: charge the page as compound or small page
00501b53
JW
6542 *
6543 * Cancel a charge transaction started by mem_cgroup_try_charge().
6544 */
f627c2f5
KS
6545void mem_cgroup_cancel_charge(struct page *page, struct mem_cgroup *memcg,
6546 bool compound)
00501b53 6547{
f627c2f5 6548 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
00501b53
JW
6549
6550 if (mem_cgroup_disabled())
6551 return;
6552 /*
6553 * Swap faults will attempt to charge the same page multiple
6554 * times. But reuse_swap_page() might have removed the page
6555 * from swapcache already, so we can't check PageSwapCache().
6556 */
6557 if (!memcg)
6558 return;
6559
00501b53
JW
6560 cancel_charge(memcg, nr_pages);
6561}
6562
a9d5adee
JG
6563struct uncharge_gather {
6564 struct mem_cgroup *memcg;
6565 unsigned long pgpgout;
6566 unsigned long nr_anon;
6567 unsigned long nr_file;
6568 unsigned long nr_kmem;
6569 unsigned long nr_huge;
6570 unsigned long nr_shmem;
6571 struct page *dummy_page;
6572};
6573
6574static inline void uncharge_gather_clear(struct uncharge_gather *ug)
747db954 6575{
a9d5adee
JG
6576 memset(ug, 0, sizeof(*ug));
6577}
6578
6579static void uncharge_batch(const struct uncharge_gather *ug)
6580{
6581 unsigned long nr_pages = ug->nr_anon + ug->nr_file + ug->nr_kmem;
747db954
JW
6582 unsigned long flags;
6583
a9d5adee
JG
6584 if (!mem_cgroup_is_root(ug->memcg)) {
6585 page_counter_uncharge(&ug->memcg->memory, nr_pages);
7941d214 6586 if (do_memsw_account())
a9d5adee
JG
6587 page_counter_uncharge(&ug->memcg->memsw, nr_pages);
6588 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && ug->nr_kmem)
6589 page_counter_uncharge(&ug->memcg->kmem, ug->nr_kmem);
6590 memcg_oom_recover(ug->memcg);
ce00a967 6591 }
747db954
JW
6592
6593 local_irq_save(flags);
c9019e9b
JW
6594 __mod_memcg_state(ug->memcg, MEMCG_RSS, -ug->nr_anon);
6595 __mod_memcg_state(ug->memcg, MEMCG_CACHE, -ug->nr_file);
6596 __mod_memcg_state(ug->memcg, MEMCG_RSS_HUGE, -ug->nr_huge);
6597 __mod_memcg_state(ug->memcg, NR_SHMEM, -ug->nr_shmem);
6598 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
871789d4 6599 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, nr_pages);
a9d5adee 6600 memcg_check_events(ug->memcg, ug->dummy_page);
747db954 6601 local_irq_restore(flags);
e8ea14cc 6602
a9d5adee
JG
6603 if (!mem_cgroup_is_root(ug->memcg))
6604 css_put_many(&ug->memcg->css, nr_pages);
6605}
6606
6607static void uncharge_page(struct page *page, struct uncharge_gather *ug)
6608{
6609 VM_BUG_ON_PAGE(PageLRU(page), page);
3f2eb028
JG
6610 VM_BUG_ON_PAGE(page_count(page) && !is_zone_device_page(page) &&
6611 !PageHWPoison(page) , page);
a9d5adee
JG
6612
6613 if (!page->mem_cgroup)
6614 return;
6615
6616 /*
6617 * Nobody should be changing or seriously looking at
6618 * page->mem_cgroup at this point, we have fully
6619 * exclusive access to the page.
6620 */
6621
6622 if (ug->memcg != page->mem_cgroup) {
6623 if (ug->memcg) {
6624 uncharge_batch(ug);
6625 uncharge_gather_clear(ug);
6626 }
6627 ug->memcg = page->mem_cgroup;
6628 }
6629
6630 if (!PageKmemcg(page)) {
6631 unsigned int nr_pages = 1;
6632
6633 if (PageTransHuge(page)) {
d8c6546b 6634 nr_pages = compound_nr(page);
a9d5adee
JG
6635 ug->nr_huge += nr_pages;
6636 }
6637 if (PageAnon(page))
6638 ug->nr_anon += nr_pages;
6639 else {
6640 ug->nr_file += nr_pages;
6641 if (PageSwapBacked(page))
6642 ug->nr_shmem += nr_pages;
6643 }
6644 ug->pgpgout++;
6645 } else {
d8c6546b 6646 ug->nr_kmem += compound_nr(page);
a9d5adee
JG
6647 __ClearPageKmemcg(page);
6648 }
6649
6650 ug->dummy_page = page;
6651 page->mem_cgroup = NULL;
747db954
JW
6652}
6653
6654static void uncharge_list(struct list_head *page_list)
6655{
a9d5adee 6656 struct uncharge_gather ug;
747db954 6657 struct list_head *next;
a9d5adee
JG
6658
6659 uncharge_gather_clear(&ug);
747db954 6660
8b592656
JW
6661 /*
6662 * Note that the list can be a single page->lru; hence the
6663 * do-while loop instead of a simple list_for_each_entry().
6664 */
747db954
JW
6665 next = page_list->next;
6666 do {
a9d5adee
JG
6667 struct page *page;
6668
747db954
JW
6669 page = list_entry(next, struct page, lru);
6670 next = page->lru.next;
6671
a9d5adee 6672 uncharge_page(page, &ug);
747db954
JW
6673 } while (next != page_list);
6674
a9d5adee
JG
6675 if (ug.memcg)
6676 uncharge_batch(&ug);
747db954
JW
6677}
6678
0a31bc97
JW
6679/**
6680 * mem_cgroup_uncharge - uncharge a page
6681 * @page: page to uncharge
6682 *
6683 * Uncharge a page previously charged with mem_cgroup_try_charge() and
6684 * mem_cgroup_commit_charge().
6685 */
6686void mem_cgroup_uncharge(struct page *page)
6687{
a9d5adee
JG
6688 struct uncharge_gather ug;
6689
0a31bc97
JW
6690 if (mem_cgroup_disabled())
6691 return;
6692
747db954 6693 /* Don't touch page->lru of any random page, pre-check: */
1306a85a 6694 if (!page->mem_cgroup)
0a31bc97
JW
6695 return;
6696
a9d5adee
JG
6697 uncharge_gather_clear(&ug);
6698 uncharge_page(page, &ug);
6699 uncharge_batch(&ug);
747db954 6700}
0a31bc97 6701
747db954
JW
6702/**
6703 * mem_cgroup_uncharge_list - uncharge a list of page
6704 * @page_list: list of pages to uncharge
6705 *
6706 * Uncharge a list of pages previously charged with
6707 * mem_cgroup_try_charge() and mem_cgroup_commit_charge().
6708 */
6709void mem_cgroup_uncharge_list(struct list_head *page_list)
6710{
6711 if (mem_cgroup_disabled())
6712 return;
0a31bc97 6713
747db954
JW
6714 if (!list_empty(page_list))
6715 uncharge_list(page_list);
0a31bc97
JW
6716}
6717
6718/**
6a93ca8f
JW
6719 * mem_cgroup_migrate - charge a page's replacement
6720 * @oldpage: currently circulating page
6721 * @newpage: replacement page
0a31bc97 6722 *
6a93ca8f
JW
6723 * Charge @newpage as a replacement page for @oldpage. @oldpage will
6724 * be uncharged upon free.
0a31bc97
JW
6725 *
6726 * Both pages must be locked, @newpage->mapping must be set up.
6727 */
6a93ca8f 6728void mem_cgroup_migrate(struct page *oldpage, struct page *newpage)
0a31bc97 6729{
29833315 6730 struct mem_cgroup *memcg;
44b7a8d3
JW
6731 unsigned int nr_pages;
6732 bool compound;
d93c4130 6733 unsigned long flags;
0a31bc97
JW
6734
6735 VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
6736 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
0a31bc97 6737 VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
6abb5a86
JW
6738 VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
6739 newpage);
0a31bc97
JW
6740
6741 if (mem_cgroup_disabled())
6742 return;
6743
6744 /* Page cache replacement: new page already charged? */
1306a85a 6745 if (newpage->mem_cgroup)
0a31bc97
JW
6746 return;
6747
45637bab 6748 /* Swapcache readahead pages can get replaced before being charged */
1306a85a 6749 memcg = oldpage->mem_cgroup;
29833315 6750 if (!memcg)
0a31bc97
JW
6751 return;
6752
44b7a8d3
JW
6753 /* Force-charge the new page. The old one will be freed soon */
6754 compound = PageTransHuge(newpage);
6755 nr_pages = compound ? hpage_nr_pages(newpage) : 1;
6756
6757 page_counter_charge(&memcg->memory, nr_pages);
6758 if (do_memsw_account())
6759 page_counter_charge(&memcg->memsw, nr_pages);
6760 css_get_many(&memcg->css, nr_pages);
0a31bc97 6761
9cf7666a 6762 commit_charge(newpage, memcg, false);
44b7a8d3 6763
d93c4130 6764 local_irq_save(flags);
44b7a8d3
JW
6765 mem_cgroup_charge_statistics(memcg, newpage, compound, nr_pages);
6766 memcg_check_events(memcg, newpage);
d93c4130 6767 local_irq_restore(flags);
0a31bc97
JW
6768}
6769
ef12947c 6770DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
11092087
JW
6771EXPORT_SYMBOL(memcg_sockets_enabled_key);
6772
2d758073 6773void mem_cgroup_sk_alloc(struct sock *sk)
11092087
JW
6774{
6775 struct mem_cgroup *memcg;
6776
2d758073
JW
6777 if (!mem_cgroup_sockets_enabled)
6778 return;
6779
edbe69ef
RG
6780 /*
6781 * Socket cloning can throw us here with sk_memcg already
6782 * filled. It won't however, necessarily happen from
6783 * process context. So the test for root memcg given
6784 * the current task's memcg won't help us in this case.
6785 *
6786 * Respecting the original socket's memcg is a better
6787 * decision in this case.
6788 */
6789 if (sk->sk_memcg) {
6790 css_get(&sk->sk_memcg->css);
6791 return;
6792 }
6793
11092087
JW
6794 rcu_read_lock();
6795 memcg = mem_cgroup_from_task(current);
f7e1cb6e
JW
6796 if (memcg == root_mem_cgroup)
6797 goto out;
0db15298 6798 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
f7e1cb6e 6799 goto out;
f7e1cb6e 6800 if (css_tryget_online(&memcg->css))
11092087 6801 sk->sk_memcg = memcg;
f7e1cb6e 6802out:
11092087
JW
6803 rcu_read_unlock();
6804}
11092087 6805
2d758073 6806void mem_cgroup_sk_free(struct sock *sk)
11092087 6807{
2d758073
JW
6808 if (sk->sk_memcg)
6809 css_put(&sk->sk_memcg->css);
11092087
JW
6810}
6811
6812/**
6813 * mem_cgroup_charge_skmem - charge socket memory
6814 * @memcg: memcg to charge
6815 * @nr_pages: number of pages to charge
6816 *
6817 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
6818 * @memcg's configured limit, %false if the charge had to be forced.
6819 */
6820bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
6821{
f7e1cb6e 6822 gfp_t gfp_mask = GFP_KERNEL;
11092087 6823
f7e1cb6e 6824 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
0db15298 6825 struct page_counter *fail;
f7e1cb6e 6826
0db15298
JW
6827 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
6828 memcg->tcpmem_pressure = 0;
f7e1cb6e
JW
6829 return true;
6830 }
0db15298
JW
6831 page_counter_charge(&memcg->tcpmem, nr_pages);
6832 memcg->tcpmem_pressure = 1;
f7e1cb6e 6833 return false;
11092087 6834 }
d886f4e4 6835
f7e1cb6e
JW
6836 /* Don't block in the packet receive path */
6837 if (in_softirq())
6838 gfp_mask = GFP_NOWAIT;
6839
c9019e9b 6840 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
b2807f07 6841
f7e1cb6e
JW
6842 if (try_charge(memcg, gfp_mask, nr_pages) == 0)
6843 return true;
6844
6845 try_charge(memcg, gfp_mask|__GFP_NOFAIL, nr_pages);
11092087
JW
6846 return false;
6847}
6848
6849/**
6850 * mem_cgroup_uncharge_skmem - uncharge socket memory
b7701a5f
MR
6851 * @memcg: memcg to uncharge
6852 * @nr_pages: number of pages to uncharge
11092087
JW
6853 */
6854void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
6855{
f7e1cb6e 6856 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
0db15298 6857 page_counter_uncharge(&memcg->tcpmem, nr_pages);
f7e1cb6e
JW
6858 return;
6859 }
d886f4e4 6860
c9019e9b 6861 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
b2807f07 6862
475d0487 6863 refill_stock(memcg, nr_pages);
11092087
JW
6864}
6865
f7e1cb6e
JW
6866static int __init cgroup_memory(char *s)
6867{
6868 char *token;
6869
6870 while ((token = strsep(&s, ",")) != NULL) {
6871 if (!*token)
6872 continue;
6873 if (!strcmp(token, "nosocket"))
6874 cgroup_memory_nosocket = true;
04823c83
VD
6875 if (!strcmp(token, "nokmem"))
6876 cgroup_memory_nokmem = true;
f7e1cb6e
JW
6877 }
6878 return 0;
6879}
6880__setup("cgroup.memory=", cgroup_memory);
11092087 6881
2d11085e 6882/*
1081312f
MH
6883 * subsys_initcall() for memory controller.
6884 *
308167fc
SAS
6885 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
6886 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
6887 * basically everything that doesn't depend on a specific mem_cgroup structure
6888 * should be initialized from here.
2d11085e
MH
6889 */
6890static int __init mem_cgroup_init(void)
6891{
95a045f6
JW
6892 int cpu, node;
6893
84c07d11 6894#ifdef CONFIG_MEMCG_KMEM
13583c3d
VD
6895 /*
6896 * Kmem cache creation is mostly done with the slab_mutex held,
17cc4dfe
TH
6897 * so use a workqueue with limited concurrency to avoid stalling
6898 * all worker threads in case lots of cgroups are created and
6899 * destroyed simultaneously.
13583c3d 6900 */
17cc4dfe
TH
6901 memcg_kmem_cache_wq = alloc_workqueue("memcg_kmem_cache", 0, 1);
6902 BUG_ON(!memcg_kmem_cache_wq);
13583c3d
VD
6903#endif
6904
308167fc
SAS
6905 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
6906 memcg_hotplug_cpu_dead);
95a045f6
JW
6907
6908 for_each_possible_cpu(cpu)
6909 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
6910 drain_local_stock);
6911
6912 for_each_node(node) {
6913 struct mem_cgroup_tree_per_node *rtpn;
95a045f6
JW
6914
6915 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
6916 node_online(node) ? node : NUMA_NO_NODE);
6917
ef8f2327 6918 rtpn->rb_root = RB_ROOT;
fa90b2fd 6919 rtpn->rb_rightmost = NULL;
ef8f2327 6920 spin_lock_init(&rtpn->lock);
95a045f6
JW
6921 soft_limit_tree.rb_tree_per_node[node] = rtpn;
6922 }
6923
2d11085e
MH
6924 return 0;
6925}
6926subsys_initcall(mem_cgroup_init);
21afa38e
JW
6927
6928#ifdef CONFIG_MEMCG_SWAP
358c07fc
AB
6929static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
6930{
1c2d479a 6931 while (!refcount_inc_not_zero(&memcg->id.ref)) {
358c07fc
AB
6932 /*
6933 * The root cgroup cannot be destroyed, so it's refcount must
6934 * always be >= 1.
6935 */
6936 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
6937 VM_BUG_ON(1);
6938 break;
6939 }
6940 memcg = parent_mem_cgroup(memcg);
6941 if (!memcg)
6942 memcg = root_mem_cgroup;
6943 }
6944 return memcg;
6945}
6946
21afa38e
JW
6947/**
6948 * mem_cgroup_swapout - transfer a memsw charge to swap
6949 * @page: page whose memsw charge to transfer
6950 * @entry: swap entry to move the charge to
6951 *
6952 * Transfer the memsw charge of @page to @entry.
6953 */
6954void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
6955{
1f47b61f 6956 struct mem_cgroup *memcg, *swap_memcg;
d6810d73 6957 unsigned int nr_entries;
21afa38e
JW
6958 unsigned short oldid;
6959
6960 VM_BUG_ON_PAGE(PageLRU(page), page);
6961 VM_BUG_ON_PAGE(page_count(page), page);
6962
7941d214 6963 if (!do_memsw_account())
21afa38e
JW
6964 return;
6965
6966 memcg = page->mem_cgroup;
6967
6968 /* Readahead page, never charged */
6969 if (!memcg)
6970 return;
6971
1f47b61f
VD
6972 /*
6973 * In case the memcg owning these pages has been offlined and doesn't
6974 * have an ID allocated to it anymore, charge the closest online
6975 * ancestor for the swap instead and transfer the memory+swap charge.
6976 */
6977 swap_memcg = mem_cgroup_id_get_online(memcg);
d6810d73
HY
6978 nr_entries = hpage_nr_pages(page);
6979 /* Get references for the tail pages, too */
6980 if (nr_entries > 1)
6981 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
6982 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
6983 nr_entries);
21afa38e 6984 VM_BUG_ON_PAGE(oldid, page);
c9019e9b 6985 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
21afa38e
JW
6986
6987 page->mem_cgroup = NULL;
6988
6989 if (!mem_cgroup_is_root(memcg))
d6810d73 6990 page_counter_uncharge(&memcg->memory, nr_entries);
21afa38e 6991
1f47b61f
VD
6992 if (memcg != swap_memcg) {
6993 if (!mem_cgroup_is_root(swap_memcg))
d6810d73
HY
6994 page_counter_charge(&swap_memcg->memsw, nr_entries);
6995 page_counter_uncharge(&memcg->memsw, nr_entries);
1f47b61f
VD
6996 }
6997
ce9ce665
SAS
6998 /*
6999 * Interrupts should be disabled here because the caller holds the
b93b0163 7000 * i_pages lock which is taken with interrupts-off. It is
ce9ce665 7001 * important here to have the interrupts disabled because it is the
b93b0163 7002 * only synchronisation we have for updating the per-CPU variables.
ce9ce665
SAS
7003 */
7004 VM_BUG_ON(!irqs_disabled());
d6810d73
HY
7005 mem_cgroup_charge_statistics(memcg, page, PageTransHuge(page),
7006 -nr_entries);
21afa38e 7007 memcg_check_events(memcg, page);
73f576c0
JW
7008
7009 if (!mem_cgroup_is_root(memcg))
d08afa14 7010 css_put_many(&memcg->css, nr_entries);
21afa38e
JW
7011}
7012
38d8b4e6
HY
7013/**
7014 * mem_cgroup_try_charge_swap - try charging swap space for a page
37e84351
VD
7015 * @page: page being added to swap
7016 * @entry: swap entry to charge
7017 *
38d8b4e6 7018 * Try to charge @page's memcg for the swap space at @entry.
37e84351
VD
7019 *
7020 * Returns 0 on success, -ENOMEM on failure.
7021 */
7022int mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry)
7023{
38d8b4e6 7024 unsigned int nr_pages = hpage_nr_pages(page);
37e84351 7025 struct page_counter *counter;
38d8b4e6 7026 struct mem_cgroup *memcg;
37e84351
VD
7027 unsigned short oldid;
7028
7029 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) || !do_swap_account)
7030 return 0;
7031
7032 memcg = page->mem_cgroup;
7033
7034 /* Readahead page, never charged */
7035 if (!memcg)
7036 return 0;
7037
f3a53a3a
TH
7038 if (!entry.val) {
7039 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
bb98f2c5 7040 return 0;
f3a53a3a 7041 }
bb98f2c5 7042
1f47b61f
VD
7043 memcg = mem_cgroup_id_get_online(memcg);
7044
37e84351 7045 if (!mem_cgroup_is_root(memcg) &&
38d8b4e6 7046 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
f3a53a3a
TH
7047 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7048 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
1f47b61f 7049 mem_cgroup_id_put(memcg);
37e84351 7050 return -ENOMEM;
1f47b61f 7051 }
37e84351 7052
38d8b4e6
HY
7053 /* Get references for the tail pages, too */
7054 if (nr_pages > 1)
7055 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7056 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
37e84351 7057 VM_BUG_ON_PAGE(oldid, page);
c9019e9b 7058 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
37e84351 7059
37e84351
VD
7060 return 0;
7061}
7062
21afa38e 7063/**
38d8b4e6 7064 * mem_cgroup_uncharge_swap - uncharge swap space
21afa38e 7065 * @entry: swap entry to uncharge
38d8b4e6 7066 * @nr_pages: the amount of swap space to uncharge
21afa38e 7067 */
38d8b4e6 7068void mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
21afa38e
JW
7069{
7070 struct mem_cgroup *memcg;
7071 unsigned short id;
7072
37e84351 7073 if (!do_swap_account)
21afa38e
JW
7074 return;
7075
38d8b4e6 7076 id = swap_cgroup_record(entry, 0, nr_pages);
21afa38e 7077 rcu_read_lock();
adbe427b 7078 memcg = mem_cgroup_from_id(id);
21afa38e 7079 if (memcg) {
37e84351
VD
7080 if (!mem_cgroup_is_root(memcg)) {
7081 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
38d8b4e6 7082 page_counter_uncharge(&memcg->swap, nr_pages);
37e84351 7083 else
38d8b4e6 7084 page_counter_uncharge(&memcg->memsw, nr_pages);
37e84351 7085 }
c9019e9b 7086 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
38d8b4e6 7087 mem_cgroup_id_put_many(memcg, nr_pages);
21afa38e
JW
7088 }
7089 rcu_read_unlock();
7090}
7091
d8b38438
VD
7092long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7093{
7094 long nr_swap_pages = get_nr_swap_pages();
7095
7096 if (!do_swap_account || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7097 return nr_swap_pages;
7098 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7099 nr_swap_pages = min_t(long, nr_swap_pages,
bbec2e15 7100 READ_ONCE(memcg->swap.max) -
d8b38438
VD
7101 page_counter_read(&memcg->swap));
7102 return nr_swap_pages;
7103}
7104
5ccc5aba
VD
7105bool mem_cgroup_swap_full(struct page *page)
7106{
7107 struct mem_cgroup *memcg;
7108
7109 VM_BUG_ON_PAGE(!PageLocked(page), page);
7110
7111 if (vm_swap_full())
7112 return true;
7113 if (!do_swap_account || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7114 return false;
7115
7116 memcg = page->mem_cgroup;
7117 if (!memcg)
7118 return false;
7119
7120 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
bbec2e15 7121 if (page_counter_read(&memcg->swap) * 2 >= memcg->swap.max)
5ccc5aba
VD
7122 return true;
7123
7124 return false;
7125}
7126
21afa38e
JW
7127/* for remember boot option*/
7128#ifdef CONFIG_MEMCG_SWAP_ENABLED
7129static int really_do_swap_account __initdata = 1;
7130#else
7131static int really_do_swap_account __initdata;
7132#endif
7133
7134static int __init enable_swap_account(char *s)
7135{
7136 if (!strcmp(s, "1"))
7137 really_do_swap_account = 1;
7138 else if (!strcmp(s, "0"))
7139 really_do_swap_account = 0;
7140 return 1;
7141}
7142__setup("swapaccount=", enable_swap_account);
7143
37e84351
VD
7144static u64 swap_current_read(struct cgroup_subsys_state *css,
7145 struct cftype *cft)
7146{
7147 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7148
7149 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7150}
7151
7152static int swap_max_show(struct seq_file *m, void *v)
7153{
677dc973
CD
7154 return seq_puts_memcg_tunable(m,
7155 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
37e84351
VD
7156}
7157
7158static ssize_t swap_max_write(struct kernfs_open_file *of,
7159 char *buf, size_t nbytes, loff_t off)
7160{
7161 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7162 unsigned long max;
7163 int err;
7164
7165 buf = strstrip(buf);
7166 err = page_counter_memparse(buf, "max", &max);
7167 if (err)
7168 return err;
7169
be09102b 7170 xchg(&memcg->swap.max, max);
37e84351
VD
7171
7172 return nbytes;
7173}
7174
f3a53a3a
TH
7175static int swap_events_show(struct seq_file *m, void *v)
7176{
aa9694bb 7177 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
f3a53a3a
TH
7178
7179 seq_printf(m, "max %lu\n",
7180 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7181 seq_printf(m, "fail %lu\n",
7182 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7183
7184 return 0;
7185}
7186
37e84351
VD
7187static struct cftype swap_files[] = {
7188 {
7189 .name = "swap.current",
7190 .flags = CFTYPE_NOT_ON_ROOT,
7191 .read_u64 = swap_current_read,
7192 },
7193 {
7194 .name = "swap.max",
7195 .flags = CFTYPE_NOT_ON_ROOT,
7196 .seq_show = swap_max_show,
7197 .write = swap_max_write,
7198 },
f3a53a3a
TH
7199 {
7200 .name = "swap.events",
7201 .flags = CFTYPE_NOT_ON_ROOT,
7202 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7203 .seq_show = swap_events_show,
7204 },
37e84351
VD
7205 { } /* terminate */
7206};
7207
21afa38e
JW
7208static struct cftype memsw_cgroup_files[] = {
7209 {
7210 .name = "memsw.usage_in_bytes",
7211 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7212 .read_u64 = mem_cgroup_read_u64,
7213 },
7214 {
7215 .name = "memsw.max_usage_in_bytes",
7216 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7217 .write = mem_cgroup_reset,
7218 .read_u64 = mem_cgroup_read_u64,
7219 },
7220 {
7221 .name = "memsw.limit_in_bytes",
7222 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7223 .write = mem_cgroup_write,
7224 .read_u64 = mem_cgroup_read_u64,
7225 },
7226 {
7227 .name = "memsw.failcnt",
7228 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7229 .write = mem_cgroup_reset,
7230 .read_u64 = mem_cgroup_read_u64,
7231 },
7232 { }, /* terminate */
7233};
7234
7235static int __init mem_cgroup_swap_init(void)
7236{
7237 if (!mem_cgroup_disabled() && really_do_swap_account) {
7238 do_swap_account = 1;
37e84351
VD
7239 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys,
7240 swap_files));
21afa38e
JW
7241 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys,
7242 memsw_cgroup_files));
7243 }
7244 return 0;
7245}
7246subsys_initcall(mem_cgroup_swap_init);
7247
7248#endif /* CONFIG_MEMCG_SWAP */