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