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