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