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