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