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