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