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