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