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