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