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