011aba6cad70fa58a887bf6220a888a8d4985598
[safe/jmp/linux-2.6] / mm / memcontrol.c
1 /* memcontrol.c - Memory Controller
2  *
3  * Copyright IBM Corporation, 2007
4  * Author Balbir Singh <balbir@linux.vnet.ibm.com>
5  *
6  * Copyright 2007 OpenVZ SWsoft Inc
7  * Author: Pavel Emelianov <xemul@openvz.org>
8  *
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>
23 #include <linux/mm.h>
24 #include <linux/pagemap.h>
25 #include <linux/smp.h>
26 #include <linux/page-flags.h>
27 #include <linux/backing-dev.h>
28 #include <linux/bit_spinlock.h>
29 #include <linux/rcupdate.h>
30 #include <linux/limits.h>
31 #include <linux/mutex.h>
32 #include <linux/rbtree.h>
33 #include <linux/slab.h>
34 #include <linux/swap.h>
35 #include <linux/spinlock.h>
36 #include <linux/fs.h>
37 #include <linux/seq_file.h>
38 #include <linux/vmalloc.h>
39 #include <linux/mm_inline.h>
40 #include <linux/page_cgroup.h>
41 #include "internal.h"
42
43 #include <asm/uaccess.h>
44
45 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
46 #define MEM_CGROUP_RECLAIM_RETRIES      5
47 struct mem_cgroup *root_mem_cgroup __read_mostly;
48
49 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
50 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
51 int do_swap_account __read_mostly;
52 static int really_do_swap_account __initdata = 1; /* for remember boot option*/
53 #else
54 #define do_swap_account         (0)
55 #endif
56
57 static DEFINE_MUTEX(memcg_tasklist);    /* can be hold under cgroup_mutex */
58 #define SOFTLIMIT_EVENTS_THRESH (1000)
59
60 /*
61  * Statistics for memory cgroup.
62  */
63 enum mem_cgroup_stat_index {
64         /*
65          * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
66          */
67         MEM_CGROUP_STAT_CACHE,     /* # of pages charged as cache */
68         MEM_CGROUP_STAT_RSS,       /* # of pages charged as anon rss */
69         MEM_CGROUP_STAT_MAPPED_FILE,  /* # of pages charged as file rss */
70         MEM_CGROUP_STAT_PGPGIN_COUNT,   /* # of pages paged in */
71         MEM_CGROUP_STAT_PGPGOUT_COUNT,  /* # of pages paged out */
72         MEM_CGROUP_STAT_EVENTS, /* sum of pagein + pageout for internal use */
73
74         MEM_CGROUP_STAT_NSTATS,
75 };
76
77 struct mem_cgroup_stat_cpu {
78         s64 count[MEM_CGROUP_STAT_NSTATS];
79 } ____cacheline_aligned_in_smp;
80
81 struct mem_cgroup_stat {
82         struct mem_cgroup_stat_cpu cpustat[0];
83 };
84
85 static inline void
86 __mem_cgroup_stat_reset_safe(struct mem_cgroup_stat_cpu *stat,
87                                 enum mem_cgroup_stat_index idx)
88 {
89         stat->count[idx] = 0;
90 }
91
92 static inline s64
93 __mem_cgroup_stat_read_local(struct mem_cgroup_stat_cpu *stat,
94                                 enum mem_cgroup_stat_index idx)
95 {
96         return stat->count[idx];
97 }
98
99 /*
100  * For accounting under irq disable, no need for increment preempt count.
101  */
102 static inline void __mem_cgroup_stat_add_safe(struct mem_cgroup_stat_cpu *stat,
103                 enum mem_cgroup_stat_index idx, int val)
104 {
105         stat->count[idx] += val;
106 }
107
108 static s64 mem_cgroup_read_stat(struct mem_cgroup_stat *stat,
109                 enum mem_cgroup_stat_index idx)
110 {
111         int cpu;
112         s64 ret = 0;
113         for_each_possible_cpu(cpu)
114                 ret += stat->cpustat[cpu].count[idx];
115         return ret;
116 }
117
118 static s64 mem_cgroup_local_usage(struct mem_cgroup_stat *stat)
119 {
120         s64 ret;
121
122         ret = mem_cgroup_read_stat(stat, MEM_CGROUP_STAT_CACHE);
123         ret += mem_cgroup_read_stat(stat, MEM_CGROUP_STAT_RSS);
124         return ret;
125 }
126
127 /*
128  * per-zone information in memory controller.
129  */
130 struct mem_cgroup_per_zone {
131         /*
132          * spin_lock to protect the per cgroup LRU
133          */
134         struct list_head        lists[NR_LRU_LISTS];
135         unsigned long           count[NR_LRU_LISTS];
136
137         struct zone_reclaim_stat reclaim_stat;
138         struct rb_node          tree_node;      /* RB tree node */
139         unsigned long long      usage_in_excess;/* Set to the value by which */
140                                                 /* the soft limit is exceeded*/
141         bool                    on_tree;
142         struct mem_cgroup       *mem;           /* Back pointer, we cannot */
143                                                 /* use container_of        */
144 };
145 /* Macro for accessing counter */
146 #define MEM_CGROUP_ZSTAT(mz, idx)       ((mz)->count[(idx)])
147
148 struct mem_cgroup_per_node {
149         struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
150 };
151
152 struct mem_cgroup_lru_info {
153         struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
154 };
155
156 /*
157  * Cgroups above their limits are maintained in a RB-Tree, independent of
158  * their hierarchy representation
159  */
160
161 struct mem_cgroup_tree_per_zone {
162         struct rb_root rb_root;
163         spinlock_t lock;
164 };
165
166 struct mem_cgroup_tree_per_node {
167         struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
168 };
169
170 struct mem_cgroup_tree {
171         struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
172 };
173
174 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
175
176 /*
177  * The memory controller data structure. The memory controller controls both
178  * page cache and RSS per cgroup. We would eventually like to provide
179  * statistics based on the statistics developed by Rik Van Riel for clock-pro,
180  * to help the administrator determine what knobs to tune.
181  *
182  * TODO: Add a water mark for the memory controller. Reclaim will begin when
183  * we hit the water mark. May be even add a low water mark, such that
184  * no reclaim occurs from a cgroup at it's low water mark, this is
185  * a feature that will be implemented much later in the future.
186  */
187 struct mem_cgroup {
188         struct cgroup_subsys_state css;
189         /*
190          * the counter to account for memory usage
191          */
192         struct res_counter res;
193         /*
194          * the counter to account for mem+swap usage.
195          */
196         struct res_counter memsw;
197         /*
198          * Per cgroup active and inactive list, similar to the
199          * per zone LRU lists.
200          */
201         struct mem_cgroup_lru_info info;
202
203         /*
204           protect against reclaim related member.
205         */
206         spinlock_t reclaim_param_lock;
207
208         int     prev_priority;  /* for recording reclaim priority */
209
210         /*
211          * While reclaiming in a hiearchy, we cache the last child we
212          * reclaimed from.
213          */
214         int last_scanned_child;
215         /*
216          * Should the accounting and control be hierarchical, per subtree?
217          */
218         bool use_hierarchy;
219         unsigned long   last_oom_jiffies;
220         atomic_t        refcnt;
221
222         unsigned int    swappiness;
223
224         /* set when res.limit == memsw.limit */
225         bool            memsw_is_minimum;
226
227         /*
228          * statistics. This must be placed at the end of memcg.
229          */
230         struct mem_cgroup_stat stat;
231 };
232
233 /*
234  * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
235  * limit reclaim to prevent infinite loops, if they ever occur.
236  */
237 #define MEM_CGROUP_MAX_RECLAIM_LOOPS            (100)
238 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
239
240 enum charge_type {
241         MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
242         MEM_CGROUP_CHARGE_TYPE_MAPPED,
243         MEM_CGROUP_CHARGE_TYPE_SHMEM,   /* used by page migration of shmem */
244         MEM_CGROUP_CHARGE_TYPE_FORCE,   /* used by force_empty */
245         MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
246         MEM_CGROUP_CHARGE_TYPE_DROP,    /* a page was unused swap cache */
247         NR_CHARGE_TYPE,
248 };
249
250 /* only for here (for easy reading.) */
251 #define PCGF_CACHE      (1UL << PCG_CACHE)
252 #define PCGF_USED       (1UL << PCG_USED)
253 #define PCGF_LOCK       (1UL << PCG_LOCK)
254 /* Not used, but added here for completeness */
255 #define PCGF_ACCT       (1UL << PCG_ACCT)
256
257 /* for encoding cft->private value on file */
258 #define _MEM                    (0)
259 #define _MEMSWAP                (1)
260 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
261 #define MEMFILE_TYPE(val)       (((val) >> 16) & 0xffff)
262 #define MEMFILE_ATTR(val)       ((val) & 0xffff)
263
264 /*
265  * Reclaim flags for mem_cgroup_hierarchical_reclaim
266  */
267 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT   0x0
268 #define MEM_CGROUP_RECLAIM_NOSWAP       (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
269 #define MEM_CGROUP_RECLAIM_SHRINK_BIT   0x1
270 #define MEM_CGROUP_RECLAIM_SHRINK       (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
271 #define MEM_CGROUP_RECLAIM_SOFT_BIT     0x2
272 #define MEM_CGROUP_RECLAIM_SOFT         (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
273
274 static void mem_cgroup_get(struct mem_cgroup *mem);
275 static void mem_cgroup_put(struct mem_cgroup *mem);
276 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
277
278 static struct mem_cgroup_per_zone *
279 mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
280 {
281         return &mem->info.nodeinfo[nid]->zoneinfo[zid];
282 }
283
284 static struct mem_cgroup_per_zone *
285 page_cgroup_zoneinfo(struct page_cgroup *pc)
286 {
287         struct mem_cgroup *mem = pc->mem_cgroup;
288         int nid = page_cgroup_nid(pc);
289         int zid = page_cgroup_zid(pc);
290
291         if (!mem)
292                 return NULL;
293
294         return mem_cgroup_zoneinfo(mem, nid, zid);
295 }
296
297 static struct mem_cgroup_tree_per_zone *
298 soft_limit_tree_node_zone(int nid, int zid)
299 {
300         return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
301 }
302
303 static struct mem_cgroup_tree_per_zone *
304 soft_limit_tree_from_page(struct page *page)
305 {
306         int nid = page_to_nid(page);
307         int zid = page_zonenum(page);
308
309         return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
310 }
311
312 static void
313 __mem_cgroup_insert_exceeded(struct mem_cgroup *mem,
314                                 struct mem_cgroup_per_zone *mz,
315                                 struct mem_cgroup_tree_per_zone *mctz)
316 {
317         struct rb_node **p = &mctz->rb_root.rb_node;
318         struct rb_node *parent = NULL;
319         struct mem_cgroup_per_zone *mz_node;
320
321         if (mz->on_tree)
322                 return;
323
324         mz->usage_in_excess = res_counter_soft_limit_excess(&mem->res);
325         while (*p) {
326                 parent = *p;
327                 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
328                                         tree_node);
329                 if (mz->usage_in_excess < mz_node->usage_in_excess)
330                         p = &(*p)->rb_left;
331                 /*
332                  * We can't avoid mem cgroups that are over their soft
333                  * limit by the same amount
334                  */
335                 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
336                         p = &(*p)->rb_right;
337         }
338         rb_link_node(&mz->tree_node, parent, p);
339         rb_insert_color(&mz->tree_node, &mctz->rb_root);
340         mz->on_tree = true;
341 }
342
343 static void
344 __mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
345                                 struct mem_cgroup_per_zone *mz,
346                                 struct mem_cgroup_tree_per_zone *mctz)
347 {
348         if (!mz->on_tree)
349                 return;
350         rb_erase(&mz->tree_node, &mctz->rb_root);
351         mz->on_tree = false;
352 }
353
354 static void
355 mem_cgroup_insert_exceeded(struct mem_cgroup *mem,
356                                 struct mem_cgroup_per_zone *mz,
357                                 struct mem_cgroup_tree_per_zone *mctz)
358 {
359         spin_lock(&mctz->lock);
360         __mem_cgroup_insert_exceeded(mem, mz, mctz);
361         spin_unlock(&mctz->lock);
362 }
363
364 static void
365 mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
366                                 struct mem_cgroup_per_zone *mz,
367                                 struct mem_cgroup_tree_per_zone *mctz)
368 {
369         spin_lock(&mctz->lock);
370         __mem_cgroup_remove_exceeded(mem, mz, mctz);
371         spin_unlock(&mctz->lock);
372 }
373
374 static bool mem_cgroup_soft_limit_check(struct mem_cgroup *mem)
375 {
376         bool ret = false;
377         int cpu;
378         s64 val;
379         struct mem_cgroup_stat_cpu *cpustat;
380
381         cpu = get_cpu();
382         cpustat = &mem->stat.cpustat[cpu];
383         val = __mem_cgroup_stat_read_local(cpustat, MEM_CGROUP_STAT_EVENTS);
384         if (unlikely(val > SOFTLIMIT_EVENTS_THRESH)) {
385                 __mem_cgroup_stat_reset_safe(cpustat, MEM_CGROUP_STAT_EVENTS);
386                 ret = true;
387         }
388         put_cpu();
389         return ret;
390 }
391
392 static void mem_cgroup_update_tree(struct mem_cgroup *mem, struct page *page)
393 {
394         unsigned long long prev_usage_in_excess, new_usage_in_excess;
395         bool updated_tree = false;
396         struct mem_cgroup_per_zone *mz;
397         struct mem_cgroup_tree_per_zone *mctz;
398
399         mz = mem_cgroup_zoneinfo(mem, page_to_nid(page), page_zonenum(page));
400         mctz = soft_limit_tree_from_page(page);
401
402         /*
403          * We do updates in lazy mode, mem's are removed
404          * lazily from the per-zone, per-node rb tree
405          */
406         prev_usage_in_excess = mz->usage_in_excess;
407
408         new_usage_in_excess = res_counter_soft_limit_excess(&mem->res);
409         if (prev_usage_in_excess) {
410                 mem_cgroup_remove_exceeded(mem, mz, mctz);
411                 updated_tree = true;
412         }
413         if (!new_usage_in_excess)
414                 goto done;
415         mem_cgroup_insert_exceeded(mem, mz, mctz);
416
417 done:
418         if (updated_tree) {
419                 spin_lock(&mctz->lock);
420                 mz->usage_in_excess = new_usage_in_excess;
421                 spin_unlock(&mctz->lock);
422         }
423 }
424
425 static void mem_cgroup_remove_from_trees(struct mem_cgroup *mem)
426 {
427         int node, zone;
428         struct mem_cgroup_per_zone *mz;
429         struct mem_cgroup_tree_per_zone *mctz;
430
431         for_each_node_state(node, N_POSSIBLE) {
432                 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
433                         mz = mem_cgroup_zoneinfo(mem, node, zone);
434                         mctz = soft_limit_tree_node_zone(node, zone);
435                         mem_cgroup_remove_exceeded(mem, mz, mctz);
436                 }
437         }
438 }
439
440 static inline unsigned long mem_cgroup_get_excess(struct mem_cgroup *mem)
441 {
442         return res_counter_soft_limit_excess(&mem->res) >> PAGE_SHIFT;
443 }
444
445 static struct mem_cgroup_per_zone *
446 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
447 {
448         struct rb_node *rightmost = NULL;
449         struct mem_cgroup_per_zone *mz = NULL;
450
451 retry:
452         rightmost = rb_last(&mctz->rb_root);
453         if (!rightmost)
454                 goto done;              /* Nothing to reclaim from */
455
456         mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
457         /*
458          * Remove the node now but someone else can add it back,
459          * we will to add it back at the end of reclaim to its correct
460          * position in the tree.
461          */
462         __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
463         if (!res_counter_soft_limit_excess(&mz->mem->res) ||
464                 !css_tryget(&mz->mem->css))
465                 goto retry;
466 done:
467         return mz;
468 }
469
470 static struct mem_cgroup_per_zone *
471 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
472 {
473         struct mem_cgroup_per_zone *mz;
474
475         spin_lock(&mctz->lock);
476         mz = __mem_cgroup_largest_soft_limit_node(mctz);
477         spin_unlock(&mctz->lock);
478         return mz;
479 }
480
481 static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
482                                          struct page_cgroup *pc,
483                                          bool charge)
484 {
485         int val = (charge)? 1 : -1;
486         struct mem_cgroup_stat *stat = &mem->stat;
487         struct mem_cgroup_stat_cpu *cpustat;
488         int cpu = get_cpu();
489
490         cpustat = &stat->cpustat[cpu];
491         if (PageCgroupCache(pc))
492                 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_CACHE, val);
493         else
494                 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_RSS, val);
495
496         if (charge)
497                 __mem_cgroup_stat_add_safe(cpustat,
498                                 MEM_CGROUP_STAT_PGPGIN_COUNT, 1);
499         else
500                 __mem_cgroup_stat_add_safe(cpustat,
501                                 MEM_CGROUP_STAT_PGPGOUT_COUNT, 1);
502         __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_EVENTS, 1);
503         put_cpu();
504 }
505
506 static unsigned long mem_cgroup_get_local_zonestat(struct mem_cgroup *mem,
507                                         enum lru_list idx)
508 {
509         int nid, zid;
510         struct mem_cgroup_per_zone *mz;
511         u64 total = 0;
512
513         for_each_online_node(nid)
514                 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
515                         mz = mem_cgroup_zoneinfo(mem, nid, zid);
516                         total += MEM_CGROUP_ZSTAT(mz, idx);
517                 }
518         return total;
519 }
520
521 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
522 {
523         return container_of(cgroup_subsys_state(cont,
524                                 mem_cgroup_subsys_id), struct mem_cgroup,
525                                 css);
526 }
527
528 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
529 {
530         /*
531          * mm_update_next_owner() may clear mm->owner to NULL
532          * if it races with swapoff, page migration, etc.
533          * So this can be called with p == NULL.
534          */
535         if (unlikely(!p))
536                 return NULL;
537
538         return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
539                                 struct mem_cgroup, css);
540 }
541
542 static struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
543 {
544         struct mem_cgroup *mem = NULL;
545
546         if (!mm)
547                 return NULL;
548         /*
549          * Because we have no locks, mm->owner's may be being moved to other
550          * cgroup. We use css_tryget() here even if this looks
551          * pessimistic (rather than adding locks here).
552          */
553         rcu_read_lock();
554         do {
555                 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
556                 if (unlikely(!mem))
557                         break;
558         } while (!css_tryget(&mem->css));
559         rcu_read_unlock();
560         return mem;
561 }
562
563 /*
564  * Call callback function against all cgroup under hierarchy tree.
565  */
566 static int mem_cgroup_walk_tree(struct mem_cgroup *root, void *data,
567                           int (*func)(struct mem_cgroup *, void *))
568 {
569         int found, ret, nextid;
570         struct cgroup_subsys_state *css;
571         struct mem_cgroup *mem;
572
573         if (!root->use_hierarchy)
574                 return (*func)(root, data);
575
576         nextid = 1;
577         do {
578                 ret = 0;
579                 mem = NULL;
580
581                 rcu_read_lock();
582                 css = css_get_next(&mem_cgroup_subsys, nextid, &root->css,
583                                    &found);
584                 if (css && css_tryget(css))
585                         mem = container_of(css, struct mem_cgroup, css);
586                 rcu_read_unlock();
587
588                 if (mem) {
589                         ret = (*func)(mem, data);
590                         css_put(&mem->css);
591                 }
592                 nextid = found + 1;
593         } while (!ret && css);
594
595         return ret;
596 }
597
598 static inline bool mem_cgroup_is_root(struct mem_cgroup *mem)
599 {
600         return (mem == root_mem_cgroup);
601 }
602
603 /*
604  * Following LRU functions are allowed to be used without PCG_LOCK.
605  * Operations are called by routine of global LRU independently from memcg.
606  * What we have to take care of here is validness of pc->mem_cgroup.
607  *
608  * Changes to pc->mem_cgroup happens when
609  * 1. charge
610  * 2. moving account
611  * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
612  * It is added to LRU before charge.
613  * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
614  * When moving account, the page is not on LRU. It's isolated.
615  */
616
617 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
618 {
619         struct page_cgroup *pc;
620         struct mem_cgroup_per_zone *mz;
621
622         if (mem_cgroup_disabled())
623                 return;
624         pc = lookup_page_cgroup(page);
625         /* can happen while we handle swapcache. */
626         if (!TestClearPageCgroupAcctLRU(pc))
627                 return;
628         VM_BUG_ON(!pc->mem_cgroup);
629         /*
630          * We don't check PCG_USED bit. It's cleared when the "page" is finally
631          * removed from global LRU.
632          */
633         mz = page_cgroup_zoneinfo(pc);
634         MEM_CGROUP_ZSTAT(mz, lru) -= 1;
635         if (mem_cgroup_is_root(pc->mem_cgroup))
636                 return;
637         VM_BUG_ON(list_empty(&pc->lru));
638         list_del_init(&pc->lru);
639         return;
640 }
641
642 void mem_cgroup_del_lru(struct page *page)
643 {
644         mem_cgroup_del_lru_list(page, page_lru(page));
645 }
646
647 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
648 {
649         struct mem_cgroup_per_zone *mz;
650         struct page_cgroup *pc;
651
652         if (mem_cgroup_disabled())
653                 return;
654
655         pc = lookup_page_cgroup(page);
656         /*
657          * Used bit is set without atomic ops but after smp_wmb().
658          * For making pc->mem_cgroup visible, insert smp_rmb() here.
659          */
660         smp_rmb();
661         /* unused or root page is not rotated. */
662         if (!PageCgroupUsed(pc) || mem_cgroup_is_root(pc->mem_cgroup))
663                 return;
664         mz = page_cgroup_zoneinfo(pc);
665         list_move(&pc->lru, &mz->lists[lru]);
666 }
667
668 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
669 {
670         struct page_cgroup *pc;
671         struct mem_cgroup_per_zone *mz;
672
673         if (mem_cgroup_disabled())
674                 return;
675         pc = lookup_page_cgroup(page);
676         VM_BUG_ON(PageCgroupAcctLRU(pc));
677         /*
678          * Used bit is set without atomic ops but after smp_wmb().
679          * For making pc->mem_cgroup visible, insert smp_rmb() here.
680          */
681         smp_rmb();
682         if (!PageCgroupUsed(pc))
683                 return;
684
685         mz = page_cgroup_zoneinfo(pc);
686         MEM_CGROUP_ZSTAT(mz, lru) += 1;
687         SetPageCgroupAcctLRU(pc);
688         if (mem_cgroup_is_root(pc->mem_cgroup))
689                 return;
690         list_add(&pc->lru, &mz->lists[lru]);
691 }
692
693 /*
694  * At handling SwapCache, pc->mem_cgroup may be changed while it's linked to
695  * lru because the page may.be reused after it's fully uncharged (because of
696  * SwapCache behavior).To handle that, unlink page_cgroup from LRU when charge
697  * it again. This function is only used to charge SwapCache. It's done under
698  * lock_page and expected that zone->lru_lock is never held.
699  */
700 static void mem_cgroup_lru_del_before_commit_swapcache(struct page *page)
701 {
702         unsigned long flags;
703         struct zone *zone = page_zone(page);
704         struct page_cgroup *pc = lookup_page_cgroup(page);
705
706         spin_lock_irqsave(&zone->lru_lock, flags);
707         /*
708          * Forget old LRU when this page_cgroup is *not* used. This Used bit
709          * is guarded by lock_page() because the page is SwapCache.
710          */
711         if (!PageCgroupUsed(pc))
712                 mem_cgroup_del_lru_list(page, page_lru(page));
713         spin_unlock_irqrestore(&zone->lru_lock, flags);
714 }
715
716 static void mem_cgroup_lru_add_after_commit_swapcache(struct page *page)
717 {
718         unsigned long flags;
719         struct zone *zone = page_zone(page);
720         struct page_cgroup *pc = lookup_page_cgroup(page);
721
722         spin_lock_irqsave(&zone->lru_lock, flags);
723         /* link when the page is linked to LRU but page_cgroup isn't */
724         if (PageLRU(page) && !PageCgroupAcctLRU(pc))
725                 mem_cgroup_add_lru_list(page, page_lru(page));
726         spin_unlock_irqrestore(&zone->lru_lock, flags);
727 }
728
729
730 void mem_cgroup_move_lists(struct page *page,
731                            enum lru_list from, enum lru_list to)
732 {
733         if (mem_cgroup_disabled())
734                 return;
735         mem_cgroup_del_lru_list(page, from);
736         mem_cgroup_add_lru_list(page, to);
737 }
738
739 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
740 {
741         int ret;
742         struct mem_cgroup *curr = NULL;
743
744         task_lock(task);
745         rcu_read_lock();
746         curr = try_get_mem_cgroup_from_mm(task->mm);
747         rcu_read_unlock();
748         task_unlock(task);
749         if (!curr)
750                 return 0;
751         if (curr->use_hierarchy)
752                 ret = css_is_ancestor(&curr->css, &mem->css);
753         else
754                 ret = (curr == mem);
755         css_put(&curr->css);
756         return ret;
757 }
758
759 /*
760  * prev_priority control...this will be used in memory reclaim path.
761  */
762 int mem_cgroup_get_reclaim_priority(struct mem_cgroup *mem)
763 {
764         int prev_priority;
765
766         spin_lock(&mem->reclaim_param_lock);
767         prev_priority = mem->prev_priority;
768         spin_unlock(&mem->reclaim_param_lock);
769
770         return prev_priority;
771 }
772
773 void mem_cgroup_note_reclaim_priority(struct mem_cgroup *mem, int priority)
774 {
775         spin_lock(&mem->reclaim_param_lock);
776         if (priority < mem->prev_priority)
777                 mem->prev_priority = priority;
778         spin_unlock(&mem->reclaim_param_lock);
779 }
780
781 void mem_cgroup_record_reclaim_priority(struct mem_cgroup *mem, int priority)
782 {
783         spin_lock(&mem->reclaim_param_lock);
784         mem->prev_priority = priority;
785         spin_unlock(&mem->reclaim_param_lock);
786 }
787
788 static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
789 {
790         unsigned long active;
791         unsigned long inactive;
792         unsigned long gb;
793         unsigned long inactive_ratio;
794
795         inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_ANON);
796         active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_ANON);
797
798         gb = (inactive + active) >> (30 - PAGE_SHIFT);
799         if (gb)
800                 inactive_ratio = int_sqrt(10 * gb);
801         else
802                 inactive_ratio = 1;
803
804         if (present_pages) {
805                 present_pages[0] = inactive;
806                 present_pages[1] = active;
807         }
808
809         return inactive_ratio;
810 }
811
812 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
813 {
814         unsigned long active;
815         unsigned long inactive;
816         unsigned long present_pages[2];
817         unsigned long inactive_ratio;
818
819         inactive_ratio = calc_inactive_ratio(memcg, present_pages);
820
821         inactive = present_pages[0];
822         active = present_pages[1];
823
824         if (inactive * inactive_ratio < active)
825                 return 1;
826
827         return 0;
828 }
829
830 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
831 {
832         unsigned long active;
833         unsigned long inactive;
834
835         inactive = mem_cgroup_get_local_zonestat(memcg, LRU_INACTIVE_FILE);
836         active = mem_cgroup_get_local_zonestat(memcg, LRU_ACTIVE_FILE);
837
838         return (active > inactive);
839 }
840
841 unsigned long mem_cgroup_zone_nr_pages(struct mem_cgroup *memcg,
842                                        struct zone *zone,
843                                        enum lru_list lru)
844 {
845         int nid = zone->zone_pgdat->node_id;
846         int zid = zone_idx(zone);
847         struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
848
849         return MEM_CGROUP_ZSTAT(mz, lru);
850 }
851
852 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
853                                                       struct zone *zone)
854 {
855         int nid = zone->zone_pgdat->node_id;
856         int zid = zone_idx(zone);
857         struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
858
859         return &mz->reclaim_stat;
860 }
861
862 struct zone_reclaim_stat *
863 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
864 {
865         struct page_cgroup *pc;
866         struct mem_cgroup_per_zone *mz;
867
868         if (mem_cgroup_disabled())
869                 return NULL;
870
871         pc = lookup_page_cgroup(page);
872         /*
873          * Used bit is set without atomic ops but after smp_wmb().
874          * For making pc->mem_cgroup visible, insert smp_rmb() here.
875          */
876         smp_rmb();
877         if (!PageCgroupUsed(pc))
878                 return NULL;
879
880         mz = page_cgroup_zoneinfo(pc);
881         if (!mz)
882                 return NULL;
883
884         return &mz->reclaim_stat;
885 }
886
887 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
888                                         struct list_head *dst,
889                                         unsigned long *scanned, int order,
890                                         int mode, struct zone *z,
891                                         struct mem_cgroup *mem_cont,
892                                         int active, int file)
893 {
894         unsigned long nr_taken = 0;
895         struct page *page;
896         unsigned long scan;
897         LIST_HEAD(pc_list);
898         struct list_head *src;
899         struct page_cgroup *pc, *tmp;
900         int nid = z->zone_pgdat->node_id;
901         int zid = zone_idx(z);
902         struct mem_cgroup_per_zone *mz;
903         int lru = LRU_FILE * file + active;
904         int ret;
905
906         BUG_ON(!mem_cont);
907         mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
908         src = &mz->lists[lru];
909
910         scan = 0;
911         list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
912                 if (scan >= nr_to_scan)
913                         break;
914
915                 page = pc->page;
916                 if (unlikely(!PageCgroupUsed(pc)))
917                         continue;
918                 if (unlikely(!PageLRU(page)))
919                         continue;
920
921                 scan++;
922                 ret = __isolate_lru_page(page, mode, file);
923                 switch (ret) {
924                 case 0:
925                         list_move(&page->lru, dst);
926                         mem_cgroup_del_lru(page);
927                         nr_taken++;
928                         break;
929                 case -EBUSY:
930                         /* we don't affect global LRU but rotate in our LRU */
931                         mem_cgroup_rotate_lru_list(page, page_lru(page));
932                         break;
933                 default:
934                         break;
935                 }
936         }
937
938         *scanned = scan;
939         return nr_taken;
940 }
941
942 #define mem_cgroup_from_res_counter(counter, member)    \
943         container_of(counter, struct mem_cgroup, member)
944
945 static bool mem_cgroup_check_under_limit(struct mem_cgroup *mem)
946 {
947         if (do_swap_account) {
948                 if (res_counter_check_under_limit(&mem->res) &&
949                         res_counter_check_under_limit(&mem->memsw))
950                         return true;
951         } else
952                 if (res_counter_check_under_limit(&mem->res))
953                         return true;
954         return false;
955 }
956
957 static unsigned int get_swappiness(struct mem_cgroup *memcg)
958 {
959         struct cgroup *cgrp = memcg->css.cgroup;
960         unsigned int swappiness;
961
962         /* root ? */
963         if (cgrp->parent == NULL)
964                 return vm_swappiness;
965
966         spin_lock(&memcg->reclaim_param_lock);
967         swappiness = memcg->swappiness;
968         spin_unlock(&memcg->reclaim_param_lock);
969
970         return swappiness;
971 }
972
973 static int mem_cgroup_count_children_cb(struct mem_cgroup *mem, void *data)
974 {
975         int *val = data;
976         (*val)++;
977         return 0;
978 }
979
980 /**
981  * mem_cgroup_print_mem_info: Called from OOM with tasklist_lock held in read mode.
982  * @memcg: The memory cgroup that went over limit
983  * @p: Task that is going to be killed
984  *
985  * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
986  * enabled
987  */
988 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
989 {
990         struct cgroup *task_cgrp;
991         struct cgroup *mem_cgrp;
992         /*
993          * Need a buffer in BSS, can't rely on allocations. The code relies
994          * on the assumption that OOM is serialized for memory controller.
995          * If this assumption is broken, revisit this code.
996          */
997         static char memcg_name[PATH_MAX];
998         int ret;
999
1000         if (!memcg)
1001                 return;
1002
1003
1004         rcu_read_lock();
1005
1006         mem_cgrp = memcg->css.cgroup;
1007         task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1008
1009         ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1010         if (ret < 0) {
1011                 /*
1012                  * Unfortunately, we are unable to convert to a useful name
1013                  * But we'll still print out the usage information
1014                  */
1015                 rcu_read_unlock();
1016                 goto done;
1017         }
1018         rcu_read_unlock();
1019
1020         printk(KERN_INFO "Task in %s killed", memcg_name);
1021
1022         rcu_read_lock();
1023         ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1024         if (ret < 0) {
1025                 rcu_read_unlock();
1026                 goto done;
1027         }
1028         rcu_read_unlock();
1029
1030         /*
1031          * Continues from above, so we don't need an KERN_ level
1032          */
1033         printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1034 done:
1035
1036         printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1037                 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1038                 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1039                 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1040         printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1041                 "failcnt %llu\n",
1042                 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1043                 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1044                 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1045 }
1046
1047 /*
1048  * This function returns the number of memcg under hierarchy tree. Returns
1049  * 1(self count) if no children.
1050  */
1051 static int mem_cgroup_count_children(struct mem_cgroup *mem)
1052 {
1053         int num = 0;
1054         mem_cgroup_walk_tree(mem, &num, mem_cgroup_count_children_cb);
1055         return num;
1056 }
1057
1058 /*
1059  * Visit the first child (need not be the first child as per the ordering
1060  * of the cgroup list, since we track last_scanned_child) of @mem and use
1061  * that to reclaim free pages from.
1062  */
1063 static struct mem_cgroup *
1064 mem_cgroup_select_victim(struct mem_cgroup *root_mem)
1065 {
1066         struct mem_cgroup *ret = NULL;
1067         struct cgroup_subsys_state *css;
1068         int nextid, found;
1069
1070         if (!root_mem->use_hierarchy) {
1071                 css_get(&root_mem->css);
1072                 ret = root_mem;
1073         }
1074
1075         while (!ret) {
1076                 rcu_read_lock();
1077                 nextid = root_mem->last_scanned_child + 1;
1078                 css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
1079                                    &found);
1080                 if (css && css_tryget(css))
1081                         ret = container_of(css, struct mem_cgroup, css);
1082
1083                 rcu_read_unlock();
1084                 /* Updates scanning parameter */
1085                 spin_lock(&root_mem->reclaim_param_lock);
1086                 if (!css) {
1087                         /* this means start scan from ID:1 */
1088                         root_mem->last_scanned_child = 0;
1089                 } else
1090                         root_mem->last_scanned_child = found;
1091                 spin_unlock(&root_mem->reclaim_param_lock);
1092         }
1093
1094         return ret;
1095 }
1096
1097 /*
1098  * Scan the hierarchy if needed to reclaim memory. We remember the last child
1099  * we reclaimed from, so that we don't end up penalizing one child extensively
1100  * based on its position in the children list.
1101  *
1102  * root_mem is the original ancestor that we've been reclaim from.
1103  *
1104  * We give up and return to the caller when we visit root_mem twice.
1105  * (other groups can be removed while we're walking....)
1106  *
1107  * If shrink==true, for avoiding to free too much, this returns immedieately.
1108  */
1109 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
1110                                                 struct zone *zone,
1111                                                 gfp_t gfp_mask,
1112                                                 unsigned long reclaim_options)
1113 {
1114         struct mem_cgroup *victim;
1115         int ret, total = 0;
1116         int loop = 0;
1117         bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1118         bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1119         bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1120         unsigned long excess = mem_cgroup_get_excess(root_mem);
1121
1122         /* If memsw_is_minimum==1, swap-out is of-no-use. */
1123         if (root_mem->memsw_is_minimum)
1124                 noswap = true;
1125
1126         while (1) {
1127                 victim = mem_cgroup_select_victim(root_mem);
1128                 if (victim == root_mem) {
1129                         loop++;
1130                         if (loop >= 2) {
1131                                 /*
1132                                  * If we have not been able to reclaim
1133                                  * anything, it might because there are
1134                                  * no reclaimable pages under this hierarchy
1135                                  */
1136                                 if (!check_soft || !total) {
1137                                         css_put(&victim->css);
1138                                         break;
1139                                 }
1140                                 /*
1141                                  * We want to do more targetted reclaim.
1142                                  * excess >> 2 is not to excessive so as to
1143                                  * reclaim too much, nor too less that we keep
1144                                  * coming back to reclaim from this cgroup
1145                                  */
1146                                 if (total >= (excess >> 2) ||
1147                                         (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1148                                         css_put(&victim->css);
1149                                         break;
1150                                 }
1151                         }
1152                 }
1153                 if (!mem_cgroup_local_usage(&victim->stat)) {
1154                         /* this cgroup's local usage == 0 */
1155                         css_put(&victim->css);
1156                         continue;
1157                 }
1158                 /* we use swappiness of local cgroup */
1159                 if (check_soft)
1160                         ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1161                                 noswap, get_swappiness(victim), zone,
1162                                 zone->zone_pgdat->node_id);
1163                 else
1164                         ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1165                                                 noswap, get_swappiness(victim));
1166                 css_put(&victim->css);
1167                 /*
1168                  * At shrinking usage, we can't check we should stop here or
1169                  * reclaim more. It's depends on callers. last_scanned_child
1170                  * will work enough for keeping fairness under tree.
1171                  */
1172                 if (shrink)
1173                         return ret;
1174                 total += ret;
1175                 if (check_soft) {
1176                         if (res_counter_check_under_soft_limit(&root_mem->res))
1177                                 return total;
1178                 } else if (mem_cgroup_check_under_limit(root_mem))
1179                         return 1 + total;
1180         }
1181         return total;
1182 }
1183
1184 bool mem_cgroup_oom_called(struct task_struct *task)
1185 {
1186         bool ret = false;
1187         struct mem_cgroup *mem;
1188         struct mm_struct *mm;
1189
1190         rcu_read_lock();
1191         mm = task->mm;
1192         if (!mm)
1193                 mm = &init_mm;
1194         mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
1195         if (mem && time_before(jiffies, mem->last_oom_jiffies + HZ/10))
1196                 ret = true;
1197         rcu_read_unlock();
1198         return ret;
1199 }
1200
1201 static int record_last_oom_cb(struct mem_cgroup *mem, void *data)
1202 {
1203         mem->last_oom_jiffies = jiffies;
1204         return 0;
1205 }
1206
1207 static void record_last_oom(struct mem_cgroup *mem)
1208 {
1209         mem_cgroup_walk_tree(mem, NULL, record_last_oom_cb);
1210 }
1211
1212 /*
1213  * Currently used to update mapped file statistics, but the routine can be
1214  * generalized to update other statistics as well.
1215  */
1216 void mem_cgroup_update_mapped_file_stat(struct page *page, int val)
1217 {
1218         struct mem_cgroup *mem;
1219         struct mem_cgroup_stat *stat;
1220         struct mem_cgroup_stat_cpu *cpustat;
1221         int cpu;
1222         struct page_cgroup *pc;
1223
1224         if (!page_is_file_cache(page))
1225                 return;
1226
1227         pc = lookup_page_cgroup(page);
1228         if (unlikely(!pc))
1229                 return;
1230
1231         lock_page_cgroup(pc);
1232         mem = pc->mem_cgroup;
1233         if (!mem)
1234                 goto done;
1235
1236         if (!PageCgroupUsed(pc))
1237                 goto done;
1238
1239         /*
1240          * Preemption is already disabled, we don't need get_cpu()
1241          */
1242         cpu = smp_processor_id();
1243         stat = &mem->stat;
1244         cpustat = &stat->cpustat[cpu];
1245
1246         __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_MAPPED_FILE, val);
1247 done:
1248         unlock_page_cgroup(pc);
1249 }
1250
1251 /*
1252  * Unlike exported interface, "oom" parameter is added. if oom==true,
1253  * oom-killer can be invoked.
1254  */
1255 static int __mem_cgroup_try_charge(struct mm_struct *mm,
1256                         gfp_t gfp_mask, struct mem_cgroup **memcg,
1257                         bool oom, struct page *page)
1258 {
1259         struct mem_cgroup *mem, *mem_over_limit, *mem_over_soft_limit;
1260         int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
1261         struct res_counter *fail_res, *soft_fail_res = NULL;
1262
1263         if (unlikely(test_thread_flag(TIF_MEMDIE))) {
1264                 /* Don't account this! */
1265                 *memcg = NULL;
1266                 return 0;
1267         }
1268
1269         /*
1270          * We always charge the cgroup the mm_struct belongs to.
1271          * The mm_struct's mem_cgroup changes on task migration if the
1272          * thread group leader migrates. It's possible that mm is not
1273          * set, if so charge the init_mm (happens for pagecache usage).
1274          */
1275         mem = *memcg;
1276         if (likely(!mem)) {
1277                 mem = try_get_mem_cgroup_from_mm(mm);
1278                 *memcg = mem;
1279         } else {
1280                 css_get(&mem->css);
1281         }
1282         if (unlikely(!mem))
1283                 return 0;
1284
1285         VM_BUG_ON(css_is_removed(&mem->css));
1286
1287         while (1) {
1288                 int ret;
1289                 unsigned long flags = 0;
1290
1291                 ret = res_counter_charge(&mem->res, PAGE_SIZE, &fail_res,
1292                                                 &soft_fail_res);
1293                 if (likely(!ret)) {
1294                         if (!do_swap_account)
1295                                 break;
1296                         ret = res_counter_charge(&mem->memsw, PAGE_SIZE,
1297                                                         &fail_res, NULL);
1298                         if (likely(!ret))
1299                                 break;
1300                         /* mem+swap counter fails */
1301                         res_counter_uncharge(&mem->res, PAGE_SIZE, NULL);
1302                         flags |= MEM_CGROUP_RECLAIM_NOSWAP;
1303                         mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1304                                                                         memsw);
1305                 } else
1306                         /* mem counter fails */
1307                         mem_over_limit = mem_cgroup_from_res_counter(fail_res,
1308                                                                         res);
1309
1310                 if (!(gfp_mask & __GFP_WAIT))
1311                         goto nomem;
1312
1313                 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
1314                                                 gfp_mask, flags);
1315                 if (ret)
1316                         continue;
1317
1318                 /*
1319                  * try_to_free_mem_cgroup_pages() might not give us a full
1320                  * picture of reclaim. Some pages are reclaimed and might be
1321                  * moved to swap cache or just unmapped from the cgroup.
1322                  * Check the limit again to see if the reclaim reduced the
1323                  * current usage of the cgroup before giving up
1324                  *
1325                  */
1326                 if (mem_cgroup_check_under_limit(mem_over_limit))
1327                         continue;
1328
1329                 if (!nr_retries--) {
1330                         if (oom) {
1331                                 mutex_lock(&memcg_tasklist);
1332                                 mem_cgroup_out_of_memory(mem_over_limit, gfp_mask);
1333                                 mutex_unlock(&memcg_tasklist);
1334                                 record_last_oom(mem_over_limit);
1335                         }
1336                         goto nomem;
1337                 }
1338         }
1339         /*
1340          * Insert just the ancestor, we should trickle down to the correct
1341          * cgroup for reclaim, since the other nodes will be below their
1342          * soft limit
1343          */
1344         if (soft_fail_res) {
1345                 mem_over_soft_limit =
1346                         mem_cgroup_from_res_counter(soft_fail_res, res);
1347                 if (mem_cgroup_soft_limit_check(mem_over_soft_limit))
1348                         mem_cgroup_update_tree(mem_over_soft_limit, page);
1349         }
1350         return 0;
1351 nomem:
1352         css_put(&mem->css);
1353         return -ENOMEM;
1354 }
1355
1356 /*
1357  * A helper function to get mem_cgroup from ID. must be called under
1358  * rcu_read_lock(). The caller must check css_is_removed() or some if
1359  * it's concern. (dropping refcnt from swap can be called against removed
1360  * memcg.)
1361  */
1362 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
1363 {
1364         struct cgroup_subsys_state *css;
1365
1366         /* ID 0 is unused ID */
1367         if (!id)
1368                 return NULL;
1369         css = css_lookup(&mem_cgroup_subsys, id);
1370         if (!css)
1371                 return NULL;
1372         return container_of(css, struct mem_cgroup, css);
1373 }
1374
1375 static struct mem_cgroup *try_get_mem_cgroup_from_swapcache(struct page *page)
1376 {
1377         struct mem_cgroup *mem;
1378         struct page_cgroup *pc;
1379         unsigned short id;
1380         swp_entry_t ent;
1381
1382         VM_BUG_ON(!PageLocked(page));
1383
1384         if (!PageSwapCache(page))
1385                 return NULL;
1386
1387         pc = lookup_page_cgroup(page);
1388         lock_page_cgroup(pc);
1389         if (PageCgroupUsed(pc)) {
1390                 mem = pc->mem_cgroup;
1391                 if (mem && !css_tryget(&mem->css))
1392                         mem = NULL;
1393         } else {
1394                 ent.val = page_private(page);
1395                 id = lookup_swap_cgroup(ent);
1396                 rcu_read_lock();
1397                 mem = mem_cgroup_lookup(id);
1398                 if (mem && !css_tryget(&mem->css))
1399                         mem = NULL;
1400                 rcu_read_unlock();
1401         }
1402         unlock_page_cgroup(pc);
1403         return mem;
1404 }
1405
1406 /*
1407  * commit a charge got by __mem_cgroup_try_charge() and makes page_cgroup to be
1408  * USED state. If already USED, uncharge and return.
1409  */
1410
1411 static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
1412                                      struct page_cgroup *pc,
1413                                      enum charge_type ctype)
1414 {
1415         /* try_charge() can return NULL to *memcg, taking care of it. */
1416         if (!mem)
1417                 return;
1418
1419         lock_page_cgroup(pc);
1420         if (unlikely(PageCgroupUsed(pc))) {
1421                 unlock_page_cgroup(pc);
1422                 res_counter_uncharge(&mem->res, PAGE_SIZE, NULL);
1423                 if (do_swap_account)
1424                         res_counter_uncharge(&mem->memsw, PAGE_SIZE, NULL);
1425                 css_put(&mem->css);
1426                 return;
1427         }
1428
1429         pc->mem_cgroup = mem;
1430         /*
1431          * We access a page_cgroup asynchronously without lock_page_cgroup().
1432          * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
1433          * is accessed after testing USED bit. To make pc->mem_cgroup visible
1434          * before USED bit, we need memory barrier here.
1435          * See mem_cgroup_add_lru_list(), etc.
1436          */
1437         smp_wmb();
1438         switch (ctype) {
1439         case MEM_CGROUP_CHARGE_TYPE_CACHE:
1440         case MEM_CGROUP_CHARGE_TYPE_SHMEM:
1441                 SetPageCgroupCache(pc);
1442                 SetPageCgroupUsed(pc);
1443                 break;
1444         case MEM_CGROUP_CHARGE_TYPE_MAPPED:
1445                 ClearPageCgroupCache(pc);
1446                 SetPageCgroupUsed(pc);
1447                 break;
1448         default:
1449                 break;
1450         }
1451
1452         mem_cgroup_charge_statistics(mem, pc, true);
1453
1454         unlock_page_cgroup(pc);
1455 }
1456
1457 /**
1458  * mem_cgroup_move_account - move account of the page
1459  * @pc: page_cgroup of the page.
1460  * @from: mem_cgroup which the page is moved from.
1461  * @to: mem_cgroup which the page is moved to. @from != @to.
1462  *
1463  * The caller must confirm following.
1464  * - page is not on LRU (isolate_page() is useful.)
1465  *
1466  * returns 0 at success,
1467  * returns -EBUSY when lock is busy or "pc" is unstable.
1468  *
1469  * This function does "uncharge" from old cgroup but doesn't do "charge" to
1470  * new cgroup. It should be done by a caller.
1471  */
1472
1473 static int mem_cgroup_move_account(struct page_cgroup *pc,
1474         struct mem_cgroup *from, struct mem_cgroup *to)
1475 {
1476         struct mem_cgroup_per_zone *from_mz, *to_mz;
1477         int nid, zid;
1478         int ret = -EBUSY;
1479         struct page *page;
1480         int cpu;
1481         struct mem_cgroup_stat *stat;
1482         struct mem_cgroup_stat_cpu *cpustat;
1483
1484         VM_BUG_ON(from == to);
1485         VM_BUG_ON(PageLRU(pc->page));
1486
1487         nid = page_cgroup_nid(pc);
1488         zid = page_cgroup_zid(pc);
1489         from_mz =  mem_cgroup_zoneinfo(from, nid, zid);
1490         to_mz =  mem_cgroup_zoneinfo(to, nid, zid);
1491
1492         if (!trylock_page_cgroup(pc))
1493                 return ret;
1494
1495         if (!PageCgroupUsed(pc))
1496                 goto out;
1497
1498         if (pc->mem_cgroup != from)
1499                 goto out;
1500
1501         res_counter_uncharge(&from->res, PAGE_SIZE, NULL);
1502         mem_cgroup_charge_statistics(from, pc, false);
1503
1504         page = pc->page;
1505         if (page_is_file_cache(page) && page_mapped(page)) {
1506                 cpu = smp_processor_id();
1507                 /* Update mapped_file data for mem_cgroup "from" */
1508                 stat = &from->stat;
1509                 cpustat = &stat->cpustat[cpu];
1510                 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_MAPPED_FILE,
1511                                                 -1);
1512
1513                 /* Update mapped_file data for mem_cgroup "to" */
1514                 stat = &to->stat;
1515                 cpustat = &stat->cpustat[cpu];
1516                 __mem_cgroup_stat_add_safe(cpustat, MEM_CGROUP_STAT_MAPPED_FILE,
1517                                                 1);
1518         }
1519
1520         if (do_swap_account)
1521                 res_counter_uncharge(&from->memsw, PAGE_SIZE, NULL);
1522         css_put(&from->css);
1523
1524         css_get(&to->css);
1525         pc->mem_cgroup = to;
1526         mem_cgroup_charge_statistics(to, pc, true);
1527         ret = 0;
1528 out:
1529         unlock_page_cgroup(pc);
1530         /*
1531          * We charges against "to" which may not have any tasks. Then, "to"
1532          * can be under rmdir(). But in current implementation, caller of
1533          * this function is just force_empty() and it's garanteed that
1534          * "to" is never removed. So, we don't check rmdir status here.
1535          */
1536         return ret;
1537 }
1538
1539 /*
1540  * move charges to its parent.
1541  */
1542
1543 static int mem_cgroup_move_parent(struct page_cgroup *pc,
1544                                   struct mem_cgroup *child,
1545                                   gfp_t gfp_mask)
1546 {
1547         struct page *page = pc->page;
1548         struct cgroup *cg = child->css.cgroup;
1549         struct cgroup *pcg = cg->parent;
1550         struct mem_cgroup *parent;
1551         int ret;
1552
1553         /* Is ROOT ? */
1554         if (!pcg)
1555                 return -EINVAL;
1556
1557
1558         parent = mem_cgroup_from_cont(pcg);
1559
1560
1561         ret = __mem_cgroup_try_charge(NULL, gfp_mask, &parent, false, page);
1562         if (ret || !parent)
1563                 return ret;
1564
1565         if (!get_page_unless_zero(page)) {
1566                 ret = -EBUSY;
1567                 goto uncharge;
1568         }
1569
1570         ret = isolate_lru_page(page);
1571
1572         if (ret)
1573                 goto cancel;
1574
1575         ret = mem_cgroup_move_account(pc, child, parent);
1576
1577         putback_lru_page(page);
1578         if (!ret) {
1579                 put_page(page);
1580                 /* drop extra refcnt by try_charge() */
1581                 css_put(&parent->css);
1582                 return 0;
1583         }
1584
1585 cancel:
1586         put_page(page);
1587 uncharge:
1588         /* drop extra refcnt by try_charge() */
1589         css_put(&parent->css);
1590         /* uncharge if move fails */
1591         res_counter_uncharge(&parent->res, PAGE_SIZE, NULL);
1592         if (do_swap_account)
1593                 res_counter_uncharge(&parent->memsw, PAGE_SIZE, NULL);
1594         return ret;
1595 }
1596
1597 /*
1598  * Charge the memory controller for page usage.
1599  * Return
1600  * 0 if the charge was successful
1601  * < 0 if the cgroup is over its limit
1602  */
1603 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
1604                                 gfp_t gfp_mask, enum charge_type ctype,
1605                                 struct mem_cgroup *memcg)
1606 {
1607         struct mem_cgroup *mem;
1608         struct page_cgroup *pc;
1609         int ret;
1610
1611         pc = lookup_page_cgroup(page);
1612         /* can happen at boot */
1613         if (unlikely(!pc))
1614                 return 0;
1615         prefetchw(pc);
1616
1617         mem = memcg;
1618         ret = __mem_cgroup_try_charge(mm, gfp_mask, &mem, true, page);
1619         if (ret || !mem)
1620                 return ret;
1621
1622         __mem_cgroup_commit_charge(mem, pc, ctype);
1623         return 0;
1624 }
1625
1626 int mem_cgroup_newpage_charge(struct page *page,
1627                               struct mm_struct *mm, gfp_t gfp_mask)
1628 {
1629         if (mem_cgroup_disabled())
1630                 return 0;
1631         if (PageCompound(page))
1632                 return 0;
1633         /*
1634          * If already mapped, we don't have to account.
1635          * If page cache, page->mapping has address_space.
1636          * But page->mapping may have out-of-use anon_vma pointer,
1637          * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
1638          * is NULL.
1639          */
1640         if (page_mapped(page) || (page->mapping && !PageAnon(page)))
1641                 return 0;
1642         if (unlikely(!mm))
1643                 mm = &init_mm;
1644         return mem_cgroup_charge_common(page, mm, gfp_mask,
1645                                 MEM_CGROUP_CHARGE_TYPE_MAPPED, NULL);
1646 }
1647
1648 static void
1649 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
1650                                         enum charge_type ctype);
1651
1652 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
1653                                 gfp_t gfp_mask)
1654 {
1655         struct mem_cgroup *mem = NULL;
1656         int ret;
1657
1658         if (mem_cgroup_disabled())
1659                 return 0;
1660         if (PageCompound(page))
1661                 return 0;
1662         /*
1663          * Corner case handling. This is called from add_to_page_cache()
1664          * in usual. But some FS (shmem) precharges this page before calling it
1665          * and call add_to_page_cache() with GFP_NOWAIT.
1666          *
1667          * For GFP_NOWAIT case, the page may be pre-charged before calling
1668          * add_to_page_cache(). (See shmem.c) check it here and avoid to call
1669          * charge twice. (It works but has to pay a bit larger cost.)
1670          * And when the page is SwapCache, it should take swap information
1671          * into account. This is under lock_page() now.
1672          */
1673         if (!(gfp_mask & __GFP_WAIT)) {
1674                 struct page_cgroup *pc;
1675
1676
1677                 pc = lookup_page_cgroup(page);
1678                 if (!pc)
1679                         return 0;
1680                 lock_page_cgroup(pc);
1681                 if (PageCgroupUsed(pc)) {
1682                         unlock_page_cgroup(pc);
1683                         return 0;
1684                 }
1685                 unlock_page_cgroup(pc);
1686         }
1687
1688         if (unlikely(!mm && !mem))
1689                 mm = &init_mm;
1690
1691         if (page_is_file_cache(page))
1692                 return mem_cgroup_charge_common(page, mm, gfp_mask,
1693                                 MEM_CGROUP_CHARGE_TYPE_CACHE, NULL);
1694
1695         /* shmem */
1696         if (PageSwapCache(page)) {
1697                 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
1698                 if (!ret)
1699                         __mem_cgroup_commit_charge_swapin(page, mem,
1700                                         MEM_CGROUP_CHARGE_TYPE_SHMEM);
1701         } else
1702                 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
1703                                         MEM_CGROUP_CHARGE_TYPE_SHMEM, mem);
1704
1705         return ret;
1706 }
1707
1708 /*
1709  * While swap-in, try_charge -> commit or cancel, the page is locked.
1710  * And when try_charge() successfully returns, one refcnt to memcg without
1711  * struct page_cgroup is aquired. This refcnt will be cumsumed by
1712  * "commit()" or removed by "cancel()"
1713  */
1714 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
1715                                  struct page *page,
1716                                  gfp_t mask, struct mem_cgroup **ptr)
1717 {
1718         struct mem_cgroup *mem;
1719         int ret;
1720
1721         if (mem_cgroup_disabled())
1722                 return 0;
1723
1724         if (!do_swap_account)
1725                 goto charge_cur_mm;
1726         /*
1727          * A racing thread's fault, or swapoff, may have already updated
1728          * the pte, and even removed page from swap cache: return success
1729          * to go on to do_swap_page()'s pte_same() test, which should fail.
1730          */
1731         if (!PageSwapCache(page))
1732                 return 0;
1733         mem = try_get_mem_cgroup_from_swapcache(page);
1734         if (!mem)
1735                 goto charge_cur_mm;
1736         *ptr = mem;
1737         ret = __mem_cgroup_try_charge(NULL, mask, ptr, true, page);
1738         /* drop extra refcnt from tryget */
1739         css_put(&mem->css);
1740         return ret;
1741 charge_cur_mm:
1742         if (unlikely(!mm))
1743                 mm = &init_mm;
1744         return __mem_cgroup_try_charge(mm, mask, ptr, true, page);
1745 }
1746
1747 static void
1748 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
1749                                         enum charge_type ctype)
1750 {
1751         struct page_cgroup *pc;
1752
1753         if (mem_cgroup_disabled())
1754                 return;
1755         if (!ptr)
1756                 return;
1757         cgroup_exclude_rmdir(&ptr->css);
1758         pc = lookup_page_cgroup(page);
1759         mem_cgroup_lru_del_before_commit_swapcache(page);
1760         __mem_cgroup_commit_charge(ptr, pc, ctype);
1761         mem_cgroup_lru_add_after_commit_swapcache(page);
1762         /*
1763          * Now swap is on-memory. This means this page may be
1764          * counted both as mem and swap....double count.
1765          * Fix it by uncharging from memsw. Basically, this SwapCache is stable
1766          * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
1767          * may call delete_from_swap_cache() before reach here.
1768          */
1769         if (do_swap_account && PageSwapCache(page)) {
1770                 swp_entry_t ent = {.val = page_private(page)};
1771                 unsigned short id;
1772                 struct mem_cgroup *memcg;
1773
1774                 id = swap_cgroup_record(ent, 0);
1775                 rcu_read_lock();
1776                 memcg = mem_cgroup_lookup(id);
1777                 if (memcg) {
1778                         /*
1779                          * This recorded memcg can be obsolete one. So, avoid
1780                          * calling css_tryget
1781                          */
1782                         res_counter_uncharge(&memcg->memsw, PAGE_SIZE, NULL);
1783                         mem_cgroup_put(memcg);
1784                 }
1785                 rcu_read_unlock();
1786         }
1787         /*
1788          * At swapin, we may charge account against cgroup which has no tasks.
1789          * So, rmdir()->pre_destroy() can be called while we do this charge.
1790          * In that case, we need to call pre_destroy() again. check it here.
1791          */
1792         cgroup_release_and_wakeup_rmdir(&ptr->css);
1793 }
1794
1795 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
1796 {
1797         __mem_cgroup_commit_charge_swapin(page, ptr,
1798                                         MEM_CGROUP_CHARGE_TYPE_MAPPED);
1799 }
1800
1801 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
1802 {
1803         if (mem_cgroup_disabled())
1804                 return;
1805         if (!mem)
1806                 return;
1807         res_counter_uncharge(&mem->res, PAGE_SIZE, NULL);
1808         if (do_swap_account)
1809                 res_counter_uncharge(&mem->memsw, PAGE_SIZE, NULL);
1810         css_put(&mem->css);
1811 }
1812
1813
1814 /*
1815  * uncharge if !page_mapped(page)
1816  */
1817 static struct mem_cgroup *
1818 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
1819 {
1820         struct page_cgroup *pc;
1821         struct mem_cgroup *mem = NULL;
1822         struct mem_cgroup_per_zone *mz;
1823         bool soft_limit_excess = false;
1824
1825         if (mem_cgroup_disabled())
1826                 return NULL;
1827
1828         if (PageSwapCache(page))
1829                 return NULL;
1830
1831         /*
1832          * Check if our page_cgroup is valid
1833          */
1834         pc = lookup_page_cgroup(page);
1835         if (unlikely(!pc || !PageCgroupUsed(pc)))
1836                 return NULL;
1837
1838         lock_page_cgroup(pc);
1839
1840         mem = pc->mem_cgroup;
1841
1842         if (!PageCgroupUsed(pc))
1843                 goto unlock_out;
1844
1845         switch (ctype) {
1846         case MEM_CGROUP_CHARGE_TYPE_MAPPED:
1847         case MEM_CGROUP_CHARGE_TYPE_DROP:
1848                 if (page_mapped(page))
1849                         goto unlock_out;
1850                 break;
1851         case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
1852                 if (!PageAnon(page)) {  /* Shared memory */
1853                         if (page->mapping && !page_is_file_cache(page))
1854                                 goto unlock_out;
1855                 } else if (page_mapped(page)) /* Anon */
1856                                 goto unlock_out;
1857                 break;
1858         default:
1859                 break;
1860         }
1861
1862         res_counter_uncharge(&mem->res, PAGE_SIZE, &soft_limit_excess);
1863         if (do_swap_account && (ctype != MEM_CGROUP_CHARGE_TYPE_SWAPOUT))
1864                 res_counter_uncharge(&mem->memsw, PAGE_SIZE, NULL);
1865         mem_cgroup_charge_statistics(mem, pc, false);
1866
1867         ClearPageCgroupUsed(pc);
1868         /*
1869          * pc->mem_cgroup is not cleared here. It will be accessed when it's
1870          * freed from LRU. This is safe because uncharged page is expected not
1871          * to be reused (freed soon). Exception is SwapCache, it's handled by
1872          * special functions.
1873          */
1874
1875         mz = page_cgroup_zoneinfo(pc);
1876         unlock_page_cgroup(pc);
1877
1878         if (soft_limit_excess && mem_cgroup_soft_limit_check(mem))
1879                 mem_cgroup_update_tree(mem, page);
1880         /* at swapout, this memcg will be accessed to record to swap */
1881         if (ctype != MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
1882                 css_put(&mem->css);
1883
1884         return mem;
1885
1886 unlock_out:
1887         unlock_page_cgroup(pc);
1888         return NULL;
1889 }
1890
1891 void mem_cgroup_uncharge_page(struct page *page)
1892 {
1893         /* early check. */
1894         if (page_mapped(page))
1895                 return;
1896         if (page->mapping && !PageAnon(page))
1897                 return;
1898         __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
1899 }
1900
1901 void mem_cgroup_uncharge_cache_page(struct page *page)
1902 {
1903         VM_BUG_ON(page_mapped(page));
1904         VM_BUG_ON(page->mapping);
1905         __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
1906 }
1907
1908 #ifdef CONFIG_SWAP
1909 /*
1910  * called after __delete_from_swap_cache() and drop "page" account.
1911  * memcg information is recorded to swap_cgroup of "ent"
1912  */
1913 void
1914 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
1915 {
1916         struct mem_cgroup *memcg;
1917         int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
1918
1919         if (!swapout) /* this was a swap cache but the swap is unused ! */
1920                 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
1921
1922         memcg = __mem_cgroup_uncharge_common(page, ctype);
1923
1924         /* record memcg information */
1925         if (do_swap_account && swapout && memcg) {
1926                 swap_cgroup_record(ent, css_id(&memcg->css));
1927                 mem_cgroup_get(memcg);
1928         }
1929         if (swapout && memcg)
1930                 css_put(&memcg->css);
1931 }
1932 #endif
1933
1934 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
1935 /*
1936  * called from swap_entry_free(). remove record in swap_cgroup and
1937  * uncharge "memsw" account.
1938  */
1939 void mem_cgroup_uncharge_swap(swp_entry_t ent)
1940 {
1941         struct mem_cgroup *memcg;
1942         unsigned short id;
1943
1944         if (!do_swap_account)
1945                 return;
1946
1947         id = swap_cgroup_record(ent, 0);
1948         rcu_read_lock();
1949         memcg = mem_cgroup_lookup(id);
1950         if (memcg) {
1951                 /*
1952                  * We uncharge this because swap is freed.
1953                  * This memcg can be obsolete one. We avoid calling css_tryget
1954                  */
1955                 res_counter_uncharge(&memcg->memsw, PAGE_SIZE, NULL);
1956                 mem_cgroup_put(memcg);
1957         }
1958         rcu_read_unlock();
1959 }
1960 #endif
1961
1962 /*
1963  * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
1964  * page belongs to.
1965  */
1966 int mem_cgroup_prepare_migration(struct page *page, struct mem_cgroup **ptr)
1967 {
1968         struct page_cgroup *pc;
1969         struct mem_cgroup *mem = NULL;
1970         int ret = 0;
1971
1972         if (mem_cgroup_disabled())
1973                 return 0;
1974
1975         pc = lookup_page_cgroup(page);
1976         lock_page_cgroup(pc);
1977         if (PageCgroupUsed(pc)) {
1978                 mem = pc->mem_cgroup;
1979                 css_get(&mem->css);
1980         }
1981         unlock_page_cgroup(pc);
1982
1983         if (mem) {
1984                 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, &mem, false,
1985                                                 page);
1986                 css_put(&mem->css);
1987         }
1988         *ptr = mem;
1989         return ret;
1990 }
1991
1992 /* remove redundant charge if migration failed*/
1993 void mem_cgroup_end_migration(struct mem_cgroup *mem,
1994                 struct page *oldpage, struct page *newpage)
1995 {
1996         struct page *target, *unused;
1997         struct page_cgroup *pc;
1998         enum charge_type ctype;
1999
2000         if (!mem)
2001                 return;
2002         cgroup_exclude_rmdir(&mem->css);
2003         /* at migration success, oldpage->mapping is NULL. */
2004         if (oldpage->mapping) {
2005                 target = oldpage;
2006                 unused = NULL;
2007         } else {
2008                 target = newpage;
2009                 unused = oldpage;
2010         }
2011
2012         if (PageAnon(target))
2013                 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
2014         else if (page_is_file_cache(target))
2015                 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
2016         else
2017                 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
2018
2019         /* unused page is not on radix-tree now. */
2020         if (unused)
2021                 __mem_cgroup_uncharge_common(unused, ctype);
2022
2023         pc = lookup_page_cgroup(target);
2024         /*
2025          * __mem_cgroup_commit_charge() check PCG_USED bit of page_cgroup.
2026          * So, double-counting is effectively avoided.
2027          */
2028         __mem_cgroup_commit_charge(mem, pc, ctype);
2029
2030         /*
2031          * Both of oldpage and newpage are still under lock_page().
2032          * Then, we don't have to care about race in radix-tree.
2033          * But we have to be careful that this page is unmapped or not.
2034          *
2035          * There is a case for !page_mapped(). At the start of
2036          * migration, oldpage was mapped. But now, it's zapped.
2037          * But we know *target* page is not freed/reused under us.
2038          * mem_cgroup_uncharge_page() does all necessary checks.
2039          */
2040         if (ctype == MEM_CGROUP_CHARGE_TYPE_MAPPED)
2041                 mem_cgroup_uncharge_page(target);
2042         /*
2043          * At migration, we may charge account against cgroup which has no tasks
2044          * So, rmdir()->pre_destroy() can be called while we do this charge.
2045          * In that case, we need to call pre_destroy() again. check it here.
2046          */
2047         cgroup_release_and_wakeup_rmdir(&mem->css);
2048 }
2049
2050 /*
2051  * A call to try to shrink memory usage on charge failure at shmem's swapin.
2052  * Calling hierarchical_reclaim is not enough because we should update
2053  * last_oom_jiffies to prevent pagefault_out_of_memory from invoking global OOM.
2054  * Moreover considering hierarchy, we should reclaim from the mem_over_limit,
2055  * not from the memcg which this page would be charged to.
2056  * try_charge_swapin does all of these works properly.
2057  */
2058 int mem_cgroup_shmem_charge_fallback(struct page *page,
2059                             struct mm_struct *mm,
2060                             gfp_t gfp_mask)
2061 {
2062         struct mem_cgroup *mem = NULL;
2063         int ret;
2064
2065         if (mem_cgroup_disabled())
2066                 return 0;
2067
2068         ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2069         if (!ret)
2070                 mem_cgroup_cancel_charge_swapin(mem); /* it does !mem check */
2071
2072         return ret;
2073 }
2074
2075 static DEFINE_MUTEX(set_limit_mutex);
2076
2077 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
2078                                 unsigned long long val)
2079 {
2080         int retry_count;
2081         int progress;
2082         u64 memswlimit;
2083         int ret = 0;
2084         int children = mem_cgroup_count_children(memcg);
2085         u64 curusage, oldusage;
2086
2087         /*
2088          * For keeping hierarchical_reclaim simple, how long we should retry
2089          * is depends on callers. We set our retry-count to be function
2090          * of # of children which we should visit in this loop.
2091          */
2092         retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
2093
2094         oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2095
2096         while (retry_count) {
2097                 if (signal_pending(current)) {
2098                         ret = -EINTR;
2099                         break;
2100                 }
2101                 /*
2102                  * Rather than hide all in some function, I do this in
2103                  * open coded manner. You see what this really does.
2104                  * We have to guarantee mem->res.limit < mem->memsw.limit.
2105                  */
2106                 mutex_lock(&set_limit_mutex);
2107                 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2108                 if (memswlimit < val) {
2109                         ret = -EINVAL;
2110                         mutex_unlock(&set_limit_mutex);
2111                         break;
2112                 }
2113                 ret = res_counter_set_limit(&memcg->res, val);
2114                 if (!ret) {
2115                         if (memswlimit == val)
2116                                 memcg->memsw_is_minimum = true;
2117                         else
2118                                 memcg->memsw_is_minimum = false;
2119                 }
2120                 mutex_unlock(&set_limit_mutex);
2121
2122                 if (!ret)
2123                         break;
2124
2125                 progress = mem_cgroup_hierarchical_reclaim(memcg, NULL,
2126                                                 GFP_KERNEL,
2127                                                 MEM_CGROUP_RECLAIM_SHRINK);
2128                 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
2129                 /* Usage is reduced ? */
2130                 if (curusage >= oldusage)
2131                         retry_count--;
2132                 else
2133                         oldusage = curusage;
2134         }
2135
2136         return ret;
2137 }
2138
2139 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
2140                                         unsigned long long val)
2141 {
2142         int retry_count;
2143         u64 memlimit, oldusage, curusage;
2144         int children = mem_cgroup_count_children(memcg);
2145         int ret = -EBUSY;
2146
2147         /* see mem_cgroup_resize_res_limit */
2148         retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
2149         oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2150         while (retry_count) {
2151                 if (signal_pending(current)) {
2152                         ret = -EINTR;
2153                         break;
2154                 }
2155                 /*
2156                  * Rather than hide all in some function, I do this in
2157                  * open coded manner. You see what this really does.
2158                  * We have to guarantee mem->res.limit < mem->memsw.limit.
2159                  */
2160                 mutex_lock(&set_limit_mutex);
2161                 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2162                 if (memlimit > val) {
2163                         ret = -EINVAL;
2164                         mutex_unlock(&set_limit_mutex);
2165                         break;
2166                 }
2167                 ret = res_counter_set_limit(&memcg->memsw, val);
2168                 if (!ret) {
2169                         if (memlimit == val)
2170                                 memcg->memsw_is_minimum = true;
2171                         else
2172                                 memcg->memsw_is_minimum = false;
2173                 }
2174                 mutex_unlock(&set_limit_mutex);
2175
2176                 if (!ret)
2177                         break;
2178
2179                 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
2180                                                 MEM_CGROUP_RECLAIM_NOSWAP |
2181                                                 MEM_CGROUP_RECLAIM_SHRINK);
2182                 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
2183                 /* Usage is reduced ? */
2184                 if (curusage >= oldusage)
2185                         retry_count--;
2186                 else
2187                         oldusage = curusage;
2188         }
2189         return ret;
2190 }
2191
2192 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
2193                                                 gfp_t gfp_mask, int nid,
2194                                                 int zid)
2195 {
2196         unsigned long nr_reclaimed = 0;
2197         struct mem_cgroup_per_zone *mz, *next_mz = NULL;
2198         unsigned long reclaimed;
2199         int loop = 0;
2200         struct mem_cgroup_tree_per_zone *mctz;
2201
2202         if (order > 0)
2203                 return 0;
2204
2205         mctz = soft_limit_tree_node_zone(nid, zid);
2206         /*
2207          * This loop can run a while, specially if mem_cgroup's continuously
2208          * keep exceeding their soft limit and putting the system under
2209          * pressure
2210          */
2211         do {
2212                 if (next_mz)
2213                         mz = next_mz;
2214                 else
2215                         mz = mem_cgroup_largest_soft_limit_node(mctz);
2216                 if (!mz)
2217                         break;
2218
2219                 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
2220                                                 gfp_mask,
2221                                                 MEM_CGROUP_RECLAIM_SOFT);
2222                 nr_reclaimed += reclaimed;
2223                 spin_lock(&mctz->lock);
2224
2225                 /*
2226                  * If we failed to reclaim anything from this memory cgroup
2227                  * it is time to move on to the next cgroup
2228                  */
2229                 next_mz = NULL;
2230                 if (!reclaimed) {
2231                         do {
2232                                 /*
2233                                  * Loop until we find yet another one.
2234                                  *
2235                                  * By the time we get the soft_limit lock
2236                                  * again, someone might have aded the
2237                                  * group back on the RB tree. Iterate to
2238                                  * make sure we get a different mem.
2239                                  * mem_cgroup_largest_soft_limit_node returns
2240                                  * NULL if no other cgroup is present on
2241                                  * the tree
2242                                  */
2243                                 next_mz =
2244                                 __mem_cgroup_largest_soft_limit_node(mctz);
2245                                 if (next_mz == mz) {
2246                                         css_put(&next_mz->mem->css);
2247                                         next_mz = NULL;
2248                                 } else /* next_mz == NULL or other memcg */
2249                                         break;
2250                         } while (1);
2251                 }
2252                 mz->usage_in_excess =
2253                         res_counter_soft_limit_excess(&mz->mem->res);
2254                 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
2255                 /*
2256                  * One school of thought says that we should not add
2257                  * back the node to the tree if reclaim returns 0.
2258                  * But our reclaim could return 0, simply because due
2259                  * to priority we are exposing a smaller subset of
2260                  * memory to reclaim from. Consider this as a longer
2261                  * term TODO.
2262                  */
2263                 if (mz->usage_in_excess)
2264                         __mem_cgroup_insert_exceeded(mz->mem, mz, mctz);
2265                 spin_unlock(&mctz->lock);
2266                 css_put(&mz->mem->css);
2267                 loop++;
2268                 /*
2269                  * Could not reclaim anything and there are no more
2270                  * mem cgroups to try or we seem to be looping without
2271                  * reclaiming anything.
2272                  */
2273                 if (!nr_reclaimed &&
2274                         (next_mz == NULL ||
2275                         loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
2276                         break;
2277         } while (!nr_reclaimed);
2278         if (next_mz)
2279                 css_put(&next_mz->mem->css);
2280         return nr_reclaimed;
2281 }
2282
2283 /*
2284  * This routine traverse page_cgroup in given list and drop them all.
2285  * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
2286  */
2287 static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
2288                                 int node, int zid, enum lru_list lru)
2289 {
2290         struct zone *zone;
2291         struct mem_cgroup_per_zone *mz;
2292         struct page_cgroup *pc, *busy;
2293         unsigned long flags, loop;
2294         struct list_head *list;
2295         int ret = 0;
2296
2297         zone = &NODE_DATA(node)->node_zones[zid];
2298         mz = mem_cgroup_zoneinfo(mem, node, zid);
2299         list = &mz->lists[lru];
2300
2301         loop = MEM_CGROUP_ZSTAT(mz, lru);
2302         /* give some margin against EBUSY etc...*/
2303         loop += 256;
2304         busy = NULL;
2305         while (loop--) {
2306                 ret = 0;
2307                 spin_lock_irqsave(&zone->lru_lock, flags);
2308                 if (list_empty(list)) {
2309                         spin_unlock_irqrestore(&zone->lru_lock, flags);
2310                         break;
2311                 }
2312                 pc = list_entry(list->prev, struct page_cgroup, lru);
2313                 if (busy == pc) {
2314                         list_move(&pc->lru, list);
2315                         busy = 0;
2316                         spin_unlock_irqrestore(&zone->lru_lock, flags);
2317                         continue;
2318                 }
2319                 spin_unlock_irqrestore(&zone->lru_lock, flags);
2320
2321                 ret = mem_cgroup_move_parent(pc, mem, GFP_KERNEL);
2322                 if (ret == -ENOMEM)
2323                         break;
2324
2325                 if (ret == -EBUSY || ret == -EINVAL) {
2326                         /* found lock contention or "pc" is obsolete. */
2327                         busy = pc;
2328                         cond_resched();
2329                 } else
2330                         busy = NULL;
2331         }
2332
2333         if (!ret && !list_empty(list))
2334                 return -EBUSY;
2335         return ret;
2336 }
2337
2338 /*
2339  * make mem_cgroup's charge to be 0 if there is no task.
2340  * This enables deleting this mem_cgroup.
2341  */
2342 static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
2343 {
2344         int ret;
2345         int node, zid, shrink;
2346         int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2347         struct cgroup *cgrp = mem->css.cgroup;
2348
2349         css_get(&mem->css);
2350
2351         shrink = 0;
2352         /* should free all ? */
2353         if (free_all)
2354                 goto try_to_free;
2355 move_account:
2356         while (mem->res.usage > 0) {
2357                 ret = -EBUSY;
2358                 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
2359                         goto out;
2360                 ret = -EINTR;
2361                 if (signal_pending(current))
2362                         goto out;
2363                 /* This is for making all *used* pages to be on LRU. */
2364                 lru_add_drain_all();
2365                 ret = 0;
2366                 for_each_node_state(node, N_HIGH_MEMORY) {
2367                         for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
2368                                 enum lru_list l;
2369                                 for_each_lru(l) {
2370                                         ret = mem_cgroup_force_empty_list(mem,
2371                                                         node, zid, l);
2372                                         if (ret)
2373                                                 break;
2374                                 }
2375                         }
2376                         if (ret)
2377                                 break;
2378                 }
2379                 /* it seems parent cgroup doesn't have enough mem */
2380                 if (ret == -ENOMEM)
2381                         goto try_to_free;
2382                 cond_resched();
2383         }
2384         ret = 0;
2385 out:
2386         css_put(&mem->css);
2387         return ret;
2388
2389 try_to_free:
2390         /* returns EBUSY if there is a task or if we come here twice. */
2391         if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
2392                 ret = -EBUSY;
2393                 goto out;
2394         }
2395         /* we call try-to-free pages for make this cgroup empty */
2396         lru_add_drain_all();
2397         /* try to free all pages in this cgroup */
2398         shrink = 1;
2399         while (nr_retries && mem->res.usage > 0) {
2400                 int progress;
2401
2402                 if (signal_pending(current)) {
2403                         ret = -EINTR;
2404                         goto out;
2405                 }
2406                 progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
2407                                                 false, get_swappiness(mem));
2408                 if (!progress) {
2409                         nr_retries--;
2410                         /* maybe some writeback is necessary */
2411                         congestion_wait(BLK_RW_ASYNC, HZ/10);
2412                 }
2413
2414         }
2415         lru_add_drain();
2416         /* try move_account...there may be some *locked* pages. */
2417         if (mem->res.usage)
2418                 goto move_account;
2419         ret = 0;
2420         goto out;
2421 }
2422
2423 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
2424 {
2425         return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
2426 }
2427
2428
2429 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
2430 {
2431         return mem_cgroup_from_cont(cont)->use_hierarchy;
2432 }
2433
2434 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
2435                                         u64 val)
2436 {
2437         int retval = 0;
2438         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2439         struct cgroup *parent = cont->parent;
2440         struct mem_cgroup *parent_mem = NULL;
2441
2442         if (parent)
2443                 parent_mem = mem_cgroup_from_cont(parent);
2444
2445         cgroup_lock();
2446         /*
2447          * If parent's use_hiearchy is set, we can't make any modifications
2448          * in the child subtrees. If it is unset, then the change can
2449          * occur, provided the current cgroup has no children.
2450          *
2451          * For the root cgroup, parent_mem is NULL, we allow value to be
2452          * set if there are no children.
2453          */
2454         if ((!parent_mem || !parent_mem->use_hierarchy) &&
2455                                 (val == 1 || val == 0)) {
2456                 if (list_empty(&cont->children))
2457                         mem->use_hierarchy = val;
2458                 else
2459                         retval = -EBUSY;
2460         } else
2461                 retval = -EINVAL;
2462         cgroup_unlock();
2463
2464         return retval;
2465 }
2466
2467 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
2468 {
2469         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
2470         u64 val = 0;
2471         int type, name;
2472
2473         type = MEMFILE_TYPE(cft->private);
2474         name = MEMFILE_ATTR(cft->private);
2475         switch (type) {
2476         case _MEM:
2477                 val = res_counter_read_u64(&mem->res, name);
2478                 break;
2479         case _MEMSWAP:
2480                 val = res_counter_read_u64(&mem->memsw, name);
2481                 break;
2482         default:
2483                 BUG();
2484                 break;
2485         }
2486         return val;
2487 }
2488 /*
2489  * The user of this function is...
2490  * RES_LIMIT.
2491  */
2492 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
2493                             const char *buffer)
2494 {
2495         struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
2496         int type, name;
2497         unsigned long long val;
2498         int ret;
2499
2500         type = MEMFILE_TYPE(cft->private);
2501         name = MEMFILE_ATTR(cft->private);
2502         switch (name) {
2503         case RES_LIMIT:
2504                 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
2505                         ret = -EINVAL;
2506                         break;
2507                 }
2508                 /* This function does all necessary parse...reuse it */
2509                 ret = res_counter_memparse_write_strategy(buffer, &val);
2510                 if (ret)
2511                         break;
2512                 if (type == _MEM)
2513                         ret = mem_cgroup_resize_limit(memcg, val);
2514                 else
2515                         ret = mem_cgroup_resize_memsw_limit(memcg, val);
2516                 break;
2517         case RES_SOFT_LIMIT:
2518                 ret = res_counter_memparse_write_strategy(buffer, &val);
2519                 if (ret)
2520                         break;
2521                 /*
2522                  * For memsw, soft limits are hard to implement in terms
2523                  * of semantics, for now, we support soft limits for
2524                  * control without swap
2525                  */
2526                 if (type == _MEM)
2527                         ret = res_counter_set_soft_limit(&memcg->res, val);
2528                 else
2529                         ret = -EINVAL;
2530                 break;
2531         default:
2532                 ret = -EINVAL; /* should be BUG() ? */
2533                 break;
2534         }
2535         return ret;
2536 }
2537
2538 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
2539                 unsigned long long *mem_limit, unsigned long long *memsw_limit)
2540 {
2541         struct cgroup *cgroup;
2542         unsigned long long min_limit, min_memsw_limit, tmp;
2543
2544         min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
2545         min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2546         cgroup = memcg->css.cgroup;
2547         if (!memcg->use_hierarchy)
2548                 goto out;
2549
2550         while (cgroup->parent) {
2551                 cgroup = cgroup->parent;
2552                 memcg = mem_cgroup_from_cont(cgroup);
2553                 if (!memcg->use_hierarchy)
2554                         break;
2555                 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
2556                 min_limit = min(min_limit, tmp);
2557                 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
2558                 min_memsw_limit = min(min_memsw_limit, tmp);
2559         }
2560 out:
2561         *mem_limit = min_limit;
2562         *memsw_limit = min_memsw_limit;
2563         return;
2564 }
2565
2566 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
2567 {
2568         struct mem_cgroup *mem;
2569         int type, name;
2570
2571         mem = mem_cgroup_from_cont(cont);
2572         type = MEMFILE_TYPE(event);
2573         name = MEMFILE_ATTR(event);
2574         switch (name) {
2575         case RES_MAX_USAGE:
2576                 if (type == _MEM)
2577                         res_counter_reset_max(&mem->res);
2578                 else
2579                         res_counter_reset_max(&mem->memsw);
2580                 break;
2581         case RES_FAILCNT:
2582                 if (type == _MEM)
2583                         res_counter_reset_failcnt(&mem->res);
2584                 else
2585                         res_counter_reset_failcnt(&mem->memsw);
2586                 break;
2587         }
2588
2589         return 0;
2590 }
2591
2592
2593 /* For read statistics */
2594 enum {
2595         MCS_CACHE,
2596         MCS_RSS,
2597         MCS_MAPPED_FILE,
2598         MCS_PGPGIN,
2599         MCS_PGPGOUT,
2600         MCS_INACTIVE_ANON,
2601         MCS_ACTIVE_ANON,
2602         MCS_INACTIVE_FILE,
2603         MCS_ACTIVE_FILE,
2604         MCS_UNEVICTABLE,
2605         NR_MCS_STAT,
2606 };
2607
2608 struct mcs_total_stat {
2609         s64 stat[NR_MCS_STAT];
2610 };
2611
2612 struct {
2613         char *local_name;
2614         char *total_name;
2615 } memcg_stat_strings[NR_MCS_STAT] = {
2616         {"cache", "total_cache"},
2617         {"rss", "total_rss"},
2618         {"mapped_file", "total_mapped_file"},
2619         {"pgpgin", "total_pgpgin"},
2620         {"pgpgout", "total_pgpgout"},
2621         {"inactive_anon", "total_inactive_anon"},
2622         {"active_anon", "total_active_anon"},
2623         {"inactive_file", "total_inactive_file"},
2624         {"active_file", "total_active_file"},
2625         {"unevictable", "total_unevictable"}
2626 };
2627
2628
2629 static int mem_cgroup_get_local_stat(struct mem_cgroup *mem, void *data)
2630 {
2631         struct mcs_total_stat *s = data;
2632         s64 val;
2633
2634         /* per cpu stat */
2635         val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_CACHE);
2636         s->stat[MCS_CACHE] += val * PAGE_SIZE;
2637         val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_RSS);
2638         s->stat[MCS_RSS] += val * PAGE_SIZE;
2639         val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_MAPPED_FILE);
2640         s->stat[MCS_MAPPED_FILE] += val * PAGE_SIZE;
2641         val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGIN_COUNT);
2642         s->stat[MCS_PGPGIN] += val;
2643         val = mem_cgroup_read_stat(&mem->stat, MEM_CGROUP_STAT_PGPGOUT_COUNT);
2644         s->stat[MCS_PGPGOUT] += val;
2645
2646         /* per zone stat */
2647         val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_ANON);
2648         s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
2649         val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_ANON);
2650         s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
2651         val = mem_cgroup_get_local_zonestat(mem, LRU_INACTIVE_FILE);
2652         s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
2653         val = mem_cgroup_get_local_zonestat(mem, LRU_ACTIVE_FILE);
2654         s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
2655         val = mem_cgroup_get_local_zonestat(mem, LRU_UNEVICTABLE);
2656         s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
2657         return 0;
2658 }
2659
2660 static void
2661 mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
2662 {
2663         mem_cgroup_walk_tree(mem, s, mem_cgroup_get_local_stat);
2664 }
2665
2666 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
2667                                  struct cgroup_map_cb *cb)
2668 {
2669         struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
2670         struct mcs_total_stat mystat;
2671         int i;
2672
2673         memset(&mystat, 0, sizeof(mystat));
2674         mem_cgroup_get_local_stat(mem_cont, &mystat);
2675
2676         for (i = 0; i < NR_MCS_STAT; i++)
2677                 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
2678
2679         /* Hierarchical information */
2680         {
2681                 unsigned long long limit, memsw_limit;
2682                 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
2683                 cb->fill(cb, "hierarchical_memory_limit", limit);
2684                 if (do_swap_account)
2685                         cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
2686         }
2687
2688         memset(&mystat, 0, sizeof(mystat));
2689         mem_cgroup_get_total_stat(mem_cont, &mystat);
2690         for (i = 0; i < NR_MCS_STAT; i++)
2691                 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
2692
2693
2694 #ifdef CONFIG_DEBUG_VM
2695         cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
2696
2697         {
2698                 int nid, zid;
2699                 struct mem_cgroup_per_zone *mz;
2700                 unsigned long recent_rotated[2] = {0, 0};
2701                 unsigned long recent_scanned[2] = {0, 0};
2702
2703                 for_each_online_node(nid)
2704                         for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2705                                 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
2706
2707                                 recent_rotated[0] +=
2708                                         mz->reclaim_stat.recent_rotated[0];
2709                                 recent_rotated[1] +=
2710                                         mz->reclaim_stat.recent_rotated[1];
2711                                 recent_scanned[0] +=
2712                                         mz->reclaim_stat.recent_scanned[0];
2713                                 recent_scanned[1] +=
2714                                         mz->reclaim_stat.recent_scanned[1];
2715                         }
2716                 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
2717                 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
2718                 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
2719                 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
2720         }
2721 #endif
2722
2723         return 0;
2724 }
2725
2726 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
2727 {
2728         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
2729
2730         return get_swappiness(memcg);
2731 }
2732
2733 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
2734                                        u64 val)
2735 {
2736         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
2737         struct mem_cgroup *parent;
2738
2739         if (val > 100)
2740                 return -EINVAL;
2741
2742         if (cgrp->parent == NULL)
2743                 return -EINVAL;
2744
2745         parent = mem_cgroup_from_cont(cgrp->parent);
2746
2747         cgroup_lock();
2748
2749         /* If under hierarchy, only empty-root can set this value */
2750         if ((parent->use_hierarchy) ||
2751             (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
2752                 cgroup_unlock();
2753                 return -EINVAL;
2754         }
2755
2756         spin_lock(&memcg->reclaim_param_lock);
2757         memcg->swappiness = val;
2758         spin_unlock(&memcg->reclaim_param_lock);
2759
2760         cgroup_unlock();
2761
2762         return 0;
2763 }
2764
2765
2766 static struct cftype mem_cgroup_files[] = {
2767         {
2768                 .name = "usage_in_bytes",
2769                 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
2770                 .read_u64 = mem_cgroup_read,
2771         },
2772         {
2773                 .name = "max_usage_in_bytes",
2774                 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
2775                 .trigger = mem_cgroup_reset,
2776                 .read_u64 = mem_cgroup_read,
2777         },
2778         {
2779                 .name = "limit_in_bytes",
2780                 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
2781                 .write_string = mem_cgroup_write,
2782                 .read_u64 = mem_cgroup_read,
2783         },
2784         {
2785                 .name = "soft_limit_in_bytes",
2786                 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
2787                 .write_string = mem_cgroup_write,
2788                 .read_u64 = mem_cgroup_read,
2789         },
2790         {
2791                 .name = "failcnt",
2792                 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
2793                 .trigger = mem_cgroup_reset,
2794                 .read_u64 = mem_cgroup_read,
2795         },
2796         {
2797                 .name = "stat",
2798                 .read_map = mem_control_stat_show,
2799         },
2800         {
2801                 .name = "force_empty",
2802                 .trigger = mem_cgroup_force_empty_write,
2803         },
2804         {
2805                 .name = "use_hierarchy",
2806                 .write_u64 = mem_cgroup_hierarchy_write,
2807                 .read_u64 = mem_cgroup_hierarchy_read,
2808         },
2809         {
2810                 .name = "swappiness",
2811                 .read_u64 = mem_cgroup_swappiness_read,
2812                 .write_u64 = mem_cgroup_swappiness_write,
2813         },
2814 };
2815
2816 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2817 static struct cftype memsw_cgroup_files[] = {
2818         {
2819                 .name = "memsw.usage_in_bytes",
2820                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
2821                 .read_u64 = mem_cgroup_read,
2822         },
2823         {
2824                 .name = "memsw.max_usage_in_bytes",
2825                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
2826                 .trigger = mem_cgroup_reset,
2827                 .read_u64 = mem_cgroup_read,
2828         },
2829         {
2830                 .name = "memsw.limit_in_bytes",
2831                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
2832                 .write_string = mem_cgroup_write,
2833                 .read_u64 = mem_cgroup_read,
2834         },
2835         {
2836                 .name = "memsw.failcnt",
2837                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
2838                 .trigger = mem_cgroup_reset,
2839                 .read_u64 = mem_cgroup_read,
2840         },
2841 };
2842
2843 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
2844 {
2845         if (!do_swap_account)
2846                 return 0;
2847         return cgroup_add_files(cont, ss, memsw_cgroup_files,
2848                                 ARRAY_SIZE(memsw_cgroup_files));
2849 };
2850 #else
2851 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
2852 {
2853         return 0;
2854 }
2855 #endif
2856
2857 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
2858 {
2859         struct mem_cgroup_per_node *pn;
2860         struct mem_cgroup_per_zone *mz;
2861         enum lru_list l;
2862         int zone, tmp = node;
2863         /*
2864          * This routine is called against possible nodes.
2865          * But it's BUG to call kmalloc() against offline node.
2866          *
2867          * TODO: this routine can waste much memory for nodes which will
2868          *       never be onlined. It's better to use memory hotplug callback
2869          *       function.
2870          */
2871         if (!node_state(node, N_NORMAL_MEMORY))
2872                 tmp = -1;
2873         pn = kmalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
2874         if (!pn)
2875                 return 1;
2876
2877         mem->info.nodeinfo[node] = pn;
2878         memset(pn, 0, sizeof(*pn));
2879
2880         for (zone = 0; zone < MAX_NR_ZONES; zone++) {
2881                 mz = &pn->zoneinfo[zone];
2882                 for_each_lru(l)
2883                         INIT_LIST_HEAD(&mz->lists[l]);
2884                 mz->usage_in_excess = 0;
2885                 mz->on_tree = false;
2886                 mz->mem = mem;
2887         }
2888         return 0;
2889 }
2890
2891 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
2892 {
2893         kfree(mem->info.nodeinfo[node]);
2894 }
2895
2896 static int mem_cgroup_size(void)
2897 {
2898         int cpustat_size = nr_cpu_ids * sizeof(struct mem_cgroup_stat_cpu);
2899         return sizeof(struct mem_cgroup) + cpustat_size;
2900 }
2901
2902 static struct mem_cgroup *mem_cgroup_alloc(void)
2903 {
2904         struct mem_cgroup *mem;
2905         int size = mem_cgroup_size();
2906
2907         if (size < PAGE_SIZE)
2908                 mem = kmalloc(size, GFP_KERNEL);
2909         else
2910                 mem = vmalloc(size);
2911
2912         if (mem)
2913                 memset(mem, 0, size);
2914         return mem;
2915 }
2916
2917 /*
2918  * At destroying mem_cgroup, references from swap_cgroup can remain.
2919  * (scanning all at force_empty is too costly...)
2920  *
2921  * Instead of clearing all references at force_empty, we remember
2922  * the number of reference from swap_cgroup and free mem_cgroup when
2923  * it goes down to 0.
2924  *
2925  * Removal of cgroup itself succeeds regardless of refs from swap.
2926  */
2927
2928 static void __mem_cgroup_free(struct mem_cgroup *mem)
2929 {
2930         int node;
2931
2932         mem_cgroup_remove_from_trees(mem);
2933         free_css_id(&mem_cgroup_subsys, &mem->css);
2934
2935         for_each_node_state(node, N_POSSIBLE)
2936                 free_mem_cgroup_per_zone_info(mem, node);
2937
2938         if (mem_cgroup_size() < PAGE_SIZE)
2939                 kfree(mem);
2940         else
2941                 vfree(mem);
2942 }
2943
2944 static void mem_cgroup_get(struct mem_cgroup *mem)
2945 {
2946         atomic_inc(&mem->refcnt);
2947 }
2948
2949 static void mem_cgroup_put(struct mem_cgroup *mem)
2950 {
2951         if (atomic_dec_and_test(&mem->refcnt)) {
2952                 struct mem_cgroup *parent = parent_mem_cgroup(mem);
2953                 __mem_cgroup_free(mem);
2954                 if (parent)
2955                         mem_cgroup_put(parent);
2956         }
2957 }
2958
2959 /*
2960  * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
2961  */
2962 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
2963 {
2964         if (!mem->res.parent)
2965                 return NULL;
2966         return mem_cgroup_from_res_counter(mem->res.parent, res);
2967 }
2968
2969 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
2970 static void __init enable_swap_cgroup(void)
2971 {
2972         if (!mem_cgroup_disabled() && really_do_swap_account)
2973                 do_swap_account = 1;
2974 }
2975 #else
2976 static void __init enable_swap_cgroup(void)
2977 {
2978 }
2979 #endif
2980
2981 static int mem_cgroup_soft_limit_tree_init(void)
2982 {
2983         struct mem_cgroup_tree_per_node *rtpn;
2984         struct mem_cgroup_tree_per_zone *rtpz;
2985         int tmp, node, zone;
2986
2987         for_each_node_state(node, N_POSSIBLE) {
2988                 tmp = node;
2989                 if (!node_state(node, N_NORMAL_MEMORY))
2990                         tmp = -1;
2991                 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
2992                 if (!rtpn)
2993                         return 1;
2994
2995                 soft_limit_tree.rb_tree_per_node[node] = rtpn;
2996
2997                 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
2998                         rtpz = &rtpn->rb_tree_per_zone[zone];
2999                         rtpz->rb_root = RB_ROOT;
3000                         spin_lock_init(&rtpz->lock);
3001                 }
3002         }
3003         return 0;
3004 }
3005
3006 static struct cgroup_subsys_state * __ref
3007 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
3008 {
3009         struct mem_cgroup *mem, *parent;
3010         long error = -ENOMEM;
3011         int node;
3012
3013         mem = mem_cgroup_alloc();
3014         if (!mem)
3015                 return ERR_PTR(error);
3016
3017         for_each_node_state(node, N_POSSIBLE)
3018                 if (alloc_mem_cgroup_per_zone_info(mem, node))
3019                         goto free_out;
3020
3021         /* root ? */
3022         if (cont->parent == NULL) {
3023                 enable_swap_cgroup();
3024                 parent = NULL;
3025                 root_mem_cgroup = mem;
3026                 if (mem_cgroup_soft_limit_tree_init())
3027                         goto free_out;
3028
3029         } else {
3030                 parent = mem_cgroup_from_cont(cont->parent);
3031                 mem->use_hierarchy = parent->use_hierarchy;
3032         }
3033
3034         if (parent && parent->use_hierarchy) {
3035                 res_counter_init(&mem->res, &parent->res);
3036                 res_counter_init(&mem->memsw, &parent->memsw);
3037                 /*
3038                  * We increment refcnt of the parent to ensure that we can
3039                  * safely access it on res_counter_charge/uncharge.
3040                  * This refcnt will be decremented when freeing this
3041                  * mem_cgroup(see mem_cgroup_put).
3042                  */
3043                 mem_cgroup_get(parent);
3044         } else {
3045                 res_counter_init(&mem->res, NULL);
3046                 res_counter_init(&mem->memsw, NULL);
3047         }
3048         mem->last_scanned_child = 0;
3049         spin_lock_init(&mem->reclaim_param_lock);
3050
3051         if (parent)
3052                 mem->swappiness = get_swappiness(parent);
3053         atomic_set(&mem->refcnt, 1);
3054         return &mem->css;
3055 free_out:
3056         __mem_cgroup_free(mem);
3057         root_mem_cgroup = NULL;
3058         return ERR_PTR(error);
3059 }
3060
3061 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
3062                                         struct cgroup *cont)
3063 {
3064         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3065
3066         return mem_cgroup_force_empty(mem, false);
3067 }
3068
3069 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
3070                                 struct cgroup *cont)
3071 {
3072         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3073
3074         mem_cgroup_put(mem);
3075 }
3076
3077 static int mem_cgroup_populate(struct cgroup_subsys *ss,
3078                                 struct cgroup *cont)
3079 {
3080         int ret;
3081
3082         ret = cgroup_add_files(cont, ss, mem_cgroup_files,
3083                                 ARRAY_SIZE(mem_cgroup_files));
3084
3085         if (!ret)
3086                 ret = register_memsw_files(cont, ss);
3087         return ret;
3088 }
3089
3090 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
3091                                 struct cgroup *cont,
3092                                 struct cgroup *old_cont,
3093                                 struct task_struct *p,
3094                                 bool threadgroup)
3095 {
3096         mutex_lock(&memcg_tasklist);
3097         /*
3098          * FIXME: It's better to move charges of this process from old
3099          * memcg to new memcg. But it's just on TODO-List now.
3100          */
3101         mutex_unlock(&memcg_tasklist);
3102 }
3103
3104 struct cgroup_subsys mem_cgroup_subsys = {
3105         .name = "memory",
3106         .subsys_id = mem_cgroup_subsys_id,
3107         .create = mem_cgroup_create,
3108         .pre_destroy = mem_cgroup_pre_destroy,
3109         .destroy = mem_cgroup_destroy,
3110         .populate = mem_cgroup_populate,
3111         .attach = mem_cgroup_move_task,
3112         .early_init = 0,
3113         .use_id = 1,
3114 };
3115
3116 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3117
3118 static int __init disable_swap_account(char *s)
3119 {
3120         really_do_swap_account = 0;
3121         return 1;
3122 }
3123 __setup("noswapaccount", disable_swap_account);
3124 #endif