]> bbs.cooldavid.org Git - net-next-2.6.git/blame - mm/memcontrol.c
memcg: avoid oom during moving charge
[net-next-2.6.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 *
8cdea7c0
BS
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 */
19
20#include <linux/res_counter.h>
21#include <linux/memcontrol.h>
22#include <linux/cgroup.h>
78fb7466 23#include <linux/mm.h>
4ffef5fe 24#include <linux/hugetlb.h>
d13d1443 25#include <linux/pagemap.h>
d52aa412 26#include <linux/smp.h>
8a9f3ccd 27#include <linux/page-flags.h>
66e1707b 28#include <linux/backing-dev.h>
8a9f3ccd
BS
29#include <linux/bit_spinlock.h>
30#include <linux/rcupdate.h>
e222432b 31#include <linux/limits.h>
8c7c6e34 32#include <linux/mutex.h>
f64c3f54 33#include <linux/rbtree.h>
b6ac57d5 34#include <linux/slab.h>
66e1707b
BS
35#include <linux/swap.h>
36#include <linux/spinlock.h>
37#include <linux/fs.h>
d2ceb9b7 38#include <linux/seq_file.h>
33327948 39#include <linux/vmalloc.h>
b69408e8 40#include <linux/mm_inline.h>
52d4b9ac 41#include <linux/page_cgroup.h>
cdec2e42 42#include <linux/cpu.h>
08e552c6 43#include "internal.h"
8cdea7c0 44
8697d331
BS
45#include <asm/uaccess.h>
46
a181b0e8 47struct cgroup_subsys mem_cgroup_subsys __read_mostly;
a181b0e8 48#define MEM_CGROUP_RECLAIM_RETRIES 5
4b3bde4c 49struct mem_cgroup *root_mem_cgroup __read_mostly;
8cdea7c0 50
c077719b 51#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
338c8431 52/* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
c077719b
KH
53int do_swap_account __read_mostly;
54static int really_do_swap_account __initdata = 1; /* for remember boot option*/
55#else
56#define do_swap_account (0)
57#endif
58
f64c3f54 59#define SOFTLIMIT_EVENTS_THRESH (1000)
c077719b 60
d52aa412
KH
61/*
62 * Statistics for memory cgroup.
63 */
64enum mem_cgroup_stat_index {
65 /*
66 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
67 */
68 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */
d69b042f 69 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */
d8046582 70 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */
55e462b0
BR
71 MEM_CGROUP_STAT_PGPGIN_COUNT, /* # of pages paged in */
72 MEM_CGROUP_STAT_PGPGOUT_COUNT, /* # of pages paged out */
f64c3f54 73 MEM_CGROUP_STAT_EVENTS, /* sum of pagein + pageout for internal use */
0c3e73e8 74 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
d52aa412
KH
75
76 MEM_CGROUP_STAT_NSTATS,
77};
78
79struct mem_cgroup_stat_cpu {
80 s64 count[MEM_CGROUP_STAT_NSTATS];
81} ____cacheline_aligned_in_smp;
82
83struct mem_cgroup_stat {
c8dad2bb 84 struct mem_cgroup_stat_cpu cpustat[0];
d52aa412
KH
85};
86
f64c3f54
BS
87static inline void
88__mem_cgroup_stat_reset_safe(struct mem_cgroup_stat_cpu *stat,
89 enum mem_cgroup_stat_index idx)
90{
91 stat->count[idx] = 0;
92}
93
94static inline s64
95__mem_cgroup_stat_read_local(struct mem_cgroup_stat_cpu *stat,
96 enum mem_cgroup_stat_index idx)
97{
98 return stat->count[idx];
99}
100
d52aa412
KH
101/*
102 * For accounting under irq disable, no need for increment preempt count.
103 */
addb9efe 104static inline void __mem_cgroup_stat_add_safe(struct mem_cgroup_stat_cpu *stat,
d52aa412
KH
105 enum mem_cgroup_stat_index idx, int val)
106{
addb9efe 107 stat->count[idx] += val;
d52aa412
KH
108}
109
110static s64 mem_cgroup_read_stat(struct mem_cgroup_stat *stat,
111 enum mem_cgroup_stat_index idx)
112{
113 int cpu;
114 s64 ret = 0;
115 for_each_possible_cpu(cpu)
116 ret += stat->cpustat[cpu].count[idx];
117 return ret;
118}
119
04046e1a
KH
120static s64 mem_cgroup_local_usage(struct mem_cgroup_stat *stat)
121{
122 s64 ret;
123
124 ret = mem_cgroup_read_stat(stat, MEM_CGROUP_STAT_CACHE);
125 ret += mem_cgroup_read_stat(stat, MEM_CGROUP_STAT_RSS);
126 return ret;
127}
128
6d12e2d8
KH
129/*
130 * per-zone information in memory controller.
131 */
6d12e2d8 132struct mem_cgroup_per_zone {
072c56c1
KH
133 /*
134 * spin_lock to protect the per cgroup LRU
135 */
b69408e8
CL
136 struct list_head lists[NR_LRU_LISTS];
137 unsigned long count[NR_LRU_LISTS];
3e2f41f1
KM
138
139 struct zone_reclaim_stat reclaim_stat;
f64c3f54
BS
140 struct rb_node tree_node; /* RB tree node */
141 unsigned long long usage_in_excess;/* Set to the value by which */
142 /* the soft limit is exceeded*/
143 bool on_tree;
4e416953
BS
144 struct mem_cgroup *mem; /* Back pointer, we cannot */
145 /* use container_of */
6d12e2d8
KH
146};
147/* Macro for accessing counter */
148#define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)])
149
150struct mem_cgroup_per_node {
151 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
152};
153
154struct mem_cgroup_lru_info {
155 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
156};
157
f64c3f54
BS
158/*
159 * Cgroups above their limits are maintained in a RB-Tree, independent of
160 * their hierarchy representation
161 */
162
163struct mem_cgroup_tree_per_zone {
164 struct rb_root rb_root;
165 spinlock_t lock;
166};
167
168struct mem_cgroup_tree_per_node {
169 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
170};
171
172struct mem_cgroup_tree {
173 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
174};
175
176static struct mem_cgroup_tree soft_limit_tree __read_mostly;
177
8cdea7c0
BS
178/*
179 * The memory controller data structure. The memory controller controls both
180 * page cache and RSS per cgroup. We would eventually like to provide
181 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
182 * to help the administrator determine what knobs to tune.
183 *
184 * TODO: Add a water mark for the memory controller. Reclaim will begin when
8a9f3ccd
BS
185 * we hit the water mark. May be even add a low water mark, such that
186 * no reclaim occurs from a cgroup at it's low water mark, this is
187 * a feature that will be implemented much later in the future.
8cdea7c0
BS
188 */
189struct mem_cgroup {
190 struct cgroup_subsys_state css;
191 /*
192 * the counter to account for memory usage
193 */
194 struct res_counter res;
8c7c6e34
KH
195 /*
196 * the counter to account for mem+swap usage.
197 */
198 struct res_counter memsw;
78fb7466
PE
199 /*
200 * Per cgroup active and inactive list, similar to the
201 * per zone LRU lists.
78fb7466 202 */
6d12e2d8 203 struct mem_cgroup_lru_info info;
072c56c1 204
2733c06a
KM
205 /*
206 protect against reclaim related member.
207 */
208 spinlock_t reclaim_param_lock;
209
6c48a1d0 210 int prev_priority; /* for recording reclaim priority */
6d61ef40
BS
211
212 /*
af901ca1 213 * While reclaiming in a hierarchy, we cache the last child we
04046e1a 214 * reclaimed from.
6d61ef40 215 */
04046e1a 216 int last_scanned_child;
18f59ea7
BS
217 /*
218 * Should the accounting and control be hierarchical, per subtree?
219 */
220 bool use_hierarchy;
a636b327 221 unsigned long last_oom_jiffies;
8c7c6e34 222 atomic_t refcnt;
14797e23 223
a7885eb8
KM
224 unsigned int swappiness;
225
22a668d7
KH
226 /* set when res.limit == memsw.limit */
227 bool memsw_is_minimum;
228
7dc74be0
DN
229 /*
230 * Should we move charges of a task when a task is moved into this
231 * mem_cgroup ? And what type of charges should we move ?
232 */
233 unsigned long move_charge_at_immigrate;
234
d52aa412 235 /*
c8dad2bb 236 * statistics. This must be placed at the end of memcg.
d52aa412
KH
237 */
238 struct mem_cgroup_stat stat;
8cdea7c0
BS
239};
240
7dc74be0
DN
241/* Stuffs for move charges at task migration. */
242/*
243 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
244 * left-shifted bitmap of these types.
245 */
246enum move_type {
4ffef5fe 247 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */
7dc74be0
DN
248 NR_MOVE_TYPE,
249};
250
4ffef5fe
DN
251/* "mc" and its members are protected by cgroup_mutex */
252static struct move_charge_struct {
253 struct mem_cgroup *from;
254 struct mem_cgroup *to;
255 unsigned long precharge;
854ffa8d 256 unsigned long moved_charge;
8033b97c
DN
257 struct task_struct *moving_task; /* a task moving charges */
258 wait_queue_head_t waitq; /* a waitq for other context */
259} mc = {
260 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
261};
4ffef5fe 262
4e416953
BS
263/*
264 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
265 * limit reclaim to prevent infinite loops, if they ever occur.
266 */
267#define MEM_CGROUP_MAX_RECLAIM_LOOPS (100)
268#define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
269
217bc319
KH
270enum charge_type {
271 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
272 MEM_CGROUP_CHARGE_TYPE_MAPPED,
4f98a2fe 273 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */
c05555b5 274 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */
d13d1443 275 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
8a9478ca 276 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
c05555b5
KH
277 NR_CHARGE_TYPE,
278};
279
52d4b9ac
KH
280/* only for here (for easy reading.) */
281#define PCGF_CACHE (1UL << PCG_CACHE)
282#define PCGF_USED (1UL << PCG_USED)
52d4b9ac 283#define PCGF_LOCK (1UL << PCG_LOCK)
4b3bde4c
BS
284/* Not used, but added here for completeness */
285#define PCGF_ACCT (1UL << PCG_ACCT)
217bc319 286
8c7c6e34
KH
287/* for encoding cft->private value on file */
288#define _MEM (0)
289#define _MEMSWAP (1)
290#define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
291#define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff)
292#define MEMFILE_ATTR(val) ((val) & 0xffff)
293
75822b44
BS
294/*
295 * Reclaim flags for mem_cgroup_hierarchical_reclaim
296 */
297#define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0
298#define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
299#define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1
300#define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
4e416953
BS
301#define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2
302#define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
75822b44 303
8c7c6e34
KH
304static void mem_cgroup_get(struct mem_cgroup *mem);
305static void mem_cgroup_put(struct mem_cgroup *mem);
7bcc1bb1 306static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
cdec2e42 307static void drain_all_stock_async(void);
8c7c6e34 308
f64c3f54
BS
309static struct mem_cgroup_per_zone *
310mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
311{
312 return &mem->info.nodeinfo[nid]->zoneinfo[zid];
313}
314
d324236b
WF
315struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *mem)
316{
317 return &mem->css;
318}
319
f64c3f54
BS
320static struct mem_cgroup_per_zone *
321page_cgroup_zoneinfo(struct page_cgroup *pc)
322{
323 struct mem_cgroup *mem = pc->mem_cgroup;
324 int nid = page_cgroup_nid(pc);
325 int zid = page_cgroup_zid(pc);
326
327 if (!mem)
328 return NULL;
329
330 return mem_cgroup_zoneinfo(mem, nid, zid);
331}
332
333static struct mem_cgroup_tree_per_zone *
334soft_limit_tree_node_zone(int nid, int zid)
335{
336 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
337}
338
339static struct mem_cgroup_tree_per_zone *
340soft_limit_tree_from_page(struct page *page)
341{
342 int nid = page_to_nid(page);
343 int zid = page_zonenum(page);
344
345 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
346}
347
348static void
4e416953 349__mem_cgroup_insert_exceeded(struct mem_cgroup *mem,
f64c3f54 350 struct mem_cgroup_per_zone *mz,
ef8745c1
KH
351 struct mem_cgroup_tree_per_zone *mctz,
352 unsigned long long new_usage_in_excess)
f64c3f54
BS
353{
354 struct rb_node **p = &mctz->rb_root.rb_node;
355 struct rb_node *parent = NULL;
356 struct mem_cgroup_per_zone *mz_node;
357
358 if (mz->on_tree)
359 return;
360
ef8745c1
KH
361 mz->usage_in_excess = new_usage_in_excess;
362 if (!mz->usage_in_excess)
363 return;
f64c3f54
BS
364 while (*p) {
365 parent = *p;
366 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
367 tree_node);
368 if (mz->usage_in_excess < mz_node->usage_in_excess)
369 p = &(*p)->rb_left;
370 /*
371 * We can't avoid mem cgroups that are over their soft
372 * limit by the same amount
373 */
374 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
375 p = &(*p)->rb_right;
376 }
377 rb_link_node(&mz->tree_node, parent, p);
378 rb_insert_color(&mz->tree_node, &mctz->rb_root);
379 mz->on_tree = true;
4e416953
BS
380}
381
382static void
383__mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
384 struct mem_cgroup_per_zone *mz,
385 struct mem_cgroup_tree_per_zone *mctz)
386{
387 if (!mz->on_tree)
388 return;
389 rb_erase(&mz->tree_node, &mctz->rb_root);
390 mz->on_tree = false;
391}
392
f64c3f54
BS
393static void
394mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
395 struct mem_cgroup_per_zone *mz,
396 struct mem_cgroup_tree_per_zone *mctz)
397{
398 spin_lock(&mctz->lock);
4e416953 399 __mem_cgroup_remove_exceeded(mem, mz, mctz);
f64c3f54
BS
400 spin_unlock(&mctz->lock);
401}
402
403static bool mem_cgroup_soft_limit_check(struct mem_cgroup *mem)
404{
405 bool ret = false;
406 int cpu;
407 s64 val;
408 struct mem_cgroup_stat_cpu *cpustat;
409
410 cpu = get_cpu();
411 cpustat = &mem->stat.cpustat[cpu];
412 val = __mem_cgroup_stat_read_local(cpustat, MEM_CGROUP_STAT_EVENTS);
413 if (unlikely(val > SOFTLIMIT_EVENTS_THRESH)) {
414 __mem_cgroup_stat_reset_safe(cpustat, MEM_CGROUP_STAT_EVENTS);
415 ret = true;
416 }
417 put_cpu();
418 return ret;
419}
420
421static void mem_cgroup_update_tree(struct mem_cgroup *mem, struct page *page)
422{
ef8745c1 423 unsigned long long excess;
f64c3f54
BS
424 struct mem_cgroup_per_zone *mz;
425 struct mem_cgroup_tree_per_zone *mctz;
4e649152
KH
426 int nid = page_to_nid(page);
427 int zid = page_zonenum(page);
f64c3f54
BS
428 mctz = soft_limit_tree_from_page(page);
429
430 /*
4e649152
KH
431 * Necessary to update all ancestors when hierarchy is used.
432 * because their event counter is not touched.
f64c3f54 433 */
4e649152
KH
434 for (; mem; mem = parent_mem_cgroup(mem)) {
435 mz = mem_cgroup_zoneinfo(mem, nid, zid);
ef8745c1 436 excess = res_counter_soft_limit_excess(&mem->res);
4e649152
KH
437 /*
438 * We have to update the tree if mz is on RB-tree or
439 * mem is over its softlimit.
440 */
ef8745c1 441 if (excess || mz->on_tree) {
4e649152
KH
442 spin_lock(&mctz->lock);
443 /* if on-tree, remove it */
444 if (mz->on_tree)
445 __mem_cgroup_remove_exceeded(mem, mz, mctz);
446 /*
ef8745c1
KH
447 * Insert again. mz->usage_in_excess will be updated.
448 * If excess is 0, no tree ops.
4e649152 449 */
ef8745c1 450 __mem_cgroup_insert_exceeded(mem, mz, mctz, excess);
4e649152
KH
451 spin_unlock(&mctz->lock);
452 }
f64c3f54
BS
453 }
454}
455
456static void mem_cgroup_remove_from_trees(struct mem_cgroup *mem)
457{
458 int node, zone;
459 struct mem_cgroup_per_zone *mz;
460 struct mem_cgroup_tree_per_zone *mctz;
461
462 for_each_node_state(node, N_POSSIBLE) {
463 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
464 mz = mem_cgroup_zoneinfo(mem, node, zone);
465 mctz = soft_limit_tree_node_zone(node, zone);
466 mem_cgroup_remove_exceeded(mem, mz, mctz);
467 }
468 }
469}
470
4e416953
BS
471static inline unsigned long mem_cgroup_get_excess(struct mem_cgroup *mem)
472{
473 return res_counter_soft_limit_excess(&mem->res) >> PAGE_SHIFT;
474}
475
476static struct mem_cgroup_per_zone *
477__mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
478{
479 struct rb_node *rightmost = NULL;
26251eaf 480 struct mem_cgroup_per_zone *mz;
4e416953
BS
481
482retry:
26251eaf 483 mz = NULL;
4e416953
BS
484 rightmost = rb_last(&mctz->rb_root);
485 if (!rightmost)
486 goto done; /* Nothing to reclaim from */
487
488 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
489 /*
490 * Remove the node now but someone else can add it back,
491 * we will to add it back at the end of reclaim to its correct
492 * position in the tree.
493 */
494 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
495 if (!res_counter_soft_limit_excess(&mz->mem->res) ||
496 !css_tryget(&mz->mem->css))
497 goto retry;
498done:
499 return mz;
500}
501
502static struct mem_cgroup_per_zone *
503mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
504{
505 struct mem_cgroup_per_zone *mz;
506
507 spin_lock(&mctz->lock);
508 mz = __mem_cgroup_largest_soft_limit_node(mctz);
509 spin_unlock(&mctz->lock);
510 return mz;
511}
512
0c3e73e8
BS
513static void mem_cgroup_swap_statistics(struct mem_cgroup *mem,
514 bool charge)
515{
516 int val = (charge) ? 1 : -1;
517 struct mem_cgroup_stat *stat = &mem->stat;
518 struct mem_cgroup_stat_cpu *cpustat;
519 int cpu = get_cpu();
520
521 cpustat = &stat->cpustat[cpu];
522 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_SWAPOUT, val);
523 put_cpu();
524}
525
c05555b5
KH
526static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
527 struct page_cgroup *pc,
528 bool charge)
d52aa412 529{
0c3e73e8 530 int val = (charge) ? 1 : -1;
d52aa412 531 struct mem_cgroup_stat *stat = &mem->stat;
addb9efe 532 struct mem_cgroup_stat_cpu *cpustat;
08e552c6 533 int cpu = get_cpu();
d52aa412 534
08e552c6 535 cpustat = &stat->cpustat[cpu];
c05555b5 536 if (PageCgroupCache(pc))
addb9efe 537 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_CACHE, val);
d52aa412 538 else
addb9efe 539 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_RSS, val);
55e462b0
BR
540
541 if (charge)
addb9efe 542 __mem_cgroup_stat_add_safe(cpustat,
55e462b0
BR
543 MEM_CGROUP_STAT_PGPGIN_COUNT, 1);
544 else
addb9efe 545 __mem_cgroup_stat_add_safe(cpustat,
55e462b0 546 MEM_CGROUP_STAT_PGPGOUT_COUNT, 1);
f64c3f54 547 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_EVENTS, 1);
08e552c6 548 put_cpu();
6d12e2d8
KH
549}
550
14067bb3 551static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup *mem,
b69408e8 552 enum lru_list idx)
6d12e2d8
KH
553{
554 int nid, zid;
555 struct mem_cgroup_per_zone *mz;
556 u64 total = 0;
557
558 for_each_online_node(nid)
559 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
560 mz = mem_cgroup_zoneinfo(mem, nid, zid);
561 total += MEM_CGROUP_ZSTAT(mz, idx);
562 }
563 return total;
d52aa412
KH
564}
565
d5b69e38 566static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
8cdea7c0
BS
567{
568 return container_of(cgroup_subsys_state(cont,
569 mem_cgroup_subsys_id), struct mem_cgroup,
570 css);
571}
572
cf475ad2 573struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
78fb7466 574{
31a78f23
BS
575 /*
576 * mm_update_next_owner() may clear mm->owner to NULL
577 * if it races with swapoff, page migration, etc.
578 * So this can be called with p == NULL.
579 */
580 if (unlikely(!p))
581 return NULL;
582
78fb7466
PE
583 return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
584 struct mem_cgroup, css);
585}
586
54595fe2
KH
587static struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
588{
589 struct mem_cgroup *mem = NULL;
0b7f569e
KH
590
591 if (!mm)
592 return NULL;
54595fe2
KH
593 /*
594 * Because we have no locks, mm->owner's may be being moved to other
595 * cgroup. We use css_tryget() here even if this looks
596 * pessimistic (rather than adding locks here).
597 */
598 rcu_read_lock();
599 do {
600 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
601 if (unlikely(!mem))
602 break;
603 } while (!css_tryget(&mem->css));
604 rcu_read_unlock();
605 return mem;
606}
607
14067bb3
KH
608/*
609 * Call callback function against all cgroup under hierarchy tree.
610 */
611static int mem_cgroup_walk_tree(struct mem_cgroup *root, void *data,
612 int (*func)(struct mem_cgroup *, void *))
613{
614 int found, ret, nextid;
615 struct cgroup_subsys_state *css;
616 struct mem_cgroup *mem;
617
618 if (!root->use_hierarchy)
619 return (*func)(root, data);
620
621 nextid = 1;
622 do {
623 ret = 0;
624 mem = NULL;
625
626 rcu_read_lock();
627 css = css_get_next(&mem_cgroup_subsys, nextid, &root->css,
628 &found);
629 if (css && css_tryget(css))
630 mem = container_of(css, struct mem_cgroup, css);
631 rcu_read_unlock();
632
633 if (mem) {
634 ret = (*func)(mem, data);
635 css_put(&mem->css);
636 }
637 nextid = found + 1;
638 } while (!ret && css);
639
640 return ret;
641}
642
4b3bde4c
BS
643static inline bool mem_cgroup_is_root(struct mem_cgroup *mem)
644{
645 return (mem == root_mem_cgroup);
646}
647
08e552c6
KH
648/*
649 * Following LRU functions are allowed to be used without PCG_LOCK.
650 * Operations are called by routine of global LRU independently from memcg.
651 * What we have to take care of here is validness of pc->mem_cgroup.
652 *
653 * Changes to pc->mem_cgroup happens when
654 * 1. charge
655 * 2. moving account
656 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
657 * It is added to LRU before charge.
658 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
659 * When moving account, the page is not on LRU. It's isolated.
660 */
4f98a2fe 661
08e552c6
KH
662void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
663{
664 struct page_cgroup *pc;
08e552c6 665 struct mem_cgroup_per_zone *mz;
6d12e2d8 666
f8d66542 667 if (mem_cgroup_disabled())
08e552c6
KH
668 return;
669 pc = lookup_page_cgroup(page);
670 /* can happen while we handle swapcache. */
4b3bde4c 671 if (!TestClearPageCgroupAcctLRU(pc))
08e552c6 672 return;
4b3bde4c 673 VM_BUG_ON(!pc->mem_cgroup);
544122e5
KH
674 /*
675 * We don't check PCG_USED bit. It's cleared when the "page" is finally
676 * removed from global LRU.
677 */
08e552c6 678 mz = page_cgroup_zoneinfo(pc);
b69408e8 679 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
4b3bde4c
BS
680 if (mem_cgroup_is_root(pc->mem_cgroup))
681 return;
682 VM_BUG_ON(list_empty(&pc->lru));
08e552c6
KH
683 list_del_init(&pc->lru);
684 return;
6d12e2d8
KH
685}
686
08e552c6 687void mem_cgroup_del_lru(struct page *page)
6d12e2d8 688{
08e552c6
KH
689 mem_cgroup_del_lru_list(page, page_lru(page));
690}
b69408e8 691
08e552c6
KH
692void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
693{
694 struct mem_cgroup_per_zone *mz;
695 struct page_cgroup *pc;
b69408e8 696
f8d66542 697 if (mem_cgroup_disabled())
08e552c6 698 return;
6d12e2d8 699
08e552c6 700 pc = lookup_page_cgroup(page);
bd112db8
DN
701 /*
702 * Used bit is set without atomic ops but after smp_wmb().
703 * For making pc->mem_cgroup visible, insert smp_rmb() here.
704 */
08e552c6 705 smp_rmb();
4b3bde4c
BS
706 /* unused or root page is not rotated. */
707 if (!PageCgroupUsed(pc) || mem_cgroup_is_root(pc->mem_cgroup))
08e552c6
KH
708 return;
709 mz = page_cgroup_zoneinfo(pc);
710 list_move(&pc->lru, &mz->lists[lru]);
6d12e2d8
KH
711}
712
08e552c6 713void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
66e1707b 714{
08e552c6
KH
715 struct page_cgroup *pc;
716 struct mem_cgroup_per_zone *mz;
6d12e2d8 717
f8d66542 718 if (mem_cgroup_disabled())
08e552c6
KH
719 return;
720 pc = lookup_page_cgroup(page);
4b3bde4c 721 VM_BUG_ON(PageCgroupAcctLRU(pc));
bd112db8
DN
722 /*
723 * Used bit is set without atomic ops but after smp_wmb().
724 * For making pc->mem_cgroup visible, insert smp_rmb() here.
725 */
08e552c6
KH
726 smp_rmb();
727 if (!PageCgroupUsed(pc))
894bc310 728 return;
b69408e8 729
08e552c6 730 mz = page_cgroup_zoneinfo(pc);
b69408e8 731 MEM_CGROUP_ZSTAT(mz, lru) += 1;
4b3bde4c
BS
732 SetPageCgroupAcctLRU(pc);
733 if (mem_cgroup_is_root(pc->mem_cgroup))
734 return;
08e552c6
KH
735 list_add(&pc->lru, &mz->lists[lru]);
736}
544122e5 737
08e552c6 738/*
544122e5
KH
739 * At handling SwapCache, pc->mem_cgroup may be changed while it's linked to
740 * lru because the page may.be reused after it's fully uncharged (because of
741 * SwapCache behavior).To handle that, unlink page_cgroup from LRU when charge
742 * it again. This function is only used to charge SwapCache. It's done under
743 * lock_page and expected that zone->lru_lock is never held.
08e552c6 744 */
544122e5 745static void mem_cgroup_lru_del_before_commit_swapcache(struct page *page)
08e552c6 746{
544122e5
KH
747 unsigned long flags;
748 struct zone *zone = page_zone(page);
749 struct page_cgroup *pc = lookup_page_cgroup(page);
750
751 spin_lock_irqsave(&zone->lru_lock, flags);
752 /*
753 * Forget old LRU when this page_cgroup is *not* used. This Used bit
754 * is guarded by lock_page() because the page is SwapCache.
755 */
756 if (!PageCgroupUsed(pc))
757 mem_cgroup_del_lru_list(page, page_lru(page));
758 spin_unlock_irqrestore(&zone->lru_lock, flags);
08e552c6
KH
759}
760
544122e5
KH
761static void mem_cgroup_lru_add_after_commit_swapcache(struct page *page)
762{
763 unsigned long flags;
764 struct zone *zone = page_zone(page);
765 struct page_cgroup *pc = lookup_page_cgroup(page);
766
767 spin_lock_irqsave(&zone->lru_lock, flags);
768 /* link when the page is linked to LRU but page_cgroup isn't */
4b3bde4c 769 if (PageLRU(page) && !PageCgroupAcctLRU(pc))
544122e5
KH
770 mem_cgroup_add_lru_list(page, page_lru(page));
771 spin_unlock_irqrestore(&zone->lru_lock, flags);
772}
773
774
08e552c6
KH
775void mem_cgroup_move_lists(struct page *page,
776 enum lru_list from, enum lru_list to)
777{
f8d66542 778 if (mem_cgroup_disabled())
08e552c6
KH
779 return;
780 mem_cgroup_del_lru_list(page, from);
781 mem_cgroup_add_lru_list(page, to);
66e1707b
BS
782}
783
4c4a2214
DR
784int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
785{
786 int ret;
0b7f569e 787 struct mem_cgroup *curr = NULL;
4c4a2214
DR
788
789 task_lock(task);
0b7f569e
KH
790 rcu_read_lock();
791 curr = try_get_mem_cgroup_from_mm(task->mm);
792 rcu_read_unlock();
4c4a2214 793 task_unlock(task);
0b7f569e
KH
794 if (!curr)
795 return 0;
d31f56db
DN
796 /*
797 * We should check use_hierarchy of "mem" not "curr". Because checking
798 * use_hierarchy of "curr" here make this function true if hierarchy is
799 * enabled in "curr" and "curr" is a child of "mem" in *cgroup*
800 * hierarchy(even if use_hierarchy is disabled in "mem").
801 */
802 if (mem->use_hierarchy)
0b7f569e
KH
803 ret = css_is_ancestor(&curr->css, &mem->css);
804 else
805 ret = (curr == mem);
806 css_put(&curr->css);
4c4a2214
DR
807 return ret;
808}
809
6c48a1d0
KH
810/*
811 * prev_priority control...this will be used in memory reclaim path.
812 */
813int mem_cgroup_get_reclaim_priority(struct mem_cgroup *mem)
814{
2733c06a
KM
815 int prev_priority;
816
817 spin_lock(&mem->reclaim_param_lock);
818 prev_priority = mem->prev_priority;
819 spin_unlock(&mem->reclaim_param_lock);
820
821 return prev_priority;
6c48a1d0
KH
822}
823
824void mem_cgroup_note_reclaim_priority(struct mem_cgroup *mem, int priority)
825{
2733c06a 826 spin_lock(&mem->reclaim_param_lock);
6c48a1d0
KH
827 if (priority < mem->prev_priority)
828 mem->prev_priority = priority;
2733c06a 829 spin_unlock(&mem->reclaim_param_lock);
6c48a1d0
KH
830}
831
832void mem_cgroup_record_reclaim_priority(struct mem_cgroup *mem, int priority)
833{
2733c06a 834 spin_lock(&mem->reclaim_param_lock);
6c48a1d0 835 mem->prev_priority = priority;
2733c06a 836 spin_unlock(&mem->reclaim_param_lock);
6c48a1d0
KH
837}
838
c772be93 839static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
14797e23
KM
840{
841 unsigned long active;
842 unsigned long inactive;
c772be93
KM
843 unsigned long gb;
844 unsigned long inactive_ratio;
14797e23 845
14067bb3
KH
846 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_ANON);
847 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_ANON);
14797e23 848
c772be93
KM
849 gb = (inactive + active) >> (30 - PAGE_SHIFT);
850 if (gb)
851 inactive_ratio = int_sqrt(10 * gb);
852 else
853 inactive_ratio = 1;
854
855 if (present_pages) {
856 present_pages[0] = inactive;
857 present_pages[1] = active;
858 }
859
860 return inactive_ratio;
861}
862
863int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
864{
865 unsigned long active;
866 unsigned long inactive;
867 unsigned long present_pages[2];
868 unsigned long inactive_ratio;
869
870 inactive_ratio = calc_inactive_ratio(memcg, present_pages);
871
872 inactive = present_pages[0];
873 active = present_pages[1];
874
875 if (inactive * inactive_ratio < active)
14797e23
KM
876 return 1;
877
878 return 0;
879}
880
56e49d21
RR
881int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
882{
883 unsigned long active;
884 unsigned long inactive;
885
886 inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_FILE);
887 active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_FILE);
888
889 return (active > inactive);
890}
891
a3d8e054
KM
892unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup *memcg,
893 struct zone *zone,
894 enum lru_list lru)
895{
896 int nid = zone->zone_pgdat->node_id;
897 int zid = zone_idx(zone);
898 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
899
900 return MEM_CGROUP_ZSTAT(mz, lru);
901}
902
3e2f41f1
KM
903struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
904 struct zone *zone)
905{
906 int nid = zone->zone_pgdat->node_id;
907 int zid = zone_idx(zone);
908 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
909
910 return &mz->reclaim_stat;
911}
912
913struct zone_reclaim_stat *
914mem_cgroup_get_reclaim_stat_from_page(struct page *page)
915{
916 struct page_cgroup *pc;
917 struct mem_cgroup_per_zone *mz;
918
919 if (mem_cgroup_disabled())
920 return NULL;
921
922 pc = lookup_page_cgroup(page);
bd112db8
DN
923 /*
924 * Used bit is set without atomic ops but after smp_wmb().
925 * For making pc->mem_cgroup visible, insert smp_rmb() here.
926 */
927 smp_rmb();
928 if (!PageCgroupUsed(pc))
929 return NULL;
930
3e2f41f1
KM
931 mz = page_cgroup_zoneinfo(pc);
932 if (!mz)
933 return NULL;
934
935 return &mz->reclaim_stat;
936}
937
66e1707b
BS
938unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
939 struct list_head *dst,
940 unsigned long *scanned, int order,
941 int mode, struct zone *z,
942 struct mem_cgroup *mem_cont,
4f98a2fe 943 int active, int file)
66e1707b
BS
944{
945 unsigned long nr_taken = 0;
946 struct page *page;
947 unsigned long scan;
948 LIST_HEAD(pc_list);
949 struct list_head *src;
ff7283fa 950 struct page_cgroup *pc, *tmp;
1ecaab2b
KH
951 int nid = z->zone_pgdat->node_id;
952 int zid = zone_idx(z);
953 struct mem_cgroup_per_zone *mz;
b7c46d15 954 int lru = LRU_FILE * file + active;
2ffebca6 955 int ret;
66e1707b 956
cf475ad2 957 BUG_ON(!mem_cont);
1ecaab2b 958 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
b69408e8 959 src = &mz->lists[lru];
66e1707b 960
ff7283fa
KH
961 scan = 0;
962 list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
436c6541 963 if (scan >= nr_to_scan)
ff7283fa 964 break;
08e552c6
KH
965
966 page = pc->page;
52d4b9ac
KH
967 if (unlikely(!PageCgroupUsed(pc)))
968 continue;
436c6541 969 if (unlikely(!PageLRU(page)))
ff7283fa 970 continue;
ff7283fa 971
436c6541 972 scan++;
2ffebca6
KH
973 ret = __isolate_lru_page(page, mode, file);
974 switch (ret) {
975 case 0:
66e1707b 976 list_move(&page->lru, dst);
2ffebca6 977 mem_cgroup_del_lru(page);
66e1707b 978 nr_taken++;
2ffebca6
KH
979 break;
980 case -EBUSY:
981 /* we don't affect global LRU but rotate in our LRU */
982 mem_cgroup_rotate_lru_list(page, page_lru(page));
983 break;
984 default:
985 break;
66e1707b
BS
986 }
987 }
988
66e1707b
BS
989 *scanned = scan;
990 return nr_taken;
991}
992
6d61ef40
BS
993#define mem_cgroup_from_res_counter(counter, member) \
994 container_of(counter, struct mem_cgroup, member)
995
b85a96c0
DN
996static bool mem_cgroup_check_under_limit(struct mem_cgroup *mem)
997{
998 if (do_swap_account) {
999 if (res_counter_check_under_limit(&mem->res) &&
1000 res_counter_check_under_limit(&mem->memsw))
1001 return true;
1002 } else
1003 if (res_counter_check_under_limit(&mem->res))
1004 return true;
1005 return false;
1006}
1007
a7885eb8
KM
1008static unsigned int get_swappiness(struct mem_cgroup *memcg)
1009{
1010 struct cgroup *cgrp = memcg->css.cgroup;
1011 unsigned int swappiness;
1012
1013 /* root ? */
1014 if (cgrp->parent == NULL)
1015 return vm_swappiness;
1016
1017 spin_lock(&memcg->reclaim_param_lock);
1018 swappiness = memcg->swappiness;
1019 spin_unlock(&memcg->reclaim_param_lock);
1020
1021 return swappiness;
1022}
1023
81d39c20
KH
1024static int mem_cgroup_count_children_cb(struct mem_cgroup *mem, void *data)
1025{
1026 int *val = data;
1027 (*val)++;
1028 return 0;
1029}
e222432b
BS
1030
1031/**
1032 * mem_cgroup_print_mem_info: Called from OOM with tasklist_lock held in read mode.
1033 * @memcg: The memory cgroup that went over limit
1034 * @p: Task that is going to be killed
1035 *
1036 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1037 * enabled
1038 */
1039void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1040{
1041 struct cgroup *task_cgrp;
1042 struct cgroup *mem_cgrp;
1043 /*
1044 * Need a buffer in BSS, can't rely on allocations. The code relies
1045 * on the assumption that OOM is serialized for memory controller.
1046 * If this assumption is broken, revisit this code.
1047 */
1048 static char memcg_name[PATH_MAX];
1049 int ret;
1050
d31f56db 1051 if (!memcg || !p)
e222432b
BS
1052 return;
1053
1054
1055 rcu_read_lock();
1056
1057 mem_cgrp = memcg->css.cgroup;
1058 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1059
1060 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1061 if (ret < 0) {
1062 /*
1063 * Unfortunately, we are unable to convert to a useful name
1064 * But we'll still print out the usage information
1065 */
1066 rcu_read_unlock();
1067 goto done;
1068 }
1069 rcu_read_unlock();
1070
1071 printk(KERN_INFO "Task in %s killed", memcg_name);
1072
1073 rcu_read_lock();
1074 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1075 if (ret < 0) {
1076 rcu_read_unlock();
1077 goto done;
1078 }
1079 rcu_read_unlock();
1080
1081 /*
1082 * Continues from above, so we don't need an KERN_ level
1083 */
1084 printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1085done:
1086
1087 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1088 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1089 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1090 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1091 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1092 "failcnt %llu\n",
1093 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1094 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1095 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1096}
1097
81d39c20
KH
1098/*
1099 * This function returns the number of memcg under hierarchy tree. Returns
1100 * 1(self count) if no children.
1101 */
1102static int mem_cgroup_count_children(struct mem_cgroup *mem)
1103{
1104 int num = 0;
1105 mem_cgroup_walk_tree(mem, &num, mem_cgroup_count_children_cb);
1106 return num;
1107}
1108
6d61ef40 1109/*
04046e1a
KH
1110 * Visit the first child (need not be the first child as per the ordering
1111 * of the cgroup list, since we track last_scanned_child) of @mem and use
1112 * that to reclaim free pages from.
1113 */
1114static struct mem_cgroup *
1115mem_cgroup_select_victim(struct mem_cgroup *root_mem)
1116{
1117 struct mem_cgroup *ret = NULL;
1118 struct cgroup_subsys_state *css;
1119 int nextid, found;
1120
1121 if (!root_mem->use_hierarchy) {
1122 css_get(&root_mem->css);
1123 ret = root_mem;
1124 }
1125
1126 while (!ret) {
1127 rcu_read_lock();
1128 nextid = root_mem->last_scanned_child + 1;
1129 css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
1130 &found);
1131 if (css && css_tryget(css))
1132 ret = container_of(css, struct mem_cgroup, css);
1133
1134 rcu_read_unlock();
1135 /* Updates scanning parameter */
1136 spin_lock(&root_mem->reclaim_param_lock);
1137 if (!css) {
1138 /* this means start scan from ID:1 */
1139 root_mem->last_scanned_child = 0;
1140 } else
1141 root_mem->last_scanned_child = found;
1142 spin_unlock(&root_mem->reclaim_param_lock);
1143 }
1144
1145 return ret;
1146}
1147
1148/*
1149 * Scan the hierarchy if needed to reclaim memory. We remember the last child
1150 * we reclaimed from, so that we don't end up penalizing one child extensively
1151 * based on its position in the children list.
6d61ef40
BS
1152 *
1153 * root_mem is the original ancestor that we've been reclaim from.
04046e1a
KH
1154 *
1155 * We give up and return to the caller when we visit root_mem twice.
1156 * (other groups can be removed while we're walking....)
81d39c20
KH
1157 *
1158 * If shrink==true, for avoiding to free too much, this returns immedieately.
6d61ef40
BS
1159 */
1160static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
4e416953 1161 struct zone *zone,
75822b44
BS
1162 gfp_t gfp_mask,
1163 unsigned long reclaim_options)
6d61ef40 1164{
04046e1a
KH
1165 struct mem_cgroup *victim;
1166 int ret, total = 0;
1167 int loop = 0;
75822b44
BS
1168 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1169 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
4e416953
BS
1170 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1171 unsigned long excess = mem_cgroup_get_excess(root_mem);
04046e1a 1172
22a668d7
KH
1173 /* If memsw_is_minimum==1, swap-out is of-no-use. */
1174 if (root_mem->memsw_is_minimum)
1175 noswap = true;
1176
4e416953 1177 while (1) {
04046e1a 1178 victim = mem_cgroup_select_victim(root_mem);
4e416953 1179 if (victim == root_mem) {
04046e1a 1180 loop++;
cdec2e42
KH
1181 if (loop >= 1)
1182 drain_all_stock_async();
4e416953
BS
1183 if (loop >= 2) {
1184 /*
1185 * If we have not been able to reclaim
1186 * anything, it might because there are
1187 * no reclaimable pages under this hierarchy
1188 */
1189 if (!check_soft || !total) {
1190 css_put(&victim->css);
1191 break;
1192 }
1193 /*
1194 * We want to do more targetted reclaim.
1195 * excess >> 2 is not to excessive so as to
1196 * reclaim too much, nor too less that we keep
1197 * coming back to reclaim from this cgroup
1198 */
1199 if (total >= (excess >> 2) ||
1200 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1201 css_put(&victim->css);
1202 break;
1203 }
1204 }
1205 }
04046e1a
KH
1206 if (!mem_cgroup_local_usage(&victim->stat)) {
1207 /* this cgroup's local usage == 0 */
1208 css_put(&victim->css);
6d61ef40
BS
1209 continue;
1210 }
04046e1a 1211 /* we use swappiness of local cgroup */
4e416953
BS
1212 if (check_soft)
1213 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1214 noswap, get_swappiness(victim), zone,
1215 zone->zone_pgdat->node_id);
1216 else
1217 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1218 noswap, get_swappiness(victim));
04046e1a 1219 css_put(&victim->css);
81d39c20
KH
1220 /*
1221 * At shrinking usage, we can't check we should stop here or
1222 * reclaim more. It's depends on callers. last_scanned_child
1223 * will work enough for keeping fairness under tree.
1224 */
1225 if (shrink)
1226 return ret;
04046e1a 1227 total += ret;
4e416953
BS
1228 if (check_soft) {
1229 if (res_counter_check_under_soft_limit(&root_mem->res))
1230 return total;
1231 } else if (mem_cgroup_check_under_limit(root_mem))
04046e1a 1232 return 1 + total;
6d61ef40 1233 }
04046e1a 1234 return total;
6d61ef40
BS
1235}
1236
a636b327
KH
1237bool mem_cgroup_oom_called(struct task_struct *task)
1238{
1239 bool ret = false;
1240 struct mem_cgroup *mem;
1241 struct mm_struct *mm;
1242
1243 rcu_read_lock();
1244 mm = task->mm;
1245 if (!mm)
1246 mm = &init_mm;
1247 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
1248 if (mem && time_before(jiffies, mem->last_oom_jiffies + HZ/10))
1249 ret = true;
1250 rcu_read_unlock();
1251 return ret;
1252}
0b7f569e
KH
1253
1254static int record_last_oom_cb(struct mem_cgroup *mem, void *data)
1255{
1256 mem->last_oom_jiffies = jiffies;
1257 return 0;
1258}
1259
1260static void record_last_oom(struct mem_cgroup *mem)
1261{
1262 mem_cgroup_walk_tree(mem, NULL, record_last_oom_cb);
1263}
1264
d69b042f
BS
1265/*
1266 * Currently used to update mapped file statistics, but the routine can be
1267 * generalized to update other statistics as well.
1268 */
d8046582 1269void mem_cgroup_update_file_mapped(struct page *page, int val)
d69b042f
BS
1270{
1271 struct mem_cgroup *mem;
1272 struct mem_cgroup_stat *stat;
1273 struct mem_cgroup_stat_cpu *cpustat;
1274 int cpu;
1275 struct page_cgroup *pc;
1276
d69b042f
BS
1277 pc = lookup_page_cgroup(page);
1278 if (unlikely(!pc))
1279 return;
1280
1281 lock_page_cgroup(pc);
1282 mem = pc->mem_cgroup;
1283 if (!mem)
1284 goto done;
1285
1286 if (!PageCgroupUsed(pc))
1287 goto done;
1288
1289 /*
1290 * Preemption is already disabled, we don't need get_cpu()
1291 */
1292 cpu = smp_processor_id();
1293 stat = &mem->stat;
1294 cpustat = &stat->cpustat[cpu];
1295
d8046582 1296 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED, val);
d69b042f
BS
1297done:
1298 unlock_page_cgroup(pc);
1299}
0b7f569e 1300
cdec2e42
KH
1301/*
1302 * size of first charge trial. "32" comes from vmscan.c's magic value.
1303 * TODO: maybe necessary to use big numbers in big irons.
1304 */
1305#define CHARGE_SIZE (32 * PAGE_SIZE)
1306struct memcg_stock_pcp {
1307 struct mem_cgroup *cached; /* this never be root cgroup */
1308 int charge;
1309 struct work_struct work;
1310};
1311static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
1312static atomic_t memcg_drain_count;
1313
1314/*
1315 * Try to consume stocked charge on this cpu. If success, PAGE_SIZE is consumed
1316 * from local stock and true is returned. If the stock is 0 or charges from a
1317 * cgroup which is not current target, returns false. This stock will be
1318 * refilled.
1319 */
1320static bool consume_stock(struct mem_cgroup *mem)
1321{
1322 struct memcg_stock_pcp *stock;
1323 bool ret = true;
1324
1325 stock = &get_cpu_var(memcg_stock);
1326 if (mem == stock->cached && stock->charge)
1327 stock->charge -= PAGE_SIZE;
1328 else /* need to call res_counter_charge */
1329 ret = false;
1330 put_cpu_var(memcg_stock);
1331 return ret;
1332}
1333
1334/*
1335 * Returns stocks cached in percpu to res_counter and reset cached information.
1336 */
1337static void drain_stock(struct memcg_stock_pcp *stock)
1338{
1339 struct mem_cgroup *old = stock->cached;
1340
1341 if (stock->charge) {
1342 res_counter_uncharge(&old->res, stock->charge);
1343 if (do_swap_account)
1344 res_counter_uncharge(&old->memsw, stock->charge);
1345 }
1346 stock->cached = NULL;
1347 stock->charge = 0;
1348}
1349
1350/*
1351 * This must be called under preempt disabled or must be called by
1352 * a thread which is pinned to local cpu.
1353 */
1354static void drain_local_stock(struct work_struct *dummy)
1355{
1356 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
1357 drain_stock(stock);
1358}
1359
1360/*
1361 * Cache charges(val) which is from res_counter, to local per_cpu area.
1362 * This will be consumed by consumt_stock() function, later.
1363 */
1364static void refill_stock(struct mem_cgroup *mem, int val)
1365{
1366 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
1367
1368 if (stock->cached != mem) { /* reset if necessary */
1369 drain_stock(stock);
1370 stock->cached = mem;
1371 }
1372 stock->charge += val;
1373 put_cpu_var(memcg_stock);
1374}
1375
1376/*
1377 * Tries to drain stocked charges in other cpus. This function is asynchronous
1378 * and just put a work per cpu for draining localy on each cpu. Caller can
1379 * expects some charges will be back to res_counter later but cannot wait for
1380 * it.
1381 */
1382static void drain_all_stock_async(void)
1383{
1384 int cpu;
1385 /* This function is for scheduling "drain" in asynchronous way.
1386 * The result of "drain" is not directly handled by callers. Then,
1387 * if someone is calling drain, we don't have to call drain more.
1388 * Anyway, WORK_STRUCT_PENDING check in queue_work_on() will catch if
1389 * there is a race. We just do loose check here.
1390 */
1391 if (atomic_read(&memcg_drain_count))
1392 return;
1393 /* Notify other cpus that system-wide "drain" is running */
1394 atomic_inc(&memcg_drain_count);
1395 get_online_cpus();
1396 for_each_online_cpu(cpu) {
1397 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
1398 schedule_work_on(cpu, &stock->work);
1399 }
1400 put_online_cpus();
1401 atomic_dec(&memcg_drain_count);
1402 /* We don't wait for flush_work */
1403}
1404
1405/* This is a synchronous drain interface. */
1406static void drain_all_stock_sync(void)
1407{
1408 /* called when force_empty is called */
1409 atomic_inc(&memcg_drain_count);
1410 schedule_on_each_cpu(drain_local_stock);
1411 atomic_dec(&memcg_drain_count);
1412}
1413
1414static int __cpuinit memcg_stock_cpu_callback(struct notifier_block *nb,
1415 unsigned long action,
1416 void *hcpu)
1417{
1418 int cpu = (unsigned long)hcpu;
1419 struct memcg_stock_pcp *stock;
1420
1421 if (action != CPU_DEAD)
1422 return NOTIFY_OK;
1423 stock = &per_cpu(memcg_stock, cpu);
1424 drain_stock(stock);
1425 return NOTIFY_OK;
1426}
1427
f817ed48
KH
1428/*
1429 * Unlike exported interface, "oom" parameter is added. if oom==true,
1430 * oom-killer can be invoked.
8a9f3ccd 1431 */
f817ed48 1432static int __mem_cgroup_try_charge(struct mm_struct *mm,
8c7c6e34 1433 gfp_t gfp_mask, struct mem_cgroup **memcg,
f64c3f54 1434 bool oom, struct page *page)
8a9f3ccd 1435{
4e649152 1436 struct mem_cgroup *mem, *mem_over_limit;
7a81b88c 1437 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
4e649152 1438 struct res_counter *fail_res;
cdec2e42 1439 int csize = CHARGE_SIZE;
a636b327
KH
1440
1441 if (unlikely(test_thread_flag(TIF_MEMDIE))) {
1442 /* Don't account this! */
1443 *memcg = NULL;
1444 return 0;
1445 }
1446
8a9f3ccd 1447 /*
3be91277
HD
1448 * We always charge the cgroup the mm_struct belongs to.
1449 * The mm_struct's mem_cgroup changes on task migration if the
8a9f3ccd
BS
1450 * thread group leader migrates. It's possible that mm is not
1451 * set, if so charge the init_mm (happens for pagecache usage).
1452 */
54595fe2
KH
1453 mem = *memcg;
1454 if (likely(!mem)) {
1455 mem = try_get_mem_cgroup_from_mm(mm);
7a81b88c 1456 *memcg = mem;
e8589cc1 1457 } else {
7a81b88c 1458 css_get(&mem->css);
e8589cc1 1459 }
54595fe2
KH
1460 if (unlikely(!mem))
1461 return 0;
1462
46f7e602 1463 VM_BUG_ON(css_is_removed(&mem->css));
cdec2e42
KH
1464 if (mem_cgroup_is_root(mem))
1465 goto done;
8a9f3ccd 1466
8c7c6e34 1467 while (1) {
0c3e73e8 1468 int ret = 0;
75822b44 1469 unsigned long flags = 0;
7a81b88c 1470
cdec2e42
KH
1471 if (consume_stock(mem))
1472 goto charged;
1473
1474 ret = res_counter_charge(&mem->res, csize, &fail_res);
8c7c6e34
KH
1475 if (likely(!ret)) {
1476 if (!do_swap_account)
1477 break;
cdec2e42 1478 ret = res_counter_charge(&mem->memsw, csize, &fail_res);
8c7c6e34
KH
1479 if (likely(!ret))
1480 break;
1481 /* mem+swap counter fails */
cdec2e42 1482 res_counter_uncharge(&mem->res, csize);
75822b44 1483 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
6d61ef40
BS
1484 mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1485 memsw);
1486 } else
1487 /* mem counter fails */
1488 mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1489 res);
1490
cdec2e42
KH
1491 /* reduce request size and retry */
1492 if (csize > PAGE_SIZE) {
1493 csize = PAGE_SIZE;
1494 continue;
1495 }
3be91277 1496 if (!(gfp_mask & __GFP_WAIT))
7a81b88c 1497 goto nomem;
e1a1cd59 1498
4e416953
BS
1499 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
1500 gfp_mask, flags);
4d1c6273
DN
1501 if (ret)
1502 continue;
66e1707b
BS
1503
1504 /*
8869b8f6
HD
1505 * try_to_free_mem_cgroup_pages() might not give us a full
1506 * picture of reclaim. Some pages are reclaimed and might be
1507 * moved to swap cache or just unmapped from the cgroup.
1508 * Check the limit again to see if the reclaim reduced the
1509 * current usage of the cgroup before giving up
8c7c6e34 1510 *
8869b8f6 1511 */
b85a96c0
DN
1512 if (mem_cgroup_check_under_limit(mem_over_limit))
1513 continue;
3be91277 1514
8033b97c
DN
1515 /* try to avoid oom while someone is moving charge */
1516 if (mc.moving_task && current != mc.moving_task) {
1517 struct mem_cgroup *from, *to;
1518 bool do_continue = false;
1519 /*
1520 * There is a small race that "from" or "to" can be
1521 * freed by rmdir, so we use css_tryget().
1522 */
1523 rcu_read_lock();
1524 from = mc.from;
1525 to = mc.to;
1526 if (from && css_tryget(&from->css)) {
1527 if (mem_over_limit->use_hierarchy)
1528 do_continue = css_is_ancestor(
1529 &from->css,
1530 &mem_over_limit->css);
1531 else
1532 do_continue = (from == mem_over_limit);
1533 css_put(&from->css);
1534 }
1535 if (!do_continue && to && css_tryget(&to->css)) {
1536 if (mem_over_limit->use_hierarchy)
1537 do_continue = css_is_ancestor(
1538 &to->css,
1539 &mem_over_limit->css);
1540 else
1541 do_continue = (to == mem_over_limit);
1542 css_put(&to->css);
1543 }
1544 rcu_read_unlock();
1545 if (do_continue) {
1546 DEFINE_WAIT(wait);
1547 prepare_to_wait(&mc.waitq, &wait,
1548 TASK_INTERRUPTIBLE);
1549 /* moving charge context might have finished. */
1550 if (mc.moving_task)
1551 schedule();
1552 finish_wait(&mc.waitq, &wait);
1553 continue;
1554 }
1555 }
1556
3be91277 1557 if (!nr_retries--) {
a636b327 1558 if (oom) {
88700756 1559 mem_cgroup_out_of_memory(mem_over_limit, gfp_mask);
0b7f569e 1560 record_last_oom(mem_over_limit);
a636b327 1561 }
7a81b88c 1562 goto nomem;
66e1707b 1563 }
8a9f3ccd 1564 }
cdec2e42
KH
1565 if (csize > PAGE_SIZE)
1566 refill_stock(mem, csize - PAGE_SIZE);
1567charged:
f64c3f54 1568 /*
4e649152
KH
1569 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
1570 * if they exceeds softlimit.
f64c3f54 1571 */
4ffef5fe 1572 if (page && mem_cgroup_soft_limit_check(mem))
4e649152 1573 mem_cgroup_update_tree(mem, page);
0c3e73e8 1574done:
7a81b88c
KH
1575 return 0;
1576nomem:
1577 css_put(&mem->css);
1578 return -ENOMEM;
1579}
8a9f3ccd 1580
a3032a2c
DN
1581/*
1582 * Somemtimes we have to undo a charge we got by try_charge().
1583 * This function is for that and do uncharge, put css's refcnt.
1584 * gotten by try_charge().
1585 */
854ffa8d
DN
1586static void __mem_cgroup_cancel_charge(struct mem_cgroup *mem,
1587 unsigned long count)
a3032a2c
DN
1588{
1589 if (!mem_cgroup_is_root(mem)) {
854ffa8d 1590 res_counter_uncharge(&mem->res, PAGE_SIZE * count);
a3032a2c 1591 if (do_swap_account)
854ffa8d
DN
1592 res_counter_uncharge(&mem->memsw, PAGE_SIZE * count);
1593 VM_BUG_ON(test_bit(CSS_ROOT, &mem->css.flags));
1594 WARN_ON_ONCE(count > INT_MAX);
1595 __css_put(&mem->css, (int)count);
a3032a2c 1596 }
854ffa8d
DN
1597 /* we don't need css_put for root */
1598}
1599
1600static void mem_cgroup_cancel_charge(struct mem_cgroup *mem)
1601{
1602 __mem_cgroup_cancel_charge(mem, 1);
a3032a2c
DN
1603}
1604
a3b2d692
KH
1605/*
1606 * A helper function to get mem_cgroup from ID. must be called under
1607 * rcu_read_lock(). The caller must check css_is_removed() or some if
1608 * it's concern. (dropping refcnt from swap can be called against removed
1609 * memcg.)
1610 */
1611static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
1612{
1613 struct cgroup_subsys_state *css;
1614
1615 /* ID 0 is unused ID */
1616 if (!id)
1617 return NULL;
1618 css = css_lookup(&mem_cgroup_subsys, id);
1619 if (!css)
1620 return NULL;
1621 return container_of(css, struct mem_cgroup, css);
1622}
1623
e42d9d5d 1624struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
b5a84319 1625{
e42d9d5d 1626 struct mem_cgroup *mem = NULL;
3c776e64 1627 struct page_cgroup *pc;
a3b2d692 1628 unsigned short id;
b5a84319
KH
1629 swp_entry_t ent;
1630
3c776e64
DN
1631 VM_BUG_ON(!PageLocked(page));
1632
3c776e64 1633 pc = lookup_page_cgroup(page);
c0bd3f63 1634 lock_page_cgroup(pc);
a3b2d692 1635 if (PageCgroupUsed(pc)) {
3c776e64 1636 mem = pc->mem_cgroup;
a3b2d692
KH
1637 if (mem && !css_tryget(&mem->css))
1638 mem = NULL;
e42d9d5d 1639 } else if (PageSwapCache(page)) {
3c776e64 1640 ent.val = page_private(page);
a3b2d692
KH
1641 id = lookup_swap_cgroup(ent);
1642 rcu_read_lock();
1643 mem = mem_cgroup_lookup(id);
1644 if (mem && !css_tryget(&mem->css))
1645 mem = NULL;
1646 rcu_read_unlock();
3c776e64 1647 }
c0bd3f63 1648 unlock_page_cgroup(pc);
b5a84319
KH
1649 return mem;
1650}
1651
7a81b88c 1652/*
a5e924f5 1653 * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
7a81b88c
KH
1654 * USED state. If already USED, uncharge and return.
1655 */
1656
1657static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
1658 struct page_cgroup *pc,
1659 enum charge_type ctype)
1660{
7a81b88c
KH
1661 /* try_charge() can return NULL to *memcg, taking care of it. */
1662 if (!mem)
1663 return;
52d4b9ac
KH
1664
1665 lock_page_cgroup(pc);
1666 if (unlikely(PageCgroupUsed(pc))) {
1667 unlock_page_cgroup(pc);
a3032a2c 1668 mem_cgroup_cancel_charge(mem);
7a81b88c 1669 return;
52d4b9ac 1670 }
4b3bde4c 1671
8a9f3ccd 1672 pc->mem_cgroup = mem;
261fb61a
KH
1673 /*
1674 * We access a page_cgroup asynchronously without lock_page_cgroup().
1675 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
1676 * is accessed after testing USED bit. To make pc->mem_cgroup visible
1677 * before USED bit, we need memory barrier here.
1678 * See mem_cgroup_add_lru_list(), etc.
1679 */
08e552c6 1680 smp_wmb();
4b3bde4c
BS
1681 switch (ctype) {
1682 case MEM_CGROUP_CHARGE_TYPE_CACHE:
1683 case MEM_CGROUP_CHARGE_TYPE_SHMEM:
1684 SetPageCgroupCache(pc);
1685 SetPageCgroupUsed(pc);
1686 break;
1687 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
1688 ClearPageCgroupCache(pc);
1689 SetPageCgroupUsed(pc);
1690 break;
1691 default:
1692 break;
1693 }
3be91277 1694
08e552c6 1695 mem_cgroup_charge_statistics(mem, pc, true);
52d4b9ac 1696
52d4b9ac 1697 unlock_page_cgroup(pc);
7a81b88c 1698}
66e1707b 1699
f817ed48 1700/**
57f9fd7d 1701 * __mem_cgroup_move_account - move account of the page
f817ed48
KH
1702 * @pc: page_cgroup of the page.
1703 * @from: mem_cgroup which the page is moved from.
1704 * @to: mem_cgroup which the page is moved to. @from != @to.
854ffa8d 1705 * @uncharge: whether we should call uncharge and css_put against @from.
f817ed48
KH
1706 *
1707 * The caller must confirm following.
08e552c6 1708 * - page is not on LRU (isolate_page() is useful.)
57f9fd7d 1709 * - the pc is locked, used, and ->mem_cgroup points to @from.
f817ed48 1710 *
854ffa8d
DN
1711 * This function doesn't do "charge" nor css_get to new cgroup. It should be
1712 * done by a caller(__mem_cgroup_try_charge would be usefull). If @uncharge is
1713 * true, this function does "uncharge" from old cgroup, but it doesn't if
1714 * @uncharge is false, so a caller should do "uncharge".
f817ed48
KH
1715 */
1716
57f9fd7d 1717static void __mem_cgroup_move_account(struct page_cgroup *pc,
854ffa8d 1718 struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
f817ed48 1719{
d69b042f
BS
1720 struct page *page;
1721 int cpu;
1722 struct mem_cgroup_stat *stat;
1723 struct mem_cgroup_stat_cpu *cpustat;
f817ed48 1724
f817ed48 1725 VM_BUG_ON(from == to);
08e552c6 1726 VM_BUG_ON(PageLRU(pc->page));
57f9fd7d
DN
1727 VM_BUG_ON(!PageCgroupLocked(pc));
1728 VM_BUG_ON(!PageCgroupUsed(pc));
1729 VM_BUG_ON(pc->mem_cgroup != from);
f817ed48 1730
d69b042f 1731 page = pc->page;
d8046582 1732 if (page_mapped(page) && !PageAnon(page)) {
d69b042f
BS
1733 cpu = smp_processor_id();
1734 /* Update mapped_file data for mem_cgroup "from" */
1735 stat = &from->stat;
1736 cpustat = &stat->cpustat[cpu];
d8046582 1737 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED,
d69b042f
BS
1738 -1);
1739
1740 /* Update mapped_file data for mem_cgroup "to" */
1741 stat = &to->stat;
1742 cpustat = &stat->cpustat[cpu];
d8046582 1743 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_FILE_MAPPED,
d69b042f
BS
1744 1);
1745 }
854ffa8d
DN
1746 mem_cgroup_charge_statistics(from, pc, false);
1747 if (uncharge)
1748 /* This is not "cancel", but cancel_charge does all we need. */
1749 mem_cgroup_cancel_charge(from);
d69b042f 1750
854ffa8d 1751 /* caller should have done css_get */
08e552c6
KH
1752 pc->mem_cgroup = to;
1753 mem_cgroup_charge_statistics(to, pc, true);
88703267
KH
1754 /*
1755 * We charges against "to" which may not have any tasks. Then, "to"
1756 * can be under rmdir(). But in current implementation, caller of
4ffef5fe
DN
1757 * this function is just force_empty() and move charge, so it's
1758 * garanteed that "to" is never removed. So, we don't check rmdir
1759 * status here.
88703267 1760 */
57f9fd7d
DN
1761}
1762
1763/*
1764 * check whether the @pc is valid for moving account and call
1765 * __mem_cgroup_move_account()
1766 */
1767static int mem_cgroup_move_account(struct page_cgroup *pc,
854ffa8d 1768 struct mem_cgroup *from, struct mem_cgroup *to, bool uncharge)
57f9fd7d
DN
1769{
1770 int ret = -EINVAL;
1771 lock_page_cgroup(pc);
1772 if (PageCgroupUsed(pc) && pc->mem_cgroup == from) {
854ffa8d 1773 __mem_cgroup_move_account(pc, from, to, uncharge);
57f9fd7d
DN
1774 ret = 0;
1775 }
1776 unlock_page_cgroup(pc);
f817ed48
KH
1777 return ret;
1778}
1779
1780/*
1781 * move charges to its parent.
1782 */
1783
1784static int mem_cgroup_move_parent(struct page_cgroup *pc,
1785 struct mem_cgroup *child,
1786 gfp_t gfp_mask)
1787{
08e552c6 1788 struct page *page = pc->page;
f817ed48
KH
1789 struct cgroup *cg = child->css.cgroup;
1790 struct cgroup *pcg = cg->parent;
1791 struct mem_cgroup *parent;
f817ed48
KH
1792 int ret;
1793
1794 /* Is ROOT ? */
1795 if (!pcg)
1796 return -EINVAL;
1797
57f9fd7d
DN
1798 ret = -EBUSY;
1799 if (!get_page_unless_zero(page))
1800 goto out;
1801 if (isolate_lru_page(page))
1802 goto put;
08e552c6 1803
f817ed48 1804 parent = mem_cgroup_from_cont(pcg);
f64c3f54 1805 ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false, page);
a636b327 1806 if (ret || !parent)
57f9fd7d 1807 goto put_back;
f817ed48 1808
854ffa8d
DN
1809 ret = mem_cgroup_move_account(pc, child, parent, true);
1810 if (ret)
1811 mem_cgroup_cancel_charge(parent);
57f9fd7d 1812put_back:
08e552c6 1813 putback_lru_page(page);
57f9fd7d 1814put:
40d58138 1815 put_page(page);
57f9fd7d 1816out:
f817ed48
KH
1817 return ret;
1818}
1819
7a81b88c
KH
1820/*
1821 * Charge the memory controller for page usage.
1822 * Return
1823 * 0 if the charge was successful
1824 * < 0 if the cgroup is over its limit
1825 */
1826static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
1827 gfp_t gfp_mask, enum charge_type ctype,
1828 struct mem_cgroup *memcg)
1829{
1830 struct mem_cgroup *mem;
1831 struct page_cgroup *pc;
1832 int ret;
1833
1834 pc = lookup_page_cgroup(page);
1835 /* can happen at boot */
1836 if (unlikely(!pc))
1837 return 0;
1838 prefetchw(pc);
1839
1840 mem = memcg;
f64c3f54 1841 ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true, page);
a636b327 1842 if (ret || !mem)
7a81b88c
KH
1843 return ret;
1844
1845 __mem_cgroup_commit_charge(mem, pc, ctype);
8a9f3ccd 1846 return 0;
8a9f3ccd
BS
1847}
1848
7a81b88c
KH
1849int mem_cgroup_newpage_charge(struct page *page,
1850 struct mm_struct *mm, gfp_t gfp_mask)
217bc319 1851{
f8d66542 1852 if (mem_cgroup_disabled())
cede86ac 1853 return 0;
52d4b9ac
KH
1854 if (PageCompound(page))
1855 return 0;
69029cd5
KH
1856 /*
1857 * If already mapped, we don't have to account.
1858 * If page cache, page->mapping has address_space.
1859 * But page->mapping may have out-of-use anon_vma pointer,
1860 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
1861 * is NULL.
1862 */
1863 if (page_mapped(page) || (page->mapping && !PageAnon(page)))
1864 return 0;
1865 if (unlikely(!mm))
1866 mm = &init_mm;
217bc319 1867 return mem_cgroup_charge_common(page, mm, gfp_mask,
e8589cc1 1868 MEM_CGROUP_CHARGE_TYPE_MAPPED, NULL);
217bc319
KH
1869}
1870
83aae4c7
DN
1871static void
1872__mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
1873 enum charge_type ctype);
1874
e1a1cd59
BS
1875int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
1876 gfp_t gfp_mask)
8697d331 1877{
b5a84319
KH
1878 struct mem_cgroup *mem = NULL;
1879 int ret;
1880
f8d66542 1881 if (mem_cgroup_disabled())
cede86ac 1882 return 0;
52d4b9ac
KH
1883 if (PageCompound(page))
1884 return 0;
accf163e
KH
1885 /*
1886 * Corner case handling. This is called from add_to_page_cache()
1887 * in usual. But some FS (shmem) precharges this page before calling it
1888 * and call add_to_page_cache() with GFP_NOWAIT.
1889 *
1890 * For GFP_NOWAIT case, the page may be pre-charged before calling
1891 * add_to_page_cache(). (See shmem.c) check it here and avoid to call
1892 * charge twice. (It works but has to pay a bit larger cost.)
b5a84319
KH
1893 * And when the page is SwapCache, it should take swap information
1894 * into account. This is under lock_page() now.
accf163e
KH
1895 */
1896 if (!(gfp_mask & __GFP_WAIT)) {
1897 struct page_cgroup *pc;
1898
52d4b9ac
KH
1899
1900 pc = lookup_page_cgroup(page);
1901 if (!pc)
1902 return 0;
1903 lock_page_cgroup(pc);
1904 if (PageCgroupUsed(pc)) {
1905 unlock_page_cgroup(pc);
accf163e
KH
1906 return 0;
1907 }
52d4b9ac 1908 unlock_page_cgroup(pc);
accf163e
KH
1909 }
1910
b5a84319 1911 if (unlikely(!mm && !mem))
8697d331 1912 mm = &init_mm;
accf163e 1913
c05555b5
KH
1914 if (page_is_file_cache(page))
1915 return mem_cgroup_charge_common(page, mm, gfp_mask,
e8589cc1 1916 MEM_CGROUP_CHARGE_TYPE_CACHE, NULL);
b5a84319 1917
83aae4c7
DN
1918 /* shmem */
1919 if (PageSwapCache(page)) {
1920 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
1921 if (!ret)
1922 __mem_cgroup_commit_charge_swapin(page, mem,
1923 MEM_CGROUP_CHARGE_TYPE_SHMEM);
1924 } else
1925 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
1926 MEM_CGROUP_CHARGE_TYPE_SHMEM, mem);
b5a84319 1927
b5a84319 1928 return ret;
e8589cc1
KH
1929}
1930
54595fe2
KH
1931/*
1932 * While swap-in, try_charge -> commit or cancel, the page is locked.
1933 * And when try_charge() successfully returns, one refcnt to memcg without
21ae2956 1934 * struct page_cgroup is acquired. This refcnt will be consumed by
54595fe2
KH
1935 * "commit()" or removed by "cancel()"
1936 */
8c7c6e34
KH
1937int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
1938 struct page *page,
1939 gfp_t mask, struct mem_cgroup **ptr)
1940{
1941 struct mem_cgroup *mem;
54595fe2 1942 int ret;
8c7c6e34 1943
f8d66542 1944 if (mem_cgroup_disabled())
8c7c6e34
KH
1945 return 0;
1946
1947 if (!do_swap_account)
1948 goto charge_cur_mm;
8c7c6e34
KH
1949 /*
1950 * A racing thread's fault, or swapoff, may have already updated
407f9c8b
HD
1951 * the pte, and even removed page from swap cache: in those cases
1952 * do_swap_page()'s pte_same() test will fail; but there's also a
1953 * KSM case which does need to charge the page.
8c7c6e34
KH
1954 */
1955 if (!PageSwapCache(page))
407f9c8b 1956 goto charge_cur_mm;
e42d9d5d 1957 mem = try_get_mem_cgroup_from_page(page);
54595fe2
KH
1958 if (!mem)
1959 goto charge_cur_mm;
8c7c6e34 1960 *ptr = mem;
f64c3f54 1961 ret = __mem_cgroup_try_charge(NULL, mask, ptr, true, page);
54595fe2
KH
1962 /* drop extra refcnt from tryget */
1963 css_put(&mem->css);
1964 return ret;
8c7c6e34
KH
1965charge_cur_mm:
1966 if (unlikely(!mm))
1967 mm = &init_mm;
f64c3f54 1968 return __mem_cgroup_try_charge(mm, mask, ptr, true, page);
8c7c6e34
KH
1969}
1970
83aae4c7
DN
1971static void
1972__mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
1973 enum charge_type ctype)
7a81b88c
KH
1974{
1975 struct page_cgroup *pc;
1976
f8d66542 1977 if (mem_cgroup_disabled())
7a81b88c
KH
1978 return;
1979 if (!ptr)
1980 return;
88703267 1981 cgroup_exclude_rmdir(&ptr->css);
7a81b88c 1982 pc = lookup_page_cgroup(page);
544122e5 1983 mem_cgroup_lru_del_before_commit_swapcache(page);
83aae4c7 1984 __mem_cgroup_commit_charge(ptr, pc, ctype);
544122e5 1985 mem_cgroup_lru_add_after_commit_swapcache(page);
8c7c6e34
KH
1986 /*
1987 * Now swap is on-memory. This means this page may be
1988 * counted both as mem and swap....double count.
03f3c433
KH
1989 * Fix it by uncharging from memsw. Basically, this SwapCache is stable
1990 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
1991 * may call delete_from_swap_cache() before reach here.
8c7c6e34 1992 */
03f3c433 1993 if (do_swap_account && PageSwapCache(page)) {
8c7c6e34 1994 swp_entry_t ent = {.val = page_private(page)};
a3b2d692 1995 unsigned short id;
8c7c6e34 1996 struct mem_cgroup *memcg;
a3b2d692
KH
1997
1998 id = swap_cgroup_record(ent, 0);
1999 rcu_read_lock();
2000 memcg = mem_cgroup_lookup(id);
8c7c6e34 2001 if (memcg) {
a3b2d692
KH
2002 /*
2003 * This recorded memcg can be obsolete one. So, avoid
2004 * calling css_tryget
2005 */
0c3e73e8 2006 if (!mem_cgroup_is_root(memcg))
4e649152 2007 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
0c3e73e8 2008 mem_cgroup_swap_statistics(memcg, false);
8c7c6e34
KH
2009 mem_cgroup_put(memcg);
2010 }
a3b2d692 2011 rcu_read_unlock();
8c7c6e34 2012 }
88703267
KH
2013 /*
2014 * At swapin, we may charge account against cgroup which has no tasks.
2015 * So, rmdir()->pre_destroy() can be called while we do this charge.
2016 * In that case, we need to call pre_destroy() again. check it here.
2017 */
2018 cgroup_release_and_wakeup_rmdir(&ptr->css);
7a81b88c
KH
2019}
2020
83aae4c7
DN
2021void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2022{
2023 __mem_cgroup_commit_charge_swapin(page, ptr,
2024 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2025}
2026
7a81b88c
KH
2027void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
2028{
f8d66542 2029 if (mem_cgroup_disabled())
7a81b88c
KH
2030 return;
2031 if (!mem)
2032 return;
a3032a2c 2033 mem_cgroup_cancel_charge(mem);
7a81b88c
KH
2034}
2035
569b846d
KH
2036static void
2037__do_uncharge(struct mem_cgroup *mem, const enum charge_type ctype)
2038{
2039 struct memcg_batch_info *batch = NULL;
2040 bool uncharge_memsw = true;
2041 /* If swapout, usage of swap doesn't decrease */
2042 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2043 uncharge_memsw = false;
2044 /*
2045 * do_batch > 0 when unmapping pages or inode invalidate/truncate.
2046 * In those cases, all pages freed continously can be expected to be in
2047 * the same cgroup and we have chance to coalesce uncharges.
2048 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
2049 * because we want to do uncharge as soon as possible.
2050 */
2051 if (!current->memcg_batch.do_batch || test_thread_flag(TIF_MEMDIE))
2052 goto direct_uncharge;
2053
2054 batch = &current->memcg_batch;
2055 /*
2056 * In usual, we do css_get() when we remember memcg pointer.
2057 * But in this case, we keep res->usage until end of a series of
2058 * uncharges. Then, it's ok to ignore memcg's refcnt.
2059 */
2060 if (!batch->memcg)
2061 batch->memcg = mem;
2062 /*
2063 * In typical case, batch->memcg == mem. This means we can
2064 * merge a series of uncharges to an uncharge of res_counter.
2065 * If not, we uncharge res_counter ony by one.
2066 */
2067 if (batch->memcg != mem)
2068 goto direct_uncharge;
2069 /* remember freed charge and uncharge it later */
2070 batch->bytes += PAGE_SIZE;
2071 if (uncharge_memsw)
2072 batch->memsw_bytes += PAGE_SIZE;
2073 return;
2074direct_uncharge:
2075 res_counter_uncharge(&mem->res, PAGE_SIZE);
2076 if (uncharge_memsw)
2077 res_counter_uncharge(&mem->memsw, PAGE_SIZE);
2078 return;
2079}
7a81b88c 2080
8a9f3ccd 2081/*
69029cd5 2082 * uncharge if !page_mapped(page)
8a9f3ccd 2083 */
8c7c6e34 2084static struct mem_cgroup *
69029cd5 2085__mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
8a9f3ccd 2086{
8289546e 2087 struct page_cgroup *pc;
8c7c6e34 2088 struct mem_cgroup *mem = NULL;
072c56c1 2089 struct mem_cgroup_per_zone *mz;
8a9f3ccd 2090
f8d66542 2091 if (mem_cgroup_disabled())
8c7c6e34 2092 return NULL;
4077960e 2093
d13d1443 2094 if (PageSwapCache(page))
8c7c6e34 2095 return NULL;
d13d1443 2096
8697d331 2097 /*
3c541e14 2098 * Check if our page_cgroup is valid
8697d331 2099 */
52d4b9ac
KH
2100 pc = lookup_page_cgroup(page);
2101 if (unlikely(!pc || !PageCgroupUsed(pc)))
8c7c6e34 2102 return NULL;
b9c565d5 2103
52d4b9ac 2104 lock_page_cgroup(pc);
d13d1443 2105
8c7c6e34
KH
2106 mem = pc->mem_cgroup;
2107
d13d1443
KH
2108 if (!PageCgroupUsed(pc))
2109 goto unlock_out;
2110
2111 switch (ctype) {
2112 case MEM_CGROUP_CHARGE_TYPE_MAPPED:
8a9478ca 2113 case MEM_CGROUP_CHARGE_TYPE_DROP:
d13d1443
KH
2114 if (page_mapped(page))
2115 goto unlock_out;
2116 break;
2117 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
2118 if (!PageAnon(page)) { /* Shared memory */
2119 if (page->mapping && !page_is_file_cache(page))
2120 goto unlock_out;
2121 } else if (page_mapped(page)) /* Anon */
2122 goto unlock_out;
2123 break;
2124 default:
2125 break;
52d4b9ac 2126 }
d13d1443 2127
569b846d
KH
2128 if (!mem_cgroup_is_root(mem))
2129 __do_uncharge(mem, ctype);
0c3e73e8
BS
2130 if (ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2131 mem_cgroup_swap_statistics(mem, true);
08e552c6 2132 mem_cgroup_charge_statistics(mem, pc, false);
04046e1a 2133
52d4b9ac 2134 ClearPageCgroupUsed(pc);
544122e5
KH
2135 /*
2136 * pc->mem_cgroup is not cleared here. It will be accessed when it's
2137 * freed from LRU. This is safe because uncharged page is expected not
2138 * to be reused (freed soon). Exception is SwapCache, it's handled by
2139 * special functions.
2140 */
b9c565d5 2141
69029cd5 2142 mz = page_cgroup_zoneinfo(pc);
52d4b9ac 2143 unlock_page_cgroup(pc);
fb59e9f1 2144
4e649152 2145 if (mem_cgroup_soft_limit_check(mem))
f64c3f54 2146 mem_cgroup_update_tree(mem, page);
a7fe942e
KH
2147 /* at swapout, this memcg will be accessed to record to swap */
2148 if (ctype != MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
2149 css_put(&mem->css);
6d12e2d8 2150
8c7c6e34 2151 return mem;
d13d1443
KH
2152
2153unlock_out:
2154 unlock_page_cgroup(pc);
8c7c6e34 2155 return NULL;
3c541e14
BS
2156}
2157
69029cd5
KH
2158void mem_cgroup_uncharge_page(struct page *page)
2159{
52d4b9ac
KH
2160 /* early check. */
2161 if (page_mapped(page))
2162 return;
2163 if (page->mapping && !PageAnon(page))
2164 return;
69029cd5
KH
2165 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
2166}
2167
2168void mem_cgroup_uncharge_cache_page(struct page *page)
2169{
2170 VM_BUG_ON(page_mapped(page));
b7abea96 2171 VM_BUG_ON(page->mapping);
69029cd5
KH
2172 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
2173}
2174
569b846d
KH
2175/*
2176 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
2177 * In that cases, pages are freed continuously and we can expect pages
2178 * are in the same memcg. All these calls itself limits the number of
2179 * pages freed at once, then uncharge_start/end() is called properly.
2180 * This may be called prural(2) times in a context,
2181 */
2182
2183void mem_cgroup_uncharge_start(void)
2184{
2185 current->memcg_batch.do_batch++;
2186 /* We can do nest. */
2187 if (current->memcg_batch.do_batch == 1) {
2188 current->memcg_batch.memcg = NULL;
2189 current->memcg_batch.bytes = 0;
2190 current->memcg_batch.memsw_bytes = 0;
2191 }
2192}
2193
2194void mem_cgroup_uncharge_end(void)
2195{
2196 struct memcg_batch_info *batch = &current->memcg_batch;
2197
2198 if (!batch->do_batch)
2199 return;
2200
2201 batch->do_batch--;
2202 if (batch->do_batch) /* If stacked, do nothing. */
2203 return;
2204
2205 if (!batch->memcg)
2206 return;
2207 /*
2208 * This "batch->memcg" is valid without any css_get/put etc...
2209 * bacause we hide charges behind us.
2210 */
2211 if (batch->bytes)
2212 res_counter_uncharge(&batch->memcg->res, batch->bytes);
2213 if (batch->memsw_bytes)
2214 res_counter_uncharge(&batch->memcg->memsw, batch->memsw_bytes);
2215 /* forget this pointer (for sanity check) */
2216 batch->memcg = NULL;
2217}
2218
e767e056 2219#ifdef CONFIG_SWAP
8c7c6e34 2220/*
e767e056 2221 * called after __delete_from_swap_cache() and drop "page" account.
8c7c6e34
KH
2222 * memcg information is recorded to swap_cgroup of "ent"
2223 */
8a9478ca
KH
2224void
2225mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
8c7c6e34
KH
2226{
2227 struct mem_cgroup *memcg;
8a9478ca
KH
2228 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
2229
2230 if (!swapout) /* this was a swap cache but the swap is unused ! */
2231 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
2232
2233 memcg = __mem_cgroup_uncharge_common(page, ctype);
8c7c6e34 2234
8c7c6e34 2235 /* record memcg information */
8a9478ca 2236 if (do_swap_account && swapout && memcg) {
a3b2d692 2237 swap_cgroup_record(ent, css_id(&memcg->css));
8c7c6e34
KH
2238 mem_cgroup_get(memcg);
2239 }
8a9478ca 2240 if (swapout && memcg)
a7fe942e 2241 css_put(&memcg->css);
8c7c6e34 2242}
e767e056 2243#endif
8c7c6e34
KH
2244
2245#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2246/*
2247 * called from swap_entry_free(). remove record in swap_cgroup and
2248 * uncharge "memsw" account.
2249 */
2250void mem_cgroup_uncharge_swap(swp_entry_t ent)
d13d1443 2251{
8c7c6e34 2252 struct mem_cgroup *memcg;
a3b2d692 2253 unsigned short id;
8c7c6e34
KH
2254
2255 if (!do_swap_account)
2256 return;
2257
a3b2d692
KH
2258 id = swap_cgroup_record(ent, 0);
2259 rcu_read_lock();
2260 memcg = mem_cgroup_lookup(id);
8c7c6e34 2261 if (memcg) {
a3b2d692
KH
2262 /*
2263 * We uncharge this because swap is freed.
2264 * This memcg can be obsolete one. We avoid calling css_tryget
2265 */
0c3e73e8 2266 if (!mem_cgroup_is_root(memcg))
4e649152 2267 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
0c3e73e8 2268 mem_cgroup_swap_statistics(memcg, false);
8c7c6e34
KH
2269 mem_cgroup_put(memcg);
2270 }
a3b2d692 2271 rcu_read_unlock();
d13d1443 2272}
8c7c6e34 2273#endif
d13d1443 2274
ae41be37 2275/*
01b1ae63
KH
2276 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
2277 * page belongs to.
ae41be37 2278 */
01b1ae63 2279int mem_cgroup_prepare_migration(struct page *page, struct mem_cgroup **ptr)
ae41be37
KH
2280{
2281 struct page_cgroup *pc;
e8589cc1 2282 struct mem_cgroup *mem = NULL;
e8589cc1 2283 int ret = 0;
8869b8f6 2284
f8d66542 2285 if (mem_cgroup_disabled())
4077960e
BS
2286 return 0;
2287
52d4b9ac
KH
2288 pc = lookup_page_cgroup(page);
2289 lock_page_cgroup(pc);
2290 if (PageCgroupUsed(pc)) {
e8589cc1
KH
2291 mem = pc->mem_cgroup;
2292 css_get(&mem->css);
e8589cc1 2293 }
52d4b9ac 2294 unlock_page_cgroup(pc);
01b1ae63 2295
e8589cc1 2296 if (mem) {
f64c3f54
BS
2297 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false,
2298 page);
e8589cc1
KH
2299 css_put(&mem->css);
2300 }
01b1ae63 2301 *ptr = mem;
e8589cc1 2302 return ret;
ae41be37 2303}
8869b8f6 2304
69029cd5 2305/* remove redundant charge if migration failed*/
01b1ae63
KH
2306void mem_cgroup_end_migration(struct mem_cgroup *mem,
2307 struct page *oldpage, struct page *newpage)
ae41be37 2308{
01b1ae63
KH
2309 struct page *target, *unused;
2310 struct page_cgroup *pc;
2311 enum charge_type ctype;
2312
2313 if (!mem)
2314 return;
88703267 2315 cgroup_exclude_rmdir(&mem->css);
01b1ae63
KH
2316 /* at migration success, oldpage->mapping is NULL. */
2317 if (oldpage->mapping) {
2318 target = oldpage;
2319 unused = NULL;
2320 } else {
2321 target = newpage;
2322 unused = oldpage;
2323 }
2324
2325 if (PageAnon(target))
2326 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
2327 else if (page_is_file_cache(target))
2328 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
2329 else
2330 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
2331
2332 /* unused page is not on radix-tree now. */
d13d1443 2333 if (unused)
01b1ae63
KH
2334 __mem_cgroup_uncharge_common(unused, ctype);
2335
2336 pc = lookup_page_cgroup(target);
69029cd5 2337 /*
01b1ae63
KH
2338 * __mem_cgroup_commit_charge() check PCG_USED bit of page_cgroup.
2339 * So, double-counting is effectively avoided.
2340 */
2341 __mem_cgroup_commit_charge(mem, pc, ctype);
2342
2343 /*
2344 * Both of oldpage and newpage are still under lock_page().
2345 * Then, we don't have to care about race in radix-tree.
2346 * But we have to be careful that this page is unmapped or not.
2347 *
2348 * There is a case for !page_mapped(). At the start of
2349 * migration, oldpage was mapped. But now, it's zapped.
2350 * But we know *target* page is not freed/reused under us.
2351 * mem_cgroup_uncharge_page() does all necessary checks.
69029cd5 2352 */
01b1ae63
KH
2353 if (ctype == MEM_CGROUP_CHARGE_TYPE_MAPPED)
2354 mem_cgroup_uncharge_page(target);
88703267
KH
2355 /*
2356 * At migration, we may charge account against cgroup which has no tasks
2357 * So, rmdir()->pre_destroy() can be called while we do this charge.
2358 * In that case, we need to call pre_destroy() again. check it here.
2359 */
2360 cgroup_release_and_wakeup_rmdir(&mem->css);
ae41be37 2361}
78fb7466 2362
c9b0ed51 2363/*
ae3abae6
DN
2364 * A call to try to shrink memory usage on charge failure at shmem's swapin.
2365 * Calling hierarchical_reclaim is not enough because we should update
2366 * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
2367 * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
2368 * not from the memcg which this page would be charged to.
2369 * try_charge_swapin does all of these works properly.
c9b0ed51 2370 */
ae3abae6 2371int mem_cgroup_shmem_charge_fallback(struct page *page,
b5a84319
KH
2372 struct mm_struct *mm,
2373 gfp_t gfp_mask)
c9b0ed51 2374{
b5a84319 2375 struct mem_cgroup *mem = NULL;
ae3abae6 2376 int ret;
c9b0ed51 2377
f8d66542 2378 if (mem_cgroup_disabled())
cede86ac 2379 return 0;
c9b0ed51 2380
ae3abae6
DN
2381 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2382 if (!ret)
2383 mem_cgroup_cancel_charge_swapin(mem); /* it does !mem check */
c9b0ed51 2384
ae3abae6 2385 return ret;
c9b0ed51
KH
2386}
2387
8c7c6e34
KH
2388static DEFINE_MUTEX(set_limit_mutex);
2389
d38d2a75 2390static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
8c7c6e34 2391 unsigned long long val)
628f4235 2392{
81d39c20 2393 int retry_count;
8c7c6e34 2394 u64 memswlimit;
628f4235 2395 int ret = 0;
81d39c20
KH
2396 int children = mem_cgroup_count_children(memcg);
2397 u64 curusage, oldusage;
2398
2399 /*
2400 * For keeping hierarchical_reclaim simple, how long we should retry
2401 * is depends on callers. We set our retry-count to be function
2402 * of # of children which we should visit in this loop.
2403 */
2404 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
2405
2406 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
628f4235 2407
8c7c6e34 2408 while (retry_count) {
628f4235
KH
2409 if (signal_pending(current)) {
2410 ret = -EINTR;
2411 break;
2412 }
8c7c6e34
KH
2413 /*
2414 * Rather than hide all in some function, I do this in
2415 * open coded manner. You see what this really does.
2416 * We have to guarantee mem->res.limit < mem->memsw.limit.
2417 */
2418 mutex_lock(&set_limit_mutex);
2419 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2420 if (memswlimit < val) {
2421 ret = -EINVAL;
2422 mutex_unlock(&set_limit_mutex);
628f4235
KH
2423 break;
2424 }
8c7c6e34 2425 ret = res_counter_set_limit(&memcg->res, val);
22a668d7
KH
2426 if (!ret) {
2427 if (memswlimit == val)
2428 memcg->memsw_is_minimum = true;
2429 else
2430 memcg->memsw_is_minimum = false;
2431 }
8c7c6e34
KH
2432 mutex_unlock(&set_limit_mutex);
2433
2434 if (!ret)
2435 break;
2436
aa20d489 2437 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
4e416953 2438 MEM_CGROUP_RECLAIM_SHRINK);
81d39c20
KH
2439 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2440 /* Usage is reduced ? */
2441 if (curusage >= oldusage)
2442 retry_count--;
2443 else
2444 oldusage = curusage;
8c7c6e34 2445 }
14797e23 2446
8c7c6e34
KH
2447 return ret;
2448}
2449
338c8431
LZ
2450static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
2451 unsigned long long val)
8c7c6e34 2452{
81d39c20 2453 int retry_count;
8c7c6e34 2454 u64 memlimit, oldusage, curusage;
81d39c20
KH
2455 int children = mem_cgroup_count_children(memcg);
2456 int ret = -EBUSY;
8c7c6e34 2457
81d39c20
KH
2458 /* see mem_cgroup_resize_res_limit */
2459 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
2460 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
8c7c6e34
KH
2461 while (retry_count) {
2462 if (signal_pending(current)) {
2463 ret = -EINTR;
2464 break;
2465 }
2466 /*
2467 * Rather than hide all in some function, I do this in
2468 * open coded manner. You see what this really does.
2469 * We have to guarantee mem->res.limit < mem->memsw.limit.
2470 */
2471 mutex_lock(&set_limit_mutex);
2472 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2473 if (memlimit > val) {
2474 ret = -EINVAL;
2475 mutex_unlock(&set_limit_mutex);
2476 break;
2477 }
2478 ret = res_counter_set_limit(&memcg->memsw, val);
22a668d7
KH
2479 if (!ret) {
2480 if (memlimit == val)
2481 memcg->memsw_is_minimum = true;
2482 else
2483 memcg->memsw_is_minimum = false;
2484 }
8c7c6e34
KH
2485 mutex_unlock(&set_limit_mutex);
2486
2487 if (!ret)
2488 break;
2489
4e416953 2490 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
75822b44
BS
2491 MEM_CGROUP_RECLAIM_NOSWAP |
2492 MEM_CGROUP_RECLAIM_SHRINK);
8c7c6e34 2493 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
81d39c20 2494 /* Usage is reduced ? */
8c7c6e34 2495 if (curusage >= oldusage)
628f4235 2496 retry_count--;
81d39c20
KH
2497 else
2498 oldusage = curusage;
628f4235
KH
2499 }
2500 return ret;
2501}
2502
4e416953
BS
2503unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
2504 gfp_t gfp_mask, int nid,
2505 int zid)
2506{
2507 unsigned long nr_reclaimed = 0;
2508 struct mem_cgroup_per_zone *mz, *next_mz = NULL;
2509 unsigned long reclaimed;
2510 int loop = 0;
2511 struct mem_cgroup_tree_per_zone *mctz;
ef8745c1 2512 unsigned long long excess;
4e416953
BS
2513
2514 if (order > 0)
2515 return 0;
2516
2517 mctz = soft_limit_tree_node_zone(nid, zid);
2518 /*
2519 * This loop can run a while, specially if mem_cgroup's continuously
2520 * keep exceeding their soft limit and putting the system under
2521 * pressure
2522 */
2523 do {
2524 if (next_mz)
2525 mz = next_mz;
2526 else
2527 mz = mem_cgroup_largest_soft_limit_node(mctz);
2528 if (!mz)
2529 break;
2530
2531 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
2532 gfp_mask,
2533 MEM_CGROUP_RECLAIM_SOFT);
2534 nr_reclaimed += reclaimed;
2535 spin_lock(&mctz->lock);
2536
2537 /*
2538 * If we failed to reclaim anything from this memory cgroup
2539 * it is time to move on to the next cgroup
2540 */
2541 next_mz = NULL;
2542 if (!reclaimed) {
2543 do {
2544 /*
2545 * Loop until we find yet another one.
2546 *
2547 * By the time we get the soft_limit lock
2548 * again, someone might have aded the
2549 * group back on the RB tree. Iterate to
2550 * make sure we get a different mem.
2551 * mem_cgroup_largest_soft_limit_node returns
2552 * NULL if no other cgroup is present on
2553 * the tree
2554 */
2555 next_mz =
2556 __mem_cgroup_largest_soft_limit_node(mctz);
2557 if (next_mz == mz) {
2558 css_put(&next_mz->mem->css);
2559 next_mz = NULL;
2560 } else /* next_mz == NULL or other memcg */
2561 break;
2562 } while (1);
2563 }
4e416953 2564 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
ef8745c1 2565 excess = res_counter_soft_limit_excess(&mz->mem->res);
4e416953
BS
2566 /*
2567 * One school of thought says that we should not add
2568 * back the node to the tree if reclaim returns 0.
2569 * But our reclaim could return 0, simply because due
2570 * to priority we are exposing a smaller subset of
2571 * memory to reclaim from. Consider this as a longer
2572 * term TODO.
2573 */
ef8745c1
KH
2574 /* If excess == 0, no tree ops */
2575 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
4e416953
BS
2576 spin_unlock(&mctz->lock);
2577 css_put(&mz->mem->css);
2578 loop++;
2579 /*
2580 * Could not reclaim anything and there are no more
2581 * mem cgroups to try or we seem to be looping without
2582 * reclaiming anything.
2583 */
2584 if (!nr_reclaimed &&
2585 (next_mz == NULL ||
2586 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
2587 break;
2588 } while (!nr_reclaimed);
2589 if (next_mz)
2590 css_put(&next_mz->mem->css);
2591 return nr_reclaimed;
2592}
2593
cc847582
KH
2594/*
2595 * This routine traverse page_cgroup in given list and drop them all.
cc847582
KH
2596 * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
2597 */
f817ed48 2598static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
08e552c6 2599 int node, int zid, enum lru_list lru)
cc847582 2600{
08e552c6
KH
2601 struct zone *zone;
2602 struct mem_cgroup_per_zone *mz;
f817ed48 2603 struct page_cgroup *pc, *busy;
08e552c6 2604 unsigned long flags, loop;
072c56c1 2605 struct list_head *list;
f817ed48 2606 int ret = 0;
072c56c1 2607
08e552c6
KH
2608 zone = &NODE_DATA(node)->node_zones[zid];
2609 mz = mem_cgroup_zoneinfo(mem, node, zid);
b69408e8 2610 list = &mz->lists[lru];
cc847582 2611
f817ed48
KH
2612 loop = MEM_CGROUP_ZSTAT(mz, lru);
2613 /* give some margin against EBUSY etc...*/
2614 loop += 256;
2615 busy = NULL;
2616 while (loop--) {
2617 ret = 0;
08e552c6 2618 spin_lock_irqsave(&zone->lru_lock, flags);
f817ed48 2619 if (list_empty(list)) {
08e552c6 2620 spin_unlock_irqrestore(&zone->lru_lock, flags);
52d4b9ac 2621 break;
f817ed48
KH
2622 }
2623 pc = list_entry(list->prev, struct page_cgroup, lru);
2624 if (busy == pc) {
2625 list_move(&pc->lru, list);
648bcc77 2626 busy = NULL;
08e552c6 2627 spin_unlock_irqrestore(&zone->lru_lock, flags);
f817ed48
KH
2628 continue;
2629 }
08e552c6 2630 spin_unlock_irqrestore(&zone->lru_lock, flags);
f817ed48 2631
2c26fdd7 2632 ret = mem_cgroup_move_parent(pc, mem, GFP_KERNEL);
f817ed48 2633 if (ret == -ENOMEM)
52d4b9ac 2634 break;
f817ed48
KH
2635
2636 if (ret == -EBUSY || ret == -EINVAL) {
2637 /* found lock contention or "pc" is obsolete. */
2638 busy = pc;
2639 cond_resched();
2640 } else
2641 busy = NULL;
cc847582 2642 }
08e552c6 2643
f817ed48
KH
2644 if (!ret && !list_empty(list))
2645 return -EBUSY;
2646 return ret;
cc847582
KH
2647}
2648
2649/*
2650 * make mem_cgroup's charge to be 0 if there is no task.
2651 * This enables deleting this mem_cgroup.
2652 */
c1e862c1 2653static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
cc847582 2654{
f817ed48
KH
2655 int ret;
2656 int node, zid, shrink;
2657 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
c1e862c1 2658 struct cgroup *cgrp = mem->css.cgroup;
8869b8f6 2659
cc847582 2660 css_get(&mem->css);
f817ed48
KH
2661
2662 shrink = 0;
c1e862c1
KH
2663 /* should free all ? */
2664 if (free_all)
2665 goto try_to_free;
f817ed48 2666move_account:
fce66477 2667 do {
f817ed48 2668 ret = -EBUSY;
c1e862c1
KH
2669 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
2670 goto out;
2671 ret = -EINTR;
2672 if (signal_pending(current))
cc847582 2673 goto out;
52d4b9ac
KH
2674 /* This is for making all *used* pages to be on LRU. */
2675 lru_add_drain_all();
cdec2e42 2676 drain_all_stock_sync();
f817ed48 2677 ret = 0;
299b4eaa 2678 for_each_node_state(node, N_HIGH_MEMORY) {
f817ed48 2679 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
b69408e8 2680 enum lru_list l;
f817ed48
KH
2681 for_each_lru(l) {
2682 ret = mem_cgroup_force_empty_list(mem,
08e552c6 2683 node, zid, l);
f817ed48
KH
2684 if (ret)
2685 break;
2686 }
1ecaab2b 2687 }
f817ed48
KH
2688 if (ret)
2689 break;
2690 }
2691 /* it seems parent cgroup doesn't have enough mem */
2692 if (ret == -ENOMEM)
2693 goto try_to_free;
52d4b9ac 2694 cond_resched();
fce66477
DN
2695 /* "ret" should also be checked to ensure all lists are empty. */
2696 } while (mem->res.usage > 0 || ret);
cc847582
KH
2697out:
2698 css_put(&mem->css);
2699 return ret;
f817ed48
KH
2700
2701try_to_free:
c1e862c1
KH
2702 /* returns EBUSY if there is a task or if we come here twice. */
2703 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
f817ed48
KH
2704 ret = -EBUSY;
2705 goto out;
2706 }
c1e862c1
KH
2707 /* we call try-to-free pages for make this cgroup empty */
2708 lru_add_drain_all();
f817ed48
KH
2709 /* try to free all pages in this cgroup */
2710 shrink = 1;
2711 while (nr_retries && mem->res.usage > 0) {
2712 int progress;
c1e862c1
KH
2713
2714 if (signal_pending(current)) {
2715 ret = -EINTR;
2716 goto out;
2717 }
a7885eb8
KM
2718 progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
2719 false, get_swappiness(mem));
c1e862c1 2720 if (!progress) {
f817ed48 2721 nr_retries--;
c1e862c1 2722 /* maybe some writeback is necessary */
8aa7e847 2723 congestion_wait(BLK_RW_ASYNC, HZ/10);
c1e862c1 2724 }
f817ed48
KH
2725
2726 }
08e552c6 2727 lru_add_drain();
f817ed48 2728 /* try move_account...there may be some *locked* pages. */
fce66477 2729 goto move_account;
cc847582
KH
2730}
2731
c1e862c1
KH
2732int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
2733{
2734 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
2735}
2736
2737
18f59ea7
BS
2738static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
2739{
2740 return mem_cgroup_from_cont(cont)->use_hierarchy;
2741}
2742
2743static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
2744 u64 val)
2745{
2746 int retval = 0;
2747 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2748 struct cgroup *parent = cont->parent;
2749 struct mem_cgroup *parent_mem = NULL;
2750
2751 if (parent)
2752 parent_mem = mem_cgroup_from_cont(parent);
2753
2754 cgroup_lock();
2755 /*
af901ca1 2756 * If parent's use_hierarchy is set, we can't make any modifications
18f59ea7
BS
2757 * in the child subtrees. If it is unset, then the change can
2758 * occur, provided the current cgroup has no children.
2759 *
2760 * For the root cgroup, parent_mem is NULL, we allow value to be
2761 * set if there are no children.
2762 */
2763 if ((!parent_mem || !parent_mem->use_hierarchy) &&
2764 (val == 1 || val == 0)) {
2765 if (list_empty(&cont->children))
2766 mem->use_hierarchy = val;
2767 else
2768 retval = -EBUSY;
2769 } else
2770 retval = -EINVAL;
2771 cgroup_unlock();
2772
2773 return retval;
2774}
2775
0c3e73e8
BS
2776struct mem_cgroup_idx_data {
2777 s64 val;
2778 enum mem_cgroup_stat_index idx;
2779};
2780
2781static int
2782mem_cgroup_get_idx_stat(struct mem_cgroup *mem, void *data)
2783{
2784 struct mem_cgroup_idx_data *d = data;
2785 d->val += mem_cgroup_read_stat(&mem->stat, d->idx);
2786 return 0;
2787}
2788
2789static void
2790mem_cgroup_get_recursive_idx_stat(struct mem_cgroup *mem,
2791 enum mem_cgroup_stat_index idx, s64 *val)
2792{
2793 struct mem_cgroup_idx_data d;
2794 d.idx = idx;
2795 d.val = 0;
2796 mem_cgroup_walk_tree(mem, &d, mem_cgroup_get_idx_stat);
2797 *val = d.val;
2798}
2799
2c3daa72 2800static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
8cdea7c0 2801{
8c7c6e34 2802 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
0c3e73e8 2803 u64 idx_val, val;
8c7c6e34
KH
2804 int type, name;
2805
2806 type = MEMFILE_TYPE(cft->private);
2807 name = MEMFILE_ATTR(cft->private);
2808 switch (type) {
2809 case _MEM:
0c3e73e8
BS
2810 if (name == RES_USAGE && mem_cgroup_is_root(mem)) {
2811 mem_cgroup_get_recursive_idx_stat(mem,
2812 MEM_CGROUP_STAT_CACHE, &idx_val);
2813 val = idx_val;
2814 mem_cgroup_get_recursive_idx_stat(mem,
2815 MEM_CGROUP_STAT_RSS, &idx_val);
2816 val += idx_val;
2817 val <<= PAGE_SHIFT;
2818 } else
2819 val = res_counter_read_u64(&mem->res, name);
8c7c6e34
KH
2820 break;
2821 case _MEMSWAP:
0c3e73e8
BS
2822 if (name == RES_USAGE && mem_cgroup_is_root(mem)) {
2823 mem_cgroup_get_recursive_idx_stat(mem,
2824 MEM_CGROUP_STAT_CACHE, &idx_val);
2825 val = idx_val;
2826 mem_cgroup_get_recursive_idx_stat(mem,
2827 MEM_CGROUP_STAT_RSS, &idx_val);
2828 val += idx_val;
2829 mem_cgroup_get_recursive_idx_stat(mem,
2830 MEM_CGROUP_STAT_SWAPOUT, &idx_val);
cd9b45b7 2831 val += idx_val;
0c3e73e8
BS
2832 val <<= PAGE_SHIFT;
2833 } else
2834 val = res_counter_read_u64(&mem->memsw, name);
8c7c6e34
KH
2835 break;
2836 default:
2837 BUG();
2838 break;
2839 }
2840 return val;
8cdea7c0 2841}
628f4235
KH
2842/*
2843 * The user of this function is...
2844 * RES_LIMIT.
2845 */
856c13aa
PM
2846static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
2847 const char *buffer)
8cdea7c0 2848{
628f4235 2849 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
8c7c6e34 2850 int type, name;
628f4235
KH
2851 unsigned long long val;
2852 int ret;
2853
8c7c6e34
KH
2854 type = MEMFILE_TYPE(cft->private);
2855 name = MEMFILE_ATTR(cft->private);
2856 switch (name) {
628f4235 2857 case RES_LIMIT:
4b3bde4c
BS
2858 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
2859 ret = -EINVAL;
2860 break;
2861 }
628f4235
KH
2862 /* This function does all necessary parse...reuse it */
2863 ret = res_counter_memparse_write_strategy(buffer, &val);
8c7c6e34
KH
2864 if (ret)
2865 break;
2866 if (type == _MEM)
628f4235 2867 ret = mem_cgroup_resize_limit(memcg, val);
8c7c6e34
KH
2868 else
2869 ret = mem_cgroup_resize_memsw_limit(memcg, val);
628f4235 2870 break;
296c81d8
BS
2871 case RES_SOFT_LIMIT:
2872 ret = res_counter_memparse_write_strategy(buffer, &val);
2873 if (ret)
2874 break;
2875 /*
2876 * For memsw, soft limits are hard to implement in terms
2877 * of semantics, for now, we support soft limits for
2878 * control without swap
2879 */
2880 if (type == _MEM)
2881 ret = res_counter_set_soft_limit(&memcg->res, val);
2882 else
2883 ret = -EINVAL;
2884 break;
628f4235
KH
2885 default:
2886 ret = -EINVAL; /* should be BUG() ? */
2887 break;
2888 }
2889 return ret;
8cdea7c0
BS
2890}
2891
fee7b548
KH
2892static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
2893 unsigned long long *mem_limit, unsigned long long *memsw_limit)
2894{
2895 struct cgroup *cgroup;
2896 unsigned long long min_limit, min_memsw_limit, tmp;
2897
2898 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2899 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2900 cgroup = memcg->css.cgroup;
2901 if (!memcg->use_hierarchy)
2902 goto out;
2903
2904 while (cgroup->parent) {
2905 cgroup = cgroup->parent;
2906 memcg = mem_cgroup_from_cont(cgroup);
2907 if (!memcg->use_hierarchy)
2908 break;
2909 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
2910 min_limit = min(min_limit, tmp);
2911 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2912 min_memsw_limit = min(min_memsw_limit, tmp);
2913 }
2914out:
2915 *mem_limit = min_limit;
2916 *memsw_limit = min_memsw_limit;
2917 return;
2918}
2919
29f2a4da 2920static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
c84872e1
PE
2921{
2922 struct mem_cgroup *mem;
8c7c6e34 2923 int type, name;
c84872e1
PE
2924
2925 mem = mem_cgroup_from_cont(cont);
8c7c6e34
KH
2926 type = MEMFILE_TYPE(event);
2927 name = MEMFILE_ATTR(event);
2928 switch (name) {
29f2a4da 2929 case RES_MAX_USAGE:
8c7c6e34
KH
2930 if (type == _MEM)
2931 res_counter_reset_max(&mem->res);
2932 else
2933 res_counter_reset_max(&mem->memsw);
29f2a4da
PE
2934 break;
2935 case RES_FAILCNT:
8c7c6e34
KH
2936 if (type == _MEM)
2937 res_counter_reset_failcnt(&mem->res);
2938 else
2939 res_counter_reset_failcnt(&mem->memsw);
29f2a4da
PE
2940 break;
2941 }
f64c3f54 2942
85cc59db 2943 return 0;
c84872e1
PE
2944}
2945
7dc74be0
DN
2946static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
2947 struct cftype *cft)
2948{
2949 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
2950}
2951
2952static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
2953 struct cftype *cft, u64 val)
2954{
2955 struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
2956
2957 if (val >= (1 << NR_MOVE_TYPE))
2958 return -EINVAL;
2959 /*
2960 * We check this value several times in both in can_attach() and
2961 * attach(), so we need cgroup lock to prevent this value from being
2962 * inconsistent.
2963 */
2964 cgroup_lock();
2965 mem->move_charge_at_immigrate = val;
2966 cgroup_unlock();
2967
2968 return 0;
2969}
2970
14067bb3
KH
2971
2972/* For read statistics */
2973enum {
2974 MCS_CACHE,
2975 MCS_RSS,
d8046582 2976 MCS_FILE_MAPPED,
14067bb3
KH
2977 MCS_PGPGIN,
2978 MCS_PGPGOUT,
1dd3a273 2979 MCS_SWAP,
14067bb3
KH
2980 MCS_INACTIVE_ANON,
2981 MCS_ACTIVE_ANON,
2982 MCS_INACTIVE_FILE,
2983 MCS_ACTIVE_FILE,
2984 MCS_UNEVICTABLE,
2985 NR_MCS_STAT,
2986};
2987
2988struct mcs_total_stat {
2989 s64 stat[NR_MCS_STAT];
d2ceb9b7
KH
2990};
2991
14067bb3
KH
2992struct {
2993 char *local_name;
2994 char *total_name;
2995} memcg_stat_strings[NR_MCS_STAT] = {
2996 {"cache", "total_cache"},
2997 {"rss", "total_rss"},
d69b042f 2998 {"mapped_file", "total_mapped_file"},
14067bb3
KH
2999 {"pgpgin", "total_pgpgin"},
3000 {"pgpgout", "total_pgpgout"},
1dd3a273 3001 {"swap", "total_swap"},
14067bb3
KH
3002 {"inactive_anon", "total_inactive_anon"},
3003 {"active_anon", "total_active_anon"},
3004 {"inactive_file", "total_inactive_file"},
3005 {"active_file", "total_active_file"},
3006 {"unevictable", "total_unevictable"}
3007};
3008
3009
3010static int mem_cgroup_get_local_stat(struct mem_cgroup *mem, void *data)
3011{
3012 struct mcs_total_stat *s = data;
3013 s64 val;
3014
3015 /* per cpu stat */
3016 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_CACHE);
3017 s->stat[MCS_CACHE] += val * PAGE_SIZE;
3018 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_RSS);
3019 s->stat[MCS_RSS] += val * PAGE_SIZE;
d8046582
KH
3020 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_FILE_MAPPED);
3021 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
14067bb3
KH
3022 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGIN_COUNT);
3023 s->stat[MCS_PGPGIN] += val;
3024 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGOUT_COUNT);
3025 s->stat[MCS_PGPGOUT] += val;
1dd3a273
DN
3026 if (do_swap_account) {
3027 val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_SWAPOUT);
3028 s->stat[MCS_SWAP] += val * PAGE_SIZE;
3029 }
14067bb3
KH
3030
3031 /* per zone stat */
3032 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
3033 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
3034 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
3035 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
3036 val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
3037 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
3038 val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
3039 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
3040 val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
3041 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
3042 return 0;
3043}
3044
3045static void
3046mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
3047{
3048 mem_cgroup_walk_tree(mem, s, mem_cgroup_get_local_stat);
3049}
3050
c64745cf
PM
3051static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
3052 struct cgroup_map_cb *cb)
d2ceb9b7 3053{
d2ceb9b7 3054 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
14067bb3 3055 struct mcs_total_stat mystat;
d2ceb9b7
KH
3056 int i;
3057
14067bb3
KH
3058 memset(&mystat, 0, sizeof(mystat));
3059 mem_cgroup_get_local_stat(mem_cont, &mystat);
d2ceb9b7 3060
1dd3a273
DN
3061 for (i = 0; i < NR_MCS_STAT; i++) {
3062 if (i == MCS_SWAP && !do_swap_account)
3063 continue;
14067bb3 3064 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
1dd3a273 3065 }
7b854121 3066
14067bb3 3067 /* Hierarchical information */
fee7b548
KH
3068 {
3069 unsigned long long limit, memsw_limit;
3070 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
3071 cb->fill(cb, "hierarchical_memory_limit", limit);
3072 if (do_swap_account)
3073 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
3074 }
7f016ee8 3075
14067bb3
KH
3076 memset(&mystat, 0, sizeof(mystat));
3077 mem_cgroup_get_total_stat(mem_cont, &mystat);
1dd3a273
DN
3078 for (i = 0; i < NR_MCS_STAT; i++) {
3079 if (i == MCS_SWAP && !do_swap_account)
3080 continue;
14067bb3 3081 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
1dd3a273 3082 }
14067bb3 3083
7f016ee8 3084#ifdef CONFIG_DEBUG_VM
c772be93 3085 cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
7f016ee8
KM
3086
3087 {
3088 int nid, zid;
3089 struct mem_cgroup_per_zone *mz;
3090 unsigned long recent_rotated[2] = {0, 0};
3091 unsigned long recent_scanned[2] = {0, 0};
3092
3093 for_each_online_node(nid)
3094 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
3095 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
3096
3097 recent_rotated[0] +=
3098 mz->reclaim_stat.recent_rotated[0];
3099 recent_rotated[1] +=
3100 mz->reclaim_stat.recent_rotated[1];
3101 recent_scanned[0] +=
3102 mz->reclaim_stat.recent_scanned[0];
3103 recent_scanned[1] +=
3104 mz->reclaim_stat.recent_scanned[1];
3105 }
3106 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
3107 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
3108 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
3109 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
3110 }
3111#endif
3112
d2ceb9b7
KH
3113 return 0;
3114}
3115
a7885eb8
KM
3116static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
3117{
3118 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3119
3120 return get_swappiness(memcg);
3121}
3122
3123static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
3124 u64 val)
3125{
3126 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
3127 struct mem_cgroup *parent;
068b38c1 3128
a7885eb8
KM
3129 if (val > 100)
3130 return -EINVAL;
3131
3132 if (cgrp->parent == NULL)
3133 return -EINVAL;
3134
3135 parent = mem_cgroup_from_cont(cgrp->parent);
068b38c1
LZ
3136
3137 cgroup_lock();
3138
a7885eb8
KM
3139 /* If under hierarchy, only empty-root can set this value */
3140 if ((parent->use_hierarchy) ||
068b38c1
LZ
3141 (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
3142 cgroup_unlock();
a7885eb8 3143 return -EINVAL;
068b38c1 3144 }
a7885eb8
KM
3145
3146 spin_lock(&memcg->reclaim_param_lock);
3147 memcg->swappiness = val;
3148 spin_unlock(&memcg->reclaim_param_lock);
3149
068b38c1
LZ
3150 cgroup_unlock();
3151
a7885eb8
KM
3152 return 0;
3153}
3154
c1e862c1 3155
8cdea7c0
BS
3156static struct cftype mem_cgroup_files[] = {
3157 {
0eea1030 3158 .name = "usage_in_bytes",
8c7c6e34 3159 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
2c3daa72 3160 .read_u64 = mem_cgroup_read,
8cdea7c0 3161 },
c84872e1
PE
3162 {
3163 .name = "max_usage_in_bytes",
8c7c6e34 3164 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
29f2a4da 3165 .trigger = mem_cgroup_reset,
c84872e1
PE
3166 .read_u64 = mem_cgroup_read,
3167 },
8cdea7c0 3168 {
0eea1030 3169 .name = "limit_in_bytes",
8c7c6e34 3170 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
856c13aa 3171 .write_string = mem_cgroup_write,
2c3daa72 3172 .read_u64 = mem_cgroup_read,
8cdea7c0 3173 },
296c81d8
BS
3174 {
3175 .name = "soft_limit_in_bytes",
3176 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
3177 .write_string = mem_cgroup_write,
3178 .read_u64 = mem_cgroup_read,
3179 },
8cdea7c0
BS
3180 {
3181 .name = "failcnt",
8c7c6e34 3182 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
29f2a4da 3183 .trigger = mem_cgroup_reset,
2c3daa72 3184 .read_u64 = mem_cgroup_read,
8cdea7c0 3185 },
d2ceb9b7
KH
3186 {
3187 .name = "stat",
c64745cf 3188 .read_map = mem_control_stat_show,
d2ceb9b7 3189 },
c1e862c1
KH
3190 {
3191 .name = "force_empty",
3192 .trigger = mem_cgroup_force_empty_write,
3193 },
18f59ea7
BS
3194 {
3195 .name = "use_hierarchy",
3196 .write_u64 = mem_cgroup_hierarchy_write,
3197 .read_u64 = mem_cgroup_hierarchy_read,
3198 },
a7885eb8
KM
3199 {
3200 .name = "swappiness",
3201 .read_u64 = mem_cgroup_swappiness_read,
3202 .write_u64 = mem_cgroup_swappiness_write,
3203 },
7dc74be0
DN
3204 {
3205 .name = "move_charge_at_immigrate",
3206 .read_u64 = mem_cgroup_move_charge_read,
3207 .write_u64 = mem_cgroup_move_charge_write,
3208 },
8cdea7c0
BS
3209};
3210
8c7c6e34
KH
3211#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3212static struct cftype memsw_cgroup_files[] = {
3213 {
3214 .name = "memsw.usage_in_bytes",
3215 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
3216 .read_u64 = mem_cgroup_read,
3217 },
3218 {
3219 .name = "memsw.max_usage_in_bytes",
3220 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
3221 .trigger = mem_cgroup_reset,
3222 .read_u64 = mem_cgroup_read,
3223 },
3224 {
3225 .name = "memsw.limit_in_bytes",
3226 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
3227 .write_string = mem_cgroup_write,
3228 .read_u64 = mem_cgroup_read,
3229 },
3230 {
3231 .name = "memsw.failcnt",
3232 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
3233 .trigger = mem_cgroup_reset,
3234 .read_u64 = mem_cgroup_read,
3235 },
3236};
3237
3238static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3239{
3240 if (!do_swap_account)
3241 return 0;
3242 return cgroup_add_files(cont, ss, memsw_cgroup_files,
3243 ARRAY_SIZE(memsw_cgroup_files));
3244};
3245#else
3246static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
3247{
3248 return 0;
3249}
3250#endif
3251
6d12e2d8
KH
3252static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3253{
3254 struct mem_cgroup_per_node *pn;
1ecaab2b 3255 struct mem_cgroup_per_zone *mz;
b69408e8 3256 enum lru_list l;
41e3355d 3257 int zone, tmp = node;
1ecaab2b
KH
3258 /*
3259 * This routine is called against possible nodes.
3260 * But it's BUG to call kmalloc() against offline node.
3261 *
3262 * TODO: this routine can waste much memory for nodes which will
3263 * never be onlined. It's better to use memory hotplug callback
3264 * function.
3265 */
41e3355d
KH
3266 if (!node_state(node, N_NORMAL_MEMORY))
3267 tmp = -1;
3268 pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
6d12e2d8
KH
3269 if (!pn)
3270 return 1;
1ecaab2b 3271
6d12e2d8
KH
3272 mem->info.nodeinfo[node] = pn;
3273 memset(pn, 0, sizeof(*pn));
1ecaab2b
KH
3274
3275 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3276 mz = &pn->zoneinfo[zone];
b69408e8
CL
3277 for_each_lru(l)
3278 INIT_LIST_HEAD(&mz->lists[l]);
f64c3f54 3279 mz->usage_in_excess = 0;
4e416953
BS
3280 mz->on_tree = false;
3281 mz->mem = mem;
1ecaab2b 3282 }
6d12e2d8
KH
3283 return 0;
3284}
3285
1ecaab2b
KH
3286static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
3287{
3288 kfree(mem->info.nodeinfo[node]);
3289}
3290
c8dad2bb
JB
3291static int mem_cgroup_size(void)
3292{
3293 int cpustat_size = nr_cpu_ids * sizeof(struct mem_cgroup_stat_cpu);
3294 return sizeof(struct mem_cgroup) + cpustat_size;
3295}
3296
33327948
KH
3297static struct mem_cgroup *mem_cgroup_alloc(void)
3298{
3299 struct mem_cgroup *mem;
c8dad2bb 3300 int size = mem_cgroup_size();
33327948 3301
c8dad2bb
JB
3302 if (size < PAGE_SIZE)
3303 mem = kmalloc(size, GFP_KERNEL);
33327948 3304 else
c8dad2bb 3305 mem = vmalloc(size);
33327948
KH
3306
3307 if (mem)
c8dad2bb 3308 memset(mem, 0, size);
33327948
KH
3309 return mem;
3310}
3311
8c7c6e34
KH
3312/*
3313 * At destroying mem_cgroup, references from swap_cgroup can remain.
3314 * (scanning all at force_empty is too costly...)
3315 *
3316 * Instead of clearing all references at force_empty, we remember
3317 * the number of reference from swap_cgroup and free mem_cgroup when
3318 * it goes down to 0.
3319 *
8c7c6e34
KH
3320 * Removal of cgroup itself succeeds regardless of refs from swap.
3321 */
3322
a7ba0eef 3323static void __mem_cgroup_free(struct mem_cgroup *mem)
33327948 3324{
08e552c6
KH
3325 int node;
3326
f64c3f54 3327 mem_cgroup_remove_from_trees(mem);
04046e1a
KH
3328 free_css_id(&mem_cgroup_subsys, &mem->css);
3329
08e552c6
KH
3330 for_each_node_state(node, N_POSSIBLE)
3331 free_mem_cgroup_per_zone_info(mem, node);
3332
c8dad2bb 3333 if (mem_cgroup_size() < PAGE_SIZE)
33327948
KH
3334 kfree(mem);
3335 else
3336 vfree(mem);
3337}
3338
8c7c6e34
KH
3339static void mem_cgroup_get(struct mem_cgroup *mem)
3340{
3341 atomic_inc(&mem->refcnt);
3342}
3343
3344static void mem_cgroup_put(struct mem_cgroup *mem)
3345{
7bcc1bb1
DN
3346 if (atomic_dec_and_test(&mem->refcnt)) {
3347 struct mem_cgroup *parent = parent_mem_cgroup(mem);
a7ba0eef 3348 __mem_cgroup_free(mem);
7bcc1bb1
DN
3349 if (parent)
3350 mem_cgroup_put(parent);
3351 }
8c7c6e34
KH
3352}
3353
7bcc1bb1
DN
3354/*
3355 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
3356 */
3357static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
3358{
3359 if (!mem->res.parent)
3360 return NULL;
3361 return mem_cgroup_from_res_counter(mem->res.parent, res);
3362}
33327948 3363
c077719b
KH
3364#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3365static void __init enable_swap_cgroup(void)
3366{
f8d66542 3367 if (!mem_cgroup_disabled() && really_do_swap_account)
c077719b
KH
3368 do_swap_account = 1;
3369}
3370#else
3371static void __init enable_swap_cgroup(void)
3372{
3373}
3374#endif
3375
f64c3f54
BS
3376static int mem_cgroup_soft_limit_tree_init(void)
3377{
3378 struct mem_cgroup_tree_per_node *rtpn;
3379 struct mem_cgroup_tree_per_zone *rtpz;
3380 int tmp, node, zone;
3381
3382 for_each_node_state(node, N_POSSIBLE) {
3383 tmp = node;
3384 if (!node_state(node, N_NORMAL_MEMORY))
3385 tmp = -1;
3386 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
3387 if (!rtpn)
3388 return 1;
3389
3390 soft_limit_tree.rb_tree_per_node[node] = rtpn;
3391
3392 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3393 rtpz = &rtpn->rb_tree_per_zone[zone];
3394 rtpz->rb_root = RB_ROOT;
3395 spin_lock_init(&rtpz->lock);
3396 }
3397 }
3398 return 0;
3399}
3400
0eb253e2 3401static struct cgroup_subsys_state * __ref
8cdea7c0
BS
3402mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
3403{
28dbc4b6 3404 struct mem_cgroup *mem, *parent;
04046e1a 3405 long error = -ENOMEM;
6d12e2d8 3406 int node;
8cdea7c0 3407
c8dad2bb
JB
3408 mem = mem_cgroup_alloc();
3409 if (!mem)
04046e1a 3410 return ERR_PTR(error);
78fb7466 3411
6d12e2d8
KH
3412 for_each_node_state(node, N_POSSIBLE)
3413 if (alloc_mem_cgroup_per_zone_info(mem, node))
3414 goto free_out;
f64c3f54 3415
c077719b 3416 /* root ? */
28dbc4b6 3417 if (cont->parent == NULL) {
cdec2e42 3418 int cpu;
c077719b 3419 enable_swap_cgroup();
28dbc4b6 3420 parent = NULL;
4b3bde4c 3421 root_mem_cgroup = mem;
f64c3f54
BS
3422 if (mem_cgroup_soft_limit_tree_init())
3423 goto free_out;
cdec2e42
KH
3424 for_each_possible_cpu(cpu) {
3425 struct memcg_stock_pcp *stock =
3426 &per_cpu(memcg_stock, cpu);
3427 INIT_WORK(&stock->work, drain_local_stock);
3428 }
3429 hotcpu_notifier(memcg_stock_cpu_callback, 0);
18f59ea7 3430 } else {
28dbc4b6 3431 parent = mem_cgroup_from_cont(cont->parent);
18f59ea7
BS
3432 mem->use_hierarchy = parent->use_hierarchy;
3433 }
28dbc4b6 3434
18f59ea7
BS
3435 if (parent && parent->use_hierarchy) {
3436 res_counter_init(&mem->res, &parent->res);
3437 res_counter_init(&mem->memsw, &parent->memsw);
7bcc1bb1
DN
3438 /*
3439 * We increment refcnt of the parent to ensure that we can
3440 * safely access it on res_counter_charge/uncharge.
3441 * This refcnt will be decremented when freeing this
3442 * mem_cgroup(see mem_cgroup_put).
3443 */
3444 mem_cgroup_get(parent);
18f59ea7
BS
3445 } else {
3446 res_counter_init(&mem->res, NULL);
3447 res_counter_init(&mem->memsw, NULL);
3448 }
04046e1a 3449 mem->last_scanned_child = 0;
2733c06a 3450 spin_lock_init(&mem->reclaim_param_lock);
6d61ef40 3451
a7885eb8
KM
3452 if (parent)
3453 mem->swappiness = get_swappiness(parent);
a7ba0eef 3454 atomic_set(&mem->refcnt, 1);
7dc74be0 3455 mem->move_charge_at_immigrate = 0;
8cdea7c0 3456 return &mem->css;
6d12e2d8 3457free_out:
a7ba0eef 3458 __mem_cgroup_free(mem);
4b3bde4c 3459 root_mem_cgroup = NULL;
04046e1a 3460 return ERR_PTR(error);
8cdea7c0
BS
3461}
3462
ec64f515 3463static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
df878fb0
KH
3464 struct cgroup *cont)
3465{
3466 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
ec64f515
KH
3467
3468 return mem_cgroup_force_empty(mem, false);
df878fb0
KH
3469}
3470
8cdea7c0
BS
3471static void mem_cgroup_destroy(struct cgroup_subsys *ss,
3472 struct cgroup *cont)
3473{
c268e994 3474 struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
c268e994 3475
c268e994 3476 mem_cgroup_put(mem);
8cdea7c0
BS
3477}
3478
3479static int mem_cgroup_populate(struct cgroup_subsys *ss,
3480 struct cgroup *cont)
3481{
8c7c6e34
KH
3482 int ret;
3483
3484 ret = cgroup_add_files(cont, ss, mem_cgroup_files,
3485 ARRAY_SIZE(mem_cgroup_files));
3486
3487 if (!ret)
3488 ret = register_memsw_files(cont, ss);
3489 return ret;
8cdea7c0
BS
3490}
3491
7dc74be0 3492/* Handlers for move charge at task migration. */
854ffa8d
DN
3493#define PRECHARGE_COUNT_AT_ONCE 256
3494static int mem_cgroup_do_precharge(unsigned long count)
7dc74be0 3495{
854ffa8d
DN
3496 int ret = 0;
3497 int batch_count = PRECHARGE_COUNT_AT_ONCE;
4ffef5fe
DN
3498 struct mem_cgroup *mem = mc.to;
3499
854ffa8d
DN
3500 if (mem_cgroup_is_root(mem)) {
3501 mc.precharge += count;
3502 /* we don't need css_get for root */
3503 return ret;
3504 }
3505 /* try to charge at once */
3506 if (count > 1) {
3507 struct res_counter *dummy;
3508 /*
3509 * "mem" cannot be under rmdir() because we've already checked
3510 * by cgroup_lock_live_cgroup() that it is not removed and we
3511 * are still under the same cgroup_mutex. So we can postpone
3512 * css_get().
3513 */
3514 if (res_counter_charge(&mem->res, PAGE_SIZE * count, &dummy))
3515 goto one_by_one;
3516 if (do_swap_account && res_counter_charge(&mem->memsw,
3517 PAGE_SIZE * count, &dummy)) {
3518 res_counter_uncharge(&mem->res, PAGE_SIZE * count);
3519 goto one_by_one;
3520 }
3521 mc.precharge += count;
3522 VM_BUG_ON(test_bit(CSS_ROOT, &mem->css.flags));
3523 WARN_ON_ONCE(count > INT_MAX);
3524 __css_get(&mem->css, (int)count);
3525 return ret;
3526 }
3527one_by_one:
3528 /* fall back to one by one charge */
3529 while (count--) {
3530 if (signal_pending(current)) {
3531 ret = -EINTR;
3532 break;
3533 }
3534 if (!batch_count--) {
3535 batch_count = PRECHARGE_COUNT_AT_ONCE;
3536 cond_resched();
3537 }
3538 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem,
3539 false, NULL);
3540 if (ret || !mem)
3541 /* mem_cgroup_clear_mc() will do uncharge later */
3542 return -ENOMEM;
3543 mc.precharge++;
3544 }
4ffef5fe
DN
3545 return ret;
3546}
3547
3548/**
3549 * is_target_pte_for_mc - check a pte whether it is valid for move charge
3550 * @vma: the vma the pte to be checked belongs
3551 * @addr: the address corresponding to the pte to be checked
3552 * @ptent: the pte to be checked
3553 * @target: the pointer the target page will be stored(can be NULL)
3554 *
3555 * Returns
3556 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
3557 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
3558 * move charge. if @target is not NULL, the page is stored in target->page
3559 * with extra refcnt got(Callers should handle it).
3560 *
3561 * Called with pte lock held.
3562 */
3563/* We add a new member later. */
3564union mc_target {
3565 struct page *page;
3566};
3567
3568/* We add a new type later. */
3569enum mc_target_type {
3570 MC_TARGET_NONE, /* not used */
3571 MC_TARGET_PAGE,
3572};
3573
3574static int is_target_pte_for_mc(struct vm_area_struct *vma,
3575 unsigned long addr, pte_t ptent, union mc_target *target)
3576{
3577 struct page *page;
3578 struct page_cgroup *pc;
3579 int ret = 0;
3580 bool move_anon = test_bit(MOVE_CHARGE_TYPE_ANON,
3581 &mc.to->move_charge_at_immigrate);
3582
3583 if (!pte_present(ptent))
3584 return 0;
3585
3586 page = vm_normal_page(vma, addr, ptent);
3587 if (!page || !page_mapped(page))
3588 return 0;
3589 /*
3590 * TODO: We don't move charges of file(including shmem/tmpfs) pages for
3591 * now.
3592 */
3593 if (!move_anon || !PageAnon(page))
3594 return 0;
3595 /*
3596 * TODO: We don't move charges of shared(used by multiple processes)
3597 * pages for now.
3598 */
3599 if (page_mapcount(page) > 1)
3600 return 0;
3601 if (!get_page_unless_zero(page))
3602 return 0;
3603
3604 pc = lookup_page_cgroup(page);
3605 /*
3606 * Do only loose check w/o page_cgroup lock. mem_cgroup_move_account()
3607 * checks the pc is valid or not under the lock.
3608 */
3609 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
3610 ret = MC_TARGET_PAGE;
3611 if (target)
3612 target->page = page;
3613 }
3614
3615 if (!ret || !target)
3616 put_page(page);
3617
3618 return ret;
3619}
3620
3621static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
3622 unsigned long addr, unsigned long end,
3623 struct mm_walk *walk)
3624{
3625 struct vm_area_struct *vma = walk->private;
3626 pte_t *pte;
3627 spinlock_t *ptl;
3628
3629 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
3630 for (; addr != end; pte++, addr += PAGE_SIZE)
3631 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
3632 mc.precharge++; /* increment precharge temporarily */
3633 pte_unmap_unlock(pte - 1, ptl);
3634 cond_resched();
3635
7dc74be0
DN
3636 return 0;
3637}
3638
4ffef5fe
DN
3639static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
3640{
3641 unsigned long precharge;
3642 struct vm_area_struct *vma;
3643
3644 down_read(&mm->mmap_sem);
3645 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3646 struct mm_walk mem_cgroup_count_precharge_walk = {
3647 .pmd_entry = mem_cgroup_count_precharge_pte_range,
3648 .mm = mm,
3649 .private = vma,
3650 };
3651 if (is_vm_hugetlb_page(vma))
3652 continue;
3653 /* TODO: We don't move charges of shmem/tmpfs pages for now. */
3654 if (vma->vm_flags & VM_SHARED)
3655 continue;
3656 walk_page_range(vma->vm_start, vma->vm_end,
3657 &mem_cgroup_count_precharge_walk);
3658 }
3659 up_read(&mm->mmap_sem);
3660
3661 precharge = mc.precharge;
3662 mc.precharge = 0;
3663
3664 return precharge;
3665}
3666
4ffef5fe
DN
3667static int mem_cgroup_precharge_mc(struct mm_struct *mm)
3668{
854ffa8d 3669 return mem_cgroup_do_precharge(mem_cgroup_count_precharge(mm));
4ffef5fe
DN
3670}
3671
3672static void mem_cgroup_clear_mc(void)
3673{
3674 /* we must uncharge all the leftover precharges from mc.to */
854ffa8d
DN
3675 if (mc.precharge) {
3676 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
3677 mc.precharge = 0;
3678 }
3679 /*
3680 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
3681 * we must uncharge here.
3682 */
3683 if (mc.moved_charge) {
3684 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
3685 mc.moved_charge = 0;
4ffef5fe
DN
3686 }
3687 mc.from = NULL;
3688 mc.to = NULL;
8033b97c
DN
3689 mc.moving_task = NULL;
3690 wake_up_all(&mc.waitq);
4ffef5fe
DN
3691}
3692
7dc74be0
DN
3693static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
3694 struct cgroup *cgroup,
3695 struct task_struct *p,
3696 bool threadgroup)
3697{
3698 int ret = 0;
3699 struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
3700
3701 if (mem->move_charge_at_immigrate) {
3702 struct mm_struct *mm;
3703 struct mem_cgroup *from = mem_cgroup_from_task(p);
3704
3705 VM_BUG_ON(from == mem);
3706
3707 mm = get_task_mm(p);
3708 if (!mm)
3709 return 0;
7dc74be0 3710 /* We move charges only when we move a owner of the mm */
4ffef5fe
DN
3711 if (mm->owner == p) {
3712 VM_BUG_ON(mc.from);
3713 VM_BUG_ON(mc.to);
3714 VM_BUG_ON(mc.precharge);
854ffa8d 3715 VM_BUG_ON(mc.moved_charge);
8033b97c 3716 VM_BUG_ON(mc.moving_task);
4ffef5fe
DN
3717 mc.from = from;
3718 mc.to = mem;
3719 mc.precharge = 0;
854ffa8d 3720 mc.moved_charge = 0;
8033b97c 3721 mc.moving_task = current;
4ffef5fe
DN
3722
3723 ret = mem_cgroup_precharge_mc(mm);
3724 if (ret)
3725 mem_cgroup_clear_mc();
3726 }
7dc74be0
DN
3727 mmput(mm);
3728 }
3729 return ret;
3730}
3731
3732static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
3733 struct cgroup *cgroup,
3734 struct task_struct *p,
3735 bool threadgroup)
3736{
4ffef5fe 3737 mem_cgroup_clear_mc();
7dc74be0
DN
3738}
3739
4ffef5fe
DN
3740static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
3741 unsigned long addr, unsigned long end,
3742 struct mm_walk *walk)
7dc74be0 3743{
4ffef5fe
DN
3744 int ret = 0;
3745 struct vm_area_struct *vma = walk->private;
3746 pte_t *pte;
3747 spinlock_t *ptl;
3748
3749retry:
3750 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
3751 for (; addr != end; addr += PAGE_SIZE) {
3752 pte_t ptent = *(pte++);
3753 union mc_target target;
3754 int type;
3755 struct page *page;
3756 struct page_cgroup *pc;
3757
3758 if (!mc.precharge)
3759 break;
3760
3761 type = is_target_pte_for_mc(vma, addr, ptent, &target);
3762 switch (type) {
3763 case MC_TARGET_PAGE:
3764 page = target.page;
3765 if (isolate_lru_page(page))
3766 goto put;
3767 pc = lookup_page_cgroup(page);
854ffa8d
DN
3768 if (!mem_cgroup_move_account(pc,
3769 mc.from, mc.to, false)) {
4ffef5fe 3770 mc.precharge--;
854ffa8d
DN
3771 /* we uncharge from mc.from later. */
3772 mc.moved_charge++;
4ffef5fe
DN
3773 }
3774 putback_lru_page(page);
3775put: /* is_target_pte_for_mc() gets the page */
3776 put_page(page);
3777 break;
3778 default:
3779 break;
3780 }
3781 }
3782 pte_unmap_unlock(pte - 1, ptl);
3783 cond_resched();
3784
3785 if (addr != end) {
3786 /*
3787 * We have consumed all precharges we got in can_attach().
3788 * We try charge one by one, but don't do any additional
3789 * charges to mc.to if we have failed in charge once in attach()
3790 * phase.
3791 */
854ffa8d 3792 ret = mem_cgroup_do_precharge(1);
4ffef5fe
DN
3793 if (!ret)
3794 goto retry;
3795 }
3796
3797 return ret;
3798}
3799
3800static void mem_cgroup_move_charge(struct mm_struct *mm)
3801{
3802 struct vm_area_struct *vma;
3803
3804 lru_add_drain_all();
3805 down_read(&mm->mmap_sem);
3806 for (vma = mm->mmap; vma; vma = vma->vm_next) {
3807 int ret;
3808 struct mm_walk mem_cgroup_move_charge_walk = {
3809 .pmd_entry = mem_cgroup_move_charge_pte_range,
3810 .mm = mm,
3811 .private = vma,
3812 };
3813 if (is_vm_hugetlb_page(vma))
3814 continue;
3815 /* TODO: We don't move charges of shmem/tmpfs pages for now. */
3816 if (vma->vm_flags & VM_SHARED)
3817 continue;
3818 ret = walk_page_range(vma->vm_start, vma->vm_end,
3819 &mem_cgroup_move_charge_walk);
3820 if (ret)
3821 /*
3822 * means we have consumed all precharges and failed in
3823 * doing additional charge. Just abandon here.
3824 */
3825 break;
3826 }
3827 up_read(&mm->mmap_sem);
7dc74be0
DN
3828}
3829
67e465a7
BS
3830static void mem_cgroup_move_task(struct cgroup_subsys *ss,
3831 struct cgroup *cont,
3832 struct cgroup *old_cont,
be367d09
BB
3833 struct task_struct *p,
3834 bool threadgroup)
67e465a7 3835{
4ffef5fe
DN
3836 struct mm_struct *mm;
3837
3838 if (!mc.to)
3839 /* no need to move charge */
3840 return;
3841
3842 mm = get_task_mm(p);
3843 if (mm) {
3844 mem_cgroup_move_charge(mm);
3845 mmput(mm);
3846 }
3847 mem_cgroup_clear_mc();
67e465a7
BS
3848}
3849
8cdea7c0
BS
3850struct cgroup_subsys mem_cgroup_subsys = {
3851 .name = "memory",
3852 .subsys_id = mem_cgroup_subsys_id,
3853 .create = mem_cgroup_create,
df878fb0 3854 .pre_destroy = mem_cgroup_pre_destroy,
8cdea7c0
BS
3855 .destroy = mem_cgroup_destroy,
3856 .populate = mem_cgroup_populate,
7dc74be0
DN
3857 .can_attach = mem_cgroup_can_attach,
3858 .cancel_attach = mem_cgroup_cancel_attach,
67e465a7 3859 .attach = mem_cgroup_move_task,
6d12e2d8 3860 .early_init = 0,
04046e1a 3861 .use_id = 1,
8cdea7c0 3862};
c077719b
KH
3863
3864#ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3865
3866static int __init disable_swap_account(char *s)
3867{
3868 really_do_swap_account = 0;
3869 return 1;
3870}
3871__setup("noswapaccount", disable_swap_account);
3872#endif