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