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