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