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