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