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