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