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