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