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