memcg: pin execution to current cpu while draining stock
[pandora-kernel.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 <linux/oom.h>
51 #include "internal.h"
52
53 #include <asm/uaccess.h>
54
55 #include <trace/events/vmscan.h>
56
57 struct cgroup_subsys mem_cgroup_subsys __read_mostly;
58 #define MEM_CGROUP_RECLAIM_RETRIES      5
59 struct mem_cgroup *root_mem_cgroup __read_mostly;
60
61 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
62 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
63 int do_swap_account __read_mostly;
64
65 /* for remember boot option*/
66 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP_ENABLED
67 static int really_do_swap_account __initdata = 1;
68 #else
69 static int really_do_swap_account __initdata = 0;
70 #endif
71
72 #else
73 #define do_swap_account         (0)
74 #endif
75
76
77 /*
78  * Statistics for memory cgroup.
79  */
80 enum mem_cgroup_stat_index {
81         /*
82          * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
83          */
84         MEM_CGROUP_STAT_CACHE,     /* # of pages charged as cache */
85         MEM_CGROUP_STAT_RSS,       /* # of pages charged as anon rss */
86         MEM_CGROUP_STAT_FILE_MAPPED,  /* # of pages charged as file rss */
87         MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */
88         MEM_CGROUP_STAT_DATA, /* end of data requires synchronization */
89         MEM_CGROUP_ON_MOVE,     /* someone is moving account between groups */
90         MEM_CGROUP_STAT_NSTATS,
91 };
92
93 enum mem_cgroup_events_index {
94         MEM_CGROUP_EVENTS_PGPGIN,       /* # of pages paged in */
95         MEM_CGROUP_EVENTS_PGPGOUT,      /* # of pages paged out */
96         MEM_CGROUP_EVENTS_COUNT,        /* # of pages paged in/out */
97         MEM_CGROUP_EVENTS_PGFAULT,      /* # of page-faults */
98         MEM_CGROUP_EVENTS_PGMAJFAULT,   /* # of major page-faults */
99         MEM_CGROUP_EVENTS_NSTATS,
100 };
101 /*
102  * Per memcg event counter is incremented at every pagein/pageout. With THP,
103  * it will be incremated by the number of pages. This counter is used for
104  * for trigger some periodic events. This is straightforward and better
105  * than using jiffies etc. to handle periodic memcg event.
106  */
107 enum mem_cgroup_events_target {
108         MEM_CGROUP_TARGET_THRESH,
109         MEM_CGROUP_TARGET_SOFTLIMIT,
110         MEM_CGROUP_TARGET_NUMAINFO,
111         MEM_CGROUP_NTARGETS,
112 };
113 #define THRESHOLDS_EVENTS_TARGET (128)
114 #define SOFTLIMIT_EVENTS_TARGET (1024)
115 #define NUMAINFO_EVENTS_TARGET  (1024)
116
117 struct mem_cgroup_stat_cpu {
118         long count[MEM_CGROUP_STAT_NSTATS];
119         unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
120         unsigned long targets[MEM_CGROUP_NTARGETS];
121 };
122
123 /*
124  * per-zone information in memory controller.
125  */
126 struct mem_cgroup_per_zone {
127         /*
128          * spin_lock to protect the per cgroup LRU
129          */
130         struct list_head        lists[NR_LRU_LISTS];
131         unsigned long           count[NR_LRU_LISTS];
132
133         struct zone_reclaim_stat reclaim_stat;
134         struct rb_node          tree_node;      /* RB tree node */
135         unsigned long long      usage_in_excess;/* Set to the value by which */
136                                                 /* the soft limit is exceeded*/
137         bool                    on_tree;
138         struct mem_cgroup       *mem;           /* Back pointer, we cannot */
139                                                 /* use container_of        */
140 };
141 /* Macro for accessing counter */
142 #define MEM_CGROUP_ZSTAT(mz, idx)       ((mz)->count[(idx)])
143
144 struct mem_cgroup_per_node {
145         struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
146 };
147
148 struct mem_cgroup_lru_info {
149         struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES];
150 };
151
152 /*
153  * Cgroups above their limits are maintained in a RB-Tree, independent of
154  * their hierarchy representation
155  */
156
157 struct mem_cgroup_tree_per_zone {
158         struct rb_root rb_root;
159         spinlock_t lock;
160 };
161
162 struct mem_cgroup_tree_per_node {
163         struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
164 };
165
166 struct mem_cgroup_tree {
167         struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
168 };
169
170 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
171
172 struct mem_cgroup_threshold {
173         struct eventfd_ctx *eventfd;
174         u64 threshold;
175 };
176
177 /* For threshold */
178 struct mem_cgroup_threshold_ary {
179         /* An array index points to threshold just below usage. */
180         int current_threshold;
181         /* Size of entries[] */
182         unsigned int size;
183         /* Array of thresholds */
184         struct mem_cgroup_threshold entries[0];
185 };
186
187 struct mem_cgroup_thresholds {
188         /* Primary thresholds array */
189         struct mem_cgroup_threshold_ary *primary;
190         /*
191          * Spare threshold array.
192          * This is needed to make mem_cgroup_unregister_event() "never fail".
193          * It must be able to store at least primary->size - 1 entries.
194          */
195         struct mem_cgroup_threshold_ary *spare;
196 };
197
198 /* for OOM */
199 struct mem_cgroup_eventfd_list {
200         struct list_head list;
201         struct eventfd_ctx *eventfd;
202 };
203
204 static void mem_cgroup_threshold(struct mem_cgroup *mem);
205 static void mem_cgroup_oom_notify(struct mem_cgroup *mem);
206
207 enum {
208         SCAN_BY_LIMIT,
209         SCAN_BY_SYSTEM,
210         NR_SCAN_CONTEXT,
211         SCAN_BY_SHRINK, /* not recorded now */
212 };
213
214 enum {
215         SCAN,
216         SCAN_ANON,
217         SCAN_FILE,
218         ROTATE,
219         ROTATE_ANON,
220         ROTATE_FILE,
221         FREED,
222         FREED_ANON,
223         FREED_FILE,
224         ELAPSED,
225         NR_SCANSTATS,
226 };
227
228 struct scanstat {
229         spinlock_t      lock;
230         unsigned long   stats[NR_SCAN_CONTEXT][NR_SCANSTATS];
231         unsigned long   rootstats[NR_SCAN_CONTEXT][NR_SCANSTATS];
232 };
233
234 const char *scanstat_string[NR_SCANSTATS] = {
235         "scanned_pages",
236         "scanned_anon_pages",
237         "scanned_file_pages",
238         "rotated_pages",
239         "rotated_anon_pages",
240         "rotated_file_pages",
241         "freed_pages",
242         "freed_anon_pages",
243         "freed_file_pages",
244         "elapsed_ns",
245 };
246 #define SCANSTAT_WORD_LIMIT     "_by_limit"
247 #define SCANSTAT_WORD_SYSTEM    "_by_system"
248 #define SCANSTAT_WORD_HIERARCHY "_under_hierarchy"
249
250
251 /*
252  * The memory controller data structure. The memory controller controls both
253  * page cache and RSS per cgroup. We would eventually like to provide
254  * statistics based on the statistics developed by Rik Van Riel for clock-pro,
255  * to help the administrator determine what knobs to tune.
256  *
257  * TODO: Add a water mark for the memory controller. Reclaim will begin when
258  * we hit the water mark. May be even add a low water mark, such that
259  * no reclaim occurs from a cgroup at it's low water mark, this is
260  * a feature that will be implemented much later in the future.
261  */
262 struct mem_cgroup {
263         struct cgroup_subsys_state css;
264         /*
265          * the counter to account for memory usage
266          */
267         struct res_counter res;
268         /*
269          * the counter to account for mem+swap usage.
270          */
271         struct res_counter memsw;
272         /*
273          * Per cgroup active and inactive list, similar to the
274          * per zone LRU lists.
275          */
276         struct mem_cgroup_lru_info info;
277         /*
278          * While reclaiming in a hierarchy, we cache the last child we
279          * reclaimed from.
280          */
281         int last_scanned_child;
282         int last_scanned_node;
283 #if MAX_NUMNODES > 1
284         nodemask_t      scan_nodes;
285         atomic_t        numainfo_events;
286         atomic_t        numainfo_updating;
287 #endif
288         /*
289          * Should the accounting and control be hierarchical, per subtree?
290          */
291         bool use_hierarchy;
292
293         bool            oom_lock;
294         atomic_t        under_oom;
295
296         atomic_t        refcnt;
297
298         int     swappiness;
299         /* OOM-Killer disable */
300         int             oom_kill_disable;
301
302         /* set when res.limit == memsw.limit */
303         bool            memsw_is_minimum;
304
305         /* protect arrays of thresholds */
306         struct mutex thresholds_lock;
307
308         /* thresholds for memory usage. RCU-protected */
309         struct mem_cgroup_thresholds thresholds;
310
311         /* thresholds for mem+swap usage. RCU-protected */
312         struct mem_cgroup_thresholds memsw_thresholds;
313
314         /* For oom notifier event fd */
315         struct list_head oom_notify;
316         /* For recording LRU-scan statistics */
317         struct scanstat scanstat;
318         /*
319          * Should we move charges of a task when a task is moved into this
320          * mem_cgroup ? And what type of charges should we move ?
321          */
322         unsigned long   move_charge_at_immigrate;
323         /*
324          * percpu counter.
325          */
326         struct mem_cgroup_stat_cpu *stat;
327         /*
328          * used when a cpu is offlined or other synchronizations
329          * See mem_cgroup_read_stat().
330          */
331         struct mem_cgroup_stat_cpu nocpu_base;
332         spinlock_t pcp_counter_lock;
333 };
334
335 /* Stuffs for move charges at task migration. */
336 /*
337  * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a
338  * left-shifted bitmap of these types.
339  */
340 enum move_type {
341         MOVE_CHARGE_TYPE_ANON,  /* private anonymous page and swap of it */
342         MOVE_CHARGE_TYPE_FILE,  /* file page(including tmpfs) and swap of it */
343         NR_MOVE_TYPE,
344 };
345
346 /* "mc" and its members are protected by cgroup_mutex */
347 static struct move_charge_struct {
348         spinlock_t        lock; /* for from, to */
349         struct mem_cgroup *from;
350         struct mem_cgroup *to;
351         unsigned long precharge;
352         unsigned long moved_charge;
353         unsigned long moved_swap;
354         struct task_struct *moving_task;        /* a task moving charges */
355         wait_queue_head_t waitq;                /* a waitq for other context */
356 } mc = {
357         .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
358         .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
359 };
360
361 static bool move_anon(void)
362 {
363         return test_bit(MOVE_CHARGE_TYPE_ANON,
364                                         &mc.to->move_charge_at_immigrate);
365 }
366
367 static bool move_file(void)
368 {
369         return test_bit(MOVE_CHARGE_TYPE_FILE,
370                                         &mc.to->move_charge_at_immigrate);
371 }
372
373 /*
374  * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
375  * limit reclaim to prevent infinite loops, if they ever occur.
376  */
377 #define MEM_CGROUP_MAX_RECLAIM_LOOPS            (100)
378 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2)
379
380 enum charge_type {
381         MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
382         MEM_CGROUP_CHARGE_TYPE_MAPPED,
383         MEM_CGROUP_CHARGE_TYPE_SHMEM,   /* used by page migration of shmem */
384         MEM_CGROUP_CHARGE_TYPE_FORCE,   /* used by force_empty */
385         MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
386         MEM_CGROUP_CHARGE_TYPE_DROP,    /* a page was unused swap cache */
387         NR_CHARGE_TYPE,
388 };
389
390 /* for encoding cft->private value on file */
391 #define _MEM                    (0)
392 #define _MEMSWAP                (1)
393 #define _OOM_TYPE               (2)
394 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val))
395 #define MEMFILE_TYPE(val)       (((val) >> 16) & 0xffff)
396 #define MEMFILE_ATTR(val)       ((val) & 0xffff)
397 /* Used for OOM nofiier */
398 #define OOM_CONTROL             (0)
399
400 /*
401  * Reclaim flags for mem_cgroup_hierarchical_reclaim
402  */
403 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT   0x0
404 #define MEM_CGROUP_RECLAIM_NOSWAP       (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
405 #define MEM_CGROUP_RECLAIM_SHRINK_BIT   0x1
406 #define MEM_CGROUP_RECLAIM_SHRINK       (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
407 #define MEM_CGROUP_RECLAIM_SOFT_BIT     0x2
408 #define MEM_CGROUP_RECLAIM_SOFT         (1 << MEM_CGROUP_RECLAIM_SOFT_BIT)
409
410 static void mem_cgroup_get(struct mem_cgroup *mem);
411 static void mem_cgroup_put(struct mem_cgroup *mem);
412 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem);
413 static void drain_all_stock_async(struct mem_cgroup *mem);
414
415 static struct mem_cgroup_per_zone *
416 mem_cgroup_zoneinfo(struct mem_cgroup *mem, int nid, int zid)
417 {
418         return &mem->info.nodeinfo[nid]->zoneinfo[zid];
419 }
420
421 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *mem)
422 {
423         return &mem->css;
424 }
425
426 static struct mem_cgroup_per_zone *
427 page_cgroup_zoneinfo(struct mem_cgroup *mem, struct page *page)
428 {
429         int nid = page_to_nid(page);
430         int zid = page_zonenum(page);
431
432         return mem_cgroup_zoneinfo(mem, nid, zid);
433 }
434
435 static struct mem_cgroup_tree_per_zone *
436 soft_limit_tree_node_zone(int nid, int zid)
437 {
438         return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
439 }
440
441 static struct mem_cgroup_tree_per_zone *
442 soft_limit_tree_from_page(struct page *page)
443 {
444         int nid = page_to_nid(page);
445         int zid = page_zonenum(page);
446
447         return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
448 }
449
450 static void
451 __mem_cgroup_insert_exceeded(struct mem_cgroup *mem,
452                                 struct mem_cgroup_per_zone *mz,
453                                 struct mem_cgroup_tree_per_zone *mctz,
454                                 unsigned long long new_usage_in_excess)
455 {
456         struct rb_node **p = &mctz->rb_root.rb_node;
457         struct rb_node *parent = NULL;
458         struct mem_cgroup_per_zone *mz_node;
459
460         if (mz->on_tree)
461                 return;
462
463         mz->usage_in_excess = new_usage_in_excess;
464         if (!mz->usage_in_excess)
465                 return;
466         while (*p) {
467                 parent = *p;
468                 mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
469                                         tree_node);
470                 if (mz->usage_in_excess < mz_node->usage_in_excess)
471                         p = &(*p)->rb_left;
472                 /*
473                  * We can't avoid mem cgroups that are over their soft
474                  * limit by the same amount
475                  */
476                 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
477                         p = &(*p)->rb_right;
478         }
479         rb_link_node(&mz->tree_node, parent, p);
480         rb_insert_color(&mz->tree_node, &mctz->rb_root);
481         mz->on_tree = true;
482 }
483
484 static void
485 __mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
486                                 struct mem_cgroup_per_zone *mz,
487                                 struct mem_cgroup_tree_per_zone *mctz)
488 {
489         if (!mz->on_tree)
490                 return;
491         rb_erase(&mz->tree_node, &mctz->rb_root);
492         mz->on_tree = false;
493 }
494
495 static void
496 mem_cgroup_remove_exceeded(struct mem_cgroup *mem,
497                                 struct mem_cgroup_per_zone *mz,
498                                 struct mem_cgroup_tree_per_zone *mctz)
499 {
500         spin_lock(&mctz->lock);
501         __mem_cgroup_remove_exceeded(mem, mz, mctz);
502         spin_unlock(&mctz->lock);
503 }
504
505
506 static void mem_cgroup_update_tree(struct mem_cgroup *mem, struct page *page)
507 {
508         unsigned long long excess;
509         struct mem_cgroup_per_zone *mz;
510         struct mem_cgroup_tree_per_zone *mctz;
511         int nid = page_to_nid(page);
512         int zid = page_zonenum(page);
513         mctz = soft_limit_tree_from_page(page);
514
515         /*
516          * Necessary to update all ancestors when hierarchy is used.
517          * because their event counter is not touched.
518          */
519         for (; mem; mem = parent_mem_cgroup(mem)) {
520                 mz = mem_cgroup_zoneinfo(mem, nid, zid);
521                 excess = res_counter_soft_limit_excess(&mem->res);
522                 /*
523                  * We have to update the tree if mz is on RB-tree or
524                  * mem is over its softlimit.
525                  */
526                 if (excess || mz->on_tree) {
527                         spin_lock(&mctz->lock);
528                         /* if on-tree, remove it */
529                         if (mz->on_tree)
530                                 __mem_cgroup_remove_exceeded(mem, mz, mctz);
531                         /*
532                          * Insert again. mz->usage_in_excess will be updated.
533                          * If excess is 0, no tree ops.
534                          */
535                         __mem_cgroup_insert_exceeded(mem, mz, mctz, excess);
536                         spin_unlock(&mctz->lock);
537                 }
538         }
539 }
540
541 static void mem_cgroup_remove_from_trees(struct mem_cgroup *mem)
542 {
543         int node, zone;
544         struct mem_cgroup_per_zone *mz;
545         struct mem_cgroup_tree_per_zone *mctz;
546
547         for_each_node_state(node, N_POSSIBLE) {
548                 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
549                         mz = mem_cgroup_zoneinfo(mem, node, zone);
550                         mctz = soft_limit_tree_node_zone(node, zone);
551                         mem_cgroup_remove_exceeded(mem, mz, mctz);
552                 }
553         }
554 }
555
556 static struct mem_cgroup_per_zone *
557 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
558 {
559         struct rb_node *rightmost = NULL;
560         struct mem_cgroup_per_zone *mz;
561
562 retry:
563         mz = NULL;
564         rightmost = rb_last(&mctz->rb_root);
565         if (!rightmost)
566                 goto done;              /* Nothing to reclaim from */
567
568         mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
569         /*
570          * Remove the node now but someone else can add it back,
571          * we will to add it back at the end of reclaim to its correct
572          * position in the tree.
573          */
574         __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
575         if (!res_counter_soft_limit_excess(&mz->mem->res) ||
576                 !css_tryget(&mz->mem->css))
577                 goto retry;
578 done:
579         return mz;
580 }
581
582 static struct mem_cgroup_per_zone *
583 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
584 {
585         struct mem_cgroup_per_zone *mz;
586
587         spin_lock(&mctz->lock);
588         mz = __mem_cgroup_largest_soft_limit_node(mctz);
589         spin_unlock(&mctz->lock);
590         return mz;
591 }
592
593 /*
594  * Implementation Note: reading percpu statistics for memcg.
595  *
596  * Both of vmstat[] and percpu_counter has threshold and do periodic
597  * synchronization to implement "quick" read. There are trade-off between
598  * reading cost and precision of value. Then, we may have a chance to implement
599  * a periodic synchronizion of counter in memcg's counter.
600  *
601  * But this _read() function is used for user interface now. The user accounts
602  * memory usage by memory cgroup and he _always_ requires exact value because
603  * he accounts memory. Even if we provide quick-and-fuzzy read, we always
604  * have to visit all online cpus and make sum. So, for now, unnecessary
605  * synchronization is not implemented. (just implemented for cpu hotplug)
606  *
607  * If there are kernel internal actions which can make use of some not-exact
608  * value, and reading all cpu value can be performance bottleneck in some
609  * common workload, threashold and synchonization as vmstat[] should be
610  * implemented.
611  */
612 static long mem_cgroup_read_stat(struct mem_cgroup *mem,
613                                  enum mem_cgroup_stat_index idx)
614 {
615         long val = 0;
616         int cpu;
617
618         get_online_cpus();
619         for_each_online_cpu(cpu)
620                 val += per_cpu(mem->stat->count[idx], cpu);
621 #ifdef CONFIG_HOTPLUG_CPU
622         spin_lock(&mem->pcp_counter_lock);
623         val += mem->nocpu_base.count[idx];
624         spin_unlock(&mem->pcp_counter_lock);
625 #endif
626         put_online_cpus();
627         return val;
628 }
629
630 static void mem_cgroup_swap_statistics(struct mem_cgroup *mem,
631                                          bool charge)
632 {
633         int val = (charge) ? 1 : -1;
634         this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_SWAPOUT], val);
635 }
636
637 void mem_cgroup_pgfault(struct mem_cgroup *mem, int val)
638 {
639         this_cpu_add(mem->stat->events[MEM_CGROUP_EVENTS_PGFAULT], val);
640 }
641
642 void mem_cgroup_pgmajfault(struct mem_cgroup *mem, int val)
643 {
644         this_cpu_add(mem->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT], val);
645 }
646
647 static unsigned long mem_cgroup_read_events(struct mem_cgroup *mem,
648                                             enum mem_cgroup_events_index idx)
649 {
650         unsigned long val = 0;
651         int cpu;
652
653         for_each_online_cpu(cpu)
654                 val += per_cpu(mem->stat->events[idx], cpu);
655 #ifdef CONFIG_HOTPLUG_CPU
656         spin_lock(&mem->pcp_counter_lock);
657         val += mem->nocpu_base.events[idx];
658         spin_unlock(&mem->pcp_counter_lock);
659 #endif
660         return val;
661 }
662
663 static void mem_cgroup_charge_statistics(struct mem_cgroup *mem,
664                                          bool file, int nr_pages)
665 {
666         preempt_disable();
667
668         if (file)
669                 __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_CACHE], nr_pages);
670         else
671                 __this_cpu_add(mem->stat->count[MEM_CGROUP_STAT_RSS], nr_pages);
672
673         /* pagein of a big page is an event. So, ignore page size */
674         if (nr_pages > 0)
675                 __this_cpu_inc(mem->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
676         else {
677                 __this_cpu_inc(mem->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
678                 nr_pages = -nr_pages; /* for event */
679         }
680
681         __this_cpu_add(mem->stat->events[MEM_CGROUP_EVENTS_COUNT], nr_pages);
682
683         preempt_enable();
684 }
685
686 unsigned long
687 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *mem, int nid, int zid,
688                         unsigned int lru_mask)
689 {
690         struct mem_cgroup_per_zone *mz;
691         enum lru_list l;
692         unsigned long ret = 0;
693
694         mz = mem_cgroup_zoneinfo(mem, nid, zid);
695
696         for_each_lru(l) {
697                 if (BIT(l) & lru_mask)
698                         ret += MEM_CGROUP_ZSTAT(mz, l);
699         }
700         return ret;
701 }
702
703 static unsigned long
704 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *mem,
705                         int nid, unsigned int lru_mask)
706 {
707         u64 total = 0;
708         int zid;
709
710         for (zid = 0; zid < MAX_NR_ZONES; zid++)
711                 total += mem_cgroup_zone_nr_lru_pages(mem, nid, zid, lru_mask);
712
713         return total;
714 }
715
716 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *mem,
717                         unsigned int lru_mask)
718 {
719         int nid;
720         u64 total = 0;
721
722         for_each_node_state(nid, N_HIGH_MEMORY)
723                 total += mem_cgroup_node_nr_lru_pages(mem, nid, lru_mask);
724         return total;
725 }
726
727 static bool __memcg_event_check(struct mem_cgroup *mem, int target)
728 {
729         unsigned long val, next;
730
731         val = this_cpu_read(mem->stat->events[MEM_CGROUP_EVENTS_COUNT]);
732         next = this_cpu_read(mem->stat->targets[target]);
733         /* from time_after() in jiffies.h */
734         return ((long)next - (long)val < 0);
735 }
736
737 static void __mem_cgroup_target_update(struct mem_cgroup *mem, int target)
738 {
739         unsigned long val, next;
740
741         val = this_cpu_read(mem->stat->events[MEM_CGROUP_EVENTS_COUNT]);
742
743         switch (target) {
744         case MEM_CGROUP_TARGET_THRESH:
745                 next = val + THRESHOLDS_EVENTS_TARGET;
746                 break;
747         case MEM_CGROUP_TARGET_SOFTLIMIT:
748                 next = val + SOFTLIMIT_EVENTS_TARGET;
749                 break;
750         case MEM_CGROUP_TARGET_NUMAINFO:
751                 next = val + NUMAINFO_EVENTS_TARGET;
752                 break;
753         default:
754                 return;
755         }
756
757         this_cpu_write(mem->stat->targets[target], next);
758 }
759
760 /*
761  * Check events in order.
762  *
763  */
764 static void memcg_check_events(struct mem_cgroup *mem, struct page *page)
765 {
766         /* threshold event is triggered in finer grain than soft limit */
767         if (unlikely(__memcg_event_check(mem, MEM_CGROUP_TARGET_THRESH))) {
768                 mem_cgroup_threshold(mem);
769                 __mem_cgroup_target_update(mem, MEM_CGROUP_TARGET_THRESH);
770                 if (unlikely(__memcg_event_check(mem,
771                              MEM_CGROUP_TARGET_SOFTLIMIT))) {
772                         mem_cgroup_update_tree(mem, page);
773                         __mem_cgroup_target_update(mem,
774                                                    MEM_CGROUP_TARGET_SOFTLIMIT);
775                 }
776 #if MAX_NUMNODES > 1
777                 if (unlikely(__memcg_event_check(mem,
778                         MEM_CGROUP_TARGET_NUMAINFO))) {
779                         atomic_inc(&mem->numainfo_events);
780                         __mem_cgroup_target_update(mem,
781                                 MEM_CGROUP_TARGET_NUMAINFO);
782                 }
783 #endif
784         }
785 }
786
787 static struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
788 {
789         return container_of(cgroup_subsys_state(cont,
790                                 mem_cgroup_subsys_id), struct mem_cgroup,
791                                 css);
792 }
793
794 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
795 {
796         /*
797          * mm_update_next_owner() may clear mm->owner to NULL
798          * if it races with swapoff, page migration, etc.
799          * So this can be called with p == NULL.
800          */
801         if (unlikely(!p))
802                 return NULL;
803
804         return container_of(task_subsys_state(p, mem_cgroup_subsys_id),
805                                 struct mem_cgroup, css);
806 }
807
808 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
809 {
810         struct mem_cgroup *mem = NULL;
811
812         if (!mm)
813                 return NULL;
814         /*
815          * Because we have no locks, mm->owner's may be being moved to other
816          * cgroup. We use css_tryget() here even if this looks
817          * pessimistic (rather than adding locks here).
818          */
819         rcu_read_lock();
820         do {
821                 mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
822                 if (unlikely(!mem))
823                         break;
824         } while (!css_tryget(&mem->css));
825         rcu_read_unlock();
826         return mem;
827 }
828
829 /* The caller has to guarantee "mem" exists before calling this */
830 static struct mem_cgroup *mem_cgroup_start_loop(struct mem_cgroup *mem)
831 {
832         struct cgroup_subsys_state *css;
833         int found;
834
835         if (!mem) /* ROOT cgroup has the smallest ID */
836                 return root_mem_cgroup; /*css_put/get against root is ignored*/
837         if (!mem->use_hierarchy) {
838                 if (css_tryget(&mem->css))
839                         return mem;
840                 return NULL;
841         }
842         rcu_read_lock();
843         /*
844          * searching a memory cgroup which has the smallest ID under given
845          * ROOT cgroup. (ID >= 1)
846          */
847         css = css_get_next(&mem_cgroup_subsys, 1, &mem->css, &found);
848         if (css && css_tryget(css))
849                 mem = container_of(css, struct mem_cgroup, css);
850         else
851                 mem = NULL;
852         rcu_read_unlock();
853         return mem;
854 }
855
856 static struct mem_cgroup *mem_cgroup_get_next(struct mem_cgroup *iter,
857                                         struct mem_cgroup *root,
858                                         bool cond)
859 {
860         int nextid = css_id(&iter->css) + 1;
861         int found;
862         int hierarchy_used;
863         struct cgroup_subsys_state *css;
864
865         hierarchy_used = iter->use_hierarchy;
866
867         css_put(&iter->css);
868         /* If no ROOT, walk all, ignore hierarchy */
869         if (!cond || (root && !hierarchy_used))
870                 return NULL;
871
872         if (!root)
873                 root = root_mem_cgroup;
874
875         do {
876                 iter = NULL;
877                 rcu_read_lock();
878
879                 css = css_get_next(&mem_cgroup_subsys, nextid,
880                                 &root->css, &found);
881                 if (css && css_tryget(css))
882                         iter = container_of(css, struct mem_cgroup, css);
883                 rcu_read_unlock();
884                 /* If css is NULL, no more cgroups will be found */
885                 nextid = found + 1;
886         } while (css && !iter);
887
888         return iter;
889 }
890 /*
891  * for_eacn_mem_cgroup_tree() for visiting all cgroup under tree. Please
892  * be careful that "break" loop is not allowed. We have reference count.
893  * Instead of that modify "cond" to be false and "continue" to exit the loop.
894  */
895 #define for_each_mem_cgroup_tree_cond(iter, root, cond) \
896         for (iter = mem_cgroup_start_loop(root);\
897              iter != NULL;\
898              iter = mem_cgroup_get_next(iter, root, cond))
899
900 #define for_each_mem_cgroup_tree(iter, root) \
901         for_each_mem_cgroup_tree_cond(iter, root, true)
902
903 #define for_each_mem_cgroup_all(iter) \
904         for_each_mem_cgroup_tree_cond(iter, NULL, true)
905
906
907 static inline bool mem_cgroup_is_root(struct mem_cgroup *mem)
908 {
909         return (mem == root_mem_cgroup);
910 }
911
912 void mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
913 {
914         struct mem_cgroup *mem;
915
916         if (!mm)
917                 return;
918
919         rcu_read_lock();
920         mem = mem_cgroup_from_task(rcu_dereference(mm->owner));
921         if (unlikely(!mem))
922                 goto out;
923
924         switch (idx) {
925         case PGMAJFAULT:
926                 mem_cgroup_pgmajfault(mem, 1);
927                 break;
928         case PGFAULT:
929                 mem_cgroup_pgfault(mem, 1);
930                 break;
931         default:
932                 BUG();
933         }
934 out:
935         rcu_read_unlock();
936 }
937 EXPORT_SYMBOL(mem_cgroup_count_vm_event);
938
939 /*
940  * Following LRU functions are allowed to be used without PCG_LOCK.
941  * Operations are called by routine of global LRU independently from memcg.
942  * What we have to take care of here is validness of pc->mem_cgroup.
943  *
944  * Changes to pc->mem_cgroup happens when
945  * 1. charge
946  * 2. moving account
947  * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
948  * It is added to LRU before charge.
949  * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
950  * When moving account, the page is not on LRU. It's isolated.
951  */
952
953 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru)
954 {
955         struct page_cgroup *pc;
956         struct mem_cgroup_per_zone *mz;
957
958         if (mem_cgroup_disabled())
959                 return;
960         pc = lookup_page_cgroup(page);
961         /* can happen while we handle swapcache. */
962         if (!TestClearPageCgroupAcctLRU(pc))
963                 return;
964         VM_BUG_ON(!pc->mem_cgroup);
965         /*
966          * We don't check PCG_USED bit. It's cleared when the "page" is finally
967          * removed from global LRU.
968          */
969         mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
970         /* huge page split is done under lru_lock. so, we have no races. */
971         MEM_CGROUP_ZSTAT(mz, lru) -= 1 << compound_order(page);
972         if (mem_cgroup_is_root(pc->mem_cgroup))
973                 return;
974         VM_BUG_ON(list_empty(&pc->lru));
975         list_del_init(&pc->lru);
976 }
977
978 void mem_cgroup_del_lru(struct page *page)
979 {
980         mem_cgroup_del_lru_list(page, page_lru(page));
981 }
982
983 /*
984  * Writeback is about to end against a page which has been marked for immediate
985  * reclaim.  If it still appears to be reclaimable, move it to the tail of the
986  * inactive list.
987  */
988 void mem_cgroup_rotate_reclaimable_page(struct page *page)
989 {
990         struct mem_cgroup_per_zone *mz;
991         struct page_cgroup *pc;
992         enum lru_list lru = page_lru(page);
993
994         if (mem_cgroup_disabled())
995                 return;
996
997         pc = lookup_page_cgroup(page);
998         /* unused or root page is not rotated. */
999         if (!PageCgroupUsed(pc))
1000                 return;
1001         /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1002         smp_rmb();
1003         if (mem_cgroup_is_root(pc->mem_cgroup))
1004                 return;
1005         mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1006         list_move_tail(&pc->lru, &mz->lists[lru]);
1007 }
1008
1009 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru)
1010 {
1011         struct mem_cgroup_per_zone *mz;
1012         struct page_cgroup *pc;
1013
1014         if (mem_cgroup_disabled())
1015                 return;
1016
1017         pc = lookup_page_cgroup(page);
1018         /* unused or root page is not rotated. */
1019         if (!PageCgroupUsed(pc))
1020                 return;
1021         /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1022         smp_rmb();
1023         if (mem_cgroup_is_root(pc->mem_cgroup))
1024                 return;
1025         mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1026         list_move(&pc->lru, &mz->lists[lru]);
1027 }
1028
1029 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru)
1030 {
1031         struct page_cgroup *pc;
1032         struct mem_cgroup_per_zone *mz;
1033
1034         if (mem_cgroup_disabled())
1035                 return;
1036         pc = lookup_page_cgroup(page);
1037         VM_BUG_ON(PageCgroupAcctLRU(pc));
1038         if (!PageCgroupUsed(pc))
1039                 return;
1040         /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1041         smp_rmb();
1042         mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1043         /* huge page split is done under lru_lock. so, we have no races. */
1044         MEM_CGROUP_ZSTAT(mz, lru) += 1 << compound_order(page);
1045         SetPageCgroupAcctLRU(pc);
1046         if (mem_cgroup_is_root(pc->mem_cgroup))
1047                 return;
1048         list_add(&pc->lru, &mz->lists[lru]);
1049 }
1050
1051 /*
1052  * At handling SwapCache and other FUSE stuff, pc->mem_cgroup may be changed
1053  * while it's linked to lru because the page may be reused after it's fully
1054  * uncharged. To handle that, unlink page_cgroup from LRU when charge it again.
1055  * It's done under lock_page and expected that zone->lru_lock isnever held.
1056  */
1057 static void mem_cgroup_lru_del_before_commit(struct page *page)
1058 {
1059         unsigned long flags;
1060         struct zone *zone = page_zone(page);
1061         struct page_cgroup *pc = lookup_page_cgroup(page);
1062
1063         /*
1064          * Doing this check without taking ->lru_lock seems wrong but this
1065          * is safe. Because if page_cgroup's USED bit is unset, the page
1066          * will not be added to any memcg's LRU. If page_cgroup's USED bit is
1067          * set, the commit after this will fail, anyway.
1068          * This all charge/uncharge is done under some mutual execustion.
1069          * So, we don't need to taking care of changes in USED bit.
1070          */
1071         if (likely(!PageLRU(page)))
1072                 return;
1073
1074         spin_lock_irqsave(&zone->lru_lock, flags);
1075         /*
1076          * Forget old LRU when this page_cgroup is *not* used. This Used bit
1077          * is guarded by lock_page() because the page is SwapCache.
1078          */
1079         if (!PageCgroupUsed(pc))
1080                 mem_cgroup_del_lru_list(page, page_lru(page));
1081         spin_unlock_irqrestore(&zone->lru_lock, flags);
1082 }
1083
1084 static void mem_cgroup_lru_add_after_commit(struct page *page)
1085 {
1086         unsigned long flags;
1087         struct zone *zone = page_zone(page);
1088         struct page_cgroup *pc = lookup_page_cgroup(page);
1089
1090         /* taking care of that the page is added to LRU while we commit it */
1091         if (likely(!PageLRU(page)))
1092                 return;
1093         spin_lock_irqsave(&zone->lru_lock, flags);
1094         /* link when the page is linked to LRU but page_cgroup isn't */
1095         if (PageLRU(page) && !PageCgroupAcctLRU(pc))
1096                 mem_cgroup_add_lru_list(page, page_lru(page));
1097         spin_unlock_irqrestore(&zone->lru_lock, flags);
1098 }
1099
1100
1101 void mem_cgroup_move_lists(struct page *page,
1102                            enum lru_list from, enum lru_list to)
1103 {
1104         if (mem_cgroup_disabled())
1105                 return;
1106         mem_cgroup_del_lru_list(page, from);
1107         mem_cgroup_add_lru_list(page, to);
1108 }
1109
1110 /*
1111  * Checks whether given mem is same or in the root_mem's
1112  * hierarchy subtree
1113  */
1114 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_mem,
1115                 struct mem_cgroup *mem)
1116 {
1117         if (root_mem != mem) {
1118                 return (root_mem->use_hierarchy &&
1119                         css_is_ancestor(&mem->css, &root_mem->css));
1120         }
1121
1122         return true;
1123 }
1124
1125 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *mem)
1126 {
1127         int ret;
1128         struct mem_cgroup *curr = NULL;
1129         struct task_struct *p;
1130
1131         p = find_lock_task_mm(task);
1132         if (!p)
1133                 return 0;
1134         curr = try_get_mem_cgroup_from_mm(p->mm);
1135         task_unlock(p);
1136         if (!curr)
1137                 return 0;
1138         /*
1139          * We should check use_hierarchy of "mem" not "curr". Because checking
1140          * use_hierarchy of "curr" here make this function true if hierarchy is
1141          * enabled in "curr" and "curr" is a child of "mem" in *cgroup*
1142          * hierarchy(even if use_hierarchy is disabled in "mem").
1143          */
1144         ret = mem_cgroup_same_or_subtree(mem, curr);
1145         css_put(&curr->css);
1146         return ret;
1147 }
1148
1149 static int calc_inactive_ratio(struct mem_cgroup *memcg, unsigned long *present_pages)
1150 {
1151         unsigned long active;
1152         unsigned long inactive;
1153         unsigned long gb;
1154         unsigned long inactive_ratio;
1155
1156         inactive = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_ANON));
1157         active = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_ANON));
1158
1159         gb = (inactive + active) >> (30 - PAGE_SHIFT);
1160         if (gb)
1161                 inactive_ratio = int_sqrt(10 * gb);
1162         else
1163                 inactive_ratio = 1;
1164
1165         if (present_pages) {
1166                 present_pages[0] = inactive;
1167                 present_pages[1] = active;
1168         }
1169
1170         return inactive_ratio;
1171 }
1172
1173 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg)
1174 {
1175         unsigned long active;
1176         unsigned long inactive;
1177         unsigned long present_pages[2];
1178         unsigned long inactive_ratio;
1179
1180         inactive_ratio = calc_inactive_ratio(memcg, present_pages);
1181
1182         inactive = present_pages[0];
1183         active = present_pages[1];
1184
1185         if (inactive * inactive_ratio < active)
1186                 return 1;
1187
1188         return 0;
1189 }
1190
1191 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg)
1192 {
1193         unsigned long active;
1194         unsigned long inactive;
1195
1196         inactive = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_FILE));
1197         active = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_FILE));
1198
1199         return (active > inactive);
1200 }
1201
1202 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg,
1203                                                       struct zone *zone)
1204 {
1205         int nid = zone_to_nid(zone);
1206         int zid = zone_idx(zone);
1207         struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1208
1209         return &mz->reclaim_stat;
1210 }
1211
1212 struct zone_reclaim_stat *
1213 mem_cgroup_get_reclaim_stat_from_page(struct page *page)
1214 {
1215         struct page_cgroup *pc;
1216         struct mem_cgroup_per_zone *mz;
1217
1218         if (mem_cgroup_disabled())
1219                 return NULL;
1220
1221         pc = lookup_page_cgroup(page);
1222         if (!PageCgroupUsed(pc))
1223                 return NULL;
1224         /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */
1225         smp_rmb();
1226         mz = page_cgroup_zoneinfo(pc->mem_cgroup, page);
1227         return &mz->reclaim_stat;
1228 }
1229
1230 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan,
1231                                         struct list_head *dst,
1232                                         unsigned long *scanned, int order,
1233                                         int mode, struct zone *z,
1234                                         struct mem_cgroup *mem_cont,
1235                                         int active, int file)
1236 {
1237         unsigned long nr_taken = 0;
1238         struct page *page;
1239         unsigned long scan;
1240         LIST_HEAD(pc_list);
1241         struct list_head *src;
1242         struct page_cgroup *pc, *tmp;
1243         int nid = zone_to_nid(z);
1244         int zid = zone_idx(z);
1245         struct mem_cgroup_per_zone *mz;
1246         int lru = LRU_FILE * file + active;
1247         int ret;
1248
1249         BUG_ON(!mem_cont);
1250         mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
1251         src = &mz->lists[lru];
1252
1253         scan = 0;
1254         list_for_each_entry_safe_reverse(pc, tmp, src, lru) {
1255                 if (scan >= nr_to_scan)
1256                         break;
1257
1258                 if (unlikely(!PageCgroupUsed(pc)))
1259                         continue;
1260
1261                 page = lookup_cgroup_page(pc);
1262
1263                 if (unlikely(!PageLRU(page)))
1264                         continue;
1265
1266                 scan++;
1267                 ret = __isolate_lru_page(page, mode, file);
1268                 switch (ret) {
1269                 case 0:
1270                         list_move(&page->lru, dst);
1271                         mem_cgroup_del_lru(page);
1272                         nr_taken += hpage_nr_pages(page);
1273                         break;
1274                 case -EBUSY:
1275                         /* we don't affect global LRU but rotate in our LRU */
1276                         mem_cgroup_rotate_lru_list(page, page_lru(page));
1277                         break;
1278                 default:
1279                         break;
1280                 }
1281         }
1282
1283         *scanned = scan;
1284
1285         trace_mm_vmscan_memcg_isolate(0, nr_to_scan, scan, nr_taken,
1286                                       0, 0, 0, mode);
1287
1288         return nr_taken;
1289 }
1290
1291 #define mem_cgroup_from_res_counter(counter, member)    \
1292         container_of(counter, struct mem_cgroup, member)
1293
1294 /**
1295  * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1296  * @mem: the memory cgroup
1297  *
1298  * Returns the maximum amount of memory @mem can be charged with, in
1299  * pages.
1300  */
1301 static unsigned long mem_cgroup_margin(struct mem_cgroup *mem)
1302 {
1303         unsigned long long margin;
1304
1305         margin = res_counter_margin(&mem->res);
1306         if (do_swap_account)
1307                 margin = min(margin, res_counter_margin(&mem->memsw));
1308         return margin >> PAGE_SHIFT;
1309 }
1310
1311 int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1312 {
1313         struct cgroup *cgrp = memcg->css.cgroup;
1314
1315         /* root ? */
1316         if (cgrp->parent == NULL)
1317                 return vm_swappiness;
1318
1319         return memcg->swappiness;
1320 }
1321
1322 static void mem_cgroup_start_move(struct mem_cgroup *mem)
1323 {
1324         int cpu;
1325
1326         get_online_cpus();
1327         spin_lock(&mem->pcp_counter_lock);
1328         for_each_online_cpu(cpu)
1329                 per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) += 1;
1330         mem->nocpu_base.count[MEM_CGROUP_ON_MOVE] += 1;
1331         spin_unlock(&mem->pcp_counter_lock);
1332         put_online_cpus();
1333
1334         synchronize_rcu();
1335 }
1336
1337 static void mem_cgroup_end_move(struct mem_cgroup *mem)
1338 {
1339         int cpu;
1340
1341         if (!mem)
1342                 return;
1343         get_online_cpus();
1344         spin_lock(&mem->pcp_counter_lock);
1345         for_each_online_cpu(cpu)
1346                 per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1;
1347         mem->nocpu_base.count[MEM_CGROUP_ON_MOVE] -= 1;
1348         spin_unlock(&mem->pcp_counter_lock);
1349         put_online_cpus();
1350 }
1351 /*
1352  * 2 routines for checking "mem" is under move_account() or not.
1353  *
1354  * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used
1355  *                        for avoiding race in accounting. If true,
1356  *                        pc->mem_cgroup may be overwritten.
1357  *
1358  * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1359  *                        under hierarchy of moving cgroups. This is for
1360  *                        waiting at hith-memory prressure caused by "move".
1361  */
1362
1363 static bool mem_cgroup_stealed(struct mem_cgroup *mem)
1364 {
1365         VM_BUG_ON(!rcu_read_lock_held());
1366         return this_cpu_read(mem->stat->count[MEM_CGROUP_ON_MOVE]) > 0;
1367 }
1368
1369 static bool mem_cgroup_under_move(struct mem_cgroup *mem)
1370 {
1371         struct mem_cgroup *from;
1372         struct mem_cgroup *to;
1373         bool ret = false;
1374         /*
1375          * Unlike task_move routines, we access mc.to, mc.from not under
1376          * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1377          */
1378         spin_lock(&mc.lock);
1379         from = mc.from;
1380         to = mc.to;
1381         if (!from)
1382                 goto unlock;
1383
1384         ret = mem_cgroup_same_or_subtree(mem, from)
1385                 || mem_cgroup_same_or_subtree(mem, to);
1386 unlock:
1387         spin_unlock(&mc.lock);
1388         return ret;
1389 }
1390
1391 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *mem)
1392 {
1393         if (mc.moving_task && current != mc.moving_task) {
1394                 if (mem_cgroup_under_move(mem)) {
1395                         DEFINE_WAIT(wait);
1396                         prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1397                         /* moving charge context might have finished. */
1398                         if (mc.moving_task)
1399                                 schedule();
1400                         finish_wait(&mc.waitq, &wait);
1401                         return true;
1402                 }
1403         }
1404         return false;
1405 }
1406
1407 /**
1408  * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode.
1409  * @memcg: The memory cgroup that went over limit
1410  * @p: Task that is going to be killed
1411  *
1412  * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1413  * enabled
1414  */
1415 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1416 {
1417         struct cgroup *task_cgrp;
1418         struct cgroup *mem_cgrp;
1419         /*
1420          * Need a buffer in BSS, can't rely on allocations. The code relies
1421          * on the assumption that OOM is serialized for memory controller.
1422          * If this assumption is broken, revisit this code.
1423          */
1424         static char memcg_name[PATH_MAX];
1425         int ret;
1426
1427         if (!memcg || !p)
1428                 return;
1429
1430
1431         rcu_read_lock();
1432
1433         mem_cgrp = memcg->css.cgroup;
1434         task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1435
1436         ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1437         if (ret < 0) {
1438                 /*
1439                  * Unfortunately, we are unable to convert to a useful name
1440                  * But we'll still print out the usage information
1441                  */
1442                 rcu_read_unlock();
1443                 goto done;
1444         }
1445         rcu_read_unlock();
1446
1447         printk(KERN_INFO "Task in %s killed", memcg_name);
1448
1449         rcu_read_lock();
1450         ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1451         if (ret < 0) {
1452                 rcu_read_unlock();
1453                 goto done;
1454         }
1455         rcu_read_unlock();
1456
1457         /*
1458          * Continues from above, so we don't need an KERN_ level
1459          */
1460         printk(KERN_CONT " as a result of limit of %s\n", memcg_name);
1461 done:
1462
1463         printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n",
1464                 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10,
1465                 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10,
1466                 res_counter_read_u64(&memcg->res, RES_FAILCNT));
1467         printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, "
1468                 "failcnt %llu\n",
1469                 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10,
1470                 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10,
1471                 res_counter_read_u64(&memcg->memsw, RES_FAILCNT));
1472 }
1473
1474 /*
1475  * This function returns the number of memcg under hierarchy tree. Returns
1476  * 1(self count) if no children.
1477  */
1478 static int mem_cgroup_count_children(struct mem_cgroup *mem)
1479 {
1480         int num = 0;
1481         struct mem_cgroup *iter;
1482
1483         for_each_mem_cgroup_tree(iter, mem)
1484                 num++;
1485         return num;
1486 }
1487
1488 /*
1489  * Return the memory (and swap, if configured) limit for a memcg.
1490  */
1491 u64 mem_cgroup_get_limit(struct mem_cgroup *memcg)
1492 {
1493         u64 limit;
1494         u64 memsw;
1495
1496         limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
1497         limit += total_swap_pages << PAGE_SHIFT;
1498
1499         memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
1500         /*
1501          * If memsw is finite and limits the amount of swap space available
1502          * to this memcg, return that limit.
1503          */
1504         return min(limit, memsw);
1505 }
1506
1507 /*
1508  * Visit the first child (need not be the first child as per the ordering
1509  * of the cgroup list, since we track last_scanned_child) of @mem and use
1510  * that to reclaim free pages from.
1511  */
1512 static struct mem_cgroup *
1513 mem_cgroup_select_victim(struct mem_cgroup *root_mem)
1514 {
1515         struct mem_cgroup *ret = NULL;
1516         struct cgroup_subsys_state *css;
1517         int nextid, found;
1518
1519         if (!root_mem->use_hierarchy) {
1520                 css_get(&root_mem->css);
1521                 ret = root_mem;
1522         }
1523
1524         while (!ret) {
1525                 rcu_read_lock();
1526                 nextid = root_mem->last_scanned_child + 1;
1527                 css = css_get_next(&mem_cgroup_subsys, nextid, &root_mem->css,
1528                                    &found);
1529                 if (css && css_tryget(css))
1530                         ret = container_of(css, struct mem_cgroup, css);
1531
1532                 rcu_read_unlock();
1533                 /* Updates scanning parameter */
1534                 if (!css) {
1535                         /* this means start scan from ID:1 */
1536                         root_mem->last_scanned_child = 0;
1537                 } else
1538                         root_mem->last_scanned_child = found;
1539         }
1540
1541         return ret;
1542 }
1543
1544 /**
1545  * test_mem_cgroup_node_reclaimable
1546  * @mem: the target memcg
1547  * @nid: the node ID to be checked.
1548  * @noswap : specify true here if the user wants flle only information.
1549  *
1550  * This function returns whether the specified memcg contains any
1551  * reclaimable pages on a node. Returns true if there are any reclaimable
1552  * pages in the node.
1553  */
1554 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *mem,
1555                 int nid, bool noswap)
1556 {
1557         if (mem_cgroup_node_nr_lru_pages(mem, nid, LRU_ALL_FILE))
1558                 return true;
1559         if (noswap || !total_swap_pages)
1560                 return false;
1561         if (mem_cgroup_node_nr_lru_pages(mem, nid, LRU_ALL_ANON))
1562                 return true;
1563         return false;
1564
1565 }
1566 #if MAX_NUMNODES > 1
1567
1568 /*
1569  * Always updating the nodemask is not very good - even if we have an empty
1570  * list or the wrong list here, we can start from some node and traverse all
1571  * nodes based on the zonelist. So update the list loosely once per 10 secs.
1572  *
1573  */
1574 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *mem)
1575 {
1576         int nid;
1577         /*
1578          * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
1579          * pagein/pageout changes since the last update.
1580          */
1581         if (!atomic_read(&mem->numainfo_events))
1582                 return;
1583         if (atomic_inc_return(&mem->numainfo_updating) > 1)
1584                 return;
1585
1586         /* make a nodemask where this memcg uses memory from */
1587         mem->scan_nodes = node_states[N_HIGH_MEMORY];
1588
1589         for_each_node_mask(nid, node_states[N_HIGH_MEMORY]) {
1590
1591                 if (!test_mem_cgroup_node_reclaimable(mem, nid, false))
1592                         node_clear(nid, mem->scan_nodes);
1593         }
1594
1595         atomic_set(&mem->numainfo_events, 0);
1596         atomic_set(&mem->numainfo_updating, 0);
1597 }
1598
1599 /*
1600  * Selecting a node where we start reclaim from. Because what we need is just
1601  * reducing usage counter, start from anywhere is O,K. Considering
1602  * memory reclaim from current node, there are pros. and cons.
1603  *
1604  * Freeing memory from current node means freeing memory from a node which
1605  * we'll use or we've used. So, it may make LRU bad. And if several threads
1606  * hit limits, it will see a contention on a node. But freeing from remote
1607  * node means more costs for memory reclaim because of memory latency.
1608  *
1609  * Now, we use round-robin. Better algorithm is welcomed.
1610  */
1611 int mem_cgroup_select_victim_node(struct mem_cgroup *mem)
1612 {
1613         int node;
1614
1615         mem_cgroup_may_update_nodemask(mem);
1616         node = mem->last_scanned_node;
1617
1618         node = next_node(node, mem->scan_nodes);
1619         if (node == MAX_NUMNODES)
1620                 node = first_node(mem->scan_nodes);
1621         /*
1622          * We call this when we hit limit, not when pages are added to LRU.
1623          * No LRU may hold pages because all pages are UNEVICTABLE or
1624          * memcg is too small and all pages are not on LRU. In that case,
1625          * we use curret node.
1626          */
1627         if (unlikely(node == MAX_NUMNODES))
1628                 node = numa_node_id();
1629
1630         mem->last_scanned_node = node;
1631         return node;
1632 }
1633
1634 /*
1635  * Check all nodes whether it contains reclaimable pages or not.
1636  * For quick scan, we make use of scan_nodes. This will allow us to skip
1637  * unused nodes. But scan_nodes is lazily updated and may not cotain
1638  * enough new information. We need to do double check.
1639  */
1640 bool mem_cgroup_reclaimable(struct mem_cgroup *mem, bool noswap)
1641 {
1642         int nid;
1643
1644         /*
1645          * quick check...making use of scan_node.
1646          * We can skip unused nodes.
1647          */
1648         if (!nodes_empty(mem->scan_nodes)) {
1649                 for (nid = first_node(mem->scan_nodes);
1650                      nid < MAX_NUMNODES;
1651                      nid = next_node(nid, mem->scan_nodes)) {
1652
1653                         if (test_mem_cgroup_node_reclaimable(mem, nid, noswap))
1654                                 return true;
1655                 }
1656         }
1657         /*
1658          * Check rest of nodes.
1659          */
1660         for_each_node_state(nid, N_HIGH_MEMORY) {
1661                 if (node_isset(nid, mem->scan_nodes))
1662                         continue;
1663                 if (test_mem_cgroup_node_reclaimable(mem, nid, noswap))
1664                         return true;
1665         }
1666         return false;
1667 }
1668
1669 #else
1670 int mem_cgroup_select_victim_node(struct mem_cgroup *mem)
1671 {
1672         return 0;
1673 }
1674
1675 bool mem_cgroup_reclaimable(struct mem_cgroup *mem, bool noswap)
1676 {
1677         return test_mem_cgroup_node_reclaimable(mem, 0, noswap);
1678 }
1679 #endif
1680
1681 static void __mem_cgroup_record_scanstat(unsigned long *stats,
1682                            struct memcg_scanrecord *rec)
1683 {
1684
1685         stats[SCAN] += rec->nr_scanned[0] + rec->nr_scanned[1];
1686         stats[SCAN_ANON] += rec->nr_scanned[0];
1687         stats[SCAN_FILE] += rec->nr_scanned[1];
1688
1689         stats[ROTATE] += rec->nr_rotated[0] + rec->nr_rotated[1];
1690         stats[ROTATE_ANON] += rec->nr_rotated[0];
1691         stats[ROTATE_FILE] += rec->nr_rotated[1];
1692
1693         stats[FREED] += rec->nr_freed[0] + rec->nr_freed[1];
1694         stats[FREED_ANON] += rec->nr_freed[0];
1695         stats[FREED_FILE] += rec->nr_freed[1];
1696
1697         stats[ELAPSED] += rec->elapsed;
1698 }
1699
1700 static void mem_cgroup_record_scanstat(struct memcg_scanrecord *rec)
1701 {
1702         struct mem_cgroup *mem;
1703         int context = rec->context;
1704
1705         if (context >= NR_SCAN_CONTEXT)
1706                 return;
1707
1708         mem = rec->mem;
1709         spin_lock(&mem->scanstat.lock);
1710         __mem_cgroup_record_scanstat(mem->scanstat.stats[context], rec);
1711         spin_unlock(&mem->scanstat.lock);
1712
1713         mem = rec->root;
1714         spin_lock(&mem->scanstat.lock);
1715         __mem_cgroup_record_scanstat(mem->scanstat.rootstats[context], rec);
1716         spin_unlock(&mem->scanstat.lock);
1717 }
1718
1719 /*
1720  * Scan the hierarchy if needed to reclaim memory. We remember the last child
1721  * we reclaimed from, so that we don't end up penalizing one child extensively
1722  * based on its position in the children list.
1723  *
1724  * root_mem is the original ancestor that we've been reclaim from.
1725  *
1726  * We give up and return to the caller when we visit root_mem twice.
1727  * (other groups can be removed while we're walking....)
1728  *
1729  * If shrink==true, for avoiding to free too much, this returns immedieately.
1730  */
1731 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_mem,
1732                                                 struct zone *zone,
1733                                                 gfp_t gfp_mask,
1734                                                 unsigned long reclaim_options,
1735                                                 unsigned long *total_scanned)
1736 {
1737         struct mem_cgroup *victim;
1738         int ret, total = 0;
1739         int loop = 0;
1740         bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP;
1741         bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK;
1742         bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT;
1743         struct memcg_scanrecord rec;
1744         unsigned long excess;
1745         unsigned long scanned;
1746
1747         excess = res_counter_soft_limit_excess(&root_mem->res) >> PAGE_SHIFT;
1748
1749         /* If memsw_is_minimum==1, swap-out is of-no-use. */
1750         if (!check_soft && !shrink && root_mem->memsw_is_minimum)
1751                 noswap = true;
1752
1753         if (shrink)
1754                 rec.context = SCAN_BY_SHRINK;
1755         else if (check_soft)
1756                 rec.context = SCAN_BY_SYSTEM;
1757         else
1758                 rec.context = SCAN_BY_LIMIT;
1759
1760         rec.root = root_mem;
1761
1762         while (1) {
1763                 victim = mem_cgroup_select_victim(root_mem);
1764                 if (victim == root_mem) {
1765                         loop++;
1766                         /*
1767                          * We are not draining per cpu cached charges during
1768                          * soft limit reclaim  because global reclaim doesn't
1769                          * care about charges. It tries to free some memory and
1770                          * charges will not give any.
1771                          */
1772                         if (!check_soft && loop >= 1)
1773                                 drain_all_stock_async(root_mem);
1774                         if (loop >= 2) {
1775                                 /*
1776                                  * If we have not been able to reclaim
1777                                  * anything, it might because there are
1778                                  * no reclaimable pages under this hierarchy
1779                                  */
1780                                 if (!check_soft || !total) {
1781                                         css_put(&victim->css);
1782                                         break;
1783                                 }
1784                                 /*
1785                                  * We want to do more targeted reclaim.
1786                                  * excess >> 2 is not to excessive so as to
1787                                  * reclaim too much, nor too less that we keep
1788                                  * coming back to reclaim from this cgroup
1789                                  */
1790                                 if (total >= (excess >> 2) ||
1791                                         (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) {
1792                                         css_put(&victim->css);
1793                                         break;
1794                                 }
1795                         }
1796                 }
1797                 if (!mem_cgroup_reclaimable(victim, noswap)) {
1798                         /* this cgroup's local usage == 0 */
1799                         css_put(&victim->css);
1800                         continue;
1801                 }
1802                 rec.mem = victim;
1803                 rec.nr_scanned[0] = 0;
1804                 rec.nr_scanned[1] = 0;
1805                 rec.nr_rotated[0] = 0;
1806                 rec.nr_rotated[1] = 0;
1807                 rec.nr_freed[0] = 0;
1808                 rec.nr_freed[1] = 0;
1809                 rec.elapsed = 0;
1810                 /* we use swappiness of local cgroup */
1811                 if (check_soft) {
1812                         ret = mem_cgroup_shrink_node_zone(victim, gfp_mask,
1813                                 noswap, zone, &rec, &scanned);
1814                         *total_scanned += scanned;
1815                 } else
1816                         ret = try_to_free_mem_cgroup_pages(victim, gfp_mask,
1817                                                 noswap, &rec);
1818                 mem_cgroup_record_scanstat(&rec);
1819                 css_put(&victim->css);
1820                 /*
1821                  * At shrinking usage, we can't check we should stop here or
1822                  * reclaim more. It's depends on callers. last_scanned_child
1823                  * will work enough for keeping fairness under tree.
1824                  */
1825                 if (shrink)
1826                         return ret;
1827                 total += ret;
1828                 if (check_soft) {
1829                         if (!res_counter_soft_limit_excess(&root_mem->res))
1830                                 return total;
1831                 } else if (mem_cgroup_margin(root_mem))
1832                         return total;
1833         }
1834         return total;
1835 }
1836
1837 /*
1838  * Check OOM-Killer is already running under our hierarchy.
1839  * If someone is running, return false.
1840  * Has to be called with memcg_oom_lock
1841  */
1842 static bool mem_cgroup_oom_lock(struct mem_cgroup *mem)
1843 {
1844         int lock_count = -1;
1845         struct mem_cgroup *iter, *failed = NULL;
1846         bool cond = true;
1847
1848         for_each_mem_cgroup_tree_cond(iter, mem, cond) {
1849                 bool locked = iter->oom_lock;
1850
1851                 iter->oom_lock = true;
1852                 if (lock_count == -1)
1853                         lock_count = iter->oom_lock;
1854                 else if (lock_count != locked) {
1855                         /*
1856                          * this subtree of our hierarchy is already locked
1857                          * so we cannot give a lock.
1858                          */
1859                         lock_count = 0;
1860                         failed = iter;
1861                         cond = false;
1862                 }
1863         }
1864
1865         if (!failed)
1866                 goto done;
1867
1868         /*
1869          * OK, we failed to lock the whole subtree so we have to clean up
1870          * what we set up to the failing subtree
1871          */
1872         cond = true;
1873         for_each_mem_cgroup_tree_cond(iter, mem, cond) {
1874                 if (iter == failed) {
1875                         cond = false;
1876                         continue;
1877                 }
1878                 iter->oom_lock = false;
1879         }
1880 done:
1881         return lock_count;
1882 }
1883
1884 /*
1885  * Has to be called with memcg_oom_lock
1886  */
1887 static int mem_cgroup_oom_unlock(struct mem_cgroup *mem)
1888 {
1889         struct mem_cgroup *iter;
1890
1891         for_each_mem_cgroup_tree(iter, mem)
1892                 iter->oom_lock = false;
1893         return 0;
1894 }
1895
1896 static void mem_cgroup_mark_under_oom(struct mem_cgroup *mem)
1897 {
1898         struct mem_cgroup *iter;
1899
1900         for_each_mem_cgroup_tree(iter, mem)
1901                 atomic_inc(&iter->under_oom);
1902 }
1903
1904 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *mem)
1905 {
1906         struct mem_cgroup *iter;
1907
1908         /*
1909          * When a new child is created while the hierarchy is under oom,
1910          * mem_cgroup_oom_lock() may not be called. We have to use
1911          * atomic_add_unless() here.
1912          */
1913         for_each_mem_cgroup_tree(iter, mem)
1914                 atomic_add_unless(&iter->under_oom, -1, 0);
1915 }
1916
1917 static DEFINE_SPINLOCK(memcg_oom_lock);
1918 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1919
1920 struct oom_wait_info {
1921         struct mem_cgroup *mem;
1922         wait_queue_t    wait;
1923 };
1924
1925 static int memcg_oom_wake_function(wait_queue_t *wait,
1926         unsigned mode, int sync, void *arg)
1927 {
1928         struct mem_cgroup *wake_mem = (struct mem_cgroup *)arg,
1929                           *oom_wait_mem;
1930         struct oom_wait_info *oom_wait_info;
1931
1932         oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1933         oom_wait_mem = oom_wait_info->mem;
1934
1935         /*
1936          * Both of oom_wait_info->mem and wake_mem are stable under us.
1937          * Then we can use css_is_ancestor without taking care of RCU.
1938          */
1939         if (!mem_cgroup_same_or_subtree(oom_wait_mem, wake_mem)
1940                         && !mem_cgroup_same_or_subtree(wake_mem, oom_wait_mem))
1941                 return 0;
1942         return autoremove_wake_function(wait, mode, sync, arg);
1943 }
1944
1945 static void memcg_wakeup_oom(struct mem_cgroup *mem)
1946 {
1947         /* for filtering, pass "mem" as argument. */
1948         __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, mem);
1949 }
1950
1951 static void memcg_oom_recover(struct mem_cgroup *mem)
1952 {
1953         if (mem && atomic_read(&mem->under_oom))
1954                 memcg_wakeup_oom(mem);
1955 }
1956
1957 /*
1958  * try to call OOM killer. returns false if we should exit memory-reclaim loop.
1959  */
1960 bool mem_cgroup_handle_oom(struct mem_cgroup *mem, gfp_t mask)
1961 {
1962         struct oom_wait_info owait;
1963         bool locked, need_to_kill;
1964
1965         owait.mem = mem;
1966         owait.wait.flags = 0;
1967         owait.wait.func = memcg_oom_wake_function;
1968         owait.wait.private = current;
1969         INIT_LIST_HEAD(&owait.wait.task_list);
1970         need_to_kill = true;
1971         mem_cgroup_mark_under_oom(mem);
1972
1973         /* At first, try to OOM lock hierarchy under mem.*/
1974         spin_lock(&memcg_oom_lock);
1975         locked = mem_cgroup_oom_lock(mem);
1976         /*
1977          * Even if signal_pending(), we can't quit charge() loop without
1978          * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL
1979          * under OOM is always welcomed, use TASK_KILLABLE here.
1980          */
1981         prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1982         if (!locked || mem->oom_kill_disable)
1983                 need_to_kill = false;
1984         if (locked)
1985                 mem_cgroup_oom_notify(mem);
1986         spin_unlock(&memcg_oom_lock);
1987
1988         if (need_to_kill) {
1989                 finish_wait(&memcg_oom_waitq, &owait.wait);
1990                 mem_cgroup_out_of_memory(mem, mask);
1991         } else {
1992                 schedule();
1993                 finish_wait(&memcg_oom_waitq, &owait.wait);
1994         }
1995         spin_lock(&memcg_oom_lock);
1996         if (locked)
1997                 mem_cgroup_oom_unlock(mem);
1998         memcg_wakeup_oom(mem);
1999         spin_unlock(&memcg_oom_lock);
2000
2001         mem_cgroup_unmark_under_oom(mem);
2002
2003         if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current))
2004                 return false;
2005         /* Give chance to dying process */
2006         schedule_timeout(1);
2007         return true;
2008 }
2009
2010 /*
2011  * Currently used to update mapped file statistics, but the routine can be
2012  * generalized to update other statistics as well.
2013  *
2014  * Notes: Race condition
2015  *
2016  * We usually use page_cgroup_lock() for accessing page_cgroup member but
2017  * it tends to be costly. But considering some conditions, we doesn't need
2018  * to do so _always_.
2019  *
2020  * Considering "charge", lock_page_cgroup() is not required because all
2021  * file-stat operations happen after a page is attached to radix-tree. There
2022  * are no race with "charge".
2023  *
2024  * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
2025  * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
2026  * if there are race with "uncharge". Statistics itself is properly handled
2027  * by flags.
2028  *
2029  * Considering "move", this is an only case we see a race. To make the race
2030  * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are
2031  * possibility of race condition. If there is, we take a lock.
2032  */
2033
2034 void mem_cgroup_update_page_stat(struct page *page,
2035                                  enum mem_cgroup_page_stat_item idx, int val)
2036 {
2037         struct mem_cgroup *mem;
2038         struct page_cgroup *pc = lookup_page_cgroup(page);
2039         bool need_unlock = false;
2040         unsigned long uninitialized_var(flags);
2041
2042         if (unlikely(!pc))
2043                 return;
2044
2045         rcu_read_lock();
2046         mem = pc->mem_cgroup;
2047         if (unlikely(!mem || !PageCgroupUsed(pc)))
2048                 goto out;
2049         /* pc->mem_cgroup is unstable ? */
2050         if (unlikely(mem_cgroup_stealed(mem)) || PageTransHuge(page)) {
2051                 /* take a lock against to access pc->mem_cgroup */
2052                 move_lock_page_cgroup(pc, &flags);
2053                 need_unlock = true;
2054                 mem = pc->mem_cgroup;
2055                 if (!mem || !PageCgroupUsed(pc))
2056                         goto out;
2057         }
2058
2059         switch (idx) {
2060         case MEMCG_NR_FILE_MAPPED:
2061                 if (val > 0)
2062                         SetPageCgroupFileMapped(pc);
2063                 else if (!page_mapped(page))
2064                         ClearPageCgroupFileMapped(pc);
2065                 idx = MEM_CGROUP_STAT_FILE_MAPPED;
2066                 break;
2067         default:
2068                 BUG();
2069         }
2070
2071         this_cpu_add(mem->stat->count[idx], val);
2072
2073 out:
2074         if (unlikely(need_unlock))
2075                 move_unlock_page_cgroup(pc, &flags);
2076         rcu_read_unlock();
2077         return;
2078 }
2079 EXPORT_SYMBOL(mem_cgroup_update_page_stat);
2080
2081 /*
2082  * size of first charge trial. "32" comes from vmscan.c's magic value.
2083  * TODO: maybe necessary to use big numbers in big irons.
2084  */
2085 #define CHARGE_BATCH    32U
2086 struct memcg_stock_pcp {
2087         struct mem_cgroup *cached; /* this never be root cgroup */
2088         unsigned int nr_pages;
2089         struct work_struct work;
2090         unsigned long flags;
2091 #define FLUSHING_CACHED_CHARGE  (0)
2092 };
2093 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2094 static DEFINE_MUTEX(percpu_charge_mutex);
2095
2096 /*
2097  * Try to consume stocked charge on this cpu. If success, one page is consumed
2098  * from local stock and true is returned. If the stock is 0 or charges from a
2099  * cgroup which is not current target, returns false. This stock will be
2100  * refilled.
2101  */
2102 static bool consume_stock(struct mem_cgroup *mem)
2103 {
2104         struct memcg_stock_pcp *stock;
2105         bool ret = true;
2106
2107         stock = &get_cpu_var(memcg_stock);
2108         if (mem == stock->cached && stock->nr_pages)
2109                 stock->nr_pages--;
2110         else /* need to call res_counter_charge */
2111                 ret = false;
2112         put_cpu_var(memcg_stock);
2113         return ret;
2114 }
2115
2116 /*
2117  * Returns stocks cached in percpu to res_counter and reset cached information.
2118  */
2119 static void drain_stock(struct memcg_stock_pcp *stock)
2120 {
2121         struct mem_cgroup *old = stock->cached;
2122
2123         if (stock->nr_pages) {
2124                 unsigned long bytes = stock->nr_pages * PAGE_SIZE;
2125
2126                 res_counter_uncharge(&old->res, bytes);
2127                 if (do_swap_account)
2128                         res_counter_uncharge(&old->memsw, bytes);
2129                 stock->nr_pages = 0;
2130         }
2131         stock->cached = NULL;
2132 }
2133
2134 /*
2135  * This must be called under preempt disabled or must be called by
2136  * a thread which is pinned to local cpu.
2137  */
2138 static void drain_local_stock(struct work_struct *dummy)
2139 {
2140         struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock);
2141         drain_stock(stock);
2142         clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2143 }
2144
2145 /*
2146  * Cache charges(val) which is from res_counter, to local per_cpu area.
2147  * This will be consumed by consume_stock() function, later.
2148  */
2149 static void refill_stock(struct mem_cgroup *mem, unsigned int nr_pages)
2150 {
2151         struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2152
2153         if (stock->cached != mem) { /* reset if necessary */
2154                 drain_stock(stock);
2155                 stock->cached = mem;
2156         }
2157         stock->nr_pages += nr_pages;
2158         put_cpu_var(memcg_stock);
2159 }
2160
2161 /*
2162  * Drains all per-CPU charge caches for given root_mem resp. subtree
2163  * of the hierarchy under it. sync flag says whether we should block
2164  * until the work is done.
2165  */
2166 static void drain_all_stock(struct mem_cgroup *root_mem, bool sync)
2167 {
2168         int cpu, curcpu;
2169
2170         /* Notify other cpus that system-wide "drain" is running */
2171         get_online_cpus();
2172         curcpu = get_cpu();
2173         for_each_online_cpu(cpu) {
2174                 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2175                 struct mem_cgroup *mem;
2176
2177                 mem = stock->cached;
2178                 if (!mem || !stock->nr_pages)
2179                         continue;
2180                 if (!mem_cgroup_same_or_subtree(root_mem, mem))
2181                         continue;
2182                 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2183                         if (cpu == curcpu)
2184                                 drain_local_stock(&stock->work);
2185                         else
2186                                 schedule_work_on(cpu, &stock->work);
2187                 }
2188         }
2189         put_cpu();
2190
2191         if (!sync)
2192                 goto out;
2193
2194         for_each_online_cpu(cpu) {
2195                 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2196                 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2197                         flush_work(&stock->work);
2198         }
2199 out:
2200         put_online_cpus();
2201 }
2202
2203 /*
2204  * Tries to drain stocked charges in other cpus. This function is asynchronous
2205  * and just put a work per cpu for draining localy on each cpu. Caller can
2206  * expects some charges will be back to res_counter later but cannot wait for
2207  * it.
2208  */
2209 static void drain_all_stock_async(struct mem_cgroup *root_mem)
2210 {
2211         /*
2212          * If someone calls draining, avoid adding more kworker runs.
2213          */
2214         if (!mutex_trylock(&percpu_charge_mutex))
2215                 return;
2216         drain_all_stock(root_mem, false);
2217         mutex_unlock(&percpu_charge_mutex);
2218 }
2219
2220 /* This is a synchronous drain interface. */
2221 static void drain_all_stock_sync(struct mem_cgroup *root_mem)
2222 {
2223         /* called when force_empty is called */
2224         mutex_lock(&percpu_charge_mutex);
2225         drain_all_stock(root_mem, true);
2226         mutex_unlock(&percpu_charge_mutex);
2227 }
2228
2229 /*
2230  * This function drains percpu counter value from DEAD cpu and
2231  * move it to local cpu. Note that this function can be preempted.
2232  */
2233 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *mem, int cpu)
2234 {
2235         int i;
2236
2237         spin_lock(&mem->pcp_counter_lock);
2238         for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) {
2239                 long x = per_cpu(mem->stat->count[i], cpu);
2240
2241                 per_cpu(mem->stat->count[i], cpu) = 0;
2242                 mem->nocpu_base.count[i] += x;
2243         }
2244         for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2245                 unsigned long x = per_cpu(mem->stat->events[i], cpu);
2246
2247                 per_cpu(mem->stat->events[i], cpu) = 0;
2248                 mem->nocpu_base.events[i] += x;
2249         }
2250         /* need to clear ON_MOVE value, works as a kind of lock. */
2251         per_cpu(mem->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0;
2252         spin_unlock(&mem->pcp_counter_lock);
2253 }
2254
2255 static void synchronize_mem_cgroup_on_move(struct mem_cgroup *mem, int cpu)
2256 {
2257         int idx = MEM_CGROUP_ON_MOVE;
2258
2259         spin_lock(&mem->pcp_counter_lock);
2260         per_cpu(mem->stat->count[idx], cpu) = mem->nocpu_base.count[idx];
2261         spin_unlock(&mem->pcp_counter_lock);
2262 }
2263
2264 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb,
2265                                         unsigned long action,
2266                                         void *hcpu)
2267 {
2268         int cpu = (unsigned long)hcpu;
2269         struct memcg_stock_pcp *stock;
2270         struct mem_cgroup *iter;
2271
2272         if ((action == CPU_ONLINE)) {
2273                 for_each_mem_cgroup_all(iter)
2274                         synchronize_mem_cgroup_on_move(iter, cpu);
2275                 return NOTIFY_OK;
2276         }
2277
2278         if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN)
2279                 return NOTIFY_OK;
2280
2281         for_each_mem_cgroup_all(iter)
2282                 mem_cgroup_drain_pcp_counter(iter, cpu);
2283
2284         stock = &per_cpu(memcg_stock, cpu);
2285         drain_stock(stock);
2286         return NOTIFY_OK;
2287 }
2288
2289
2290 /* See __mem_cgroup_try_charge() for details */
2291 enum {
2292         CHARGE_OK,              /* success */
2293         CHARGE_RETRY,           /* need to retry but retry is not bad */
2294         CHARGE_NOMEM,           /* we can't do more. return -ENOMEM */
2295         CHARGE_WOULDBLOCK,      /* GFP_WAIT wasn't set and no enough res. */
2296         CHARGE_OOM_DIE,         /* the current is killed because of OOM */
2297 };
2298
2299 static int mem_cgroup_do_charge(struct mem_cgroup *mem, gfp_t gfp_mask,
2300                                 unsigned int nr_pages, bool oom_check)
2301 {
2302         unsigned long csize = nr_pages * PAGE_SIZE;
2303         struct mem_cgroup *mem_over_limit;
2304         struct res_counter *fail_res;
2305         unsigned long flags = 0;
2306         int ret;
2307
2308         ret = res_counter_charge(&mem->res, csize, &fail_res);
2309
2310         if (likely(!ret)) {
2311                 if (!do_swap_account)
2312                         return CHARGE_OK;
2313                 ret = res_counter_charge(&mem->memsw, csize, &fail_res);
2314                 if (likely(!ret))
2315                         return CHARGE_OK;
2316
2317                 res_counter_uncharge(&mem->res, csize);
2318                 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw);
2319                 flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2320         } else
2321                 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res);
2322         /*
2323          * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch
2324          * of regular pages (CHARGE_BATCH), or a single regular page (1).
2325          *
2326          * Never reclaim on behalf of optional batching, retry with a
2327          * single page instead.
2328          */
2329         if (nr_pages == CHARGE_BATCH)
2330                 return CHARGE_RETRY;
2331
2332         if (!(gfp_mask & __GFP_WAIT))
2333                 return CHARGE_WOULDBLOCK;
2334
2335         ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL,
2336                                               gfp_mask, flags, NULL);
2337         if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2338                 return CHARGE_RETRY;
2339         /*
2340          * Even though the limit is exceeded at this point, reclaim
2341          * may have been able to free some pages.  Retry the charge
2342          * before killing the task.
2343          *
2344          * Only for regular pages, though: huge pages are rather
2345          * unlikely to succeed so close to the limit, and we fall back
2346          * to regular pages anyway in case of failure.
2347          */
2348         if (nr_pages == 1 && ret)
2349                 return CHARGE_RETRY;
2350
2351         /*
2352          * At task move, charge accounts can be doubly counted. So, it's
2353          * better to wait until the end of task_move if something is going on.
2354          */
2355         if (mem_cgroup_wait_acct_move(mem_over_limit))
2356                 return CHARGE_RETRY;
2357
2358         /* If we don't need to call oom-killer at el, return immediately */
2359         if (!oom_check)
2360                 return CHARGE_NOMEM;
2361         /* check OOM */
2362         if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask))
2363                 return CHARGE_OOM_DIE;
2364
2365         return CHARGE_RETRY;
2366 }
2367
2368 /*
2369  * Unlike exported interface, "oom" parameter is added. if oom==true,
2370  * oom-killer can be invoked.
2371  */
2372 static int __mem_cgroup_try_charge(struct mm_struct *mm,
2373                                    gfp_t gfp_mask,
2374                                    unsigned int nr_pages,
2375                                    struct mem_cgroup **memcg,
2376                                    bool oom)
2377 {
2378         unsigned int batch = max(CHARGE_BATCH, nr_pages);
2379         int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2380         struct mem_cgroup *mem = NULL;
2381         int ret;
2382
2383         /*
2384          * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2385          * in system level. So, allow to go ahead dying process in addition to
2386          * MEMDIE process.
2387          */
2388         if (unlikely(test_thread_flag(TIF_MEMDIE)
2389                      || fatal_signal_pending(current)))
2390                 goto bypass;
2391
2392         /*
2393          * We always charge the cgroup the mm_struct belongs to.
2394          * The mm_struct's mem_cgroup changes on task migration if the
2395          * thread group leader migrates. It's possible that mm is not
2396          * set, if so charge the init_mm (happens for pagecache usage).
2397          */
2398         if (!*memcg && !mm)
2399                 goto bypass;
2400 again:
2401         if (*memcg) { /* css should be a valid one */
2402                 mem = *memcg;
2403                 VM_BUG_ON(css_is_removed(&mem->css));
2404                 if (mem_cgroup_is_root(mem))
2405                         goto done;
2406                 if (nr_pages == 1 && consume_stock(mem))
2407                         goto done;
2408                 css_get(&mem->css);
2409         } else {
2410                 struct task_struct *p;
2411
2412                 rcu_read_lock();
2413                 p = rcu_dereference(mm->owner);
2414                 /*
2415                  * Because we don't have task_lock(), "p" can exit.
2416                  * In that case, "mem" can point to root or p can be NULL with
2417                  * race with swapoff. Then, we have small risk of mis-accouning.
2418                  * But such kind of mis-account by race always happens because
2419                  * we don't have cgroup_mutex(). It's overkill and we allo that
2420                  * small race, here.
2421                  * (*) swapoff at el will charge against mm-struct not against
2422                  * task-struct. So, mm->owner can be NULL.
2423                  */
2424                 mem = mem_cgroup_from_task(p);
2425                 if (!mem || mem_cgroup_is_root(mem)) {
2426                         rcu_read_unlock();
2427                         goto done;
2428                 }
2429                 if (nr_pages == 1 && consume_stock(mem)) {
2430                         /*
2431                          * It seems dagerous to access memcg without css_get().
2432                          * But considering how consume_stok works, it's not
2433                          * necessary. If consume_stock success, some charges
2434                          * from this memcg are cached on this cpu. So, we
2435                          * don't need to call css_get()/css_tryget() before
2436                          * calling consume_stock().
2437                          */
2438                         rcu_read_unlock();
2439                         goto done;
2440                 }
2441                 /* after here, we may be blocked. we need to get refcnt */
2442                 if (!css_tryget(&mem->css)) {
2443                         rcu_read_unlock();
2444                         goto again;
2445                 }
2446                 rcu_read_unlock();
2447         }
2448
2449         do {
2450                 bool oom_check;
2451
2452                 /* If killed, bypass charge */
2453                 if (fatal_signal_pending(current)) {
2454                         css_put(&mem->css);
2455                         goto bypass;
2456                 }
2457
2458                 oom_check = false;
2459                 if (oom && !nr_oom_retries) {
2460                         oom_check = true;
2461                         nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2462                 }
2463
2464                 ret = mem_cgroup_do_charge(mem, gfp_mask, batch, oom_check);
2465                 switch (ret) {
2466                 case CHARGE_OK:
2467                         break;
2468                 case CHARGE_RETRY: /* not in OOM situation but retry */
2469                         batch = nr_pages;
2470                         css_put(&mem->css);
2471                         mem = NULL;
2472                         goto again;
2473                 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2474                         css_put(&mem->css);
2475                         goto nomem;
2476                 case CHARGE_NOMEM: /* OOM routine works */
2477                         if (!oom) {
2478                                 css_put(&mem->css);
2479                                 goto nomem;
2480                         }
2481                         /* If oom, we never return -ENOMEM */
2482                         nr_oom_retries--;
2483                         break;
2484                 case CHARGE_OOM_DIE: /* Killed by OOM Killer */
2485                         css_put(&mem->css);
2486                         goto bypass;
2487                 }
2488         } while (ret != CHARGE_OK);
2489
2490         if (batch > nr_pages)
2491                 refill_stock(mem, batch - nr_pages);
2492         css_put(&mem->css);
2493 done:
2494         *memcg = mem;
2495         return 0;
2496 nomem:
2497         *memcg = NULL;
2498         return -ENOMEM;
2499 bypass:
2500         *memcg = NULL;
2501         return 0;
2502 }
2503
2504 /*
2505  * Somemtimes we have to undo a charge we got by try_charge().
2506  * This function is for that and do uncharge, put css's refcnt.
2507  * gotten by try_charge().
2508  */
2509 static void __mem_cgroup_cancel_charge(struct mem_cgroup *mem,
2510                                        unsigned int nr_pages)
2511 {
2512         if (!mem_cgroup_is_root(mem)) {
2513                 unsigned long bytes = nr_pages * PAGE_SIZE;
2514
2515                 res_counter_uncharge(&mem->res, bytes);
2516                 if (do_swap_account)
2517                         res_counter_uncharge(&mem->memsw, bytes);
2518         }
2519 }
2520
2521 /*
2522  * A helper function to get mem_cgroup from ID. must be called under
2523  * rcu_read_lock(). The caller must check css_is_removed() or some if
2524  * it's concern. (dropping refcnt from swap can be called against removed
2525  * memcg.)
2526  */
2527 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2528 {
2529         struct cgroup_subsys_state *css;
2530
2531         /* ID 0 is unused ID */
2532         if (!id)
2533                 return NULL;
2534         css = css_lookup(&mem_cgroup_subsys, id);
2535         if (!css)
2536                 return NULL;
2537         return container_of(css, struct mem_cgroup, css);
2538 }
2539
2540 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2541 {
2542         struct mem_cgroup *mem = NULL;
2543         struct page_cgroup *pc;
2544         unsigned short id;
2545         swp_entry_t ent;
2546
2547         VM_BUG_ON(!PageLocked(page));
2548
2549         pc = lookup_page_cgroup(page);
2550         lock_page_cgroup(pc);
2551         if (PageCgroupUsed(pc)) {
2552                 mem = pc->mem_cgroup;
2553                 if (mem && !css_tryget(&mem->css))
2554                         mem = NULL;
2555         } else if (PageSwapCache(page)) {
2556                 ent.val = page_private(page);
2557                 id = lookup_swap_cgroup(ent);
2558                 rcu_read_lock();
2559                 mem = mem_cgroup_lookup(id);
2560                 if (mem && !css_tryget(&mem->css))
2561                         mem = NULL;
2562                 rcu_read_unlock();
2563         }
2564         unlock_page_cgroup(pc);
2565         return mem;
2566 }
2567
2568 static void __mem_cgroup_commit_charge(struct mem_cgroup *mem,
2569                                        struct page *page,
2570                                        unsigned int nr_pages,
2571                                        struct page_cgroup *pc,
2572                                        enum charge_type ctype)
2573 {
2574         lock_page_cgroup(pc);
2575         if (unlikely(PageCgroupUsed(pc))) {
2576                 unlock_page_cgroup(pc);
2577                 __mem_cgroup_cancel_charge(mem, nr_pages);
2578                 return;
2579         }
2580         /*
2581          * we don't need page_cgroup_lock about tail pages, becase they are not
2582          * accessed by any other context at this point.
2583          */
2584         pc->mem_cgroup = mem;
2585         /*
2586          * We access a page_cgroup asynchronously without lock_page_cgroup().
2587          * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
2588          * is accessed after testing USED bit. To make pc->mem_cgroup visible
2589          * before USED bit, we need memory barrier here.
2590          * See mem_cgroup_add_lru_list(), etc.
2591          */
2592         smp_wmb();
2593         switch (ctype) {
2594         case MEM_CGROUP_CHARGE_TYPE_CACHE:
2595         case MEM_CGROUP_CHARGE_TYPE_SHMEM:
2596                 SetPageCgroupCache(pc);
2597                 SetPageCgroupUsed(pc);
2598                 break;
2599         case MEM_CGROUP_CHARGE_TYPE_MAPPED:
2600                 ClearPageCgroupCache(pc);
2601                 SetPageCgroupUsed(pc);
2602                 break;
2603         default:
2604                 break;
2605         }
2606
2607         mem_cgroup_charge_statistics(mem, PageCgroupCache(pc), nr_pages);
2608         unlock_page_cgroup(pc);
2609         /*
2610          * "charge_statistics" updated event counter. Then, check it.
2611          * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
2612          * if they exceeds softlimit.
2613          */
2614         memcg_check_events(mem, page);
2615 }
2616
2617 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2618
2619 #define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\
2620                         (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION))
2621 /*
2622  * Because tail pages are not marked as "used", set it. We're under
2623  * zone->lru_lock, 'splitting on pmd' and compund_lock.
2624  */
2625 void mem_cgroup_split_huge_fixup(struct page *head, struct page *tail)
2626 {
2627         struct page_cgroup *head_pc = lookup_page_cgroup(head);
2628         struct page_cgroup *tail_pc = lookup_page_cgroup(tail);
2629         unsigned long flags;
2630
2631         if (mem_cgroup_disabled())
2632                 return;
2633         /*
2634          * We have no races with charge/uncharge but will have races with
2635          * page state accounting.
2636          */
2637         move_lock_page_cgroup(head_pc, &flags);
2638
2639         tail_pc->mem_cgroup = head_pc->mem_cgroup;
2640         smp_wmb(); /* see __commit_charge() */
2641         if (PageCgroupAcctLRU(head_pc)) {
2642                 enum lru_list lru;
2643                 struct mem_cgroup_per_zone *mz;
2644
2645                 /*
2646                  * LRU flags cannot be copied because we need to add tail
2647                  *.page to LRU by generic call and our hook will be called.
2648                  * We hold lru_lock, then, reduce counter directly.
2649                  */
2650                 lru = page_lru(head);
2651                 mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head);
2652                 MEM_CGROUP_ZSTAT(mz, lru) -= 1;
2653         }
2654         tail_pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
2655         move_unlock_page_cgroup(head_pc, &flags);
2656 }
2657 #endif
2658
2659 /**
2660  * mem_cgroup_move_account - move account of the page
2661  * @page: the page
2662  * @nr_pages: number of regular pages (>1 for huge pages)
2663  * @pc: page_cgroup of the page.
2664  * @from: mem_cgroup which the page is moved from.
2665  * @to: mem_cgroup which the page is moved to. @from != @to.
2666  * @uncharge: whether we should call uncharge and css_put against @from.
2667  *
2668  * The caller must confirm following.
2669  * - page is not on LRU (isolate_page() is useful.)
2670  * - compound_lock is held when nr_pages > 1
2671  *
2672  * This function doesn't do "charge" nor css_get to new cgroup. It should be
2673  * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is
2674  * true, this function does "uncharge" from old cgroup, but it doesn't if
2675  * @uncharge is false, so a caller should do "uncharge".
2676  */
2677 static int mem_cgroup_move_account(struct page *page,
2678                                    unsigned int nr_pages,
2679                                    struct page_cgroup *pc,
2680                                    struct mem_cgroup *from,
2681                                    struct mem_cgroup *to,
2682                                    bool uncharge)
2683 {
2684         unsigned long flags;
2685         int ret;
2686
2687         VM_BUG_ON(from == to);
2688         VM_BUG_ON(PageLRU(page));
2689         /*
2690          * The page is isolated from LRU. So, collapse function
2691          * will not handle this page. But page splitting can happen.
2692          * Do this check under compound_page_lock(). The caller should
2693          * hold it.
2694          */
2695         ret = -EBUSY;
2696         if (nr_pages > 1 && !PageTransHuge(page))
2697                 goto out;
2698
2699         lock_page_cgroup(pc);
2700
2701         ret = -EINVAL;
2702         if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
2703                 goto unlock;
2704
2705         move_lock_page_cgroup(pc, &flags);
2706
2707         if (PageCgroupFileMapped(pc)) {
2708                 /* Update mapped_file data for mem_cgroup */
2709                 preempt_disable();
2710                 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2711                 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
2712                 preempt_enable();
2713         }
2714         mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages);
2715         if (uncharge)
2716                 /* This is not "cancel", but cancel_charge does all we need. */
2717                 __mem_cgroup_cancel_charge(from, nr_pages);
2718
2719         /* caller should have done css_get */
2720         pc->mem_cgroup = to;
2721         mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages);
2722         /*
2723          * We charges against "to" which may not have any tasks. Then, "to"
2724          * can be under rmdir(). But in current implementation, caller of
2725          * this function is just force_empty() and move charge, so it's
2726          * guaranteed that "to" is never removed. So, we don't check rmdir
2727          * status here.
2728          */
2729         move_unlock_page_cgroup(pc, &flags);
2730         ret = 0;
2731 unlock:
2732         unlock_page_cgroup(pc);
2733         /*
2734          * check events
2735          */
2736         memcg_check_events(to, page);
2737         memcg_check_events(from, page);
2738 out:
2739         return ret;
2740 }
2741
2742 /*
2743  * move charges to its parent.
2744  */
2745
2746 static int mem_cgroup_move_parent(struct page *page,
2747                                   struct page_cgroup *pc,
2748                                   struct mem_cgroup *child,
2749                                   gfp_t gfp_mask)
2750 {
2751         struct cgroup *cg = child->css.cgroup;
2752         struct cgroup *pcg = cg->parent;
2753         struct mem_cgroup *parent;
2754         unsigned int nr_pages;
2755         unsigned long uninitialized_var(flags);
2756         int ret;
2757
2758         /* Is ROOT ? */
2759         if (!pcg)
2760                 return -EINVAL;
2761
2762         ret = -EBUSY;
2763         if (!get_page_unless_zero(page))
2764                 goto out;
2765         if (isolate_lru_page(page))
2766                 goto put;
2767
2768         nr_pages = hpage_nr_pages(page);
2769
2770         parent = mem_cgroup_from_cont(pcg);
2771         ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false);
2772         if (ret || !parent)
2773                 goto put_back;
2774
2775         if (nr_pages > 1)
2776                 flags = compound_lock_irqsave(page);
2777
2778         ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true);
2779         if (ret)
2780                 __mem_cgroup_cancel_charge(parent, nr_pages);
2781
2782         if (nr_pages > 1)
2783                 compound_unlock_irqrestore(page, flags);
2784 put_back:
2785         putback_lru_page(page);
2786 put:
2787         put_page(page);
2788 out:
2789         return ret;
2790 }
2791
2792 /*
2793  * Charge the memory controller for page usage.
2794  * Return
2795  * 0 if the charge was successful
2796  * < 0 if the cgroup is over its limit
2797  */
2798 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
2799                                 gfp_t gfp_mask, enum charge_type ctype)
2800 {
2801         struct mem_cgroup *mem = NULL;
2802         unsigned int nr_pages = 1;
2803         struct page_cgroup *pc;
2804         bool oom = true;
2805         int ret;
2806
2807         if (PageTransHuge(page)) {
2808                 nr_pages <<= compound_order(page);
2809                 VM_BUG_ON(!PageTransHuge(page));
2810                 /*
2811                  * Never OOM-kill a process for a huge page.  The
2812                  * fault handler will fall back to regular pages.
2813                  */
2814                 oom = false;
2815         }
2816
2817         pc = lookup_page_cgroup(page);
2818         BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */
2819
2820         ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &mem, oom);
2821         if (ret || !mem)
2822                 return ret;
2823
2824         __mem_cgroup_commit_charge(mem, page, nr_pages, pc, ctype);
2825         return 0;
2826 }
2827
2828 int mem_cgroup_newpage_charge(struct page *page,
2829                               struct mm_struct *mm, gfp_t gfp_mask)
2830 {
2831         if (mem_cgroup_disabled())
2832                 return 0;
2833         /*
2834          * If already mapped, we don't have to account.
2835          * If page cache, page->mapping has address_space.
2836          * But page->mapping may have out-of-use anon_vma pointer,
2837          * detecit it by PageAnon() check. newly-mapped-anon's page->mapping
2838          * is NULL.
2839          */
2840         if (page_mapped(page) || (page->mapping && !PageAnon(page)))
2841                 return 0;
2842         if (unlikely(!mm))
2843                 mm = &init_mm;
2844         return mem_cgroup_charge_common(page, mm, gfp_mask,
2845                                 MEM_CGROUP_CHARGE_TYPE_MAPPED);
2846 }
2847
2848 static void
2849 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2850                                         enum charge_type ctype);
2851
2852 static void
2853 __mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *mem,
2854                                         enum charge_type ctype)
2855 {
2856         struct page_cgroup *pc = lookup_page_cgroup(page);
2857         /*
2858          * In some case, SwapCache, FUSE(splice_buf->radixtree), the page
2859          * is already on LRU. It means the page may on some other page_cgroup's
2860          * LRU. Take care of it.
2861          */
2862         mem_cgroup_lru_del_before_commit(page);
2863         __mem_cgroup_commit_charge(mem, page, 1, pc, ctype);
2864         mem_cgroup_lru_add_after_commit(page);
2865         return;
2866 }
2867
2868 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
2869                                 gfp_t gfp_mask)
2870 {
2871         struct mem_cgroup *mem = NULL;
2872         int ret;
2873
2874         if (mem_cgroup_disabled())
2875                 return 0;
2876         if (PageCompound(page))
2877                 return 0;
2878
2879         if (unlikely(!mm))
2880                 mm = &init_mm;
2881
2882         if (page_is_file_cache(page)) {
2883                 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, &mem, true);
2884                 if (ret || !mem)
2885                         return ret;
2886
2887                 /*
2888                  * FUSE reuses pages without going through the final
2889                  * put that would remove them from the LRU list, make
2890                  * sure that they get relinked properly.
2891                  */
2892                 __mem_cgroup_commit_charge_lrucare(page, mem,
2893                                         MEM_CGROUP_CHARGE_TYPE_CACHE);
2894                 return ret;
2895         }
2896         /* shmem */
2897         if (PageSwapCache(page)) {
2898                 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &mem);
2899                 if (!ret)
2900                         __mem_cgroup_commit_charge_swapin(page, mem,
2901                                         MEM_CGROUP_CHARGE_TYPE_SHMEM);
2902         } else
2903                 ret = mem_cgroup_charge_common(page, mm, gfp_mask,
2904                                         MEM_CGROUP_CHARGE_TYPE_SHMEM);
2905
2906         return ret;
2907 }
2908
2909 /*
2910  * While swap-in, try_charge -> commit or cancel, the page is locked.
2911  * And when try_charge() successfully returns, one refcnt to memcg without
2912  * struct page_cgroup is acquired. This refcnt will be consumed by
2913  * "commit()" or removed by "cancel()"
2914  */
2915 int mem_cgroup_try_charge_swapin(struct mm_struct *mm,
2916                                  struct page *page,
2917                                  gfp_t mask, struct mem_cgroup **ptr)
2918 {
2919         struct mem_cgroup *mem;
2920         int ret;
2921
2922         *ptr = NULL;
2923
2924         if (mem_cgroup_disabled())
2925                 return 0;
2926
2927         if (!do_swap_account)
2928                 goto charge_cur_mm;
2929         /*
2930          * A racing thread's fault, or swapoff, may have already updated
2931          * the pte, and even removed page from swap cache: in those cases
2932          * do_swap_page()'s pte_same() test will fail; but there's also a
2933          * KSM case which does need to charge the page.
2934          */
2935         if (!PageSwapCache(page))
2936                 goto charge_cur_mm;
2937         mem = try_get_mem_cgroup_from_page(page);
2938         if (!mem)
2939                 goto charge_cur_mm;
2940         *ptr = mem;
2941         ret = __mem_cgroup_try_charge(NULL, mask, 1, ptr, true);
2942         css_put(&mem->css);
2943         return ret;
2944 charge_cur_mm:
2945         if (unlikely(!mm))
2946                 mm = &init_mm;
2947         return __mem_cgroup_try_charge(mm, mask, 1, ptr, true);
2948 }
2949
2950 static void
2951 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr,
2952                                         enum charge_type ctype)
2953 {
2954         if (mem_cgroup_disabled())
2955                 return;
2956         if (!ptr)
2957                 return;
2958         cgroup_exclude_rmdir(&ptr->css);
2959
2960         __mem_cgroup_commit_charge_lrucare(page, ptr, ctype);
2961         /*
2962          * Now swap is on-memory. This means this page may be
2963          * counted both as mem and swap....double count.
2964          * Fix it by uncharging from memsw. Basically, this SwapCache is stable
2965          * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
2966          * may call delete_from_swap_cache() before reach here.
2967          */
2968         if (do_swap_account && PageSwapCache(page)) {
2969                 swp_entry_t ent = {.val = page_private(page)};
2970                 unsigned short id;
2971                 struct mem_cgroup *memcg;
2972
2973                 id = swap_cgroup_record(ent, 0);
2974                 rcu_read_lock();
2975                 memcg = mem_cgroup_lookup(id);
2976                 if (memcg) {
2977                         /*
2978                          * This recorded memcg can be obsolete one. So, avoid
2979                          * calling css_tryget
2980                          */
2981                         if (!mem_cgroup_is_root(memcg))
2982                                 res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
2983                         mem_cgroup_swap_statistics(memcg, false);
2984                         mem_cgroup_put(memcg);
2985                 }
2986                 rcu_read_unlock();
2987         }
2988         /*
2989          * At swapin, we may charge account against cgroup which has no tasks.
2990          * So, rmdir()->pre_destroy() can be called while we do this charge.
2991          * In that case, we need to call pre_destroy() again. check it here.
2992          */
2993         cgroup_release_and_wakeup_rmdir(&ptr->css);
2994 }
2995
2996 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr)
2997 {
2998         __mem_cgroup_commit_charge_swapin(page, ptr,
2999                                         MEM_CGROUP_CHARGE_TYPE_MAPPED);
3000 }
3001
3002 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *mem)
3003 {
3004         if (mem_cgroup_disabled())
3005                 return;
3006         if (!mem)
3007                 return;
3008         __mem_cgroup_cancel_charge(mem, 1);
3009 }
3010
3011 static void mem_cgroup_do_uncharge(struct mem_cgroup *mem,
3012                                    unsigned int nr_pages,
3013                                    const enum charge_type ctype)
3014 {
3015         struct memcg_batch_info *batch = NULL;
3016         bool uncharge_memsw = true;
3017
3018         /* If swapout, usage of swap doesn't decrease */
3019         if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
3020                 uncharge_memsw = false;
3021
3022         batch = &current->memcg_batch;
3023         /*
3024          * In usual, we do css_get() when we remember memcg pointer.
3025          * But in this case, we keep res->usage until end of a series of
3026          * uncharges. Then, it's ok to ignore memcg's refcnt.
3027          */
3028         if (!batch->memcg)
3029                 batch->memcg = mem;
3030         /*
3031          * do_batch > 0 when unmapping pages or inode invalidate/truncate.
3032          * In those cases, all pages freed continuously can be expected to be in
3033          * the same cgroup and we have chance to coalesce uncharges.
3034          * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
3035          * because we want to do uncharge as soon as possible.
3036          */
3037
3038         if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
3039                 goto direct_uncharge;
3040
3041         if (nr_pages > 1)
3042                 goto direct_uncharge;
3043
3044         /*
3045          * In typical case, batch->memcg == mem. This means we can
3046          * merge a series of uncharges to an uncharge of res_counter.
3047          * If not, we uncharge res_counter ony by one.
3048          */
3049         if (batch->memcg != mem)
3050                 goto direct_uncharge;
3051         /* remember freed charge and uncharge it later */
3052         batch->nr_pages++;
3053         if (uncharge_memsw)
3054                 batch->memsw_nr_pages++;
3055         return;
3056 direct_uncharge:
3057         res_counter_uncharge(&mem->res, nr_pages * PAGE_SIZE);
3058         if (uncharge_memsw)
3059                 res_counter_uncharge(&mem->memsw, nr_pages * PAGE_SIZE);
3060         if (unlikely(batch->memcg != mem))
3061                 memcg_oom_recover(mem);
3062         return;
3063 }
3064
3065 /*
3066  * uncharge if !page_mapped(page)
3067  */
3068 static struct mem_cgroup *
3069 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype)
3070 {
3071         struct mem_cgroup *mem = NULL;
3072         unsigned int nr_pages = 1;
3073         struct page_cgroup *pc;
3074
3075         if (mem_cgroup_disabled())
3076                 return NULL;
3077
3078         if (PageSwapCache(page))
3079                 return NULL;
3080
3081         if (PageTransHuge(page)) {
3082                 nr_pages <<= compound_order(page);
3083                 VM_BUG_ON(!PageTransHuge(page));
3084         }
3085         /*
3086          * Check if our page_cgroup is valid
3087          */
3088         pc = lookup_page_cgroup(page);
3089         if (unlikely(!pc || !PageCgroupUsed(pc)))
3090                 return NULL;
3091
3092         lock_page_cgroup(pc);
3093
3094         mem = pc->mem_cgroup;
3095
3096         if (!PageCgroupUsed(pc))
3097                 goto unlock_out;
3098
3099         switch (ctype) {
3100         case MEM_CGROUP_CHARGE_TYPE_MAPPED:
3101         case MEM_CGROUP_CHARGE_TYPE_DROP:
3102                 /* See mem_cgroup_prepare_migration() */
3103                 if (page_mapped(page) || PageCgroupMigration(pc))
3104                         goto unlock_out;
3105                 break;
3106         case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
3107                 if (!PageAnon(page)) {  /* Shared memory */
3108                         if (page->mapping && !page_is_file_cache(page))
3109                                 goto unlock_out;
3110                 } else if (page_mapped(page)) /* Anon */
3111                                 goto unlock_out;
3112                 break;
3113         default:
3114                 break;
3115         }
3116
3117         mem_cgroup_charge_statistics(mem, PageCgroupCache(pc), -nr_pages);
3118
3119         ClearPageCgroupUsed(pc);
3120         /*
3121          * pc->mem_cgroup is not cleared here. It will be accessed when it's
3122          * freed from LRU. This is safe because uncharged page is expected not
3123          * to be reused (freed soon). Exception is SwapCache, it's handled by
3124          * special functions.
3125          */
3126
3127         unlock_page_cgroup(pc);
3128         /*
3129          * even after unlock, we have mem->res.usage here and this memcg
3130          * will never be freed.
3131          */
3132         memcg_check_events(mem, page);
3133         if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
3134                 mem_cgroup_swap_statistics(mem, true);
3135                 mem_cgroup_get(mem);
3136         }
3137         if (!mem_cgroup_is_root(mem))
3138                 mem_cgroup_do_uncharge(mem, nr_pages, ctype);
3139
3140         return mem;
3141
3142 unlock_out:
3143         unlock_page_cgroup(pc);
3144         return NULL;
3145 }
3146
3147 void mem_cgroup_uncharge_page(struct page *page)
3148 {
3149         /* early check. */
3150         if (page_mapped(page))
3151                 return;
3152         if (page->mapping && !PageAnon(page))
3153                 return;
3154         __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED);
3155 }
3156
3157 void mem_cgroup_uncharge_cache_page(struct page *page)
3158 {
3159         VM_BUG_ON(page_mapped(page));
3160         VM_BUG_ON(page->mapping);
3161         __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE);
3162 }
3163
3164 /*
3165  * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
3166  * In that cases, pages are freed continuously and we can expect pages
3167  * are in the same memcg. All these calls itself limits the number of
3168  * pages freed at once, then uncharge_start/end() is called properly.
3169  * This may be called prural(2) times in a context,
3170  */
3171
3172 void mem_cgroup_uncharge_start(void)
3173 {
3174         current->memcg_batch.do_batch++;
3175         /* We can do nest. */
3176         if (current->memcg_batch.do_batch == 1) {
3177                 current->memcg_batch.memcg = NULL;
3178                 current->memcg_batch.nr_pages = 0;
3179                 current->memcg_batch.memsw_nr_pages = 0;
3180         }
3181 }
3182
3183 void mem_cgroup_uncharge_end(void)
3184 {
3185         struct memcg_batch_info *batch = &current->memcg_batch;
3186
3187         if (!batch->do_batch)
3188                 return;
3189
3190         batch->do_batch--;
3191         if (batch->do_batch) /* If stacked, do nothing. */
3192                 return;
3193
3194         if (!batch->memcg)
3195                 return;
3196         /*
3197          * This "batch->memcg" is valid without any css_get/put etc...
3198          * bacause we hide charges behind us.
3199          */
3200         if (batch->nr_pages)
3201                 res_counter_uncharge(&batch->memcg->res,
3202                                      batch->nr_pages * PAGE_SIZE);
3203         if (batch->memsw_nr_pages)
3204                 res_counter_uncharge(&batch->memcg->memsw,
3205                                      batch->memsw_nr_pages * PAGE_SIZE);
3206         memcg_oom_recover(batch->memcg);
3207         /* forget this pointer (for sanity check) */
3208         batch->memcg = NULL;
3209 }
3210
3211 #ifdef CONFIG_SWAP
3212 /*
3213  * called after __delete_from_swap_cache() and drop "page" account.
3214  * memcg information is recorded to swap_cgroup of "ent"
3215  */
3216 void
3217 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
3218 {
3219         struct mem_cgroup *memcg;
3220         int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
3221
3222         if (!swapout) /* this was a swap cache but the swap is unused ! */
3223                 ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
3224
3225         memcg = __mem_cgroup_uncharge_common(page, ctype);
3226
3227         /*
3228          * record memcg information,  if swapout && memcg != NULL,
3229          * mem_cgroup_get() was called in uncharge().
3230          */
3231         if (do_swap_account && swapout && memcg)
3232                 swap_cgroup_record(ent, css_id(&memcg->css));
3233 }
3234 #endif
3235
3236 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
3237 /*
3238  * called from swap_entry_free(). remove record in swap_cgroup and
3239  * uncharge "memsw" account.
3240  */
3241 void mem_cgroup_uncharge_swap(swp_entry_t ent)
3242 {
3243         struct mem_cgroup *memcg;
3244         unsigned short id;
3245
3246         if (!do_swap_account)
3247                 return;
3248
3249         id = swap_cgroup_record(ent, 0);
3250         rcu_read_lock();
3251         memcg = mem_cgroup_lookup(id);
3252         if (memcg) {
3253                 /*
3254                  * We uncharge this because swap is freed.
3255                  * This memcg can be obsolete one. We avoid calling css_tryget
3256                  */
3257                 if (!mem_cgroup_is_root(memcg))
3258                         res_counter_uncharge(&memcg->memsw, PAGE_SIZE);
3259                 mem_cgroup_swap_statistics(memcg, false);
3260                 mem_cgroup_put(memcg);
3261         }
3262         rcu_read_unlock();
3263 }
3264
3265 /**
3266  * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3267  * @entry: swap entry to be moved
3268  * @from:  mem_cgroup which the entry is moved from
3269  * @to:  mem_cgroup which the entry is moved to
3270  * @need_fixup: whether we should fixup res_counters and refcounts.
3271  *
3272  * It succeeds only when the swap_cgroup's record for this entry is the same
3273  * as the mem_cgroup's id of @from.
3274  *
3275  * Returns 0 on success, -EINVAL on failure.
3276  *
3277  * The caller must have charged to @to, IOW, called res_counter_charge() about
3278  * both res and memsw, and called css_get().
3279  */
3280 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3281                 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3282 {
3283         unsigned short old_id, new_id;
3284
3285         old_id = css_id(&from->css);
3286         new_id = css_id(&to->css);
3287
3288         if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3289                 mem_cgroup_swap_statistics(from, false);
3290                 mem_cgroup_swap_statistics(to, true);
3291                 /*
3292                  * This function is only called from task migration context now.
3293                  * It postpones res_counter and refcount handling till the end
3294                  * of task migration(mem_cgroup_clear_mc()) for performance
3295                  * improvement. But we cannot postpone mem_cgroup_get(to)
3296                  * because if the process that has been moved to @to does
3297                  * swap-in, the refcount of @to might be decreased to 0.
3298                  */
3299                 mem_cgroup_get(to);
3300                 if (need_fixup) {
3301                         if (!mem_cgroup_is_root(from))
3302                                 res_counter_uncharge(&from->memsw, PAGE_SIZE);
3303                         mem_cgroup_put(from);
3304                         /*
3305                          * we charged both to->res and to->memsw, so we should
3306                          * uncharge to->res.
3307                          */
3308                         if (!mem_cgroup_is_root(to))
3309                                 res_counter_uncharge(&to->res, PAGE_SIZE);
3310                 }
3311                 return 0;
3312         }
3313         return -EINVAL;
3314 }
3315 #else
3316 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3317                 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup)
3318 {
3319         return -EINVAL;
3320 }
3321 #endif
3322
3323 /*
3324  * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
3325  * page belongs to.
3326  */
3327 int mem_cgroup_prepare_migration(struct page *page,
3328         struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask)
3329 {
3330         struct mem_cgroup *mem = NULL;
3331         struct page_cgroup *pc;
3332         enum charge_type ctype;
3333         int ret = 0;
3334
3335         *ptr = NULL;
3336
3337         VM_BUG_ON(PageTransHuge(page));
3338         if (mem_cgroup_disabled())
3339                 return 0;
3340
3341         pc = lookup_page_cgroup(page);
3342         lock_page_cgroup(pc);
3343         if (PageCgroupUsed(pc)) {
3344                 mem = pc->mem_cgroup;
3345                 css_get(&mem->css);
3346                 /*
3347                  * At migrating an anonymous page, its mapcount goes down
3348                  * to 0 and uncharge() will be called. But, even if it's fully
3349                  * unmapped, migration may fail and this page has to be
3350                  * charged again. We set MIGRATION flag here and delay uncharge
3351                  * until end_migration() is called
3352                  *
3353                  * Corner Case Thinking
3354                  * A)
3355                  * When the old page was mapped as Anon and it's unmap-and-freed
3356                  * while migration was ongoing.
3357                  * If unmap finds the old page, uncharge() of it will be delayed
3358                  * until end_migration(). If unmap finds a new page, it's
3359                  * uncharged when it make mapcount to be 1->0. If unmap code
3360                  * finds swap_migration_entry, the new page will not be mapped
3361                  * and end_migration() will find it(mapcount==0).
3362                  *
3363                  * B)
3364                  * When the old page was mapped but migraion fails, the kernel
3365                  * remaps it. A charge for it is kept by MIGRATION flag even
3366                  * if mapcount goes down to 0. We can do remap successfully
3367                  * without charging it again.
3368                  *
3369                  * C)
3370                  * The "old" page is under lock_page() until the end of
3371                  * migration, so, the old page itself will not be swapped-out.
3372                  * If the new page is swapped out before end_migraton, our
3373                  * hook to usual swap-out path will catch the event.
3374                  */
3375                 if (PageAnon(page))
3376                         SetPageCgroupMigration(pc);
3377         }
3378         unlock_page_cgroup(pc);
3379         /*
3380          * If the page is not charged at this point,
3381          * we return here.
3382          */
3383         if (!mem)
3384                 return 0;
3385
3386         *ptr = mem;
3387         ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, ptr, false);
3388         css_put(&mem->css);/* drop extra refcnt */
3389         if (ret || *ptr == NULL) {
3390                 if (PageAnon(page)) {
3391                         lock_page_cgroup(pc);
3392                         ClearPageCgroupMigration(pc);
3393                         unlock_page_cgroup(pc);
3394                         /*
3395                          * The old page may be fully unmapped while we kept it.
3396                          */
3397                         mem_cgroup_uncharge_page(page);
3398                 }
3399                 return -ENOMEM;
3400         }
3401         /*
3402          * We charge new page before it's used/mapped. So, even if unlock_page()
3403          * is called before end_migration, we can catch all events on this new
3404          * page. In the case new page is migrated but not remapped, new page's
3405          * mapcount will be finally 0 and we call uncharge in end_migration().
3406          */
3407         pc = lookup_page_cgroup(newpage);
3408         if (PageAnon(page))
3409                 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED;
3410         else if (page_is_file_cache(page))
3411                 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
3412         else
3413                 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM;
3414         __mem_cgroup_commit_charge(mem, page, 1, pc, ctype);
3415         return ret;
3416 }
3417
3418 /* remove redundant charge if migration failed*/
3419 void mem_cgroup_end_migration(struct mem_cgroup *mem,
3420         struct page *oldpage, struct page *newpage, bool migration_ok)
3421 {
3422         struct page *used, *unused;
3423         struct page_cgroup *pc;
3424
3425         if (!mem)
3426                 return;
3427         /* blocks rmdir() */
3428         cgroup_exclude_rmdir(&mem->css);
3429         if (!migration_ok) {
3430                 used = oldpage;
3431                 unused = newpage;
3432         } else {
3433                 used = newpage;
3434                 unused = oldpage;
3435         }
3436         /*
3437          * We disallowed uncharge of pages under migration because mapcount
3438          * of the page goes down to zero, temporarly.
3439          * Clear the flag and check the page should be charged.
3440          */
3441         pc = lookup_page_cgroup(oldpage);
3442         lock_page_cgroup(pc);
3443         ClearPageCgroupMigration(pc);
3444         unlock_page_cgroup(pc);
3445
3446         __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE);
3447
3448         /*
3449          * If a page is a file cache, radix-tree replacement is very atomic
3450          * and we can skip this check. When it was an Anon page, its mapcount
3451          * goes down to 0. But because we added MIGRATION flage, it's not
3452          * uncharged yet. There are several case but page->mapcount check
3453          * and USED bit check in mem_cgroup_uncharge_page() will do enough
3454          * check. (see prepare_charge() also)
3455          */
3456         if (PageAnon(used))
3457                 mem_cgroup_uncharge_page(used);
3458         /*
3459          * At migration, we may charge account against cgroup which has no
3460          * tasks.
3461          * So, rmdir()->pre_destroy() can be called while we do this charge.
3462          * In that case, we need to call pre_destroy() again. check it here.
3463          */
3464         cgroup_release_and_wakeup_rmdir(&mem->css);
3465 }
3466
3467 #ifdef CONFIG_DEBUG_VM
3468 static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
3469 {
3470         struct page_cgroup *pc;
3471
3472         pc = lookup_page_cgroup(page);
3473         if (likely(pc) && PageCgroupUsed(pc))
3474                 return pc;
3475         return NULL;
3476 }
3477
3478 bool mem_cgroup_bad_page_check(struct page *page)
3479 {
3480         if (mem_cgroup_disabled())
3481                 return false;
3482
3483         return lookup_page_cgroup_used(page) != NULL;
3484 }
3485
3486 void mem_cgroup_print_bad_page(struct page *page)
3487 {
3488         struct page_cgroup *pc;
3489
3490         pc = lookup_page_cgroup_used(page);
3491         if (pc) {
3492                 int ret = -1;
3493                 char *path;
3494
3495                 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p",
3496                        pc, pc->flags, pc->mem_cgroup);
3497
3498                 path = kmalloc(PATH_MAX, GFP_KERNEL);
3499                 if (path) {
3500                         rcu_read_lock();
3501                         ret = cgroup_path(pc->mem_cgroup->css.cgroup,
3502                                                         path, PATH_MAX);
3503                         rcu_read_unlock();
3504                 }
3505
3506                 printk(KERN_CONT "(%s)\n",
3507                                 (ret < 0) ? "cannot get the path" : path);
3508                 kfree(path);
3509         }
3510 }
3511 #endif
3512
3513 static DEFINE_MUTEX(set_limit_mutex);
3514
3515 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
3516                                 unsigned long long val)
3517 {
3518         int retry_count;
3519         u64 memswlimit, memlimit;
3520         int ret = 0;
3521         int children = mem_cgroup_count_children(memcg);
3522         u64 curusage, oldusage;
3523         int enlarge;
3524
3525         /*
3526          * For keeping hierarchical_reclaim simple, how long we should retry
3527          * is depends on callers. We set our retry-count to be function
3528          * of # of children which we should visit in this loop.
3529          */
3530         retry_count = MEM_CGROUP_RECLAIM_RETRIES * children;
3531
3532         oldusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3533
3534         enlarge = 0;
3535         while (retry_count) {
3536                 if (signal_pending(current)) {
3537                         ret = -EINTR;
3538                         break;
3539                 }
3540                 /*
3541                  * Rather than hide all in some function, I do this in
3542                  * open coded manner. You see what this really does.
3543                  * We have to guarantee mem->res.limit < mem->memsw.limit.
3544                  */
3545                 mutex_lock(&set_limit_mutex);
3546                 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3547                 if (memswlimit < val) {
3548                         ret = -EINVAL;
3549                         mutex_unlock(&set_limit_mutex);
3550                         break;
3551                 }
3552
3553                 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3554                 if (memlimit < val)
3555                         enlarge = 1;
3556
3557                 ret = res_counter_set_limit(&memcg->res, val);
3558                 if (!ret) {
3559                         if (memswlimit == val)
3560                                 memcg->memsw_is_minimum = true;
3561                         else
3562                                 memcg->memsw_is_minimum = false;
3563                 }
3564                 mutex_unlock(&set_limit_mutex);
3565
3566                 if (!ret)
3567                         break;
3568
3569                 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3570                                                 MEM_CGROUP_RECLAIM_SHRINK,
3571                                                 NULL);
3572                 curusage = res_counter_read_u64(&memcg->res, RES_USAGE);
3573                 /* Usage is reduced ? */
3574                 if (curusage >= oldusage)
3575                         retry_count--;
3576                 else
3577                         oldusage = curusage;
3578         }
3579         if (!ret && enlarge)
3580                 memcg_oom_recover(memcg);
3581
3582         return ret;
3583 }
3584
3585 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
3586                                         unsigned long long val)
3587 {
3588         int retry_count;
3589         u64 memlimit, memswlimit, oldusage, curusage;
3590         int children = mem_cgroup_count_children(memcg);
3591         int ret = -EBUSY;
3592         int enlarge = 0;
3593
3594         /* see mem_cgroup_resize_res_limit */
3595         retry_count = children * MEM_CGROUP_RECLAIM_RETRIES;
3596         oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3597         while (retry_count) {
3598                 if (signal_pending(current)) {
3599                         ret = -EINTR;
3600                         break;
3601                 }
3602                 /*
3603                  * Rather than hide all in some function, I do this in
3604                  * open coded manner. You see what this really does.
3605                  * We have to guarantee mem->res.limit < mem->memsw.limit.
3606                  */
3607                 mutex_lock(&set_limit_mutex);
3608                 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT);
3609                 if (memlimit > val) {
3610                         ret = -EINVAL;
3611                         mutex_unlock(&set_limit_mutex);
3612                         break;
3613                 }
3614                 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
3615                 if (memswlimit < val)
3616                         enlarge = 1;
3617                 ret = res_counter_set_limit(&memcg->memsw, val);
3618                 if (!ret) {
3619                         if (memlimit == val)
3620                                 memcg->memsw_is_minimum = true;
3621                         else
3622                                 memcg->memsw_is_minimum = false;
3623                 }
3624                 mutex_unlock(&set_limit_mutex);
3625
3626                 if (!ret)
3627                         break;
3628
3629                 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL,
3630                                                 MEM_CGROUP_RECLAIM_NOSWAP |
3631                                                 MEM_CGROUP_RECLAIM_SHRINK,
3632                                                 NULL);
3633                 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE);
3634                 /* Usage is reduced ? */
3635                 if (curusage >= oldusage)
3636                         retry_count--;
3637                 else
3638                         oldusage = curusage;
3639         }
3640         if (!ret && enlarge)
3641                 memcg_oom_recover(memcg);
3642         return ret;
3643 }
3644
3645 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
3646                                             gfp_t gfp_mask,
3647                                             unsigned long *total_scanned)
3648 {
3649         unsigned long nr_reclaimed = 0;
3650         struct mem_cgroup_per_zone *mz, *next_mz = NULL;
3651         unsigned long reclaimed;
3652         int loop = 0;
3653         struct mem_cgroup_tree_per_zone *mctz;
3654         unsigned long long excess;
3655         unsigned long nr_scanned;
3656
3657         if (order > 0)
3658                 return 0;
3659
3660         mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
3661         /*
3662          * This loop can run a while, specially if mem_cgroup's continuously
3663          * keep exceeding their soft limit and putting the system under
3664          * pressure
3665          */
3666         do {
3667                 if (next_mz)
3668                         mz = next_mz;
3669                 else
3670                         mz = mem_cgroup_largest_soft_limit_node(mctz);
3671                 if (!mz)
3672                         break;
3673
3674                 nr_scanned = 0;
3675                 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone,
3676                                                 gfp_mask,
3677                                                 MEM_CGROUP_RECLAIM_SOFT,
3678                                                 &nr_scanned);
3679                 nr_reclaimed += reclaimed;
3680                 *total_scanned += nr_scanned;
3681                 spin_lock(&mctz->lock);
3682
3683                 /*
3684                  * If we failed to reclaim anything from this memory cgroup
3685                  * it is time to move on to the next cgroup
3686                  */
3687                 next_mz = NULL;
3688                 if (!reclaimed) {
3689                         do {
3690                                 /*
3691                                  * Loop until we find yet another one.
3692                                  *
3693                                  * By the time we get the soft_limit lock
3694                                  * again, someone might have aded the
3695                                  * group back on the RB tree. Iterate to
3696                                  * make sure we get a different mem.
3697                                  * mem_cgroup_largest_soft_limit_node returns
3698                                  * NULL if no other cgroup is present on
3699                                  * the tree
3700                                  */
3701                                 next_mz =
3702                                 __mem_cgroup_largest_soft_limit_node(mctz);
3703                                 if (next_mz == mz)
3704                                         css_put(&next_mz->mem->css);
3705                                 else /* next_mz == NULL or other memcg */
3706                                         break;
3707                         } while (1);
3708                 }
3709                 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz);
3710                 excess = res_counter_soft_limit_excess(&mz->mem->res);
3711                 /*
3712                  * One school of thought says that we should not add
3713                  * back the node to the tree if reclaim returns 0.
3714                  * But our reclaim could return 0, simply because due
3715                  * to priority we are exposing a smaller subset of
3716                  * memory to reclaim from. Consider this as a longer
3717                  * term TODO.
3718                  */
3719                 /* If excess == 0, no tree ops */
3720                 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess);
3721                 spin_unlock(&mctz->lock);
3722                 css_put(&mz->mem->css);
3723                 loop++;
3724                 /*
3725                  * Could not reclaim anything and there are no more
3726                  * mem cgroups to try or we seem to be looping without
3727                  * reclaiming anything.
3728                  */
3729                 if (!nr_reclaimed &&
3730                         (next_mz == NULL ||
3731                         loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3732                         break;
3733         } while (!nr_reclaimed);
3734         if (next_mz)
3735                 css_put(&next_mz->mem->css);
3736         return nr_reclaimed;
3737 }
3738
3739 /*
3740  * This routine traverse page_cgroup in given list and drop them all.
3741  * *And* this routine doesn't reclaim page itself, just removes page_cgroup.
3742  */
3743 static int mem_cgroup_force_empty_list(struct mem_cgroup *mem,
3744                                 int node, int zid, enum lru_list lru)
3745 {
3746         struct zone *zone;
3747         struct mem_cgroup_per_zone *mz;
3748         struct page_cgroup *pc, *busy;
3749         unsigned long flags, loop;
3750         struct list_head *list;
3751         int ret = 0;
3752
3753         zone = &NODE_DATA(node)->node_zones[zid];
3754         mz = mem_cgroup_zoneinfo(mem, node, zid);
3755         list = &mz->lists[lru];
3756
3757         loop = MEM_CGROUP_ZSTAT(mz, lru);
3758         /* give some margin against EBUSY etc...*/
3759         loop += 256;
3760         busy = NULL;
3761         while (loop--) {
3762                 struct page *page;
3763
3764                 ret = 0;
3765                 spin_lock_irqsave(&zone->lru_lock, flags);
3766                 if (list_empty(list)) {
3767                         spin_unlock_irqrestore(&zone->lru_lock, flags);
3768                         break;
3769                 }
3770                 pc = list_entry(list->prev, struct page_cgroup, lru);
3771                 if (busy == pc) {
3772                         list_move(&pc->lru, list);
3773                         busy = NULL;
3774                         spin_unlock_irqrestore(&zone->lru_lock, flags);
3775                         continue;
3776                 }
3777                 spin_unlock_irqrestore(&zone->lru_lock, flags);
3778
3779                 page = lookup_cgroup_page(pc);
3780
3781                 ret = mem_cgroup_move_parent(page, pc, mem, GFP_KERNEL);
3782                 if (ret == -ENOMEM)
3783                         break;
3784
3785                 if (ret == -EBUSY || ret == -EINVAL) {
3786                         /* found lock contention or "pc" is obsolete. */
3787                         busy = pc;
3788                         cond_resched();
3789                 } else
3790                         busy = NULL;
3791         }
3792
3793         if (!ret && !list_empty(list))
3794                 return -EBUSY;
3795         return ret;
3796 }
3797
3798 /*
3799  * make mem_cgroup's charge to be 0 if there is no task.
3800  * This enables deleting this mem_cgroup.
3801  */
3802 static int mem_cgroup_force_empty(struct mem_cgroup *mem, bool free_all)
3803 {
3804         int ret;
3805         int node, zid, shrink;
3806         int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3807         struct cgroup *cgrp = mem->css.cgroup;
3808
3809         css_get(&mem->css);
3810
3811         shrink = 0;
3812         /* should free all ? */
3813         if (free_all)
3814                 goto try_to_free;
3815 move_account:
3816         do {
3817                 ret = -EBUSY;
3818                 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
3819                         goto out;
3820                 ret = -EINTR;
3821                 if (signal_pending(current))
3822                         goto out;
3823                 /* This is for making all *used* pages to be on LRU. */
3824                 lru_add_drain_all();
3825                 drain_all_stock_sync(mem);
3826                 ret = 0;
3827                 mem_cgroup_start_move(mem);
3828                 for_each_node_state(node, N_HIGH_MEMORY) {
3829                         for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) {
3830                                 enum lru_list l;
3831                                 for_each_lru(l) {
3832                                         ret = mem_cgroup_force_empty_list(mem,
3833                                                         node, zid, l);
3834                                         if (ret)
3835                                                 break;
3836                                 }
3837                         }
3838                         if (ret)
3839                                 break;
3840                 }
3841                 mem_cgroup_end_move(mem);
3842                 memcg_oom_recover(mem);
3843                 /* it seems parent cgroup doesn't have enough mem */
3844                 if (ret == -ENOMEM)
3845                         goto try_to_free;
3846                 cond_resched();
3847         /* "ret" should also be checked to ensure all lists are empty. */
3848         } while (mem->res.usage > 0 || ret);
3849 out:
3850         css_put(&mem->css);
3851         return ret;
3852
3853 try_to_free:
3854         /* returns EBUSY if there is a task or if we come here twice. */
3855         if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) {
3856                 ret = -EBUSY;
3857                 goto out;
3858         }
3859         /* we call try-to-free pages for make this cgroup empty */
3860         lru_add_drain_all();
3861         /* try to free all pages in this cgroup */
3862         shrink = 1;
3863         while (nr_retries && mem->res.usage > 0) {
3864                 struct memcg_scanrecord rec;
3865                 int progress;
3866
3867                 if (signal_pending(current)) {
3868                         ret = -EINTR;
3869                         goto out;
3870                 }
3871                 rec.context = SCAN_BY_SHRINK;
3872                 rec.mem = mem;
3873                 rec.root = mem;
3874                 progress = try_to_free_mem_cgroup_pages(mem, GFP_KERNEL,
3875                                                 false, &rec);
3876                 if (!progress) {
3877                         nr_retries--;
3878                         /* maybe some writeback is necessary */
3879                         congestion_wait(BLK_RW_ASYNC, HZ/10);
3880                 }
3881
3882         }
3883         lru_add_drain();
3884         /* try move_account...there may be some *locked* pages. */
3885         goto move_account;
3886 }
3887
3888 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
3889 {
3890         return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true);
3891 }
3892
3893
3894 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
3895 {
3896         return mem_cgroup_from_cont(cont)->use_hierarchy;
3897 }
3898
3899 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
3900                                         u64 val)
3901 {
3902         int retval = 0;
3903         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3904         struct cgroup *parent = cont->parent;
3905         struct mem_cgroup *parent_mem = NULL;
3906
3907         if (parent)
3908                 parent_mem = mem_cgroup_from_cont(parent);
3909
3910         cgroup_lock();
3911         /*
3912          * If parent's use_hierarchy is set, we can't make any modifications
3913          * in the child subtrees. If it is unset, then the change can
3914          * occur, provided the current cgroup has no children.
3915          *
3916          * For the root cgroup, parent_mem is NULL, we allow value to be
3917          * set if there are no children.
3918          */
3919         if ((!parent_mem || !parent_mem->use_hierarchy) &&
3920                                 (val == 1 || val == 0)) {
3921                 if (list_empty(&cont->children))
3922                         mem->use_hierarchy = val;
3923                 else
3924                         retval = -EBUSY;
3925         } else
3926                 retval = -EINVAL;
3927         cgroup_unlock();
3928
3929         return retval;
3930 }
3931
3932
3933 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *mem,
3934                                                enum mem_cgroup_stat_index idx)
3935 {
3936         struct mem_cgroup *iter;
3937         long val = 0;
3938
3939         /* Per-cpu values can be negative, use a signed accumulator */
3940         for_each_mem_cgroup_tree(iter, mem)
3941                 val += mem_cgroup_read_stat(iter, idx);
3942
3943         if (val < 0) /* race ? */
3944                 val = 0;
3945         return val;
3946 }
3947
3948 static inline u64 mem_cgroup_usage(struct mem_cgroup *mem, bool swap)
3949 {
3950         u64 val;
3951
3952         if (!mem_cgroup_is_root(mem)) {
3953                 if (!swap)
3954                         return res_counter_read_u64(&mem->res, RES_USAGE);
3955                 else
3956                         return res_counter_read_u64(&mem->memsw, RES_USAGE);
3957         }
3958
3959         val = mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_CACHE);
3960         val += mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_RSS);
3961
3962         if (swap)
3963                 val += mem_cgroup_recursive_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
3964
3965         return val << PAGE_SHIFT;
3966 }
3967
3968 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft)
3969 {
3970         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
3971         u64 val;
3972         int type, name;
3973
3974         type = MEMFILE_TYPE(cft->private);
3975         name = MEMFILE_ATTR(cft->private);
3976         switch (type) {
3977         case _MEM:
3978                 if (name == RES_USAGE)
3979                         val = mem_cgroup_usage(mem, false);
3980                 else
3981                         val = res_counter_read_u64(&mem->res, name);
3982                 break;
3983         case _MEMSWAP:
3984                 if (name == RES_USAGE)
3985                         val = mem_cgroup_usage(mem, true);
3986                 else
3987                         val = res_counter_read_u64(&mem->memsw, name);
3988                 break;
3989         default:
3990                 BUG();
3991                 break;
3992         }
3993         return val;
3994 }
3995 /*
3996  * The user of this function is...
3997  * RES_LIMIT.
3998  */
3999 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
4000                             const char *buffer)
4001 {
4002         struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4003         int type, name;
4004         unsigned long long val;
4005         int ret;
4006
4007         type = MEMFILE_TYPE(cft->private);
4008         name = MEMFILE_ATTR(cft->private);
4009         switch (name) {
4010         case RES_LIMIT:
4011                 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
4012                         ret = -EINVAL;
4013                         break;
4014                 }
4015                 /* This function does all necessary parse...reuse it */
4016                 ret = res_counter_memparse_write_strategy(buffer, &val);
4017                 if (ret)
4018                         break;
4019                 if (type == _MEM)
4020                         ret = mem_cgroup_resize_limit(memcg, val);
4021                 else
4022                         ret = mem_cgroup_resize_memsw_limit(memcg, val);
4023                 break;
4024         case RES_SOFT_LIMIT:
4025                 ret = res_counter_memparse_write_strategy(buffer, &val);
4026                 if (ret)
4027                         break;
4028                 /*
4029                  * For memsw, soft limits are hard to implement in terms
4030                  * of semantics, for now, we support soft limits for
4031                  * control without swap
4032                  */
4033                 if (type == _MEM)
4034                         ret = res_counter_set_soft_limit(&memcg->res, val);
4035                 else
4036                         ret = -EINVAL;
4037                 break;
4038         default:
4039                 ret = -EINVAL; /* should be BUG() ? */
4040                 break;
4041         }
4042         return ret;
4043 }
4044
4045 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg,
4046                 unsigned long long *mem_limit, unsigned long long *memsw_limit)
4047 {
4048         struct cgroup *cgroup;
4049         unsigned long long min_limit, min_memsw_limit, tmp;
4050
4051         min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT);
4052         min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4053         cgroup = memcg->css.cgroup;
4054         if (!memcg->use_hierarchy)
4055                 goto out;
4056
4057         while (cgroup->parent) {
4058                 cgroup = cgroup->parent;
4059                 memcg = mem_cgroup_from_cont(cgroup);
4060                 if (!memcg->use_hierarchy)
4061                         break;
4062                 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT);
4063                 min_limit = min(min_limit, tmp);
4064                 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT);
4065                 min_memsw_limit = min(min_memsw_limit, tmp);
4066         }
4067 out:
4068         *mem_limit = min_limit;
4069         *memsw_limit = min_memsw_limit;
4070         return;
4071 }
4072
4073 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
4074 {
4075         struct mem_cgroup *mem;
4076         int type, name;
4077
4078         mem = mem_cgroup_from_cont(cont);
4079         type = MEMFILE_TYPE(event);
4080         name = MEMFILE_ATTR(event);
4081         switch (name) {
4082         case RES_MAX_USAGE:
4083                 if (type == _MEM)
4084                         res_counter_reset_max(&mem->res);
4085                 else
4086                         res_counter_reset_max(&mem->memsw);
4087                 break;
4088         case RES_FAILCNT:
4089                 if (type == _MEM)
4090                         res_counter_reset_failcnt(&mem->res);
4091                 else
4092                         res_counter_reset_failcnt(&mem->memsw);
4093                 break;
4094         }
4095
4096         return 0;
4097 }
4098
4099 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
4100                                         struct cftype *cft)
4101 {
4102         return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
4103 }
4104
4105 #ifdef CONFIG_MMU
4106 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4107                                         struct cftype *cft, u64 val)
4108 {
4109         struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
4110
4111         if (val >= (1 << NR_MOVE_TYPE))
4112                 return -EINVAL;
4113         /*
4114          * We check this value several times in both in can_attach() and
4115          * attach(), so we need cgroup lock to prevent this value from being
4116          * inconsistent.
4117          */
4118         cgroup_lock();
4119         mem->move_charge_at_immigrate = val;
4120         cgroup_unlock();
4121
4122         return 0;
4123 }
4124 #else
4125 static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
4126                                         struct cftype *cft, u64 val)
4127 {
4128         return -ENOSYS;
4129 }
4130 #endif
4131
4132
4133 /* For read statistics */
4134 enum {
4135         MCS_CACHE,
4136         MCS_RSS,
4137         MCS_FILE_MAPPED,
4138         MCS_PGPGIN,
4139         MCS_PGPGOUT,
4140         MCS_SWAP,
4141         MCS_PGFAULT,
4142         MCS_PGMAJFAULT,
4143         MCS_INACTIVE_ANON,
4144         MCS_ACTIVE_ANON,
4145         MCS_INACTIVE_FILE,
4146         MCS_ACTIVE_FILE,
4147         MCS_UNEVICTABLE,
4148         NR_MCS_STAT,
4149 };
4150
4151 struct mcs_total_stat {
4152         s64 stat[NR_MCS_STAT];
4153 };
4154
4155 struct {
4156         char *local_name;
4157         char *total_name;
4158 } memcg_stat_strings[NR_MCS_STAT] = {
4159         {"cache", "total_cache"},
4160         {"rss", "total_rss"},
4161         {"mapped_file", "total_mapped_file"},
4162         {"pgpgin", "total_pgpgin"},
4163         {"pgpgout", "total_pgpgout"},
4164         {"swap", "total_swap"},
4165         {"pgfault", "total_pgfault"},
4166         {"pgmajfault", "total_pgmajfault"},
4167         {"inactive_anon", "total_inactive_anon"},
4168         {"active_anon", "total_active_anon"},
4169         {"inactive_file", "total_inactive_file"},
4170         {"active_file", "total_active_file"},
4171         {"unevictable", "total_unevictable"}
4172 };
4173
4174
4175 static void
4176 mem_cgroup_get_local_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
4177 {
4178         s64 val;
4179
4180         /* per cpu stat */
4181         val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_CACHE);
4182         s->stat[MCS_CACHE] += val * PAGE_SIZE;
4183         val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_RSS);
4184         s->stat[MCS_RSS] += val * PAGE_SIZE;
4185         val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_FILE_MAPPED);
4186         s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE;
4187         val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGPGIN);
4188         s->stat[MCS_PGPGIN] += val;
4189         val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGPGOUT);
4190         s->stat[MCS_PGPGOUT] += val;
4191         if (do_swap_account) {
4192                 val = mem_cgroup_read_stat(mem, MEM_CGROUP_STAT_SWAPOUT);
4193                 s->stat[MCS_SWAP] += val * PAGE_SIZE;
4194         }
4195         val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGFAULT);
4196         s->stat[MCS_PGFAULT] += val;
4197         val = mem_cgroup_read_events(mem, MEM_CGROUP_EVENTS_PGMAJFAULT);
4198         s->stat[MCS_PGMAJFAULT] += val;
4199
4200         /* per zone stat */
4201         val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_INACTIVE_ANON));
4202         s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE;
4203         val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_ACTIVE_ANON));
4204         s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE;
4205         val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_INACTIVE_FILE));
4206         s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE;
4207         val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_ACTIVE_FILE));
4208         s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE;
4209         val = mem_cgroup_nr_lru_pages(mem, BIT(LRU_UNEVICTABLE));
4210         s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE;
4211 }
4212
4213 static void
4214 mem_cgroup_get_total_stat(struct mem_cgroup *mem, struct mcs_total_stat *s)
4215 {
4216         struct mem_cgroup *iter;
4217
4218         for_each_mem_cgroup_tree(iter, mem)
4219                 mem_cgroup_get_local_stat(iter, s);
4220 }
4221
4222 #ifdef CONFIG_NUMA
4223 static int mem_control_numa_stat_show(struct seq_file *m, void *arg)
4224 {
4225         int nid;
4226         unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
4227         unsigned long node_nr;
4228         struct cgroup *cont = m->private;
4229         struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4230
4231         total_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL);
4232         seq_printf(m, "total=%lu", total_nr);
4233         for_each_node_state(nid, N_HIGH_MEMORY) {
4234                 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, LRU_ALL);
4235                 seq_printf(m, " N%d=%lu", nid, node_nr);
4236         }
4237         seq_putc(m, '\n');
4238
4239         file_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_FILE);
4240         seq_printf(m, "file=%lu", file_nr);
4241         for_each_node_state(nid, N_HIGH_MEMORY) {
4242                 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4243                                 LRU_ALL_FILE);
4244                 seq_printf(m, " N%d=%lu", nid, node_nr);
4245         }
4246         seq_putc(m, '\n');
4247
4248         anon_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_ANON);
4249         seq_printf(m, "anon=%lu", anon_nr);
4250         for_each_node_state(nid, N_HIGH_MEMORY) {
4251                 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4252                                 LRU_ALL_ANON);
4253                 seq_printf(m, " N%d=%lu", nid, node_nr);
4254         }
4255         seq_putc(m, '\n');
4256
4257         unevictable_nr = mem_cgroup_nr_lru_pages(mem_cont, BIT(LRU_UNEVICTABLE));
4258         seq_printf(m, "unevictable=%lu", unevictable_nr);
4259         for_each_node_state(nid, N_HIGH_MEMORY) {
4260                 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid,
4261                                 BIT(LRU_UNEVICTABLE));
4262                 seq_printf(m, " N%d=%lu", nid, node_nr);
4263         }
4264         seq_putc(m, '\n');
4265         return 0;
4266 }
4267 #endif /* CONFIG_NUMA */
4268
4269 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft,
4270                                  struct cgroup_map_cb *cb)
4271 {
4272         struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont);
4273         struct mcs_total_stat mystat;
4274         int i;
4275
4276         memset(&mystat, 0, sizeof(mystat));
4277         mem_cgroup_get_local_stat(mem_cont, &mystat);
4278
4279
4280         for (i = 0; i < NR_MCS_STAT; i++) {
4281                 if (i == MCS_SWAP && !do_swap_account)
4282                         continue;
4283                 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]);
4284         }
4285
4286         /* Hierarchical information */
4287         {
4288                 unsigned long long limit, memsw_limit;
4289                 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit);
4290                 cb->fill(cb, "hierarchical_memory_limit", limit);
4291                 if (do_swap_account)
4292                         cb->fill(cb, "hierarchical_memsw_limit", memsw_limit);
4293         }
4294
4295         memset(&mystat, 0, sizeof(mystat));
4296         mem_cgroup_get_total_stat(mem_cont, &mystat);
4297         for (i = 0; i < NR_MCS_STAT; i++) {
4298                 if (i == MCS_SWAP && !do_swap_account)
4299                         continue;
4300                 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]);
4301         }
4302
4303 #ifdef CONFIG_DEBUG_VM
4304         cb->fill(cb, "inactive_ratio", calc_inactive_ratio(mem_cont, NULL));
4305
4306         {
4307                 int nid, zid;
4308                 struct mem_cgroup_per_zone *mz;
4309                 unsigned long recent_rotated[2] = {0, 0};
4310                 unsigned long recent_scanned[2] = {0, 0};
4311
4312                 for_each_online_node(nid)
4313                         for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4314                                 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid);
4315
4316                                 recent_rotated[0] +=
4317                                         mz->reclaim_stat.recent_rotated[0];
4318                                 recent_rotated[1] +=
4319                                         mz->reclaim_stat.recent_rotated[1];
4320                                 recent_scanned[0] +=
4321                                         mz->reclaim_stat.recent_scanned[0];
4322                                 recent_scanned[1] +=
4323                                         mz->reclaim_stat.recent_scanned[1];
4324                         }
4325                 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]);
4326                 cb->fill(cb, "recent_rotated_file", recent_rotated[1]);
4327                 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]);
4328                 cb->fill(cb, "recent_scanned_file", recent_scanned[1]);
4329         }
4330 #endif
4331
4332         return 0;
4333 }
4334
4335 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
4336 {
4337         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4338
4339         return mem_cgroup_swappiness(memcg);
4340 }
4341
4342 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
4343                                        u64 val)
4344 {
4345         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4346         struct mem_cgroup *parent;
4347
4348         if (val > 100)
4349                 return -EINVAL;
4350
4351         if (cgrp->parent == NULL)
4352                 return -EINVAL;
4353
4354         parent = mem_cgroup_from_cont(cgrp->parent);
4355
4356         cgroup_lock();
4357
4358         /* If under hierarchy, only empty-root can set this value */
4359         if ((parent->use_hierarchy) ||
4360             (memcg->use_hierarchy && !list_empty(&cgrp->children))) {
4361                 cgroup_unlock();
4362                 return -EINVAL;
4363         }
4364
4365         memcg->swappiness = val;
4366
4367         cgroup_unlock();
4368
4369         return 0;
4370 }
4371
4372 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4373 {
4374         struct mem_cgroup_threshold_ary *t;
4375         u64 usage;
4376         int i;
4377
4378         rcu_read_lock();
4379         if (!swap)
4380                 t = rcu_dereference(memcg->thresholds.primary);
4381         else
4382                 t = rcu_dereference(memcg->memsw_thresholds.primary);
4383
4384         if (!t)
4385                 goto unlock;
4386
4387         usage = mem_cgroup_usage(memcg, swap);
4388
4389         /*
4390          * current_threshold points to threshold just below usage.
4391          * If it's not true, a threshold was crossed after last
4392          * call of __mem_cgroup_threshold().
4393          */
4394         i = t->current_threshold;
4395
4396         /*
4397          * Iterate backward over array of thresholds starting from
4398          * current_threshold and check if a threshold is crossed.
4399          * If none of thresholds below usage is crossed, we read
4400          * only one element of the array here.
4401          */
4402         for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4403                 eventfd_signal(t->entries[i].eventfd, 1);
4404
4405         /* i = current_threshold + 1 */
4406         i++;
4407
4408         /*
4409          * Iterate forward over array of thresholds starting from
4410          * current_threshold+1 and check if a threshold is crossed.
4411          * If none of thresholds above usage is crossed, we read
4412          * only one element of the array here.
4413          */
4414         for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4415                 eventfd_signal(t->entries[i].eventfd, 1);
4416
4417         /* Update current_threshold */
4418         t->current_threshold = i - 1;
4419 unlock:
4420         rcu_read_unlock();
4421 }
4422
4423 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4424 {
4425         while (memcg) {
4426                 __mem_cgroup_threshold(memcg, false);
4427                 if (do_swap_account)
4428                         __mem_cgroup_threshold(memcg, true);
4429
4430                 memcg = parent_mem_cgroup(memcg);
4431         }
4432 }
4433
4434 static int compare_thresholds(const void *a, const void *b)
4435 {
4436         const struct mem_cgroup_threshold *_a = a;
4437         const struct mem_cgroup_threshold *_b = b;
4438
4439         return _a->threshold - _b->threshold;
4440 }
4441
4442 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *mem)
4443 {
4444         struct mem_cgroup_eventfd_list *ev;
4445
4446         list_for_each_entry(ev, &mem->oom_notify, list)
4447                 eventfd_signal(ev->eventfd, 1);
4448         return 0;
4449 }
4450
4451 static void mem_cgroup_oom_notify(struct mem_cgroup *mem)
4452 {
4453         struct mem_cgroup *iter;
4454
4455         for_each_mem_cgroup_tree(iter, mem)
4456                 mem_cgroup_oom_notify_cb(iter);
4457 }
4458
4459 static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
4460         struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4461 {
4462         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4463         struct mem_cgroup_thresholds *thresholds;
4464         struct mem_cgroup_threshold_ary *new;
4465         int type = MEMFILE_TYPE(cft->private);
4466         u64 threshold, usage;
4467         int i, size, ret;
4468
4469         ret = res_counter_memparse_write_strategy(args, &threshold);
4470         if (ret)
4471                 return ret;
4472
4473         mutex_lock(&memcg->thresholds_lock);
4474
4475         if (type == _MEM)
4476                 thresholds = &memcg->thresholds;
4477         else if (type == _MEMSWAP)
4478                 thresholds = &memcg->memsw_thresholds;
4479         else
4480                 BUG();
4481
4482         usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4483
4484         /* Check if a threshold crossed before adding a new one */
4485         if (thresholds->primary)
4486                 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4487
4488         size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4489
4490         /* Allocate memory for new array of thresholds */
4491         new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
4492                         GFP_KERNEL);
4493         if (!new) {
4494                 ret = -ENOMEM;
4495                 goto unlock;
4496         }
4497         new->size = size;
4498
4499         /* Copy thresholds (if any) to new array */
4500         if (thresholds->primary) {
4501                 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4502                                 sizeof(struct mem_cgroup_threshold));
4503         }
4504
4505         /* Add new threshold */
4506         new->entries[size - 1].eventfd = eventfd;
4507         new->entries[size - 1].threshold = threshold;
4508
4509         /* Sort thresholds. Registering of new threshold isn't time-critical */
4510         sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4511                         compare_thresholds, NULL);
4512
4513         /* Find current threshold */
4514         new->current_threshold = -1;
4515         for (i = 0; i < size; i++) {
4516                 if (new->entries[i].threshold < usage) {
4517                         /*
4518                          * new->current_threshold will not be used until
4519                          * rcu_assign_pointer(), so it's safe to increment
4520                          * it here.
4521                          */
4522                         ++new->current_threshold;
4523                 }
4524         }
4525
4526         /* Free old spare buffer and save old primary buffer as spare */
4527         kfree(thresholds->spare);
4528         thresholds->spare = thresholds->primary;
4529
4530         rcu_assign_pointer(thresholds->primary, new);
4531
4532         /* To be sure that nobody uses thresholds */
4533         synchronize_rcu();
4534
4535 unlock:
4536         mutex_unlock(&memcg->thresholds_lock);
4537
4538         return ret;
4539 }
4540
4541 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
4542         struct cftype *cft, struct eventfd_ctx *eventfd)
4543 {
4544         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4545         struct mem_cgroup_thresholds *thresholds;
4546         struct mem_cgroup_threshold_ary *new;
4547         int type = MEMFILE_TYPE(cft->private);
4548         u64 usage;
4549         int i, j, size;
4550
4551         mutex_lock(&memcg->thresholds_lock);
4552         if (type == _MEM)
4553                 thresholds = &memcg->thresholds;
4554         else if (type == _MEMSWAP)
4555                 thresholds = &memcg->memsw_thresholds;
4556         else
4557                 BUG();
4558
4559         /*
4560          * Something went wrong if we trying to unregister a threshold
4561          * if we don't have thresholds
4562          */
4563         BUG_ON(!thresholds);
4564
4565         usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
4566
4567         /* Check if a threshold crossed before removing */
4568         __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4569
4570         /* Calculate new number of threshold */
4571         size = 0;
4572         for (i = 0; i < thresholds->primary->size; i++) {
4573                 if (thresholds->primary->entries[i].eventfd != eventfd)
4574                         size++;
4575         }
4576
4577         new = thresholds->spare;
4578
4579         /* Set thresholds array to NULL if we don't have thresholds */
4580         if (!size) {
4581                 kfree(new);
4582                 new = NULL;
4583                 goto swap_buffers;
4584         }
4585
4586         new->size = size;
4587
4588         /* Copy thresholds and find current threshold */
4589         new->current_threshold = -1;
4590         for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4591                 if (thresholds->primary->entries[i].eventfd == eventfd)
4592                         continue;
4593
4594                 new->entries[j] = thresholds->primary->entries[i];
4595                 if (new->entries[j].threshold < usage) {
4596                         /*
4597                          * new->current_threshold will not be used
4598                          * until rcu_assign_pointer(), so it's safe to increment
4599                          * it here.
4600                          */
4601                         ++new->current_threshold;
4602                 }
4603                 j++;
4604         }
4605
4606 swap_buffers:
4607         /* Swap primary and spare array */
4608         thresholds->spare = thresholds->primary;
4609         rcu_assign_pointer(thresholds->primary, new);
4610
4611         /* To be sure that nobody uses thresholds */
4612         synchronize_rcu();
4613
4614         mutex_unlock(&memcg->thresholds_lock);
4615 }
4616
4617 static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
4618         struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
4619 {
4620         struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
4621         struct mem_cgroup_eventfd_list *event;
4622         int type = MEMFILE_TYPE(cft->private);
4623
4624         BUG_ON(type != _OOM_TYPE);
4625         event = kmalloc(sizeof(*event), GFP_KERNEL);
4626         if (!event)
4627                 return -ENOMEM;
4628
4629         spin_lock(&memcg_oom_lock);
4630
4631         event->eventfd = eventfd;
4632         list_add(&event->list, &memcg->oom_notify);
4633
4634         /* already in OOM ? */
4635         if (atomic_read(&memcg->under_oom))
4636                 eventfd_signal(eventfd, 1);
4637         spin_unlock(&memcg_oom_lock);
4638
4639         return 0;
4640 }
4641
4642 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
4643         struct cftype *cft, struct eventfd_ctx *eventfd)
4644 {
4645         struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
4646         struct mem_cgroup_eventfd_list *ev, *tmp;
4647         int type = MEMFILE_TYPE(cft->private);
4648
4649         BUG_ON(type != _OOM_TYPE);
4650
4651         spin_lock(&memcg_oom_lock);
4652
4653         list_for_each_entry_safe(ev, tmp, &mem->oom_notify, list) {
4654                 if (ev->eventfd == eventfd) {
4655                         list_del(&ev->list);
4656                         kfree(ev);
4657                 }
4658         }
4659
4660         spin_unlock(&memcg_oom_lock);
4661 }
4662
4663 static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
4664         struct cftype *cft,  struct cgroup_map_cb *cb)
4665 {
4666         struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
4667
4668         cb->fill(cb, "oom_kill_disable", mem->oom_kill_disable);
4669
4670         if (atomic_read(&mem->under_oom))
4671                 cb->fill(cb, "under_oom", 1);
4672         else
4673                 cb->fill(cb, "under_oom", 0);
4674         return 0;
4675 }
4676
4677 static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
4678         struct cftype *cft, u64 val)
4679 {
4680         struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
4681         struct mem_cgroup *parent;
4682
4683         /* cannot set to root cgroup and only 0 and 1 are allowed */
4684         if (!cgrp->parent || !((val == 0) || (val == 1)))
4685                 return -EINVAL;
4686
4687         parent = mem_cgroup_from_cont(cgrp->parent);
4688
4689         cgroup_lock();
4690         /* oom-kill-disable is a flag for subhierarchy. */
4691         if ((parent->use_hierarchy) ||
4692             (mem->use_hierarchy && !list_empty(&cgrp->children))) {
4693                 cgroup_unlock();
4694                 return -EINVAL;
4695         }
4696         mem->oom_kill_disable = val;
4697         if (!val)
4698                 memcg_oom_recover(mem);
4699         cgroup_unlock();
4700         return 0;
4701 }
4702
4703 #ifdef CONFIG_NUMA
4704 static const struct file_operations mem_control_numa_stat_file_operations = {
4705         .read = seq_read,
4706         .llseek = seq_lseek,
4707         .release = single_release,
4708 };
4709
4710 static int mem_control_numa_stat_open(struct inode *unused, struct file *file)
4711 {
4712         struct cgroup *cont = file->f_dentry->d_parent->d_fsdata;
4713
4714         file->f_op = &mem_control_numa_stat_file_operations;
4715         return single_open(file, mem_control_numa_stat_show, cont);
4716 }
4717 #endif /* CONFIG_NUMA */
4718
4719 static int mem_cgroup_vmscan_stat_read(struct cgroup *cgrp,
4720                                 struct cftype *cft,
4721                                 struct cgroup_map_cb *cb)
4722 {
4723         struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
4724         char string[64];
4725         int i;
4726
4727         for (i = 0; i < NR_SCANSTATS; i++) {
4728                 strcpy(string, scanstat_string[i]);
4729                 strcat(string, SCANSTAT_WORD_LIMIT);
4730                 cb->fill(cb, string,  mem->scanstat.stats[SCAN_BY_LIMIT][i]);
4731         }
4732
4733         for (i = 0; i < NR_SCANSTATS; i++) {
4734                 strcpy(string, scanstat_string[i]);
4735                 strcat(string, SCANSTAT_WORD_SYSTEM);
4736                 cb->fill(cb, string,  mem->scanstat.stats[SCAN_BY_SYSTEM][i]);
4737         }
4738
4739         for (i = 0; i < NR_SCANSTATS; i++) {
4740                 strcpy(string, scanstat_string[i]);
4741                 strcat(string, SCANSTAT_WORD_LIMIT);
4742                 strcat(string, SCANSTAT_WORD_HIERARCHY);
4743                 cb->fill(cb, string,  mem->scanstat.rootstats[SCAN_BY_LIMIT][i]);
4744         }
4745         for (i = 0; i < NR_SCANSTATS; i++) {
4746                 strcpy(string, scanstat_string[i]);
4747                 strcat(string, SCANSTAT_WORD_SYSTEM);
4748                 strcat(string, SCANSTAT_WORD_HIERARCHY);
4749                 cb->fill(cb, string,  mem->scanstat.rootstats[SCAN_BY_SYSTEM][i]);
4750         }
4751         return 0;
4752 }
4753
4754 static int mem_cgroup_reset_vmscan_stat(struct cgroup *cgrp,
4755                                 unsigned int event)
4756 {
4757         struct mem_cgroup *mem = mem_cgroup_from_cont(cgrp);
4758
4759         spin_lock(&mem->scanstat.lock);
4760         memset(&mem->scanstat.stats, 0, sizeof(mem->scanstat.stats));
4761         memset(&mem->scanstat.rootstats, 0, sizeof(mem->scanstat.rootstats));
4762         spin_unlock(&mem->scanstat.lock);
4763         return 0;
4764 }
4765
4766
4767 static struct cftype mem_cgroup_files[] = {
4768         {
4769                 .name = "usage_in_bytes",
4770                 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4771                 .read_u64 = mem_cgroup_read,
4772                 .register_event = mem_cgroup_usage_register_event,
4773                 .unregister_event = mem_cgroup_usage_unregister_event,
4774         },
4775         {
4776                 .name = "max_usage_in_bytes",
4777                 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4778                 .trigger = mem_cgroup_reset,
4779                 .read_u64 = mem_cgroup_read,
4780         },
4781         {
4782                 .name = "limit_in_bytes",
4783                 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4784                 .write_string = mem_cgroup_write,
4785                 .read_u64 = mem_cgroup_read,
4786         },
4787         {
4788                 .name = "soft_limit_in_bytes",
4789                 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4790                 .write_string = mem_cgroup_write,
4791                 .read_u64 = mem_cgroup_read,
4792         },
4793         {
4794                 .name = "failcnt",
4795                 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4796                 .trigger = mem_cgroup_reset,
4797                 .read_u64 = mem_cgroup_read,
4798         },
4799         {
4800                 .name = "stat",
4801                 .read_map = mem_control_stat_show,
4802         },
4803         {
4804                 .name = "force_empty",
4805                 .trigger = mem_cgroup_force_empty_write,
4806         },
4807         {
4808                 .name = "use_hierarchy",
4809                 .write_u64 = mem_cgroup_hierarchy_write,
4810                 .read_u64 = mem_cgroup_hierarchy_read,
4811         },
4812         {
4813                 .name = "swappiness",
4814                 .read_u64 = mem_cgroup_swappiness_read,
4815                 .write_u64 = mem_cgroup_swappiness_write,
4816         },
4817         {
4818                 .name = "move_charge_at_immigrate",
4819                 .read_u64 = mem_cgroup_move_charge_read,
4820                 .write_u64 = mem_cgroup_move_charge_write,
4821         },
4822         {
4823                 .name = "oom_control",
4824                 .read_map = mem_cgroup_oom_control_read,
4825                 .write_u64 = mem_cgroup_oom_control_write,
4826                 .register_event = mem_cgroup_oom_register_event,
4827                 .unregister_event = mem_cgroup_oom_unregister_event,
4828                 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4829         },
4830 #ifdef CONFIG_NUMA
4831         {
4832                 .name = "numa_stat",
4833                 .open = mem_control_numa_stat_open,
4834                 .mode = S_IRUGO,
4835         },
4836 #endif
4837         {
4838                 .name = "vmscan_stat",
4839                 .read_map = mem_cgroup_vmscan_stat_read,
4840                 .trigger = mem_cgroup_reset_vmscan_stat,
4841         },
4842 };
4843
4844 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
4845 static struct cftype memsw_cgroup_files[] = {
4846         {
4847                 .name = "memsw.usage_in_bytes",
4848                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
4849                 .read_u64 = mem_cgroup_read,
4850                 .register_event = mem_cgroup_usage_register_event,
4851                 .unregister_event = mem_cgroup_usage_unregister_event,
4852         },
4853         {
4854                 .name = "memsw.max_usage_in_bytes",
4855                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
4856                 .trigger = mem_cgroup_reset,
4857                 .read_u64 = mem_cgroup_read,
4858         },
4859         {
4860                 .name = "memsw.limit_in_bytes",
4861                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
4862                 .write_string = mem_cgroup_write,
4863                 .read_u64 = mem_cgroup_read,
4864         },
4865         {
4866                 .name = "memsw.failcnt",
4867                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
4868                 .trigger = mem_cgroup_reset,
4869                 .read_u64 = mem_cgroup_read,
4870         },
4871 };
4872
4873 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4874 {
4875         if (!do_swap_account)
4876                 return 0;
4877         return cgroup_add_files(cont, ss, memsw_cgroup_files,
4878                                 ARRAY_SIZE(memsw_cgroup_files));
4879 };
4880 #else
4881 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss)
4882 {
4883         return 0;
4884 }
4885 #endif
4886
4887 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
4888 {
4889         struct mem_cgroup_per_node *pn;
4890         struct mem_cgroup_per_zone *mz;
4891         enum lru_list l;
4892         int zone, tmp = node;
4893         /*
4894          * This routine is called against possible nodes.
4895          * But it's BUG to call kmalloc() against offline node.
4896          *
4897          * TODO: this routine can waste much memory for nodes which will
4898          *       never be onlined. It's better to use memory hotplug callback
4899          *       function.
4900          */
4901         if (!node_state(node, N_NORMAL_MEMORY))
4902                 tmp = -1;
4903         pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
4904         if (!pn)
4905                 return 1;
4906
4907         mem->info.nodeinfo[node] = pn;
4908         for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4909                 mz = &pn->zoneinfo[zone];
4910                 for_each_lru(l)
4911                         INIT_LIST_HEAD(&mz->lists[l]);
4912                 mz->usage_in_excess = 0;
4913                 mz->on_tree = false;
4914                 mz->mem = mem;
4915         }
4916         return 0;
4917 }
4918
4919 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *mem, int node)
4920 {
4921         kfree(mem->info.nodeinfo[node]);
4922 }
4923
4924 static struct mem_cgroup *mem_cgroup_alloc(void)
4925 {
4926         struct mem_cgroup *mem;
4927         int size = sizeof(struct mem_cgroup);
4928
4929         /* Can be very big if MAX_NUMNODES is very big */
4930         if (size < PAGE_SIZE)
4931                 mem = kzalloc(size, GFP_KERNEL);
4932         else
4933                 mem = vzalloc(size);
4934
4935         if (!mem)
4936                 return NULL;
4937
4938         mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
4939         if (!mem->stat)
4940                 goto out_free;
4941         spin_lock_init(&mem->pcp_counter_lock);
4942         return mem;
4943
4944 out_free:
4945         if (size < PAGE_SIZE)
4946                 kfree(mem);
4947         else
4948                 vfree(mem);
4949         return NULL;
4950 }
4951
4952 /*
4953  * At destroying mem_cgroup, references from swap_cgroup can remain.
4954  * (scanning all at force_empty is too costly...)
4955  *
4956  * Instead of clearing all references at force_empty, we remember
4957  * the number of reference from swap_cgroup and free mem_cgroup when
4958  * it goes down to 0.
4959  *
4960  * Removal of cgroup itself succeeds regardless of refs from swap.
4961  */
4962
4963 static void __mem_cgroup_free(struct mem_cgroup *mem)
4964 {
4965         int node;
4966
4967         mem_cgroup_remove_from_trees(mem);
4968         free_css_id(&mem_cgroup_subsys, &mem->css);
4969
4970         for_each_node_state(node, N_POSSIBLE)
4971                 free_mem_cgroup_per_zone_info(mem, node);
4972
4973         free_percpu(mem->stat);
4974         if (sizeof(struct mem_cgroup) < PAGE_SIZE)
4975                 kfree(mem);
4976         else
4977                 vfree(mem);
4978 }
4979
4980 static void mem_cgroup_get(struct mem_cgroup *mem)
4981 {
4982         atomic_inc(&mem->refcnt);
4983 }
4984
4985 static void __mem_cgroup_put(struct mem_cgroup *mem, int count)
4986 {
4987         if (atomic_sub_and_test(count, &mem->refcnt)) {
4988                 struct mem_cgroup *parent = parent_mem_cgroup(mem);
4989                 __mem_cgroup_free(mem);
4990                 if (parent)
4991                         mem_cgroup_put(parent);
4992         }
4993 }
4994
4995 static void mem_cgroup_put(struct mem_cgroup *mem)
4996 {
4997         __mem_cgroup_put(mem, 1);
4998 }
4999
5000 /*
5001  * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
5002  */
5003 static struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *mem)
5004 {
5005         if (!mem->res.parent)
5006                 return NULL;
5007         return mem_cgroup_from_res_counter(mem->res.parent, res);
5008 }
5009
5010 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5011 static void __init enable_swap_cgroup(void)
5012 {
5013         if (!mem_cgroup_disabled() && really_do_swap_account)
5014                 do_swap_account = 1;
5015 }
5016 #else
5017 static void __init enable_swap_cgroup(void)
5018 {
5019 }
5020 #endif
5021
5022 static int mem_cgroup_soft_limit_tree_init(void)
5023 {
5024         struct mem_cgroup_tree_per_node *rtpn;
5025         struct mem_cgroup_tree_per_zone *rtpz;
5026         int tmp, node, zone;
5027
5028         for_each_node_state(node, N_POSSIBLE) {
5029                 tmp = node;
5030                 if (!node_state(node, N_NORMAL_MEMORY))
5031                         tmp = -1;
5032                 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
5033                 if (!rtpn)
5034                         return 1;
5035
5036                 soft_limit_tree.rb_tree_per_node[node] = rtpn;
5037
5038                 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
5039                         rtpz = &rtpn->rb_tree_per_zone[zone];
5040                         rtpz->rb_root = RB_ROOT;
5041                         spin_lock_init(&rtpz->lock);
5042                 }
5043         }
5044         return 0;
5045 }
5046
5047 static struct cgroup_subsys_state * __ref
5048 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont)
5049 {
5050         struct mem_cgroup *mem, *parent;
5051         long error = -ENOMEM;
5052         int node;
5053
5054         mem = mem_cgroup_alloc();
5055         if (!mem)
5056                 return ERR_PTR(error);
5057
5058         for_each_node_state(node, N_POSSIBLE)
5059                 if (alloc_mem_cgroup_per_zone_info(mem, node))
5060                         goto free_out;
5061
5062         /* root ? */
5063         if (cont->parent == NULL) {
5064                 int cpu;
5065                 enable_swap_cgroup();
5066                 parent = NULL;
5067                 root_mem_cgroup = mem;
5068                 if (mem_cgroup_soft_limit_tree_init())
5069                         goto free_out;
5070                 for_each_possible_cpu(cpu) {
5071                         struct memcg_stock_pcp *stock =
5072                                                 &per_cpu(memcg_stock, cpu);
5073                         INIT_WORK(&stock->work, drain_local_stock);
5074                 }
5075                 hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
5076         } else {
5077                 parent = mem_cgroup_from_cont(cont->parent);
5078                 mem->use_hierarchy = parent->use_hierarchy;
5079                 mem->oom_kill_disable = parent->oom_kill_disable;
5080         }
5081
5082         if (parent && parent->use_hierarchy) {
5083                 res_counter_init(&mem->res, &parent->res);
5084                 res_counter_init(&mem->memsw, &parent->memsw);
5085                 /*
5086                  * We increment refcnt of the parent to ensure that we can
5087                  * safely access it on res_counter_charge/uncharge.
5088                  * This refcnt will be decremented when freeing this
5089                  * mem_cgroup(see mem_cgroup_put).
5090                  */
5091                 mem_cgroup_get(parent);
5092         } else {
5093                 res_counter_init(&mem->res, NULL);
5094                 res_counter_init(&mem->memsw, NULL);
5095         }
5096         mem->last_scanned_child = 0;
5097         mem->last_scanned_node = MAX_NUMNODES;
5098         INIT_LIST_HEAD(&mem->oom_notify);
5099
5100         if (parent)
5101                 mem->swappiness = mem_cgroup_swappiness(parent);
5102         atomic_set(&mem->refcnt, 1);
5103         mem->move_charge_at_immigrate = 0;
5104         mutex_init(&mem->thresholds_lock);
5105         spin_lock_init(&mem->scanstat.lock);
5106         return &mem->css;
5107 free_out:
5108         __mem_cgroup_free(mem);
5109         root_mem_cgroup = NULL;
5110         return ERR_PTR(error);
5111 }
5112
5113 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss,
5114                                         struct cgroup *cont)
5115 {
5116         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
5117
5118         return mem_cgroup_force_empty(mem, false);
5119 }
5120
5121 static void mem_cgroup_destroy(struct cgroup_subsys *ss,
5122                                 struct cgroup *cont)
5123 {
5124         struct mem_cgroup *mem = mem_cgroup_from_cont(cont);
5125
5126         mem_cgroup_put(mem);
5127 }
5128
5129 static int mem_cgroup_populate(struct cgroup_subsys *ss,
5130                                 struct cgroup *cont)
5131 {
5132         int ret;
5133
5134         ret = cgroup_add_files(cont, ss, mem_cgroup_files,
5135                                 ARRAY_SIZE(mem_cgroup_files));
5136
5137         if (!ret)
5138                 ret = register_memsw_files(cont, ss);
5139         return ret;
5140 }
5141
5142 #ifdef CONFIG_MMU
5143 /* Handlers for move charge at task migration. */
5144 #define PRECHARGE_COUNT_AT_ONCE 256
5145 static int mem_cgroup_do_precharge(unsigned long count)
5146 {
5147         int ret = 0;
5148         int batch_count = PRECHARGE_COUNT_AT_ONCE;
5149         struct mem_cgroup *mem = mc.to;
5150
5151         if (mem_cgroup_is_root(mem)) {
5152                 mc.precharge += count;
5153                 /* we don't need css_get for root */
5154                 return ret;
5155         }
5156         /* try to charge at once */
5157         if (count > 1) {
5158                 struct res_counter *dummy;
5159                 /*
5160                  * "mem" cannot be under rmdir() because we've already checked
5161                  * by cgroup_lock_live_cgroup() that it is not removed and we
5162                  * are still under the same cgroup_mutex. So we can postpone
5163                  * css_get().
5164                  */
5165                 if (res_counter_charge(&mem->res, PAGE_SIZE * count, &dummy))
5166                         goto one_by_one;
5167                 if (do_swap_account && res_counter_charge(&mem->memsw,
5168                                                 PAGE_SIZE * count, &dummy)) {
5169                         res_counter_uncharge(&mem->res, PAGE_SIZE * count);
5170                         goto one_by_one;
5171                 }
5172                 mc.precharge += count;
5173                 return ret;
5174         }
5175 one_by_one:
5176         /* fall back to one by one charge */
5177         while (count--) {
5178                 if (signal_pending(current)) {
5179                         ret = -EINTR;
5180                         break;
5181                 }
5182                 if (!batch_count--) {
5183                         batch_count = PRECHARGE_COUNT_AT_ONCE;
5184                         cond_resched();
5185                 }
5186                 ret = __mem_cgroup_try_charge(NULL, GFP_KERNEL, 1, &mem, false);
5187                 if (ret || !mem)
5188                         /* mem_cgroup_clear_mc() will do uncharge later */
5189                         return -ENOMEM;
5190                 mc.precharge++;
5191         }
5192         return ret;
5193 }
5194
5195 /**
5196  * is_target_pte_for_mc - check a pte whether it is valid for move charge
5197  * @vma: the vma the pte to be checked belongs
5198  * @addr: the address corresponding to the pte to be checked
5199  * @ptent: the pte to be checked
5200  * @target: the pointer the target page or swap ent will be stored(can be NULL)
5201  *
5202  * Returns
5203  *   0(MC_TARGET_NONE): if the pte is not a target for move charge.
5204  *   1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5205  *     move charge. if @target is not NULL, the page is stored in target->page
5206  *     with extra refcnt got(Callers should handle it).
5207  *   2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5208  *     target for charge migration. if @target is not NULL, the entry is stored
5209  *     in target->ent.
5210  *
5211  * Called with pte lock held.
5212  */
5213 union mc_target {
5214         struct page     *page;
5215         swp_entry_t     ent;
5216 };
5217
5218 enum mc_target_type {
5219         MC_TARGET_NONE, /* not used */
5220         MC_TARGET_PAGE,
5221         MC_TARGET_SWAP,
5222 };
5223
5224 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5225                                                 unsigned long addr, pte_t ptent)
5226 {
5227         struct page *page = vm_normal_page(vma, addr, ptent);
5228
5229         if (!page || !page_mapped(page))
5230                 return NULL;
5231         if (PageAnon(page)) {
5232                 /* we don't move shared anon */
5233                 if (!move_anon() || page_mapcount(page) > 2)
5234                         return NULL;
5235         } else if (!move_file())
5236                 /* we ignore mapcount for file pages */
5237                 return NULL;
5238         if (!get_page_unless_zero(page))
5239                 return NULL;
5240
5241         return page;
5242 }
5243
5244 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5245                         unsigned long addr, pte_t ptent, swp_entry_t *entry)
5246 {
5247         int usage_count;
5248         struct page *page = NULL;
5249         swp_entry_t ent = pte_to_swp_entry(ptent);
5250
5251         if (!move_anon() || non_swap_entry(ent))
5252                 return NULL;
5253         usage_count = mem_cgroup_count_swap_user(ent, &page);
5254         if (usage_count > 1) { /* we don't move shared anon */
5255                 if (page)
5256                         put_page(page);
5257                 return NULL;
5258         }
5259         if (do_swap_account)
5260                 entry->val = ent.val;
5261
5262         return page;
5263 }
5264
5265 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5266                         unsigned long addr, pte_t ptent, swp_entry_t *entry)
5267 {
5268         struct page *page = NULL;
5269         struct inode *inode;
5270         struct address_space *mapping;
5271         pgoff_t pgoff;
5272
5273         if (!vma->vm_file) /* anonymous vma */
5274                 return NULL;
5275         if (!move_file())
5276                 return NULL;
5277
5278         inode = vma->vm_file->f_path.dentry->d_inode;
5279         mapping = vma->vm_file->f_mapping;
5280         if (pte_none(ptent))
5281                 pgoff = linear_page_index(vma, addr);
5282         else /* pte_file(ptent) is true */
5283                 pgoff = pte_to_pgoff(ptent);
5284
5285         /* page is moved even if it's not RSS of this task(page-faulted). */
5286         page = find_get_page(mapping, pgoff);
5287
5288 #ifdef CONFIG_SWAP
5289         /* shmem/tmpfs may report page out on swap: account for that too. */
5290         if (radix_tree_exceptional_entry(page)) {
5291                 swp_entry_t swap = radix_to_swp_entry(page);
5292                 if (do_swap_account)
5293                         *entry = swap;
5294                 page = find_get_page(&swapper_space, swap.val);
5295         }
5296 #endif
5297         return page;
5298 }
5299
5300 static int is_target_pte_for_mc(struct vm_area_struct *vma,
5301                 unsigned long addr, pte_t ptent, union mc_target *target)
5302 {
5303         struct page *page = NULL;
5304         struct page_cgroup *pc;
5305         int ret = 0;
5306         swp_entry_t ent = { .val = 0 };
5307
5308         if (pte_present(ptent))
5309                 page = mc_handle_present_pte(vma, addr, ptent);
5310         else if (is_swap_pte(ptent))
5311                 page = mc_handle_swap_pte(vma, addr, ptent, &ent);
5312         else if (pte_none(ptent) || pte_file(ptent))
5313                 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5314
5315         if (!page && !ent.val)
5316                 return 0;
5317         if (page) {
5318                 pc = lookup_page_cgroup(page);
5319                 /*
5320                  * Do only loose check w/o page_cgroup lock.
5321                  * mem_cgroup_move_account() checks the pc is valid or not under
5322                  * the lock.
5323                  */
5324                 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
5325                         ret = MC_TARGET_PAGE;
5326                         if (target)
5327                                 target->page = page;
5328                 }
5329                 if (!ret || !target)
5330                         put_page(page);
5331         }
5332         /* There is a swap entry and a page doesn't exist or isn't charged */
5333         if (ent.val && !ret &&
5334                         css_id(&mc.from->css) == lookup_swap_cgroup(ent)) {
5335                 ret = MC_TARGET_SWAP;
5336                 if (target)
5337                         target->ent = ent;
5338         }
5339         return ret;
5340 }
5341
5342 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5343                                         unsigned long addr, unsigned long end,
5344                                         struct mm_walk *walk)
5345 {
5346         struct vm_area_struct *vma = walk->private;
5347         pte_t *pte;
5348         spinlock_t *ptl;
5349
5350         split_huge_page_pmd(walk->mm, pmd);
5351
5352         pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5353         for (; addr != end; pte++, addr += PAGE_SIZE)
5354                 if (is_target_pte_for_mc(vma, addr, *pte, NULL))
5355                         mc.precharge++; /* increment precharge temporarily */
5356         pte_unmap_unlock(pte - 1, ptl);
5357         cond_resched();
5358
5359         return 0;
5360 }
5361
5362 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5363 {
5364         unsigned long precharge;
5365         struct vm_area_struct *vma;
5366
5367         down_read(&mm->mmap_sem);
5368         for (vma = mm->mmap; vma; vma = vma->vm_next) {
5369                 struct mm_walk mem_cgroup_count_precharge_walk = {
5370                         .pmd_entry = mem_cgroup_count_precharge_pte_range,
5371                         .mm = mm,
5372                         .private = vma,
5373                 };
5374                 if (is_vm_hugetlb_page(vma))
5375                         continue;
5376                 walk_page_range(vma->vm_start, vma->vm_end,
5377                                         &mem_cgroup_count_precharge_walk);
5378         }
5379         up_read(&mm->mmap_sem);
5380
5381         precharge = mc.precharge;
5382         mc.precharge = 0;
5383
5384         return precharge;
5385 }
5386
5387 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5388 {
5389         unsigned long precharge = mem_cgroup_count_precharge(mm);
5390
5391         VM_BUG_ON(mc.moving_task);
5392         mc.moving_task = current;
5393         return mem_cgroup_do_precharge(precharge);
5394 }
5395
5396 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5397 static void __mem_cgroup_clear_mc(void)
5398 {
5399         struct mem_cgroup *from = mc.from;
5400         struct mem_cgroup *to = mc.to;
5401
5402         /* we must uncharge all the leftover precharges from mc.to */
5403         if (mc.precharge) {
5404                 __mem_cgroup_cancel_charge(mc.to, mc.precharge);
5405                 mc.precharge = 0;
5406         }
5407         /*
5408          * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5409          * we must uncharge here.
5410          */
5411         if (mc.moved_charge) {
5412                 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
5413                 mc.moved_charge = 0;
5414         }
5415         /* we must fixup refcnts and charges */
5416         if (mc.moved_swap) {
5417                 /* uncharge swap account from the old cgroup */
5418                 if (!mem_cgroup_is_root(mc.from))
5419                         res_counter_uncharge(&mc.from->memsw,
5420                                                 PAGE_SIZE * mc.moved_swap);
5421                 __mem_cgroup_put(mc.from, mc.moved_swap);
5422
5423                 if (!mem_cgroup_is_root(mc.to)) {
5424                         /*
5425                          * we charged both to->res and to->memsw, so we should
5426                          * uncharge to->res.
5427                          */
5428                         res_counter_uncharge(&mc.to->res,
5429                                                 PAGE_SIZE * mc.moved_swap);
5430                 }
5431                 /* we've already done mem_cgroup_get(mc.to) */
5432                 mc.moved_swap = 0;
5433         }
5434         memcg_oom_recover(from);
5435         memcg_oom_recover(to);
5436         wake_up_all(&mc.waitq);
5437 }
5438
5439 static void mem_cgroup_clear_mc(void)
5440 {
5441         struct mem_cgroup *from = mc.from;
5442
5443         /*
5444          * we must clear moving_task before waking up waiters at the end of
5445          * task migration.
5446          */
5447         mc.moving_task = NULL;
5448         __mem_cgroup_clear_mc();
5449         spin_lock(&mc.lock);
5450         mc.from = NULL;
5451         mc.to = NULL;
5452         spin_unlock(&mc.lock);
5453         mem_cgroup_end_move(from);
5454 }
5455
5456 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5457                                 struct cgroup *cgroup,
5458                                 struct task_struct *p)
5459 {
5460         int ret = 0;
5461         struct mem_cgroup *mem = mem_cgroup_from_cont(cgroup);
5462
5463         if (mem->move_charge_at_immigrate) {
5464                 struct mm_struct *mm;
5465                 struct mem_cgroup *from = mem_cgroup_from_task(p);
5466
5467                 VM_BUG_ON(from == mem);
5468
5469                 mm = get_task_mm(p);
5470                 if (!mm)
5471                         return 0;
5472                 /* We move charges only when we move a owner of the mm */
5473                 if (mm->owner == p) {
5474                         VM_BUG_ON(mc.from);
5475                         VM_BUG_ON(mc.to);
5476                         VM_BUG_ON(mc.precharge);
5477                         VM_BUG_ON(mc.moved_charge);
5478                         VM_BUG_ON(mc.moved_swap);
5479                         mem_cgroup_start_move(from);
5480                         spin_lock(&mc.lock);
5481                         mc.from = from;
5482                         mc.to = mem;
5483                         spin_unlock(&mc.lock);
5484                         /* We set mc.moving_task later */
5485
5486                         ret = mem_cgroup_precharge_mc(mm);
5487                         if (ret)
5488                                 mem_cgroup_clear_mc();
5489                 }
5490                 mmput(mm);
5491         }
5492         return ret;
5493 }
5494
5495 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5496                                 struct cgroup *cgroup,
5497                                 struct task_struct *p)
5498 {
5499         mem_cgroup_clear_mc();
5500 }
5501
5502 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5503                                 unsigned long addr, unsigned long end,
5504                                 struct mm_walk *walk)
5505 {
5506         int ret = 0;
5507         struct vm_area_struct *vma = walk->private;
5508         pte_t *pte;
5509         spinlock_t *ptl;
5510
5511         split_huge_page_pmd(walk->mm, pmd);
5512 retry:
5513         pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5514         for (; addr != end; addr += PAGE_SIZE) {
5515                 pte_t ptent = *(pte++);
5516                 union mc_target target;
5517                 int type;
5518                 struct page *page;
5519                 struct page_cgroup *pc;
5520                 swp_entry_t ent;
5521
5522                 if (!mc.precharge)
5523                         break;
5524
5525                 type = is_target_pte_for_mc(vma, addr, ptent, &target);
5526                 switch (type) {
5527                 case MC_TARGET_PAGE:
5528                         page = target.page;
5529                         if (isolate_lru_page(page))
5530                                 goto put;
5531                         pc = lookup_page_cgroup(page);
5532                         if (!mem_cgroup_move_account(page, 1, pc,
5533                                                      mc.from, mc.to, false)) {
5534                                 mc.precharge--;
5535                                 /* we uncharge from mc.from later. */
5536                                 mc.moved_charge++;
5537                         }
5538                         putback_lru_page(page);
5539 put:                    /* is_target_pte_for_mc() gets the page */
5540                         put_page(page);
5541                         break;
5542                 case MC_TARGET_SWAP:
5543                         ent = target.ent;
5544                         if (!mem_cgroup_move_swap_account(ent,
5545                                                 mc.from, mc.to, false)) {
5546                                 mc.precharge--;
5547                                 /* we fixup refcnts and charges later. */
5548                                 mc.moved_swap++;
5549                         }
5550                         break;
5551                 default:
5552                         break;
5553                 }
5554         }
5555         pte_unmap_unlock(pte - 1, ptl);
5556         cond_resched();
5557
5558         if (addr != end) {
5559                 /*
5560                  * We have consumed all precharges we got in can_attach().
5561                  * We try charge one by one, but don't do any additional
5562                  * charges to mc.to if we have failed in charge once in attach()
5563                  * phase.
5564                  */
5565                 ret = mem_cgroup_do_precharge(1);
5566                 if (!ret)
5567                         goto retry;
5568         }
5569
5570         return ret;
5571 }
5572
5573 static void mem_cgroup_move_charge(struct mm_struct *mm)
5574 {
5575         struct vm_area_struct *vma;
5576
5577         lru_add_drain_all();
5578 retry:
5579         if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
5580                 /*
5581                  * Someone who are holding the mmap_sem might be waiting in
5582                  * waitq. So we cancel all extra charges, wake up all waiters,
5583                  * and retry. Because we cancel precharges, we might not be able
5584                  * to move enough charges, but moving charge is a best-effort
5585                  * feature anyway, so it wouldn't be a big problem.
5586                  */
5587                 __mem_cgroup_clear_mc();
5588                 cond_resched();
5589                 goto retry;
5590         }
5591         for (vma = mm->mmap; vma; vma = vma->vm_next) {
5592                 int ret;
5593                 struct mm_walk mem_cgroup_move_charge_walk = {
5594                         .pmd_entry = mem_cgroup_move_charge_pte_range,
5595                         .mm = mm,
5596                         .private = vma,
5597                 };
5598                 if (is_vm_hugetlb_page(vma))
5599                         continue;
5600                 ret = walk_page_range(vma->vm_start, vma->vm_end,
5601                                                 &mem_cgroup_move_charge_walk);
5602                 if (ret)
5603                         /*
5604                          * means we have consumed all precharges and failed in
5605                          * doing additional charge. Just abandon here.
5606                          */
5607                         break;
5608         }
5609         up_read(&mm->mmap_sem);
5610 }
5611
5612 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5613                                 struct cgroup *cont,
5614                                 struct cgroup *old_cont,
5615                                 struct task_struct *p)
5616 {
5617         struct mm_struct *mm = get_task_mm(p);
5618
5619         if (mm) {
5620                 if (mc.to)
5621                         mem_cgroup_move_charge(mm);
5622                 put_swap_token(mm);
5623                 mmput(mm);
5624         }
5625         if (mc.to)
5626                 mem_cgroup_clear_mc();
5627 }
5628 #else   /* !CONFIG_MMU */
5629 static int mem_cgroup_can_attach(struct cgroup_subsys *ss,
5630                                 struct cgroup *cgroup,
5631                                 struct task_struct *p)
5632 {
5633         return 0;
5634 }
5635 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss,
5636                                 struct cgroup *cgroup,
5637                                 struct task_struct *p)
5638 {
5639 }
5640 static void mem_cgroup_move_task(struct cgroup_subsys *ss,
5641                                 struct cgroup *cont,
5642                                 struct cgroup *old_cont,
5643                                 struct task_struct *p)
5644 {
5645 }
5646 #endif
5647
5648 struct cgroup_subsys mem_cgroup_subsys = {
5649         .name = "memory",
5650         .subsys_id = mem_cgroup_subsys_id,
5651         .create = mem_cgroup_create,
5652         .pre_destroy = mem_cgroup_pre_destroy,
5653         .destroy = mem_cgroup_destroy,
5654         .populate = mem_cgroup_populate,
5655         .can_attach = mem_cgroup_can_attach,
5656         .cancel_attach = mem_cgroup_cancel_attach,
5657         .attach = mem_cgroup_move_task,
5658         .early_init = 0,
5659         .use_id = 1,
5660 };
5661
5662 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP
5663 static int __init enable_swap_account(char *s)
5664 {
5665         /* consider enabled if no parameter or 1 is given */
5666         if (!strcmp(s, "1"))
5667                 really_do_swap_account = 1;
5668         else if (!strcmp(s, "0"))
5669                 really_do_swap_account = 0;
5670         return 1;
5671 }
5672 __setup("swapaccount=", enable_swap_account);
5673
5674 #endif