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