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