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