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