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