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