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