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