]> git.proxmox.com Git - mirror_ubuntu-focal-kernel.git/blame - mm/memcontrol.c
irda: use msecs_to_jiffies() rather than manual calculation
[mirror_ubuntu-focal-kernel.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 *
8cdea7c0
BS
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 */
23
24#include <linux/res_counter.h>
25#include <linux/memcontrol.h>
26#include <linux/cgroup.h>
78fb7466 27#include <linux/mm.h>
4ffef5fe 28#include <linux/hugetlb.h>
d13d1443 29#include <linux/pagemap.h>
d52aa412 30#include <linux/smp.h>
8a9f3ccd 31#include <linux/page-flags.h>
66e1707b 32#include <linux/backing-dev.h>
8a9f3ccd
BS
33#include <linux/bit_spinlock.h>
34#include <linux/rcupdate.h>
e222432b 35#include <linux/limits.h>
b9e15baf 36#include <linux/export.h>
8c7c6e34 37#include <linux/mutex.h>
f64c3f54 38#include <linux/rbtree.h>
b6ac57d5 39#include <linux/slab.h>
66e1707b 40#include <linux/swap.h>
02491447 41#include <linux/swapops.h>
66e1707b 42#include <linux/spinlock.h>
2e72b634
KS
43#include <linux/eventfd.h>
44#include <linux/sort.h>
66e1707b 45#include <linux/fs.h>
d2ceb9b7 46#include <linux/seq_file.h>
33327948 47#include <linux/vmalloc.h>
b69408e8 48#include <linux/mm_inline.h>
52d4b9ac 49#include <linux/page_cgroup.h>
cdec2e42 50#include <linux/cpu.h>
158e0a2d 51#include <linux/oom.h>
08e552c6 52#include "internal.h"
d1a4c0b3
GC
53#include <net/sock.h>
54#include <net/tcp_memcontrol.h>
8cdea7c0 55
8697d331
BS
56#include <asm/uaccess.h>
57
cc8e970c
KM
58#include <trace/events/vmscan.h>
59
a181b0e8 60struct cgroup_subsys mem_cgroup_subsys __read_mostly;
a181b0e8 61#define MEM_CGROUP_RECLAIM_RETRIES 5
4b3bde4c 62struct mem_cgroup *root_mem_cgroup __read_mostly;
8cdea7c0 63
c077719b 64#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
338c8431 65/* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
c077719b 66int do_swap_account __read_mostly;
a42c390c
MH
67
68/* for remember boot option*/
69#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP_ENABLED
70static int really_do_swap_account __initdata = 1;
71#else
72static int really_do_swap_account __initdata = 0;
73#endif
74
c077719b
KH
75#else
76#define do_swap_account (0)
77#endif
78
79
d52aa412
KH
80/*
81 * Statistics for memory cgroup.
82 */
83enum mem_cgroup_stat_index {
84 /*
85 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
86 */
87 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
d69b042f 88 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
d8046582 89 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
0c3e73e8 90 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
711d3d2c 91 MEM_CGROUP_STAT_DATA, /* end of data requires synchronization */
32047e2a 92 MEM_CGROUP_ON_MOVE, /* someone is moving account between groups */
d52aa412
KH
93 MEM_CGROUP_STAT_NSTATS,
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 */
99 MEM_CGROUP_EVENTS_COUNT, /* # of pages paged in/out */
456f998e
YH
100 MEM_CGROUP_EVENTS_PGFAULT, /* # of page-faults */
101 MEM_CGROUP_EVENTS_PGMAJFAULT, /* # of major page-faults */
e9f8974f
JW
102 MEM_CGROUP_EVENTS_NSTATS,
103};
7a159cc9
JW
104/*
105 * Per memcg event counter is incremented at every pagein/pageout. With THP,
106 * it will be incremated by the number of pages. This counter is used for
107 * for trigger some periodic events. This is straightforward and better
108 * than using jiffies etc. to handle periodic memcg event.
109 */
110enum mem_cgroup_events_target {
111 MEM_CGROUP_TARGET_THRESH,
112 MEM_CGROUP_TARGET_SOFTLIMIT,
453a9bf3 113 MEM_CGROUP_TARGET_NUMAINFO,
7a159cc9
JW
114 MEM_CGROUP_NTARGETS,
115};
116#define THRESHOLDS_EVENTS_TARGET (128)
117#define SOFTLIMIT_EVENTS_TARGET (1024)
453a9bf3 118#define NUMAINFO_EVENTS_TARGET (1024)
e9f8974f 119
d52aa412 120struct mem_cgroup_stat_cpu {
7a159cc9 121 long count[MEM_CGROUP_STAT_NSTATS];
e9f8974f 122 unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
7a159cc9 123 unsigned long targets[MEM_CGROUP_NTARGETS];
d52aa412
KH
124};
125
6d12e2d8
KH
126/*
127 * per-zone information in memory controller.
128 */
6d12e2d8 129struct mem_cgroup_per_zone {
072c56c1
KH
130 /*
131 * spin_lock to protect the per cgroup LRU
132 */
b69408e8
CL
133 struct list_head lists[NR_LRU_LISTS];
134 unsigned long count[NR_LRU_LISTS];
3e2f41f1
KM
135
136 struct zone_reclaim_stat reclaim_stat;
f64c3f54
BS
137 struct rb_node tree_node; /* RB tree node */
138 unsigned long long usage_in_excess;/* Set to the value by which */
139 /* the soft limit is exceeded*/
140 bool on_tree;
4e416953
BS
141 struct mem_cgroup *mem; /* Back pointer, we cannot */
142 /* use container_of */
6d12e2d8
KH
143};
144/* Macro for accessing counter */
145#define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
146
147struct mem_cgroup_per_node {
148 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
149};
150
151struct mem_cgroup_lru_info {
152 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
153};
154
f64c3f54
BS
155/*
156 * Cgroups above their limits are maintained in a RB-Tree, independent of
157 * their hierarchy representation
158 */
159
160struct mem_cgroup_tree_per_zone {
161 struct rb_root rb_root;
162 spinlock_t lock;
163};
164
165struct mem_cgroup_tree_per_node {
166 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
167};
168
169struct mem_cgroup_tree {
170 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
171};
172
173static struct mem_cgroup_tree soft_limit_tree __read_mostly;
174
2e72b634
KS
175struct mem_cgroup_threshold {
176 struct eventfd_ctx *eventfd;
177 u64 threshold;
178};
179
9490ff27 180/* For threshold */
2e72b634
KS
181struct mem_cgroup_threshold_ary {
182 /* An array index points to threshold just below usage. */
5407a562 183 int current_threshold;
2e72b634
KS
184 /* Size of entries[] */
185 unsigned int size;
186 /* Array of thresholds */
187 struct mem_cgroup_threshold entries[0];
188};
2c488db2
KS
189
190struct mem_cgroup_thresholds {
191 /* Primary thresholds array */
192 struct mem_cgroup_threshold_ary *primary;
193 /*
194 * Spare threshold array.
195 * This is needed to make mem_cgroup_unregister_event() "never fail".
196 * It must be able to store at least primary->size - 1 entries.
197 */
198 struct mem_cgroup_threshold_ary *spare;
199};
200
9490ff27
KH
201/* for OOM */
202struct mem_cgroup_eventfd_list {
203 struct list_head list;
204 struct eventfd_ctx *eventfd;
205};
2e72b634 206
c0ff4b85
R
207static void mem_cgroup_threshold(struct mem_cgroup *memcg);
208static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
2e72b634 209
8cdea7c0
BS
210/*
211 * The memory controller data structure. The memory controller controls both
212 * page cache and RSS per cgroup. We would eventually like to provide
213 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
214 * to help the administrator determine what knobs to tune.
215 *
216 * TODO: Add a water mark for the memory controller. Reclaim will begin when
8a9f3ccd
BS
217 * we hit the water mark. May be even add a low water mark, such that
218 * no reclaim occurs from a cgroup at it's low water mark, this is
219 * a feature that will be implemented much later in the future.
8cdea7c0
BS
220 */
221struct mem_cgroup {
222 struct cgroup_subsys_state css;
223 /*
224 * the counter to account for memory usage
225 */
226 struct res_counter res;
8c7c6e34
KH
227 /*
228 * the counter to account for mem+swap usage.
229 */
230 struct res_counter memsw;
e5671dfa
GC
231 /*
232 * the counter to account for kmem usage.
233 */
234 struct res_counter kmem;
78fb7466
PE
235 /*
236 * Per cgroup active and inactive list, similar to the
237 * per zone LRU lists.
78fb7466 238 */
6d12e2d8 239 struct mem_cgroup_lru_info info;
6d61ef40 240 /*
af901ca1 241 * While reclaiming in a hierarchy, we cache the last child we
04046e1a 242 * reclaimed from.
6d61ef40 243 */
04046e1a 244 int last_scanned_child;
889976db
YH
245 int last_scanned_node;
246#if MAX_NUMNODES > 1
247 nodemask_t scan_nodes;
453a9bf3
KH
248 atomic_t numainfo_events;
249 atomic_t numainfo_updating;
889976db 250#endif
18f59ea7
BS
251 /*
252 * Should the accounting and control be hierarchical, per subtree?
253 */
254 bool use_hierarchy;
79dfdacc
MH
255
256 bool oom_lock;
257 atomic_t under_oom;
258
8c7c6e34 259 atomic_t refcnt;
14797e23 260
1f4c025b 261 int swappiness;
3c11ecf4
KH
262 /* OOM-Killer disable */
263 int oom_kill_disable;
a7885eb8 264
22a668d7
KH
265 /* set when res.limit == memsw.limit */
266 bool memsw_is_minimum;
267
2e72b634
KS
268 /* protect arrays of thresholds */
269 struct mutex thresholds_lock;
270
271 /* thresholds for memory usage. RCU-protected */
2c488db2 272 struct mem_cgroup_thresholds thresholds;
907860ed 273
2e72b634 274 /* thresholds for mem+swap usage. RCU-protected */
2c488db2 275 struct mem_cgroup_thresholds memsw_thresholds;
907860ed 276
9490ff27
KH
277 /* For oom notifier event fd */
278 struct list_head oom_notify;
185efc0f 279
7dc74be0
DN
280 /*
281 * Should we move charges of a task when a task is moved into this
282 * mem_cgroup ? And what type of charges should we move ?
283 */
284 unsigned long move_charge_at_immigrate;
e5671dfa
GC
285 /*
286 * Should kernel memory limits be stabilished independently
287 * from user memory ?
288 */
289 int kmem_independent_accounting;
d52aa412 290 /*
c62b1a3b 291 * percpu counter.
d52aa412 292 */
c62b1a3b 293 struct mem_cgroup_stat_cpu *stat;
711d3d2c
KH
294 /*
295 * used when a cpu is offlined or other synchronizations
296 * See mem_cgroup_read_stat().
297 */
298 struct mem_cgroup_stat_cpu nocpu_base;
299 spinlock_t pcp_counter_lock;
d1a4c0b3
GC
300
301#ifdef CONFIG_INET
302 struct tcp_memcontrol tcp_mem;
303#endif
8cdea7c0
BS
304};
305
7dc74be0
DN
306/* Stuffs for move charges at task migration. */
307/*
308 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
309 * left-shifted bitmap of these types.
310 */
311enum move_type {
4ffef5fe 312 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
87946a72 313 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */
7dc74be0
DN
314 NR_MOVE_TYPE,
315};
316
4ffef5fe
DN
317/* "mc" and its members are protected by cgroup_mutex */
318static struct move_charge_struct {
b1dd693e 319 spinlock_t lock; /* for from, to */
4ffef5fe
DN
320 struct mem_cgroup *from;
321 struct mem_cgroup *to;
322 unsigned long precharge;
854ffa8d 323 unsigned long moved_charge;
483c30b5 324 unsigned long moved_swap;
8033b97c
DN
325 struct task_struct *moving_task; /* a task moving charges */
326 wait_queue_head_t waitq; /* a waitq for other context */
327} mc = {
2bd9bb20 328 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
8033b97c
DN
329 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
330};
4ffef5fe 331
90254a65
DN
332static bool move_anon(void)
333{
334 return test_bit(MOVE_CHARGE_TYPE_ANON,
335 &mc.to->move_charge_at_immigrate);
336}
337
87946a72
DN
338static bool move_file(void)
339{
340 return test_bit(MOVE_CHARGE_TYPE_FILE,
341 &mc.to->move_charge_at_immigrate);
342}
343
4e416953
BS
344/*
345 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
346 * limit reclaim to prevent infinite loops, if they ever occur.
347 */
348#define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
349#define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
350
217bc319
KH
351enum charge_type {
352 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
353 MEM_CGROUP_CHARGE_TYPE_MAPPED,
4f98a2fe 354 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
c05555b5 355 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
d13d1443 356 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
8a9478ca 357 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
c05555b5
KH
358 NR_CHARGE_TYPE,
359};
360
8c7c6e34 361/* for encoding cft->private value on file */
e5671dfa
GC
362
363enum mem_type {
364 _MEM = 0,
365 _MEMSWAP,
366 _OOM_TYPE,
367 _KMEM,
368};
369
8c7c6e34
KH
370#define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
371#define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
372#define MEMFILE_ATTR(val) ((val) & 0xffff)
9490ff27
KH
373/* Used for OOM nofiier */
374#define OOM_CONTROL (0)
8c7c6e34 375
75822b44
BS
376/*
377 * Reclaim flags for mem_cgroup_hierarchical_reclaim
378 */
379#define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
380#define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
381#define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
382#define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
4e416953
BS
383#define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
384#define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
75822b44 385
c0ff4b85
R
386static void mem_cgroup_get(struct mem_cgroup *memcg);
387static void mem_cgroup_put(struct mem_cgroup *memcg);
e1aab161
GC
388
389/* Writing them here to avoid exposing memcg's inner layout */
390#ifdef CONFIG_CGROUP_MEM_RES_CTLR_KMEM
391#ifdef CONFIG_INET
392#include <net/sock.h>
d1a4c0b3 393#include <net/ip.h>
e1aab161
GC
394
395static bool mem_cgroup_is_root(struct mem_cgroup *memcg);
396void sock_update_memcg(struct sock *sk)
397{
398 /* A socket spends its whole life in the same cgroup */
399 if (sk->sk_cgrp) {
400 WARN_ON(1);
401 return;
402 }
403 if (static_branch(&memcg_socket_limit_enabled)) {
404 struct mem_cgroup *memcg;
405
406 BUG_ON(!sk->sk_prot->proto_cgroup);
407
408 rcu_read_lock();
409 memcg = mem_cgroup_from_task(current);
410 if (!mem_cgroup_is_root(memcg)) {
411 mem_cgroup_get(memcg);
412 sk->sk_cgrp = sk->sk_prot->proto_cgroup(memcg);
413 }
414 rcu_read_unlock();
415 }
416}
417EXPORT_SYMBOL(sock_update_memcg);
418
419void sock_release_memcg(struct sock *sk)
420{
421 if (static_branch(&memcg_socket_limit_enabled) && sk->sk_cgrp) {
422 struct mem_cgroup *memcg;
423 WARN_ON(!sk->sk_cgrp->memcg);
424 memcg = sk->sk_cgrp->memcg;
425 mem_cgroup_put(memcg);
426 }
427}
d1a4c0b3
GC
428
429struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
430{
431 if (!memcg || mem_cgroup_is_root(memcg))
432 return NULL;
433
434 return &memcg->tcp_mem.cg_proto;
435}
436EXPORT_SYMBOL(tcp_proto_cgroup);
e1aab161
GC
437#endif /* CONFIG_INET */
438#endif /* CONFIG_CGROUP_MEM_RES_CTLR_KMEM */
439
c0ff4b85 440static void drain_all_stock_async(struct mem_cgroup *memcg);
8c7c6e34 441
f64c3f54 442static struct mem_cgroup_per_zone *
c0ff4b85 443mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
f64c3f54 444{
c0ff4b85 445 return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
f64c3f54
BS
446}
447
c0ff4b85 448struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
d324236b 449{
c0ff4b85 450 return &memcg->css;
d324236b
WF
451}
452
f64c3f54 453static struct mem_cgroup_per_zone *
c0ff4b85 454page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
f64c3f54 455{
97a6c37b
JW
456 int nid = page_to_nid(page);
457 int zid = page_zonenum(page);
f64c3f54 458
c0ff4b85 459 return mem_cgroup_zoneinfo(memcg, nid, zid);
f64c3f54
BS
460}
461
462static struct mem_cgroup_tree_per_zone *
463soft_limit_tree_node_zone(int nid, int zid)
464{
465 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
466}
467
468static struct mem_cgroup_tree_per_zone *
469soft_limit_tree_from_page(struct page *page)
470{
471 int nid = page_to_nid(page);
472 int zid = page_zonenum(page);
473
474 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
475}
476
477static void
c0ff4b85 478__mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
f64c3f54 479 struct mem_cgroup_per_zone *mz,
ef8745c1
KH
480 struct mem_cgroup_tree_per_zone *mctz,
481 unsigned long long new_usage_in_excess)
f64c3f54
BS
482{
483 struct rb_node **p = &mctz->rb_root.rb_node;
484 struct rb_node *parent = NULL;
485 struct mem_cgroup_per_zone *mz_node;
486
487 if (mz->on_tree)
488 return;
489
ef8745c1
KH
490 mz->usage_in_excess = new_usage_in_excess;
491 if (!mz->usage_in_excess)
492 return;
f64c3f54
BS
493 while (*p) {
494 parent = *p;
495 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
496 tree_node);
497 if (mz->usage_in_excess < mz_node->usage_in_excess)
498 p = &(*p)->rb_left;
499 /*
500 * We can't avoid mem cgroups that are over their soft
501 * limit by the same amount
502 */
503 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
504 p = &(*p)->rb_right;
505 }
506 rb_link_node(&mz->tree_node, parent, p);
507 rb_insert_color(&mz->tree_node, &mctz->rb_root);
508 mz->on_tree = true;
4e416953
BS
509}
510
511static void
c0ff4b85 512__mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
4e416953
BS
513 struct mem_cgroup_per_zone *mz,
514 struct mem_cgroup_tree_per_zone *mctz)
515{
516 if (!mz->on_tree)
517 return;
518 rb_erase(&mz->tree_node, &mctz->rb_root);
519 mz->on_tree = false;
520}
521
f64c3f54 522static void
c0ff4b85 523mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
f64c3f54
BS
524 struct mem_cgroup_per_zone *mz,
525 struct mem_cgroup_tree_per_zone *mctz)
526{
527 spin_lock(&mctz->lock);
c0ff4b85 528 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
f64c3f54
BS
529 spin_unlock(&mctz->lock);
530}
531
f64c3f54 532
c0ff4b85 533static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
f64c3f54 534{
ef8745c1 535 unsigned long long excess;
f64c3f54
BS
536 struct mem_cgroup_per_zone *mz;
537 struct mem_cgroup_tree_per_zone *mctz;
4e649152
KH
538 int nid = page_to_nid(page);
539 int zid = page_zonenum(page);
f64c3f54
BS
540 mctz = soft_limit_tree_from_page(page);
541
542 /*
4e649152
KH
543 * Necessary to update all ancestors when hierarchy is used.
544 * because their event counter is not touched.
f64c3f54 545 */
c0ff4b85
R
546 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
547 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
548 excess = res_counter_soft_limit_excess(&memcg->res);
4e649152
KH
549 /*
550 * We have to update the tree if mz is on RB-tree or
551 * mem is over its softlimit.
552 */
ef8745c1 553 if (excess || mz->on_tree) {
4e649152
KH
554 spin_lock(&mctz->lock);
555 /* if on-tree, remove it */
556 if (mz->on_tree)
c0ff4b85 557 __mem_cgroup_remove_exceeded(memcg, mz, mctz);
4e649152 558 /*
ef8745c1
KH
559 * Insert again. mz->usage_in_excess will be updated.
560 * If excess is 0, no tree ops.
4e649152 561 */
c0ff4b85 562 __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
4e649152
KH
563 spin_unlock(&mctz->lock);
564 }
f64c3f54
BS
565 }
566}
567
c0ff4b85 568static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
f64c3f54
BS
569{
570 int node, zone;
571 struct mem_cgroup_per_zone *mz;
572 struct mem_cgroup_tree_per_zone *mctz;
573
574 for_each_node_state(node, N_POSSIBLE) {
575 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
c0ff4b85 576 mz = mem_cgroup_zoneinfo(memcg, node, zone);
f64c3f54 577 mctz = soft_limit_tree_node_zone(node, zone);
c0ff4b85 578 mem_cgroup_remove_exceeded(memcg, mz, mctz);
f64c3f54
BS
579 }
580 }
581}
582
4e416953
BS
583static struct mem_cgroup_per_zone *
584__mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
585{
586 struct rb_node *rightmost = NULL;
26251eaf 587 struct mem_cgroup_per_zone *mz;
4e416953
BS
588
589retry:
26251eaf 590 mz = NULL;
4e416953
BS
591 rightmost = rb_last(&mctz->rb_root);
592 if (!rightmost)
593 goto done; /* Nothing to reclaim from */
594
595 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
596 /*
597 * Remove the node now but someone else can add it back,
598 * we will to add it back at the end of reclaim to its correct
599 * position in the tree.
600 */
601 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
602 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
603 !css_tryget(&mz->mem->css))
604 goto retry;
605done:
606 return mz;
607}
608
609static struct mem_cgroup_per_zone *
610mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
611{
612 struct mem_cgroup_per_zone *mz;
613
614 spin_lock(&mctz->lock);
615 mz = __mem_cgroup_largest_soft_limit_node(mctz);
616 spin_unlock(&mctz->lock);
617 return mz;
618}
619
711d3d2c
KH
620/*
621 * Implementation Note: reading percpu statistics for memcg.
622 *
623 * Both of vmstat[] and percpu_counter has threshold and do periodic
624 * synchronization to implement "quick" read. There are trade-off between
625 * reading cost and precision of value. Then, we may have a chance to implement
626 * a periodic synchronizion of counter in memcg's counter.
627 *
628 * But this _read() function is used for user interface now. The user accounts
629 * memory usage by memory cgroup and he _always_ requires exact value because
630 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
631 * have to visit all online cpus and make sum. So, for now, unnecessary
632 * synchronization is not implemented. (just implemented for cpu hotplug)
633 *
634 * If there are kernel internal actions which can make use of some not-exact
635 * value, and reading all cpu value can be performance bottleneck in some
636 * common workload, threashold and synchonization as vmstat[] should be
637 * implemented.
638 */
c0ff4b85 639static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
7a159cc9 640 enum mem_cgroup_stat_index idx)
c62b1a3b 641{
7a159cc9 642 long val = 0;
c62b1a3b 643 int cpu;
c62b1a3b 644
711d3d2c
KH
645 get_online_cpus();
646 for_each_online_cpu(cpu)
c0ff4b85 647 val += per_cpu(memcg->stat->count[idx], cpu);
711d3d2c 648#ifdef CONFIG_HOTPLUG_CPU
c0ff4b85
R
649 spin_lock(&memcg->pcp_counter_lock);
650 val += memcg->nocpu_base.count[idx];
651 spin_unlock(&memcg->pcp_counter_lock);
711d3d2c
KH
652#endif
653 put_online_cpus();
c62b1a3b
KH
654 return val;
655}
656
c0ff4b85 657static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
0c3e73e8
BS
658 bool charge)
659{
660 int val = (charge) ? 1 : -1;
c0ff4b85 661 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
0c3e73e8
BS
662}
663
c0ff4b85 664void mem_cgroup_pgfault(struct mem_cgroup *memcg, int val)
456f998e 665{
c0ff4b85 666 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT], val);
456f998e
YH
667}
668
c0ff4b85 669void mem_cgroup_pgmajfault(struct mem_cgroup *memcg, int val)
456f998e 670{
c0ff4b85 671 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT], val);
456f998e
YH
672}
673
c0ff4b85 674static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
e9f8974f
JW
675 enum mem_cgroup_events_index idx)
676{
677 unsigned long val = 0;
678 int cpu;
679
680 for_each_online_cpu(cpu)
c0ff4b85 681 val += per_cpu(memcg->stat->events[idx], cpu);
e9f8974f 682#ifdef CONFIG_HOTPLUG_CPU
c0ff4b85
R
683 spin_lock(&memcg->pcp_counter_lock);
684 val += memcg->nocpu_base.events[idx];
685 spin_unlock(&memcg->pcp_counter_lock);
e9f8974f
JW
686#endif
687 return val;
688}
689
c0ff4b85 690static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
e401f176 691 bool file, int nr_pages)
d52aa412 692{
c62b1a3b
KH
693 preempt_disable();
694
e401f176 695 if (file)
c0ff4b85
R
696 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
697 nr_pages);
d52aa412 698 else
c0ff4b85
R
699 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
700 nr_pages);
55e462b0 701
e401f176
KH
702 /* pagein of a big page is an event. So, ignore page size */
703 if (nr_pages > 0)
c0ff4b85 704 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
3751d604 705 else {
c0ff4b85 706 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
3751d604
KH
707 nr_pages = -nr_pages; /* for event */
708 }
e401f176 709
c0ff4b85 710 __this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT], nr_pages);
2e72b634 711
c62b1a3b 712 preempt_enable();
6d12e2d8
KH
713}
714
bb2a0de9 715unsigned long
c0ff4b85 716mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
bb2a0de9 717 unsigned int lru_mask)
889976db
YH
718{
719 struct mem_cgroup_per_zone *mz;
bb2a0de9
KH
720 enum lru_list l;
721 unsigned long ret = 0;
722
c0ff4b85 723 mz = mem_cgroup_zoneinfo(memcg, nid, zid);
bb2a0de9
KH
724
725 for_each_lru(l) {
726 if (BIT(l) & lru_mask)
727 ret += MEM_CGROUP_ZSTAT(mz, l);
728 }
729 return ret;
730}
731
732static unsigned long
c0ff4b85 733mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
bb2a0de9
KH
734 int nid, unsigned int lru_mask)
735{
889976db
YH
736 u64 total = 0;
737 int zid;
738
bb2a0de9 739 for (zid = 0; zid < MAX_NR_ZONES; zid++)
c0ff4b85
R
740 total += mem_cgroup_zone_nr_lru_pages(memcg,
741 nid, zid, lru_mask);
bb2a0de9 742
889976db
YH
743 return total;
744}
bb2a0de9 745
c0ff4b85 746static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
bb2a0de9 747 unsigned int lru_mask)
6d12e2d8 748{
889976db 749 int nid;
6d12e2d8
KH
750 u64 total = 0;
751
bb2a0de9 752 for_each_node_state(nid, N_HIGH_MEMORY)
c0ff4b85 753 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
6d12e2d8 754 return total;
d52aa412
KH
755}
756
c0ff4b85 757static bool __memcg_event_check(struct mem_cgroup *memcg, int target)
7a159cc9
JW
758{
759 unsigned long val, next;
760
4799401f
SR
761 val = __this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
762 next = __this_cpu_read(memcg->stat->targets[target]);
7a159cc9
JW
763 /* from time_after() in jiffies.h */
764 return ((long)next - (long)val < 0);
765}
766
c0ff4b85 767static void __mem_cgroup_target_update(struct mem_cgroup *memcg, int target)
d2265e6f 768{
7a159cc9 769 unsigned long val, next;
d2265e6f 770
4799401f 771 val = __this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]);
d2265e6f 772
7a159cc9
JW
773 switch (target) {
774 case MEM_CGROUP_TARGET_THRESH:
775 next = val + THRESHOLDS_EVENTS_TARGET;
776 break;
777 case MEM_CGROUP_TARGET_SOFTLIMIT:
778 next = val + SOFTLIMIT_EVENTS_TARGET;
779 break;
453a9bf3
KH
780 case MEM_CGROUP_TARGET_NUMAINFO:
781 next = val + NUMAINFO_EVENTS_TARGET;
782 break;
7a159cc9
JW
783 default:
784 return;
785 }
786
4799401f 787 __this_cpu_write(memcg->stat->targets[target], next);
d2265e6f
KH
788}
789
790/*
791 * Check events in order.
792 *
793 */
c0ff4b85 794static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
d2265e6f 795{
4799401f 796 preempt_disable();
d2265e6f 797 /* threshold event is triggered in finer grain than soft limit */
c0ff4b85
R
798 if (unlikely(__memcg_event_check(memcg, MEM_CGROUP_TARGET_THRESH))) {
799 mem_cgroup_threshold(memcg);
800 __mem_cgroup_target_update(memcg, MEM_CGROUP_TARGET_THRESH);
801 if (unlikely(__memcg_event_check(memcg,
453a9bf3 802 MEM_CGROUP_TARGET_SOFTLIMIT))) {
c0ff4b85
R
803 mem_cgroup_update_tree(memcg, page);
804 __mem_cgroup_target_update(memcg,
453a9bf3
KH
805 MEM_CGROUP_TARGET_SOFTLIMIT);
806 }
807#if MAX_NUMNODES > 1
c0ff4b85 808 if (unlikely(__memcg_event_check(memcg,
453a9bf3 809 MEM_CGROUP_TARGET_NUMAINFO))) {
c0ff4b85
R
810 atomic_inc(&memcg->numainfo_events);
811 __mem_cgroup_target_update(memcg,
453a9bf3 812 MEM_CGROUP_TARGET_NUMAINFO);
7a159cc9 813 }
453a9bf3 814#endif
d2265e6f 815 }
4799401f 816 preempt_enable();
d2265e6f
KH
817}
818
d1a4c0b3 819struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
8cdea7c0
BS
820{
821 return container_of(cgroup_subsys_state(cont,
822 mem_cgroup_subsys_id), struct mem_cgroup,
823 css);
824}
825
cf475ad2 826struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
78fb7466 827{
31a78f23
BS
828 /*
829 * mm_update_next_owner() may clear mm->owner to NULL
830 * if it races with swapoff, page migration, etc.
831 * So this can be called with p == NULL.
832 */
833 if (unlikely(!p))
834 return NULL;
835
78fb7466
PE
836 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
837 struct mem_cgroup, css);
838}
839
a433658c 840struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
54595fe2 841{
c0ff4b85 842 struct mem_cgroup *memcg = NULL;
0b7f569e
KH
843
844 if (!mm)
845 return NULL;
54595fe2
KH
846 /*
847 * Because we have no locks, mm->owner's may be being moved to other
848 * cgroup. We use css_tryget() here even if this looks
849 * pessimistic (rather than adding locks here).
850 */
851 rcu_read_lock();
852 do {
c0ff4b85
R
853 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
854 if (unlikely(!memcg))
54595fe2 855 break;
c0ff4b85 856 } while (!css_tryget(&memcg->css));
54595fe2 857 rcu_read_unlock();
c0ff4b85 858 return memcg;
54595fe2
KH
859}
860
7d74b06f 861/* The caller has to guarantee "mem" exists before calling this */
c0ff4b85 862static struct mem_cgroup *mem_cgroup_start_loop(struct mem_cgroup *memcg)
14067bb3 863{
711d3d2c
KH
864 struct cgroup_subsys_state *css;
865 int found;
866
c0ff4b85 867 if (!memcg) /* ROOT cgroup has the smallest ID */
711d3d2c 868 return root_mem_cgroup; /*css_put/get against root is ignored*/
c0ff4b85
R
869 if (!memcg->use_hierarchy) {
870 if (css_tryget(&memcg->css))
871 return memcg;
711d3d2c
KH
872 return NULL;
873 }
874 rcu_read_lock();
875 /*
876 * searching a memory cgroup which has the smallest ID under given
877 * ROOT cgroup. (ID >= 1)
878 */
c0ff4b85 879 css = css_get_next(&mem_cgroup_subsys, 1, &memcg->css, &found);
711d3d2c 880 if (css && css_tryget(css))
c0ff4b85 881 memcg = container_of(css, struct mem_cgroup, css);
711d3d2c 882 else
c0ff4b85 883 memcg = NULL;
711d3d2c 884 rcu_read_unlock();
c0ff4b85 885 return memcg;
7d74b06f
KH
886}
887
888static struct mem_cgroup *mem_cgroup_get_next(struct mem_cgroup *iter,
889 struct mem_cgroup *root,
890 bool cond)
891{
892 int nextid = css_id(&iter->css) + 1;
893 int found;
894 int hierarchy_used;
14067bb3 895 struct cgroup_subsys_state *css;
14067bb3 896
7d74b06f 897 hierarchy_used = iter->use_hierarchy;
14067bb3 898
7d74b06f 899 css_put(&iter->css);
711d3d2c
KH
900 /* If no ROOT, walk all, ignore hierarchy */
901 if (!cond || (root && !hierarchy_used))
7d74b06f 902 return NULL;
14067bb3 903
711d3d2c
KH
904 if (!root)
905 root = root_mem_cgroup;
906
7d74b06f
KH
907 do {
908 iter = NULL;
14067bb3 909 rcu_read_lock();
7d74b06f
KH
910
911 css = css_get_next(&mem_cgroup_subsys, nextid,
912 &root->css, &found);
14067bb3 913 if (css && css_tryget(css))
7d74b06f 914 iter = container_of(css, struct mem_cgroup, css);
14067bb3 915 rcu_read_unlock();
7d74b06f 916 /* If css is NULL, no more cgroups will be found */
14067bb3 917 nextid = found + 1;
7d74b06f 918 } while (css && !iter);
14067bb3 919
7d74b06f 920 return iter;
14067bb3 921}
7d74b06f
KH
922/*
923 * for_eacn_mem_cgroup_tree() for visiting all cgroup under tree. Please
924 * be careful that "break" loop is not allowed. We have reference count.
925 * Instead of that modify "cond" to be false and "continue" to exit the loop.
926 */
927#define for_each_mem_cgroup_tree_cond(iter, root, cond) \
928 for (iter = mem_cgroup_start_loop(root);\
929 iter != NULL;\
930 iter = mem_cgroup_get_next(iter, root, cond))
931
932#define for_each_mem_cgroup_tree(iter, root) \
933 for_each_mem_cgroup_tree_cond(iter, root, true)
934
711d3d2c
KH
935#define for_each_mem_cgroup_all(iter) \
936 for_each_mem_cgroup_tree_cond(iter, NULL, true)
937
14067bb3 938
c0ff4b85 939static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
4b3bde4c 940{
c0ff4b85 941 return (memcg == root_mem_cgroup);
4b3bde4c
BS
942}
943
456f998e
YH
944void mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
945{
c0ff4b85 946 struct mem_cgroup *memcg;
456f998e
YH
947
948 if (!mm)
949 return;
950
951 rcu_read_lock();
c0ff4b85
R
952 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
953 if (unlikely(!memcg))
456f998e
YH
954 goto out;
955
956 switch (idx) {
957 case PGMAJFAULT:
c0ff4b85 958 mem_cgroup_pgmajfault(memcg, 1);
456f998e
YH
959 break;
960 case PGFAULT:
c0ff4b85 961 mem_cgroup_pgfault(memcg, 1);
456f998e
YH
962 break;
963 default:
964 BUG();
965 }
966out:
967 rcu_read_unlock();
968}
969EXPORT_SYMBOL(mem_cgroup_count_vm_event);
970
08e552c6
KH
971/*
972 * Following LRU functions are allowed to be used without PCG_LOCK.
973 * Operations are called by routine of global LRU independently from memcg.
974 * What we have to take care of here is validness of pc->mem_cgroup.
975 *
976 * Changes to pc->mem_cgroup happens when
977 * 1. charge
978 * 2. moving account
979 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
980 * It is added to LRU before charge.
981 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
982 * When moving account, the page is not on LRU. It's isolated.
983 */
4f98a2fe 984
08e552c6
KH
985void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
986{
987 struct page_cgroup *pc;
08e552c6 988 struct mem_cgroup_per_zone *mz;
6d12e2d8 989
f8d66542 990 if (mem_cgroup_disabled())
08e552c6
KH
991 return;
992 pc = lookup_page_cgroup(page);
993 /* can happen while we handle swapcache. */
4b3bde4c 994 if (!TestClearPageCgroupAcctLRU(pc))
08e552c6 995 return;
4b3bde4c 996 VM_BUG_ON(!pc->mem_cgroup);
544122e5
KH
997 /*
998 * We don't check PCG_USED bit. It's cleared when the "page" is finally
999 * removed from global LRU.
1000 */
97a6c37b 1001 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
ece35ca8
KH
1002 /* huge page split is done under lru_lock. so, we have no races. */
1003 MEM_CGROUP_ZSTAT(mz, lru) -= 1 << compound_order(page);
4b3bde4c
BS
1004 if (mem_cgroup_is_root(pc->mem_cgroup))
1005 return;
1006 VM_BUG_ON(list_empty(&pc->lru));
08e552c6 1007 list_del_init(&pc->lru);
6d12e2d8
KH
1008}
1009
08e552c6 1010void mem_cgroup_del_lru(struct page *page)
6d12e2d8 1011{
08e552c6
KH
1012 mem_cgroup_del_lru_list(page, page_lru(page));
1013}
b69408e8 1014
3f58a829
MK
1015/*
1016 * Writeback is about to end against a page which has been marked for immediate
1017 * reclaim. If it still appears to be reclaimable, move it to the tail of the
1018 * inactive list.
1019 */
1020void mem_cgroup_rotate_reclaimable_page(struct page *page)
1021{
1022 struct mem_cgroup_per_zone *mz;
1023 struct page_cgroup *pc;
1024 enum lru_list lru = page_lru(page);
1025
1026 if (mem_cgroup_disabled())
1027 return;
1028
1029 pc = lookup_page_cgroup(page);
1030 /* unused or root page is not rotated. */
1031 if (!PageCgroupUsed(pc))
1032 return;
1033 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1034 smp_rmb();
1035 if (mem_cgroup_is_root(pc->mem_cgroup))
1036 return;
97a6c37b 1037 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
3f58a829
MK
1038 list_move_tail(&pc->lru, &mz->lists[lru]);
1039}
1040
08e552c6
KH
1041void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
1042{
1043 struct mem_cgroup_per_zone *mz;
1044 struct page_cgroup *pc;
b69408e8 1045
f8d66542 1046 if (mem_cgroup_disabled())
08e552c6 1047 return;
6d12e2d8 1048
08e552c6 1049 pc = lookup_page_cgroup(page);
4b3bde4c 1050 /* unused or root page is not rotated. */
713735b4
JW
1051 if (!PageCgroupUsed(pc))
1052 return;
1053 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1054 smp_rmb();
1055 if (mem_cgroup_is_root(pc->mem_cgroup))
08e552c6 1056 return;
97a6c37b 1057 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
08e552c6 1058 list_move(&pc->lru, &mz->lists[lru]);
6d12e2d8
KH
1059}
1060
08e552c6 1061void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
66e1707b 1062{
08e552c6
KH
1063 struct page_cgroup *pc;
1064 struct mem_cgroup_per_zone *mz;
6d12e2d8 1065
f8d66542 1066 if (mem_cgroup_disabled())
08e552c6
KH
1067 return;
1068 pc = lookup_page_cgroup(page);
4b3bde4c 1069 VM_BUG_ON(PageCgroupAcctLRU(pc));
a61ed3ce
JW
1070 /*
1071 * putback: charge:
1072 * SetPageLRU SetPageCgroupUsed
1073 * smp_mb smp_mb
1074 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
1075 *
1076 * Ensure that one of the two sides adds the page to the memcg
1077 * LRU during a race.
1078 */
1079 smp_mb();
08e552c6 1080 if (!PageCgroupUsed(pc))
894bc310 1081 return;
713735b4
JW
1082 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1083 smp_rmb();
97a6c37b 1084 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
ece35ca8
KH
1085 /* huge page split is done under lru_lock. so, we have no races. */
1086 MEM_CGROUP_ZSTAT(mz, lru) += 1 << compound_order(page);
4b3bde4c
BS
1087 SetPageCgroupAcctLRU(pc);
1088 if (mem_cgroup_is_root(pc->mem_cgroup))
1089 return;
08e552c6
KH
1090 list_add(&pc->lru, &mz->lists[lru]);
1091}
544122e5 1092
08e552c6 1093/*
5a6475a4
KH
1094 * At handling SwapCache and other FUSE stuff, pc->mem_cgroup may be changed
1095 * while it's linked to lru because the page may be reused after it's fully
1096 * uncharged. To handle that, unlink page_cgroup from LRU when charge it again.
1097 * It's done under lock_page and expected that zone->lru_lock isnever held.
08e552c6 1098 */
5a6475a4 1099static void mem_cgroup_lru_del_before_commit(struct page *page)
08e552c6 1100{
544122e5
KH
1101 unsigned long flags;
1102 struct zone *zone = page_zone(page);
1103 struct page_cgroup *pc = lookup_page_cgroup(page);
1104
5a6475a4
KH
1105 /*
1106 * Doing this check without taking ->lru_lock seems wrong but this
1107 * is safe. Because if page_cgroup's USED bit is unset, the page
1108 * will not be added to any memcg's LRU. If page_cgroup's USED bit is
1109 * set, the commit after this will fail, anyway.
1110 * This all charge/uncharge is done under some mutual execustion.
1111 * So, we don't need to taking care of changes in USED bit.
1112 */
1113 if (likely(!PageLRU(page)))
1114 return;
1115
544122e5
KH
1116 spin_lock_irqsave(&zone->lru_lock, flags);
1117 /*
1118 * Forget old LRU when this page_cgroup is *not* used. This Used bit
1119 * is guarded by lock_page() because the page is SwapCache.
1120 */
1121 if (!PageCgroupUsed(pc))
1122 mem_cgroup_del_lru_list(page, page_lru(page));
1123 spin_unlock_irqrestore(&zone->lru_lock, flags);
08e552c6
KH
1124}
1125
5a6475a4 1126static void mem_cgroup_lru_add_after_commit(struct page *page)
544122e5
KH
1127{
1128 unsigned long flags;
1129 struct zone *zone = page_zone(page);
1130 struct page_cgroup *pc = lookup_page_cgroup(page);
a61ed3ce
JW
1131 /*
1132 * putback: charge:
1133 * SetPageLRU SetPageCgroupUsed
1134 * smp_mb smp_mb
1135 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU
1136 *
1137 * Ensure that one of the two sides adds the page to the memcg
1138 * LRU during a race.
1139 */
1140 smp_mb();
5a6475a4
KH
1141 /* taking care of that the page is added to LRU while we commit it */
1142 if (likely(!PageLRU(page)))
1143 return;
544122e5
KH
1144 spin_lock_irqsave(&zone->lru_lock, flags);
1145 /* link when the page is linked to LRU but page_cgroup isn't */
4b3bde4c 1146 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
544122e5
KH
1147 mem_cgroup_add_lru_list(page, page_lru(page));
1148 spin_unlock_irqrestore(&zone->lru_lock, flags);
1149}
1150
1151
08e552c6
KH
1152void mem_cgroup_move_lists(struct page *page,
1153 enum lru_list from, enum lru_list to)
1154{
f8d66542 1155 if (mem_cgroup_disabled())
08e552c6
KH
1156 return;
1157 mem_cgroup_del_lru_list(page, from);
1158 mem_cgroup_add_lru_list(page, to);
66e1707b
BS
1159}
1160
3e92041d 1161/*
c0ff4b85 1162 * Checks whether given mem is same or in the root_mem_cgroup's
3e92041d
MH
1163 * hierarchy subtree
1164 */
c0ff4b85
R
1165static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1166 struct mem_cgroup *memcg)
3e92041d 1167{
c0ff4b85
R
1168 if (root_memcg != memcg) {
1169 return (root_memcg->use_hierarchy &&
1170 css_is_ancestor(&memcg->css, &root_memcg->css));
3e92041d
MH
1171 }
1172
1173 return true;
1174}
1175
c0ff4b85 1176int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
4c4a2214
DR
1177{
1178 int ret;
0b7f569e 1179 struct mem_cgroup *curr = NULL;
158e0a2d 1180 struct task_struct *p;
4c4a2214 1181
158e0a2d
KH
1182 p = find_lock_task_mm(task);
1183 if (!p)
1184 return 0;
1185 curr = try_get_mem_cgroup_from_mm(p->mm);
1186 task_unlock(p);
0b7f569e
KH
1187 if (!curr)
1188 return 0;
d31f56db 1189 /*
c0ff4b85 1190 * We should check use_hierarchy of "memcg" not "curr". Because checking
d31f56db 1191 * use_hierarchy of "curr" here make this function true if hierarchy is
c0ff4b85
R
1192 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1193 * hierarchy(even if use_hierarchy is disabled in "memcg").
d31f56db 1194 */
c0ff4b85 1195 ret = mem_cgroup_same_or_subtree(memcg, curr);
0b7f569e 1196 css_put(&curr->css);
4c4a2214
DR
1197 return ret;
1198}
1199
9b272977 1200int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg, struct zone *zone)
14797e23 1201{
9b272977
JW
1202 unsigned long inactive_ratio;
1203 int nid = zone_to_nid(zone);
1204 int zid = zone_idx(zone);
14797e23 1205 unsigned long inactive;
9b272977 1206 unsigned long active;
c772be93 1207 unsigned long gb;
14797e23 1208
9b272977
JW
1209 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1210 BIT(LRU_INACTIVE_ANON));
1211 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1212 BIT(LRU_ACTIVE_ANON));
14797e23 1213
c772be93
KM
1214 gb = (inactive + active) >> (30 - PAGE_SHIFT);
1215 if (gb)
1216 inactive_ratio = int_sqrt(10 * gb);
1217 else
1218 inactive_ratio = 1;
1219
9b272977 1220 return inactive * inactive_ratio < active;
14797e23
KM
1221}
1222
9b272977 1223int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg, struct zone *zone)
56e49d21
RR
1224{
1225 unsigned long active;
1226 unsigned long inactive;
9b272977
JW
1227 int zid = zone_idx(zone);
1228 int nid = zone_to_nid(zone);
56e49d21 1229
9b272977
JW
1230 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1231 BIT(LRU_INACTIVE_FILE));
1232 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid,
1233 BIT(LRU_ACTIVE_FILE));
56e49d21
RR
1234
1235 return (active > inactive);
1236}
1237
3e2f41f1
KM
1238struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
1239 struct zone *zone)
1240{
13d7e3a2 1241 int nid = zone_to_nid(zone);
3e2f41f1
KM
1242 int zid = zone_idx(zone);
1243 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1244
1245 return &mz->reclaim_stat;
1246}
1247
1248struct zone_reclaim_stat *
1249mem_cgroup_get_reclaim_stat_from_page(struct page *page)
1250{
1251 struct page_cgroup *pc;
1252 struct mem_cgroup_per_zone *mz;
1253
1254 if (mem_cgroup_disabled())
1255 return NULL;
1256
1257 pc = lookup_page_cgroup(page);
bd112db8
DN
1258 if (!PageCgroupUsed(pc))
1259 return NULL;
713735b4
JW
1260 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1261 smp_rmb();
97a6c37b 1262 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
3e2f41f1
KM
1263 return &mz->reclaim_stat;
1264}
1265
66e1707b
BS
1266unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
1267 struct list_head *dst,
1268 unsigned long *scanned, int order,
4356f21d
MK
1269 isolate_mode_t mode,
1270 struct zone *z,
66e1707b 1271 struct mem_cgroup *mem_cont,
4f98a2fe 1272 int active, int file)
66e1707b
BS
1273{
1274 unsigned long nr_taken = 0;
1275 struct page *page;
1276 unsigned long scan;
1277 LIST_HEAD(pc_list);
1278 struct list_head *src;
ff7283fa 1279 struct page_cgroup *pc, *tmp;
13d7e3a2 1280 int nid = zone_to_nid(z);
1ecaab2b
KH
1281 int zid = zone_idx(z);
1282 struct mem_cgroup_per_zone *mz;
b7c46d15 1283 int lru = LRU_FILE * file + active;
2ffebca6 1284 int ret;
66e1707b 1285
cf475ad2 1286 BUG_ON(!mem_cont);
1ecaab2b 1287 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
b69408e8 1288 src = &mz->lists[lru];
66e1707b 1289
ff7283fa
KH
1290 scan = 0;
1291 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
436c6541 1292 if (scan >= nr_to_scan)
ff7283fa 1293 break;
08e552c6 1294
52d4b9ac
KH
1295 if (unlikely(!PageCgroupUsed(pc)))
1296 continue;
5564e88b 1297
6b3ae58e 1298 page = lookup_cgroup_page(pc);
5564e88b 1299
436c6541 1300 if (unlikely(!PageLRU(page)))
ff7283fa 1301 continue;
ff7283fa 1302
436c6541 1303 scan++;
2ffebca6
KH
1304 ret = __isolate_lru_page(page, mode, file);
1305 switch (ret) {
1306 case 0:
66e1707b 1307 list_move(&page->lru, dst);
2ffebca6 1308 mem_cgroup_del_lru(page);
2c888cfb 1309 nr_taken += hpage_nr_pages(page);
2ffebca6
KH
1310 break;
1311 case -EBUSY:
1312 /* we don't affect global LRU but rotate in our LRU */
1313 mem_cgroup_rotate_lru_list(page, page_lru(page));
1314 break;
1315 default:
1316 break;
66e1707b
BS
1317 }
1318 }
1319
66e1707b 1320 *scanned = scan;
cc8e970c
KM
1321
1322 trace_mm_vmscan_memcg_isolate(0, nr_to_scan, scan, nr_taken,
1323 0, 0, 0, mode);
1324
66e1707b
BS
1325 return nr_taken;
1326}
1327
6d61ef40
BS
1328#define mem_cgroup_from_res_counter(counter, member) \
1329 container_of(counter, struct mem_cgroup, member)
1330
19942822 1331/**
9d11ea9f
JW
1332 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1333 * @mem: the memory cgroup
19942822 1334 *
9d11ea9f 1335 * Returns the maximum amount of memory @mem can be charged with, in
7ec99d62 1336 * pages.
19942822 1337 */
c0ff4b85 1338static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
19942822 1339{
9d11ea9f
JW
1340 unsigned long long margin;
1341
c0ff4b85 1342 margin = res_counter_margin(&memcg->res);
9d11ea9f 1343 if (do_swap_account)
c0ff4b85 1344 margin = min(margin, res_counter_margin(&memcg->memsw));
7ec99d62 1345 return margin >> PAGE_SHIFT;
19942822
JW
1346}
1347
1f4c025b 1348int mem_cgroup_swappiness(struct mem_cgroup *memcg)
a7885eb8
KM
1349{
1350 struct cgroup *cgrp = memcg->css.cgroup;
a7885eb8
KM
1351
1352 /* root ? */
1353 if (cgrp->parent == NULL)
1354 return vm_swappiness;
1355
bf1ff263 1356 return memcg->swappiness;
a7885eb8
KM
1357}
1358
c0ff4b85 1359static void mem_cgroup_start_move(struct mem_cgroup *memcg)
32047e2a
KH
1360{
1361 int cpu;
1489ebad
KH
1362
1363 get_online_cpus();
c0ff4b85 1364 spin_lock(&memcg->pcp_counter_lock);
1489ebad 1365 for_each_online_cpu(cpu)
c0ff4b85
R
1366 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) += 1;
1367 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] += 1;
1368 spin_unlock(&memcg->pcp_counter_lock);
1489ebad 1369 put_online_cpus();
32047e2a
KH
1370
1371 synchronize_rcu();
1372}
1373
c0ff4b85 1374static void mem_cgroup_end_move(struct mem_cgroup *memcg)
32047e2a
KH
1375{
1376 int cpu;
1377
c0ff4b85 1378 if (!memcg)
32047e2a 1379 return;
1489ebad 1380 get_online_cpus();
c0ff4b85 1381 spin_lock(&memcg->pcp_counter_lock);
1489ebad 1382 for_each_online_cpu(cpu)
c0ff4b85
R
1383 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1;
1384 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] -= 1;
1385 spin_unlock(&memcg->pcp_counter_lock);
1489ebad 1386 put_online_cpus();
32047e2a
KH
1387}
1388/*
1389 * 2 routines for checking "mem" is under move_account() or not.
1390 *
1391 * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used
1392 * for avoiding race in accounting. If true,
1393 * pc->mem_cgroup may be overwritten.
1394 *
1395 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1396 * under hierarchy of moving cgroups. This is for
1397 * waiting at hith-memory prressure caused by "move".
1398 */
1399
c0ff4b85 1400static bool mem_cgroup_stealed(struct mem_cgroup *memcg)
32047e2a
KH
1401{
1402 VM_BUG_ON(!rcu_read_lock_held());
c0ff4b85 1403 return this_cpu_read(memcg->stat->count[MEM_CGROUP_ON_MOVE]) > 0;
32047e2a 1404}
4b534334 1405
c0ff4b85 1406static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
4b534334 1407{
2bd9bb20
KH
1408 struct mem_cgroup *from;
1409 struct mem_cgroup *to;
4b534334 1410 bool ret = false;
2bd9bb20
KH
1411 /*
1412 * Unlike task_move routines, we access mc.to, mc.from not under
1413 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1414 */
1415 spin_lock(&mc.lock);
1416 from = mc.from;
1417 to = mc.to;
1418 if (!from)
1419 goto unlock;
3e92041d 1420
c0ff4b85
R
1421 ret = mem_cgroup_same_or_subtree(memcg, from)
1422 || mem_cgroup_same_or_subtree(memcg, to);
2bd9bb20
KH
1423unlock:
1424 spin_unlock(&mc.lock);
4b534334
KH
1425 return ret;
1426}
1427
c0ff4b85 1428static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
4b534334
KH
1429{
1430 if (mc.moving_task && current != mc.moving_task) {
c0ff4b85 1431 if (mem_cgroup_under_move(memcg)) {
4b534334
KH
1432 DEFINE_WAIT(wait);
1433 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1434 /* moving charge context might have finished. */
1435 if (mc.moving_task)
1436 schedule();
1437 finish_wait(&mc.waitq, &wait);
1438 return true;
1439 }
1440 }
1441 return false;
1442}
1443
e222432b 1444/**
6a6135b6 1445 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
e222432b
BS
1446 * @memcg: The memory cgroup that went over limit
1447 * @p: Task that is going to be killed
1448 *
1449 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1450 * enabled
1451 */
1452void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1453{
1454 struct cgroup *task_cgrp;
1455 struct cgroup *mem_cgrp;
1456 /*
1457 * Need a buffer in BSS, can't rely on allocations. The code relies
1458 * on the assumption that OOM is serialized for memory controller.
1459 * If this assumption is broken, revisit this code.
1460 */
1461 static char memcg_name[PATH_MAX];
1462 int ret;
1463
d31f56db 1464 if (!memcg || !p)
e222432b
BS
1465 return;
1466
1467
1468 rcu_read_lock();
1469
1470 mem_cgrp = memcg->css.cgroup;
1471 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1472
1473 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1474 if (ret < 0) {
1475 /*
1476 * Unfortunately, we are unable to convert to a useful name
1477 * But we'll still print out the usage information
1478 */
1479 rcu_read_unlock();
1480 goto done;
1481 }
1482 rcu_read_unlock();
1483
1484 printk(KERN_INFO "Task in %s killed", memcg_name);
1485
1486 rcu_read_lock();
1487 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1488 if (ret < 0) {
1489 rcu_read_unlock();
1490 goto done;
1491 }
1492 rcu_read_unlock();
1493
1494 /*
1495 * Continues from above, so we don't need an KERN_ level
1496 */
1497 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1498done:
1499
1500 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1501 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1502 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1503 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1504 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1505 "failcnt %llu\n",
1506 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1507 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1508 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1509}
1510
81d39c20
KH
1511/*
1512 * This function returns the number of memcg under hierarchy tree. Returns
1513 * 1(self count) if no children.
1514 */
c0ff4b85 1515static int mem_cgroup_count_children(struct mem_cgroup *memcg)
81d39c20
KH
1516{
1517 int num = 0;
7d74b06f
KH
1518 struct mem_cgroup *iter;
1519
c0ff4b85 1520 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f 1521 num++;
81d39c20
KH
1522 return num;
1523}
1524
a63d83f4
DR
1525/*
1526 * Return the memory (and swap, if configured) limit for a memcg.
1527 */
1528u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1529{
1530 u64 limit;
1531 u64 memsw;
1532
f3e8eb70
JW
1533 limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1534 limit += total_swap_pages << PAGE_SHIFT;
1535
a63d83f4
DR
1536 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1537 /*
1538 * If memsw is finite and limits the amount of swap space available
1539 * to this memcg, return that limit.
1540 */
1541 return min(limit, memsw);
1542}
1543
6d61ef40 1544/*
04046e1a
KH
1545 * Visit the first child (need not be the first child as per the ordering
1546 * of the cgroup list, since we track last_scanned_child) of @mem and use
1547 * that to reclaim free pages from.
1548 */
1549static struct mem_cgroup *
c0ff4b85 1550mem_cgroup_select_victim(struct mem_cgroup *root_memcg)
04046e1a
KH
1551{
1552 struct mem_cgroup *ret = NULL;
1553 struct cgroup_subsys_state *css;
1554 int nextid, found;
1555
c0ff4b85
R
1556 if (!root_memcg->use_hierarchy) {
1557 css_get(&root_memcg->css);
1558 ret = root_memcg;
04046e1a
KH
1559 }
1560
1561 while (!ret) {
1562 rcu_read_lock();
c0ff4b85
R
1563 nextid = root_memcg->last_scanned_child + 1;
1564 css = css_get_next(&mem_cgroup_subsys, nextid, &root_memcg->css,
04046e1a
KH
1565 &found);
1566 if (css && css_tryget(css))
1567 ret = container_of(css, struct mem_cgroup, css);
1568
1569 rcu_read_unlock();
1570 /* Updates scanning parameter */
04046e1a
KH
1571 if (!css) {
1572 /* this means start scan from ID:1 */
c0ff4b85 1573 root_memcg->last_scanned_child = 0;
04046e1a 1574 } else
c0ff4b85 1575 root_memcg->last_scanned_child = found;
04046e1a
KH
1576 }
1577
1578 return ret;
1579}
1580
4d0c066d
KH
1581/**
1582 * test_mem_cgroup_node_reclaimable
1583 * @mem: the target memcg
1584 * @nid: the node ID to be checked.
1585 * @noswap : specify true here if the user wants flle only information.
1586 *
1587 * This function returns whether the specified memcg contains any
1588 * reclaimable pages on a node. Returns true if there are any reclaimable
1589 * pages in the node.
1590 */
c0ff4b85 1591static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
4d0c066d
KH
1592 int nid, bool noswap)
1593{
c0ff4b85 1594 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
4d0c066d
KH
1595 return true;
1596 if (noswap || !total_swap_pages)
1597 return false;
c0ff4b85 1598 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
4d0c066d
KH
1599 return true;
1600 return false;
1601
1602}
889976db
YH
1603#if MAX_NUMNODES > 1
1604
1605/*
1606 * Always updating the nodemask is not very good - even if we have an empty
1607 * list or the wrong list here, we can start from some node and traverse all
1608 * nodes based on the zonelist. So update the list loosely once per 10 secs.
1609 *
1610 */
c0ff4b85 1611static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
889976db
YH
1612{
1613 int nid;
453a9bf3
KH
1614 /*
1615 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1616 * pagein/pageout changes since the last update.
1617 */
c0ff4b85 1618 if (!atomic_read(&memcg->numainfo_events))
453a9bf3 1619 return;
c0ff4b85 1620 if (atomic_inc_return(&memcg->numainfo_updating) > 1)
889976db
YH
1621 return;
1622
889976db 1623 /* make a nodemask where this memcg uses memory from */
c0ff4b85 1624 memcg->scan_nodes = node_states[N_HIGH_MEMORY];
889976db
YH
1625
1626 for_each_node_mask(nid, node_states[N_HIGH_MEMORY]) {
1627
c0ff4b85
R
1628 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
1629 node_clear(nid, memcg->scan_nodes);
889976db 1630 }
453a9bf3 1631
c0ff4b85
R
1632 atomic_set(&memcg->numainfo_events, 0);
1633 atomic_set(&memcg->numainfo_updating, 0);
889976db
YH
1634}
1635
1636/*
1637 * Selecting a node where we start reclaim from. Because what we need is just
1638 * reducing usage counter, start from anywhere is O,K. Considering
1639 * memory reclaim from current node, there are pros. and cons.
1640 *
1641 * Freeing memory from current node means freeing memory from a node which
1642 * we'll use or we've used. So, it may make LRU bad. And if several threads
1643 * hit limits, it will see a contention on a node. But freeing from remote
1644 * node means more costs for memory reclaim because of memory latency.
1645 *
1646 * Now, we use round-robin. Better algorithm is welcomed.
1647 */
c0ff4b85 1648int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
889976db
YH
1649{
1650 int node;
1651
c0ff4b85
R
1652 mem_cgroup_may_update_nodemask(memcg);
1653 node = memcg->last_scanned_node;
889976db 1654
c0ff4b85 1655 node = next_node(node, memcg->scan_nodes);
889976db 1656 if (node == MAX_NUMNODES)
c0ff4b85 1657 node = first_node(memcg->scan_nodes);
889976db
YH
1658 /*
1659 * We call this when we hit limit, not when pages are added to LRU.
1660 * No LRU may hold pages because all pages are UNEVICTABLE or
1661 * memcg is too small and all pages are not on LRU. In that case,
1662 * we use curret node.
1663 */
1664 if (unlikely(node == MAX_NUMNODES))
1665 node = numa_node_id();
1666
c0ff4b85 1667 memcg->last_scanned_node = node;
889976db
YH
1668 return node;
1669}
1670
4d0c066d
KH
1671/*
1672 * Check all nodes whether it contains reclaimable pages or not.
1673 * For quick scan, we make use of scan_nodes. This will allow us to skip
1674 * unused nodes. But scan_nodes is lazily updated and may not cotain
1675 * enough new information. We need to do double check.
1676 */
c0ff4b85 1677bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
4d0c066d
KH
1678{
1679 int nid;
1680
1681 /*
1682 * quick check...making use of scan_node.
1683 * We can skip unused nodes.
1684 */
c0ff4b85
R
1685 if (!nodes_empty(memcg->scan_nodes)) {
1686 for (nid = first_node(memcg->scan_nodes);
4d0c066d 1687 nid < MAX_NUMNODES;
c0ff4b85 1688 nid = next_node(nid, memcg->scan_nodes)) {
4d0c066d 1689
c0ff4b85 1690 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
4d0c066d
KH
1691 return true;
1692 }
1693 }
1694 /*
1695 * Check rest of nodes.
1696 */
1697 for_each_node_state(nid, N_HIGH_MEMORY) {
c0ff4b85 1698 if (node_isset(nid, memcg->scan_nodes))
4d0c066d 1699 continue;
c0ff4b85 1700 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
4d0c066d
KH
1701 return true;
1702 }
1703 return false;
1704}
1705
889976db 1706#else
c0ff4b85 1707int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
889976db
YH
1708{
1709 return 0;
1710}
4d0c066d 1711
c0ff4b85 1712bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
4d0c066d 1713{
c0ff4b85 1714 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
4d0c066d 1715}
889976db
YH
1716#endif
1717
04046e1a
KH
1718/*
1719 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1720 * we reclaimed from, so that we don't end up penalizing one child extensively
1721 * based on its position in the children list.
6d61ef40 1722 *
c0ff4b85 1723 * root_memcg is the original ancestor that we've been reclaim from.
04046e1a 1724 *
c0ff4b85 1725 * We give up and return to the caller when we visit root_memcg twice.
04046e1a 1726 * (other groups can be removed while we're walking....)
81d39c20
KH
1727 *
1728 * If shrink==true, for avoiding to free too much, this returns immedieately.
6d61ef40 1729 */
c0ff4b85 1730static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_memcg,
4e416953 1731 struct zone *zone,
75822b44 1732 gfp_t gfp_mask,
0ae5e89c
YH
1733 unsigned long reclaim_options,
1734 unsigned long *total_scanned)
6d61ef40 1735{
04046e1a
KH
1736 struct mem_cgroup *victim;
1737 int ret, total = 0;
1738 int loop = 0;
75822b44
BS
1739 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1740 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
4e416953 1741 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
9d11ea9f 1742 unsigned long excess;
185efc0f 1743 unsigned long nr_scanned;
9d11ea9f 1744
c0ff4b85 1745 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT;
04046e1a 1746
22a668d7 1747 /* If memsw_is_minimum==1, swap-out is of-no-use. */
c0ff4b85 1748 if (!check_soft && !shrink && root_memcg->memsw_is_minimum)
22a668d7
KH
1749 noswap = true;
1750
4e416953 1751 while (1) {
c0ff4b85
R
1752 victim = mem_cgroup_select_victim(root_memcg);
1753 if (victim == root_memcg) {
04046e1a 1754 loop++;
fbc29a25
KH
1755 /*
1756 * We are not draining per cpu cached charges during
1757 * soft limit reclaim because global reclaim doesn't
1758 * care about charges. It tries to free some memory and
1759 * charges will not give any.
1760 */
1761 if (!check_soft && loop >= 1)
c0ff4b85 1762 drain_all_stock_async(root_memcg);
4e416953
BS
1763 if (loop >= 2) {
1764 /*
1765 * If we have not been able to reclaim
1766 * anything, it might because there are
1767 * no reclaimable pages under this hierarchy
1768 */
1769 if (!check_soft || !total) {
1770 css_put(&victim->css);
1771 break;
1772 }
1773 /*
25985edc 1774 * We want to do more targeted reclaim.
4e416953
BS
1775 * excess >> 2 is not to excessive so as to
1776 * reclaim too much, nor too less that we keep
1777 * coming back to reclaim from this cgroup
1778 */
1779 if (total >= (excess >> 2) ||
1780 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1781 css_put(&victim->css);
1782 break;
1783 }
1784 }
1785 }
4d0c066d 1786 if (!mem_cgroup_reclaimable(victim, noswap)) {
04046e1a
KH
1787 /* this cgroup's local usage == 0 */
1788 css_put(&victim->css);
6d61ef40
BS
1789 continue;
1790 }
04046e1a 1791 /* we use swappiness of local cgroup */
0ae5e89c 1792 if (check_soft) {
4e416953 1793 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
185efc0f
JW
1794 noswap, zone, &nr_scanned);
1795 *total_scanned += nr_scanned;
0ae5e89c 1796 } else
4e416953 1797 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
185efc0f 1798 noswap);
04046e1a 1799 css_put(&victim->css);
81d39c20
KH
1800 /*
1801 * At shrinking usage, we can't check we should stop here or
1802 * reclaim more. It's depends on callers. last_scanned_child
1803 * will work enough for keeping fairness under tree.
1804 */
1805 if (shrink)
1806 return ret;
04046e1a 1807 total += ret;
4e416953 1808 if (check_soft) {
c0ff4b85 1809 if (!res_counter_soft_limit_excess(&root_memcg->res))
4e416953 1810 return total;
c0ff4b85 1811 } else if (mem_cgroup_margin(root_memcg))
4fd14ebf 1812 return total;
6d61ef40 1813 }
04046e1a 1814 return total;
6d61ef40
BS
1815}
1816
867578cb
KH
1817/*
1818 * Check OOM-Killer is already running under our hierarchy.
1819 * If someone is running, return false.
1af8efe9 1820 * Has to be called with memcg_oom_lock
867578cb 1821 */
c0ff4b85 1822static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg)
867578cb 1823{
79dfdacc
MH
1824 struct mem_cgroup *iter, *failed = NULL;
1825 bool cond = true;
a636b327 1826
c0ff4b85 1827 for_each_mem_cgroup_tree_cond(iter, memcg, cond) {
23751be0 1828 if (iter->oom_lock) {
79dfdacc
MH
1829 /*
1830 * this subtree of our hierarchy is already locked
1831 * so we cannot give a lock.
1832 */
79dfdacc
MH
1833 failed = iter;
1834 cond = false;
23751be0
JW
1835 } else
1836 iter->oom_lock = true;
7d74b06f 1837 }
867578cb 1838
79dfdacc 1839 if (!failed)
23751be0 1840 return true;
79dfdacc
MH
1841
1842 /*
1843 * OK, we failed to lock the whole subtree so we have to clean up
1844 * what we set up to the failing subtree
1845 */
1846 cond = true;
c0ff4b85 1847 for_each_mem_cgroup_tree_cond(iter, memcg, cond) {
79dfdacc
MH
1848 if (iter == failed) {
1849 cond = false;
1850 continue;
1851 }
1852 iter->oom_lock = false;
1853 }
23751be0 1854 return false;
a636b327 1855}
0b7f569e 1856
79dfdacc 1857/*
1af8efe9 1858 * Has to be called with memcg_oom_lock
79dfdacc 1859 */
c0ff4b85 1860static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
0b7f569e 1861{
7d74b06f
KH
1862 struct mem_cgroup *iter;
1863
c0ff4b85 1864 for_each_mem_cgroup_tree(iter, memcg)
79dfdacc
MH
1865 iter->oom_lock = false;
1866 return 0;
1867}
1868
c0ff4b85 1869static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
79dfdacc
MH
1870{
1871 struct mem_cgroup *iter;
1872
c0ff4b85 1873 for_each_mem_cgroup_tree(iter, memcg)
79dfdacc
MH
1874 atomic_inc(&iter->under_oom);
1875}
1876
c0ff4b85 1877static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
79dfdacc
MH
1878{
1879 struct mem_cgroup *iter;
1880
867578cb
KH
1881 /*
1882 * When a new child is created while the hierarchy is under oom,
1883 * mem_cgroup_oom_lock() may not be called. We have to use
1884 * atomic_add_unless() here.
1885 */
c0ff4b85 1886 for_each_mem_cgroup_tree(iter, memcg)
79dfdacc 1887 atomic_add_unless(&iter->under_oom, -1, 0);
0b7f569e
KH
1888}
1889
1af8efe9 1890static DEFINE_SPINLOCK(memcg_oom_lock);
867578cb
KH
1891static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1892
dc98df5a
KH
1893struct oom_wait_info {
1894 struct mem_cgroup *mem;
1895 wait_queue_t wait;
1896};
1897
1898static int memcg_oom_wake_function(wait_queue_t *wait,
1899 unsigned mode, int sync, void *arg)
1900{
c0ff4b85
R
1901 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg,
1902 *oom_wait_memcg;
dc98df5a
KH
1903 struct oom_wait_info *oom_wait_info;
1904
1905 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
c0ff4b85 1906 oom_wait_memcg = oom_wait_info->mem;
dc98df5a 1907
dc98df5a
KH
1908 /*
1909 * Both of oom_wait_info->mem and wake_mem are stable under us.
1910 * Then we can use css_is_ancestor without taking care of RCU.
1911 */
c0ff4b85
R
1912 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
1913 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
dc98df5a 1914 return 0;
dc98df5a
KH
1915 return autoremove_wake_function(wait, mode, sync, arg);
1916}
1917
c0ff4b85 1918static void memcg_wakeup_oom(struct mem_cgroup *memcg)
dc98df5a 1919{
c0ff4b85
R
1920 /* for filtering, pass "memcg" as argument. */
1921 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
dc98df5a
KH
1922}
1923
c0ff4b85 1924static void memcg_oom_recover(struct mem_cgroup *memcg)
3c11ecf4 1925{
c0ff4b85
R
1926 if (memcg && atomic_read(&memcg->under_oom))
1927 memcg_wakeup_oom(memcg);
3c11ecf4
KH
1928}
1929
867578cb
KH
1930/*
1931 * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1932 */
c0ff4b85 1933bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask)
0b7f569e 1934{
dc98df5a 1935 struct oom_wait_info owait;
3c11ecf4 1936 bool locked, need_to_kill;
867578cb 1937
c0ff4b85 1938 owait.mem = memcg;
dc98df5a
KH
1939 owait.wait.flags = 0;
1940 owait.wait.func = memcg_oom_wake_function;
1941 owait.wait.private = current;
1942 INIT_LIST_HEAD(&owait.wait.task_list);
3c11ecf4 1943 need_to_kill = true;
c0ff4b85 1944 mem_cgroup_mark_under_oom(memcg);
79dfdacc 1945
c0ff4b85 1946 /* At first, try to OOM lock hierarchy under memcg.*/
1af8efe9 1947 spin_lock(&memcg_oom_lock);
c0ff4b85 1948 locked = mem_cgroup_oom_lock(memcg);
867578cb
KH
1949 /*
1950 * Even if signal_pending(), we can't quit charge() loop without
1951 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1952 * under OOM is always welcomed, use TASK_KILLABLE here.
1953 */
3c11ecf4 1954 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
c0ff4b85 1955 if (!locked || memcg->oom_kill_disable)
3c11ecf4
KH
1956 need_to_kill = false;
1957 if (locked)
c0ff4b85 1958 mem_cgroup_oom_notify(memcg);
1af8efe9 1959 spin_unlock(&memcg_oom_lock);
867578cb 1960
3c11ecf4
KH
1961 if (need_to_kill) {
1962 finish_wait(&memcg_oom_waitq, &owait.wait);
c0ff4b85 1963 mem_cgroup_out_of_memory(memcg, mask);
3c11ecf4 1964 } else {
867578cb 1965 schedule();
dc98df5a 1966 finish_wait(&memcg_oom_waitq, &owait.wait);
867578cb 1967 }
1af8efe9 1968 spin_lock(&memcg_oom_lock);
79dfdacc 1969 if (locked)
c0ff4b85
R
1970 mem_cgroup_oom_unlock(memcg);
1971 memcg_wakeup_oom(memcg);
1af8efe9 1972 spin_unlock(&memcg_oom_lock);
867578cb 1973
c0ff4b85 1974 mem_cgroup_unmark_under_oom(memcg);
79dfdacc 1975
867578cb
KH
1976 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
1977 return false;
1978 /* Give chance to dying process */
715a5ee8 1979 schedule_timeout_uninterruptible(1);
867578cb 1980 return true;
0b7f569e
KH
1981}
1982
d69b042f
BS
1983/*
1984 * Currently used to update mapped file statistics, but the routine can be
1985 * generalized to update other statistics as well.
32047e2a
KH
1986 *
1987 * Notes: Race condition
1988 *
1989 * We usually use page_cgroup_lock() for accessing page_cgroup member but
1990 * it tends to be costly. But considering some conditions, we doesn't need
1991 * to do so _always_.
1992 *
1993 * Considering "charge", lock_page_cgroup() is not required because all
1994 * file-stat operations happen after a page is attached to radix-tree. There
1995 * are no race with "charge".
1996 *
1997 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
1998 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
1999 * if there are race with "uncharge". Statistics itself is properly handled
2000 * by flags.
2001 *
2002 * Considering "move", this is an only case we see a race. To make the race
2003 * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
2004 * possibility of race condition. If there is, we take a lock.
d69b042f 2005 */
26174efd 2006
2a7106f2
GT
2007void mem_cgroup_update_page_stat(struct page *page,
2008 enum mem_cgroup_page_stat_item idx, int val)
d69b042f 2009{
c0ff4b85 2010 struct mem_cgroup *memcg;
32047e2a
KH
2011 struct page_cgroup *pc = lookup_page_cgroup(page);
2012 bool need_unlock = false;
dbd4ea78 2013 unsigned long uninitialized_var(flags);
d69b042f 2014
d69b042f
BS
2015 if (unlikely(!pc))
2016 return;
2017
32047e2a 2018 rcu_read_lock();
c0ff4b85
R
2019 memcg = pc->mem_cgroup;
2020 if (unlikely(!memcg || !PageCgroupUsed(pc)))
32047e2a
KH
2021 goto out;
2022 /* pc->mem_cgroup is unstable ? */
c0ff4b85 2023 if (unlikely(mem_cgroup_stealed(memcg)) || PageTransHuge(page)) {
32047e2a 2024 /* take a lock against to access pc->mem_cgroup */
dbd4ea78 2025 move_lock_page_cgroup(pc, &flags);
32047e2a 2026 need_unlock = true;
c0ff4b85
R
2027 memcg = pc->mem_cgroup;
2028 if (!memcg || !PageCgroupUsed(pc))
32047e2a
KH
2029 goto out;
2030 }
26174efd 2031
26174efd 2032 switch (idx) {
2a7106f2 2033 case MEMCG_NR_FILE_MAPPED:
26174efd
KH
2034 if (val > 0)
2035 SetPageCgroupFileMapped(pc);
2036 else if (!page_mapped(page))
0c270f8f 2037 ClearPageCgroupFileMapped(pc);
2a7106f2 2038 idx = MEM_CGROUP_STAT_FILE_MAPPED;
26174efd
KH
2039 break;
2040 default:
2041 BUG();
8725d541 2042 }
d69b042f 2043
c0ff4b85 2044 this_cpu_add(memcg->stat->count[idx], val);
2a7106f2 2045
32047e2a
KH
2046out:
2047 if (unlikely(need_unlock))
dbd4ea78 2048 move_unlock_page_cgroup(pc, &flags);
32047e2a
KH
2049 rcu_read_unlock();
2050 return;
d69b042f 2051}
2a7106f2 2052EXPORT_SYMBOL(mem_cgroup_update_page_stat);
26174efd 2053
cdec2e42
KH
2054/*
2055 * size of first charge trial. "32" comes from vmscan.c's magic value.
2056 * TODO: maybe necessary to use big numbers in big irons.
2057 */
7ec99d62 2058#define CHARGE_BATCH 32U
cdec2e42
KH
2059struct memcg_stock_pcp {
2060 struct mem_cgroup *cached; /* this never be root cgroup */
11c9ea4e 2061 unsigned int nr_pages;
cdec2e42 2062 struct work_struct work;
26fe6168
KH
2063 unsigned long flags;
2064#define FLUSHING_CACHED_CHARGE (0)
cdec2e42
KH
2065};
2066static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
9f50fad6 2067static DEFINE_MUTEX(percpu_charge_mutex);
cdec2e42
KH
2068
2069/*
11c9ea4e 2070 * Try to consume stocked charge on this cpu. If success, one page is consumed
cdec2e42
KH
2071 * from local stock and true is returned. If the stock is 0 or charges from a
2072 * cgroup which is not current target, returns false. This stock will be
2073 * refilled.
2074 */
c0ff4b85 2075static bool consume_stock(struct mem_cgroup *memcg)
cdec2e42
KH
2076{
2077 struct memcg_stock_pcp *stock;
2078 bool ret = true;
2079
2080 stock = &get_cpu_var(memcg_stock);
c0ff4b85 2081 if (memcg == stock->cached && stock->nr_pages)
11c9ea4e 2082 stock->nr_pages--;
cdec2e42
KH
2083 else /* need to call res_counter_charge */
2084 ret = false;
2085 put_cpu_var(memcg_stock);
2086 return ret;
2087}
2088
2089/*
2090 * Returns stocks cached in percpu to res_counter and reset cached information.
2091 */
2092static void drain_stock(struct memcg_stock_pcp *stock)
2093{
2094 struct mem_cgroup *old = stock->cached;
2095
11c9ea4e
JW
2096 if (stock->nr_pages) {
2097 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2098
2099 res_counter_uncharge(&old->res, bytes);
cdec2e42 2100 if (do_swap_account)
11c9ea4e
JW
2101 res_counter_uncharge(&old->memsw, bytes);
2102 stock->nr_pages = 0;
cdec2e42
KH
2103 }
2104 stock->cached = NULL;
cdec2e42
KH
2105}
2106
2107/*
2108 * This must be called under preempt disabled or must be called by
2109 * a thread which is pinned to local cpu.
2110 */
2111static void drain_local_stock(struct work_struct *dummy)
2112{
2113 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2114 drain_stock(stock);
26fe6168 2115 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
cdec2e42
KH
2116}
2117
2118/*
2119 * Cache charges(val) which is from res_counter, to local per_cpu area.
320cc51d 2120 * This will be consumed by consume_stock() function, later.
cdec2e42 2121 */
c0ff4b85 2122static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
cdec2e42
KH
2123{
2124 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2125
c0ff4b85 2126 if (stock->cached != memcg) { /* reset if necessary */
cdec2e42 2127 drain_stock(stock);
c0ff4b85 2128 stock->cached = memcg;
cdec2e42 2129 }
11c9ea4e 2130 stock->nr_pages += nr_pages;
cdec2e42
KH
2131 put_cpu_var(memcg_stock);
2132}
2133
2134/*
c0ff4b85 2135 * Drains all per-CPU charge caches for given root_memcg resp. subtree
d38144b7
MH
2136 * of the hierarchy under it. sync flag says whether we should block
2137 * until the work is done.
cdec2e42 2138 */
c0ff4b85 2139static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
cdec2e42 2140{
26fe6168 2141 int cpu, curcpu;
d38144b7 2142
cdec2e42 2143 /* Notify other cpus that system-wide "drain" is running */
cdec2e42 2144 get_online_cpus();
5af12d0e 2145 curcpu = get_cpu();
cdec2e42
KH
2146 for_each_online_cpu(cpu) {
2147 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
c0ff4b85 2148 struct mem_cgroup *memcg;
26fe6168 2149
c0ff4b85
R
2150 memcg = stock->cached;
2151 if (!memcg || !stock->nr_pages)
26fe6168 2152 continue;
c0ff4b85 2153 if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
3e92041d 2154 continue;
d1a05b69
MH
2155 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2156 if (cpu == curcpu)
2157 drain_local_stock(&stock->work);
2158 else
2159 schedule_work_on(cpu, &stock->work);
2160 }
cdec2e42 2161 }
5af12d0e 2162 put_cpu();
d38144b7
MH
2163
2164 if (!sync)
2165 goto out;
2166
2167 for_each_online_cpu(cpu) {
2168 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
9f50fad6 2169 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
d38144b7
MH
2170 flush_work(&stock->work);
2171 }
2172out:
cdec2e42 2173 put_online_cpus();
d38144b7
MH
2174}
2175
2176/*
2177 * Tries to drain stocked charges in other cpus. This function is asynchronous
2178 * and just put a work per cpu for draining localy on each cpu. Caller can
2179 * expects some charges will be back to res_counter later but cannot wait for
2180 * it.
2181 */
c0ff4b85 2182static void drain_all_stock_async(struct mem_cgroup *root_memcg)
d38144b7 2183{
9f50fad6
MH
2184 /*
2185 * If someone calls draining, avoid adding more kworker runs.
2186 */
2187 if (!mutex_trylock(&percpu_charge_mutex))
2188 return;
c0ff4b85 2189 drain_all_stock(root_memcg, false);
9f50fad6 2190 mutex_unlock(&percpu_charge_mutex);
cdec2e42
KH
2191}
2192
2193/* This is a synchronous drain interface. */
c0ff4b85 2194static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
cdec2e42
KH
2195{
2196 /* called when force_empty is called */
9f50fad6 2197 mutex_lock(&percpu_charge_mutex);
c0ff4b85 2198 drain_all_stock(root_memcg, true);
9f50fad6 2199 mutex_unlock(&percpu_charge_mutex);
cdec2e42
KH
2200}
2201
711d3d2c
KH
2202/*
2203 * This function drains percpu counter value from DEAD cpu and
2204 * move it to local cpu. Note that this function can be preempted.
2205 */
c0ff4b85 2206static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
711d3d2c
KH
2207{
2208 int i;
2209
c0ff4b85 2210 spin_lock(&memcg->pcp_counter_lock);
711d3d2c 2211 for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
c0ff4b85 2212 long x = per_cpu(memcg->stat->count[i], cpu);
711d3d2c 2213
c0ff4b85
R
2214 per_cpu(memcg->stat->count[i], cpu) = 0;
2215 memcg->nocpu_base.count[i] += x;
711d3d2c 2216 }
e9f8974f 2217 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
c0ff4b85 2218 unsigned long x = per_cpu(memcg->stat->events[i], cpu);
e9f8974f 2219
c0ff4b85
R
2220 per_cpu(memcg->stat->events[i], cpu) = 0;
2221 memcg->nocpu_base.events[i] += x;
e9f8974f 2222 }
1489ebad 2223 /* need to clear ON_MOVE value, works as a kind of lock. */
c0ff4b85
R
2224 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0;
2225 spin_unlock(&memcg->pcp_counter_lock);
1489ebad
KH
2226}
2227
c0ff4b85 2228static void synchronize_mem_cgroup_on_move(struct mem_cgroup *memcg, int cpu)
1489ebad
KH
2229{
2230 int idx = MEM_CGROUP_ON_MOVE;
2231
c0ff4b85
R
2232 spin_lock(&memcg->pcp_counter_lock);
2233 per_cpu(memcg->stat->count[idx], cpu) = memcg->nocpu_base.count[idx];
2234 spin_unlock(&memcg->pcp_counter_lock);
711d3d2c
KH
2235}
2236
2237static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
cdec2e42
KH
2238 unsigned long action,
2239 void *hcpu)
2240{
2241 int cpu = (unsigned long)hcpu;
2242 struct memcg_stock_pcp *stock;
711d3d2c 2243 struct mem_cgroup *iter;
cdec2e42 2244
1489ebad
KH
2245 if ((action == CPU_ONLINE)) {
2246 for_each_mem_cgroup_all(iter)
2247 synchronize_mem_cgroup_on_move(iter, cpu);
2248 return NOTIFY_OK;
2249 }
2250
711d3d2c 2251 if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
cdec2e42 2252 return NOTIFY_OK;
711d3d2c
KH
2253
2254 for_each_mem_cgroup_all(iter)
2255 mem_cgroup_drain_pcp_counter(iter, cpu);
2256
cdec2e42
KH
2257 stock = &per_cpu(memcg_stock, cpu);
2258 drain_stock(stock);
2259 return NOTIFY_OK;
2260}
2261
4b534334
KH
2262
2263/* See __mem_cgroup_try_charge() for details */
2264enum {
2265 CHARGE_OK, /* success */
2266 CHARGE_RETRY, /* need to retry but retry is not bad */
2267 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */
2268 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */
2269 CHARGE_OOM_DIE, /* the current is killed because of OOM */
2270};
2271
c0ff4b85 2272static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
7ec99d62 2273 unsigned int nr_pages, bool oom_check)
4b534334 2274{
7ec99d62 2275 unsigned long csize = nr_pages * PAGE_SIZE;
4b534334
KH
2276 struct mem_cgroup *mem_over_limit;
2277 struct res_counter *fail_res;
2278 unsigned long flags = 0;
2279 int ret;
2280
c0ff4b85 2281 ret = res_counter_charge(&memcg->res, csize, &fail_res);
4b534334
KH
2282
2283 if (likely(!ret)) {
2284 if (!do_swap_account)
2285 return CHARGE_OK;
c0ff4b85 2286 ret = res_counter_charge(&memcg->memsw, csize, &fail_res);
4b534334
KH
2287 if (likely(!ret))
2288 return CHARGE_OK;
2289
c0ff4b85 2290 res_counter_uncharge(&memcg->res, csize);
4b534334
KH
2291 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2292 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2293 } else
2294 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
9221edb7 2295 /*
7ec99d62
JW
2296 * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch
2297 * of regular pages (CHARGE_BATCH), or a single regular page (1).
9221edb7
JW
2298 *
2299 * Never reclaim on behalf of optional batching, retry with a
2300 * single page instead.
2301 */
7ec99d62 2302 if (nr_pages == CHARGE_BATCH)
4b534334
KH
2303 return CHARGE_RETRY;
2304
2305 if (!(gfp_mask & __GFP_WAIT))
2306 return CHARGE_WOULDBLOCK;
2307
2308 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
0ae5e89c 2309 gfp_mask, flags, NULL);
7ec99d62 2310 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
19942822 2311 return CHARGE_RETRY;
4b534334 2312 /*
19942822
JW
2313 * Even though the limit is exceeded at this point, reclaim
2314 * may have been able to free some pages. Retry the charge
2315 * before killing the task.
2316 *
2317 * Only for regular pages, though: huge pages are rather
2318 * unlikely to succeed so close to the limit, and we fall back
2319 * to regular pages anyway in case of failure.
4b534334 2320 */
7ec99d62 2321 if (nr_pages == 1 && ret)
4b534334
KH
2322 return CHARGE_RETRY;
2323
2324 /*
2325 * At task move, charge accounts can be doubly counted. So, it's
2326 * better to wait until the end of task_move if something is going on.
2327 */
2328 if (mem_cgroup_wait_acct_move(mem_over_limit))
2329 return CHARGE_RETRY;
2330
2331 /* If we don't need to call oom-killer at el, return immediately */
2332 if (!oom_check)
2333 return CHARGE_NOMEM;
2334 /* check OOM */
2335 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
2336 return CHARGE_OOM_DIE;
2337
2338 return CHARGE_RETRY;
2339}
2340
f817ed48
KH
2341/*
2342 * Unlike exported interface, "oom" parameter is added. if oom==true,
2343 * oom-killer can be invoked.
8a9f3ccd 2344 */
f817ed48 2345static int __mem_cgroup_try_charge(struct mm_struct *mm,
ec168510 2346 gfp_t gfp_mask,
7ec99d62 2347 unsigned int nr_pages,
c0ff4b85 2348 struct mem_cgroup **ptr,
7ec99d62 2349 bool oom)
8a9f3ccd 2350{
7ec99d62 2351 unsigned int batch = max(CHARGE_BATCH, nr_pages);
4b534334 2352 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
c0ff4b85 2353 struct mem_cgroup *memcg = NULL;
4b534334 2354 int ret;
a636b327 2355
867578cb
KH
2356 /*
2357 * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2358 * in system level. So, allow to go ahead dying process in addition to
2359 * MEMDIE process.
2360 */
2361 if (unlikely(test_thread_flag(TIF_MEMDIE)
2362 || fatal_signal_pending(current)))
2363 goto bypass;
a636b327 2364
8a9f3ccd 2365 /*
3be91277
HD
2366 * We always charge the cgroup the mm_struct belongs to.
2367 * The mm_struct's mem_cgroup changes on task migration if the
8a9f3ccd
BS
2368 * thread group leader migrates. It's possible that mm is not
2369 * set, if so charge the init_mm (happens for pagecache usage).
2370 */
c0ff4b85 2371 if (!*ptr && !mm)
f75ca962
KH
2372 goto bypass;
2373again:
c0ff4b85
R
2374 if (*ptr) { /* css should be a valid one */
2375 memcg = *ptr;
2376 VM_BUG_ON(css_is_removed(&memcg->css));
2377 if (mem_cgroup_is_root(memcg))
f75ca962 2378 goto done;
c0ff4b85 2379 if (nr_pages == 1 && consume_stock(memcg))
f75ca962 2380 goto done;
c0ff4b85 2381 css_get(&memcg->css);
4b534334 2382 } else {
f75ca962 2383 struct task_struct *p;
54595fe2 2384
f75ca962
KH
2385 rcu_read_lock();
2386 p = rcu_dereference(mm->owner);
f75ca962 2387 /*
ebb76ce1 2388 * Because we don't have task_lock(), "p" can exit.
c0ff4b85 2389 * In that case, "memcg" can point to root or p can be NULL with
ebb76ce1
KH
2390 * race with swapoff. Then, we have small risk of mis-accouning.
2391 * But such kind of mis-account by race always happens because
2392 * we don't have cgroup_mutex(). It's overkill and we allo that
2393 * small race, here.
2394 * (*) swapoff at el will charge against mm-struct not against
2395 * task-struct. So, mm->owner can be NULL.
f75ca962 2396 */
c0ff4b85
R
2397 memcg = mem_cgroup_from_task(p);
2398 if (!memcg || mem_cgroup_is_root(memcg)) {
f75ca962
KH
2399 rcu_read_unlock();
2400 goto done;
2401 }
c0ff4b85 2402 if (nr_pages == 1 && consume_stock(memcg)) {
f75ca962
KH
2403 /*
2404 * It seems dagerous to access memcg without css_get().
2405 * But considering how consume_stok works, it's not
2406 * necessary. If consume_stock success, some charges
2407 * from this memcg are cached on this cpu. So, we
2408 * don't need to call css_get()/css_tryget() before
2409 * calling consume_stock().
2410 */
2411 rcu_read_unlock();
2412 goto done;
2413 }
2414 /* after here, we may be blocked. we need to get refcnt */
c0ff4b85 2415 if (!css_tryget(&memcg->css)) {
f75ca962
KH
2416 rcu_read_unlock();
2417 goto again;
2418 }
2419 rcu_read_unlock();
2420 }
8a9f3ccd 2421
4b534334
KH
2422 do {
2423 bool oom_check;
7a81b88c 2424
4b534334 2425 /* If killed, bypass charge */
f75ca962 2426 if (fatal_signal_pending(current)) {
c0ff4b85 2427 css_put(&memcg->css);
4b534334 2428 goto bypass;
f75ca962 2429 }
6d61ef40 2430
4b534334
KH
2431 oom_check = false;
2432 if (oom && !nr_oom_retries) {
2433 oom_check = true;
2434 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
cdec2e42 2435 }
66e1707b 2436
c0ff4b85 2437 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, oom_check);
4b534334
KH
2438 switch (ret) {
2439 case CHARGE_OK:
2440 break;
2441 case CHARGE_RETRY: /* not in OOM situation but retry */
7ec99d62 2442 batch = nr_pages;
c0ff4b85
R
2443 css_put(&memcg->css);
2444 memcg = NULL;
f75ca962 2445 goto again;
4b534334 2446 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
c0ff4b85 2447 css_put(&memcg->css);
4b534334
KH
2448 goto nomem;
2449 case CHARGE_NOMEM: /* OOM routine works */
f75ca962 2450 if (!oom) {
c0ff4b85 2451 css_put(&memcg->css);
867578cb 2452 goto nomem;
f75ca962 2453 }
4b534334
KH
2454 /* If oom, we never return -ENOMEM */
2455 nr_oom_retries--;
2456 break;
2457 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
c0ff4b85 2458 css_put(&memcg->css);
867578cb 2459 goto bypass;
66e1707b 2460 }
4b534334
KH
2461 } while (ret != CHARGE_OK);
2462
7ec99d62 2463 if (batch > nr_pages)
c0ff4b85
R
2464 refill_stock(memcg, batch - nr_pages);
2465 css_put(&memcg->css);
0c3e73e8 2466done:
c0ff4b85 2467 *ptr = memcg;
7a81b88c
KH
2468 return 0;
2469nomem:
c0ff4b85 2470 *ptr = NULL;
7a81b88c 2471 return -ENOMEM;
867578cb 2472bypass:
c0ff4b85 2473 *ptr = NULL;
867578cb 2474 return 0;
7a81b88c 2475}
8a9f3ccd 2476
a3032a2c
DN
2477/*
2478 * Somemtimes we have to undo a charge we got by try_charge().
2479 * This function is for that and do uncharge, put css's refcnt.
2480 * gotten by try_charge().
2481 */
c0ff4b85 2482static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
e7018b8d 2483 unsigned int nr_pages)
a3032a2c 2484{
c0ff4b85 2485 if (!mem_cgroup_is_root(memcg)) {
e7018b8d
JW
2486 unsigned long bytes = nr_pages * PAGE_SIZE;
2487
c0ff4b85 2488 res_counter_uncharge(&memcg->res, bytes);
a3032a2c 2489 if (do_swap_account)
c0ff4b85 2490 res_counter_uncharge(&memcg->memsw, bytes);
a3032a2c 2491 }
854ffa8d
DN
2492}
2493
a3b2d692
KH
2494/*
2495 * A helper function to get mem_cgroup from ID. must be called under
2496 * rcu_read_lock(). The caller must check css_is_removed() or some if
2497 * it's concern. (dropping refcnt from swap can be called against removed
2498 * memcg.)
2499 */
2500static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2501{
2502 struct cgroup_subsys_state *css;
2503
2504 /* ID 0 is unused ID */
2505 if (!id)
2506 return NULL;
2507 css = css_lookup(&mem_cgroup_subsys, id);
2508 if (!css)
2509 return NULL;
2510 return container_of(css, struct mem_cgroup, css);
2511}
2512
e42d9d5d 2513struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
b5a84319 2514{
c0ff4b85 2515 struct mem_cgroup *memcg = NULL;
3c776e64 2516 struct page_cgroup *pc;
a3b2d692 2517 unsigned short id;
b5a84319
KH
2518 swp_entry_t ent;
2519
3c776e64
DN
2520 VM_BUG_ON(!PageLocked(page));
2521
3c776e64 2522 pc = lookup_page_cgroup(page);
c0bd3f63 2523 lock_page_cgroup(pc);
a3b2d692 2524 if (PageCgroupUsed(pc)) {
c0ff4b85
R
2525 memcg = pc->mem_cgroup;
2526 if (memcg && !css_tryget(&memcg->css))
2527 memcg = NULL;
e42d9d5d 2528 } else if (PageSwapCache(page)) {
3c776e64 2529 ent.val = page_private(page);
a3b2d692
KH
2530 id = lookup_swap_cgroup(ent);
2531 rcu_read_lock();
c0ff4b85
R
2532 memcg = mem_cgroup_lookup(id);
2533 if (memcg && !css_tryget(&memcg->css))
2534 memcg = NULL;
a3b2d692 2535 rcu_read_unlock();
3c776e64 2536 }
c0bd3f63 2537 unlock_page_cgroup(pc);
c0ff4b85 2538 return memcg;
b5a84319
KH
2539}
2540
c0ff4b85 2541static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
5564e88b 2542 struct page *page,
7ec99d62 2543 unsigned int nr_pages,
ca3e0214 2544 struct page_cgroup *pc,
7ec99d62 2545 enum charge_type ctype)
7a81b88c 2546{
ca3e0214
KH
2547 lock_page_cgroup(pc);
2548 if (unlikely(PageCgroupUsed(pc))) {
2549 unlock_page_cgroup(pc);
c0ff4b85 2550 __mem_cgroup_cancel_charge(memcg, nr_pages);
ca3e0214
KH
2551 return;
2552 }
2553 /*
2554 * we don't need page_cgroup_lock about tail pages, becase they are not
2555 * accessed by any other context at this point.
2556 */
c0ff4b85 2557 pc->mem_cgroup = memcg;
261fb61a
KH
2558 /*
2559 * We access a page_cgroup asynchronously without lock_page_cgroup().
2560 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2561 * is accessed after testing USED bit. To make pc->mem_cgroup visible
2562 * before USED bit, we need memory barrier here.
2563 * See mem_cgroup_add_lru_list(), etc.
2564 */
08e552c6 2565 smp_wmb();
4b3bde4c
BS
2566 switch (ctype) {
2567 case MEM_CGROUP_CHARGE_TYPE_CACHE:
2568 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
2569 SetPageCgroupCache(pc);
2570 SetPageCgroupUsed(pc);
2571 break;
2572 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2573 ClearPageCgroupCache(pc);
2574 SetPageCgroupUsed(pc);
2575 break;
2576 default:
2577 break;
2578 }
3be91277 2579
c0ff4b85 2580 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), nr_pages);
52d4b9ac 2581 unlock_page_cgroup(pc);
430e4863
KH
2582 /*
2583 * "charge_statistics" updated event counter. Then, check it.
2584 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2585 * if they exceeds softlimit.
2586 */
c0ff4b85 2587 memcg_check_events(memcg, page);
7a81b88c 2588}
66e1707b 2589
ca3e0214
KH
2590#ifdef CONFIG_TRANSPARENT_HUGEPAGE
2591
2592#define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
2593 (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
2594/*
2595 * Because tail pages are not marked as "used", set it. We're under
2596 * zone->lru_lock, 'splitting on pmd' and compund_lock.
2597 */
2598void mem_cgroup_split_huge_fixup(struct page *head, struct page *tail)
2599{
2600 struct page_cgroup *head_pc = lookup_page_cgroup(head);
2601 struct page_cgroup *tail_pc = lookup_page_cgroup(tail);
2602 unsigned long flags;
2603
3d37c4a9
KH
2604 if (mem_cgroup_disabled())
2605 return;
ca3e0214 2606 /*
ece35ca8 2607 * We have no races with charge/uncharge but will have races with
ca3e0214
KH
2608 * page state accounting.
2609 */
2610 move_lock_page_cgroup(head_pc, &flags);
2611
2612 tail_pc->mem_cgroup = head_pc->mem_cgroup;
2613 smp_wmb(); /* see __commit_charge() */
ece35ca8
KH
2614 if (PageCgroupAcctLRU(head_pc)) {
2615 enum lru_list lru;
2616 struct mem_cgroup_per_zone *mz;
2617
2618 /*
2619 * LRU flags cannot be copied because we need to add tail
2620 *.page to LRU by generic call and our hook will be called.
2621 * We hold lru_lock, then, reduce counter directly.
2622 */
2623 lru = page_lru(head);
97a6c37b 2624 mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
ece35ca8
KH
2625 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
2626 }
ca3e0214
KH
2627 tail_pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2628 move_unlock_page_cgroup(head_pc, &flags);
2629}
2630#endif
2631
f817ed48 2632/**
de3638d9 2633 * mem_cgroup_move_account - move account of the page
5564e88b 2634 * @page: the page
7ec99d62 2635 * @nr_pages: number of regular pages (>1 for huge pages)
f817ed48
KH
2636 * @pc: page_cgroup of the page.
2637 * @from: mem_cgroup which the page is moved from.
2638 * @to: mem_cgroup which the page is moved to. @from != @to.
854ffa8d 2639 * @uncharge: whether we should call uncharge and css_put against @from.
f817ed48
KH
2640 *
2641 * The caller must confirm following.
08e552c6 2642 * - page is not on LRU (isolate_page() is useful.)
7ec99d62 2643 * - compound_lock is held when nr_pages > 1
f817ed48 2644 *
854ffa8d 2645 * This function doesn't do "charge" nor css_get to new cgroup. It should be
25985edc 2646 * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
854ffa8d
DN
2647 * true, this function does "uncharge" from old cgroup, but it doesn't if
2648 * @uncharge is false, so a caller should do "uncharge".
f817ed48 2649 */
7ec99d62
JW
2650static int mem_cgroup_move_account(struct page *page,
2651 unsigned int nr_pages,
2652 struct page_cgroup *pc,
2653 struct mem_cgroup *from,
2654 struct mem_cgroup *to,
2655 bool uncharge)
f817ed48 2656{
de3638d9
JW
2657 unsigned long flags;
2658 int ret;
987eba66 2659
f817ed48 2660 VM_BUG_ON(from == to);
5564e88b 2661 VM_BUG_ON(PageLRU(page));
de3638d9
JW
2662 /*
2663 * The page is isolated from LRU. So, collapse function
2664 * will not handle this page. But page splitting can happen.
2665 * Do this check under compound_page_lock(). The caller should
2666 * hold it.
2667 */
2668 ret = -EBUSY;
7ec99d62 2669 if (nr_pages > 1 && !PageTransHuge(page))
de3638d9
JW
2670 goto out;
2671
2672 lock_page_cgroup(pc);
2673
2674 ret = -EINVAL;
2675 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
2676 goto unlock;
2677
2678 move_lock_page_cgroup(pc, &flags);
f817ed48 2679
8725d541 2680 if (PageCgroupFileMapped(pc)) {
c62b1a3b
KH
2681 /* Update mapped_file data for mem_cgroup */
2682 preempt_disable();
2683 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2684 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2685 preempt_enable();
d69b042f 2686 }
987eba66 2687 mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
854ffa8d
DN
2688 if (uncharge)
2689 /* This is not "cancel", but cancel_charge does all we need. */
e7018b8d 2690 __mem_cgroup_cancel_charge(from, nr_pages);
d69b042f 2691
854ffa8d 2692 /* caller should have done css_get */
08e552c6 2693 pc->mem_cgroup = to;
987eba66 2694 mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
88703267
KH
2695 /*
2696 * We charges against "to" which may not have any tasks. Then, "to"
2697 * can be under rmdir(). But in current implementation, caller of
4ffef5fe 2698 * this function is just force_empty() and move charge, so it's
25985edc 2699 * guaranteed that "to" is never removed. So, we don't check rmdir
4ffef5fe 2700 * status here.
88703267 2701 */
de3638d9
JW
2702 move_unlock_page_cgroup(pc, &flags);
2703 ret = 0;
2704unlock:
57f9fd7d 2705 unlock_page_cgroup(pc);
d2265e6f
KH
2706 /*
2707 * check events
2708 */
5564e88b
JW
2709 memcg_check_events(to, page);
2710 memcg_check_events(from, page);
de3638d9 2711out:
f817ed48
KH
2712 return ret;
2713}
2714
2715/*
2716 * move charges to its parent.
2717 */
2718
5564e88b
JW
2719static int mem_cgroup_move_parent(struct page *page,
2720 struct page_cgroup *pc,
f817ed48
KH
2721 struct mem_cgroup *child,
2722 gfp_t gfp_mask)
2723{
2724 struct cgroup *cg = child->css.cgroup;
2725 struct cgroup *pcg = cg->parent;
2726 struct mem_cgroup *parent;
7ec99d62 2727 unsigned int nr_pages;
4be4489f 2728 unsigned long uninitialized_var(flags);
f817ed48
KH
2729 int ret;
2730
2731 /* Is ROOT ? */
2732 if (!pcg)
2733 return -EINVAL;
2734
57f9fd7d
DN
2735 ret = -EBUSY;
2736 if (!get_page_unless_zero(page))
2737 goto out;
2738 if (isolate_lru_page(page))
2739 goto put;
52dbb905 2740
7ec99d62 2741 nr_pages = hpage_nr_pages(page);
08e552c6 2742
f817ed48 2743 parent = mem_cgroup_from_cont(pcg);
7ec99d62 2744 ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false);
a636b327 2745 if (ret || !parent)
57f9fd7d 2746 goto put_back;
f817ed48 2747
7ec99d62 2748 if (nr_pages > 1)
987eba66
KH
2749 flags = compound_lock_irqsave(page);
2750
7ec99d62 2751 ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true);
854ffa8d 2752 if (ret)
7ec99d62 2753 __mem_cgroup_cancel_charge(parent, nr_pages);
8dba474f 2754
7ec99d62 2755 if (nr_pages > 1)
987eba66 2756 compound_unlock_irqrestore(page, flags);
8dba474f 2757put_back:
08e552c6 2758 putback_lru_page(page);
57f9fd7d 2759put:
40d58138 2760 put_page(page);
57f9fd7d 2761out:
f817ed48
KH
2762 return ret;
2763}
2764
7a81b88c
KH
2765/*
2766 * Charge the memory controller for page usage.
2767 * Return
2768 * 0 if the charge was successful
2769 * < 0 if the cgroup is over its limit
2770 */
2771static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
73045c47 2772 gfp_t gfp_mask, enum charge_type ctype)
7a81b88c 2773{
c0ff4b85 2774 struct mem_cgroup *memcg = NULL;
7ec99d62 2775 unsigned int nr_pages = 1;
7a81b88c 2776 struct page_cgroup *pc;
8493ae43 2777 bool oom = true;
7a81b88c 2778 int ret;
ec168510 2779
37c2ac78 2780 if (PageTransHuge(page)) {
7ec99d62 2781 nr_pages <<= compound_order(page);
37c2ac78 2782 VM_BUG_ON(!PageTransHuge(page));
8493ae43
JW
2783 /*
2784 * Never OOM-kill a process for a huge page. The
2785 * fault handler will fall back to regular pages.
2786 */
2787 oom = false;
37c2ac78 2788 }
7a81b88c
KH
2789
2790 pc = lookup_page_cgroup(page);
af4a6621 2791 BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
7a81b88c 2792
c0ff4b85
R
2793 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
2794 if (ret || !memcg)
7a81b88c
KH
2795 return ret;
2796
c0ff4b85 2797 __mem_cgroup_commit_charge(memcg, page, nr_pages, pc, ctype);
8a9f3ccd 2798 return 0;
8a9f3ccd
BS
2799}
2800
7a81b88c
KH
2801int mem_cgroup_newpage_charge(struct page *page,
2802 struct mm_struct *mm, gfp_t gfp_mask)
217bc319 2803{
f8d66542 2804 if (mem_cgroup_disabled())
cede86ac 2805 return 0;
69029cd5
KH
2806 /*
2807 * If already mapped, we don't have to account.
2808 * If page cache, page->mapping has address_space.
2809 * But page->mapping may have out-of-use anon_vma pointer,
2810 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2811 * is NULL.
2812 */
2813 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
2814 return 0;
2815 if (unlikely(!mm))
2816 mm = &init_mm;
217bc319 2817 return mem_cgroup_charge_common(page, mm, gfp_mask,
73045c47 2818 MEM_CGROUP_CHARGE_TYPE_MAPPED);
217bc319
KH
2819}
2820
83aae4c7
DN
2821static void
2822__mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2823 enum charge_type ctype);
2824
5a6475a4 2825static void
c0ff4b85 2826__mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *memcg,
5a6475a4
KH
2827 enum charge_type ctype)
2828{
2829 struct page_cgroup *pc = lookup_page_cgroup(page);
2830 /*
2831 * In some case, SwapCache, FUSE(splice_buf->radixtree), the page
2832 * is already on LRU. It means the page may on some other page_cgroup's
2833 * LRU. Take care of it.
2834 */
2835 mem_cgroup_lru_del_before_commit(page);
c0ff4b85 2836 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
5a6475a4
KH
2837 mem_cgroup_lru_add_after_commit(page);
2838 return;
2839}
2840
e1a1cd59
BS
2841int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2842 gfp_t gfp_mask)
8697d331 2843{
c0ff4b85 2844 struct mem_cgroup *memcg = NULL;
b5a84319
KH
2845 int ret;
2846
f8d66542 2847 if (mem_cgroup_disabled())
cede86ac 2848 return 0;
52d4b9ac
KH
2849 if (PageCompound(page))
2850 return 0;
accf163e 2851
73045c47 2852 if (unlikely(!mm))
8697d331 2853 mm = &init_mm;
accf163e 2854
5a6475a4 2855 if (page_is_file_cache(page)) {
c0ff4b85
R
2856 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, &memcg, true);
2857 if (ret || !memcg)
5a6475a4 2858 return ret;
b5a84319 2859
5a6475a4
KH
2860 /*
2861 * FUSE reuses pages without going through the final
2862 * put that would remove them from the LRU list, make
2863 * sure that they get relinked properly.
2864 */
c0ff4b85 2865 __mem_cgroup_commit_charge_lrucare(page, memcg,
5a6475a4
KH
2866 MEM_CGROUP_CHARGE_TYPE_CACHE);
2867 return ret;
2868 }
83aae4c7
DN
2869 /* shmem */
2870 if (PageSwapCache(page)) {
c0ff4b85 2871 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &memcg);
83aae4c7 2872 if (!ret)
c0ff4b85 2873 __mem_cgroup_commit_charge_swapin(page, memcg,
83aae4c7
DN
2874 MEM_CGROUP_CHARGE_TYPE_SHMEM);
2875 } else
2876 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
73045c47 2877 MEM_CGROUP_CHARGE_TYPE_SHMEM);
b5a84319 2878
b5a84319 2879 return ret;
e8589cc1
KH
2880}
2881
54595fe2
KH
2882/*
2883 * While swap-in, try_charge -> commit or cancel, the page is locked.
2884 * And when try_charge() successfully returns, one refcnt to memcg without
21ae2956 2885 * struct page_cgroup is acquired. This refcnt will be consumed by
54595fe2
KH
2886 * "commit()" or removed by "cancel()"
2887 */
8c7c6e34
KH
2888int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
2889 struct page *page,
2890 gfp_t mask, struct mem_cgroup **ptr)
2891{
c0ff4b85 2892 struct mem_cgroup *memcg;
54595fe2 2893 int ret;
8c7c6e34 2894
56039efa
KH
2895 *ptr = NULL;
2896
f8d66542 2897 if (mem_cgroup_disabled())
8c7c6e34
KH
2898 return 0;
2899
2900 if (!do_swap_account)
2901 goto charge_cur_mm;
8c7c6e34
KH
2902 /*
2903 * A racing thread's fault, or swapoff, may have already updated
407f9c8b
HD
2904 * the pte, and even removed page from swap cache: in those cases
2905 * do_swap_page()'s pte_same() test will fail; but there's also a
2906 * KSM case which does need to charge the page.
8c7c6e34
KH
2907 */
2908 if (!PageSwapCache(page))
407f9c8b 2909 goto charge_cur_mm;
c0ff4b85
R
2910 memcg = try_get_mem_cgroup_from_page(page);
2911 if (!memcg)
54595fe2 2912 goto charge_cur_mm;
c0ff4b85 2913 *ptr = memcg;
7ec99d62 2914 ret = __mem_cgroup_try_charge(NULL, mask, 1, ptr, true);
c0ff4b85 2915 css_put(&memcg->css);
54595fe2 2916 return ret;
8c7c6e34
KH
2917charge_cur_mm:
2918 if (unlikely(!mm))
2919 mm = &init_mm;
7ec99d62 2920 return __mem_cgroup_try_charge(mm, mask, 1, ptr, true);
8c7c6e34
KH
2921}
2922
83aae4c7
DN
2923static void
2924__mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2925 enum charge_type ctype)
7a81b88c 2926{
f8d66542 2927 if (mem_cgroup_disabled())
7a81b88c
KH
2928 return;
2929 if (!ptr)
2930 return;
88703267 2931 cgroup_exclude_rmdir(&ptr->css);
5a6475a4
KH
2932
2933 __mem_cgroup_commit_charge_lrucare(page, ptr, ctype);
8c7c6e34
KH
2934 /*
2935 * Now swap is on-memory. This means this page may be
2936 * counted both as mem and swap....double count.
03f3c433
KH
2937 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2938 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2939 * may call delete_from_swap_cache() before reach here.
8c7c6e34 2940 */
03f3c433 2941 if (do_swap_account && PageSwapCache(page)) {
8c7c6e34 2942 swp_entry_t ent = {.val = page_private(page)};
a3b2d692 2943 unsigned short id;
8c7c6e34 2944 struct mem_cgroup *memcg;
a3b2d692
KH
2945
2946 id = swap_cgroup_record(ent, 0);
2947 rcu_read_lock();
2948 memcg = mem_cgroup_lookup(id);
8c7c6e34 2949 if (memcg) {
a3b2d692
KH
2950 /*
2951 * This recorded memcg can be obsolete one. So, avoid
2952 * calling css_tryget
2953 */
0c3e73e8 2954 if (!mem_cgroup_is_root(memcg))
4e649152 2955 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
0c3e73e8 2956 mem_cgroup_swap_statistics(memcg, false);
8c7c6e34
KH
2957 mem_cgroup_put(memcg);
2958 }
a3b2d692 2959 rcu_read_unlock();
8c7c6e34 2960 }
88703267
KH
2961 /*
2962 * At swapin, we may charge account against cgroup which has no tasks.
2963 * So, rmdir()->pre_destroy() can be called while we do this charge.
2964 * In that case, we need to call pre_destroy() again. check it here.
2965 */
2966 cgroup_release_and_wakeup_rmdir(&ptr->css);
7a81b88c
KH
2967}
2968
83aae4c7
DN
2969void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2970{
2971 __mem_cgroup_commit_charge_swapin(page, ptr,
2972 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2973}
2974
c0ff4b85 2975void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
7a81b88c 2976{
f8d66542 2977 if (mem_cgroup_disabled())
7a81b88c 2978 return;
c0ff4b85 2979 if (!memcg)
7a81b88c 2980 return;
c0ff4b85 2981 __mem_cgroup_cancel_charge(memcg, 1);
7a81b88c
KH
2982}
2983
c0ff4b85 2984static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
7ec99d62
JW
2985 unsigned int nr_pages,
2986 const enum charge_type ctype)
569b846d
KH
2987{
2988 struct memcg_batch_info *batch = NULL;
2989 bool uncharge_memsw = true;
7ec99d62 2990
569b846d
KH
2991 /* If swapout, usage of swap doesn't decrease */
2992 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2993 uncharge_memsw = false;
569b846d
KH
2994
2995 batch = &current->memcg_batch;
2996 /*
2997 * In usual, we do css_get() when we remember memcg pointer.
2998 * But in this case, we keep res->usage until end of a series of
2999 * uncharges. Then, it's ok to ignore memcg's refcnt.
3000 */
3001 if (!batch->memcg)
c0ff4b85 3002 batch->memcg = memcg;
3c11ecf4
KH
3003 /*
3004 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
25985edc 3005 * In those cases, all pages freed continuously can be expected to be in
3c11ecf4
KH
3006 * the same cgroup and we have chance to coalesce uncharges.
3007 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
3008 * because we want to do uncharge as soon as possible.
3009 */
3010
3011 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
3012 goto direct_uncharge;
3013
7ec99d62 3014 if (nr_pages > 1)
ec168510
AA
3015 goto direct_uncharge;
3016
569b846d
KH
3017 /*
3018 * In typical case, batch->memcg == mem. This means we can
3019 * merge a series of uncharges to an uncharge of res_counter.
3020 * If not, we uncharge res_counter ony by one.
3021 */
c0ff4b85 3022 if (batch->memcg != memcg)
569b846d
KH
3023 goto direct_uncharge;
3024 /* remember freed charge and uncharge it later */
7ffd4ca7 3025 batch->nr_pages++;
569b846d 3026 if (uncharge_memsw)
7ffd4ca7 3027 batch->memsw_nr_pages++;
569b846d
KH
3028 return;
3029direct_uncharge:
c0ff4b85 3030 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE);
569b846d 3031 if (uncharge_memsw)
c0ff4b85
R
3032 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE);
3033 if (unlikely(batch->memcg != memcg))
3034 memcg_oom_recover(memcg);
569b846d
KH
3035 return;
3036}
7a81b88c 3037
8a9f3ccd 3038/*
69029cd5 3039 * uncharge if !page_mapped(page)
8a9f3ccd 3040 */
8c7c6e34 3041static struct mem_cgroup *
69029cd5 3042__mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
8a9f3ccd 3043{
c0ff4b85 3044 struct mem_cgroup *memcg = NULL;
7ec99d62
JW
3045 unsigned int nr_pages = 1;
3046 struct page_cgroup *pc;
8a9f3ccd 3047
f8d66542 3048 if (mem_cgroup_disabled())
8c7c6e34 3049 return NULL;
4077960e 3050
d13d1443 3051 if (PageSwapCache(page))
8c7c6e34 3052 return NULL;
d13d1443 3053
37c2ac78 3054 if (PageTransHuge(page)) {
7ec99d62 3055 nr_pages <<= compound_order(page);
37c2ac78
AA
3056 VM_BUG_ON(!PageTransHuge(page));
3057 }
8697d331 3058 /*
3c541e14 3059 * Check if our page_cgroup is valid
8697d331 3060 */
52d4b9ac
KH
3061 pc = lookup_page_cgroup(page);
3062 if (unlikely(!pc || !PageCgroupUsed(pc)))
8c7c6e34 3063 return NULL;
b9c565d5 3064
52d4b9ac 3065 lock_page_cgroup(pc);
d13d1443 3066
c0ff4b85 3067 memcg = pc->mem_cgroup;
8c7c6e34 3068
d13d1443
KH
3069 if (!PageCgroupUsed(pc))
3070 goto unlock_out;
3071
3072 switch (ctype) {
3073 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
8a9478ca 3074 case MEM_CGROUP_CHARGE_TYPE_DROP:
ac39cf8c
AM
3075 /* See mem_cgroup_prepare_migration() */
3076 if (page_mapped(page) || PageCgroupMigration(pc))
d13d1443
KH
3077 goto unlock_out;
3078 break;
3079 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
3080 if (!PageAnon(page)) { /* Shared memory */
3081 if (page->mapping && !page_is_file_cache(page))
3082 goto unlock_out;
3083 } else if (page_mapped(page)) /* Anon */
3084 goto unlock_out;
3085 break;
3086 default:
3087 break;
52d4b9ac 3088 }
d13d1443 3089
c0ff4b85 3090 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), -nr_pages);
04046e1a 3091
52d4b9ac 3092 ClearPageCgroupUsed(pc);
544122e5
KH
3093 /*
3094 * pc->mem_cgroup is not cleared here. It will be accessed when it's
3095 * freed from LRU. This is safe because uncharged page is expected not
3096 * to be reused (freed soon). Exception is SwapCache, it's handled by
3097 * special functions.
3098 */
b9c565d5 3099
52d4b9ac 3100 unlock_page_cgroup(pc);
f75ca962 3101 /*
c0ff4b85 3102 * even after unlock, we have memcg->res.usage here and this memcg
f75ca962
KH
3103 * will never be freed.
3104 */
c0ff4b85 3105 memcg_check_events(memcg, page);
f75ca962 3106 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
c0ff4b85
R
3107 mem_cgroup_swap_statistics(memcg, true);
3108 mem_cgroup_get(memcg);
f75ca962 3109 }
c0ff4b85
R
3110 if (!mem_cgroup_is_root(memcg))
3111 mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
6d12e2d8 3112
c0ff4b85 3113 return memcg;
d13d1443
KH
3114
3115unlock_out:
3116 unlock_page_cgroup(pc);
8c7c6e34 3117 return NULL;
3c541e14
BS
3118}
3119
69029cd5
KH
3120void mem_cgroup_uncharge_page(struct page *page)
3121{
52d4b9ac
KH
3122 /* early check. */
3123 if (page_mapped(page))
3124 return;
3125 if (page->mapping && !PageAnon(page))
3126 return;
69029cd5
KH
3127 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
3128}
3129
3130void mem_cgroup_uncharge_cache_page(struct page *page)
3131{
3132 VM_BUG_ON(page_mapped(page));
b7abea96 3133 VM_BUG_ON(page->mapping);
69029cd5
KH
3134 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
3135}
3136
569b846d
KH
3137/*
3138 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3139 * In that cases, pages are freed continuously and we can expect pages
3140 * are in the same memcg. All these calls itself limits the number of
3141 * pages freed at once, then uncharge_start/end() is called properly.
3142 * This may be called prural(2) times in a context,
3143 */
3144
3145void mem_cgroup_uncharge_start(void)
3146{
3147 current->memcg_batch.do_batch++;
3148 /* We can do nest. */
3149 if (current->memcg_batch.do_batch == 1) {
3150 current->memcg_batch.memcg = NULL;
7ffd4ca7
JW
3151 current->memcg_batch.nr_pages = 0;
3152 current->memcg_batch.memsw_nr_pages = 0;
569b846d
KH
3153 }
3154}
3155
3156void mem_cgroup_uncharge_end(void)
3157{
3158 struct memcg_batch_info *batch = &current->memcg_batch;
3159
3160 if (!batch->do_batch)
3161 return;
3162
3163 batch->do_batch--;
3164 if (batch->do_batch) /* If stacked, do nothing. */
3165 return;
3166
3167 if (!batch->memcg)
3168 return;
3169 /*
3170 * This "batch->memcg" is valid without any css_get/put etc...
3171 * bacause we hide charges behind us.
3172 */
7ffd4ca7
JW
3173 if (batch->nr_pages)
3174 res_counter_uncharge(&batch->memcg->res,
3175 batch->nr_pages * PAGE_SIZE);
3176 if (batch->memsw_nr_pages)
3177 res_counter_uncharge(&batch->memcg->memsw,
3178 batch->memsw_nr_pages * PAGE_SIZE);
3c11ecf4 3179 memcg_oom_recover(batch->memcg);
569b846d
KH
3180 /* forget this pointer (for sanity check) */
3181 batch->memcg = NULL;
3182}
3183
e767e056 3184#ifdef CONFIG_SWAP
8c7c6e34 3185/*
e767e056 3186 * called after __delete_from_swap_cache() and drop "page" account.
8c7c6e34
KH
3187 * memcg information is recorded to swap_cgroup of "ent"
3188 */
8a9478ca
KH
3189void
3190mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
8c7c6e34
KH
3191{
3192 struct mem_cgroup *memcg;
8a9478ca
KH
3193 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
3194
3195 if (!swapout) /* this was a swap cache but the swap is unused ! */
3196 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
3197
3198 memcg = __mem_cgroup_uncharge_common(page, ctype);
8c7c6e34 3199
f75ca962
KH
3200 /*
3201 * record memcg information, if swapout && memcg != NULL,
3202 * mem_cgroup_get() was called in uncharge().
3203 */
3204 if (do_swap_account && swapout && memcg)
a3b2d692 3205 swap_cgroup_record(ent, css_id(&memcg->css));
8c7c6e34 3206}
e767e056 3207#endif
8c7c6e34
KH
3208
3209#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3210/*
3211 * called from swap_entry_free(). remove record in swap_cgroup and
3212 * uncharge "memsw" account.
3213 */
3214void mem_cgroup_uncharge_swap(swp_entry_t ent)
d13d1443 3215{
8c7c6e34 3216 struct mem_cgroup *memcg;
a3b2d692 3217 unsigned short id;
8c7c6e34
KH
3218
3219 if (!do_swap_account)
3220 return;
3221
a3b2d692
KH
3222 id = swap_cgroup_record(ent, 0);
3223 rcu_read_lock();
3224 memcg = mem_cgroup_lookup(id);
8c7c6e34 3225 if (memcg) {
a3b2d692
KH
3226 /*
3227 * We uncharge this because swap is freed.
3228 * This memcg can be obsolete one. We avoid calling css_tryget
3229 */
0c3e73e8 3230 if (!mem_cgroup_is_root(memcg))
4e649152 3231 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
0c3e73e8 3232 mem_cgroup_swap_statistics(memcg, false);
8c7c6e34
KH
3233 mem_cgroup_put(memcg);
3234 }
a3b2d692 3235 rcu_read_unlock();
d13d1443 3236}
02491447
DN
3237
3238/**
3239 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3240 * @entry: swap entry to be moved
3241 * @from: mem_cgroup which the entry is moved from
3242 * @to: mem_cgroup which the entry is moved to
483c30b5 3243 * @need_fixup: whether we should fixup res_counters and refcounts.
02491447
DN
3244 *
3245 * It succeeds only when the swap_cgroup's record for this entry is the same
3246 * as the mem_cgroup's id of @from.
3247 *
3248 * Returns 0 on success, -EINVAL on failure.
3249 *
3250 * The caller must have charged to @to, IOW, called res_counter_charge() about
3251 * both res and memsw, and called css_get().
3252 */
3253static int mem_cgroup_move_swap_account(swp_entry_t entry,
483c30b5 3254 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
02491447
DN
3255{
3256 unsigned short old_id, new_id;
3257
3258 old_id = css_id(&from->css);
3259 new_id = css_id(&to->css);
3260
3261 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
02491447 3262 mem_cgroup_swap_statistics(from, false);
483c30b5 3263 mem_cgroup_swap_statistics(to, true);
02491447 3264 /*
483c30b5
DN
3265 * This function is only called from task migration context now.
3266 * It postpones res_counter and refcount handling till the end
3267 * of task migration(mem_cgroup_clear_mc()) for performance
3268 * improvement. But we cannot postpone mem_cgroup_get(to)
3269 * because if the process that has been moved to @to does
3270 * swap-in, the refcount of @to might be decreased to 0.
02491447 3271 */
02491447 3272 mem_cgroup_get(to);
483c30b5
DN
3273 if (need_fixup) {
3274 if (!mem_cgroup_is_root(from))
3275 res_counter_uncharge(&from->memsw, PAGE_SIZE);
3276 mem_cgroup_put(from);
3277 /*
3278 * we charged both to->res and to->memsw, so we should
3279 * uncharge to->res.
3280 */
3281 if (!mem_cgroup_is_root(to))
3282 res_counter_uncharge(&to->res, PAGE_SIZE);
483c30b5 3283 }
02491447
DN
3284 return 0;
3285 }
3286 return -EINVAL;
3287}
3288#else
3289static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
483c30b5 3290 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
02491447
DN
3291{
3292 return -EINVAL;
3293}
8c7c6e34 3294#endif
d13d1443 3295
ae41be37 3296/*
01b1ae63
KH
3297 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3298 * page belongs to.
ae41be37 3299 */
ac39cf8c 3300int mem_cgroup_prepare_migration(struct page *page,
ef6a3c63 3301 struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask)
ae41be37 3302{
c0ff4b85 3303 struct mem_cgroup *memcg = NULL;
7ec99d62 3304 struct page_cgroup *pc;
ac39cf8c 3305 enum charge_type ctype;
e8589cc1 3306 int ret = 0;
8869b8f6 3307
56039efa
KH
3308 *ptr = NULL;
3309
ec168510 3310 VM_BUG_ON(PageTransHuge(page));
f8d66542 3311 if (mem_cgroup_disabled())
4077960e
BS
3312 return 0;
3313
52d4b9ac
KH
3314 pc = lookup_page_cgroup(page);
3315 lock_page_cgroup(pc);
3316 if (PageCgroupUsed(pc)) {
c0ff4b85
R
3317 memcg = pc->mem_cgroup;
3318 css_get(&memcg->css);
ac39cf8c
AM
3319 /*
3320 * At migrating an anonymous page, its mapcount goes down
3321 * to 0 and uncharge() will be called. But, even if it's fully
3322 * unmapped, migration may fail and this page has to be
3323 * charged again. We set MIGRATION flag here and delay uncharge
3324 * until end_migration() is called
3325 *
3326 * Corner Case Thinking
3327 * A)
3328 * When the old page was mapped as Anon and it's unmap-and-freed
3329 * while migration was ongoing.
3330 * If unmap finds the old page, uncharge() of it will be delayed
3331 * until end_migration(). If unmap finds a new page, it's
3332 * uncharged when it make mapcount to be 1->0. If unmap code
3333 * finds swap_migration_entry, the new page will not be mapped
3334 * and end_migration() will find it(mapcount==0).
3335 *
3336 * B)
3337 * When the old page was mapped but migraion fails, the kernel
3338 * remaps it. A charge for it is kept by MIGRATION flag even
3339 * if mapcount goes down to 0. We can do remap successfully
3340 * without charging it again.
3341 *
3342 * C)
3343 * The "old" page is under lock_page() until the end of
3344 * migration, so, the old page itself will not be swapped-out.
3345 * If the new page is swapped out before end_migraton, our
3346 * hook to usual swap-out path will catch the event.
3347 */
3348 if (PageAnon(page))
3349 SetPageCgroupMigration(pc);
e8589cc1 3350 }
52d4b9ac 3351 unlock_page_cgroup(pc);
ac39cf8c
AM
3352 /*
3353 * If the page is not charged at this point,
3354 * we return here.
3355 */
c0ff4b85 3356 if (!memcg)
ac39cf8c 3357 return 0;
01b1ae63 3358
c0ff4b85 3359 *ptr = memcg;
7ec99d62 3360 ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, ptr, false);
c0ff4b85 3361 css_put(&memcg->css);/* drop extra refcnt */
ac39cf8c
AM
3362 if (ret || *ptr == NULL) {
3363 if (PageAnon(page)) {
3364 lock_page_cgroup(pc);
3365 ClearPageCgroupMigration(pc);
3366 unlock_page_cgroup(pc);
3367 /*
3368 * The old page may be fully unmapped while we kept it.
3369 */
3370 mem_cgroup_uncharge_page(page);
3371 }
3372 return -ENOMEM;
e8589cc1 3373 }
ac39cf8c
AM
3374 /*
3375 * We charge new page before it's used/mapped. So, even if unlock_page()
3376 * is called before end_migration, we can catch all events on this new
3377 * page. In the case new page is migrated but not remapped, new page's
3378 * mapcount will be finally 0 and we call uncharge in end_migration().
3379 */
3380 pc = lookup_page_cgroup(newpage);
3381 if (PageAnon(page))
3382 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
3383 else if (page_is_file_cache(page))
3384 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
3385 else
3386 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
c0ff4b85 3387 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
e8589cc1 3388 return ret;
ae41be37 3389}
8869b8f6 3390
69029cd5 3391/* remove redundant charge if migration failed*/
c0ff4b85 3392void mem_cgroup_end_migration(struct mem_cgroup *memcg,
50de1dd9 3393 struct page *oldpage, struct page *newpage, bool migration_ok)
ae41be37 3394{
ac39cf8c 3395 struct page *used, *unused;
01b1ae63 3396 struct page_cgroup *pc;
01b1ae63 3397
c0ff4b85 3398 if (!memcg)
01b1ae63 3399 return;
ac39cf8c 3400 /* blocks rmdir() */
c0ff4b85 3401 cgroup_exclude_rmdir(&memcg->css);
50de1dd9 3402 if (!migration_ok) {
ac39cf8c
AM
3403 used = oldpage;
3404 unused = newpage;
01b1ae63 3405 } else {
ac39cf8c 3406 used = newpage;
01b1ae63
KH
3407 unused = oldpage;
3408 }
69029cd5 3409 /*
ac39cf8c
AM
3410 * We disallowed uncharge of pages under migration because mapcount
3411 * of the page goes down to zero, temporarly.
3412 * Clear the flag and check the page should be charged.
01b1ae63 3413 */
ac39cf8c
AM
3414 pc = lookup_page_cgroup(oldpage);
3415 lock_page_cgroup(pc);
3416 ClearPageCgroupMigration(pc);
3417 unlock_page_cgroup(pc);
01b1ae63 3418
ac39cf8c
AM
3419 __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
3420
01b1ae63 3421 /*
ac39cf8c
AM
3422 * If a page is a file cache, radix-tree replacement is very atomic
3423 * and we can skip this check. When it was an Anon page, its mapcount
3424 * goes down to 0. But because we added MIGRATION flage, it's not
3425 * uncharged yet. There are several case but page->mapcount check
3426 * and USED bit check in mem_cgroup_uncharge_page() will do enough
3427 * check. (see prepare_charge() also)
69029cd5 3428 */
ac39cf8c
AM
3429 if (PageAnon(used))
3430 mem_cgroup_uncharge_page(used);
88703267 3431 /*
ac39cf8c
AM
3432 * At migration, we may charge account against cgroup which has no
3433 * tasks.
88703267
KH
3434 * So, rmdir()->pre_destroy() can be called while we do this charge.
3435 * In that case, we need to call pre_destroy() again. check it here.
3436 */
c0ff4b85 3437 cgroup_release_and_wakeup_rmdir(&memcg->css);
ae41be37 3438}
78fb7466 3439
f212ad7c
DN
3440#ifdef CONFIG_DEBUG_VM
3441static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3442{
3443 struct page_cgroup *pc;
3444
3445 pc = lookup_page_cgroup(page);
3446 if (likely(pc) && PageCgroupUsed(pc))
3447 return pc;
3448 return NULL;
3449}
3450
3451bool mem_cgroup_bad_page_check(struct page *page)
3452{
3453 if (mem_cgroup_disabled())
3454 return false;
3455
3456 return lookup_page_cgroup_used(page) != NULL;
3457}
3458
3459void mem_cgroup_print_bad_page(struct page *page)
3460{
3461 struct page_cgroup *pc;
3462
3463 pc = lookup_page_cgroup_used(page);
3464 if (pc) {
3465 int ret = -1;
3466 char *path;
3467
3468 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p",
3469 pc, pc->flags, pc->mem_cgroup);
3470
3471 path = kmalloc(PATH_MAX, GFP_KERNEL);
3472 if (path) {
3473 rcu_read_lock();
3474 ret = cgroup_path(pc->mem_cgroup->css.cgroup,
3475 path, PATH_MAX);
3476 rcu_read_unlock();
3477 }
3478
3479 printk(KERN_CONT "(%s)\n",
3480 (ret < 0) ? "cannot get the path" : path);
3481 kfree(path);
3482 }
3483}
3484#endif
3485
8c7c6e34
KH
3486static DEFINE_MUTEX(set_limit_mutex);
3487
d38d2a75 3488static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
8c7c6e34 3489 unsigned long long val)
628f4235 3490{
81d39c20 3491 int retry_count;
3c11ecf4 3492 u64 memswlimit, memlimit;
628f4235 3493 int ret = 0;
81d39c20
KH
3494 int children = mem_cgroup_count_children(memcg);
3495 u64 curusage, oldusage;
3c11ecf4 3496 int enlarge;
81d39c20
KH
3497
3498 /*
3499 * For keeping hierarchical_reclaim simple, how long we should retry
3500 * is depends on callers. We set our retry-count to be function
3501 * of # of children which we should visit in this loop.
3502 */
3503 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
3504
3505 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
628f4235 3506
3c11ecf4 3507 enlarge = 0;
8c7c6e34 3508 while (retry_count) {
628f4235
KH
3509 if (signal_pending(current)) {
3510 ret = -EINTR;
3511 break;
3512 }
8c7c6e34
KH
3513 /*
3514 * Rather than hide all in some function, I do this in
3515 * open coded manner. You see what this really does.
c0ff4b85 3516 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
8c7c6e34
KH
3517 */
3518 mutex_lock(&set_limit_mutex);
3519 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3520 if (memswlimit < val) {
3521 ret = -EINVAL;
3522 mutex_unlock(&set_limit_mutex);
628f4235
KH
3523 break;
3524 }
3c11ecf4
KH
3525
3526 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3527 if (memlimit < val)
3528 enlarge = 1;
3529
8c7c6e34 3530 ret = res_counter_set_limit(&memcg->res, val);
22a668d7
KH
3531 if (!ret) {
3532 if (memswlimit == val)
3533 memcg->memsw_is_minimum = true;
3534 else
3535 memcg->memsw_is_minimum = false;
3536 }
8c7c6e34
KH
3537 mutex_unlock(&set_limit_mutex);
3538
3539 if (!ret)
3540 break;
3541
aa20d489 3542 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
0ae5e89c
YH
3543 MEM_CGROUP_RECLAIM_SHRINK,
3544 NULL);
81d39c20
KH
3545 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3546 /* Usage is reduced ? */
3547 if (curusage >= oldusage)
3548 retry_count--;
3549 else
3550 oldusage = curusage;
8c7c6e34 3551 }
3c11ecf4
KH
3552 if (!ret && enlarge)
3553 memcg_oom_recover(memcg);
14797e23 3554
8c7c6e34
KH
3555 return ret;
3556}
3557
338c8431
LZ
3558static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3559 unsigned long long val)
8c7c6e34 3560{
81d39c20 3561 int retry_count;
3c11ecf4 3562 u64 memlimit, memswlimit, oldusage, curusage;
81d39c20
KH
3563 int children = mem_cgroup_count_children(memcg);
3564 int ret = -EBUSY;
3c11ecf4 3565 int enlarge = 0;
8c7c6e34 3566
81d39c20
KH
3567 /* see mem_cgroup_resize_res_limit */
3568 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
3569 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
8c7c6e34
KH
3570 while (retry_count) {
3571 if (signal_pending(current)) {
3572 ret = -EINTR;
3573 break;
3574 }
3575 /*
3576 * Rather than hide all in some function, I do this in
3577 * open coded manner. You see what this really does.
c0ff4b85 3578 * We have to guarantee memcg->res.limit < memcg->memsw.limit.
8c7c6e34
KH
3579 */
3580 mutex_lock(&set_limit_mutex);
3581 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3582 if (memlimit > val) {
3583 ret = -EINVAL;
3584 mutex_unlock(&set_limit_mutex);
3585 break;
3586 }
3c11ecf4
KH
3587 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3588 if (memswlimit < val)
3589 enlarge = 1;
8c7c6e34 3590 ret = res_counter_set_limit(&memcg->memsw, val);
22a668d7
KH
3591 if (!ret) {
3592 if (memlimit == val)
3593 memcg->memsw_is_minimum = true;
3594 else
3595 memcg->memsw_is_minimum = false;
3596 }
8c7c6e34
KH
3597 mutex_unlock(&set_limit_mutex);
3598
3599 if (!ret)
3600 break;
3601
4e416953 3602 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
75822b44 3603 MEM_CGROUP_RECLAIM_NOSWAP |
0ae5e89c
YH
3604 MEM_CGROUP_RECLAIM_SHRINK,
3605 NULL);
8c7c6e34 3606 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
81d39c20 3607 /* Usage is reduced ? */
8c7c6e34 3608 if (curusage >= oldusage)
628f4235 3609 retry_count--;
81d39c20
KH
3610 else
3611 oldusage = curusage;
628f4235 3612 }
3c11ecf4
KH
3613 if (!ret && enlarge)
3614 memcg_oom_recover(memcg);
628f4235
KH
3615 return ret;
3616}
3617
4e416953 3618unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
0ae5e89c
YH
3619 gfp_t gfp_mask,
3620 unsigned long *total_scanned)
4e416953
BS
3621{
3622 unsigned long nr_reclaimed = 0;
3623 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3624 unsigned long reclaimed;
3625 int loop = 0;
3626 struct mem_cgroup_tree_per_zone *mctz;
ef8745c1 3627 unsigned long long excess;
0ae5e89c 3628 unsigned long nr_scanned;
4e416953
BS
3629
3630 if (order > 0)
3631 return 0;
3632
00918b6a 3633 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
4e416953
BS
3634 /*
3635 * This loop can run a while, specially if mem_cgroup's continuously
3636 * keep exceeding their soft limit and putting the system under
3637 * pressure
3638 */
3639 do {
3640 if (next_mz)
3641 mz = next_mz;
3642 else
3643 mz = mem_cgroup_largest_soft_limit_node(mctz);
3644 if (!mz)
3645 break;
3646
0ae5e89c 3647 nr_scanned = 0;
4e416953
BS
3648 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
3649 gfp_mask,
0ae5e89c
YH
3650 MEM_CGROUP_RECLAIM_SOFT,
3651 &nr_scanned);
4e416953 3652 nr_reclaimed += reclaimed;
0ae5e89c 3653 *total_scanned += nr_scanned;
4e416953
BS
3654 spin_lock(&mctz->lock);
3655
3656 /*
3657 * If we failed to reclaim anything from this memory cgroup
3658 * it is time to move on to the next cgroup
3659 */
3660 next_mz = NULL;
3661 if (!reclaimed) {
3662 do {
3663 /*
3664 * Loop until we find yet another one.
3665 *
3666 * By the time we get the soft_limit lock
3667 * again, someone might have aded the
3668 * group back on the RB tree. Iterate to
3669 * make sure we get a different mem.
3670 * mem_cgroup_largest_soft_limit_node returns
3671 * NULL if no other cgroup is present on
3672 * the tree
3673 */
3674 next_mz =
3675 __mem_cgroup_largest_soft_limit_node(mctz);
39cc98f1 3676 if (next_mz == mz)
4e416953 3677 css_put(&next_mz->mem->css);
39cc98f1 3678 else /* next_mz == NULL or other memcg */
4e416953
BS
3679 break;
3680 } while (1);
3681 }
4e416953 3682 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
ef8745c1 3683 excess = res_counter_soft_limit_excess(&mz->mem->res);
4e416953
BS
3684 /*
3685 * One school of thought says that we should not add
3686 * back the node to the tree if reclaim returns 0.
3687 * But our reclaim could return 0, simply because due
3688 * to priority we are exposing a smaller subset of
3689 * memory to reclaim from. Consider this as a longer
3690 * term TODO.
3691 */
ef8745c1
KH
3692 /* If excess == 0, no tree ops */
3693 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
4e416953
BS
3694 spin_unlock(&mctz->lock);
3695 css_put(&mz->mem->css);
3696 loop++;
3697 /*
3698 * Could not reclaim anything and there are no more
3699 * mem cgroups to try or we seem to be looping without
3700 * reclaiming anything.
3701 */
3702 if (!nr_reclaimed &&
3703 (next_mz == NULL ||
3704 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3705 break;
3706 } while (!nr_reclaimed);
3707 if (next_mz)
3708 css_put(&next_mz->mem->css);
3709 return nr_reclaimed;
3710}
3711
cc847582
KH
3712/*
3713 * This routine traverse page_cgroup in given list and drop them all.
cc847582
KH
3714 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
3715 */
c0ff4b85 3716static int mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
08e552c6 3717 int node, int zid, enum lru_list lru)
cc847582 3718{
08e552c6
KH
3719 struct zone *zone;
3720 struct mem_cgroup_per_zone *mz;
f817ed48 3721 struct page_cgroup *pc, *busy;
08e552c6 3722 unsigned long flags, loop;
072c56c1 3723 struct list_head *list;
f817ed48 3724 int ret = 0;
072c56c1 3725
08e552c6 3726 zone = &NODE_DATA(node)->node_zones[zid];
c0ff4b85 3727 mz = mem_cgroup_zoneinfo(memcg, node, zid);
b69408e8 3728 list = &mz->lists[lru];
cc847582 3729
f817ed48
KH
3730 loop = MEM_CGROUP_ZSTAT(mz, lru);
3731 /* give some margin against EBUSY etc...*/
3732 loop += 256;
3733 busy = NULL;
3734 while (loop--) {
5564e88b
JW
3735 struct page *page;
3736
f817ed48 3737 ret = 0;
08e552c6 3738 spin_lock_irqsave(&zone->lru_lock, flags);
f817ed48 3739 if (list_empty(list)) {
08e552c6 3740 spin_unlock_irqrestore(&zone->lru_lock, flags);
52d4b9ac 3741 break;
f817ed48
KH
3742 }
3743 pc = list_entry(list->prev, struct page_cgroup, lru);
3744 if (busy == pc) {
3745 list_move(&pc->lru, list);
648bcc77 3746 busy = NULL;
08e552c6 3747 spin_unlock_irqrestore(&zone->lru_lock, flags);
f817ed48
KH
3748 continue;
3749 }
08e552c6 3750 spin_unlock_irqrestore(&zone->lru_lock, flags);
f817ed48 3751
6b3ae58e 3752 page = lookup_cgroup_page(pc);
5564e88b 3753
c0ff4b85 3754 ret = mem_cgroup_move_parent(page, pc, memcg, GFP_KERNEL);
f817ed48 3755 if (ret == -ENOMEM)
52d4b9ac 3756 break;
f817ed48
KH
3757
3758 if (ret == -EBUSY || ret == -EINVAL) {
3759 /* found lock contention or "pc" is obsolete. */
3760 busy = pc;
3761 cond_resched();
3762 } else
3763 busy = NULL;
cc847582 3764 }
08e552c6 3765
f817ed48
KH
3766 if (!ret && !list_empty(list))
3767 return -EBUSY;
3768 return ret;
cc847582
KH
3769}
3770
3771/*
3772 * make mem_cgroup's charge to be 0 if there is no task.
3773 * This enables deleting this mem_cgroup.
3774 */
c0ff4b85 3775static int mem_cgroup_force_empty(struct mem_cgroup *memcg, bool free_all)
cc847582 3776{
f817ed48
KH
3777 int ret;
3778 int node, zid, shrink;
3779 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
c0ff4b85 3780 struct cgroup *cgrp = memcg->css.cgroup;
8869b8f6 3781
c0ff4b85 3782 css_get(&memcg->css);
f817ed48
KH
3783
3784 shrink = 0;
c1e862c1
KH
3785 /* should free all ? */
3786 if (free_all)
3787 goto try_to_free;
f817ed48 3788move_account:
fce66477 3789 do {
f817ed48 3790 ret = -EBUSY;
c1e862c1
KH
3791 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
3792 goto out;
3793 ret = -EINTR;
3794 if (signal_pending(current))
cc847582 3795 goto out;
52d4b9ac
KH
3796 /* This is for making all *used* pages to be on LRU. */
3797 lru_add_drain_all();
c0ff4b85 3798 drain_all_stock_sync(memcg);
f817ed48 3799 ret = 0;
c0ff4b85 3800 mem_cgroup_start_move(memcg);
299b4eaa 3801 for_each_node_state(node, N_HIGH_MEMORY) {
f817ed48 3802 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
b69408e8 3803 enum lru_list l;
f817ed48 3804 for_each_lru(l) {
c0ff4b85 3805 ret = mem_cgroup_force_empty_list(memcg,
08e552c6 3806 node, zid, l);
f817ed48
KH
3807 if (ret)
3808 break;
3809 }
1ecaab2b 3810 }
f817ed48
KH
3811 if (ret)
3812 break;
3813 }
c0ff4b85
R
3814 mem_cgroup_end_move(memcg);
3815 memcg_oom_recover(memcg);
f817ed48
KH
3816 /* it seems parent cgroup doesn't have enough mem */
3817 if (ret == -ENOMEM)
3818 goto try_to_free;
52d4b9ac 3819 cond_resched();
fce66477 3820 /* "ret" should also be checked to ensure all lists are empty. */
c0ff4b85 3821 } while (memcg->res.usage > 0 || ret);
cc847582 3822out:
c0ff4b85 3823 css_put(&memcg->css);
cc847582 3824 return ret;
f817ed48
KH
3825
3826try_to_free:
c1e862c1
KH
3827 /* returns EBUSY if there is a task or if we come here twice. */
3828 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
f817ed48
KH
3829 ret = -EBUSY;
3830 goto out;
3831 }
c1e862c1
KH
3832 /* we call try-to-free pages for make this cgroup empty */
3833 lru_add_drain_all();
f817ed48
KH
3834 /* try to free all pages in this cgroup */
3835 shrink = 1;
c0ff4b85 3836 while (nr_retries && memcg->res.usage > 0) {
f817ed48 3837 int progress;
c1e862c1
KH
3838
3839 if (signal_pending(current)) {
3840 ret = -EINTR;
3841 goto out;
3842 }
c0ff4b85 3843 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
185efc0f 3844 false);
c1e862c1 3845 if (!progress) {
f817ed48 3846 nr_retries--;
c1e862c1 3847 /* maybe some writeback is necessary */
8aa7e847 3848 congestion_wait(BLK_RW_ASYNC, HZ/10);
c1e862c1 3849 }
f817ed48
KH
3850
3851 }
08e552c6 3852 lru_add_drain();
f817ed48 3853 /* try move_account...there may be some *locked* pages. */
fce66477 3854 goto move_account;
cc847582
KH
3855}
3856
c1e862c1
KH
3857int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
3858{
3859 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
3860}
3861
3862
18f59ea7
BS
3863static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3864{
3865 return mem_cgroup_from_cont(cont)->use_hierarchy;
3866}
3867
3868static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
3869 u64 val)
3870{
3871 int retval = 0;
c0ff4b85 3872 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
18f59ea7 3873 struct cgroup *parent = cont->parent;
c0ff4b85 3874 struct mem_cgroup *parent_memcg = NULL;
18f59ea7
BS
3875
3876 if (parent)
c0ff4b85 3877 parent_memcg = mem_cgroup_from_cont(parent);
18f59ea7
BS
3878
3879 cgroup_lock();
3880 /*
af901ca1 3881 * If parent's use_hierarchy is set, we can't make any modifications
18f59ea7
BS
3882 * in the child subtrees. If it is unset, then the change can
3883 * occur, provided the current cgroup has no children.
3884 *
3885 * For the root cgroup, parent_mem is NULL, we allow value to be
3886 * set if there are no children.
3887 */
c0ff4b85 3888 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
18f59ea7
BS
3889 (val == 1 || val == 0)) {
3890 if (list_empty(&cont->children))
c0ff4b85 3891 memcg->use_hierarchy = val;
18f59ea7
BS
3892 else
3893 retval = -EBUSY;
3894 } else
3895 retval = -EINVAL;
3896 cgroup_unlock();
3897
3898 return retval;
3899}
3900
0c3e73e8 3901
c0ff4b85 3902static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg,
7a159cc9 3903 enum mem_cgroup_stat_index idx)
0c3e73e8 3904{
7d74b06f 3905 struct mem_cgroup *iter;
7a159cc9 3906 long val = 0;
0c3e73e8 3907
7a159cc9 3908 /* Per-cpu values can be negative, use a signed accumulator */
c0ff4b85 3909 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f
KH
3910 val += mem_cgroup_read_stat(iter, idx);
3911
3912 if (val < 0) /* race ? */
3913 val = 0;
3914 return val;
0c3e73e8
BS
3915}
3916
c0ff4b85 3917static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
104f3928 3918{
7d74b06f 3919 u64 val;
104f3928 3920
c0ff4b85 3921 if (!mem_cgroup_is_root(memcg)) {
e5671dfa
GC
3922 val = 0;
3923#ifdef CONFIG_CGROUP_MEM_RES_CTLR_KMEM
3924 if (!memcg->kmem_independent_accounting)
3925 val = res_counter_read_u64(&memcg->kmem, RES_USAGE);
3926#endif
104f3928 3927 if (!swap)
e5671dfa 3928 val += res_counter_read_u64(&memcg->res, RES_USAGE);
104f3928 3929 else
e5671dfa
GC
3930 val += res_counter_read_u64(&memcg->memsw, RES_USAGE);
3931
3932 return val;
104f3928
KS
3933 }
3934
c0ff4b85
R
3935 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE);
3936 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS);
104f3928 3937
7d74b06f 3938 if (swap)
c0ff4b85 3939 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
104f3928
KS
3940
3941 return val << PAGE_SHIFT;
3942}
3943
2c3daa72 3944static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
8cdea7c0 3945{
c0ff4b85 3946 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
104f3928 3947 u64 val;
8c7c6e34
KH
3948 int type, name;
3949
3950 type = MEMFILE_TYPE(cft->private);
3951 name = MEMFILE_ATTR(cft->private);
3952 switch (type) {
3953 case _MEM:
104f3928 3954 if (name == RES_USAGE)
c0ff4b85 3955 val = mem_cgroup_usage(memcg, false);
104f3928 3956 else
c0ff4b85 3957 val = res_counter_read_u64(&memcg->res, name);
8c7c6e34
KH
3958 break;
3959 case _MEMSWAP:
104f3928 3960 if (name == RES_USAGE)
c0ff4b85 3961 val = mem_cgroup_usage(memcg, true);
104f3928 3962 else
c0ff4b85 3963 val = res_counter_read_u64(&memcg->memsw, name);
8c7c6e34 3964 break;
e5671dfa
GC
3965#ifdef CONFIG_CGROUP_MEM_RES_CTLR_KMEM
3966 case _KMEM:
3967 val = res_counter_read_u64(&memcg->kmem, name);
3968 break;
3969#endif
8c7c6e34
KH
3970 default:
3971 BUG();
3972 break;
3973 }
3974 return val;
8cdea7c0 3975}
628f4235
KH
3976/*
3977 * The user of this function is...
3978 * RES_LIMIT.
3979 */
856c13aa
PM
3980static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
3981 const char *buffer)
8cdea7c0 3982{
628f4235 3983 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
8c7c6e34 3984 int type, name;
628f4235
KH
3985 unsigned long long val;
3986 int ret;
3987
8c7c6e34
KH
3988 type = MEMFILE_TYPE(cft->private);
3989 name = MEMFILE_ATTR(cft->private);
3990 switch (name) {
628f4235 3991 case RES_LIMIT:
4b3bde4c
BS
3992 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3993 ret = -EINVAL;
3994 break;
3995 }
628f4235
KH
3996 /* This function does all necessary parse...reuse it */
3997 ret = res_counter_memparse_write_strategy(buffer, &val);
8c7c6e34
KH
3998 if (ret)
3999 break;
4000 if (type == _MEM)
628f4235 4001 ret = mem_cgroup_resize_limit(memcg, val);
8c7c6e34
KH
4002 else
4003 ret = mem_cgroup_resize_memsw_limit(memcg, val);
628f4235 4004 break;
296c81d8
BS
4005 case RES_SOFT_LIMIT:
4006 ret = res_counter_memparse_write_strategy(buffer, &val);
4007 if (ret)
4008 break;
4009 /*
4010 * For memsw, soft limits are hard to implement in terms
4011 * of semantics, for now, we support soft limits for
4012 * control without swap
4013 */
4014 if (type == _MEM)
4015 ret = res_counter_set_soft_limit(&memcg->res, val);
4016 else
4017 ret = -EINVAL;
4018 break;
628f4235
KH
4019 default:
4020 ret = -EINVAL; /* should be BUG() ? */
4021 break;
4022 }
4023 return ret;
8cdea7c0
BS
4024}
4025
fee7b548
KH
4026static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
4027 unsigned long long *mem_limit, unsigned long long *memsw_limit)
4028{
4029 struct cgroup *cgroup;
4030 unsigned long long min_limit, min_memsw_limit, tmp;
4031
4032 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4033 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4034 cgroup = memcg->css.cgroup;
4035 if (!memcg->use_hierarchy)
4036 goto out;
4037
4038 while (cgroup->parent) {
4039 cgroup = cgroup->parent;
4040 memcg = mem_cgroup_from_cont(cgroup);
4041 if (!memcg->use_hierarchy)
4042 break;
4043 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
4044 min_limit = min(min_limit, tmp);
4045 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4046 min_memsw_limit = min(min_memsw_limit, tmp);
4047 }
4048out:
4049 *mem_limit = min_limit;
4050 *memsw_limit = min_memsw_limit;
4051 return;
4052}
4053
29f2a4da 4054static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
c84872e1 4055{
c0ff4b85 4056 struct mem_cgroup *memcg;
8c7c6e34 4057 int type, name;
c84872e1 4058
c0ff4b85 4059 memcg = mem_cgroup_from_cont(cont);
8c7c6e34
KH
4060 type = MEMFILE_TYPE(event);
4061 name = MEMFILE_ATTR(event);
4062 switch (name) {
29f2a4da 4063 case RES_MAX_USAGE:
8c7c6e34 4064 if (type == _MEM)
c0ff4b85 4065 res_counter_reset_max(&memcg->res);
8c7c6e34 4066 else
c0ff4b85 4067 res_counter_reset_max(&memcg->memsw);
29f2a4da
PE
4068 break;
4069 case RES_FAILCNT:
8c7c6e34 4070 if (type == _MEM)
c0ff4b85 4071 res_counter_reset_failcnt(&memcg->res);
8c7c6e34 4072 else
c0ff4b85 4073 res_counter_reset_failcnt(&memcg->memsw);
29f2a4da
PE
4074 break;
4075 }
f64c3f54 4076
85cc59db 4077 return 0;
c84872e1
PE
4078}
4079
7dc74be0
DN
4080static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
4081 struct cftype *cft)
4082{
4083 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
4084}
4085
02491447 4086#ifdef CONFIG_MMU
7dc74be0
DN
4087static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4088 struct cftype *cft, u64 val)
4089{
c0ff4b85 4090 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
7dc74be0
DN
4091
4092 if (val >= (1 << NR_MOVE_TYPE))
4093 return -EINVAL;
4094 /*
4095 * We check this value several times in both in can_attach() and
4096 * attach(), so we need cgroup lock to prevent this value from being
4097 * inconsistent.
4098 */
4099 cgroup_lock();
c0ff4b85 4100 memcg->move_charge_at_immigrate = val;
7dc74be0
DN
4101 cgroup_unlock();
4102
4103 return 0;
4104}
02491447
DN
4105#else
4106static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4107 struct cftype *cft, u64 val)
4108{
4109 return -ENOSYS;
4110}
4111#endif
7dc74be0 4112
14067bb3
KH
4113
4114/* For read statistics */
4115enum {
4116 MCS_CACHE,
4117 MCS_RSS,
d8046582 4118 MCS_FILE_MAPPED,
14067bb3
KH
4119 MCS_PGPGIN,
4120 MCS_PGPGOUT,
1dd3a273 4121 MCS_SWAP,
456f998e
YH
4122 MCS_PGFAULT,
4123 MCS_PGMAJFAULT,
14067bb3
KH
4124 MCS_INACTIVE_ANON,
4125 MCS_ACTIVE_ANON,
4126 MCS_INACTIVE_FILE,
4127 MCS_ACTIVE_FILE,
4128 MCS_UNEVICTABLE,
4129 NR_MCS_STAT,
4130};
4131
4132struct mcs_total_stat {
4133 s64 stat[NR_MCS_STAT];
d2ceb9b7
KH
4134};
4135
14067bb3
KH
4136struct {
4137 char *local_name;
4138 char *total_name;
4139} memcg_stat_strings[NR_MCS_STAT] = {
4140 {"cache", "total_cache"},
4141 {"rss", "total_rss"},
d69b042f 4142 {"mapped_file", "total_mapped_file"},
14067bb3
KH
4143 {"pgpgin", "total_pgpgin"},
4144 {"pgpgout", "total_pgpgout"},
1dd3a273 4145 {"swap", "total_swap"},
456f998e
YH
4146 {"pgfault", "total_pgfault"},
4147 {"pgmajfault", "total_pgmajfault"},
14067bb3
KH
4148 {"inactive_anon", "total_inactive_anon"},
4149 {"active_anon", "total_active_anon"},
4150 {"inactive_file", "total_inactive_file"},
4151 {"active_file", "total_active_file"},
4152 {"unevictable", "total_unevictable"}
4153};
4154
4155
7d74b06f 4156static void
c0ff4b85 4157mem_cgroup_get_local_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
14067bb3 4158{
14067bb3
KH
4159 s64 val;
4160
4161 /* per cpu stat */
c0ff4b85 4162 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_CACHE);
14067bb3 4163 s->stat[MCS_CACHE] += val * PAGE_SIZE;
c0ff4b85 4164 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_RSS);
14067bb3 4165 s->stat[MCS_RSS] += val * PAGE_SIZE;
c0ff4b85 4166 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_FILE_MAPPED);
d8046582 4167 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
c0ff4b85 4168 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGIN);
14067bb3 4169 s->stat[MCS_PGPGIN] += val;
c0ff4b85 4170 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGOUT);
14067bb3 4171 s->stat[MCS_PGPGOUT] += val;
1dd3a273 4172 if (do_swap_account) {
c0ff4b85 4173 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_SWAPOUT);
1dd3a273
DN
4174 s->stat[MCS_SWAP] += val * PAGE_SIZE;
4175 }
c0ff4b85 4176 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGFAULT);
456f998e 4177 s->stat[MCS_PGFAULT] += val;
c0ff4b85 4178 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGMAJFAULT);
456f998e 4179 s->stat[MCS_PGMAJFAULT] += val;
14067bb3
KH
4180
4181 /* per zone stat */
c0ff4b85 4182 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_ANON));
14067bb3 4183 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
c0ff4b85 4184 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_ANON));
14067bb3 4185 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
c0ff4b85 4186 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_FILE));
14067bb3 4187 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
c0ff4b85 4188 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_FILE));
14067bb3 4189 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
c0ff4b85 4190 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
14067bb3 4191 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
14067bb3
KH
4192}
4193
4194static void
c0ff4b85 4195mem_cgroup_get_total_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s)
14067bb3 4196{
7d74b06f
KH
4197 struct mem_cgroup *iter;
4198
c0ff4b85 4199 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f 4200 mem_cgroup_get_local_stat(iter, s);
14067bb3
KH
4201}
4202
406eb0c9
YH
4203#ifdef CONFIG_NUMA
4204static int mem_control_numa_stat_show(struct seq_file *m, void *arg)
4205{
4206 int nid;
4207 unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
4208 unsigned long node_nr;
4209 struct cgroup *cont = m->private;
4210 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4211
bb2a0de9 4212 total_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL);
406eb0c9
YH
4213 seq_printf(m, "total=%lu", total_nr);
4214 for_each_node_state(nid, N_HIGH_MEMORY) {
bb2a0de9 4215 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, LRU_ALL);
406eb0c9
YH
4216 seq_printf(m, " N%d=%lu", nid, node_nr);
4217 }
4218 seq_putc(m, '\n');
4219
bb2a0de9 4220 file_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_FILE);
406eb0c9
YH
4221 seq_printf(m, "file=%lu", file_nr);
4222 for_each_node_state(nid, N_HIGH_MEMORY) {
bb2a0de9
KH
4223 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4224 LRU_ALL_FILE);
406eb0c9
YH
4225 seq_printf(m, " N%d=%lu", nid, node_nr);
4226 }
4227 seq_putc(m, '\n');
4228
bb2a0de9 4229 anon_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_ANON);
406eb0c9
YH
4230 seq_printf(m, "anon=%lu", anon_nr);
4231 for_each_node_state(nid, N_HIGH_MEMORY) {
bb2a0de9
KH
4232 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4233 LRU_ALL_ANON);
406eb0c9
YH
4234 seq_printf(m, " N%d=%lu", nid, node_nr);
4235 }
4236 seq_putc(m, '\n');
4237
bb2a0de9 4238 unevictable_nr = mem_cgroup_nr_lru_pages(mem_cont, BIT(LRU_UNEVICTABLE));
406eb0c9
YH
4239 seq_printf(m, "unevictable=%lu", unevictable_nr);
4240 for_each_node_state(nid, N_HIGH_MEMORY) {
bb2a0de9
KH
4241 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4242 BIT(LRU_UNEVICTABLE));
406eb0c9
YH
4243 seq_printf(m, " N%d=%lu", nid, node_nr);
4244 }
4245 seq_putc(m, '\n');
4246 return 0;
4247}
4248#endif /* CONFIG_NUMA */
4249
c64745cf
PM
4250static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
4251 struct cgroup_map_cb *cb)
d2ceb9b7 4252{
d2ceb9b7 4253 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
14067bb3 4254 struct mcs_total_stat mystat;
d2ceb9b7
KH
4255 int i;
4256
14067bb3
KH
4257 memset(&mystat, 0, sizeof(mystat));
4258 mem_cgroup_get_local_stat(mem_cont, &mystat);
d2ceb9b7 4259
406eb0c9 4260
1dd3a273
DN
4261 for (i = 0; i < NR_MCS_STAT; i++) {
4262 if (i == MCS_SWAP && !do_swap_account)
4263 continue;
14067bb3 4264 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
1dd3a273 4265 }
7b854121 4266
14067bb3 4267 /* Hierarchical information */
fee7b548
KH
4268 {
4269 unsigned long long limit, memsw_limit;
4270 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
4271 cb->fill(cb, "hierarchical_memory_limit", limit);
4272 if (do_swap_account)
4273 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
4274 }
7f016ee8 4275
14067bb3
KH
4276 memset(&mystat, 0, sizeof(mystat));
4277 mem_cgroup_get_total_stat(mem_cont, &mystat);
1dd3a273
DN
4278 for (i = 0; i < NR_MCS_STAT; i++) {
4279 if (i == MCS_SWAP && !do_swap_account)
4280 continue;
14067bb3 4281 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
1dd3a273 4282 }
14067bb3 4283
7f016ee8 4284#ifdef CONFIG_DEBUG_VM
7f016ee8
KM
4285 {
4286 int nid, zid;
4287 struct mem_cgroup_per_zone *mz;
4288 unsigned long recent_rotated[2] = {0, 0};
4289 unsigned long recent_scanned[2] = {0, 0};
4290
4291 for_each_online_node(nid)
4292 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4293 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
4294
4295 recent_rotated[0] +=
4296 mz->reclaim_stat.recent_rotated[0];
4297 recent_rotated[1] +=
4298 mz->reclaim_stat.recent_rotated[1];
4299 recent_scanned[0] +=
4300 mz->reclaim_stat.recent_scanned[0];
4301 recent_scanned[1] +=
4302 mz->reclaim_stat.recent_scanned[1];
4303 }
4304 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
4305 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
4306 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
4307 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
4308 }
4309#endif
4310
d2ceb9b7
KH
4311 return 0;
4312}
4313
a7885eb8
KM
4314static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
4315{
4316 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4317
1f4c025b 4318 return mem_cgroup_swappiness(memcg);
a7885eb8
KM
4319}
4320
4321static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
4322 u64 val)
4323{
4324 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4325 struct mem_cgroup *parent;
068b38c1 4326
a7885eb8
KM
4327 if (val > 100)
4328 return -EINVAL;
4329
4330 if (cgrp->parent == NULL)
4331 return -EINVAL;
4332
4333 parent = mem_cgroup_from_cont(cgrp->parent);
068b38c1
LZ
4334
4335 cgroup_lock();
4336
a7885eb8
KM
4337 /* If under hierarchy, only empty-root can set this value */
4338 if ((parent->use_hierarchy) ||
068b38c1
LZ
4339 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4340 cgroup_unlock();
a7885eb8 4341 return -EINVAL;
068b38c1 4342 }
a7885eb8 4343
a7885eb8 4344 memcg->swappiness = val;
a7885eb8 4345
068b38c1
LZ
4346 cgroup_unlock();
4347
a7885eb8
KM
4348 return 0;
4349}
4350
2e72b634
KS
4351static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4352{
4353 struct mem_cgroup_threshold_ary *t;
4354 u64 usage;
4355 int i;
4356
4357 rcu_read_lock();
4358 if (!swap)
2c488db2 4359 t = rcu_dereference(memcg->thresholds.primary);
2e72b634 4360 else
2c488db2 4361 t = rcu_dereference(memcg->memsw_thresholds.primary);
2e72b634
KS
4362
4363 if (!t)
4364 goto unlock;
4365
4366 usage = mem_cgroup_usage(memcg, swap);
4367
4368 /*
4369 * current_threshold points to threshold just below usage.
4370 * If it's not true, a threshold was crossed after last
4371 * call of __mem_cgroup_threshold().
4372 */
5407a562 4373 i = t->current_threshold;
2e72b634
KS
4374
4375 /*
4376 * Iterate backward over array of thresholds starting from
4377 * current_threshold and check if a threshold is crossed.
4378 * If none of thresholds below usage is crossed, we read
4379 * only one element of the array here.
4380 */
4381 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4382 eventfd_signal(t->entries[i].eventfd, 1);
4383
4384 /* i = current_threshold + 1 */
4385 i++;
4386
4387 /*
4388 * Iterate forward over array of thresholds starting from
4389 * current_threshold+1 and check if a threshold is crossed.
4390 * If none of thresholds above usage is crossed, we read
4391 * only one element of the array here.
4392 */
4393 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4394 eventfd_signal(t->entries[i].eventfd, 1);
4395
4396 /* Update current_threshold */
5407a562 4397 t->current_threshold = i - 1;
2e72b634
KS
4398unlock:
4399 rcu_read_unlock();
4400}
4401
4402static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4403{
ad4ca5f4
KS
4404 while (memcg) {
4405 __mem_cgroup_threshold(memcg, false);
4406 if (do_swap_account)
4407 __mem_cgroup_threshold(memcg, true);
4408
4409 memcg = parent_mem_cgroup(memcg);
4410 }
2e72b634
KS
4411}
4412
4413static int compare_thresholds(const void *a, const void *b)
4414{
4415 const struct mem_cgroup_threshold *_a = a;
4416 const struct mem_cgroup_threshold *_b = b;
4417
4418 return _a->threshold - _b->threshold;
4419}
4420
c0ff4b85 4421static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
9490ff27
KH
4422{
4423 struct mem_cgroup_eventfd_list *ev;
4424
c0ff4b85 4425 list_for_each_entry(ev, &memcg->oom_notify, list)
9490ff27
KH
4426 eventfd_signal(ev->eventfd, 1);
4427 return 0;
4428}
4429
c0ff4b85 4430static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
9490ff27 4431{
7d74b06f
KH
4432 struct mem_cgroup *iter;
4433
c0ff4b85 4434 for_each_mem_cgroup_tree(iter, memcg)
7d74b06f 4435 mem_cgroup_oom_notify_cb(iter);
9490ff27
KH
4436}
4437
4438static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4439 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
2e72b634
KS
4440{
4441 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
2c488db2
KS
4442 struct mem_cgroup_thresholds *thresholds;
4443 struct mem_cgroup_threshold_ary *new;
2e72b634
KS
4444 int type = MEMFILE_TYPE(cft->private);
4445 u64 threshold, usage;
2c488db2 4446 int i, size, ret;
2e72b634
KS
4447
4448 ret = res_counter_memparse_write_strategy(args, &threshold);
4449 if (ret)
4450 return ret;
4451
4452 mutex_lock(&memcg->thresholds_lock);
2c488db2 4453
2e72b634 4454 if (type == _MEM)
2c488db2 4455 thresholds = &memcg->thresholds;
2e72b634 4456 else if (type == _MEMSWAP)
2c488db2 4457 thresholds = &memcg->memsw_thresholds;
2e72b634
KS
4458 else
4459 BUG();
4460
4461 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4462
4463 /* Check if a threshold crossed before adding a new one */
2c488db2 4464 if (thresholds->primary)
2e72b634
KS
4465 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4466
2c488db2 4467 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
2e72b634
KS
4468
4469 /* Allocate memory for new array of thresholds */
2c488db2 4470 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
2e72b634 4471 GFP_KERNEL);
2c488db2 4472 if (!new) {
2e72b634
KS
4473 ret = -ENOMEM;
4474 goto unlock;
4475 }
2c488db2 4476 new->size = size;
2e72b634
KS
4477
4478 /* Copy thresholds (if any) to new array */
2c488db2
KS
4479 if (thresholds->primary) {
4480 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
2e72b634 4481 sizeof(struct mem_cgroup_threshold));
2c488db2
KS
4482 }
4483
2e72b634 4484 /* Add new threshold */
2c488db2
KS
4485 new->entries[size - 1].eventfd = eventfd;
4486 new->entries[size - 1].threshold = threshold;
2e72b634
KS
4487
4488 /* Sort thresholds. Registering of new threshold isn't time-critical */
2c488db2 4489 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
2e72b634
KS
4490 compare_thresholds, NULL);
4491
4492 /* Find current threshold */
2c488db2 4493 new->current_threshold = -1;
2e72b634 4494 for (i = 0; i < size; i++) {
2c488db2 4495 if (new->entries[i].threshold < usage) {
2e72b634 4496 /*
2c488db2
KS
4497 * new->current_threshold will not be used until
4498 * rcu_assign_pointer(), so it's safe to increment
2e72b634
KS
4499 * it here.
4500 */
2c488db2 4501 ++new->current_threshold;
2e72b634
KS
4502 }
4503 }
4504
2c488db2
KS
4505 /* Free old spare buffer and save old primary buffer as spare */
4506 kfree(thresholds->spare);
4507 thresholds->spare = thresholds->primary;
4508
4509 rcu_assign_pointer(thresholds->primary, new);
2e72b634 4510
907860ed 4511 /* To be sure that nobody uses thresholds */
2e72b634
KS
4512 synchronize_rcu();
4513
2e72b634
KS
4514unlock:
4515 mutex_unlock(&memcg->thresholds_lock);
4516
4517 return ret;
4518}
4519
907860ed 4520static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
9490ff27 4521 struct cftype *cft, struct eventfd_ctx *eventfd)
2e72b634
KS
4522{
4523 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
2c488db2
KS
4524 struct mem_cgroup_thresholds *thresholds;
4525 struct mem_cgroup_threshold_ary *new;
2e72b634
KS
4526 int type = MEMFILE_TYPE(cft->private);
4527 u64 usage;
2c488db2 4528 int i, j, size;
2e72b634
KS
4529
4530 mutex_lock(&memcg->thresholds_lock);
4531 if (type == _MEM)
2c488db2 4532 thresholds = &memcg->thresholds;
2e72b634 4533 else if (type == _MEMSWAP)
2c488db2 4534 thresholds = &memcg->memsw_thresholds;
2e72b634
KS
4535 else
4536 BUG();
4537
4538 /*
4539 * Something went wrong if we trying to unregister a threshold
4540 * if we don't have thresholds
4541 */
4542 BUG_ON(!thresholds);
4543
4544 usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4545
4546 /* Check if a threshold crossed before removing */
4547 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4548
4549 /* Calculate new number of threshold */
2c488db2
KS
4550 size = 0;
4551 for (i = 0; i < thresholds->primary->size; i++) {
4552 if (thresholds->primary->entries[i].eventfd != eventfd)
2e72b634
KS
4553 size++;
4554 }
4555
2c488db2 4556 new = thresholds->spare;
907860ed 4557
2e72b634
KS
4558 /* Set thresholds array to NULL if we don't have thresholds */
4559 if (!size) {
2c488db2
KS
4560 kfree(new);
4561 new = NULL;
907860ed 4562 goto swap_buffers;
2e72b634
KS
4563 }
4564
2c488db2 4565 new->size = size;
2e72b634
KS
4566
4567 /* Copy thresholds and find current threshold */
2c488db2
KS
4568 new->current_threshold = -1;
4569 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4570 if (thresholds->primary->entries[i].eventfd == eventfd)
2e72b634
KS
4571 continue;
4572
2c488db2
KS
4573 new->entries[j] = thresholds->primary->entries[i];
4574 if (new->entries[j].threshold < usage) {
2e72b634 4575 /*
2c488db2 4576 * new->current_threshold will not be used
2e72b634
KS
4577 * until rcu_assign_pointer(), so it's safe to increment
4578 * it here.
4579 */
2c488db2 4580 ++new->current_threshold;
2e72b634
KS
4581 }
4582 j++;
4583 }
4584
907860ed 4585swap_buffers:
2c488db2
KS
4586 /* Swap primary and spare array */
4587 thresholds->spare = thresholds->primary;
4588 rcu_assign_pointer(thresholds->primary, new);
2e72b634 4589
907860ed 4590 /* To be sure that nobody uses thresholds */
2e72b634
KS
4591 synchronize_rcu();
4592
2e72b634 4593 mutex_unlock(&memcg->thresholds_lock);
2e72b634 4594}
c1e862c1 4595
9490ff27
KH
4596static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
4597 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4598{
4599 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4600 struct mem_cgroup_eventfd_list *event;
4601 int type = MEMFILE_TYPE(cft->private);
4602
4603 BUG_ON(type != _OOM_TYPE);
4604 event = kmalloc(sizeof(*event), GFP_KERNEL);
4605 if (!event)
4606 return -ENOMEM;
4607
1af8efe9 4608 spin_lock(&memcg_oom_lock);
9490ff27
KH
4609
4610 event->eventfd = eventfd;
4611 list_add(&event->list, &memcg->oom_notify);
4612
4613 /* already in OOM ? */
79dfdacc 4614 if (atomic_read(&memcg->under_oom))
9490ff27 4615 eventfd_signal(eventfd, 1);
1af8efe9 4616 spin_unlock(&memcg_oom_lock);
9490ff27
KH
4617
4618 return 0;
4619}
4620
907860ed 4621static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
9490ff27
KH
4622 struct cftype *cft, struct eventfd_ctx *eventfd)
4623{
c0ff4b85 4624 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
9490ff27
KH
4625 struct mem_cgroup_eventfd_list *ev, *tmp;
4626 int type = MEMFILE_TYPE(cft->private);
4627
4628 BUG_ON(type != _OOM_TYPE);
4629
1af8efe9 4630 spin_lock(&memcg_oom_lock);
9490ff27 4631
c0ff4b85 4632 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
9490ff27
KH
4633 if (ev->eventfd == eventfd) {
4634 list_del(&ev->list);
4635 kfree(ev);
4636 }
4637 }
4638
1af8efe9 4639 spin_unlock(&memcg_oom_lock);
9490ff27
KH
4640}
4641
3c11ecf4
KH
4642static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
4643 struct cftype *cft, struct cgroup_map_cb *cb)
4644{
c0ff4b85 4645 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3c11ecf4 4646
c0ff4b85 4647 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
3c11ecf4 4648
c0ff4b85 4649 if (atomic_read(&memcg->under_oom))
3c11ecf4
KH
4650 cb->fill(cb, "under_oom", 1);
4651 else
4652 cb->fill(cb, "under_oom", 0);
4653 return 0;
4654}
4655
3c11ecf4
KH
4656static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
4657 struct cftype *cft, u64 val)
4658{
c0ff4b85 4659 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3c11ecf4
KH
4660 struct mem_cgroup *parent;
4661
4662 /* cannot set to root cgroup and only 0 and 1 are allowed */
4663 if (!cgrp->parent || !((val == 0) || (val == 1)))
4664 return -EINVAL;
4665
4666 parent = mem_cgroup_from_cont(cgrp->parent);
4667
4668 cgroup_lock();
4669 /* oom-kill-disable is a flag for subhierarchy. */
4670 if ((parent->use_hierarchy) ||
c0ff4b85 4671 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
3c11ecf4
KH
4672 cgroup_unlock();
4673 return -EINVAL;
4674 }
c0ff4b85 4675 memcg->oom_kill_disable = val;
4d845ebf 4676 if (!val)
c0ff4b85 4677 memcg_oom_recover(memcg);
3c11ecf4
KH
4678 cgroup_unlock();
4679 return 0;
4680}
4681
406eb0c9
YH
4682#ifdef CONFIG_NUMA
4683static const struct file_operations mem_control_numa_stat_file_operations = {
4684 .read = seq_read,
4685 .llseek = seq_lseek,
4686 .release = single_release,
4687};
4688
4689static int mem_control_numa_stat_open(struct inode *unused, struct file *file)
4690{
4691 struct cgroup *cont = file->f_dentry->d_parent->d_fsdata;
4692
4693 file->f_op = &mem_control_numa_stat_file_operations;
4694 return single_open(file, mem_control_numa_stat_show, cont);
4695}
4696#endif /* CONFIG_NUMA */
4697
e5671dfa
GC
4698#ifdef CONFIG_CGROUP_MEM_RES_CTLR_KMEM
4699static u64 kmem_limit_independent_read(struct cgroup *cgroup, struct cftype *cft)
4700{
4701 return mem_cgroup_from_cont(cgroup)->kmem_independent_accounting;
4702}
4703
4704static int kmem_limit_independent_write(struct cgroup *cgroup, struct cftype *cft,
4705 u64 val)
4706{
4707 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
4708 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4709
4710 val = !!val;
4711
4712 /*
4713 * This follows the same hierarchy restrictions than
4714 * mem_cgroup_hierarchy_write()
4715 */
4716 if (!parent || !parent->use_hierarchy) {
4717 if (list_empty(&cgroup->children))
4718 memcg->kmem_independent_accounting = val;
4719 else
4720 return -EBUSY;
4721 }
4722 else
4723 return -EINVAL;
4724
4725 return 0;
4726}
4727static struct cftype kmem_cgroup_files[] = {
4728 {
4729 .name = "independent_kmem_limit",
4730 .read_u64 = kmem_limit_independent_read,
4731 .write_u64 = kmem_limit_independent_write,
4732 },
4733 {
4734 .name = "kmem.usage_in_bytes",
4735 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
4736 .read_u64 = mem_cgroup_read,
4737 },
4738 {
4739 .name = "kmem.limit_in_bytes",
4740 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
4741 .read_u64 = mem_cgroup_read,
4742 },
4743};
4744
4745static int register_kmem_files(struct cgroup *cont, struct cgroup_subsys *ss)
4746{
4747 int ret = 0;
4748
4749 ret = cgroup_add_files(cont, ss, kmem_cgroup_files,
4750 ARRAY_SIZE(kmem_cgroup_files));
d1a4c0b3
GC
4751
4752 /*
4753 * Part of this would be better living in a separate allocation
4754 * function, leaving us with just the cgroup tree population work.
4755 * We, however, depend on state such as network's proto_list that
4756 * is only initialized after cgroup creation. I found the less
4757 * cumbersome way to deal with it to defer it all to populate time
4758 */
4759 if (!ret)
4760 ret = mem_cgroup_sockets_init(cont, ss);
e5671dfa
GC
4761 return ret;
4762};
4763
d1a4c0b3
GC
4764static void kmem_cgroup_destroy(struct cgroup_subsys *ss,
4765 struct cgroup *cont)
4766{
4767 mem_cgroup_sockets_destroy(cont, ss);
4768}
e5671dfa
GC
4769#else
4770static int register_kmem_files(struct cgroup *cont, struct cgroup_subsys *ss)
4771{
4772 return 0;
4773}
d1a4c0b3
GC
4774
4775static void kmem_cgroup_destroy(struct cgroup_subsys *ss,
4776 struct cgroup *cont)
4777{
4778}
e5671dfa
GC
4779#endif
4780
8cdea7c0
BS
4781static struct cftype mem_cgroup_files[] = {
4782 {
0eea1030 4783 .name = "usage_in_bytes",
8c7c6e34 4784 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
2c3daa72 4785 .read_u64 = mem_cgroup_read,
9490ff27
KH
4786 .register_event = mem_cgroup_usage_register_event,
4787 .unregister_event = mem_cgroup_usage_unregister_event,
8cdea7c0 4788 },
c84872e1
PE
4789 {
4790 .name = "max_usage_in_bytes",
8c7c6e34 4791 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
29f2a4da 4792 .trigger = mem_cgroup_reset,
c84872e1
PE
4793 .read_u64 = mem_cgroup_read,
4794 },
8cdea7c0 4795 {
0eea1030 4796 .name = "limit_in_bytes",
8c7c6e34 4797 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
856c13aa 4798 .write_string = mem_cgroup_write,
2c3daa72 4799 .read_u64 = mem_cgroup_read,
8cdea7c0 4800 },
296c81d8
BS
4801 {
4802 .name = "soft_limit_in_bytes",
4803 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4804 .write_string = mem_cgroup_write,
4805 .read_u64 = mem_cgroup_read,
4806 },
8cdea7c0
BS
4807 {
4808 .name = "failcnt",
8c7c6e34 4809 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
29f2a4da 4810 .trigger = mem_cgroup_reset,
2c3daa72 4811 .read_u64 = mem_cgroup_read,
8cdea7c0 4812 },
d2ceb9b7
KH
4813 {
4814 .name = "stat",
c64745cf 4815 .read_map = mem_control_stat_show,
d2ceb9b7 4816 },
c1e862c1
KH
4817 {
4818 .name = "force_empty",
4819 .trigger = mem_cgroup_force_empty_write,
4820 },
18f59ea7
BS
4821 {
4822 .name = "use_hierarchy",
4823 .write_u64 = mem_cgroup_hierarchy_write,
4824 .read_u64 = mem_cgroup_hierarchy_read,
4825 },
a7885eb8
KM
4826 {
4827 .name = "swappiness",
4828 .read_u64 = mem_cgroup_swappiness_read,
4829 .write_u64 = mem_cgroup_swappiness_write,
4830 },
7dc74be0
DN
4831 {
4832 .name = "move_charge_at_immigrate",
4833 .read_u64 = mem_cgroup_move_charge_read,
4834 .write_u64 = mem_cgroup_move_charge_write,
4835 },
9490ff27
KH
4836 {
4837 .name = "oom_control",
3c11ecf4
KH
4838 .read_map = mem_cgroup_oom_control_read,
4839 .write_u64 = mem_cgroup_oom_control_write,
9490ff27
KH
4840 .register_event = mem_cgroup_oom_register_event,
4841 .unregister_event = mem_cgroup_oom_unregister_event,
4842 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4843 },
406eb0c9
YH
4844#ifdef CONFIG_NUMA
4845 {
4846 .name = "numa_stat",
4847 .open = mem_control_numa_stat_open,
89577127 4848 .mode = S_IRUGO,
406eb0c9
YH
4849 },
4850#endif
8cdea7c0
BS
4851};
4852
8c7c6e34
KH
4853#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4854static struct cftype memsw_cgroup_files[] = {
4855 {
4856 .name = "memsw.usage_in_bytes",
4857 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
4858 .read_u64 = mem_cgroup_read,
9490ff27
KH
4859 .register_event = mem_cgroup_usage_register_event,
4860 .unregister_event = mem_cgroup_usage_unregister_event,
8c7c6e34
KH
4861 },
4862 {
4863 .name = "memsw.max_usage_in_bytes",
4864 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
4865 .trigger = mem_cgroup_reset,
4866 .read_u64 = mem_cgroup_read,
4867 },
4868 {
4869 .name = "memsw.limit_in_bytes",
4870 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
4871 .write_string = mem_cgroup_write,
4872 .read_u64 = mem_cgroup_read,
4873 },
4874 {
4875 .name = "memsw.failcnt",
4876 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
4877 .trigger = mem_cgroup_reset,
4878 .read_u64 = mem_cgroup_read,
4879 },
4880};
4881
4882static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4883{
4884 if (!do_swap_account)
4885 return 0;
4886 return cgroup_add_files(cont, ss, memsw_cgroup_files,
4887 ARRAY_SIZE(memsw_cgroup_files));
4888};
4889#else
4890static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4891{
4892 return 0;
4893}
4894#endif
4895
c0ff4b85 4896static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
6d12e2d8
KH
4897{
4898 struct mem_cgroup_per_node *pn;
1ecaab2b 4899 struct mem_cgroup_per_zone *mz;
b69408e8 4900 enum lru_list l;
41e3355d 4901 int zone, tmp = node;
1ecaab2b
KH
4902 /*
4903 * This routine is called against possible nodes.
4904 * But it's BUG to call kmalloc() against offline node.
4905 *
4906 * TODO: this routine can waste much memory for nodes which will
4907 * never be onlined. It's better to use memory hotplug callback
4908 * function.
4909 */
41e3355d
KH
4910 if (!node_state(node, N_NORMAL_MEMORY))
4911 tmp = -1;
17295c88 4912 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
6d12e2d8
KH
4913 if (!pn)
4914 return 1;
1ecaab2b 4915
1ecaab2b
KH
4916 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4917 mz = &pn->zoneinfo[zone];
b69408e8
CL
4918 for_each_lru(l)
4919 INIT_LIST_HEAD(&mz->lists[l]);
f64c3f54 4920 mz->usage_in_excess = 0;
4e416953 4921 mz->on_tree = false;
c0ff4b85 4922 mz->mem = memcg;
1ecaab2b 4923 }
0a619e58 4924 memcg->info.nodeinfo[node] = pn;
6d12e2d8
KH
4925 return 0;
4926}
4927
c0ff4b85 4928static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
1ecaab2b 4929{
c0ff4b85 4930 kfree(memcg->info.nodeinfo[node]);
1ecaab2b
KH
4931}
4932
33327948
KH
4933static struct mem_cgroup *mem_cgroup_alloc(void)
4934{
4935 struct mem_cgroup *mem;
c62b1a3b 4936 int size = sizeof(struct mem_cgroup);
33327948 4937
c62b1a3b 4938 /* Can be very big if MAX_NUMNODES is very big */
c8dad2bb 4939 if (size < PAGE_SIZE)
17295c88 4940 mem = kzalloc(size, GFP_KERNEL);
33327948 4941 else
17295c88 4942 mem = vzalloc(size);
33327948 4943
e7bbcdf3
DC
4944 if (!mem)
4945 return NULL;
4946
c62b1a3b 4947 mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
d2e61b8d
DC
4948 if (!mem->stat)
4949 goto out_free;
711d3d2c 4950 spin_lock_init(&mem->pcp_counter_lock);
33327948 4951 return mem;
d2e61b8d
DC
4952
4953out_free:
4954 if (size < PAGE_SIZE)
4955 kfree(mem);
4956 else
4957 vfree(mem);
4958 return NULL;
33327948
KH
4959}
4960
8c7c6e34
KH
4961/*
4962 * At destroying mem_cgroup, references from swap_cgroup can remain.
4963 * (scanning all at force_empty is too costly...)
4964 *
4965 * Instead of clearing all references at force_empty, we remember
4966 * the number of reference from swap_cgroup and free mem_cgroup when
4967 * it goes down to 0.
4968 *
8c7c6e34
KH
4969 * Removal of cgroup itself succeeds regardless of refs from swap.
4970 */
4971
c0ff4b85 4972static void __mem_cgroup_free(struct mem_cgroup *memcg)
33327948 4973{
08e552c6
KH
4974 int node;
4975
c0ff4b85
R
4976 mem_cgroup_remove_from_trees(memcg);
4977 free_css_id(&mem_cgroup_subsys, &memcg->css);
04046e1a 4978
08e552c6 4979 for_each_node_state(node, N_POSSIBLE)
c0ff4b85 4980 free_mem_cgroup_per_zone_info(memcg, node);
08e552c6 4981
c0ff4b85 4982 free_percpu(memcg->stat);
c62b1a3b 4983 if (sizeof(struct mem_cgroup) < PAGE_SIZE)
c0ff4b85 4984 kfree(memcg);
33327948 4985 else
c0ff4b85 4986 vfree(memcg);
33327948
KH
4987}
4988
c0ff4b85 4989static void mem_cgroup_get(struct mem_cgroup *memcg)
8c7c6e34 4990{
c0ff4b85 4991 atomic_inc(&memcg->refcnt);
8c7c6e34
KH
4992}
4993
c0ff4b85 4994static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
8c7c6e34 4995{
c0ff4b85
R
4996 if (atomic_sub_and_test(count, &memcg->refcnt)) {
4997 struct mem_cgroup *parent = parent_mem_cgroup(memcg);
4998 __mem_cgroup_free(memcg);
7bcc1bb1
DN
4999 if (parent)
5000 mem_cgroup_put(parent);
5001 }
8c7c6e34
KH
5002}
5003
c0ff4b85 5004static void mem_cgroup_put(struct mem_cgroup *memcg)
483c30b5 5005{
c0ff4b85 5006 __mem_cgroup_put(memcg, 1);
483c30b5
DN
5007}
5008
7bcc1bb1
DN
5009/*
5010 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
5011 */
e1aab161 5012struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
7bcc1bb1 5013{
c0ff4b85 5014 if (!memcg->res.parent)
7bcc1bb1 5015 return NULL;
c0ff4b85 5016 return mem_cgroup_from_res_counter(memcg->res.parent, res);
7bcc1bb1 5017}
e1aab161 5018EXPORT_SYMBOL(parent_mem_cgroup);
33327948 5019
c077719b
KH
5020#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5021static void __init enable_swap_cgroup(void)
5022{
f8d66542 5023 if (!mem_cgroup_disabled() && really_do_swap_account)
c077719b
KH
5024 do_swap_account = 1;
5025}
5026#else
5027static void __init enable_swap_cgroup(void)
5028{
5029}
5030#endif
5031
f64c3f54
BS
5032static int mem_cgroup_soft_limit_tree_init(void)
5033{
5034 struct mem_cgroup_tree_per_node *rtpn;
5035 struct mem_cgroup_tree_per_zone *rtpz;
5036 int tmp, node, zone;
5037
5038 for_each_node_state(node, N_POSSIBLE) {
5039 tmp = node;
5040 if (!node_state(node, N_NORMAL_MEMORY))
5041 tmp = -1;
5042 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
5043 if (!rtpn)
5044 return 1;
5045
5046 soft_limit_tree.rb_tree_per_node[node] = rtpn;
5047
5048 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
5049 rtpz = &rtpn->rb_tree_per_zone[zone];
5050 rtpz->rb_root = RB_ROOT;
5051 spin_lock_init(&rtpz->lock);
5052 }
5053 }
5054 return 0;
5055}
5056
0eb253e2 5057static struct cgroup_subsys_state * __ref
8cdea7c0
BS
5058mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
5059{
c0ff4b85 5060 struct mem_cgroup *memcg, *parent;
04046e1a 5061 long error = -ENOMEM;
6d12e2d8 5062 int node;
8cdea7c0 5063
c0ff4b85
R
5064 memcg = mem_cgroup_alloc();
5065 if (!memcg)
04046e1a 5066 return ERR_PTR(error);
78fb7466 5067
6d12e2d8 5068 for_each_node_state(node, N_POSSIBLE)
c0ff4b85 5069 if (alloc_mem_cgroup_per_zone_info(memcg, node))
6d12e2d8 5070 goto free_out;
f64c3f54 5071
c077719b 5072 /* root ? */
28dbc4b6 5073 if (cont->parent == NULL) {
cdec2e42 5074 int cpu;
c077719b 5075 enable_swap_cgroup();
28dbc4b6 5076 parent = NULL;
c0ff4b85 5077 root_mem_cgroup = memcg;
f64c3f54
BS
5078 if (mem_cgroup_soft_limit_tree_init())
5079 goto free_out;
cdec2e42
KH
5080 for_each_possible_cpu(cpu) {
5081 struct memcg_stock_pcp *stock =
5082 &per_cpu(memcg_stock, cpu);
5083 INIT_WORK(&stock->work, drain_local_stock);
5084 }
711d3d2c 5085 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
18f59ea7 5086 } else {
28dbc4b6 5087 parent = mem_cgroup_from_cont(cont->parent);
c0ff4b85
R
5088 memcg->use_hierarchy = parent->use_hierarchy;
5089 memcg->oom_kill_disable = parent->oom_kill_disable;
18f59ea7 5090 }
28dbc4b6 5091
18f59ea7 5092 if (parent && parent->use_hierarchy) {
c0ff4b85
R
5093 res_counter_init(&memcg->res, &parent->res);
5094 res_counter_init(&memcg->memsw, &parent->memsw);
e5671dfa 5095 res_counter_init(&memcg->kmem, &parent->kmem);
7bcc1bb1
DN
5096 /*
5097 * We increment refcnt of the parent to ensure that we can
5098 * safely access it on res_counter_charge/uncharge.
5099 * This refcnt will be decremented when freeing this
5100 * mem_cgroup(see mem_cgroup_put).
5101 */
5102 mem_cgroup_get(parent);
18f59ea7 5103 } else {
c0ff4b85
R
5104 res_counter_init(&memcg->res, NULL);
5105 res_counter_init(&memcg->memsw, NULL);
e5671dfa 5106 res_counter_init(&memcg->kmem, NULL);
18f59ea7 5107 }
c0ff4b85
R
5108 memcg->last_scanned_child = 0;
5109 memcg->last_scanned_node = MAX_NUMNODES;
5110 INIT_LIST_HEAD(&memcg->oom_notify);
6d61ef40 5111
a7885eb8 5112 if (parent)
c0ff4b85
R
5113 memcg->swappiness = mem_cgroup_swappiness(parent);
5114 atomic_set(&memcg->refcnt, 1);
5115 memcg->move_charge_at_immigrate = 0;
5116 mutex_init(&memcg->thresholds_lock);
5117 return &memcg->css;
6d12e2d8 5118free_out:
c0ff4b85 5119 __mem_cgroup_free(memcg);
4b3bde4c 5120 root_mem_cgroup = NULL;
04046e1a 5121 return ERR_PTR(error);
8cdea7c0
BS
5122}
5123
ec64f515 5124static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
df878fb0
KH
5125 struct cgroup *cont)
5126{
c0ff4b85 5127 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
ec64f515 5128
c0ff4b85 5129 return mem_cgroup_force_empty(memcg, false);
df878fb0
KH
5130}
5131
8cdea7c0
BS
5132static void mem_cgroup_destroy(struct cgroup_subsys *ss,
5133 struct cgroup *cont)
5134{
c0ff4b85 5135 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
c268e994 5136
d1a4c0b3
GC
5137 kmem_cgroup_destroy(ss, cont);
5138
c0ff4b85 5139 mem_cgroup_put(memcg);
8cdea7c0
BS
5140}
5141
5142static int mem_cgroup_populate(struct cgroup_subsys *ss,
5143 struct cgroup *cont)
5144{
8c7c6e34
KH
5145 int ret;
5146
5147 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
5148 ARRAY_SIZE(mem_cgroup_files));
5149
5150 if (!ret)
5151 ret = register_memsw_files(cont, ss);
e5671dfa
GC
5152
5153 if (!ret)
5154 ret = register_kmem_files(cont, ss);
5155
8c7c6e34 5156 return ret;
8cdea7c0
BS
5157}
5158
02491447 5159#ifdef CONFIG_MMU
7dc74be0 5160/* Handlers for move charge at task migration. */
854ffa8d
DN
5161#define PRECHARGE_COUNT_AT_ONCE 256
5162static int mem_cgroup_do_precharge(unsigned long count)
7dc74be0 5163{
854ffa8d
DN
5164 int ret = 0;
5165 int batch_count = PRECHARGE_COUNT_AT_ONCE;
c0ff4b85 5166 struct mem_cgroup *memcg = mc.to;
4ffef5fe 5167
c0ff4b85 5168 if (mem_cgroup_is_root(memcg)) {
854ffa8d
DN
5169 mc.precharge += count;
5170 /* we don't need css_get for root */
5171 return ret;
5172 }
5173 /* try to charge at once */
5174 if (count > 1) {
5175 struct res_counter *dummy;
5176 /*
c0ff4b85 5177 * "memcg" cannot be under rmdir() because we've already checked
854ffa8d
DN
5178 * by cgroup_lock_live_cgroup() that it is not removed and we
5179 * are still under the same cgroup_mutex. So we can postpone
5180 * css_get().
5181 */
c0ff4b85 5182 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy))
854ffa8d 5183 goto one_by_one;
c0ff4b85 5184 if (do_swap_account && res_counter_charge(&memcg->memsw,
854ffa8d 5185 PAGE_SIZE * count, &dummy)) {
c0ff4b85 5186 res_counter_uncharge(&memcg->res, PAGE_SIZE * count);
854ffa8d
DN
5187 goto one_by_one;
5188 }
5189 mc.precharge += count;
854ffa8d
DN
5190 return ret;
5191 }
5192one_by_one:
5193 /* fall back to one by one charge */
5194 while (count--) {
5195 if (signal_pending(current)) {
5196 ret = -EINTR;
5197 break;
5198 }
5199 if (!batch_count--) {
5200 batch_count = PRECHARGE_COUNT_AT_ONCE;
5201 cond_resched();
5202 }
c0ff4b85
R
5203 ret = __mem_cgroup_try_charge(NULL,
5204 GFP_KERNEL, 1, &memcg, false);
5205 if (ret || !memcg)
854ffa8d
DN
5206 /* mem_cgroup_clear_mc() will do uncharge later */
5207 return -ENOMEM;
5208 mc.precharge++;
5209 }
4ffef5fe
DN
5210 return ret;
5211}
5212
5213/**
5214 * is_target_pte_for_mc - check a pte whether it is valid for move charge
5215 * @vma: the vma the pte to be checked belongs
5216 * @addr: the address corresponding to the pte to be checked
5217 * @ptent: the pte to be checked
02491447 5218 * @target: the pointer the target page or swap ent will be stored(can be NULL)
4ffef5fe
DN
5219 *
5220 * Returns
5221 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5222 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5223 * move charge. if @target is not NULL, the page is stored in target->page
5224 * with extra refcnt got(Callers should handle it).
02491447
DN
5225 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5226 * target for charge migration. if @target is not NULL, the entry is stored
5227 * in target->ent.
4ffef5fe
DN
5228 *
5229 * Called with pte lock held.
5230 */
4ffef5fe
DN
5231union mc_target {
5232 struct page *page;
02491447 5233 swp_entry_t ent;
4ffef5fe
DN
5234};
5235
4ffef5fe
DN
5236enum mc_target_type {
5237 MC_TARGET_NONE, /* not used */
5238 MC_TARGET_PAGE,
02491447 5239 MC_TARGET_SWAP,
4ffef5fe
DN
5240};
5241
90254a65
DN
5242static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5243 unsigned long addr, pte_t ptent)
4ffef5fe 5244{
90254a65 5245 struct page *page = vm_normal_page(vma, addr, ptent);
4ffef5fe 5246
90254a65
DN
5247 if (!page || !page_mapped(page))
5248 return NULL;
5249 if (PageAnon(page)) {
5250 /* we don't move shared anon */
5251 if (!move_anon() || page_mapcount(page) > 2)
5252 return NULL;
87946a72
DN
5253 } else if (!move_file())
5254 /* we ignore mapcount for file pages */
90254a65
DN
5255 return NULL;
5256 if (!get_page_unless_zero(page))
5257 return NULL;
5258
5259 return page;
5260}
5261
5262static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5263 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5264{
5265 int usage_count;
5266 struct page *page = NULL;
5267 swp_entry_t ent = pte_to_swp_entry(ptent);
5268
5269 if (!move_anon() || non_swap_entry(ent))
5270 return NULL;
5271 usage_count = mem_cgroup_count_swap_user(ent, &page);
5272 if (usage_count > 1) { /* we don't move shared anon */
02491447
DN
5273 if (page)
5274 put_page(page);
90254a65 5275 return NULL;
02491447 5276 }
90254a65
DN
5277 if (do_swap_account)
5278 entry->val = ent.val;
5279
5280 return page;
5281}
5282
87946a72
DN
5283static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5284 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5285{
5286 struct page *page = NULL;
5287 struct inode *inode;
5288 struct address_space *mapping;
5289 pgoff_t pgoff;
5290
5291 if (!vma->vm_file) /* anonymous vma */
5292 return NULL;
5293 if (!move_file())
5294 return NULL;
5295
5296 inode = vma->vm_file->f_path.dentry->d_inode;
5297 mapping = vma->vm_file->f_mapping;
5298 if (pte_none(ptent))
5299 pgoff = linear_page_index(vma, addr);
5300 else /* pte_file(ptent) is true */
5301 pgoff = pte_to_pgoff(ptent);
5302
5303 /* page is moved even if it's not RSS of this task(page-faulted). */
aa3b1895
HD
5304 page = find_get_page(mapping, pgoff);
5305
5306#ifdef CONFIG_SWAP
5307 /* shmem/tmpfs may report page out on swap: account for that too. */
5308 if (radix_tree_exceptional_entry(page)) {
5309 swp_entry_t swap = radix_to_swp_entry(page);
87946a72 5310 if (do_swap_account)
aa3b1895
HD
5311 *entry = swap;
5312 page = find_get_page(&swapper_space, swap.val);
87946a72 5313 }
aa3b1895 5314#endif
87946a72
DN
5315 return page;
5316}
5317
90254a65
DN
5318static int is_target_pte_for_mc(struct vm_area_struct *vma,
5319 unsigned long addr, pte_t ptent, union mc_target *target)
5320{
5321 struct page *page = NULL;
5322 struct page_cgroup *pc;
5323 int ret = 0;
5324 swp_entry_t ent = { .val = 0 };
5325
5326 if (pte_present(ptent))
5327 page = mc_handle_present_pte(vma, addr, ptent);
5328 else if (is_swap_pte(ptent))
5329 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
87946a72
DN
5330 else if (pte_none(ptent) || pte_file(ptent))
5331 page = mc_handle_file_pte(vma, addr, ptent, &ent);
90254a65
DN
5332
5333 if (!page && !ent.val)
5334 return 0;
02491447
DN
5335 if (page) {
5336 pc = lookup_page_cgroup(page);
5337 /*
5338 * Do only loose check w/o page_cgroup lock.
5339 * mem_cgroup_move_account() checks the pc is valid or not under
5340 * the lock.
5341 */
5342 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5343 ret = MC_TARGET_PAGE;
5344 if (target)
5345 target->page = page;
5346 }
5347 if (!ret || !target)
5348 put_page(page);
5349 }
90254a65
DN
5350 /* There is a swap entry and a page doesn't exist or isn't charged */
5351 if (ent.val && !ret &&
7f0f1546
KH
5352 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
5353 ret = MC_TARGET_SWAP;
5354 if (target)
5355 target->ent = ent;
4ffef5fe 5356 }
4ffef5fe
DN
5357 return ret;
5358}
5359
5360static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5361 unsigned long addr, unsigned long end,
5362 struct mm_walk *walk)
5363{
5364 struct vm_area_struct *vma = walk->private;
5365 pte_t *pte;
5366 spinlock_t *ptl;
5367
03319327
DH
5368 split_huge_page_pmd(walk->mm, pmd);
5369
4ffef5fe
DN
5370 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5371 for (; addr != end; pte++, addr += PAGE_SIZE)
5372 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
5373 mc.precharge++; /* increment precharge temporarily */
5374 pte_unmap_unlock(pte - 1, ptl);
5375 cond_resched();
5376
7dc74be0
DN
5377 return 0;
5378}
5379
4ffef5fe
DN
5380static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5381{
5382 unsigned long precharge;
5383 struct vm_area_struct *vma;
5384
dfe076b0 5385 down_read(&mm->mmap_sem);
4ffef5fe
DN
5386 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5387 struct mm_walk mem_cgroup_count_precharge_walk = {
5388 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5389 .mm = mm,
5390 .private = vma,
5391 };
5392 if (is_vm_hugetlb_page(vma))
5393 continue;
4ffef5fe
DN
5394 walk_page_range(vma->vm_start, vma->vm_end,
5395 &mem_cgroup_count_precharge_walk);
5396 }
dfe076b0 5397 up_read(&mm->mmap_sem);
4ffef5fe
DN
5398
5399 precharge = mc.precharge;
5400 mc.precharge = 0;
5401
5402 return precharge;
5403}
5404
4ffef5fe
DN
5405static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5406{
dfe076b0
DN
5407 unsigned long precharge = mem_cgroup_count_precharge(mm);
5408
5409 VM_BUG_ON(mc.moving_task);
5410 mc.moving_task = current;
5411 return mem_cgroup_do_precharge(precharge);
4ffef5fe
DN
5412}
5413
dfe076b0
DN
5414/* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5415static void __mem_cgroup_clear_mc(void)
4ffef5fe 5416{
2bd9bb20
KH
5417 struct mem_cgroup *from = mc.from;
5418 struct mem_cgroup *to = mc.to;
5419
4ffef5fe 5420 /* we must uncharge all the leftover precharges from mc.to */
854ffa8d
DN
5421 if (mc.precharge) {
5422 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
5423 mc.precharge = 0;
5424 }
5425 /*
5426 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5427 * we must uncharge here.
5428 */
5429 if (mc.moved_charge) {
5430 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
5431 mc.moved_charge = 0;
4ffef5fe 5432 }
483c30b5
DN
5433 /* we must fixup refcnts and charges */
5434 if (mc.moved_swap) {
483c30b5
DN
5435 /* uncharge swap account from the old cgroup */
5436 if (!mem_cgroup_is_root(mc.from))
5437 res_counter_uncharge(&mc.from->memsw,
5438 PAGE_SIZE * mc.moved_swap);
5439 __mem_cgroup_put(mc.from, mc.moved_swap);
5440
5441 if (!mem_cgroup_is_root(mc.to)) {
5442 /*
5443 * we charged both to->res and to->memsw, so we should
5444 * uncharge to->res.
5445 */
5446 res_counter_uncharge(&mc.to->res,
5447 PAGE_SIZE * mc.moved_swap);
483c30b5
DN
5448 }
5449 /* we've already done mem_cgroup_get(mc.to) */
483c30b5
DN
5450 mc.moved_swap = 0;
5451 }
dfe076b0
DN
5452 memcg_oom_recover(from);
5453 memcg_oom_recover(to);
5454 wake_up_all(&mc.waitq);
5455}
5456
5457static void mem_cgroup_clear_mc(void)
5458{
5459 struct mem_cgroup *from = mc.from;
5460
5461 /*
5462 * we must clear moving_task before waking up waiters at the end of
5463 * task migration.
5464 */
5465 mc.moving_task = NULL;
5466 __mem_cgroup_clear_mc();
2bd9bb20 5467 spin_lock(&mc.lock);
4ffef5fe
DN
5468 mc.from = NULL;
5469 mc.to = NULL;
2bd9bb20 5470 spin_unlock(&mc.lock);
32047e2a 5471 mem_cgroup_end_move(from);
4ffef5fe
DN
5472}
5473
7dc74be0
DN
5474static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5475 struct cgroup *cgroup,
f780bdb7 5476 struct task_struct *p)
7dc74be0
DN
5477{
5478 int ret = 0;
c0ff4b85 5479 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
7dc74be0 5480
c0ff4b85 5481 if (memcg->move_charge_at_immigrate) {
7dc74be0
DN
5482 struct mm_struct *mm;
5483 struct mem_cgroup *from = mem_cgroup_from_task(p);
5484
c0ff4b85 5485 VM_BUG_ON(from == memcg);
7dc74be0
DN
5486
5487 mm = get_task_mm(p);
5488 if (!mm)
5489 return 0;
7dc74be0 5490 /* We move charges only when we move a owner of the mm */
4ffef5fe
DN
5491 if (mm->owner == p) {
5492 VM_BUG_ON(mc.from);
5493 VM_BUG_ON(mc.to);
5494 VM_BUG_ON(mc.precharge);
854ffa8d 5495 VM_BUG_ON(mc.moved_charge);
483c30b5 5496 VM_BUG_ON(mc.moved_swap);
32047e2a 5497 mem_cgroup_start_move(from);
2bd9bb20 5498 spin_lock(&mc.lock);
4ffef5fe 5499 mc.from = from;
c0ff4b85 5500 mc.to = memcg;
2bd9bb20 5501 spin_unlock(&mc.lock);
dfe076b0 5502 /* We set mc.moving_task later */
4ffef5fe
DN
5503
5504 ret = mem_cgroup_precharge_mc(mm);
5505 if (ret)
5506 mem_cgroup_clear_mc();
dfe076b0
DN
5507 }
5508 mmput(mm);
7dc74be0
DN
5509 }
5510 return ret;
5511}
5512
5513static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5514 struct cgroup *cgroup,
f780bdb7 5515 struct task_struct *p)
7dc74be0 5516{
4ffef5fe 5517 mem_cgroup_clear_mc();
7dc74be0
DN
5518}
5519
4ffef5fe
DN
5520static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5521 unsigned long addr, unsigned long end,
5522 struct mm_walk *walk)
7dc74be0 5523{
4ffef5fe
DN
5524 int ret = 0;
5525 struct vm_area_struct *vma = walk->private;
5526 pte_t *pte;
5527 spinlock_t *ptl;
5528
03319327 5529 split_huge_page_pmd(walk->mm, pmd);
4ffef5fe
DN
5530retry:
5531 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5532 for (; addr != end; addr += PAGE_SIZE) {
5533 pte_t ptent = *(pte++);
5534 union mc_target target;
5535 int type;
5536 struct page *page;
5537 struct page_cgroup *pc;
02491447 5538 swp_entry_t ent;
4ffef5fe
DN
5539
5540 if (!mc.precharge)
5541 break;
5542
5543 type = is_target_pte_for_mc(vma, addr, ptent, &target);
5544 switch (type) {
5545 case MC_TARGET_PAGE:
5546 page = target.page;
5547 if (isolate_lru_page(page))
5548 goto put;
5549 pc = lookup_page_cgroup(page);
7ec99d62
JW
5550 if (!mem_cgroup_move_account(page, 1, pc,
5551 mc.from, mc.to, false)) {
4ffef5fe 5552 mc.precharge--;
854ffa8d
DN
5553 /* we uncharge from mc.from later. */
5554 mc.moved_charge++;
4ffef5fe
DN
5555 }
5556 putback_lru_page(page);
5557put: /* is_target_pte_for_mc() gets the page */
5558 put_page(page);
5559 break;
02491447
DN
5560 case MC_TARGET_SWAP:
5561 ent = target.ent;
483c30b5
DN
5562 if (!mem_cgroup_move_swap_account(ent,
5563 mc.from, mc.to, false)) {
02491447 5564 mc.precharge--;
483c30b5
DN
5565 /* we fixup refcnts and charges later. */
5566 mc.moved_swap++;
5567 }
02491447 5568 break;
4ffef5fe
DN
5569 default:
5570 break;
5571 }
5572 }
5573 pte_unmap_unlock(pte - 1, ptl);
5574 cond_resched();
5575
5576 if (addr != end) {
5577 /*
5578 * We have consumed all precharges we got in can_attach().
5579 * We try charge one by one, but don't do any additional
5580 * charges to mc.to if we have failed in charge once in attach()
5581 * phase.
5582 */
854ffa8d 5583 ret = mem_cgroup_do_precharge(1);
4ffef5fe
DN
5584 if (!ret)
5585 goto retry;
5586 }
5587
5588 return ret;
5589}
5590
5591static void mem_cgroup_move_charge(struct mm_struct *mm)
5592{
5593 struct vm_area_struct *vma;
5594
5595 lru_add_drain_all();
dfe076b0
DN
5596retry:
5597 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
5598 /*
5599 * Someone who are holding the mmap_sem might be waiting in
5600 * waitq. So we cancel all extra charges, wake up all waiters,
5601 * and retry. Because we cancel precharges, we might not be able
5602 * to move enough charges, but moving charge is a best-effort
5603 * feature anyway, so it wouldn't be a big problem.
5604 */
5605 __mem_cgroup_clear_mc();
5606 cond_resched();
5607 goto retry;
5608 }
4ffef5fe
DN
5609 for (vma = mm->mmap; vma; vma = vma->vm_next) {
5610 int ret;
5611 struct mm_walk mem_cgroup_move_charge_walk = {
5612 .pmd_entry = mem_cgroup_move_charge_pte_range,
5613 .mm = mm,
5614 .private = vma,
5615 };
5616 if (is_vm_hugetlb_page(vma))
5617 continue;
4ffef5fe
DN
5618 ret = walk_page_range(vma->vm_start, vma->vm_end,
5619 &mem_cgroup_move_charge_walk);
5620 if (ret)
5621 /*
5622 * means we have consumed all precharges and failed in
5623 * doing additional charge. Just abandon here.
5624 */
5625 break;
5626 }
dfe076b0 5627 up_read(&mm->mmap_sem);
7dc74be0
DN
5628}
5629
67e465a7
BS
5630static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5631 struct cgroup *cont,
5632 struct cgroup *old_cont,
f780bdb7 5633 struct task_struct *p)
67e465a7 5634{
a433658c 5635 struct mm_struct *mm = get_task_mm(p);
dfe076b0 5636
dfe076b0 5637 if (mm) {
a433658c
KM
5638 if (mc.to)
5639 mem_cgroup_move_charge(mm);
5640 put_swap_token(mm);
dfe076b0
DN
5641 mmput(mm);
5642 }
a433658c
KM
5643 if (mc.to)
5644 mem_cgroup_clear_mc();
67e465a7 5645}
5cfb80a7
DN
5646#else /* !CONFIG_MMU */
5647static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5648 struct cgroup *cgroup,
f780bdb7 5649 struct task_struct *p)
5cfb80a7
DN
5650{
5651 return 0;
5652}
5653static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5654 struct cgroup *cgroup,
f780bdb7 5655 struct task_struct *p)
5cfb80a7
DN
5656{
5657}
5658static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5659 struct cgroup *cont,
5660 struct cgroup *old_cont,
f780bdb7 5661 struct task_struct *p)
5cfb80a7
DN
5662{
5663}
5664#endif
67e465a7 5665
8cdea7c0
BS
5666struct cgroup_subsys mem_cgroup_subsys = {
5667 .name = "memory",
5668 .subsys_id = mem_cgroup_subsys_id,
5669 .create = mem_cgroup_create,
df878fb0 5670 .pre_destroy = mem_cgroup_pre_destroy,
8cdea7c0
BS
5671 .destroy = mem_cgroup_destroy,
5672 .populate = mem_cgroup_populate,
7dc74be0
DN
5673 .can_attach = mem_cgroup_can_attach,
5674 .cancel_attach = mem_cgroup_cancel_attach,
67e465a7 5675 .attach = mem_cgroup_move_task,
6d12e2d8 5676 .early_init = 0,
04046e1a 5677 .use_id = 1,
8cdea7c0 5678};
c077719b
KH
5679
5680#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
a42c390c
MH
5681static int __init enable_swap_account(char *s)
5682{
5683 /* consider enabled if no parameter or 1 is given */
a2c8990a 5684 if (!strcmp(s, "1"))
a42c390c 5685 really_do_swap_account = 1;
a2c8990a 5686 else if (!strcmp(s, "0"))
a42c390c
MH
5687 really_do_swap_account = 0;
5688 return 1;
5689}
a2c8990a 5690__setup("swapaccount=", enable_swap_account);
c077719b 5691
c077719b 5692#endif