mm: memcg: prepare for byte-sized vmstat items
[linux-2.6-microblaze.git] / mm / memcontrol.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* memcontrol.c - Memory Controller
3  *
4  * Copyright IBM Corporation, 2007
5  * Author Balbir Singh <balbir@linux.vnet.ibm.com>
6  *
7  * Copyright 2007 OpenVZ SWsoft Inc
8  * Author: Pavel Emelianov <xemul@openvz.org>
9  *
10  * Memory thresholds
11  * Copyright (C) 2009 Nokia Corporation
12  * Author: Kirill A. Shutemov
13  *
14  * Kernel Memory Controller
15  * Copyright (C) 2012 Parallels Inc. and Google Inc.
16  * Authors: Glauber Costa and Suleiman Souhlal
17  *
18  * Native page reclaim
19  * Charge lifetime sanitation
20  * Lockless page tracking & accounting
21  * Unified hierarchy configuration model
22  * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
23  */
24
25 #include <linux/page_counter.h>
26 #include <linux/memcontrol.h>
27 #include <linux/cgroup.h>
28 #include <linux/pagewalk.h>
29 #include <linux/sched/mm.h>
30 #include <linux/shmem_fs.h>
31 #include <linux/hugetlb.h>
32 #include <linux/pagemap.h>
33 #include <linux/vm_event_item.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/poll.h>
49 #include <linux/sort.h>
50 #include <linux/fs.h>
51 #include <linux/seq_file.h>
52 #include <linux/vmpressure.h>
53 #include <linux/mm_inline.h>
54 #include <linux/swap_cgroup.h>
55 #include <linux/cpu.h>
56 #include <linux/oom.h>
57 #include <linux/lockdep.h>
58 #include <linux/file.h>
59 #include <linux/tracehook.h>
60 #include <linux/psi.h>
61 #include <linux/seq_buf.h>
62 #include "internal.h"
63 #include <net/sock.h>
64 #include <net/ip.h>
65 #include "slab.h"
66
67 #include <linux/uaccess.h>
68
69 #include <trace/events/vmscan.h>
70
71 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
72 EXPORT_SYMBOL(memory_cgrp_subsys);
73
74 struct mem_cgroup *root_mem_cgroup __read_mostly;
75
76 #define MEM_CGROUP_RECLAIM_RETRIES      5
77
78 /* Socket memory accounting disabled? */
79 static bool cgroup_memory_nosocket;
80
81 /* Kernel memory accounting disabled? */
82 static bool cgroup_memory_nokmem;
83
84 /* Whether the swap controller is active */
85 #ifdef CONFIG_MEMCG_SWAP
86 bool cgroup_memory_noswap __read_mostly;
87 #else
88 #define cgroup_memory_noswap            1
89 #endif
90
91 #ifdef CONFIG_CGROUP_WRITEBACK
92 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
93 #endif
94
95 /* Whether legacy memory+swap accounting is active */
96 static bool do_memsw_account(void)
97 {
98         return !cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_noswap;
99 }
100
101 #define THRESHOLDS_EVENTS_TARGET 128
102 #define SOFTLIMIT_EVENTS_TARGET 1024
103
104 /*
105  * Cgroups above their limits are maintained in a RB-Tree, independent of
106  * their hierarchy representation
107  */
108
109 struct mem_cgroup_tree_per_node {
110         struct rb_root rb_root;
111         struct rb_node *rb_rightmost;
112         spinlock_t lock;
113 };
114
115 struct mem_cgroup_tree {
116         struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
117 };
118
119 static struct mem_cgroup_tree soft_limit_tree __read_mostly;
120
121 /* for OOM */
122 struct mem_cgroup_eventfd_list {
123         struct list_head list;
124         struct eventfd_ctx *eventfd;
125 };
126
127 /*
128  * cgroup_event represents events which userspace want to receive.
129  */
130 struct mem_cgroup_event {
131         /*
132          * memcg which the event belongs to.
133          */
134         struct mem_cgroup *memcg;
135         /*
136          * eventfd to signal userspace about the event.
137          */
138         struct eventfd_ctx *eventfd;
139         /*
140          * Each of these stored in a list by the cgroup.
141          */
142         struct list_head list;
143         /*
144          * register_event() callback will be used to add new userspace
145          * waiter for changes related to this event.  Use eventfd_signal()
146          * on eventfd to send notification to userspace.
147          */
148         int (*register_event)(struct mem_cgroup *memcg,
149                               struct eventfd_ctx *eventfd, const char *args);
150         /*
151          * unregister_event() callback will be called when userspace closes
152          * the eventfd or on cgroup removing.  This callback must be set,
153          * if you want provide notification functionality.
154          */
155         void (*unregister_event)(struct mem_cgroup *memcg,
156                                  struct eventfd_ctx *eventfd);
157         /*
158          * All fields below needed to unregister event when
159          * userspace closes eventfd.
160          */
161         poll_table pt;
162         wait_queue_head_t *wqh;
163         wait_queue_entry_t wait;
164         struct work_struct remove;
165 };
166
167 static void mem_cgroup_threshold(struct mem_cgroup *memcg);
168 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
169
170 /* Stuffs for move charges at task migration. */
171 /*
172  * Types of charges to be moved.
173  */
174 #define MOVE_ANON       0x1U
175 #define MOVE_FILE       0x2U
176 #define MOVE_MASK       (MOVE_ANON | MOVE_FILE)
177
178 /* "mc" and its members are protected by cgroup_mutex */
179 static struct move_charge_struct {
180         spinlock_t        lock; /* for from, to */
181         struct mm_struct  *mm;
182         struct mem_cgroup *from;
183         struct mem_cgroup *to;
184         unsigned long flags;
185         unsigned long precharge;
186         unsigned long moved_charge;
187         unsigned long moved_swap;
188         struct task_struct *moving_task;        /* a task moving charges */
189         wait_queue_head_t waitq;                /* a waitq for other context */
190 } mc = {
191         .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
192         .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
193 };
194
195 /*
196  * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
197  * limit reclaim to prevent infinite loops, if they ever occur.
198  */
199 #define MEM_CGROUP_MAX_RECLAIM_LOOPS            100
200 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
201
202 enum charge_type {
203         MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
204         MEM_CGROUP_CHARGE_TYPE_ANON,
205         MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
206         MEM_CGROUP_CHARGE_TYPE_DROP,    /* a page was unused swap cache */
207         NR_CHARGE_TYPE,
208 };
209
210 /* for encoding cft->private value on file */
211 enum res_type {
212         _MEM,
213         _MEMSWAP,
214         _OOM_TYPE,
215         _KMEM,
216         _TCP,
217 };
218
219 #define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
220 #define MEMFILE_TYPE(val)       ((val) >> 16 & 0xffff)
221 #define MEMFILE_ATTR(val)       ((val) & 0xffff)
222 /* Used for OOM nofiier */
223 #define OOM_CONTROL             (0)
224
225 /*
226  * Iteration constructs for visiting all cgroups (under a tree).  If
227  * loops are exited prematurely (break), mem_cgroup_iter_break() must
228  * be used for reference counting.
229  */
230 #define for_each_mem_cgroup_tree(iter, root)            \
231         for (iter = mem_cgroup_iter(root, NULL, NULL);  \
232              iter != NULL;                              \
233              iter = mem_cgroup_iter(root, iter, NULL))
234
235 #define for_each_mem_cgroup(iter)                       \
236         for (iter = mem_cgroup_iter(NULL, NULL, NULL);  \
237              iter != NULL;                              \
238              iter = mem_cgroup_iter(NULL, iter, NULL))
239
240 static inline bool should_force_charge(void)
241 {
242         return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
243                 (current->flags & PF_EXITING);
244 }
245
246 /* Some nice accessors for the vmpressure. */
247 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
248 {
249         if (!memcg)
250                 memcg = root_mem_cgroup;
251         return &memcg->vmpressure;
252 }
253
254 struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
255 {
256         return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
257 }
258
259 #ifdef CONFIG_MEMCG_KMEM
260 /*
261  * This will be the memcg's index in each cache's ->memcg_params.memcg_caches.
262  * The main reason for not using cgroup id for this:
263  *  this works better in sparse environments, where we have a lot of memcgs,
264  *  but only a few kmem-limited. Or also, if we have, for instance, 200
265  *  memcgs, and none but the 200th is kmem-limited, we'd have to have a
266  *  200 entry array for that.
267  *
268  * The current size of the caches array is stored in memcg_nr_cache_ids. It
269  * will double each time we have to increase it.
270  */
271 static DEFINE_IDA(memcg_cache_ida);
272 int memcg_nr_cache_ids;
273
274 /* Protects memcg_nr_cache_ids */
275 static DECLARE_RWSEM(memcg_cache_ids_sem);
276
277 void memcg_get_cache_ids(void)
278 {
279         down_read(&memcg_cache_ids_sem);
280 }
281
282 void memcg_put_cache_ids(void)
283 {
284         up_read(&memcg_cache_ids_sem);
285 }
286
287 /*
288  * MIN_SIZE is different than 1, because we would like to avoid going through
289  * the alloc/free process all the time. In a small machine, 4 kmem-limited
290  * cgroups is a reasonable guess. In the future, it could be a parameter or
291  * tunable, but that is strictly not necessary.
292  *
293  * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
294  * this constant directly from cgroup, but it is understandable that this is
295  * better kept as an internal representation in cgroup.c. In any case, the
296  * cgrp_id space is not getting any smaller, and we don't have to necessarily
297  * increase ours as well if it increases.
298  */
299 #define MEMCG_CACHES_MIN_SIZE 4
300 #define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
301
302 /*
303  * A lot of the calls to the cache allocation functions are expected to be
304  * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
305  * conditional to this static branch, we'll have to allow modules that does
306  * kmem_cache_alloc and the such to see this symbol as well
307  */
308 DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
309 EXPORT_SYMBOL(memcg_kmem_enabled_key);
310
311 struct workqueue_struct *memcg_kmem_cache_wq;
312 #endif
313
314 static int memcg_shrinker_map_size;
315 static DEFINE_MUTEX(memcg_shrinker_map_mutex);
316
317 static void memcg_free_shrinker_map_rcu(struct rcu_head *head)
318 {
319         kvfree(container_of(head, struct memcg_shrinker_map, rcu));
320 }
321
322 static int memcg_expand_one_shrinker_map(struct mem_cgroup *memcg,
323                                          int size, int old_size)
324 {
325         struct memcg_shrinker_map *new, *old;
326         int nid;
327
328         lockdep_assert_held(&memcg_shrinker_map_mutex);
329
330         for_each_node(nid) {
331                 old = rcu_dereference_protected(
332                         mem_cgroup_nodeinfo(memcg, nid)->shrinker_map, true);
333                 /* Not yet online memcg */
334                 if (!old)
335                         return 0;
336
337                 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
338                 if (!new)
339                         return -ENOMEM;
340
341                 /* Set all old bits, clear all new bits */
342                 memset(new->map, (int)0xff, old_size);
343                 memset((void *)new->map + old_size, 0, size - old_size);
344
345                 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, new);
346                 call_rcu(&old->rcu, memcg_free_shrinker_map_rcu);
347         }
348
349         return 0;
350 }
351
352 static void memcg_free_shrinker_maps(struct mem_cgroup *memcg)
353 {
354         struct mem_cgroup_per_node *pn;
355         struct memcg_shrinker_map *map;
356         int nid;
357
358         if (mem_cgroup_is_root(memcg))
359                 return;
360
361         for_each_node(nid) {
362                 pn = mem_cgroup_nodeinfo(memcg, nid);
363                 map = rcu_dereference_protected(pn->shrinker_map, true);
364                 if (map)
365                         kvfree(map);
366                 rcu_assign_pointer(pn->shrinker_map, NULL);
367         }
368 }
369
370 static int memcg_alloc_shrinker_maps(struct mem_cgroup *memcg)
371 {
372         struct memcg_shrinker_map *map;
373         int nid, size, ret = 0;
374
375         if (mem_cgroup_is_root(memcg))
376                 return 0;
377
378         mutex_lock(&memcg_shrinker_map_mutex);
379         size = memcg_shrinker_map_size;
380         for_each_node(nid) {
381                 map = kvzalloc_node(sizeof(*map) + size, GFP_KERNEL, nid);
382                 if (!map) {
383                         memcg_free_shrinker_maps(memcg);
384                         ret = -ENOMEM;
385                         break;
386                 }
387                 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, map);
388         }
389         mutex_unlock(&memcg_shrinker_map_mutex);
390
391         return ret;
392 }
393
394 int memcg_expand_shrinker_maps(int new_id)
395 {
396         int size, old_size, ret = 0;
397         struct mem_cgroup *memcg;
398
399         size = DIV_ROUND_UP(new_id + 1, BITS_PER_LONG) * sizeof(unsigned long);
400         old_size = memcg_shrinker_map_size;
401         if (size <= old_size)
402                 return 0;
403
404         mutex_lock(&memcg_shrinker_map_mutex);
405         if (!root_mem_cgroup)
406                 goto unlock;
407
408         for_each_mem_cgroup(memcg) {
409                 if (mem_cgroup_is_root(memcg))
410                         continue;
411                 ret = memcg_expand_one_shrinker_map(memcg, size, old_size);
412                 if (ret) {
413                         mem_cgroup_iter_break(NULL, memcg);
414                         goto unlock;
415                 }
416         }
417 unlock:
418         if (!ret)
419                 memcg_shrinker_map_size = size;
420         mutex_unlock(&memcg_shrinker_map_mutex);
421         return ret;
422 }
423
424 void memcg_set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
425 {
426         if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
427                 struct memcg_shrinker_map *map;
428
429                 rcu_read_lock();
430                 map = rcu_dereference(memcg->nodeinfo[nid]->shrinker_map);
431                 /* Pairs with smp mb in shrink_slab() */
432                 smp_mb__before_atomic();
433                 set_bit(shrinker_id, map->map);
434                 rcu_read_unlock();
435         }
436 }
437
438 /**
439  * mem_cgroup_css_from_page - css of the memcg associated with a page
440  * @page: page of interest
441  *
442  * If memcg is bound to the default hierarchy, css of the memcg associated
443  * with @page is returned.  The returned css remains associated with @page
444  * until it is released.
445  *
446  * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
447  * is returned.
448  */
449 struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
450 {
451         struct mem_cgroup *memcg;
452
453         memcg = page->mem_cgroup;
454
455         if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
456                 memcg = root_mem_cgroup;
457
458         return &memcg->css;
459 }
460
461 /**
462  * page_cgroup_ino - return inode number of the memcg a page is charged to
463  * @page: the page
464  *
465  * Look up the closest online ancestor of the memory cgroup @page is charged to
466  * and return its inode number or 0 if @page is not charged to any cgroup. It
467  * is safe to call this function without holding a reference to @page.
468  *
469  * Note, this function is inherently racy, because there is nothing to prevent
470  * the cgroup inode from getting torn down and potentially reallocated a moment
471  * after page_cgroup_ino() returns, so it only should be used by callers that
472  * do not care (such as procfs interfaces).
473  */
474 ino_t page_cgroup_ino(struct page *page)
475 {
476         struct mem_cgroup *memcg;
477         unsigned long ino = 0;
478
479         rcu_read_lock();
480         if (PageSlab(page) && !PageTail(page))
481                 memcg = memcg_from_slab_page(page);
482         else
483                 memcg = READ_ONCE(page->mem_cgroup);
484         while (memcg && !(memcg->css.flags & CSS_ONLINE))
485                 memcg = parent_mem_cgroup(memcg);
486         if (memcg)
487                 ino = cgroup_ino(memcg->css.cgroup);
488         rcu_read_unlock();
489         return ino;
490 }
491
492 static struct mem_cgroup_per_node *
493 mem_cgroup_page_nodeinfo(struct mem_cgroup *memcg, struct page *page)
494 {
495         int nid = page_to_nid(page);
496
497         return memcg->nodeinfo[nid];
498 }
499
500 static struct mem_cgroup_tree_per_node *
501 soft_limit_tree_node(int nid)
502 {
503         return soft_limit_tree.rb_tree_per_node[nid];
504 }
505
506 static struct mem_cgroup_tree_per_node *
507 soft_limit_tree_from_page(struct page *page)
508 {
509         int nid = page_to_nid(page);
510
511         return soft_limit_tree.rb_tree_per_node[nid];
512 }
513
514 static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
515                                          struct mem_cgroup_tree_per_node *mctz,
516                                          unsigned long new_usage_in_excess)
517 {
518         struct rb_node **p = &mctz->rb_root.rb_node;
519         struct rb_node *parent = NULL;
520         struct mem_cgroup_per_node *mz_node;
521         bool rightmost = true;
522
523         if (mz->on_tree)
524                 return;
525
526         mz->usage_in_excess = new_usage_in_excess;
527         if (!mz->usage_in_excess)
528                 return;
529         while (*p) {
530                 parent = *p;
531                 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
532                                         tree_node);
533                 if (mz->usage_in_excess < mz_node->usage_in_excess) {
534                         p = &(*p)->rb_left;
535                         rightmost = false;
536                 }
537
538                 /*
539                  * We can't avoid mem cgroups that are over their soft
540                  * limit by the same amount
541                  */
542                 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
543                         p = &(*p)->rb_right;
544         }
545
546         if (rightmost)
547                 mctz->rb_rightmost = &mz->tree_node;
548
549         rb_link_node(&mz->tree_node, parent, p);
550         rb_insert_color(&mz->tree_node, &mctz->rb_root);
551         mz->on_tree = true;
552 }
553
554 static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
555                                          struct mem_cgroup_tree_per_node *mctz)
556 {
557         if (!mz->on_tree)
558                 return;
559
560         if (&mz->tree_node == mctz->rb_rightmost)
561                 mctz->rb_rightmost = rb_prev(&mz->tree_node);
562
563         rb_erase(&mz->tree_node, &mctz->rb_root);
564         mz->on_tree = false;
565 }
566
567 static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
568                                        struct mem_cgroup_tree_per_node *mctz)
569 {
570         unsigned long flags;
571
572         spin_lock_irqsave(&mctz->lock, flags);
573         __mem_cgroup_remove_exceeded(mz, mctz);
574         spin_unlock_irqrestore(&mctz->lock, flags);
575 }
576
577 static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
578 {
579         unsigned long nr_pages = page_counter_read(&memcg->memory);
580         unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
581         unsigned long excess = 0;
582
583         if (nr_pages > soft_limit)
584                 excess = nr_pages - soft_limit;
585
586         return excess;
587 }
588
589 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
590 {
591         unsigned long excess;
592         struct mem_cgroup_per_node *mz;
593         struct mem_cgroup_tree_per_node *mctz;
594
595         mctz = soft_limit_tree_from_page(page);
596         if (!mctz)
597                 return;
598         /*
599          * Necessary to update all ancestors when hierarchy is used.
600          * because their event counter is not touched.
601          */
602         for (; memcg; memcg = parent_mem_cgroup(memcg)) {
603                 mz = mem_cgroup_page_nodeinfo(memcg, page);
604                 excess = soft_limit_excess(memcg);
605                 /*
606                  * We have to update the tree if mz is on RB-tree or
607                  * mem is over its softlimit.
608                  */
609                 if (excess || mz->on_tree) {
610                         unsigned long flags;
611
612                         spin_lock_irqsave(&mctz->lock, flags);
613                         /* if on-tree, remove it */
614                         if (mz->on_tree)
615                                 __mem_cgroup_remove_exceeded(mz, mctz);
616                         /*
617                          * Insert again. mz->usage_in_excess will be updated.
618                          * If excess is 0, no tree ops.
619                          */
620                         __mem_cgroup_insert_exceeded(mz, mctz, excess);
621                         spin_unlock_irqrestore(&mctz->lock, flags);
622                 }
623         }
624 }
625
626 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
627 {
628         struct mem_cgroup_tree_per_node *mctz;
629         struct mem_cgroup_per_node *mz;
630         int nid;
631
632         for_each_node(nid) {
633                 mz = mem_cgroup_nodeinfo(memcg, nid);
634                 mctz = soft_limit_tree_node(nid);
635                 if (mctz)
636                         mem_cgroup_remove_exceeded(mz, mctz);
637         }
638 }
639
640 static struct mem_cgroup_per_node *
641 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
642 {
643         struct mem_cgroup_per_node *mz;
644
645 retry:
646         mz = NULL;
647         if (!mctz->rb_rightmost)
648                 goto done;              /* Nothing to reclaim from */
649
650         mz = rb_entry(mctz->rb_rightmost,
651                       struct mem_cgroup_per_node, tree_node);
652         /*
653          * Remove the node now but someone else can add it back,
654          * we will to add it back at the end of reclaim to its correct
655          * position in the tree.
656          */
657         __mem_cgroup_remove_exceeded(mz, mctz);
658         if (!soft_limit_excess(mz->memcg) ||
659             !css_tryget(&mz->memcg->css))
660                 goto retry;
661 done:
662         return mz;
663 }
664
665 static struct mem_cgroup_per_node *
666 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
667 {
668         struct mem_cgroup_per_node *mz;
669
670         spin_lock_irq(&mctz->lock);
671         mz = __mem_cgroup_largest_soft_limit_node(mctz);
672         spin_unlock_irq(&mctz->lock);
673         return mz;
674 }
675
676 /**
677  * __mod_memcg_state - update cgroup memory statistics
678  * @memcg: the memory cgroup
679  * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
680  * @val: delta to add to the counter, can be negative
681  */
682 void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
683 {
684         long x, threshold = MEMCG_CHARGE_BATCH;
685
686         if (mem_cgroup_disabled())
687                 return;
688
689         if (vmstat_item_in_bytes(idx))
690                 threshold <<= PAGE_SHIFT;
691
692         x = val + __this_cpu_read(memcg->vmstats_percpu->stat[idx]);
693         if (unlikely(abs(x) > threshold)) {
694                 struct mem_cgroup *mi;
695
696                 /*
697                  * Batch local counters to keep them in sync with
698                  * the hierarchical ones.
699                  */
700                 __this_cpu_add(memcg->vmstats_local->stat[idx], x);
701                 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
702                         atomic_long_add(x, &mi->vmstats[idx]);
703                 x = 0;
704         }
705         __this_cpu_write(memcg->vmstats_percpu->stat[idx], x);
706 }
707
708 static struct mem_cgroup_per_node *
709 parent_nodeinfo(struct mem_cgroup_per_node *pn, int nid)
710 {
711         struct mem_cgroup *parent;
712
713         parent = parent_mem_cgroup(pn->memcg);
714         if (!parent)
715                 return NULL;
716         return mem_cgroup_nodeinfo(parent, nid);
717 }
718
719 void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
720                               int val)
721 {
722         struct mem_cgroup_per_node *pn;
723         struct mem_cgroup *memcg;
724         long x, threshold = MEMCG_CHARGE_BATCH;
725
726         pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
727         memcg = pn->memcg;
728
729         /* Update memcg */
730         __mod_memcg_state(memcg, idx, val);
731
732         /* Update lruvec */
733         __this_cpu_add(pn->lruvec_stat_local->count[idx], val);
734
735         if (vmstat_item_in_bytes(idx))
736                 threshold <<= PAGE_SHIFT;
737
738         x = val + __this_cpu_read(pn->lruvec_stat_cpu->count[idx]);
739         if (unlikely(abs(x) > threshold)) {
740                 pg_data_t *pgdat = lruvec_pgdat(lruvec);
741                 struct mem_cgroup_per_node *pi;
742
743                 for (pi = pn; pi; pi = parent_nodeinfo(pi, pgdat->node_id))
744                         atomic_long_add(x, &pi->lruvec_stat[idx]);
745                 x = 0;
746         }
747         __this_cpu_write(pn->lruvec_stat_cpu->count[idx], x);
748 }
749
750 /**
751  * __mod_lruvec_state - update lruvec memory statistics
752  * @lruvec: the lruvec
753  * @idx: the stat item
754  * @val: delta to add to the counter, can be negative
755  *
756  * The lruvec is the intersection of the NUMA node and a cgroup. This
757  * function updates the all three counters that are affected by a
758  * change of state at this level: per-node, per-cgroup, per-lruvec.
759  */
760 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
761                         int val)
762 {
763         /* Update node */
764         __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
765
766         /* Update memcg and lruvec */
767         if (!mem_cgroup_disabled())
768                 __mod_memcg_lruvec_state(lruvec, idx, val);
769 }
770
771 void __mod_lruvec_slab_state(void *p, enum node_stat_item idx, int val)
772 {
773         pg_data_t *pgdat = page_pgdat(virt_to_page(p));
774         struct mem_cgroup *memcg;
775         struct lruvec *lruvec;
776
777         rcu_read_lock();
778         memcg = mem_cgroup_from_obj(p);
779
780         /* Untracked pages have no memcg, no lruvec. Update only the node */
781         if (!memcg || memcg == root_mem_cgroup) {
782                 __mod_node_page_state(pgdat, idx, val);
783         } else {
784                 lruvec = mem_cgroup_lruvec(memcg, pgdat);
785                 __mod_lruvec_state(lruvec, idx, val);
786         }
787         rcu_read_unlock();
788 }
789
790 void mod_memcg_obj_state(void *p, int idx, int val)
791 {
792         struct mem_cgroup *memcg;
793
794         rcu_read_lock();
795         memcg = mem_cgroup_from_obj(p);
796         if (memcg)
797                 mod_memcg_state(memcg, idx, val);
798         rcu_read_unlock();
799 }
800
801 /**
802  * __count_memcg_events - account VM events in a cgroup
803  * @memcg: the memory cgroup
804  * @idx: the event item
805  * @count: the number of events that occured
806  */
807 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
808                           unsigned long count)
809 {
810         unsigned long x;
811
812         if (mem_cgroup_disabled())
813                 return;
814
815         x = count + __this_cpu_read(memcg->vmstats_percpu->events[idx]);
816         if (unlikely(x > MEMCG_CHARGE_BATCH)) {
817                 struct mem_cgroup *mi;
818
819                 /*
820                  * Batch local counters to keep them in sync with
821                  * the hierarchical ones.
822                  */
823                 __this_cpu_add(memcg->vmstats_local->events[idx], x);
824                 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
825                         atomic_long_add(x, &mi->vmevents[idx]);
826                 x = 0;
827         }
828         __this_cpu_write(memcg->vmstats_percpu->events[idx], x);
829 }
830
831 static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
832 {
833         return atomic_long_read(&memcg->vmevents[event]);
834 }
835
836 static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
837 {
838         long x = 0;
839         int cpu;
840
841         for_each_possible_cpu(cpu)
842                 x += per_cpu(memcg->vmstats_local->events[event], cpu);
843         return x;
844 }
845
846 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
847                                          struct page *page,
848                                          int nr_pages)
849 {
850         /* pagein of a big page is an event. So, ignore page size */
851         if (nr_pages > 0)
852                 __count_memcg_events(memcg, PGPGIN, 1);
853         else {
854                 __count_memcg_events(memcg, PGPGOUT, 1);
855                 nr_pages = -nr_pages; /* for event */
856         }
857
858         __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
859 }
860
861 static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
862                                        enum mem_cgroup_events_target target)
863 {
864         unsigned long val, next;
865
866         val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
867         next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
868         /* from time_after() in jiffies.h */
869         if ((long)(next - val) < 0) {
870                 switch (target) {
871                 case MEM_CGROUP_TARGET_THRESH:
872                         next = val + THRESHOLDS_EVENTS_TARGET;
873                         break;
874                 case MEM_CGROUP_TARGET_SOFTLIMIT:
875                         next = val + SOFTLIMIT_EVENTS_TARGET;
876                         break;
877                 default:
878                         break;
879                 }
880                 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
881                 return true;
882         }
883         return false;
884 }
885
886 /*
887  * Check events in order.
888  *
889  */
890 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
891 {
892         /* threshold event is triggered in finer grain than soft limit */
893         if (unlikely(mem_cgroup_event_ratelimit(memcg,
894                                                 MEM_CGROUP_TARGET_THRESH))) {
895                 bool do_softlimit;
896
897                 do_softlimit = mem_cgroup_event_ratelimit(memcg,
898                                                 MEM_CGROUP_TARGET_SOFTLIMIT);
899                 mem_cgroup_threshold(memcg);
900                 if (unlikely(do_softlimit))
901                         mem_cgroup_update_tree(memcg, page);
902         }
903 }
904
905 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
906 {
907         /*
908          * mm_update_next_owner() may clear mm->owner to NULL
909          * if it races with swapoff, page migration, etc.
910          * So this can be called with p == NULL.
911          */
912         if (unlikely(!p))
913                 return NULL;
914
915         return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
916 }
917 EXPORT_SYMBOL(mem_cgroup_from_task);
918
919 /**
920  * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
921  * @mm: mm from which memcg should be extracted. It can be NULL.
922  *
923  * Obtain a reference on mm->memcg and returns it if successful. Otherwise
924  * root_mem_cgroup is returned. However if mem_cgroup is disabled, NULL is
925  * returned.
926  */
927 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
928 {
929         struct mem_cgroup *memcg;
930
931         if (mem_cgroup_disabled())
932                 return NULL;
933
934         rcu_read_lock();
935         do {
936                 /*
937                  * Page cache insertions can happen withou an
938                  * actual mm context, e.g. during disk probing
939                  * on boot, loopback IO, acct() writes etc.
940                  */
941                 if (unlikely(!mm))
942                         memcg = root_mem_cgroup;
943                 else {
944                         memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
945                         if (unlikely(!memcg))
946                                 memcg = root_mem_cgroup;
947                 }
948         } while (!css_tryget(&memcg->css));
949         rcu_read_unlock();
950         return memcg;
951 }
952 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
953
954 /**
955  * get_mem_cgroup_from_page: Obtain a reference on given page's memcg.
956  * @page: page from which memcg should be extracted.
957  *
958  * Obtain a reference on page->memcg and returns it if successful. Otherwise
959  * root_mem_cgroup is returned.
960  */
961 struct mem_cgroup *get_mem_cgroup_from_page(struct page *page)
962 {
963         struct mem_cgroup *memcg = page->mem_cgroup;
964
965         if (mem_cgroup_disabled())
966                 return NULL;
967
968         rcu_read_lock();
969         /* Page should not get uncharged and freed memcg under us. */
970         if (!memcg || WARN_ON_ONCE(!css_tryget(&memcg->css)))
971                 memcg = root_mem_cgroup;
972         rcu_read_unlock();
973         return memcg;
974 }
975 EXPORT_SYMBOL(get_mem_cgroup_from_page);
976
977 /**
978  * If current->active_memcg is non-NULL, do not fallback to current->mm->memcg.
979  */
980 static __always_inline struct mem_cgroup *get_mem_cgroup_from_current(void)
981 {
982         if (unlikely(current->active_memcg)) {
983                 struct mem_cgroup *memcg;
984
985                 rcu_read_lock();
986                 /* current->active_memcg must hold a ref. */
987                 if (WARN_ON_ONCE(!css_tryget(&current->active_memcg->css)))
988                         memcg = root_mem_cgroup;
989                 else
990                         memcg = current->active_memcg;
991                 rcu_read_unlock();
992                 return memcg;
993         }
994         return get_mem_cgroup_from_mm(current->mm);
995 }
996
997 /**
998  * mem_cgroup_iter - iterate over memory cgroup hierarchy
999  * @root: hierarchy root
1000  * @prev: previously returned memcg, NULL on first invocation
1001  * @reclaim: cookie for shared reclaim walks, NULL for full walks
1002  *
1003  * Returns references to children of the hierarchy below @root, or
1004  * @root itself, or %NULL after a full round-trip.
1005  *
1006  * Caller must pass the return value in @prev on subsequent
1007  * invocations for reference counting, or use mem_cgroup_iter_break()
1008  * to cancel a hierarchy walk before the round-trip is complete.
1009  *
1010  * Reclaimers can specify a node and a priority level in @reclaim to
1011  * divide up the memcgs in the hierarchy among all concurrent
1012  * reclaimers operating on the same node and priority.
1013  */
1014 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1015                                    struct mem_cgroup *prev,
1016                                    struct mem_cgroup_reclaim_cookie *reclaim)
1017 {
1018         struct mem_cgroup_reclaim_iter *iter;
1019         struct cgroup_subsys_state *css = NULL;
1020         struct mem_cgroup *memcg = NULL;
1021         struct mem_cgroup *pos = NULL;
1022
1023         if (mem_cgroup_disabled())
1024                 return NULL;
1025
1026         if (!root)
1027                 root = root_mem_cgroup;
1028
1029         if (prev && !reclaim)
1030                 pos = prev;
1031
1032         if (!root->use_hierarchy && root != root_mem_cgroup) {
1033                 if (prev)
1034                         goto out;
1035                 return root;
1036         }
1037
1038         rcu_read_lock();
1039
1040         if (reclaim) {
1041                 struct mem_cgroup_per_node *mz;
1042
1043                 mz = mem_cgroup_nodeinfo(root, reclaim->pgdat->node_id);
1044                 iter = &mz->iter;
1045
1046                 if (prev && reclaim->generation != iter->generation)
1047                         goto out_unlock;
1048
1049                 while (1) {
1050                         pos = READ_ONCE(iter->position);
1051                         if (!pos || css_tryget(&pos->css))
1052                                 break;
1053                         /*
1054                          * css reference reached zero, so iter->position will
1055                          * be cleared by ->css_released. However, we should not
1056                          * rely on this happening soon, because ->css_released
1057                          * is called from a work queue, and by busy-waiting we
1058                          * might block it. So we clear iter->position right
1059                          * away.
1060                          */
1061                         (void)cmpxchg(&iter->position, pos, NULL);
1062                 }
1063         }
1064
1065         if (pos)
1066                 css = &pos->css;
1067
1068         for (;;) {
1069                 css = css_next_descendant_pre(css, &root->css);
1070                 if (!css) {
1071                         /*
1072                          * Reclaimers share the hierarchy walk, and a
1073                          * new one might jump in right at the end of
1074                          * the hierarchy - make sure they see at least
1075                          * one group and restart from the beginning.
1076                          */
1077                         if (!prev)
1078                                 continue;
1079                         break;
1080                 }
1081
1082                 /*
1083                  * Verify the css and acquire a reference.  The root
1084                  * is provided by the caller, so we know it's alive
1085                  * and kicking, and don't take an extra reference.
1086                  */
1087                 memcg = mem_cgroup_from_css(css);
1088
1089                 if (css == &root->css)
1090                         break;
1091
1092                 if (css_tryget(css))
1093                         break;
1094
1095                 memcg = NULL;
1096         }
1097
1098         if (reclaim) {
1099                 /*
1100                  * The position could have already been updated by a competing
1101                  * thread, so check that the value hasn't changed since we read
1102                  * it to avoid reclaiming from the same cgroup twice.
1103                  */
1104                 (void)cmpxchg(&iter->position, pos, memcg);
1105
1106                 if (pos)
1107                         css_put(&pos->css);
1108
1109                 if (!memcg)
1110                         iter->generation++;
1111                 else if (!prev)
1112                         reclaim->generation = iter->generation;
1113         }
1114
1115 out_unlock:
1116         rcu_read_unlock();
1117 out:
1118         if (prev && prev != root)
1119                 css_put(&prev->css);
1120
1121         return memcg;
1122 }
1123
1124 /**
1125  * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1126  * @root: hierarchy root
1127  * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1128  */
1129 void mem_cgroup_iter_break(struct mem_cgroup *root,
1130                            struct mem_cgroup *prev)
1131 {
1132         if (!root)
1133                 root = root_mem_cgroup;
1134         if (prev && prev != root)
1135                 css_put(&prev->css);
1136 }
1137
1138 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1139                                         struct mem_cgroup *dead_memcg)
1140 {
1141         struct mem_cgroup_reclaim_iter *iter;
1142         struct mem_cgroup_per_node *mz;
1143         int nid;
1144
1145         for_each_node(nid) {
1146                 mz = mem_cgroup_nodeinfo(from, nid);
1147                 iter = &mz->iter;
1148                 cmpxchg(&iter->position, dead_memcg, NULL);
1149         }
1150 }
1151
1152 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1153 {
1154         struct mem_cgroup *memcg = dead_memcg;
1155         struct mem_cgroup *last;
1156
1157         do {
1158                 __invalidate_reclaim_iterators(memcg, dead_memcg);
1159                 last = memcg;
1160         } while ((memcg = parent_mem_cgroup(memcg)));
1161
1162         /*
1163          * When cgruop1 non-hierarchy mode is used,
1164          * parent_mem_cgroup() does not walk all the way up to the
1165          * cgroup root (root_mem_cgroup). So we have to handle
1166          * dead_memcg from cgroup root separately.
1167          */
1168         if (last != root_mem_cgroup)
1169                 __invalidate_reclaim_iterators(root_mem_cgroup,
1170                                                 dead_memcg);
1171 }
1172
1173 /**
1174  * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1175  * @memcg: hierarchy root
1176  * @fn: function to call for each task
1177  * @arg: argument passed to @fn
1178  *
1179  * This function iterates over tasks attached to @memcg or to any of its
1180  * descendants and calls @fn for each task. If @fn returns a non-zero
1181  * value, the function breaks the iteration loop and returns the value.
1182  * Otherwise, it will iterate over all tasks and return 0.
1183  *
1184  * This function must not be called for the root memory cgroup.
1185  */
1186 int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1187                           int (*fn)(struct task_struct *, void *), void *arg)
1188 {
1189         struct mem_cgroup *iter;
1190         int ret = 0;
1191
1192         BUG_ON(memcg == root_mem_cgroup);
1193
1194         for_each_mem_cgroup_tree(iter, memcg) {
1195                 struct css_task_iter it;
1196                 struct task_struct *task;
1197
1198                 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1199                 while (!ret && (task = css_task_iter_next(&it)))
1200                         ret = fn(task, arg);
1201                 css_task_iter_end(&it);
1202                 if (ret) {
1203                         mem_cgroup_iter_break(memcg, iter);
1204                         break;
1205                 }
1206         }
1207         return ret;
1208 }
1209
1210 /**
1211  * mem_cgroup_page_lruvec - return lruvec for isolating/putting an LRU page
1212  * @page: the page
1213  * @pgdat: pgdat of the page
1214  *
1215  * This function relies on page->mem_cgroup being stable - see the
1216  * access rules in commit_charge().
1217  */
1218 struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct pglist_data *pgdat)
1219 {
1220         struct mem_cgroup_per_node *mz;
1221         struct mem_cgroup *memcg;
1222         struct lruvec *lruvec;
1223
1224         if (mem_cgroup_disabled()) {
1225                 lruvec = &pgdat->__lruvec;
1226                 goto out;
1227         }
1228
1229         memcg = page->mem_cgroup;
1230         /*
1231          * Swapcache readahead pages are added to the LRU - and
1232          * possibly migrated - before they are charged.
1233          */
1234         if (!memcg)
1235                 memcg = root_mem_cgroup;
1236
1237         mz = mem_cgroup_page_nodeinfo(memcg, page);
1238         lruvec = &mz->lruvec;
1239 out:
1240         /*
1241          * Since a node can be onlined after the mem_cgroup was created,
1242          * we have to be prepared to initialize lruvec->zone here;
1243          * and if offlined then reonlined, we need to reinitialize it.
1244          */
1245         if (unlikely(lruvec->pgdat != pgdat))
1246                 lruvec->pgdat = pgdat;
1247         return lruvec;
1248 }
1249
1250 /**
1251  * mem_cgroup_update_lru_size - account for adding or removing an lru page
1252  * @lruvec: mem_cgroup per zone lru vector
1253  * @lru: index of lru list the page is sitting on
1254  * @zid: zone id of the accounted pages
1255  * @nr_pages: positive when adding or negative when removing
1256  *
1257  * This function must be called under lru_lock, just before a page is added
1258  * to or just after a page is removed from an lru list (that ordering being
1259  * so as to allow it to check that lru_size 0 is consistent with list_empty).
1260  */
1261 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1262                                 int zid, int nr_pages)
1263 {
1264         struct mem_cgroup_per_node *mz;
1265         unsigned long *lru_size;
1266         long size;
1267
1268         if (mem_cgroup_disabled())
1269                 return;
1270
1271         mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1272         lru_size = &mz->lru_zone_size[zid][lru];
1273
1274         if (nr_pages < 0)
1275                 *lru_size += nr_pages;
1276
1277         size = *lru_size;
1278         if (WARN_ONCE(size < 0,
1279                 "%s(%p, %d, %d): lru_size %ld\n",
1280                 __func__, lruvec, lru, nr_pages, size)) {
1281                 VM_BUG_ON(1);
1282                 *lru_size = 0;
1283         }
1284
1285         if (nr_pages > 0)
1286                 *lru_size += nr_pages;
1287 }
1288
1289 /**
1290  * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1291  * @memcg: the memory cgroup
1292  *
1293  * Returns the maximum amount of memory @mem can be charged with, in
1294  * pages.
1295  */
1296 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1297 {
1298         unsigned long margin = 0;
1299         unsigned long count;
1300         unsigned long limit;
1301
1302         count = page_counter_read(&memcg->memory);
1303         limit = READ_ONCE(memcg->memory.max);
1304         if (count < limit)
1305                 margin = limit - count;
1306
1307         if (do_memsw_account()) {
1308                 count = page_counter_read(&memcg->memsw);
1309                 limit = READ_ONCE(memcg->memsw.max);
1310                 if (count < limit)
1311                         margin = min(margin, limit - count);
1312                 else
1313                         margin = 0;
1314         }
1315
1316         return margin;
1317 }
1318
1319 /*
1320  * A routine for checking "mem" is under move_account() or not.
1321  *
1322  * Checking a cgroup is mc.from or mc.to or under hierarchy of
1323  * moving cgroups. This is for waiting at high-memory pressure
1324  * caused by "move".
1325  */
1326 static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1327 {
1328         struct mem_cgroup *from;
1329         struct mem_cgroup *to;
1330         bool ret = false;
1331         /*
1332          * Unlike task_move routines, we access mc.to, mc.from not under
1333          * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1334          */
1335         spin_lock(&mc.lock);
1336         from = mc.from;
1337         to = mc.to;
1338         if (!from)
1339                 goto unlock;
1340
1341         ret = mem_cgroup_is_descendant(from, memcg) ||
1342                 mem_cgroup_is_descendant(to, memcg);
1343 unlock:
1344         spin_unlock(&mc.lock);
1345         return ret;
1346 }
1347
1348 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1349 {
1350         if (mc.moving_task && current != mc.moving_task) {
1351                 if (mem_cgroup_under_move(memcg)) {
1352                         DEFINE_WAIT(wait);
1353                         prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1354                         /* moving charge context might have finished. */
1355                         if (mc.moving_task)
1356                                 schedule();
1357                         finish_wait(&mc.waitq, &wait);
1358                         return true;
1359                 }
1360         }
1361         return false;
1362 }
1363
1364 static char *memory_stat_format(struct mem_cgroup *memcg)
1365 {
1366         struct seq_buf s;
1367         int i;
1368
1369         seq_buf_init(&s, kmalloc(PAGE_SIZE, GFP_KERNEL), PAGE_SIZE);
1370         if (!s.buffer)
1371                 return NULL;
1372
1373         /*
1374          * Provide statistics on the state of the memory subsystem as
1375          * well as cumulative event counters that show past behavior.
1376          *
1377          * This list is ordered following a combination of these gradients:
1378          * 1) generic big picture -> specifics and details
1379          * 2) reflecting userspace activity -> reflecting kernel heuristics
1380          *
1381          * Current memory state:
1382          */
1383
1384         seq_buf_printf(&s, "anon %llu\n",
1385                        (u64)memcg_page_state(memcg, NR_ANON_MAPPED) *
1386                        PAGE_SIZE);
1387         seq_buf_printf(&s, "file %llu\n",
1388                        (u64)memcg_page_state(memcg, NR_FILE_PAGES) *
1389                        PAGE_SIZE);
1390         seq_buf_printf(&s, "kernel_stack %llu\n",
1391                        (u64)memcg_page_state(memcg, MEMCG_KERNEL_STACK_KB) *
1392                        1024);
1393         seq_buf_printf(&s, "slab %llu\n",
1394                        (u64)(memcg_page_state(memcg, NR_SLAB_RECLAIMABLE) +
1395                              memcg_page_state(memcg, NR_SLAB_UNRECLAIMABLE)) *
1396                        PAGE_SIZE);
1397         seq_buf_printf(&s, "sock %llu\n",
1398                        (u64)memcg_page_state(memcg, MEMCG_SOCK) *
1399                        PAGE_SIZE);
1400
1401         seq_buf_printf(&s, "shmem %llu\n",
1402                        (u64)memcg_page_state(memcg, NR_SHMEM) *
1403                        PAGE_SIZE);
1404         seq_buf_printf(&s, "file_mapped %llu\n",
1405                        (u64)memcg_page_state(memcg, NR_FILE_MAPPED) *
1406                        PAGE_SIZE);
1407         seq_buf_printf(&s, "file_dirty %llu\n",
1408                        (u64)memcg_page_state(memcg, NR_FILE_DIRTY) *
1409                        PAGE_SIZE);
1410         seq_buf_printf(&s, "file_writeback %llu\n",
1411                        (u64)memcg_page_state(memcg, NR_WRITEBACK) *
1412                        PAGE_SIZE);
1413
1414 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1415         seq_buf_printf(&s, "anon_thp %llu\n",
1416                        (u64)memcg_page_state(memcg, NR_ANON_THPS) *
1417                        HPAGE_PMD_SIZE);
1418 #endif
1419
1420         for (i = 0; i < NR_LRU_LISTS; i++)
1421                 seq_buf_printf(&s, "%s %llu\n", lru_list_name(i),
1422                                (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
1423                                PAGE_SIZE);
1424
1425         seq_buf_printf(&s, "slab_reclaimable %llu\n",
1426                        (u64)memcg_page_state(memcg, NR_SLAB_RECLAIMABLE) *
1427                        PAGE_SIZE);
1428         seq_buf_printf(&s, "slab_unreclaimable %llu\n",
1429                        (u64)memcg_page_state(memcg, NR_SLAB_UNRECLAIMABLE) *
1430                        PAGE_SIZE);
1431
1432         /* Accumulated memory events */
1433
1434         seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGFAULT),
1435                        memcg_events(memcg, PGFAULT));
1436         seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGMAJFAULT),
1437                        memcg_events(memcg, PGMAJFAULT));
1438
1439         seq_buf_printf(&s, "workingset_refault %lu\n",
1440                        memcg_page_state(memcg, WORKINGSET_REFAULT));
1441         seq_buf_printf(&s, "workingset_activate %lu\n",
1442                        memcg_page_state(memcg, WORKINGSET_ACTIVATE));
1443         seq_buf_printf(&s, "workingset_restore %lu\n",
1444                        memcg_page_state(memcg, WORKINGSET_RESTORE));
1445         seq_buf_printf(&s, "workingset_nodereclaim %lu\n",
1446                        memcg_page_state(memcg, WORKINGSET_NODERECLAIM));
1447
1448         seq_buf_printf(&s, "%s %lu\n",  vm_event_name(PGREFILL),
1449                        memcg_events(memcg, PGREFILL));
1450         seq_buf_printf(&s, "pgscan %lu\n",
1451                        memcg_events(memcg, PGSCAN_KSWAPD) +
1452                        memcg_events(memcg, PGSCAN_DIRECT));
1453         seq_buf_printf(&s, "pgsteal %lu\n",
1454                        memcg_events(memcg, PGSTEAL_KSWAPD) +
1455                        memcg_events(memcg, PGSTEAL_DIRECT));
1456         seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGACTIVATE),
1457                        memcg_events(memcg, PGACTIVATE));
1458         seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGDEACTIVATE),
1459                        memcg_events(memcg, PGDEACTIVATE));
1460         seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREE),
1461                        memcg_events(memcg, PGLAZYFREE));
1462         seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREED),
1463                        memcg_events(memcg, PGLAZYFREED));
1464
1465 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1466         seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_FAULT_ALLOC),
1467                        memcg_events(memcg, THP_FAULT_ALLOC));
1468         seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_COLLAPSE_ALLOC),
1469                        memcg_events(memcg, THP_COLLAPSE_ALLOC));
1470 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1471
1472         /* The above should easily fit into one page */
1473         WARN_ON_ONCE(seq_buf_has_overflowed(&s));
1474
1475         return s.buffer;
1476 }
1477
1478 #define K(x) ((x) << (PAGE_SHIFT-10))
1479 /**
1480  * mem_cgroup_print_oom_context: Print OOM information relevant to
1481  * memory controller.
1482  * @memcg: The memory cgroup that went over limit
1483  * @p: Task that is going to be killed
1484  *
1485  * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1486  * enabled
1487  */
1488 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1489 {
1490         rcu_read_lock();
1491
1492         if (memcg) {
1493                 pr_cont(",oom_memcg=");
1494                 pr_cont_cgroup_path(memcg->css.cgroup);
1495         } else
1496                 pr_cont(",global_oom");
1497         if (p) {
1498                 pr_cont(",task_memcg=");
1499                 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1500         }
1501         rcu_read_unlock();
1502 }
1503
1504 /**
1505  * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1506  * memory controller.
1507  * @memcg: The memory cgroup that went over limit
1508  */
1509 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1510 {
1511         char *buf;
1512
1513         pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1514                 K((u64)page_counter_read(&memcg->memory)),
1515                 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
1516         if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1517                 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1518                         K((u64)page_counter_read(&memcg->swap)),
1519                         K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
1520         else {
1521                 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1522                         K((u64)page_counter_read(&memcg->memsw)),
1523                         K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1524                 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1525                         K((u64)page_counter_read(&memcg->kmem)),
1526                         K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1527         }
1528
1529         pr_info("Memory cgroup stats for ");
1530         pr_cont_cgroup_path(memcg->css.cgroup);
1531         pr_cont(":");
1532         buf = memory_stat_format(memcg);
1533         if (!buf)
1534                 return;
1535         pr_info("%s", buf);
1536         kfree(buf);
1537 }
1538
1539 /*
1540  * Return the memory (and swap, if configured) limit for a memcg.
1541  */
1542 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1543 {
1544         unsigned long max;
1545
1546         max = READ_ONCE(memcg->memory.max);
1547         if (mem_cgroup_swappiness(memcg)) {
1548                 unsigned long memsw_max;
1549                 unsigned long swap_max;
1550
1551                 memsw_max = memcg->memsw.max;
1552                 swap_max = READ_ONCE(memcg->swap.max);
1553                 swap_max = min(swap_max, (unsigned long)total_swap_pages);
1554                 max = min(max + swap_max, memsw_max);
1555         }
1556         return max;
1557 }
1558
1559 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1560 {
1561         return page_counter_read(&memcg->memory);
1562 }
1563
1564 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1565                                      int order)
1566 {
1567         struct oom_control oc = {
1568                 .zonelist = NULL,
1569                 .nodemask = NULL,
1570                 .memcg = memcg,
1571                 .gfp_mask = gfp_mask,
1572                 .order = order,
1573         };
1574         bool ret;
1575
1576         if (mutex_lock_killable(&oom_lock))
1577                 return true;
1578         /*
1579          * A few threads which were not waiting at mutex_lock_killable() can
1580          * fail to bail out. Therefore, check again after holding oom_lock.
1581          */
1582         ret = should_force_charge() || out_of_memory(&oc);
1583         mutex_unlock(&oom_lock);
1584         return ret;
1585 }
1586
1587 static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
1588                                    pg_data_t *pgdat,
1589                                    gfp_t gfp_mask,
1590                                    unsigned long *total_scanned)
1591 {
1592         struct mem_cgroup *victim = NULL;
1593         int total = 0;
1594         int loop = 0;
1595         unsigned long excess;
1596         unsigned long nr_scanned;
1597         struct mem_cgroup_reclaim_cookie reclaim = {
1598                 .pgdat = pgdat,
1599         };
1600
1601         excess = soft_limit_excess(root_memcg);
1602
1603         while (1) {
1604                 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1605                 if (!victim) {
1606                         loop++;
1607                         if (loop >= 2) {
1608                                 /*
1609                                  * If we have not been able to reclaim
1610                                  * anything, it might because there are
1611                                  * no reclaimable pages under this hierarchy
1612                                  */
1613                                 if (!total)
1614                                         break;
1615                                 /*
1616                                  * We want to do more targeted reclaim.
1617                                  * excess >> 2 is not to excessive so as to
1618                                  * reclaim too much, nor too less that we keep
1619                                  * coming back to reclaim from this cgroup
1620                                  */
1621                                 if (total >= (excess >> 2) ||
1622                                         (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1623                                         break;
1624                         }
1625                         continue;
1626                 }
1627                 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
1628                                         pgdat, &nr_scanned);
1629                 *total_scanned += nr_scanned;
1630                 if (!soft_limit_excess(root_memcg))
1631                         break;
1632         }
1633         mem_cgroup_iter_break(root_memcg, victim);
1634         return total;
1635 }
1636
1637 #ifdef CONFIG_LOCKDEP
1638 static struct lockdep_map memcg_oom_lock_dep_map = {
1639         .name = "memcg_oom_lock",
1640 };
1641 #endif
1642
1643 static DEFINE_SPINLOCK(memcg_oom_lock);
1644
1645 /*
1646  * Check OOM-Killer is already running under our hierarchy.
1647  * If someone is running, return false.
1648  */
1649 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
1650 {
1651         struct mem_cgroup *iter, *failed = NULL;
1652
1653         spin_lock(&memcg_oom_lock);
1654
1655         for_each_mem_cgroup_tree(iter, memcg) {
1656                 if (iter->oom_lock) {
1657                         /*
1658                          * this subtree of our hierarchy is already locked
1659                          * so we cannot give a lock.
1660                          */
1661                         failed = iter;
1662                         mem_cgroup_iter_break(memcg, iter);
1663                         break;
1664                 } else
1665                         iter->oom_lock = true;
1666         }
1667
1668         if (failed) {
1669                 /*
1670                  * OK, we failed to lock the whole subtree so we have
1671                  * to clean up what we set up to the failing subtree
1672                  */
1673                 for_each_mem_cgroup_tree(iter, memcg) {
1674                         if (iter == failed) {
1675                                 mem_cgroup_iter_break(memcg, iter);
1676                                 break;
1677                         }
1678                         iter->oom_lock = false;
1679                 }
1680         } else
1681                 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
1682
1683         spin_unlock(&memcg_oom_lock);
1684
1685         return !failed;
1686 }
1687
1688 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
1689 {
1690         struct mem_cgroup *iter;
1691
1692         spin_lock(&memcg_oom_lock);
1693         mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
1694         for_each_mem_cgroup_tree(iter, memcg)
1695                 iter->oom_lock = false;
1696         spin_unlock(&memcg_oom_lock);
1697 }
1698
1699 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
1700 {
1701         struct mem_cgroup *iter;
1702
1703         spin_lock(&memcg_oom_lock);
1704         for_each_mem_cgroup_tree(iter, memcg)
1705                 iter->under_oom++;
1706         spin_unlock(&memcg_oom_lock);
1707 }
1708
1709 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
1710 {
1711         struct mem_cgroup *iter;
1712
1713         /*
1714          * When a new child is created while the hierarchy is under oom,
1715          * mem_cgroup_oom_lock() may not be called. Watch for underflow.
1716          */
1717         spin_lock(&memcg_oom_lock);
1718         for_each_mem_cgroup_tree(iter, memcg)
1719                 if (iter->under_oom > 0)
1720                         iter->under_oom--;
1721         spin_unlock(&memcg_oom_lock);
1722 }
1723
1724 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1725
1726 struct oom_wait_info {
1727         struct mem_cgroup *memcg;
1728         wait_queue_entry_t      wait;
1729 };
1730
1731 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
1732         unsigned mode, int sync, void *arg)
1733 {
1734         struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1735         struct mem_cgroup *oom_wait_memcg;
1736         struct oom_wait_info *oom_wait_info;
1737
1738         oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1739         oom_wait_memcg = oom_wait_info->memcg;
1740
1741         if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1742             !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1743                 return 0;
1744         return autoremove_wake_function(wait, mode, sync, arg);
1745 }
1746
1747 static void memcg_oom_recover(struct mem_cgroup *memcg)
1748 {
1749         /*
1750          * For the following lockless ->under_oom test, the only required
1751          * guarantee is that it must see the state asserted by an OOM when
1752          * this function is called as a result of userland actions
1753          * triggered by the notification of the OOM.  This is trivially
1754          * achieved by invoking mem_cgroup_mark_under_oom() before
1755          * triggering notification.
1756          */
1757         if (memcg && memcg->under_oom)
1758                 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1759 }
1760
1761 enum oom_status {
1762         OOM_SUCCESS,
1763         OOM_FAILED,
1764         OOM_ASYNC,
1765         OOM_SKIPPED
1766 };
1767
1768 static enum oom_status mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1769 {
1770         enum oom_status ret;
1771         bool locked;
1772
1773         if (order > PAGE_ALLOC_COSTLY_ORDER)
1774                 return OOM_SKIPPED;
1775
1776         memcg_memory_event(memcg, MEMCG_OOM);
1777
1778         /*
1779          * We are in the middle of the charge context here, so we
1780          * don't want to block when potentially sitting on a callstack
1781          * that holds all kinds of filesystem and mm locks.
1782          *
1783          * cgroup1 allows disabling the OOM killer and waiting for outside
1784          * handling until the charge can succeed; remember the context and put
1785          * the task to sleep at the end of the page fault when all locks are
1786          * released.
1787          *
1788          * On the other hand, in-kernel OOM killer allows for an async victim
1789          * memory reclaim (oom_reaper) and that means that we are not solely
1790          * relying on the oom victim to make a forward progress and we can
1791          * invoke the oom killer here.
1792          *
1793          * Please note that mem_cgroup_out_of_memory might fail to find a
1794          * victim and then we have to bail out from the charge path.
1795          */
1796         if (memcg->oom_kill_disable) {
1797                 if (!current->in_user_fault)
1798                         return OOM_SKIPPED;
1799                 css_get(&memcg->css);
1800                 current->memcg_in_oom = memcg;
1801                 current->memcg_oom_gfp_mask = mask;
1802                 current->memcg_oom_order = order;
1803
1804                 return OOM_ASYNC;
1805         }
1806
1807         mem_cgroup_mark_under_oom(memcg);
1808
1809         locked = mem_cgroup_oom_trylock(memcg);
1810
1811         if (locked)
1812                 mem_cgroup_oom_notify(memcg);
1813
1814         mem_cgroup_unmark_under_oom(memcg);
1815         if (mem_cgroup_out_of_memory(memcg, mask, order))
1816                 ret = OOM_SUCCESS;
1817         else
1818                 ret = OOM_FAILED;
1819
1820         if (locked)
1821                 mem_cgroup_oom_unlock(memcg);
1822
1823         return ret;
1824 }
1825
1826 /**
1827  * mem_cgroup_oom_synchronize - complete memcg OOM handling
1828  * @handle: actually kill/wait or just clean up the OOM state
1829  *
1830  * This has to be called at the end of a page fault if the memcg OOM
1831  * handler was enabled.
1832  *
1833  * Memcg supports userspace OOM handling where failed allocations must
1834  * sleep on a waitqueue until the userspace task resolves the
1835  * situation.  Sleeping directly in the charge context with all kinds
1836  * of locks held is not a good idea, instead we remember an OOM state
1837  * in the task and mem_cgroup_oom_synchronize() has to be called at
1838  * the end of the page fault to complete the OOM handling.
1839  *
1840  * Returns %true if an ongoing memcg OOM situation was detected and
1841  * completed, %false otherwise.
1842  */
1843 bool mem_cgroup_oom_synchronize(bool handle)
1844 {
1845         struct mem_cgroup *memcg = current->memcg_in_oom;
1846         struct oom_wait_info owait;
1847         bool locked;
1848
1849         /* OOM is global, do not handle */
1850         if (!memcg)
1851                 return false;
1852
1853         if (!handle)
1854                 goto cleanup;
1855
1856         owait.memcg = memcg;
1857         owait.wait.flags = 0;
1858         owait.wait.func = memcg_oom_wake_function;
1859         owait.wait.private = current;
1860         INIT_LIST_HEAD(&owait.wait.entry);
1861
1862         prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1863         mem_cgroup_mark_under_oom(memcg);
1864
1865         locked = mem_cgroup_oom_trylock(memcg);
1866
1867         if (locked)
1868                 mem_cgroup_oom_notify(memcg);
1869
1870         if (locked && !memcg->oom_kill_disable) {
1871                 mem_cgroup_unmark_under_oom(memcg);
1872                 finish_wait(&memcg_oom_waitq, &owait.wait);
1873                 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
1874                                          current->memcg_oom_order);
1875         } else {
1876                 schedule();
1877                 mem_cgroup_unmark_under_oom(memcg);
1878                 finish_wait(&memcg_oom_waitq, &owait.wait);
1879         }
1880
1881         if (locked) {
1882                 mem_cgroup_oom_unlock(memcg);
1883                 /*
1884                  * There is no guarantee that an OOM-lock contender
1885                  * sees the wakeups triggered by the OOM kill
1886                  * uncharges.  Wake any sleepers explicitely.
1887                  */
1888                 memcg_oom_recover(memcg);
1889         }
1890 cleanup:
1891         current->memcg_in_oom = NULL;
1892         css_put(&memcg->css);
1893         return true;
1894 }
1895
1896 /**
1897  * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
1898  * @victim: task to be killed by the OOM killer
1899  * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
1900  *
1901  * Returns a pointer to a memory cgroup, which has to be cleaned up
1902  * by killing all belonging OOM-killable tasks.
1903  *
1904  * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
1905  */
1906 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
1907                                             struct mem_cgroup *oom_domain)
1908 {
1909         struct mem_cgroup *oom_group = NULL;
1910         struct mem_cgroup *memcg;
1911
1912         if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
1913                 return NULL;
1914
1915         if (!oom_domain)
1916                 oom_domain = root_mem_cgroup;
1917
1918         rcu_read_lock();
1919
1920         memcg = mem_cgroup_from_task(victim);
1921         if (memcg == root_mem_cgroup)
1922                 goto out;
1923
1924         /*
1925          * If the victim task has been asynchronously moved to a different
1926          * memory cgroup, we might end up killing tasks outside oom_domain.
1927          * In this case it's better to ignore memory.group.oom.
1928          */
1929         if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
1930                 goto out;
1931
1932         /*
1933          * Traverse the memory cgroup hierarchy from the victim task's
1934          * cgroup up to the OOMing cgroup (or root) to find the
1935          * highest-level memory cgroup with oom.group set.
1936          */
1937         for (; memcg; memcg = parent_mem_cgroup(memcg)) {
1938                 if (memcg->oom_group)
1939                         oom_group = memcg;
1940
1941                 if (memcg == oom_domain)
1942                         break;
1943         }
1944
1945         if (oom_group)
1946                 css_get(&oom_group->css);
1947 out:
1948         rcu_read_unlock();
1949
1950         return oom_group;
1951 }
1952
1953 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
1954 {
1955         pr_info("Tasks in ");
1956         pr_cont_cgroup_path(memcg->css.cgroup);
1957         pr_cont(" are going to be killed due to memory.oom.group set\n");
1958 }
1959
1960 /**
1961  * lock_page_memcg - lock a page->mem_cgroup binding
1962  * @page: the page
1963  *
1964  * This function protects unlocked LRU pages from being moved to
1965  * another cgroup.
1966  *
1967  * It ensures lifetime of the returned memcg. Caller is responsible
1968  * for the lifetime of the page; __unlock_page_memcg() is available
1969  * when @page might get freed inside the locked section.
1970  */
1971 struct mem_cgroup *lock_page_memcg(struct page *page)
1972 {
1973         struct page *head = compound_head(page); /* rmap on tail pages */
1974         struct mem_cgroup *memcg;
1975         unsigned long flags;
1976
1977         /*
1978          * The RCU lock is held throughout the transaction.  The fast
1979          * path can get away without acquiring the memcg->move_lock
1980          * because page moving starts with an RCU grace period.
1981          *
1982          * The RCU lock also protects the memcg from being freed when
1983          * the page state that is going to change is the only thing
1984          * preventing the page itself from being freed. E.g. writeback
1985          * doesn't hold a page reference and relies on PG_writeback to
1986          * keep off truncation, migration and so forth.
1987          */
1988         rcu_read_lock();
1989
1990         if (mem_cgroup_disabled())
1991                 return NULL;
1992 again:
1993         memcg = head->mem_cgroup;
1994         if (unlikely(!memcg))
1995                 return NULL;
1996
1997         if (atomic_read(&memcg->moving_account) <= 0)
1998                 return memcg;
1999
2000         spin_lock_irqsave(&memcg->move_lock, flags);
2001         if (memcg != head->mem_cgroup) {
2002                 spin_unlock_irqrestore(&memcg->move_lock, flags);
2003                 goto again;
2004         }
2005
2006         /*
2007          * When charge migration first begins, we can have locked and
2008          * unlocked page stat updates happening concurrently.  Track
2009          * the task who has the lock for unlock_page_memcg().
2010          */
2011         memcg->move_lock_task = current;
2012         memcg->move_lock_flags = flags;
2013
2014         return memcg;
2015 }
2016 EXPORT_SYMBOL(lock_page_memcg);
2017
2018 /**
2019  * __unlock_page_memcg - unlock and unpin a memcg
2020  * @memcg: the memcg
2021  *
2022  * Unlock and unpin a memcg returned by lock_page_memcg().
2023  */
2024 void __unlock_page_memcg(struct mem_cgroup *memcg)
2025 {
2026         if (memcg && memcg->move_lock_task == current) {
2027                 unsigned long flags = memcg->move_lock_flags;
2028
2029                 memcg->move_lock_task = NULL;
2030                 memcg->move_lock_flags = 0;
2031
2032                 spin_unlock_irqrestore(&memcg->move_lock, flags);
2033         }
2034
2035         rcu_read_unlock();
2036 }
2037
2038 /**
2039  * unlock_page_memcg - unlock a page->mem_cgroup binding
2040  * @page: the page
2041  */
2042 void unlock_page_memcg(struct page *page)
2043 {
2044         struct page *head = compound_head(page);
2045
2046         __unlock_page_memcg(head->mem_cgroup);
2047 }
2048 EXPORT_SYMBOL(unlock_page_memcg);
2049
2050 struct memcg_stock_pcp {
2051         struct mem_cgroup *cached; /* this never be root cgroup */
2052         unsigned int nr_pages;
2053         struct work_struct work;
2054         unsigned long flags;
2055 #define FLUSHING_CACHED_CHARGE  0
2056 };
2057 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2058 static DEFINE_MUTEX(percpu_charge_mutex);
2059
2060 /**
2061  * consume_stock: Try to consume stocked charge on this cpu.
2062  * @memcg: memcg to consume from.
2063  * @nr_pages: how many pages to charge.
2064  *
2065  * The charges will only happen if @memcg matches the current cpu's memcg
2066  * stock, and at least @nr_pages are available in that stock.  Failure to
2067  * service an allocation will refill the stock.
2068  *
2069  * returns true if successful, false otherwise.
2070  */
2071 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2072 {
2073         struct memcg_stock_pcp *stock;
2074         unsigned long flags;
2075         bool ret = false;
2076
2077         if (nr_pages > MEMCG_CHARGE_BATCH)
2078                 return ret;
2079
2080         local_irq_save(flags);
2081
2082         stock = this_cpu_ptr(&memcg_stock);
2083         if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
2084                 stock->nr_pages -= nr_pages;
2085                 ret = true;
2086         }
2087
2088         local_irq_restore(flags);
2089
2090         return ret;
2091 }
2092
2093 /*
2094  * Returns stocks cached in percpu and reset cached information.
2095  */
2096 static void drain_stock(struct memcg_stock_pcp *stock)
2097 {
2098         struct mem_cgroup *old = stock->cached;
2099
2100         if (stock->nr_pages) {
2101                 page_counter_uncharge(&old->memory, stock->nr_pages);
2102                 if (do_memsw_account())
2103                         page_counter_uncharge(&old->memsw, stock->nr_pages);
2104                 css_put_many(&old->css, stock->nr_pages);
2105                 stock->nr_pages = 0;
2106         }
2107         stock->cached = NULL;
2108 }
2109
2110 static void drain_local_stock(struct work_struct *dummy)
2111 {
2112         struct memcg_stock_pcp *stock;
2113         unsigned long flags;
2114
2115         /*
2116          * The only protection from memory hotplug vs. drain_stock races is
2117          * that we always operate on local CPU stock here with IRQ disabled
2118          */
2119         local_irq_save(flags);
2120
2121         stock = this_cpu_ptr(&memcg_stock);
2122         drain_stock(stock);
2123         clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2124
2125         local_irq_restore(flags);
2126 }
2127
2128 /*
2129  * Cache charges(val) to local per_cpu area.
2130  * This will be consumed by consume_stock() function, later.
2131  */
2132 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2133 {
2134         struct memcg_stock_pcp *stock;
2135         unsigned long flags;
2136
2137         local_irq_save(flags);
2138
2139         stock = this_cpu_ptr(&memcg_stock);
2140         if (stock->cached != memcg) { /* reset if necessary */
2141                 drain_stock(stock);
2142                 stock->cached = memcg;
2143         }
2144         stock->nr_pages += nr_pages;
2145
2146         if (stock->nr_pages > MEMCG_CHARGE_BATCH)
2147                 drain_stock(stock);
2148
2149         local_irq_restore(flags);
2150 }
2151
2152 /*
2153  * Drains all per-CPU charge caches for given root_memcg resp. subtree
2154  * of the hierarchy under it.
2155  */
2156 static void drain_all_stock(struct mem_cgroup *root_memcg)
2157 {
2158         int cpu, curcpu;
2159
2160         /* If someone's already draining, avoid adding running more workers. */
2161         if (!mutex_trylock(&percpu_charge_mutex))
2162                 return;
2163         /*
2164          * Notify other cpus that system-wide "drain" is running
2165          * We do not care about races with the cpu hotplug because cpu down
2166          * as well as workers from this path always operate on the local
2167          * per-cpu data. CPU up doesn't touch memcg_stock at all.
2168          */
2169         curcpu = get_cpu();
2170         for_each_online_cpu(cpu) {
2171                 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2172                 struct mem_cgroup *memcg;
2173                 bool flush = false;
2174
2175                 rcu_read_lock();
2176                 memcg = stock->cached;
2177                 if (memcg && stock->nr_pages &&
2178                     mem_cgroup_is_descendant(memcg, root_memcg))
2179                         flush = true;
2180                 rcu_read_unlock();
2181
2182                 if (flush &&
2183                     !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2184                         if (cpu == curcpu)
2185                                 drain_local_stock(&stock->work);
2186                         else
2187                                 schedule_work_on(cpu, &stock->work);
2188                 }
2189         }
2190         put_cpu();
2191         mutex_unlock(&percpu_charge_mutex);
2192 }
2193
2194 static int memcg_hotplug_cpu_dead(unsigned int cpu)
2195 {
2196         struct memcg_stock_pcp *stock;
2197         struct mem_cgroup *memcg, *mi;
2198
2199         stock = &per_cpu(memcg_stock, cpu);
2200         drain_stock(stock);
2201
2202         for_each_mem_cgroup(memcg) {
2203                 int i;
2204
2205                 for (i = 0; i < MEMCG_NR_STAT; i++) {
2206                         int nid;
2207                         long x;
2208
2209                         x = this_cpu_xchg(memcg->vmstats_percpu->stat[i], 0);
2210                         if (x)
2211                                 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2212                                         atomic_long_add(x, &memcg->vmstats[i]);
2213
2214                         if (i >= NR_VM_NODE_STAT_ITEMS)
2215                                 continue;
2216
2217                         for_each_node(nid) {
2218                                 struct mem_cgroup_per_node *pn;
2219
2220                                 pn = mem_cgroup_nodeinfo(memcg, nid);
2221                                 x = this_cpu_xchg(pn->lruvec_stat_cpu->count[i], 0);
2222                                 if (x)
2223                                         do {
2224                                                 atomic_long_add(x, &pn->lruvec_stat[i]);
2225                                         } while ((pn = parent_nodeinfo(pn, nid)));
2226                         }
2227                 }
2228
2229                 for (i = 0; i < NR_VM_EVENT_ITEMS; i++) {
2230                         long x;
2231
2232                         x = this_cpu_xchg(memcg->vmstats_percpu->events[i], 0);
2233                         if (x)
2234                                 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2235                                         atomic_long_add(x, &memcg->vmevents[i]);
2236                 }
2237         }
2238
2239         return 0;
2240 }
2241
2242 static void reclaim_high(struct mem_cgroup *memcg,
2243                          unsigned int nr_pages,
2244                          gfp_t gfp_mask)
2245 {
2246         do {
2247                 if (page_counter_read(&memcg->memory) <=
2248                     READ_ONCE(memcg->memory.high))
2249                         continue;
2250                 memcg_memory_event(memcg, MEMCG_HIGH);
2251                 try_to_free_mem_cgroup_pages(memcg, nr_pages, gfp_mask, true);
2252         } while ((memcg = parent_mem_cgroup(memcg)) &&
2253                  !mem_cgroup_is_root(memcg));
2254 }
2255
2256 static void high_work_func(struct work_struct *work)
2257 {
2258         struct mem_cgroup *memcg;
2259
2260         memcg = container_of(work, struct mem_cgroup, high_work);
2261         reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
2262 }
2263
2264 /*
2265  * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2266  * enough to still cause a significant slowdown in most cases, while still
2267  * allowing diagnostics and tracing to proceed without becoming stuck.
2268  */
2269 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2270
2271 /*
2272  * When calculating the delay, we use these either side of the exponentiation to
2273  * maintain precision and scale to a reasonable number of jiffies (see the table
2274  * below.
2275  *
2276  * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2277  *   overage ratio to a delay.
2278  * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down down the
2279  *   proposed penalty in order to reduce to a reasonable number of jiffies, and
2280  *   to produce a reasonable delay curve.
2281  *
2282  * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2283  * reasonable delay curve compared to precision-adjusted overage, not
2284  * penalising heavily at first, but still making sure that growth beyond the
2285  * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2286  * example, with a high of 100 megabytes:
2287  *
2288  *  +-------+------------------------+
2289  *  | usage | time to allocate in ms |
2290  *  +-------+------------------------+
2291  *  | 100M  |                      0 |
2292  *  | 101M  |                      6 |
2293  *  | 102M  |                     25 |
2294  *  | 103M  |                     57 |
2295  *  | 104M  |                    102 |
2296  *  | 105M  |                    159 |
2297  *  | 106M  |                    230 |
2298  *  | 107M  |                    313 |
2299  *  | 108M  |                    409 |
2300  *  | 109M  |                    518 |
2301  *  | 110M  |                    639 |
2302  *  | 111M  |                    774 |
2303  *  | 112M  |                    921 |
2304  *  | 113M  |                   1081 |
2305  *  | 114M  |                   1254 |
2306  *  | 115M  |                   1439 |
2307  *  | 116M  |                   1638 |
2308  *  | 117M  |                   1849 |
2309  *  | 118M  |                   2000 |
2310  *  | 119M  |                   2000 |
2311  *  | 120M  |                   2000 |
2312  *  +-------+------------------------+
2313  */
2314  #define MEMCG_DELAY_PRECISION_SHIFT 20
2315  #define MEMCG_DELAY_SCALING_SHIFT 14
2316
2317 static u64 calculate_overage(unsigned long usage, unsigned long high)
2318 {
2319         u64 overage;
2320
2321         if (usage <= high)
2322                 return 0;
2323
2324         /*
2325          * Prevent division by 0 in overage calculation by acting as if
2326          * it was a threshold of 1 page
2327          */
2328         high = max(high, 1UL);
2329
2330         overage = usage - high;
2331         overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2332         return div64_u64(overage, high);
2333 }
2334
2335 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2336 {
2337         u64 overage, max_overage = 0;
2338
2339         do {
2340                 overage = calculate_overage(page_counter_read(&memcg->memory),
2341                                             READ_ONCE(memcg->memory.high));
2342                 max_overage = max(overage, max_overage);
2343         } while ((memcg = parent_mem_cgroup(memcg)) &&
2344                  !mem_cgroup_is_root(memcg));
2345
2346         return max_overage;
2347 }
2348
2349 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2350 {
2351         u64 overage, max_overage = 0;
2352
2353         do {
2354                 overage = calculate_overage(page_counter_read(&memcg->swap),
2355                                             READ_ONCE(memcg->swap.high));
2356                 if (overage)
2357                         memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2358                 max_overage = max(overage, max_overage);
2359         } while ((memcg = parent_mem_cgroup(memcg)) &&
2360                  !mem_cgroup_is_root(memcg));
2361
2362         return max_overage;
2363 }
2364
2365 /*
2366  * Get the number of jiffies that we should penalise a mischievous cgroup which
2367  * is exceeding its memory.high by checking both it and its ancestors.
2368  */
2369 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2370                                           unsigned int nr_pages,
2371                                           u64 max_overage)
2372 {
2373         unsigned long penalty_jiffies;
2374
2375         if (!max_overage)
2376                 return 0;
2377
2378         /*
2379          * We use overage compared to memory.high to calculate the number of
2380          * jiffies to sleep (penalty_jiffies). Ideally this value should be
2381          * fairly lenient on small overages, and increasingly harsh when the
2382          * memcg in question makes it clear that it has no intention of stopping
2383          * its crazy behaviour, so we exponentially increase the delay based on
2384          * overage amount.
2385          */
2386         penalty_jiffies = max_overage * max_overage * HZ;
2387         penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2388         penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2389
2390         /*
2391          * Factor in the task's own contribution to the overage, such that four
2392          * N-sized allocations are throttled approximately the same as one
2393          * 4N-sized allocation.
2394          *
2395          * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2396          * larger the current charge patch is than that.
2397          */
2398         return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2399 }
2400
2401 /*
2402  * Scheduled by try_charge() to be executed from the userland return path
2403  * and reclaims memory over the high limit.
2404  */
2405 void mem_cgroup_handle_over_high(void)
2406 {
2407         unsigned long penalty_jiffies;
2408         unsigned long pflags;
2409         unsigned int nr_pages = current->memcg_nr_pages_over_high;
2410         struct mem_cgroup *memcg;
2411
2412         if (likely(!nr_pages))
2413                 return;
2414
2415         memcg = get_mem_cgroup_from_mm(current->mm);
2416         reclaim_high(memcg, nr_pages, GFP_KERNEL);
2417         current->memcg_nr_pages_over_high = 0;
2418
2419         /*
2420          * memory.high is breached and reclaim is unable to keep up. Throttle
2421          * allocators proactively to slow down excessive growth.
2422          */
2423         penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2424                                                mem_find_max_overage(memcg));
2425
2426         penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2427                                                 swap_find_max_overage(memcg));
2428
2429         /*
2430          * Clamp the max delay per usermode return so as to still keep the
2431          * application moving forwards and also permit diagnostics, albeit
2432          * extremely slowly.
2433          */
2434         penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2435
2436         /*
2437          * Don't sleep if the amount of jiffies this memcg owes us is so low
2438          * that it's not even worth doing, in an attempt to be nice to those who
2439          * go only a small amount over their memory.high value and maybe haven't
2440          * been aggressively reclaimed enough yet.
2441          */
2442         if (penalty_jiffies <= HZ / 100)
2443                 goto out;
2444
2445         /*
2446          * If we exit early, we're guaranteed to die (since
2447          * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2448          * need to account for any ill-begotten jiffies to pay them off later.
2449          */
2450         psi_memstall_enter(&pflags);
2451         schedule_timeout_killable(penalty_jiffies);
2452         psi_memstall_leave(&pflags);
2453
2454 out:
2455         css_put(&memcg->css);
2456 }
2457
2458 static int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2459                       unsigned int nr_pages)
2460 {
2461         unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2462         int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2463         struct mem_cgroup *mem_over_limit;
2464         struct page_counter *counter;
2465         unsigned long nr_reclaimed;
2466         bool may_swap = true;
2467         bool drained = false;
2468         enum oom_status oom_status;
2469
2470         if (mem_cgroup_is_root(memcg))
2471                 return 0;
2472 retry:
2473         if (consume_stock(memcg, nr_pages))
2474                 return 0;
2475
2476         if (!do_memsw_account() ||
2477             page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2478                 if (page_counter_try_charge(&memcg->memory, batch, &counter))
2479                         goto done_restock;
2480                 if (do_memsw_account())
2481                         page_counter_uncharge(&memcg->memsw, batch);
2482                 mem_over_limit = mem_cgroup_from_counter(counter, memory);
2483         } else {
2484                 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2485                 may_swap = false;
2486         }
2487
2488         if (batch > nr_pages) {
2489                 batch = nr_pages;
2490                 goto retry;
2491         }
2492
2493         /*
2494          * Memcg doesn't have a dedicated reserve for atomic
2495          * allocations. But like the global atomic pool, we need to
2496          * put the burden of reclaim on regular allocation requests
2497          * and let these go through as privileged allocations.
2498          */
2499         if (gfp_mask & __GFP_ATOMIC)
2500                 goto force;
2501
2502         /*
2503          * Unlike in global OOM situations, memcg is not in a physical
2504          * memory shortage.  Allow dying and OOM-killed tasks to
2505          * bypass the last charges so that they can exit quickly and
2506          * free their memory.
2507          */
2508         if (unlikely(should_force_charge()))
2509                 goto force;
2510
2511         /*
2512          * Prevent unbounded recursion when reclaim operations need to
2513          * allocate memory. This might exceed the limits temporarily,
2514          * but we prefer facilitating memory reclaim and getting back
2515          * under the limit over triggering OOM kills in these cases.
2516          */
2517         if (unlikely(current->flags & PF_MEMALLOC))
2518                 goto force;
2519
2520         if (unlikely(task_in_memcg_oom(current)))
2521                 goto nomem;
2522
2523         if (!gfpflags_allow_blocking(gfp_mask))
2524                 goto nomem;
2525
2526         memcg_memory_event(mem_over_limit, MEMCG_MAX);
2527
2528         nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2529                                                     gfp_mask, may_swap);
2530
2531         if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2532                 goto retry;
2533
2534         if (!drained) {
2535                 drain_all_stock(mem_over_limit);
2536                 drained = true;
2537                 goto retry;
2538         }
2539
2540         if (gfp_mask & __GFP_NORETRY)
2541                 goto nomem;
2542         /*
2543          * Even though the limit is exceeded at this point, reclaim
2544          * may have been able to free some pages.  Retry the charge
2545          * before killing the task.
2546          *
2547          * Only for regular pages, though: huge pages are rather
2548          * unlikely to succeed so close to the limit, and we fall back
2549          * to regular pages anyway in case of failure.
2550          */
2551         if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2552                 goto retry;
2553         /*
2554          * At task move, charge accounts can be doubly counted. So, it's
2555          * better to wait until the end of task_move if something is going on.
2556          */
2557         if (mem_cgroup_wait_acct_move(mem_over_limit))
2558                 goto retry;
2559
2560         if (nr_retries--)
2561                 goto retry;
2562
2563         if (gfp_mask & __GFP_RETRY_MAYFAIL)
2564                 goto nomem;
2565
2566         if (gfp_mask & __GFP_NOFAIL)
2567                 goto force;
2568
2569         if (fatal_signal_pending(current))
2570                 goto force;
2571
2572         /*
2573          * keep retrying as long as the memcg oom killer is able to make
2574          * a forward progress or bypass the charge if the oom killer
2575          * couldn't make any progress.
2576          */
2577         oom_status = mem_cgroup_oom(mem_over_limit, gfp_mask,
2578                        get_order(nr_pages * PAGE_SIZE));
2579         switch (oom_status) {
2580         case OOM_SUCCESS:
2581                 nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
2582                 goto retry;
2583         case OOM_FAILED:
2584                 goto force;
2585         default:
2586                 goto nomem;
2587         }
2588 nomem:
2589         if (!(gfp_mask & __GFP_NOFAIL))
2590                 return -ENOMEM;
2591 force:
2592         /*
2593          * The allocation either can't fail or will lead to more memory
2594          * being freed very soon.  Allow memory usage go over the limit
2595          * temporarily by force charging it.
2596          */
2597         page_counter_charge(&memcg->memory, nr_pages);
2598         if (do_memsw_account())
2599                 page_counter_charge(&memcg->memsw, nr_pages);
2600         css_get_many(&memcg->css, nr_pages);
2601
2602         return 0;
2603
2604 done_restock:
2605         css_get_many(&memcg->css, batch);
2606         if (batch > nr_pages)
2607                 refill_stock(memcg, batch - nr_pages);
2608
2609         /*
2610          * If the hierarchy is above the normal consumption range, schedule
2611          * reclaim on returning to userland.  We can perform reclaim here
2612          * if __GFP_RECLAIM but let's always punt for simplicity and so that
2613          * GFP_KERNEL can consistently be used during reclaim.  @memcg is
2614          * not recorded as it most likely matches current's and won't
2615          * change in the meantime.  As high limit is checked again before
2616          * reclaim, the cost of mismatch is negligible.
2617          */
2618         do {
2619                 bool mem_high, swap_high;
2620
2621                 mem_high = page_counter_read(&memcg->memory) >
2622                         READ_ONCE(memcg->memory.high);
2623                 swap_high = page_counter_read(&memcg->swap) >
2624                         READ_ONCE(memcg->swap.high);
2625
2626                 /* Don't bother a random interrupted task */
2627                 if (in_interrupt()) {
2628                         if (mem_high) {
2629                                 schedule_work(&memcg->high_work);
2630                                 break;
2631                         }
2632                         continue;
2633                 }
2634
2635                 if (mem_high || swap_high) {
2636                         /*
2637                          * The allocating tasks in this cgroup will need to do
2638                          * reclaim or be throttled to prevent further growth
2639                          * of the memory or swap footprints.
2640                          *
2641                          * Target some best-effort fairness between the tasks,
2642                          * and distribute reclaim work and delay penalties
2643                          * based on how much each task is actually allocating.
2644                          */
2645                         current->memcg_nr_pages_over_high += batch;
2646                         set_notify_resume(current);
2647                         break;
2648                 }
2649         } while ((memcg = parent_mem_cgroup(memcg)));
2650
2651         return 0;
2652 }
2653
2654 #if defined(CONFIG_MEMCG_KMEM) || defined(CONFIG_MMU)
2655 static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2656 {
2657         if (mem_cgroup_is_root(memcg))
2658                 return;
2659
2660         page_counter_uncharge(&memcg->memory, nr_pages);
2661         if (do_memsw_account())
2662                 page_counter_uncharge(&memcg->memsw, nr_pages);
2663
2664         css_put_many(&memcg->css, nr_pages);
2665 }
2666 #endif
2667
2668 static void commit_charge(struct page *page, struct mem_cgroup *memcg)
2669 {
2670         VM_BUG_ON_PAGE(page->mem_cgroup, page);
2671         /*
2672          * Any of the following ensures page->mem_cgroup stability:
2673          *
2674          * - the page lock
2675          * - LRU isolation
2676          * - lock_page_memcg()
2677          * - exclusive reference
2678          */
2679         page->mem_cgroup = memcg;
2680 }
2681
2682 #ifdef CONFIG_MEMCG_KMEM
2683 /*
2684  * Returns a pointer to the memory cgroup to which the kernel object is charged.
2685  *
2686  * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2687  * cgroup_mutex, etc.
2688  */
2689 struct mem_cgroup *mem_cgroup_from_obj(void *p)
2690 {
2691         struct page *page;
2692
2693         if (mem_cgroup_disabled())
2694                 return NULL;
2695
2696         page = virt_to_head_page(p);
2697
2698         /*
2699          * Slab pages don't have page->mem_cgroup set because corresponding
2700          * kmem caches can be reparented during the lifetime. That's why
2701          * memcg_from_slab_page() should be used instead.
2702          */
2703         if (PageSlab(page))
2704                 return memcg_from_slab_page(page);
2705
2706         /* All other pages use page->mem_cgroup */
2707         return page->mem_cgroup;
2708 }
2709
2710 static int memcg_alloc_cache_id(void)
2711 {
2712         int id, size;
2713         int err;
2714
2715         id = ida_simple_get(&memcg_cache_ida,
2716                             0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2717         if (id < 0)
2718                 return id;
2719
2720         if (id < memcg_nr_cache_ids)
2721                 return id;
2722
2723         /*
2724          * There's no space for the new id in memcg_caches arrays,
2725          * so we have to grow them.
2726          */
2727         down_write(&memcg_cache_ids_sem);
2728
2729         size = 2 * (id + 1);
2730         if (size < MEMCG_CACHES_MIN_SIZE)
2731                 size = MEMCG_CACHES_MIN_SIZE;
2732         else if (size > MEMCG_CACHES_MAX_SIZE)
2733                 size = MEMCG_CACHES_MAX_SIZE;
2734
2735         err = memcg_update_all_caches(size);
2736         if (!err)
2737                 err = memcg_update_all_list_lrus(size);
2738         if (!err)
2739                 memcg_nr_cache_ids = size;
2740
2741         up_write(&memcg_cache_ids_sem);
2742
2743         if (err) {
2744                 ida_simple_remove(&memcg_cache_ida, id);
2745                 return err;
2746         }
2747         return id;
2748 }
2749
2750 static void memcg_free_cache_id(int id)
2751 {
2752         ida_simple_remove(&memcg_cache_ida, id);
2753 }
2754
2755 struct memcg_kmem_cache_create_work {
2756         struct mem_cgroup *memcg;
2757         struct kmem_cache *cachep;
2758         struct work_struct work;
2759 };
2760
2761 static void memcg_kmem_cache_create_func(struct work_struct *w)
2762 {
2763         struct memcg_kmem_cache_create_work *cw =
2764                 container_of(w, struct memcg_kmem_cache_create_work, work);
2765         struct mem_cgroup *memcg = cw->memcg;
2766         struct kmem_cache *cachep = cw->cachep;
2767
2768         memcg_create_kmem_cache(memcg, cachep);
2769
2770         css_put(&memcg->css);
2771         kfree(cw);
2772 }
2773
2774 /*
2775  * Enqueue the creation of a per-memcg kmem_cache.
2776  */
2777 static void memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
2778                                                struct kmem_cache *cachep)
2779 {
2780         struct memcg_kmem_cache_create_work *cw;
2781
2782         if (!css_tryget_online(&memcg->css))
2783                 return;
2784
2785         cw = kmalloc(sizeof(*cw), GFP_NOWAIT | __GFP_NOWARN);
2786         if (!cw) {
2787                 css_put(&memcg->css);
2788                 return;
2789         }
2790
2791         cw->memcg = memcg;
2792         cw->cachep = cachep;
2793         INIT_WORK(&cw->work, memcg_kmem_cache_create_func);
2794
2795         queue_work(memcg_kmem_cache_wq, &cw->work);
2796 }
2797
2798 static inline bool memcg_kmem_bypass(void)
2799 {
2800         if (in_interrupt())
2801                 return true;
2802
2803         /* Allow remote memcg charging in kthread contexts. */
2804         if ((!current->mm || (current->flags & PF_KTHREAD)) &&
2805              !current->active_memcg)
2806                 return true;
2807         return false;
2808 }
2809
2810 /**
2811  * memcg_kmem_get_cache: select the correct per-memcg cache for allocation
2812  * @cachep: the original global kmem cache
2813  *
2814  * Return the kmem_cache we're supposed to use for a slab allocation.
2815  * We try to use the current memcg's version of the cache.
2816  *
2817  * If the cache does not exist yet, if we are the first user of it, we
2818  * create it asynchronously in a workqueue and let the current allocation
2819  * go through with the original cache.
2820  *
2821  * This function takes a reference to the cache it returns to assure it
2822  * won't get destroyed while we are working with it. Once the caller is
2823  * done with it, memcg_kmem_put_cache() must be called to release the
2824  * reference.
2825  */
2826 struct kmem_cache *memcg_kmem_get_cache(struct kmem_cache *cachep)
2827 {
2828         struct mem_cgroup *memcg;
2829         struct kmem_cache *memcg_cachep;
2830         struct memcg_cache_array *arr;
2831         int kmemcg_id;
2832
2833         VM_BUG_ON(!is_root_cache(cachep));
2834
2835         if (memcg_kmem_bypass())
2836                 return cachep;
2837
2838         rcu_read_lock();
2839
2840         if (unlikely(current->active_memcg))
2841                 memcg = current->active_memcg;
2842         else
2843                 memcg = mem_cgroup_from_task(current);
2844
2845         if (!memcg || memcg == root_mem_cgroup)
2846                 goto out_unlock;
2847
2848         kmemcg_id = READ_ONCE(memcg->kmemcg_id);
2849         if (kmemcg_id < 0)
2850                 goto out_unlock;
2851
2852         arr = rcu_dereference(cachep->memcg_params.memcg_caches);
2853
2854         /*
2855          * Make sure we will access the up-to-date value. The code updating
2856          * memcg_caches issues a write barrier to match the data dependency
2857          * barrier inside READ_ONCE() (see memcg_create_kmem_cache()).
2858          */
2859         memcg_cachep = READ_ONCE(arr->entries[kmemcg_id]);
2860
2861         /*
2862          * If we are in a safe context (can wait, and not in interrupt
2863          * context), we could be be predictable and return right away.
2864          * This would guarantee that the allocation being performed
2865          * already belongs in the new cache.
2866          *
2867          * However, there are some clashes that can arrive from locking.
2868          * For instance, because we acquire the slab_mutex while doing
2869          * memcg_create_kmem_cache, this means no further allocation
2870          * could happen with the slab_mutex held. So it's better to
2871          * defer everything.
2872          *
2873          * If the memcg is dying or memcg_cache is about to be released,
2874          * don't bother creating new kmem_caches. Because memcg_cachep
2875          * is ZEROed as the fist step of kmem offlining, we don't need
2876          * percpu_ref_tryget_live() here. css_tryget_online() check in
2877          * memcg_schedule_kmem_cache_create() will prevent us from
2878          * creation of a new kmem_cache.
2879          */
2880         if (unlikely(!memcg_cachep))
2881                 memcg_schedule_kmem_cache_create(memcg, cachep);
2882         else if (percpu_ref_tryget(&memcg_cachep->memcg_params.refcnt))
2883                 cachep = memcg_cachep;
2884 out_unlock:
2885         rcu_read_unlock();
2886         return cachep;
2887 }
2888
2889 /**
2890  * memcg_kmem_put_cache: drop reference taken by memcg_kmem_get_cache
2891  * @cachep: the cache returned by memcg_kmem_get_cache
2892  */
2893 void memcg_kmem_put_cache(struct kmem_cache *cachep)
2894 {
2895         if (!is_root_cache(cachep))
2896                 percpu_ref_put(&cachep->memcg_params.refcnt);
2897 }
2898
2899 /**
2900  * __memcg_kmem_charge: charge a number of kernel pages to a memcg
2901  * @memcg: memory cgroup to charge
2902  * @gfp: reclaim mode
2903  * @nr_pages: number of pages to charge
2904  *
2905  * Returns 0 on success, an error code on failure.
2906  */
2907 int __memcg_kmem_charge(struct mem_cgroup *memcg, gfp_t gfp,
2908                         unsigned int nr_pages)
2909 {
2910         struct page_counter *counter;
2911         int ret;
2912
2913         ret = try_charge(memcg, gfp, nr_pages);
2914         if (ret)
2915                 return ret;
2916
2917         if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) &&
2918             !page_counter_try_charge(&memcg->kmem, nr_pages, &counter)) {
2919
2920                 /*
2921                  * Enforce __GFP_NOFAIL allocation because callers are not
2922                  * prepared to see failures and likely do not have any failure
2923                  * handling code.
2924                  */
2925                 if (gfp & __GFP_NOFAIL) {
2926                         page_counter_charge(&memcg->kmem, nr_pages);
2927                         return 0;
2928                 }
2929                 cancel_charge(memcg, nr_pages);
2930                 return -ENOMEM;
2931         }
2932         return 0;
2933 }
2934
2935 /**
2936  * __memcg_kmem_uncharge: uncharge a number of kernel pages from a memcg
2937  * @memcg: memcg to uncharge
2938  * @nr_pages: number of pages to uncharge
2939  */
2940 void __memcg_kmem_uncharge(struct mem_cgroup *memcg, unsigned int nr_pages)
2941 {
2942         if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2943                 page_counter_uncharge(&memcg->kmem, nr_pages);
2944
2945         page_counter_uncharge(&memcg->memory, nr_pages);
2946         if (do_memsw_account())
2947                 page_counter_uncharge(&memcg->memsw, nr_pages);
2948 }
2949
2950 /**
2951  * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
2952  * @page: page to charge
2953  * @gfp: reclaim mode
2954  * @order: allocation order
2955  *
2956  * Returns 0 on success, an error code on failure.
2957  */
2958 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
2959 {
2960         struct mem_cgroup *memcg;
2961         int ret = 0;
2962
2963         if (memcg_kmem_bypass())
2964                 return 0;
2965
2966         memcg = get_mem_cgroup_from_current();
2967         if (!mem_cgroup_is_root(memcg)) {
2968                 ret = __memcg_kmem_charge(memcg, gfp, 1 << order);
2969                 if (!ret) {
2970                         page->mem_cgroup = memcg;
2971                         __SetPageKmemcg(page);
2972                 }
2973         }
2974         css_put(&memcg->css);
2975         return ret;
2976 }
2977
2978 /**
2979  * __memcg_kmem_uncharge_page: uncharge a kmem page
2980  * @page: page to uncharge
2981  * @order: allocation order
2982  */
2983 void __memcg_kmem_uncharge_page(struct page *page, int order)
2984 {
2985         struct mem_cgroup *memcg = page->mem_cgroup;
2986         unsigned int nr_pages = 1 << order;
2987
2988         if (!memcg)
2989                 return;
2990
2991         VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
2992         __memcg_kmem_uncharge(memcg, nr_pages);
2993         page->mem_cgroup = NULL;
2994
2995         /* slab pages do not have PageKmemcg flag set */
2996         if (PageKmemcg(page))
2997                 __ClearPageKmemcg(page);
2998
2999         css_put_many(&memcg->css, nr_pages);
3000 }
3001 #endif /* CONFIG_MEMCG_KMEM */
3002
3003 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3004
3005 /*
3006  * Because tail pages are not marked as "used", set it. We're under
3007  * pgdat->lru_lock and migration entries setup in all page mappings.
3008  */
3009 void mem_cgroup_split_huge_fixup(struct page *head)
3010 {
3011         int i;
3012
3013         if (mem_cgroup_disabled())
3014                 return;
3015
3016         for (i = 1; i < HPAGE_PMD_NR; i++)
3017                 head[i].mem_cgroup = head->mem_cgroup;
3018 }
3019 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3020
3021 #ifdef CONFIG_MEMCG_SWAP
3022 /**
3023  * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3024  * @entry: swap entry to be moved
3025  * @from:  mem_cgroup which the entry is moved from
3026  * @to:  mem_cgroup which the entry is moved to
3027  *
3028  * It succeeds only when the swap_cgroup's record for this entry is the same
3029  * as the mem_cgroup's id of @from.
3030  *
3031  * Returns 0 on success, -EINVAL on failure.
3032  *
3033  * The caller must have charged to @to, IOW, called page_counter_charge() about
3034  * both res and memsw, and called css_get().
3035  */
3036 static int mem_cgroup_move_swap_account(swp_entry_t entry,
3037                                 struct mem_cgroup *from, struct mem_cgroup *to)
3038 {
3039         unsigned short old_id, new_id;
3040
3041         old_id = mem_cgroup_id(from);
3042         new_id = mem_cgroup_id(to);
3043
3044         if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
3045                 mod_memcg_state(from, MEMCG_SWAP, -1);
3046                 mod_memcg_state(to, MEMCG_SWAP, 1);
3047                 return 0;
3048         }
3049         return -EINVAL;
3050 }
3051 #else
3052 static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
3053                                 struct mem_cgroup *from, struct mem_cgroup *to)
3054 {
3055         return -EINVAL;
3056 }
3057 #endif
3058
3059 static DEFINE_MUTEX(memcg_max_mutex);
3060
3061 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3062                                  unsigned long max, bool memsw)
3063 {
3064         bool enlarge = false;
3065         bool drained = false;
3066         int ret;
3067         bool limits_invariant;
3068         struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
3069
3070         do {
3071                 if (signal_pending(current)) {
3072                         ret = -EINTR;
3073                         break;
3074                 }
3075
3076                 mutex_lock(&memcg_max_mutex);
3077                 /*
3078                  * Make sure that the new limit (memsw or memory limit) doesn't
3079                  * break our basic invariant rule memory.max <= memsw.max.
3080                  */
3081                 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
3082                                            max <= memcg->memsw.max;
3083                 if (!limits_invariant) {
3084                         mutex_unlock(&memcg_max_mutex);
3085                         ret = -EINVAL;
3086                         break;
3087                 }
3088                 if (max > counter->max)
3089                         enlarge = true;
3090                 ret = page_counter_set_max(counter, max);
3091                 mutex_unlock(&memcg_max_mutex);
3092
3093                 if (!ret)
3094                         break;
3095
3096                 if (!drained) {
3097                         drain_all_stock(memcg);
3098                         drained = true;
3099                         continue;
3100                 }
3101
3102                 if (!try_to_free_mem_cgroup_pages(memcg, 1,
3103                                         GFP_KERNEL, !memsw)) {
3104                         ret = -EBUSY;
3105                         break;
3106                 }
3107         } while (true);
3108
3109         if (!ret && enlarge)
3110                 memcg_oom_recover(memcg);
3111
3112         return ret;
3113 }
3114
3115 unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
3116                                             gfp_t gfp_mask,
3117                                             unsigned long *total_scanned)
3118 {
3119         unsigned long nr_reclaimed = 0;
3120         struct mem_cgroup_per_node *mz, *next_mz = NULL;
3121         unsigned long reclaimed;
3122         int loop = 0;
3123         struct mem_cgroup_tree_per_node *mctz;
3124         unsigned long excess;
3125         unsigned long nr_scanned;
3126
3127         if (order > 0)
3128                 return 0;
3129
3130         mctz = soft_limit_tree_node(pgdat->node_id);
3131
3132         /*
3133          * Do not even bother to check the largest node if the root
3134          * is empty. Do it lockless to prevent lock bouncing. Races
3135          * are acceptable as soft limit is best effort anyway.
3136          */
3137         if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
3138                 return 0;
3139
3140         /*
3141          * This loop can run a while, specially if mem_cgroup's continuously
3142          * keep exceeding their soft limit and putting the system under
3143          * pressure
3144          */
3145         do {
3146                 if (next_mz)
3147                         mz = next_mz;
3148                 else
3149                         mz = mem_cgroup_largest_soft_limit_node(mctz);
3150                 if (!mz)
3151                         break;
3152
3153                 nr_scanned = 0;
3154                 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
3155                                                     gfp_mask, &nr_scanned);
3156                 nr_reclaimed += reclaimed;
3157                 *total_scanned += nr_scanned;
3158                 spin_lock_irq(&mctz->lock);
3159                 __mem_cgroup_remove_exceeded(mz, mctz);
3160
3161                 /*
3162                  * If we failed to reclaim anything from this memory cgroup
3163                  * it is time to move on to the next cgroup
3164                  */
3165                 next_mz = NULL;
3166                 if (!reclaimed)
3167                         next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3168
3169                 excess = soft_limit_excess(mz->memcg);
3170                 /*
3171                  * One school of thought says that we should not add
3172                  * back the node to the tree if reclaim returns 0.
3173                  * But our reclaim could return 0, simply because due
3174                  * to priority we are exposing a smaller subset of
3175                  * memory to reclaim from. Consider this as a longer
3176                  * term TODO.
3177                  */
3178                 /* If excess == 0, no tree ops */
3179                 __mem_cgroup_insert_exceeded(mz, mctz, excess);
3180                 spin_unlock_irq(&mctz->lock);
3181                 css_put(&mz->memcg->css);
3182                 loop++;
3183                 /*
3184                  * Could not reclaim anything and there are no more
3185                  * mem cgroups to try or we seem to be looping without
3186                  * reclaiming anything.
3187                  */
3188                 if (!nr_reclaimed &&
3189                         (next_mz == NULL ||
3190                         loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3191                         break;
3192         } while (!nr_reclaimed);
3193         if (next_mz)
3194                 css_put(&next_mz->memcg->css);
3195         return nr_reclaimed;
3196 }
3197
3198 /*
3199  * Test whether @memcg has children, dead or alive.  Note that this
3200  * function doesn't care whether @memcg has use_hierarchy enabled and
3201  * returns %true if there are child csses according to the cgroup
3202  * hierarchy.  Testing use_hierarchy is the caller's responsibility.
3203  */
3204 static inline bool memcg_has_children(struct mem_cgroup *memcg)
3205 {
3206         bool ret;
3207
3208         rcu_read_lock();
3209         ret = css_next_child(NULL, &memcg->css);
3210         rcu_read_unlock();
3211         return ret;
3212 }
3213
3214 /*
3215  * Reclaims as many pages from the given memcg as possible.
3216  *
3217  * Caller is responsible for holding css reference for memcg.
3218  */
3219 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3220 {
3221         int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
3222
3223         /* we call try-to-free pages for make this cgroup empty */
3224         lru_add_drain_all();
3225
3226         drain_all_stock(memcg);
3227
3228         /* try to free all pages in this cgroup */
3229         while (nr_retries && page_counter_read(&memcg->memory)) {
3230                 int progress;
3231
3232                 if (signal_pending(current))
3233                         return -EINTR;
3234
3235                 progress = try_to_free_mem_cgroup_pages(memcg, 1,
3236                                                         GFP_KERNEL, true);
3237                 if (!progress) {
3238                         nr_retries--;
3239                         /* maybe some writeback is necessary */
3240                         congestion_wait(BLK_RW_ASYNC, HZ/10);
3241                 }
3242
3243         }
3244
3245         return 0;
3246 }
3247
3248 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3249                                             char *buf, size_t nbytes,
3250                                             loff_t off)
3251 {
3252         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3253
3254         if (mem_cgroup_is_root(memcg))
3255                 return -EINVAL;
3256         return mem_cgroup_force_empty(memcg) ?: nbytes;
3257 }
3258
3259 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3260                                      struct cftype *cft)
3261 {
3262         return mem_cgroup_from_css(css)->use_hierarchy;
3263 }
3264
3265 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3266                                       struct cftype *cft, u64 val)
3267 {
3268         int retval = 0;
3269         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3270         struct mem_cgroup *parent_memcg = mem_cgroup_from_css(memcg->css.parent);
3271
3272         if (memcg->use_hierarchy == val)
3273                 return 0;
3274
3275         /*
3276          * If parent's use_hierarchy is set, we can't make any modifications
3277          * in the child subtrees. If it is unset, then the change can
3278          * occur, provided the current cgroup has no children.
3279          *
3280          * For the root cgroup, parent_mem is NULL, we allow value to be
3281          * set if there are no children.
3282          */
3283         if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
3284                                 (val == 1 || val == 0)) {
3285                 if (!memcg_has_children(memcg))
3286                         memcg->use_hierarchy = val;
3287                 else
3288                         retval = -EBUSY;
3289         } else
3290                 retval = -EINVAL;
3291
3292         return retval;
3293 }
3294
3295 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3296 {
3297         unsigned long val;
3298
3299         if (mem_cgroup_is_root(memcg)) {
3300                 val = memcg_page_state(memcg, NR_FILE_PAGES) +
3301                         memcg_page_state(memcg, NR_ANON_MAPPED);
3302                 if (swap)
3303                         val += memcg_page_state(memcg, MEMCG_SWAP);
3304         } else {
3305                 if (!swap)
3306                         val = page_counter_read(&memcg->memory);
3307                 else
3308                         val = page_counter_read(&memcg->memsw);
3309         }
3310         return val;
3311 }
3312
3313 enum {
3314         RES_USAGE,
3315         RES_LIMIT,
3316         RES_MAX_USAGE,
3317         RES_FAILCNT,
3318         RES_SOFT_LIMIT,
3319 };
3320
3321 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
3322                                struct cftype *cft)
3323 {
3324         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3325         struct page_counter *counter;
3326
3327         switch (MEMFILE_TYPE(cft->private)) {
3328         case _MEM:
3329                 counter = &memcg->memory;
3330                 break;
3331         case _MEMSWAP:
3332                 counter = &memcg->memsw;
3333                 break;
3334         case _KMEM:
3335                 counter = &memcg->kmem;
3336                 break;
3337         case _TCP:
3338                 counter = &memcg->tcpmem;
3339                 break;
3340         default:
3341                 BUG();
3342         }
3343
3344         switch (MEMFILE_ATTR(cft->private)) {
3345         case RES_USAGE:
3346                 if (counter == &memcg->memory)
3347                         return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
3348                 if (counter == &memcg->memsw)
3349                         return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
3350                 return (u64)page_counter_read(counter) * PAGE_SIZE;
3351         case RES_LIMIT:
3352                 return (u64)counter->max * PAGE_SIZE;
3353         case RES_MAX_USAGE:
3354                 return (u64)counter->watermark * PAGE_SIZE;
3355         case RES_FAILCNT:
3356                 return counter->failcnt;
3357         case RES_SOFT_LIMIT:
3358                 return (u64)memcg->soft_limit * PAGE_SIZE;
3359         default:
3360                 BUG();
3361         }
3362 }
3363
3364 static void memcg_flush_percpu_vmstats(struct mem_cgroup *memcg)
3365 {
3366         unsigned long stat[MEMCG_NR_STAT] = {0};
3367         struct mem_cgroup *mi;
3368         int node, cpu, i;
3369
3370         for_each_online_cpu(cpu)
3371                 for (i = 0; i < MEMCG_NR_STAT; i++)
3372                         stat[i] += per_cpu(memcg->vmstats_percpu->stat[i], cpu);
3373
3374         for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
3375                 for (i = 0; i < MEMCG_NR_STAT; i++)
3376                         atomic_long_add(stat[i], &mi->vmstats[i]);
3377
3378         for_each_node(node) {
3379                 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
3380                 struct mem_cgroup_per_node *pi;
3381
3382                 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
3383                         stat[i] = 0;
3384
3385                 for_each_online_cpu(cpu)
3386                         for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
3387                                 stat[i] += per_cpu(
3388                                         pn->lruvec_stat_cpu->count[i], cpu);
3389
3390                 for (pi = pn; pi; pi = parent_nodeinfo(pi, node))
3391                         for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
3392                                 atomic_long_add(stat[i], &pi->lruvec_stat[i]);
3393         }
3394 }
3395
3396 static void memcg_flush_percpu_vmevents(struct mem_cgroup *memcg)
3397 {
3398         unsigned long events[NR_VM_EVENT_ITEMS];
3399         struct mem_cgroup *mi;
3400         int cpu, i;
3401
3402         for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3403                 events[i] = 0;
3404
3405         for_each_online_cpu(cpu)
3406                 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3407                         events[i] += per_cpu(memcg->vmstats_percpu->events[i],
3408                                              cpu);
3409
3410         for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
3411                 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3412                         atomic_long_add(events[i], &mi->vmevents[i]);
3413 }
3414
3415 #ifdef CONFIG_MEMCG_KMEM
3416 static int memcg_online_kmem(struct mem_cgroup *memcg)
3417 {
3418         int memcg_id;
3419
3420         if (cgroup_memory_nokmem)
3421                 return 0;
3422
3423         BUG_ON(memcg->kmemcg_id >= 0);
3424         BUG_ON(memcg->kmem_state);
3425
3426         memcg_id = memcg_alloc_cache_id();
3427         if (memcg_id < 0)
3428                 return memcg_id;
3429
3430         static_branch_enable(&memcg_kmem_enabled_key);
3431
3432         /*
3433          * A memory cgroup is considered kmem-online as soon as it gets
3434          * kmemcg_id. Setting the id after enabling static branching will
3435          * guarantee no one starts accounting before all call sites are
3436          * patched.
3437          */
3438         memcg->kmemcg_id = memcg_id;
3439         memcg->kmem_state = KMEM_ONLINE;
3440         INIT_LIST_HEAD(&memcg->kmem_caches);
3441
3442         return 0;
3443 }
3444
3445 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3446 {
3447         struct cgroup_subsys_state *css;
3448         struct mem_cgroup *parent, *child;
3449         int kmemcg_id;
3450
3451         if (memcg->kmem_state != KMEM_ONLINE)
3452                 return;
3453         /*
3454          * Clear the online state before clearing memcg_caches array
3455          * entries. The slab_mutex in memcg_deactivate_kmem_caches()
3456          * guarantees that no cache will be created for this cgroup
3457          * after we are done (see memcg_create_kmem_cache()).
3458          */
3459         memcg->kmem_state = KMEM_ALLOCATED;
3460
3461         parent = parent_mem_cgroup(memcg);
3462         if (!parent)
3463                 parent = root_mem_cgroup;
3464
3465         /*
3466          * Deactivate and reparent kmem_caches.
3467          */
3468         memcg_deactivate_kmem_caches(memcg, parent);
3469
3470         kmemcg_id = memcg->kmemcg_id;
3471         BUG_ON(kmemcg_id < 0);
3472
3473         /*
3474          * Change kmemcg_id of this cgroup and all its descendants to the
3475          * parent's id, and then move all entries from this cgroup's list_lrus
3476          * to ones of the parent. After we have finished, all list_lrus
3477          * corresponding to this cgroup are guaranteed to remain empty. The
3478          * ordering is imposed by list_lru_node->lock taken by
3479          * memcg_drain_all_list_lrus().
3480          */
3481         rcu_read_lock(); /* can be called from css_free w/o cgroup_mutex */
3482         css_for_each_descendant_pre(css, &memcg->css) {
3483                 child = mem_cgroup_from_css(css);
3484                 BUG_ON(child->kmemcg_id != kmemcg_id);
3485                 child->kmemcg_id = parent->kmemcg_id;
3486                 if (!memcg->use_hierarchy)
3487                         break;
3488         }
3489         rcu_read_unlock();
3490
3491         memcg_drain_all_list_lrus(kmemcg_id, parent);
3492
3493         memcg_free_cache_id(kmemcg_id);
3494 }
3495
3496 static void memcg_free_kmem(struct mem_cgroup *memcg)
3497 {
3498         /* css_alloc() failed, offlining didn't happen */
3499         if (unlikely(memcg->kmem_state == KMEM_ONLINE))
3500                 memcg_offline_kmem(memcg);
3501 }
3502 #else
3503 static int memcg_online_kmem(struct mem_cgroup *memcg)
3504 {
3505         return 0;
3506 }
3507 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3508 {
3509 }
3510 static void memcg_free_kmem(struct mem_cgroup *memcg)
3511 {
3512 }
3513 #endif /* CONFIG_MEMCG_KMEM */
3514
3515 static int memcg_update_kmem_max(struct mem_cgroup *memcg,
3516                                  unsigned long max)
3517 {
3518         int ret;
3519
3520         mutex_lock(&memcg_max_mutex);
3521         ret = page_counter_set_max(&memcg->kmem, max);
3522         mutex_unlock(&memcg_max_mutex);
3523         return ret;
3524 }
3525
3526 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
3527 {
3528         int ret;
3529
3530         mutex_lock(&memcg_max_mutex);
3531
3532         ret = page_counter_set_max(&memcg->tcpmem, max);
3533         if (ret)
3534                 goto out;
3535
3536         if (!memcg->tcpmem_active) {
3537                 /*
3538                  * The active flag needs to be written after the static_key
3539                  * update. This is what guarantees that the socket activation
3540                  * function is the last one to run. See mem_cgroup_sk_alloc()
3541                  * for details, and note that we don't mark any socket as
3542                  * belonging to this memcg until that flag is up.
3543                  *
3544                  * We need to do this, because static_keys will span multiple
3545                  * sites, but we can't control their order. If we mark a socket
3546                  * as accounted, but the accounting functions are not patched in
3547                  * yet, we'll lose accounting.
3548                  *
3549                  * We never race with the readers in mem_cgroup_sk_alloc(),
3550                  * because when this value change, the code to process it is not
3551                  * patched in yet.
3552                  */
3553                 static_branch_inc(&memcg_sockets_enabled_key);
3554                 memcg->tcpmem_active = true;
3555         }
3556 out:
3557         mutex_unlock(&memcg_max_mutex);
3558         return ret;
3559 }
3560
3561 /*
3562  * The user of this function is...
3563  * RES_LIMIT.
3564  */
3565 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3566                                 char *buf, size_t nbytes, loff_t off)
3567 {
3568         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3569         unsigned long nr_pages;
3570         int ret;
3571
3572         buf = strstrip(buf);
3573         ret = page_counter_memparse(buf, "-1", &nr_pages);
3574         if (ret)
3575                 return ret;
3576
3577         switch (MEMFILE_ATTR(of_cft(of)->private)) {
3578         case RES_LIMIT:
3579                 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3580                         ret = -EINVAL;
3581                         break;
3582                 }
3583                 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3584                 case _MEM:
3585                         ret = mem_cgroup_resize_max(memcg, nr_pages, false);
3586                         break;
3587                 case _MEMSWAP:
3588                         ret = mem_cgroup_resize_max(memcg, nr_pages, true);
3589                         break;
3590                 case _KMEM:
3591                         pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
3592                                      "Please report your usecase to linux-mm@kvack.org if you "
3593                                      "depend on this functionality.\n");
3594                         ret = memcg_update_kmem_max(memcg, nr_pages);
3595                         break;
3596                 case _TCP:
3597                         ret = memcg_update_tcp_max(memcg, nr_pages);
3598                         break;
3599                 }
3600                 break;
3601         case RES_SOFT_LIMIT:
3602                 memcg->soft_limit = nr_pages;
3603                 ret = 0;
3604                 break;
3605         }
3606         return ret ?: nbytes;
3607 }
3608
3609 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3610                                 size_t nbytes, loff_t off)
3611 {
3612         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
3613         struct page_counter *counter;
3614
3615         switch (MEMFILE_TYPE(of_cft(of)->private)) {
3616         case _MEM:
3617                 counter = &memcg->memory;
3618                 break;
3619         case _MEMSWAP:
3620                 counter = &memcg->memsw;
3621                 break;
3622         case _KMEM:
3623                 counter = &memcg->kmem;
3624                 break;
3625         case _TCP:
3626                 counter = &memcg->tcpmem;
3627                 break;
3628         default:
3629                 BUG();
3630         }
3631
3632         switch (MEMFILE_ATTR(of_cft(of)->private)) {
3633         case RES_MAX_USAGE:
3634                 page_counter_reset_watermark(counter);
3635                 break;
3636         case RES_FAILCNT:
3637                 counter->failcnt = 0;
3638                 break;
3639         default:
3640                 BUG();
3641         }
3642
3643         return nbytes;
3644 }
3645
3646 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
3647                                         struct cftype *cft)
3648 {
3649         return mem_cgroup_from_css(css)->move_charge_at_immigrate;
3650 }
3651
3652 #ifdef CONFIG_MMU
3653 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3654                                         struct cftype *cft, u64 val)
3655 {
3656         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3657
3658         if (val & ~MOVE_MASK)
3659                 return -EINVAL;
3660
3661         /*
3662          * No kind of locking is needed in here, because ->can_attach() will
3663          * check this value once in the beginning of the process, and then carry
3664          * on with stale data. This means that changes to this value will only
3665          * affect task migrations starting after the change.
3666          */
3667         memcg->move_charge_at_immigrate = val;
3668         return 0;
3669 }
3670 #else
3671 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
3672                                         struct cftype *cft, u64 val)
3673 {
3674         return -ENOSYS;
3675 }
3676 #endif
3677
3678 #ifdef CONFIG_NUMA
3679
3680 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3681 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3682 #define LRU_ALL      ((1 << NR_LRU_LISTS) - 1)
3683
3684 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
3685                                 int nid, unsigned int lru_mask, bool tree)
3686 {
3687         struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
3688         unsigned long nr = 0;
3689         enum lru_list lru;
3690
3691         VM_BUG_ON((unsigned)nid >= nr_node_ids);
3692
3693         for_each_lru(lru) {
3694                 if (!(BIT(lru) & lru_mask))
3695                         continue;
3696                 if (tree)
3697                         nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
3698                 else
3699                         nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
3700         }
3701         return nr;
3702 }
3703
3704 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
3705                                              unsigned int lru_mask,
3706                                              bool tree)
3707 {
3708         unsigned long nr = 0;
3709         enum lru_list lru;
3710
3711         for_each_lru(lru) {
3712                 if (!(BIT(lru) & lru_mask))
3713                         continue;
3714                 if (tree)
3715                         nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
3716                 else
3717                         nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
3718         }
3719         return nr;
3720 }
3721
3722 static int memcg_numa_stat_show(struct seq_file *m, void *v)
3723 {
3724         struct numa_stat {
3725                 const char *name;
3726                 unsigned int lru_mask;
3727         };
3728
3729         static const struct numa_stat stats[] = {
3730                 { "total", LRU_ALL },
3731                 { "file", LRU_ALL_FILE },
3732                 { "anon", LRU_ALL_ANON },
3733                 { "unevictable", BIT(LRU_UNEVICTABLE) },
3734         };
3735         const struct numa_stat *stat;
3736         int nid;
3737         struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3738
3739         for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3740                 seq_printf(m, "%s=%lu", stat->name,
3741                            mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
3742                                                    false));
3743                 for_each_node_state(nid, N_MEMORY)
3744                         seq_printf(m, " N%d=%lu", nid,
3745                                    mem_cgroup_node_nr_lru_pages(memcg, nid,
3746                                                         stat->lru_mask, false));
3747                 seq_putc(m, '\n');
3748         }
3749
3750         for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
3751
3752                 seq_printf(m, "hierarchical_%s=%lu", stat->name,
3753                            mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
3754                                                    true));
3755                 for_each_node_state(nid, N_MEMORY)
3756                         seq_printf(m, " N%d=%lu", nid,
3757                                    mem_cgroup_node_nr_lru_pages(memcg, nid,
3758                                                         stat->lru_mask, true));
3759                 seq_putc(m, '\n');
3760         }
3761
3762         return 0;
3763 }
3764 #endif /* CONFIG_NUMA */
3765
3766 static const unsigned int memcg1_stats[] = {
3767         NR_FILE_PAGES,
3768         NR_ANON_MAPPED,
3769 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3770         NR_ANON_THPS,
3771 #endif
3772         NR_SHMEM,
3773         NR_FILE_MAPPED,
3774         NR_FILE_DIRTY,
3775         NR_WRITEBACK,
3776         MEMCG_SWAP,
3777 };
3778
3779 static const char *const memcg1_stat_names[] = {
3780         "cache",
3781         "rss",
3782 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3783         "rss_huge",
3784 #endif
3785         "shmem",
3786         "mapped_file",
3787         "dirty",
3788         "writeback",
3789         "swap",
3790 };
3791
3792 /* Universal VM events cgroup1 shows, original sort order */
3793 static const unsigned int memcg1_events[] = {
3794         PGPGIN,
3795         PGPGOUT,
3796         PGFAULT,
3797         PGMAJFAULT,
3798 };
3799
3800 static int memcg_stat_show(struct seq_file *m, void *v)
3801 {
3802         struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
3803         unsigned long memory, memsw;
3804         struct mem_cgroup *mi;
3805         unsigned int i;
3806
3807         BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
3808
3809         for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
3810                 unsigned long nr;
3811
3812                 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
3813                         continue;
3814                 nr = memcg_page_state_local(memcg, memcg1_stats[i]);
3815 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3816                 if (memcg1_stats[i] == NR_ANON_THPS)
3817                         nr *= HPAGE_PMD_NR;
3818 #endif
3819                 seq_printf(m, "%s %lu\n", memcg1_stat_names[i], nr * PAGE_SIZE);
3820         }
3821
3822         for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3823                 seq_printf(m, "%s %lu\n", vm_event_name(memcg1_events[i]),
3824                            memcg_events_local(memcg, memcg1_events[i]));
3825
3826         for (i = 0; i < NR_LRU_LISTS; i++)
3827                 seq_printf(m, "%s %lu\n", lru_list_name(i),
3828                            memcg_page_state_local(memcg, NR_LRU_BASE + i) *
3829                            PAGE_SIZE);
3830
3831         /* Hierarchical information */
3832         memory = memsw = PAGE_COUNTER_MAX;
3833         for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
3834                 memory = min(memory, READ_ONCE(mi->memory.max));
3835                 memsw = min(memsw, READ_ONCE(mi->memsw.max));
3836         }
3837         seq_printf(m, "hierarchical_memory_limit %llu\n",
3838                    (u64)memory * PAGE_SIZE);
3839         if (do_memsw_account())
3840                 seq_printf(m, "hierarchical_memsw_limit %llu\n",
3841                            (u64)memsw * PAGE_SIZE);
3842
3843         for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
3844                 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
3845                         continue;
3846                 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
3847                            (u64)memcg_page_state(memcg, memcg1_stats[i]) *
3848                            PAGE_SIZE);
3849         }
3850
3851         for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
3852                 seq_printf(m, "total_%s %llu\n",
3853                            vm_event_name(memcg1_events[i]),
3854                            (u64)memcg_events(memcg, memcg1_events[i]));
3855
3856         for (i = 0; i < NR_LRU_LISTS; i++)
3857                 seq_printf(m, "total_%s %llu\n", lru_list_name(i),
3858                            (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
3859                            PAGE_SIZE);
3860
3861 #ifdef CONFIG_DEBUG_VM
3862         {
3863                 pg_data_t *pgdat;
3864                 struct mem_cgroup_per_node *mz;
3865                 unsigned long anon_cost = 0;
3866                 unsigned long file_cost = 0;
3867
3868                 for_each_online_pgdat(pgdat) {
3869                         mz = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
3870
3871                         anon_cost += mz->lruvec.anon_cost;
3872                         file_cost += mz->lruvec.file_cost;
3873                 }
3874                 seq_printf(m, "anon_cost %lu\n", anon_cost);
3875                 seq_printf(m, "file_cost %lu\n", file_cost);
3876         }
3877 #endif
3878
3879         return 0;
3880 }
3881
3882 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
3883                                       struct cftype *cft)
3884 {
3885         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3886
3887         return mem_cgroup_swappiness(memcg);
3888 }
3889
3890 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
3891                                        struct cftype *cft, u64 val)
3892 {
3893         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3894
3895         if (val > 100)
3896                 return -EINVAL;
3897
3898         if (css->parent)
3899                 memcg->swappiness = val;
3900         else
3901                 vm_swappiness = val;
3902
3903         return 0;
3904 }
3905
3906 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
3907 {
3908         struct mem_cgroup_threshold_ary *t;
3909         unsigned long usage;
3910         int i;
3911
3912         rcu_read_lock();
3913         if (!swap)
3914                 t = rcu_dereference(memcg->thresholds.primary);
3915         else
3916                 t = rcu_dereference(memcg->memsw_thresholds.primary);
3917
3918         if (!t)
3919                 goto unlock;
3920
3921         usage = mem_cgroup_usage(memcg, swap);
3922
3923         /*
3924          * current_threshold points to threshold just below or equal to usage.
3925          * If it's not true, a threshold was crossed after last
3926          * call of __mem_cgroup_threshold().
3927          */
3928         i = t->current_threshold;
3929
3930         /*
3931          * Iterate backward over array of thresholds starting from
3932          * current_threshold and check if a threshold is crossed.
3933          * If none of thresholds below usage is crossed, we read
3934          * only one element of the array here.
3935          */
3936         for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
3937                 eventfd_signal(t->entries[i].eventfd, 1);
3938
3939         /* i = current_threshold + 1 */
3940         i++;
3941
3942         /*
3943          * Iterate forward over array of thresholds starting from
3944          * current_threshold+1 and check if a threshold is crossed.
3945          * If none of thresholds above usage is crossed, we read
3946          * only one element of the array here.
3947          */
3948         for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
3949                 eventfd_signal(t->entries[i].eventfd, 1);
3950
3951         /* Update current_threshold */
3952         t->current_threshold = i - 1;
3953 unlock:
3954         rcu_read_unlock();
3955 }
3956
3957 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
3958 {
3959         while (memcg) {
3960                 __mem_cgroup_threshold(memcg, false);
3961                 if (do_memsw_account())
3962                         __mem_cgroup_threshold(memcg, true);
3963
3964                 memcg = parent_mem_cgroup(memcg);
3965         }
3966 }
3967
3968 static int compare_thresholds(const void *a, const void *b)
3969 {
3970         const struct mem_cgroup_threshold *_a = a;
3971         const struct mem_cgroup_threshold *_b = b;
3972
3973         if (_a->threshold > _b->threshold)
3974                 return 1;
3975
3976         if (_a->threshold < _b->threshold)
3977                 return -1;
3978
3979         return 0;
3980 }
3981
3982 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
3983 {
3984         struct mem_cgroup_eventfd_list *ev;
3985
3986         spin_lock(&memcg_oom_lock);
3987
3988         list_for_each_entry(ev, &memcg->oom_notify, list)
3989                 eventfd_signal(ev->eventfd, 1);
3990
3991         spin_unlock(&memcg_oom_lock);
3992         return 0;
3993 }
3994
3995 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
3996 {
3997         struct mem_cgroup *iter;
3998
3999         for_each_mem_cgroup_tree(iter, memcg)
4000                 mem_cgroup_oom_notify_cb(iter);
4001 }
4002
4003 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4004         struct eventfd_ctx *eventfd, const char *args, enum res_type type)
4005 {
4006         struct mem_cgroup_thresholds *thresholds;
4007         struct mem_cgroup_threshold_ary *new;
4008         unsigned long threshold;
4009         unsigned long usage;
4010         int i, size, ret;
4011
4012         ret = page_counter_memparse(args, "-1", &threshold);
4013         if (ret)
4014                 return ret;
4015
4016         mutex_lock(&memcg->thresholds_lock);
4017
4018         if (type == _MEM) {
4019                 thresholds = &memcg->thresholds;
4020                 usage = mem_cgroup_usage(memcg, false);
4021         } else if (type == _MEMSWAP) {
4022                 thresholds = &memcg->memsw_thresholds;
4023                 usage = mem_cgroup_usage(memcg, true);
4024         } else
4025                 BUG();
4026
4027         /* Check if a threshold crossed before adding a new one */
4028         if (thresholds->primary)
4029                 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4030
4031         size = thresholds->primary ? thresholds->primary->size + 1 : 1;
4032
4033         /* Allocate memory for new array of thresholds */
4034         new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
4035         if (!new) {
4036                 ret = -ENOMEM;
4037                 goto unlock;
4038         }
4039         new->size = size;
4040
4041         /* Copy thresholds (if any) to new array */
4042         if (thresholds->primary) {
4043                 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
4044                                 sizeof(struct mem_cgroup_threshold));
4045         }
4046
4047         /* Add new threshold */
4048         new->entries[size - 1].eventfd = eventfd;
4049         new->entries[size - 1].threshold = threshold;
4050
4051         /* Sort thresholds. Registering of new threshold isn't time-critical */
4052         sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
4053                         compare_thresholds, NULL);
4054
4055         /* Find current threshold */
4056         new->current_threshold = -1;
4057         for (i = 0; i < size; i++) {
4058                 if (new->entries[i].threshold <= usage) {
4059                         /*
4060                          * new->current_threshold will not be used until
4061                          * rcu_assign_pointer(), so it's safe to increment
4062                          * it here.
4063                          */
4064                         ++new->current_threshold;
4065                 } else
4066                         break;
4067         }
4068
4069         /* Free old spare buffer and save old primary buffer as spare */
4070         kfree(thresholds->spare);
4071         thresholds->spare = thresholds->primary;
4072
4073         rcu_assign_pointer(thresholds->primary, new);
4074
4075         /* To be sure that nobody uses thresholds */
4076         synchronize_rcu();
4077
4078 unlock:
4079         mutex_unlock(&memcg->thresholds_lock);
4080
4081         return ret;
4082 }
4083
4084 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
4085         struct eventfd_ctx *eventfd, const char *args)
4086 {
4087         return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
4088 }
4089
4090 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
4091         struct eventfd_ctx *eventfd, const char *args)
4092 {
4093         return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
4094 }
4095
4096 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4097         struct eventfd_ctx *eventfd, enum res_type type)
4098 {
4099         struct mem_cgroup_thresholds *thresholds;
4100         struct mem_cgroup_threshold_ary *new;
4101         unsigned long usage;
4102         int i, j, size, entries;
4103
4104         mutex_lock(&memcg->thresholds_lock);
4105
4106         if (type == _MEM) {
4107                 thresholds = &memcg->thresholds;
4108                 usage = mem_cgroup_usage(memcg, false);
4109         } else if (type == _MEMSWAP) {
4110                 thresholds = &memcg->memsw_thresholds;
4111                 usage = mem_cgroup_usage(memcg, true);
4112         } else
4113                 BUG();
4114
4115         if (!thresholds->primary)
4116                 goto unlock;
4117
4118         /* Check if a threshold crossed before removing */
4119         __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4120
4121         /* Calculate new number of threshold */
4122         size = entries = 0;
4123         for (i = 0; i < thresholds->primary->size; i++) {
4124                 if (thresholds->primary->entries[i].eventfd != eventfd)
4125                         size++;
4126                 else
4127                         entries++;
4128         }
4129
4130         new = thresholds->spare;
4131
4132         /* If no items related to eventfd have been cleared, nothing to do */
4133         if (!entries)
4134                 goto unlock;
4135
4136         /* Set thresholds array to NULL if we don't have thresholds */
4137         if (!size) {
4138                 kfree(new);
4139                 new = NULL;
4140                 goto swap_buffers;
4141         }
4142
4143         new->size = size;
4144
4145         /* Copy thresholds and find current threshold */
4146         new->current_threshold = -1;
4147         for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4148                 if (thresholds->primary->entries[i].eventfd == eventfd)
4149                         continue;
4150
4151                 new->entries[j] = thresholds->primary->entries[i];
4152                 if (new->entries[j].threshold <= usage) {
4153                         /*
4154                          * new->current_threshold will not be used
4155                          * until rcu_assign_pointer(), so it's safe to increment
4156                          * it here.
4157                          */
4158                         ++new->current_threshold;
4159                 }
4160                 j++;
4161         }
4162
4163 swap_buffers:
4164         /* Swap primary and spare array */
4165         thresholds->spare = thresholds->primary;
4166
4167         rcu_assign_pointer(thresholds->primary, new);
4168
4169         /* To be sure that nobody uses thresholds */
4170         synchronize_rcu();
4171
4172         /* If all events are unregistered, free the spare array */
4173         if (!new) {
4174                 kfree(thresholds->spare);
4175                 thresholds->spare = NULL;
4176         }
4177 unlock:
4178         mutex_unlock(&memcg->thresholds_lock);
4179 }
4180
4181 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4182         struct eventfd_ctx *eventfd)
4183 {
4184         return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
4185 }
4186
4187 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
4188         struct eventfd_ctx *eventfd)
4189 {
4190         return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
4191 }
4192
4193 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
4194         struct eventfd_ctx *eventfd, const char *args)
4195 {
4196         struct mem_cgroup_eventfd_list *event;
4197
4198         event = kmalloc(sizeof(*event), GFP_KERNEL);
4199         if (!event)
4200                 return -ENOMEM;
4201
4202         spin_lock(&memcg_oom_lock);
4203
4204         event->eventfd = eventfd;
4205         list_add(&event->list, &memcg->oom_notify);
4206
4207         /* already in OOM ? */
4208         if (memcg->under_oom)
4209                 eventfd_signal(eventfd, 1);
4210         spin_unlock(&memcg_oom_lock);
4211
4212         return 0;
4213 }
4214
4215 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
4216         struct eventfd_ctx *eventfd)
4217 {
4218         struct mem_cgroup_eventfd_list *ev, *tmp;
4219
4220         spin_lock(&memcg_oom_lock);
4221
4222         list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
4223                 if (ev->eventfd == eventfd) {
4224                         list_del(&ev->list);
4225                         kfree(ev);
4226                 }
4227         }
4228
4229         spin_unlock(&memcg_oom_lock);
4230 }
4231
4232 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
4233 {
4234         struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
4235
4236         seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
4237         seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
4238         seq_printf(sf, "oom_kill %lu\n",
4239                    atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
4240         return 0;
4241 }
4242
4243 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
4244         struct cftype *cft, u64 val)
4245 {
4246         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4247
4248         /* cannot set to root cgroup and only 0 and 1 are allowed */
4249         if (!css->parent || !((val == 0) || (val == 1)))
4250                 return -EINVAL;
4251
4252         memcg->oom_kill_disable = val;
4253         if (!val)
4254                 memcg_oom_recover(memcg);
4255
4256         return 0;
4257 }
4258
4259 #ifdef CONFIG_CGROUP_WRITEBACK
4260
4261 #include <trace/events/writeback.h>
4262
4263 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4264 {
4265         return wb_domain_init(&memcg->cgwb_domain, gfp);
4266 }
4267
4268 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4269 {
4270         wb_domain_exit(&memcg->cgwb_domain);
4271 }
4272
4273 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4274 {
4275         wb_domain_size_changed(&memcg->cgwb_domain);
4276 }
4277
4278 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4279 {
4280         struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4281
4282         if (!memcg->css.parent)
4283                 return NULL;
4284
4285         return &memcg->cgwb_domain;
4286 }
4287
4288 /*
4289  * idx can be of type enum memcg_stat_item or node_stat_item.
4290  * Keep in sync with memcg_exact_page().
4291  */
4292 static unsigned long memcg_exact_page_state(struct mem_cgroup *memcg, int idx)
4293 {
4294         long x = atomic_long_read(&memcg->vmstats[idx]);
4295         int cpu;
4296
4297         for_each_online_cpu(cpu)
4298                 x += per_cpu_ptr(memcg->vmstats_percpu, cpu)->stat[idx];
4299         if (x < 0)
4300                 x = 0;
4301         return x;
4302 }
4303
4304 /**
4305  * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4306  * @wb: bdi_writeback in question
4307  * @pfilepages: out parameter for number of file pages
4308  * @pheadroom: out parameter for number of allocatable pages according to memcg
4309  * @pdirty: out parameter for number of dirty pages
4310  * @pwriteback: out parameter for number of pages under writeback
4311  *
4312  * Determine the numbers of file, headroom, dirty, and writeback pages in
4313  * @wb's memcg.  File, dirty and writeback are self-explanatory.  Headroom
4314  * is a bit more involved.
4315  *
4316  * A memcg's headroom is "min(max, high) - used".  In the hierarchy, the
4317  * headroom is calculated as the lowest headroom of itself and the
4318  * ancestors.  Note that this doesn't consider the actual amount of
4319  * available memory in the system.  The caller should further cap
4320  * *@pheadroom accordingly.
4321  */
4322 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4323                          unsigned long *pheadroom, unsigned long *pdirty,
4324                          unsigned long *pwriteback)
4325 {
4326         struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4327         struct mem_cgroup *parent;
4328
4329         *pdirty = memcg_exact_page_state(memcg, NR_FILE_DIRTY);
4330
4331         *pwriteback = memcg_exact_page_state(memcg, NR_WRITEBACK);
4332         *pfilepages = memcg_exact_page_state(memcg, NR_INACTIVE_FILE) +
4333                         memcg_exact_page_state(memcg, NR_ACTIVE_FILE);
4334         *pheadroom = PAGE_COUNTER_MAX;
4335
4336         while ((parent = parent_mem_cgroup(memcg))) {
4337                 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
4338                                             READ_ONCE(memcg->memory.high));
4339                 unsigned long used = page_counter_read(&memcg->memory);
4340
4341                 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
4342                 memcg = parent;
4343         }
4344 }
4345
4346 /*
4347  * Foreign dirty flushing
4348  *
4349  * There's an inherent mismatch between memcg and writeback.  The former
4350  * trackes ownership per-page while the latter per-inode.  This was a
4351  * deliberate design decision because honoring per-page ownership in the
4352  * writeback path is complicated, may lead to higher CPU and IO overheads
4353  * and deemed unnecessary given that write-sharing an inode across
4354  * different cgroups isn't a common use-case.
4355  *
4356  * Combined with inode majority-writer ownership switching, this works well
4357  * enough in most cases but there are some pathological cases.  For
4358  * example, let's say there are two cgroups A and B which keep writing to
4359  * different but confined parts of the same inode.  B owns the inode and
4360  * A's memory is limited far below B's.  A's dirty ratio can rise enough to
4361  * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4362  * triggering background writeback.  A will be slowed down without a way to
4363  * make writeback of the dirty pages happen.
4364  *
4365  * Conditions like the above can lead to a cgroup getting repatedly and
4366  * severely throttled after making some progress after each
4367  * dirty_expire_interval while the underyling IO device is almost
4368  * completely idle.
4369  *
4370  * Solving this problem completely requires matching the ownership tracking
4371  * granularities between memcg and writeback in either direction.  However,
4372  * the more egregious behaviors can be avoided by simply remembering the
4373  * most recent foreign dirtying events and initiating remote flushes on
4374  * them when local writeback isn't enough to keep the memory clean enough.
4375  *
4376  * The following two functions implement such mechanism.  When a foreign
4377  * page - a page whose memcg and writeback ownerships don't match - is
4378  * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4379  * bdi_writeback on the page owning memcg.  When balance_dirty_pages()
4380  * decides that the memcg needs to sleep due to high dirty ratio, it calls
4381  * mem_cgroup_flush_foreign() which queues writeback on the recorded
4382  * foreign bdi_writebacks which haven't expired.  Both the numbers of
4383  * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4384  * limited to MEMCG_CGWB_FRN_CNT.
4385  *
4386  * The mechanism only remembers IDs and doesn't hold any object references.
4387  * As being wrong occasionally doesn't matter, updates and accesses to the
4388  * records are lockless and racy.
4389  */
4390 void mem_cgroup_track_foreign_dirty_slowpath(struct page *page,
4391                                              struct bdi_writeback *wb)
4392 {
4393         struct mem_cgroup *memcg = page->mem_cgroup;
4394         struct memcg_cgwb_frn *frn;
4395         u64 now = get_jiffies_64();
4396         u64 oldest_at = now;
4397         int oldest = -1;
4398         int i;
4399
4400         trace_track_foreign_dirty(page, wb);
4401
4402         /*
4403          * Pick the slot to use.  If there is already a slot for @wb, keep
4404          * using it.  If not replace the oldest one which isn't being
4405          * written out.
4406          */
4407         for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4408                 frn = &memcg->cgwb_frn[i];
4409                 if (frn->bdi_id == wb->bdi->id &&
4410                     frn->memcg_id == wb->memcg_css->id)
4411                         break;
4412                 if (time_before64(frn->at, oldest_at) &&
4413                     atomic_read(&frn->done.cnt) == 1) {
4414                         oldest = i;
4415                         oldest_at = frn->at;
4416                 }
4417         }
4418
4419         if (i < MEMCG_CGWB_FRN_CNT) {
4420                 /*
4421                  * Re-using an existing one.  Update timestamp lazily to
4422                  * avoid making the cacheline hot.  We want them to be
4423                  * reasonably up-to-date and significantly shorter than
4424                  * dirty_expire_interval as that's what expires the record.
4425                  * Use the shorter of 1s and dirty_expire_interval / 8.
4426                  */
4427                 unsigned long update_intv =
4428                         min_t(unsigned long, HZ,
4429                               msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4430
4431                 if (time_before64(frn->at, now - update_intv))
4432                         frn->at = now;
4433         } else if (oldest >= 0) {
4434                 /* replace the oldest free one */
4435                 frn = &memcg->cgwb_frn[oldest];
4436                 frn->bdi_id = wb->bdi->id;
4437                 frn->memcg_id = wb->memcg_css->id;
4438                 frn->at = now;
4439         }
4440 }
4441
4442 /* issue foreign writeback flushes for recorded foreign dirtying events */
4443 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4444 {
4445         struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4446         unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4447         u64 now = jiffies_64;
4448         int i;
4449
4450         for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4451                 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4452
4453                 /*
4454                  * If the record is older than dirty_expire_interval,
4455                  * writeback on it has already started.  No need to kick it
4456                  * off again.  Also, don't start a new one if there's
4457                  * already one in flight.
4458                  */
4459                 if (time_after64(frn->at, now - intv) &&
4460                     atomic_read(&frn->done.cnt) == 1) {
4461                         frn->at = 0;
4462                         trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
4463                         cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id, 0,
4464                                                WB_REASON_FOREIGN_FLUSH,
4465                                                &frn->done);
4466                 }
4467         }
4468 }
4469
4470 #else   /* CONFIG_CGROUP_WRITEBACK */
4471
4472 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4473 {
4474         return 0;
4475 }
4476
4477 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4478 {
4479 }
4480
4481 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4482 {
4483 }
4484
4485 #endif  /* CONFIG_CGROUP_WRITEBACK */
4486
4487 /*
4488  * DO NOT USE IN NEW FILES.
4489  *
4490  * "cgroup.event_control" implementation.
4491  *
4492  * This is way over-engineered.  It tries to support fully configurable
4493  * events for each user.  Such level of flexibility is completely
4494  * unnecessary especially in the light of the planned unified hierarchy.
4495  *
4496  * Please deprecate this and replace with something simpler if at all
4497  * possible.
4498  */
4499
4500 /*
4501  * Unregister event and free resources.
4502  *
4503  * Gets called from workqueue.
4504  */
4505 static void memcg_event_remove(struct work_struct *work)
4506 {
4507         struct mem_cgroup_event *event =
4508                 container_of(work, struct mem_cgroup_event, remove);
4509         struct mem_cgroup *memcg = event->memcg;
4510
4511         remove_wait_queue(event->wqh, &event->wait);
4512
4513         event->unregister_event(memcg, event->eventfd);
4514
4515         /* Notify userspace the event is going away. */
4516         eventfd_signal(event->eventfd, 1);
4517
4518         eventfd_ctx_put(event->eventfd);
4519         kfree(event);
4520         css_put(&memcg->css);
4521 }
4522
4523 /*
4524  * Gets called on EPOLLHUP on eventfd when user closes it.
4525  *
4526  * Called with wqh->lock held and interrupts disabled.
4527  */
4528 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
4529                             int sync, void *key)
4530 {
4531         struct mem_cgroup_event *event =
4532                 container_of(wait, struct mem_cgroup_event, wait);
4533         struct mem_cgroup *memcg = event->memcg;
4534         __poll_t flags = key_to_poll(key);
4535
4536         if (flags & EPOLLHUP) {
4537                 /*
4538                  * If the event has been detached at cgroup removal, we
4539                  * can simply return knowing the other side will cleanup
4540                  * for us.
4541                  *
4542                  * We can't race against event freeing since the other
4543                  * side will require wqh->lock via remove_wait_queue(),
4544                  * which we hold.
4545                  */
4546                 spin_lock(&memcg->event_list_lock);
4547                 if (!list_empty(&event->list)) {
4548                         list_del_init(&event->list);
4549                         /*
4550                          * We are in atomic context, but cgroup_event_remove()
4551                          * may sleep, so we have to call it in workqueue.
4552                          */
4553                         schedule_work(&event->remove);
4554                 }
4555                 spin_unlock(&memcg->event_list_lock);
4556         }
4557
4558         return 0;
4559 }
4560
4561 static void memcg_event_ptable_queue_proc(struct file *file,
4562                 wait_queue_head_t *wqh, poll_table *pt)
4563 {
4564         struct mem_cgroup_event *event =
4565                 container_of(pt, struct mem_cgroup_event, pt);
4566
4567         event->wqh = wqh;
4568         add_wait_queue(wqh, &event->wait);
4569 }
4570
4571 /*
4572  * DO NOT USE IN NEW FILES.
4573  *
4574  * Parse input and register new cgroup event handler.
4575  *
4576  * Input must be in format '<event_fd> <control_fd> <args>'.
4577  * Interpretation of args is defined by control file implementation.
4578  */
4579 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4580                                          char *buf, size_t nbytes, loff_t off)
4581 {
4582         struct cgroup_subsys_state *css = of_css(of);
4583         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
4584         struct mem_cgroup_event *event;
4585         struct cgroup_subsys_state *cfile_css;
4586         unsigned int efd, cfd;
4587         struct fd efile;
4588         struct fd cfile;
4589         const char *name;
4590         char *endp;
4591         int ret;
4592
4593         buf = strstrip(buf);
4594
4595         efd = simple_strtoul(buf, &endp, 10);
4596         if (*endp != ' ')
4597                 return -EINVAL;
4598         buf = endp + 1;
4599
4600         cfd = simple_strtoul(buf, &endp, 10);
4601         if ((*endp != ' ') && (*endp != '\0'))
4602                 return -EINVAL;
4603         buf = endp + 1;
4604
4605         event = kzalloc(sizeof(*event), GFP_KERNEL);
4606         if (!event)
4607                 return -ENOMEM;
4608
4609         event->memcg = memcg;
4610         INIT_LIST_HEAD(&event->list);
4611         init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4612         init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4613         INIT_WORK(&event->remove, memcg_event_remove);
4614
4615         efile = fdget(efd);
4616         if (!efile.file) {
4617                 ret = -EBADF;
4618                 goto out_kfree;
4619         }
4620
4621         event->eventfd = eventfd_ctx_fileget(efile.file);
4622         if (IS_ERR(event->eventfd)) {
4623                 ret = PTR_ERR(event->eventfd);
4624                 goto out_put_efile;
4625         }
4626
4627         cfile = fdget(cfd);
4628         if (!cfile.file) {
4629                 ret = -EBADF;
4630                 goto out_put_eventfd;
4631         }
4632
4633         /* the process need read permission on control file */
4634         /* AV: shouldn't we check that it's been opened for read instead? */
4635         ret = inode_permission(file_inode(cfile.file), MAY_READ);
4636         if (ret < 0)
4637                 goto out_put_cfile;
4638
4639         /*
4640          * Determine the event callbacks and set them in @event.  This used
4641          * to be done via struct cftype but cgroup core no longer knows
4642          * about these events.  The following is crude but the whole thing
4643          * is for compatibility anyway.
4644          *
4645          * DO NOT ADD NEW FILES.
4646          */
4647         name = cfile.file->f_path.dentry->d_name.name;
4648
4649         if (!strcmp(name, "memory.usage_in_bytes")) {
4650                 event->register_event = mem_cgroup_usage_register_event;
4651                 event->unregister_event = mem_cgroup_usage_unregister_event;
4652         } else if (!strcmp(name, "memory.oom_control")) {
4653                 event->register_event = mem_cgroup_oom_register_event;
4654                 event->unregister_event = mem_cgroup_oom_unregister_event;
4655         } else if (!strcmp(name, "memory.pressure_level")) {
4656                 event->register_event = vmpressure_register_event;
4657                 event->unregister_event = vmpressure_unregister_event;
4658         } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
4659                 event->register_event = memsw_cgroup_usage_register_event;
4660                 event->unregister_event = memsw_cgroup_usage_unregister_event;
4661         } else {
4662                 ret = -EINVAL;
4663                 goto out_put_cfile;
4664         }
4665
4666         /*
4667          * Verify @cfile should belong to @css.  Also, remaining events are
4668          * automatically removed on cgroup destruction but the removal is
4669          * asynchronous, so take an extra ref on @css.
4670          */
4671         cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
4672                                                &memory_cgrp_subsys);
4673         ret = -EINVAL;
4674         if (IS_ERR(cfile_css))
4675                 goto out_put_cfile;
4676         if (cfile_css != css) {
4677                 css_put(cfile_css);
4678                 goto out_put_cfile;
4679         }
4680
4681         ret = event->register_event(memcg, event->eventfd, buf);
4682         if (ret)
4683                 goto out_put_css;
4684
4685         vfs_poll(efile.file, &event->pt);
4686
4687         spin_lock(&memcg->event_list_lock);
4688         list_add(&event->list, &memcg->event_list);
4689         spin_unlock(&memcg->event_list_lock);
4690
4691         fdput(cfile);
4692         fdput(efile);
4693
4694         return nbytes;
4695
4696 out_put_css:
4697         css_put(css);
4698 out_put_cfile:
4699         fdput(cfile);
4700 out_put_eventfd:
4701         eventfd_ctx_put(event->eventfd);
4702 out_put_efile:
4703         fdput(efile);
4704 out_kfree:
4705         kfree(event);
4706
4707         return ret;
4708 }
4709
4710 static struct cftype mem_cgroup_legacy_files[] = {
4711         {
4712                 .name = "usage_in_bytes",
4713                 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
4714                 .read_u64 = mem_cgroup_read_u64,
4715         },
4716         {
4717                 .name = "max_usage_in_bytes",
4718                 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
4719                 .write = mem_cgroup_reset,
4720                 .read_u64 = mem_cgroup_read_u64,
4721         },
4722         {
4723                 .name = "limit_in_bytes",
4724                 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
4725                 .write = mem_cgroup_write,
4726                 .read_u64 = mem_cgroup_read_u64,
4727         },
4728         {
4729                 .name = "soft_limit_in_bytes",
4730                 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
4731                 .write = mem_cgroup_write,
4732                 .read_u64 = mem_cgroup_read_u64,
4733         },
4734         {
4735                 .name = "failcnt",
4736                 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
4737                 .write = mem_cgroup_reset,
4738                 .read_u64 = mem_cgroup_read_u64,
4739         },
4740         {
4741                 .name = "stat",
4742                 .seq_show = memcg_stat_show,
4743         },
4744         {
4745                 .name = "force_empty",
4746                 .write = mem_cgroup_force_empty_write,
4747         },
4748         {
4749                 .name = "use_hierarchy",
4750                 .write_u64 = mem_cgroup_hierarchy_write,
4751                 .read_u64 = mem_cgroup_hierarchy_read,
4752         },
4753         {
4754                 .name = "cgroup.event_control",         /* XXX: for compat */
4755                 .write = memcg_write_event_control,
4756                 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
4757         },
4758         {
4759                 .name = "swappiness",
4760                 .read_u64 = mem_cgroup_swappiness_read,
4761                 .write_u64 = mem_cgroup_swappiness_write,
4762         },
4763         {
4764                 .name = "move_charge_at_immigrate",
4765                 .read_u64 = mem_cgroup_move_charge_read,
4766                 .write_u64 = mem_cgroup_move_charge_write,
4767         },
4768         {
4769                 .name = "oom_control",
4770                 .seq_show = mem_cgroup_oom_control_read,
4771                 .write_u64 = mem_cgroup_oom_control_write,
4772                 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
4773         },
4774         {
4775                 .name = "pressure_level",
4776         },
4777 #ifdef CONFIG_NUMA
4778         {
4779                 .name = "numa_stat",
4780                 .seq_show = memcg_numa_stat_show,
4781         },
4782 #endif
4783         {
4784                 .name = "kmem.limit_in_bytes",
4785                 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
4786                 .write = mem_cgroup_write,
4787                 .read_u64 = mem_cgroup_read_u64,
4788         },
4789         {
4790                 .name = "kmem.usage_in_bytes",
4791                 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
4792                 .read_u64 = mem_cgroup_read_u64,
4793         },
4794         {
4795                 .name = "kmem.failcnt",
4796                 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
4797                 .write = mem_cgroup_reset,
4798                 .read_u64 = mem_cgroup_read_u64,
4799         },
4800         {
4801                 .name = "kmem.max_usage_in_bytes",
4802                 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
4803                 .write = mem_cgroup_reset,
4804                 .read_u64 = mem_cgroup_read_u64,
4805         },
4806 #if defined(CONFIG_MEMCG_KMEM) && \
4807         (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
4808         {
4809                 .name = "kmem.slabinfo",
4810                 .seq_start = memcg_slab_start,
4811                 .seq_next = memcg_slab_next,
4812                 .seq_stop = memcg_slab_stop,
4813                 .seq_show = memcg_slab_show,
4814         },
4815 #endif
4816         {
4817                 .name = "kmem.tcp.limit_in_bytes",
4818                 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
4819                 .write = mem_cgroup_write,
4820                 .read_u64 = mem_cgroup_read_u64,
4821         },
4822         {
4823                 .name = "kmem.tcp.usage_in_bytes",
4824                 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
4825                 .read_u64 = mem_cgroup_read_u64,
4826         },
4827         {
4828                 .name = "kmem.tcp.failcnt",
4829                 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
4830                 .write = mem_cgroup_reset,
4831                 .read_u64 = mem_cgroup_read_u64,
4832         },
4833         {
4834                 .name = "kmem.tcp.max_usage_in_bytes",
4835                 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
4836                 .write = mem_cgroup_reset,
4837                 .read_u64 = mem_cgroup_read_u64,
4838         },
4839         { },    /* terminate */
4840 };
4841
4842 /*
4843  * Private memory cgroup IDR
4844  *
4845  * Swap-out records and page cache shadow entries need to store memcg
4846  * references in constrained space, so we maintain an ID space that is
4847  * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
4848  * memory-controlled cgroups to 64k.
4849  *
4850  * However, there usually are many references to the offline CSS after
4851  * the cgroup has been destroyed, such as page cache or reclaimable
4852  * slab objects, that don't need to hang on to the ID. We want to keep
4853  * those dead CSS from occupying IDs, or we might quickly exhaust the
4854  * relatively small ID space and prevent the creation of new cgroups
4855  * even when there are much fewer than 64k cgroups - possibly none.
4856  *
4857  * Maintain a private 16-bit ID space for memcg, and allow the ID to
4858  * be freed and recycled when it's no longer needed, which is usually
4859  * when the CSS is offlined.
4860  *
4861  * The only exception to that are records of swapped out tmpfs/shmem
4862  * pages that need to be attributed to live ancestors on swapin. But
4863  * those references are manageable from userspace.
4864  */
4865
4866 static DEFINE_IDR(mem_cgroup_idr);
4867
4868 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
4869 {
4870         if (memcg->id.id > 0) {
4871                 idr_remove(&mem_cgroup_idr, memcg->id.id);
4872                 memcg->id.id = 0;
4873         }
4874 }
4875
4876 static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
4877                                                   unsigned int n)
4878 {
4879         refcount_add(n, &memcg->id.ref);
4880 }
4881
4882 static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
4883 {
4884         if (refcount_sub_and_test(n, &memcg->id.ref)) {
4885                 mem_cgroup_id_remove(memcg);
4886
4887                 /* Memcg ID pins CSS */
4888                 css_put(&memcg->css);
4889         }
4890 }
4891
4892 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
4893 {
4894         mem_cgroup_id_put_many(memcg, 1);
4895 }
4896
4897 /**
4898  * mem_cgroup_from_id - look up a memcg from a memcg id
4899  * @id: the memcg id to look up
4900  *
4901  * Caller must hold rcu_read_lock().
4902  */
4903 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
4904 {
4905         WARN_ON_ONCE(!rcu_read_lock_held());
4906         return idr_find(&mem_cgroup_idr, id);
4907 }
4908
4909 static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
4910 {
4911         struct mem_cgroup_per_node *pn;
4912         int tmp = node;
4913         /*
4914          * This routine is called against possible nodes.
4915          * But it's BUG to call kmalloc() against offline node.
4916          *
4917          * TODO: this routine can waste much memory for nodes which will
4918          *       never be onlined. It's better to use memory hotplug callback
4919          *       function.
4920          */
4921         if (!node_state(node, N_NORMAL_MEMORY))
4922                 tmp = -1;
4923         pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
4924         if (!pn)
4925                 return 1;
4926
4927         pn->lruvec_stat_local = alloc_percpu(struct lruvec_stat);
4928         if (!pn->lruvec_stat_local) {
4929                 kfree(pn);
4930                 return 1;
4931         }
4932
4933         pn->lruvec_stat_cpu = alloc_percpu(struct lruvec_stat);
4934         if (!pn->lruvec_stat_cpu) {
4935                 free_percpu(pn->lruvec_stat_local);
4936                 kfree(pn);
4937                 return 1;
4938         }
4939
4940         lruvec_init(&pn->lruvec);
4941         pn->usage_in_excess = 0;
4942         pn->on_tree = false;
4943         pn->memcg = memcg;
4944
4945         memcg->nodeinfo[node] = pn;
4946         return 0;
4947 }
4948
4949 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
4950 {
4951         struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
4952
4953         if (!pn)
4954                 return;
4955
4956         free_percpu(pn->lruvec_stat_cpu);
4957         free_percpu(pn->lruvec_stat_local);
4958         kfree(pn);
4959 }
4960
4961 static void __mem_cgroup_free(struct mem_cgroup *memcg)
4962 {
4963         int node;
4964
4965         for_each_node(node)
4966                 free_mem_cgroup_per_node_info(memcg, node);
4967         free_percpu(memcg->vmstats_percpu);
4968         free_percpu(memcg->vmstats_local);
4969         kfree(memcg);
4970 }
4971
4972 static void mem_cgroup_free(struct mem_cgroup *memcg)
4973 {
4974         memcg_wb_domain_exit(memcg);
4975         /*
4976          * Flush percpu vmstats and vmevents to guarantee the value correctness
4977          * on parent's and all ancestor levels.
4978          */
4979         memcg_flush_percpu_vmstats(memcg);
4980         memcg_flush_percpu_vmevents(memcg);
4981         __mem_cgroup_free(memcg);
4982 }
4983
4984 static struct mem_cgroup *mem_cgroup_alloc(void)
4985 {
4986         struct mem_cgroup *memcg;
4987         unsigned int size;
4988         int node;
4989         int __maybe_unused i;
4990         long error = -ENOMEM;
4991
4992         size = sizeof(struct mem_cgroup);
4993         size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
4994
4995         memcg = kzalloc(size, GFP_KERNEL);
4996         if (!memcg)
4997                 return ERR_PTR(error);
4998
4999         memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5000                                  1, MEM_CGROUP_ID_MAX,
5001                                  GFP_KERNEL);
5002         if (memcg->id.id < 0) {
5003                 error = memcg->id.id;
5004                 goto fail;
5005         }
5006
5007         memcg->vmstats_local = alloc_percpu(struct memcg_vmstats_percpu);
5008         if (!memcg->vmstats_local)
5009                 goto fail;
5010
5011         memcg->vmstats_percpu = alloc_percpu(struct memcg_vmstats_percpu);
5012         if (!memcg->vmstats_percpu)
5013                 goto fail;
5014
5015         for_each_node(node)
5016                 if (alloc_mem_cgroup_per_node_info(memcg, node))
5017                         goto fail;
5018
5019         if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5020                 goto fail;
5021
5022         INIT_WORK(&memcg->high_work, high_work_func);
5023         INIT_LIST_HEAD(&memcg->oom_notify);
5024         mutex_init(&memcg->thresholds_lock);
5025         spin_lock_init(&memcg->move_lock);
5026         vmpressure_init(&memcg->vmpressure);
5027         INIT_LIST_HEAD(&memcg->event_list);
5028         spin_lock_init(&memcg->event_list_lock);
5029         memcg->socket_pressure = jiffies;
5030 #ifdef CONFIG_MEMCG_KMEM
5031         memcg->kmemcg_id = -1;
5032 #endif
5033 #ifdef CONFIG_CGROUP_WRITEBACK
5034         INIT_LIST_HEAD(&memcg->cgwb_list);
5035         for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5036                 memcg->cgwb_frn[i].done =
5037                         __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
5038 #endif
5039 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5040         spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5041         INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5042         memcg->deferred_split_queue.split_queue_len = 0;
5043 #endif
5044         idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
5045         return memcg;
5046 fail:
5047         mem_cgroup_id_remove(memcg);
5048         __mem_cgroup_free(memcg);
5049         return ERR_PTR(error);
5050 }
5051
5052 static struct cgroup_subsys_state * __ref
5053 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
5054 {
5055         struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5056         struct mem_cgroup *memcg;
5057         long error = -ENOMEM;
5058
5059         memcg = mem_cgroup_alloc();
5060         if (IS_ERR(memcg))
5061                 return ERR_CAST(memcg);
5062
5063         page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5064         memcg->soft_limit = PAGE_COUNTER_MAX;
5065         page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5066         if (parent) {
5067                 memcg->swappiness = mem_cgroup_swappiness(parent);
5068                 memcg->oom_kill_disable = parent->oom_kill_disable;
5069         }
5070         if (parent && parent->use_hierarchy) {
5071                 memcg->use_hierarchy = true;
5072                 page_counter_init(&memcg->memory, &parent->memory);
5073                 page_counter_init(&memcg->swap, &parent->swap);
5074                 page_counter_init(&memcg->memsw, &parent->memsw);
5075                 page_counter_init(&memcg->kmem, &parent->kmem);
5076                 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
5077         } else {
5078                 page_counter_init(&memcg->memory, NULL);
5079                 page_counter_init(&memcg->swap, NULL);
5080                 page_counter_init(&memcg->memsw, NULL);
5081                 page_counter_init(&memcg->kmem, NULL);
5082                 page_counter_init(&memcg->tcpmem, NULL);
5083                 /*
5084                  * Deeper hierachy with use_hierarchy == false doesn't make
5085                  * much sense so let cgroup subsystem know about this
5086                  * unfortunate state in our controller.
5087                  */
5088                 if (parent != root_mem_cgroup)
5089                         memory_cgrp_subsys.broken_hierarchy = true;
5090         }
5091
5092         /* The following stuff does not apply to the root */
5093         if (!parent) {
5094 #ifdef CONFIG_MEMCG_KMEM
5095                 INIT_LIST_HEAD(&memcg->kmem_caches);
5096 #endif
5097                 root_mem_cgroup = memcg;
5098                 return &memcg->css;
5099         }
5100
5101         error = memcg_online_kmem(memcg);
5102         if (error)
5103                 goto fail;
5104
5105         if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5106                 static_branch_inc(&memcg_sockets_enabled_key);
5107
5108         return &memcg->css;
5109 fail:
5110         mem_cgroup_id_remove(memcg);
5111         mem_cgroup_free(memcg);
5112         return ERR_PTR(error);
5113 }
5114
5115 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
5116 {
5117         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5118
5119         /*
5120          * A memcg must be visible for memcg_expand_shrinker_maps()
5121          * by the time the maps are allocated. So, we allocate maps
5122          * here, when for_each_mem_cgroup() can't skip it.
5123          */
5124         if (memcg_alloc_shrinker_maps(memcg)) {
5125                 mem_cgroup_id_remove(memcg);
5126                 return -ENOMEM;
5127         }
5128
5129         /* Online state pins memcg ID, memcg ID pins CSS */
5130         refcount_set(&memcg->id.ref, 1);
5131         css_get(css);
5132         return 0;
5133 }
5134
5135 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
5136 {
5137         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5138         struct mem_cgroup_event *event, *tmp;
5139
5140         /*
5141          * Unregister events and notify userspace.
5142          * Notify userspace about cgroup removing only after rmdir of cgroup
5143          * directory to avoid race between userspace and kernelspace.
5144          */
5145         spin_lock(&memcg->event_list_lock);
5146         list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
5147                 list_del_init(&event->list);
5148                 schedule_work(&event->remove);
5149         }
5150         spin_unlock(&memcg->event_list_lock);
5151
5152         page_counter_set_min(&memcg->memory, 0);
5153         page_counter_set_low(&memcg->memory, 0);
5154
5155         memcg_offline_kmem(memcg);
5156         wb_memcg_offline(memcg);
5157
5158         drain_all_stock(memcg);
5159
5160         mem_cgroup_id_put(memcg);
5161 }
5162
5163 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5164 {
5165         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5166
5167         invalidate_reclaim_iterators(memcg);
5168 }
5169
5170 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
5171 {
5172         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5173         int __maybe_unused i;
5174
5175 #ifdef CONFIG_CGROUP_WRITEBACK
5176         for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5177                 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5178 #endif
5179         if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
5180                 static_branch_dec(&memcg_sockets_enabled_key);
5181
5182         if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
5183                 static_branch_dec(&memcg_sockets_enabled_key);
5184
5185         vmpressure_cleanup(&memcg->vmpressure);
5186         cancel_work_sync(&memcg->high_work);
5187         mem_cgroup_remove_from_trees(memcg);
5188         memcg_free_shrinker_maps(memcg);
5189         memcg_free_kmem(memcg);
5190         mem_cgroup_free(memcg);
5191 }
5192
5193 /**
5194  * mem_cgroup_css_reset - reset the states of a mem_cgroup
5195  * @css: the target css
5196  *
5197  * Reset the states of the mem_cgroup associated with @css.  This is
5198  * invoked when the userland requests disabling on the default hierarchy
5199  * but the memcg is pinned through dependency.  The memcg should stop
5200  * applying policies and should revert to the vanilla state as it may be
5201  * made visible again.
5202  *
5203  * The current implementation only resets the essential configurations.
5204  * This needs to be expanded to cover all the visible parts.
5205  */
5206 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5207 {
5208         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5209
5210         page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5211         page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5212         page_counter_set_max(&memcg->memsw, PAGE_COUNTER_MAX);
5213         page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5214         page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
5215         page_counter_set_min(&memcg->memory, 0);
5216         page_counter_set_low(&memcg->memory, 0);
5217         page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
5218         memcg->soft_limit = PAGE_COUNTER_MAX;
5219         page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
5220         memcg_wb_domain_size_changed(memcg);
5221 }
5222
5223 #ifdef CONFIG_MMU
5224 /* Handlers for move charge at task migration. */
5225 static int mem_cgroup_do_precharge(unsigned long count)
5226 {
5227         int ret;
5228
5229         /* Try a single bulk charge without reclaim first, kswapd may wake */
5230         ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
5231         if (!ret) {
5232                 mc.precharge += count;
5233                 return ret;
5234         }
5235
5236         /* Try charges one by one with reclaim, but do not retry */
5237         while (count--) {
5238                 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
5239                 if (ret)
5240                         return ret;
5241                 mc.precharge++;
5242                 cond_resched();
5243         }
5244         return 0;
5245 }
5246
5247 union mc_target {
5248         struct page     *page;
5249         swp_entry_t     ent;
5250 };
5251
5252 enum mc_target_type {
5253         MC_TARGET_NONE = 0,
5254         MC_TARGET_PAGE,
5255         MC_TARGET_SWAP,
5256         MC_TARGET_DEVICE,
5257 };
5258
5259 static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5260                                                 unsigned long addr, pte_t ptent)
5261 {
5262         struct page *page = vm_normal_page(vma, addr, ptent);
5263
5264         if (!page || !page_mapped(page))
5265                 return NULL;
5266         if (PageAnon(page)) {
5267                 if (!(mc.flags & MOVE_ANON))
5268                         return NULL;
5269         } else {
5270                 if (!(mc.flags & MOVE_FILE))
5271                         return NULL;
5272         }
5273         if (!get_page_unless_zero(page))
5274                 return NULL;
5275
5276         return page;
5277 }
5278
5279 #if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
5280 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5281                         pte_t ptent, swp_entry_t *entry)
5282 {
5283         struct page *page = NULL;
5284         swp_entry_t ent = pte_to_swp_entry(ptent);
5285
5286         if (!(mc.flags & MOVE_ANON) || non_swap_entry(ent))
5287                 return NULL;
5288
5289         /*
5290          * Handle MEMORY_DEVICE_PRIVATE which are ZONE_DEVICE page belonging to
5291          * a device and because they are not accessible by CPU they are store
5292          * as special swap entry in the CPU page table.
5293          */
5294         if (is_device_private_entry(ent)) {
5295                 page = device_private_entry_to_page(ent);
5296                 /*
5297                  * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have
5298                  * a refcount of 1 when free (unlike normal page)
5299                  */
5300                 if (!page_ref_add_unless(page, 1, 1))
5301                         return NULL;
5302                 return page;
5303         }
5304
5305         /*
5306          * Because lookup_swap_cache() updates some statistics counter,
5307          * we call find_get_page() with swapper_space directly.
5308          */
5309         page = find_get_page(swap_address_space(ent), swp_offset(ent));
5310         entry->val = ent.val;
5311
5312         return page;
5313 }
5314 #else
5315 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
5316                         pte_t ptent, swp_entry_t *entry)
5317 {
5318         return NULL;
5319 }
5320 #endif
5321
5322 static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5323                         unsigned long addr, pte_t ptent, swp_entry_t *entry)
5324 {
5325         struct page *page = NULL;
5326         struct address_space *mapping;
5327         pgoff_t pgoff;
5328
5329         if (!vma->vm_file) /* anonymous vma */
5330                 return NULL;
5331         if (!(mc.flags & MOVE_FILE))
5332                 return NULL;
5333
5334         mapping = vma->vm_file->f_mapping;
5335         pgoff = linear_page_index(vma, addr);
5336
5337         /* page is moved even if it's not RSS of this task(page-faulted). */
5338 #ifdef CONFIG_SWAP
5339         /* shmem/tmpfs may report page out on swap: account for that too. */
5340         if (shmem_mapping(mapping)) {
5341                 page = find_get_entry(mapping, pgoff);
5342                 if (xa_is_value(page)) {
5343                         swp_entry_t swp = radix_to_swp_entry(page);
5344                         *entry = swp;
5345                         page = find_get_page(swap_address_space(swp),
5346                                              swp_offset(swp));
5347                 }
5348         } else
5349                 page = find_get_page(mapping, pgoff);
5350 #else
5351         page = find_get_page(mapping, pgoff);
5352 #endif
5353         return page;
5354 }
5355
5356 /**
5357  * mem_cgroup_move_account - move account of the page
5358  * @page: the page
5359  * @compound: charge the page as compound or small page
5360  * @from: mem_cgroup which the page is moved from.
5361  * @to: mem_cgroup which the page is moved to. @from != @to.
5362  *
5363  * The caller must make sure the page is not on LRU (isolate_page() is useful.)
5364  *
5365  * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5366  * from old cgroup.
5367  */
5368 static int mem_cgroup_move_account(struct page *page,
5369                                    bool compound,
5370                                    struct mem_cgroup *from,
5371                                    struct mem_cgroup *to)
5372 {
5373         struct lruvec *from_vec, *to_vec;
5374         struct pglist_data *pgdat;
5375         unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
5376         int ret;
5377
5378         VM_BUG_ON(from == to);
5379         VM_BUG_ON_PAGE(PageLRU(page), page);
5380         VM_BUG_ON(compound && !PageTransHuge(page));
5381
5382         /*
5383          * Prevent mem_cgroup_migrate() from looking at
5384          * page->mem_cgroup of its source page while we change it.
5385          */
5386         ret = -EBUSY;
5387         if (!trylock_page(page))
5388                 goto out;
5389
5390         ret = -EINVAL;
5391         if (page->mem_cgroup != from)
5392                 goto out_unlock;
5393
5394         pgdat = page_pgdat(page);
5395         from_vec = mem_cgroup_lruvec(from, pgdat);
5396         to_vec = mem_cgroup_lruvec(to, pgdat);
5397
5398         lock_page_memcg(page);
5399
5400         if (PageAnon(page)) {
5401                 if (page_mapped(page)) {
5402                         __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5403                         __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
5404                         if (PageTransHuge(page)) {
5405                                 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5406                                                    -nr_pages);
5407                                 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5408                                                    nr_pages);
5409                         }
5410
5411                 }
5412         } else {
5413                 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5414                 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5415
5416                 if (PageSwapBacked(page)) {
5417                         __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5418                         __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5419                 }
5420
5421                 if (page_mapped(page)) {
5422                         __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5423                         __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5424                 }
5425
5426                 if (PageDirty(page)) {
5427                         struct address_space *mapping = page_mapping(page);
5428
5429                         if (mapping_cap_account_dirty(mapping)) {
5430                                 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5431                                                    -nr_pages);
5432                                 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5433                                                    nr_pages);
5434                         }
5435                 }
5436         }
5437
5438         if (PageWriteback(page)) {
5439                 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5440                 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
5441         }
5442
5443         /*
5444          * All state has been migrated, let's switch to the new memcg.
5445          *
5446          * It is safe to change page->mem_cgroup here because the page
5447          * is referenced, charged, isolated, and locked: we can't race
5448          * with (un)charging, migration, LRU putback, or anything else
5449          * that would rely on a stable page->mem_cgroup.
5450          *
5451          * Note that lock_page_memcg is a memcg lock, not a page lock,
5452          * to save space. As soon as we switch page->mem_cgroup to a
5453          * new memcg that isn't locked, the above state can change
5454          * concurrently again. Make sure we're truly done with it.
5455          */
5456         smp_mb();
5457
5458         page->mem_cgroup = to;  /* caller should have done css_get */
5459
5460         __unlock_page_memcg(from);
5461
5462         ret = 0;
5463
5464         local_irq_disable();
5465         mem_cgroup_charge_statistics(to, page, nr_pages);
5466         memcg_check_events(to, page);
5467         mem_cgroup_charge_statistics(from, page, -nr_pages);
5468         memcg_check_events(from, page);
5469         local_irq_enable();
5470 out_unlock:
5471         unlock_page(page);
5472 out:
5473         return ret;
5474 }
5475
5476 /**
5477  * get_mctgt_type - get target type of moving charge
5478  * @vma: the vma the pte to be checked belongs
5479  * @addr: the address corresponding to the pte to be checked
5480  * @ptent: the pte to be checked
5481  * @target: the pointer the target page or swap ent will be stored(can be NULL)
5482  *
5483  * Returns
5484  *   0(MC_TARGET_NONE): if the pte is not a target for move charge.
5485  *   1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5486  *     move charge. if @target is not NULL, the page is stored in target->page
5487  *     with extra refcnt got(Callers should handle it).
5488  *   2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5489  *     target for charge migration. if @target is not NULL, the entry is stored
5490  *     in target->ent.
5491  *   3(MC_TARGET_DEVICE): like MC_TARGET_PAGE  but page is MEMORY_DEVICE_PRIVATE
5492  *     (so ZONE_DEVICE page and thus not on the lru).
5493  *     For now we such page is charge like a regular page would be as for all
5494  *     intent and purposes it is just special memory taking the place of a
5495  *     regular page.
5496  *
5497  *     See Documentations/vm/hmm.txt and include/linux/hmm.h
5498  *
5499  * Called with pte lock held.
5500  */
5501
5502 static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
5503                 unsigned long addr, pte_t ptent, union mc_target *target)
5504 {
5505         struct page *page = NULL;
5506         enum mc_target_type ret = MC_TARGET_NONE;
5507         swp_entry_t ent = { .val = 0 };
5508
5509         if (pte_present(ptent))
5510                 page = mc_handle_present_pte(vma, addr, ptent);
5511         else if (is_swap_pte(ptent))
5512                 page = mc_handle_swap_pte(vma, ptent, &ent);
5513         else if (pte_none(ptent))
5514                 page = mc_handle_file_pte(vma, addr, ptent, &ent);
5515
5516         if (!page && !ent.val)
5517                 return ret;
5518         if (page) {
5519                 /*
5520                  * Do only loose check w/o serialization.
5521                  * mem_cgroup_move_account() checks the page is valid or
5522                  * not under LRU exclusion.
5523                  */
5524                 if (page->mem_cgroup == mc.from) {
5525                         ret = MC_TARGET_PAGE;
5526                         if (is_device_private_page(page))
5527                                 ret = MC_TARGET_DEVICE;
5528                         if (target)
5529                                 target->page = page;
5530                 }
5531                 if (!ret || !target)
5532                         put_page(page);
5533         }
5534         /*
5535          * There is a swap entry and a page doesn't exist or isn't charged.
5536          * But we cannot move a tail-page in a THP.
5537          */
5538         if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
5539             mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
5540                 ret = MC_TARGET_SWAP;
5541                 if (target)
5542                         target->ent = ent;
5543         }
5544         return ret;
5545 }
5546
5547 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5548 /*
5549  * We don't consider PMD mapped swapping or file mapped pages because THP does
5550  * not support them for now.
5551  * Caller should make sure that pmd_trans_huge(pmd) is true.
5552  */
5553 static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5554                 unsigned long addr, pmd_t pmd, union mc_target *target)
5555 {
5556         struct page *page = NULL;
5557         enum mc_target_type ret = MC_TARGET_NONE;
5558
5559         if (unlikely(is_swap_pmd(pmd))) {
5560                 VM_BUG_ON(thp_migration_supported() &&
5561                                   !is_pmd_migration_entry(pmd));
5562                 return ret;
5563         }
5564         page = pmd_page(pmd);
5565         VM_BUG_ON_PAGE(!page || !PageHead(page), page);
5566         if (!(mc.flags & MOVE_ANON))
5567                 return ret;
5568         if (page->mem_cgroup == mc.from) {
5569                 ret = MC_TARGET_PAGE;
5570                 if (target) {
5571                         get_page(page);
5572                         target->page = page;
5573                 }
5574         }
5575         return ret;
5576 }
5577 #else
5578 static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5579                 unsigned long addr, pmd_t pmd, union mc_target *target)
5580 {
5581         return MC_TARGET_NONE;
5582 }
5583 #endif
5584
5585 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5586                                         unsigned long addr, unsigned long end,
5587                                         struct mm_walk *walk)
5588 {
5589         struct vm_area_struct *vma = walk->vma;
5590         pte_t *pte;
5591         spinlock_t *ptl;
5592
5593         ptl = pmd_trans_huge_lock(pmd, vma);
5594         if (ptl) {
5595                 /*
5596                  * Note their can not be MC_TARGET_DEVICE for now as we do not
5597                  * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5598                  * this might change.
5599                  */
5600                 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5601                         mc.precharge += HPAGE_PMD_NR;
5602                 spin_unlock(ptl);
5603                 return 0;
5604         }
5605
5606         if (pmd_trans_unstable(pmd))
5607                 return 0;
5608         pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5609         for (; addr != end; pte++, addr += PAGE_SIZE)
5610                 if (get_mctgt_type(vma, addr, *pte, NULL))
5611                         mc.precharge++; /* increment precharge temporarily */
5612         pte_unmap_unlock(pte - 1, ptl);
5613         cond_resched();
5614
5615         return 0;
5616 }
5617
5618 static const struct mm_walk_ops precharge_walk_ops = {
5619         .pmd_entry      = mem_cgroup_count_precharge_pte_range,
5620 };
5621
5622 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5623 {
5624         unsigned long precharge;
5625
5626         mmap_read_lock(mm);
5627         walk_page_range(mm, 0, mm->highest_vm_end, &precharge_walk_ops, NULL);
5628         mmap_read_unlock(mm);
5629
5630         precharge = mc.precharge;
5631         mc.precharge = 0;
5632
5633         return precharge;
5634 }
5635
5636 static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5637 {
5638         unsigned long precharge = mem_cgroup_count_precharge(mm);
5639
5640         VM_BUG_ON(mc.moving_task);
5641         mc.moving_task = current;
5642         return mem_cgroup_do_precharge(precharge);
5643 }
5644
5645 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5646 static void __mem_cgroup_clear_mc(void)
5647 {
5648         struct mem_cgroup *from = mc.from;
5649         struct mem_cgroup *to = mc.to;
5650
5651         /* we must uncharge all the leftover precharges from mc.to */
5652         if (mc.precharge) {
5653                 cancel_charge(mc.to, mc.precharge);
5654                 mc.precharge = 0;
5655         }
5656         /*
5657          * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5658          * we must uncharge here.
5659          */
5660         if (mc.moved_charge) {
5661                 cancel_charge(mc.from, mc.moved_charge);
5662                 mc.moved_charge = 0;
5663         }
5664         /* we must fixup refcnts and charges */
5665         if (mc.moved_swap) {
5666                 /* uncharge swap account from the old cgroup */
5667                 if (!mem_cgroup_is_root(mc.from))
5668                         page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
5669
5670                 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
5671
5672                 /*
5673                  * we charged both to->memory and to->memsw, so we
5674                  * should uncharge to->memory.
5675                  */
5676                 if (!mem_cgroup_is_root(mc.to))
5677                         page_counter_uncharge(&mc.to->memory, mc.moved_swap);
5678
5679                 css_put_many(&mc.to->css, mc.moved_swap);
5680
5681                 mc.moved_swap = 0;
5682         }
5683         memcg_oom_recover(from);
5684         memcg_oom_recover(to);
5685         wake_up_all(&mc.waitq);
5686 }
5687
5688 static void mem_cgroup_clear_mc(void)
5689 {
5690         struct mm_struct *mm = mc.mm;
5691
5692         /*
5693          * we must clear moving_task before waking up waiters at the end of
5694          * task migration.
5695          */
5696         mc.moving_task = NULL;
5697         __mem_cgroup_clear_mc();
5698         spin_lock(&mc.lock);
5699         mc.from = NULL;
5700         mc.to = NULL;
5701         mc.mm = NULL;
5702         spin_unlock(&mc.lock);
5703
5704         mmput(mm);
5705 }
5706
5707 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5708 {
5709         struct cgroup_subsys_state *css;
5710         struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
5711         struct mem_cgroup *from;
5712         struct task_struct *leader, *p;
5713         struct mm_struct *mm;
5714         unsigned long move_flags;
5715         int ret = 0;
5716
5717         /* charge immigration isn't supported on the default hierarchy */
5718         if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
5719                 return 0;
5720
5721         /*
5722          * Multi-process migrations only happen on the default hierarchy
5723          * where charge immigration is not used.  Perform charge
5724          * immigration if @tset contains a leader and whine if there are
5725          * multiple.
5726          */
5727         p = NULL;
5728         cgroup_taskset_for_each_leader(leader, css, tset) {
5729                 WARN_ON_ONCE(p);
5730                 p = leader;
5731                 memcg = mem_cgroup_from_css(css);
5732         }
5733         if (!p)
5734                 return 0;
5735
5736         /*
5737          * We are now commited to this value whatever it is. Changes in this
5738          * tunable will only affect upcoming migrations, not the current one.
5739          * So we need to save it, and keep it going.
5740          */
5741         move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
5742         if (!move_flags)
5743                 return 0;
5744
5745         from = mem_cgroup_from_task(p);
5746
5747         VM_BUG_ON(from == memcg);
5748
5749         mm = get_task_mm(p);
5750         if (!mm)
5751                 return 0;
5752         /* We move charges only when we move a owner of the mm */
5753         if (mm->owner == p) {
5754                 VM_BUG_ON(mc.from);
5755                 VM_BUG_ON(mc.to);
5756                 VM_BUG_ON(mc.precharge);
5757                 VM_BUG_ON(mc.moved_charge);
5758                 VM_BUG_ON(mc.moved_swap);
5759
5760                 spin_lock(&mc.lock);
5761                 mc.mm = mm;
5762                 mc.from = from;
5763                 mc.to = memcg;
5764                 mc.flags = move_flags;
5765                 spin_unlock(&mc.lock);
5766                 /* We set mc.moving_task later */
5767
5768                 ret = mem_cgroup_precharge_mc(mm);
5769                 if (ret)
5770                         mem_cgroup_clear_mc();
5771         } else {
5772                 mmput(mm);
5773         }
5774         return ret;
5775 }
5776
5777 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
5778 {
5779         if (mc.to)
5780                 mem_cgroup_clear_mc();
5781 }
5782
5783 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
5784                                 unsigned long addr, unsigned long end,
5785                                 struct mm_walk *walk)
5786 {
5787         int ret = 0;
5788         struct vm_area_struct *vma = walk->vma;
5789         pte_t *pte;
5790         spinlock_t *ptl;
5791         enum mc_target_type target_type;
5792         union mc_target target;
5793         struct page *page;
5794
5795         ptl = pmd_trans_huge_lock(pmd, vma);
5796         if (ptl) {
5797                 if (mc.precharge < HPAGE_PMD_NR) {
5798                         spin_unlock(ptl);
5799                         return 0;
5800                 }
5801                 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
5802                 if (target_type == MC_TARGET_PAGE) {
5803                         page = target.page;
5804                         if (!isolate_lru_page(page)) {
5805                                 if (!mem_cgroup_move_account(page, true,
5806                                                              mc.from, mc.to)) {
5807                                         mc.precharge -= HPAGE_PMD_NR;
5808                                         mc.moved_charge += HPAGE_PMD_NR;
5809                                 }
5810                                 putback_lru_page(page);
5811                         }
5812                         put_page(page);
5813                 } else if (target_type == MC_TARGET_DEVICE) {
5814                         page = target.page;
5815                         if (!mem_cgroup_move_account(page, true,
5816                                                      mc.from, mc.to)) {
5817                                 mc.precharge -= HPAGE_PMD_NR;
5818                                 mc.moved_charge += HPAGE_PMD_NR;
5819                         }
5820                         put_page(page);
5821                 }
5822                 spin_unlock(ptl);
5823                 return 0;
5824         }
5825
5826         if (pmd_trans_unstable(pmd))
5827                 return 0;
5828 retry:
5829         pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5830         for (; addr != end; addr += PAGE_SIZE) {
5831                 pte_t ptent = *(pte++);
5832                 bool device = false;
5833                 swp_entry_t ent;
5834
5835                 if (!mc.precharge)
5836                         break;
5837
5838                 switch (get_mctgt_type(vma, addr, ptent, &target)) {
5839                 case MC_TARGET_DEVICE:
5840                         device = true;
5841                         fallthrough;
5842                 case MC_TARGET_PAGE:
5843                         page = target.page;
5844                         /*
5845                          * We can have a part of the split pmd here. Moving it
5846                          * can be done but it would be too convoluted so simply
5847                          * ignore such a partial THP and keep it in original
5848                          * memcg. There should be somebody mapping the head.
5849                          */
5850                         if (PageTransCompound(page))
5851                                 goto put;
5852                         if (!device && isolate_lru_page(page))
5853                                 goto put;
5854                         if (!mem_cgroup_move_account(page, false,
5855                                                 mc.from, mc.to)) {
5856                                 mc.precharge--;
5857                                 /* we uncharge from mc.from later. */
5858                                 mc.moved_charge++;
5859                         }
5860                         if (!device)
5861                                 putback_lru_page(page);
5862 put:                    /* get_mctgt_type() gets the page */
5863                         put_page(page);
5864                         break;
5865                 case MC_TARGET_SWAP:
5866                         ent = target.ent;
5867                         if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
5868                                 mc.precharge--;
5869                                 mem_cgroup_id_get_many(mc.to, 1);
5870                                 /* we fixup other refcnts and charges later. */
5871                                 mc.moved_swap++;
5872                         }
5873                         break;
5874                 default:
5875                         break;
5876                 }
5877         }
5878         pte_unmap_unlock(pte - 1, ptl);
5879         cond_resched();
5880
5881         if (addr != end) {
5882                 /*
5883                  * We have consumed all precharges we got in can_attach().
5884                  * We try charge one by one, but don't do any additional
5885                  * charges to mc.to if we have failed in charge once in attach()
5886                  * phase.
5887                  */
5888                 ret = mem_cgroup_do_precharge(1);
5889                 if (!ret)
5890                         goto retry;
5891         }
5892
5893         return ret;
5894 }
5895
5896 static const struct mm_walk_ops charge_walk_ops = {
5897         .pmd_entry      = mem_cgroup_move_charge_pte_range,
5898 };
5899
5900 static void mem_cgroup_move_charge(void)
5901 {
5902         lru_add_drain_all();
5903         /*
5904          * Signal lock_page_memcg() to take the memcg's move_lock
5905          * while we're moving its pages to another memcg. Then wait
5906          * for already started RCU-only updates to finish.
5907          */
5908         atomic_inc(&mc.from->moving_account);
5909         synchronize_rcu();
5910 retry:
5911         if (unlikely(!mmap_read_trylock(mc.mm))) {
5912                 /*
5913                  * Someone who are holding the mmap_lock might be waiting in
5914                  * waitq. So we cancel all extra charges, wake up all waiters,
5915                  * and retry. Because we cancel precharges, we might not be able
5916                  * to move enough charges, but moving charge is a best-effort
5917                  * feature anyway, so it wouldn't be a big problem.
5918                  */
5919                 __mem_cgroup_clear_mc();
5920                 cond_resched();
5921                 goto retry;
5922         }
5923         /*
5924          * When we have consumed all precharges and failed in doing
5925          * additional charge, the page walk just aborts.
5926          */
5927         walk_page_range(mc.mm, 0, mc.mm->highest_vm_end, &charge_walk_ops,
5928                         NULL);
5929
5930         mmap_read_unlock(mc.mm);
5931         atomic_dec(&mc.from->moving_account);
5932 }
5933
5934 static void mem_cgroup_move_task(void)
5935 {
5936         if (mc.to) {
5937                 mem_cgroup_move_charge();
5938                 mem_cgroup_clear_mc();
5939         }
5940 }
5941 #else   /* !CONFIG_MMU */
5942 static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
5943 {
5944         return 0;
5945 }
5946 static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
5947 {
5948 }
5949 static void mem_cgroup_move_task(void)
5950 {
5951 }
5952 #endif
5953
5954 /*
5955  * Cgroup retains root cgroups across [un]mount cycles making it necessary
5956  * to verify whether we're attached to the default hierarchy on each mount
5957  * attempt.
5958  */
5959 static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
5960 {
5961         /*
5962          * use_hierarchy is forced on the default hierarchy.  cgroup core
5963          * guarantees that @root doesn't have any children, so turning it
5964          * on for the root memcg is enough.
5965          */
5966         if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
5967                 root_mem_cgroup->use_hierarchy = true;
5968         else
5969                 root_mem_cgroup->use_hierarchy = false;
5970 }
5971
5972 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
5973 {
5974         if (value == PAGE_COUNTER_MAX)
5975                 seq_puts(m, "max\n");
5976         else
5977                 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
5978
5979         return 0;
5980 }
5981
5982 static u64 memory_current_read(struct cgroup_subsys_state *css,
5983                                struct cftype *cft)
5984 {
5985         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5986
5987         return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
5988 }
5989
5990 static int memory_min_show(struct seq_file *m, void *v)
5991 {
5992         return seq_puts_memcg_tunable(m,
5993                 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
5994 }
5995
5996 static ssize_t memory_min_write(struct kernfs_open_file *of,
5997                                 char *buf, size_t nbytes, loff_t off)
5998 {
5999         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6000         unsigned long min;
6001         int err;
6002
6003         buf = strstrip(buf);
6004         err = page_counter_memparse(buf, "max", &min);
6005         if (err)
6006                 return err;
6007
6008         page_counter_set_min(&memcg->memory, min);
6009
6010         return nbytes;
6011 }
6012
6013 static int memory_low_show(struct seq_file *m, void *v)
6014 {
6015         return seq_puts_memcg_tunable(m,
6016                 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
6017 }
6018
6019 static ssize_t memory_low_write(struct kernfs_open_file *of,
6020                                 char *buf, size_t nbytes, loff_t off)
6021 {
6022         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6023         unsigned long low;
6024         int err;
6025
6026         buf = strstrip(buf);
6027         err = page_counter_memparse(buf, "max", &low);
6028         if (err)
6029                 return err;
6030
6031         page_counter_set_low(&memcg->memory, low);
6032
6033         return nbytes;
6034 }
6035
6036 static int memory_high_show(struct seq_file *m, void *v)
6037 {
6038         return seq_puts_memcg_tunable(m,
6039                 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
6040 }
6041
6042 static ssize_t memory_high_write(struct kernfs_open_file *of,
6043                                  char *buf, size_t nbytes, loff_t off)
6044 {
6045         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6046         unsigned int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
6047         bool drained = false;
6048         unsigned long high;
6049         int err;
6050
6051         buf = strstrip(buf);
6052         err = page_counter_memparse(buf, "max", &high);
6053         if (err)
6054                 return err;
6055
6056         page_counter_set_high(&memcg->memory, high);
6057
6058         for (;;) {
6059                 unsigned long nr_pages = page_counter_read(&memcg->memory);
6060                 unsigned long reclaimed;
6061
6062                 if (nr_pages <= high)
6063                         break;
6064
6065                 if (signal_pending(current))
6066                         break;
6067
6068                 if (!drained) {
6069                         drain_all_stock(memcg);
6070                         drained = true;
6071                         continue;
6072                 }
6073
6074                 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6075                                                          GFP_KERNEL, true);
6076
6077                 if (!reclaimed && !nr_retries--)
6078                         break;
6079         }
6080
6081         return nbytes;
6082 }
6083
6084 static int memory_max_show(struct seq_file *m, void *v)
6085 {
6086         return seq_puts_memcg_tunable(m,
6087                 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
6088 }
6089
6090 static ssize_t memory_max_write(struct kernfs_open_file *of,
6091                                 char *buf, size_t nbytes, loff_t off)
6092 {
6093         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6094         unsigned int nr_reclaims = MEM_CGROUP_RECLAIM_RETRIES;
6095         bool drained = false;
6096         unsigned long max;
6097         int err;
6098
6099         buf = strstrip(buf);
6100         err = page_counter_memparse(buf, "max", &max);
6101         if (err)
6102                 return err;
6103
6104         xchg(&memcg->memory.max, max);
6105
6106         for (;;) {
6107                 unsigned long nr_pages = page_counter_read(&memcg->memory);
6108
6109                 if (nr_pages <= max)
6110                         break;
6111
6112                 if (signal_pending(current))
6113                         break;
6114
6115                 if (!drained) {
6116                         drain_all_stock(memcg);
6117                         drained = true;
6118                         continue;
6119                 }
6120
6121                 if (nr_reclaims) {
6122                         if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6123                                                           GFP_KERNEL, true))
6124                                 nr_reclaims--;
6125                         continue;
6126                 }
6127
6128                 memcg_memory_event(memcg, MEMCG_OOM);
6129                 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6130                         break;
6131         }
6132
6133         memcg_wb_domain_size_changed(memcg);
6134         return nbytes;
6135 }
6136
6137 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6138 {
6139         seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6140         seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6141         seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6142         seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6143         seq_printf(m, "oom_kill %lu\n",
6144                    atomic_long_read(&events[MEMCG_OOM_KILL]));
6145 }
6146
6147 static int memory_events_show(struct seq_file *m, void *v)
6148 {
6149         struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6150
6151         __memory_events_show(m, memcg->memory_events);
6152         return 0;
6153 }
6154
6155 static int memory_events_local_show(struct seq_file *m, void *v)
6156 {
6157         struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6158
6159         __memory_events_show(m, memcg->memory_events_local);
6160         return 0;
6161 }
6162
6163 static int memory_stat_show(struct seq_file *m, void *v)
6164 {
6165         struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6166         char *buf;
6167
6168         buf = memory_stat_format(memcg);
6169         if (!buf)
6170                 return -ENOMEM;
6171         seq_puts(m, buf);
6172         kfree(buf);
6173         return 0;
6174 }
6175
6176 static int memory_oom_group_show(struct seq_file *m, void *v)
6177 {
6178         struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6179
6180         seq_printf(m, "%d\n", memcg->oom_group);
6181
6182         return 0;
6183 }
6184
6185 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6186                                       char *buf, size_t nbytes, loff_t off)
6187 {
6188         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6189         int ret, oom_group;
6190
6191         buf = strstrip(buf);
6192         if (!buf)
6193                 return -EINVAL;
6194
6195         ret = kstrtoint(buf, 0, &oom_group);
6196         if (ret)
6197                 return ret;
6198
6199         if (oom_group != 0 && oom_group != 1)
6200                 return -EINVAL;
6201
6202         memcg->oom_group = oom_group;
6203
6204         return nbytes;
6205 }
6206
6207 static struct cftype memory_files[] = {
6208         {
6209                 .name = "current",
6210                 .flags = CFTYPE_NOT_ON_ROOT,
6211                 .read_u64 = memory_current_read,
6212         },
6213         {
6214                 .name = "min",
6215                 .flags = CFTYPE_NOT_ON_ROOT,
6216                 .seq_show = memory_min_show,
6217                 .write = memory_min_write,
6218         },
6219         {
6220                 .name = "low",
6221                 .flags = CFTYPE_NOT_ON_ROOT,
6222                 .seq_show = memory_low_show,
6223                 .write = memory_low_write,
6224         },
6225         {
6226                 .name = "high",
6227                 .flags = CFTYPE_NOT_ON_ROOT,
6228                 .seq_show = memory_high_show,
6229                 .write = memory_high_write,
6230         },
6231         {
6232                 .name = "max",
6233                 .flags = CFTYPE_NOT_ON_ROOT,
6234                 .seq_show = memory_max_show,
6235                 .write = memory_max_write,
6236         },
6237         {
6238                 .name = "events",
6239                 .flags = CFTYPE_NOT_ON_ROOT,
6240                 .file_offset = offsetof(struct mem_cgroup, events_file),
6241                 .seq_show = memory_events_show,
6242         },
6243         {
6244                 .name = "events.local",
6245                 .flags = CFTYPE_NOT_ON_ROOT,
6246                 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6247                 .seq_show = memory_events_local_show,
6248         },
6249         {
6250                 .name = "stat",
6251                 .seq_show = memory_stat_show,
6252         },
6253         {
6254                 .name = "oom.group",
6255                 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6256                 .seq_show = memory_oom_group_show,
6257                 .write = memory_oom_group_write,
6258         },
6259         { }     /* terminate */
6260 };
6261
6262 struct cgroup_subsys memory_cgrp_subsys = {
6263         .css_alloc = mem_cgroup_css_alloc,
6264         .css_online = mem_cgroup_css_online,
6265         .css_offline = mem_cgroup_css_offline,
6266         .css_released = mem_cgroup_css_released,
6267         .css_free = mem_cgroup_css_free,
6268         .css_reset = mem_cgroup_css_reset,
6269         .can_attach = mem_cgroup_can_attach,
6270         .cancel_attach = mem_cgroup_cancel_attach,
6271         .post_attach = mem_cgroup_move_task,
6272         .bind = mem_cgroup_bind,
6273         .dfl_cftypes = memory_files,
6274         .legacy_cftypes = mem_cgroup_legacy_files,
6275         .early_init = 0,
6276 };
6277
6278 /*
6279  * This function calculates an individual cgroup's effective
6280  * protection which is derived from its own memory.min/low, its
6281  * parent's and siblings' settings, as well as the actual memory
6282  * distribution in the tree.
6283  *
6284  * The following rules apply to the effective protection values:
6285  *
6286  * 1. At the first level of reclaim, effective protection is equal to
6287  *    the declared protection in memory.min and memory.low.
6288  *
6289  * 2. To enable safe delegation of the protection configuration, at
6290  *    subsequent levels the effective protection is capped to the
6291  *    parent's effective protection.
6292  *
6293  * 3. To make complex and dynamic subtrees easier to configure, the
6294  *    user is allowed to overcommit the declared protection at a given
6295  *    level. If that is the case, the parent's effective protection is
6296  *    distributed to the children in proportion to how much protection
6297  *    they have declared and how much of it they are utilizing.
6298  *
6299  *    This makes distribution proportional, but also work-conserving:
6300  *    if one cgroup claims much more protection than it uses memory,
6301  *    the unused remainder is available to its siblings.
6302  *
6303  * 4. Conversely, when the declared protection is undercommitted at a
6304  *    given level, the distribution of the larger parental protection
6305  *    budget is NOT proportional. A cgroup's protection from a sibling
6306  *    is capped to its own memory.min/low setting.
6307  *
6308  * 5. However, to allow protecting recursive subtrees from each other
6309  *    without having to declare each individual cgroup's fixed share
6310  *    of the ancestor's claim to protection, any unutilized -
6311  *    "floating" - protection from up the tree is distributed in
6312  *    proportion to each cgroup's *usage*. This makes the protection
6313  *    neutral wrt sibling cgroups and lets them compete freely over
6314  *    the shared parental protection budget, but it protects the
6315  *    subtree as a whole from neighboring subtrees.
6316  *
6317  * Note that 4. and 5. are not in conflict: 4. is about protecting
6318  * against immediate siblings whereas 5. is about protecting against
6319  * neighboring subtrees.
6320  */
6321 static unsigned long effective_protection(unsigned long usage,
6322                                           unsigned long parent_usage,
6323                                           unsigned long setting,
6324                                           unsigned long parent_effective,
6325                                           unsigned long siblings_protected)
6326 {
6327         unsigned long protected;
6328         unsigned long ep;
6329
6330         protected = min(usage, setting);
6331         /*
6332          * If all cgroups at this level combined claim and use more
6333          * protection then what the parent affords them, distribute
6334          * shares in proportion to utilization.
6335          *
6336          * We are using actual utilization rather than the statically
6337          * claimed protection in order to be work-conserving: claimed
6338          * but unused protection is available to siblings that would
6339          * otherwise get a smaller chunk than what they claimed.
6340          */
6341         if (siblings_protected > parent_effective)
6342                 return protected * parent_effective / siblings_protected;
6343
6344         /*
6345          * Ok, utilized protection of all children is within what the
6346          * parent affords them, so we know whatever this child claims
6347          * and utilizes is effectively protected.
6348          *
6349          * If there is unprotected usage beyond this value, reclaim
6350          * will apply pressure in proportion to that amount.
6351          *
6352          * If there is unutilized protection, the cgroup will be fully
6353          * shielded from reclaim, but we do return a smaller value for
6354          * protection than what the group could enjoy in theory. This
6355          * is okay. With the overcommit distribution above, effective
6356          * protection is always dependent on how memory is actually
6357          * consumed among the siblings anyway.
6358          */
6359         ep = protected;
6360
6361         /*
6362          * If the children aren't claiming (all of) the protection
6363          * afforded to them by the parent, distribute the remainder in
6364          * proportion to the (unprotected) memory of each cgroup. That
6365          * way, cgroups that aren't explicitly prioritized wrt each
6366          * other compete freely over the allowance, but they are
6367          * collectively protected from neighboring trees.
6368          *
6369          * We're using unprotected memory for the weight so that if
6370          * some cgroups DO claim explicit protection, we don't protect
6371          * the same bytes twice.
6372          *
6373          * Check both usage and parent_usage against the respective
6374          * protected values. One should imply the other, but they
6375          * aren't read atomically - make sure the division is sane.
6376          */
6377         if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6378                 return ep;
6379         if (parent_effective > siblings_protected &&
6380             parent_usage > siblings_protected &&
6381             usage > protected) {
6382                 unsigned long unclaimed;
6383
6384                 unclaimed = parent_effective - siblings_protected;
6385                 unclaimed *= usage - protected;
6386                 unclaimed /= parent_usage - siblings_protected;
6387
6388                 ep += unclaimed;
6389         }
6390
6391         return ep;
6392 }
6393
6394 /**
6395  * mem_cgroup_protected - check if memory consumption is in the normal range
6396  * @root: the top ancestor of the sub-tree being checked
6397  * @memcg: the memory cgroup to check
6398  *
6399  * WARNING: This function is not stateless! It can only be used as part
6400  *          of a top-down tree iteration, not for isolated queries.
6401  *
6402  * Returns one of the following:
6403  *   MEMCG_PROT_NONE: cgroup memory is not protected
6404  *   MEMCG_PROT_LOW: cgroup memory is protected as long there is
6405  *     an unprotected supply of reclaimable memory from other cgroups.
6406  *   MEMCG_PROT_MIN: cgroup memory is protected
6407  */
6408 enum mem_cgroup_protection mem_cgroup_protected(struct mem_cgroup *root,
6409                                                 struct mem_cgroup *memcg)
6410 {
6411         unsigned long usage, parent_usage;
6412         struct mem_cgroup *parent;
6413
6414         if (mem_cgroup_disabled())
6415                 return MEMCG_PROT_NONE;
6416
6417         if (!root)
6418                 root = root_mem_cgroup;
6419         if (memcg == root)
6420                 return MEMCG_PROT_NONE;
6421
6422         usage = page_counter_read(&memcg->memory);
6423         if (!usage)
6424                 return MEMCG_PROT_NONE;
6425
6426         parent = parent_mem_cgroup(memcg);
6427         /* No parent means a non-hierarchical mode on v1 memcg */
6428         if (!parent)
6429                 return MEMCG_PROT_NONE;
6430
6431         if (parent == root) {
6432                 memcg->memory.emin = READ_ONCE(memcg->memory.min);
6433                 memcg->memory.elow = READ_ONCE(memcg->memory.low);
6434                 goto out;
6435         }
6436
6437         parent_usage = page_counter_read(&parent->memory);
6438
6439         WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
6440                         READ_ONCE(memcg->memory.min),
6441                         READ_ONCE(parent->memory.emin),
6442                         atomic_long_read(&parent->memory.children_min_usage)));
6443
6444         WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
6445                         READ_ONCE(memcg->memory.low),
6446                         READ_ONCE(parent->memory.elow),
6447                         atomic_long_read(&parent->memory.children_low_usage)));
6448
6449 out:
6450         if (usage <= memcg->memory.emin)
6451                 return MEMCG_PROT_MIN;
6452         else if (usage <= memcg->memory.elow)
6453                 return MEMCG_PROT_LOW;
6454         else
6455                 return MEMCG_PROT_NONE;
6456 }
6457
6458 /**
6459  * mem_cgroup_charge - charge a newly allocated page to a cgroup
6460  * @page: page to charge
6461  * @mm: mm context of the victim
6462  * @gfp_mask: reclaim mode
6463  *
6464  * Try to charge @page to the memcg that @mm belongs to, reclaiming
6465  * pages according to @gfp_mask if necessary.
6466  *
6467  * Returns 0 on success. Otherwise, an error code is returned.
6468  */
6469 int mem_cgroup_charge(struct page *page, struct mm_struct *mm, gfp_t gfp_mask)
6470 {
6471         unsigned int nr_pages = hpage_nr_pages(page);
6472         struct mem_cgroup *memcg = NULL;
6473         int ret = 0;
6474
6475         if (mem_cgroup_disabled())
6476                 goto out;
6477
6478         if (PageSwapCache(page)) {
6479                 swp_entry_t ent = { .val = page_private(page), };
6480                 unsigned short id;
6481
6482                 /*
6483                  * Every swap fault against a single page tries to charge the
6484                  * page, bail as early as possible.  shmem_unuse() encounters
6485                  * already charged pages, too.  page->mem_cgroup is protected
6486                  * by the page lock, which serializes swap cache removal, which
6487                  * in turn serializes uncharging.
6488                  */
6489                 VM_BUG_ON_PAGE(!PageLocked(page), page);
6490                 if (compound_head(page)->mem_cgroup)
6491                         goto out;
6492
6493                 id = lookup_swap_cgroup_id(ent);
6494                 rcu_read_lock();
6495                 memcg = mem_cgroup_from_id(id);
6496                 if (memcg && !css_tryget_online(&memcg->css))
6497                         memcg = NULL;
6498                 rcu_read_unlock();
6499         }
6500
6501         if (!memcg)
6502                 memcg = get_mem_cgroup_from_mm(mm);
6503
6504         ret = try_charge(memcg, gfp_mask, nr_pages);
6505         if (ret)
6506                 goto out_put;
6507
6508         commit_charge(page, memcg);
6509
6510         local_irq_disable();
6511         mem_cgroup_charge_statistics(memcg, page, nr_pages);
6512         memcg_check_events(memcg, page);
6513         local_irq_enable();
6514
6515         if (PageSwapCache(page)) {
6516                 swp_entry_t entry = { .val = page_private(page) };
6517                 /*
6518                  * The swap entry might not get freed for a long time,
6519                  * let's not wait for it.  The page already received a
6520                  * memory+swap charge, drop the swap entry duplicate.
6521                  */
6522                 mem_cgroup_uncharge_swap(entry, nr_pages);
6523         }
6524
6525 out_put:
6526         css_put(&memcg->css);
6527 out:
6528         return ret;
6529 }
6530
6531 struct uncharge_gather {
6532         struct mem_cgroup *memcg;
6533         unsigned long nr_pages;
6534         unsigned long pgpgout;
6535         unsigned long nr_kmem;
6536         struct page *dummy_page;
6537 };
6538
6539 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
6540 {
6541         memset(ug, 0, sizeof(*ug));
6542 }
6543
6544 static void uncharge_batch(const struct uncharge_gather *ug)
6545 {
6546         unsigned long flags;
6547
6548         if (!mem_cgroup_is_root(ug->memcg)) {
6549                 page_counter_uncharge(&ug->memcg->memory, ug->nr_pages);
6550                 if (do_memsw_account())
6551                         page_counter_uncharge(&ug->memcg->memsw, ug->nr_pages);
6552                 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && ug->nr_kmem)
6553                         page_counter_uncharge(&ug->memcg->kmem, ug->nr_kmem);
6554                 memcg_oom_recover(ug->memcg);
6555         }
6556
6557         local_irq_save(flags);
6558         __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
6559         __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_pages);
6560         memcg_check_events(ug->memcg, ug->dummy_page);
6561         local_irq_restore(flags);
6562
6563         if (!mem_cgroup_is_root(ug->memcg))
6564                 css_put_many(&ug->memcg->css, ug->nr_pages);
6565 }
6566
6567 static void uncharge_page(struct page *page, struct uncharge_gather *ug)
6568 {
6569         unsigned long nr_pages;
6570
6571         VM_BUG_ON_PAGE(PageLRU(page), page);
6572
6573         if (!page->mem_cgroup)
6574                 return;
6575
6576         /*
6577          * Nobody should be changing or seriously looking at
6578          * page->mem_cgroup at this point, we have fully
6579          * exclusive access to the page.
6580          */
6581
6582         if (ug->memcg != page->mem_cgroup) {
6583                 if (ug->memcg) {
6584                         uncharge_batch(ug);
6585                         uncharge_gather_clear(ug);
6586                 }
6587                 ug->memcg = page->mem_cgroup;
6588         }
6589
6590         nr_pages = compound_nr(page);
6591         ug->nr_pages += nr_pages;
6592
6593         if (!PageKmemcg(page)) {
6594                 ug->pgpgout++;
6595         } else {
6596                 ug->nr_kmem += nr_pages;
6597                 __ClearPageKmemcg(page);
6598         }
6599
6600         ug->dummy_page = page;
6601         page->mem_cgroup = NULL;
6602 }
6603
6604 static void uncharge_list(struct list_head *page_list)
6605 {
6606         struct uncharge_gather ug;
6607         struct list_head *next;
6608
6609         uncharge_gather_clear(&ug);
6610
6611         /*
6612          * Note that the list can be a single page->lru; hence the
6613          * do-while loop instead of a simple list_for_each_entry().
6614          */
6615         next = page_list->next;
6616         do {
6617                 struct page *page;
6618
6619                 page = list_entry(next, struct page, lru);
6620                 next = page->lru.next;
6621
6622                 uncharge_page(page, &ug);
6623         } while (next != page_list);
6624
6625         if (ug.memcg)
6626                 uncharge_batch(&ug);
6627 }
6628
6629 /**
6630  * mem_cgroup_uncharge - uncharge a page
6631  * @page: page to uncharge
6632  *
6633  * Uncharge a page previously charged with mem_cgroup_charge().
6634  */
6635 void mem_cgroup_uncharge(struct page *page)
6636 {
6637         struct uncharge_gather ug;
6638
6639         if (mem_cgroup_disabled())
6640                 return;
6641
6642         /* Don't touch page->lru of any random page, pre-check: */
6643         if (!page->mem_cgroup)
6644                 return;
6645
6646         uncharge_gather_clear(&ug);
6647         uncharge_page(page, &ug);
6648         uncharge_batch(&ug);
6649 }
6650
6651 /**
6652  * mem_cgroup_uncharge_list - uncharge a list of page
6653  * @page_list: list of pages to uncharge
6654  *
6655  * Uncharge a list of pages previously charged with
6656  * mem_cgroup_charge().
6657  */
6658 void mem_cgroup_uncharge_list(struct list_head *page_list)
6659 {
6660         if (mem_cgroup_disabled())
6661                 return;
6662
6663         if (!list_empty(page_list))
6664                 uncharge_list(page_list);
6665 }
6666
6667 /**
6668  * mem_cgroup_migrate - charge a page's replacement
6669  * @oldpage: currently circulating page
6670  * @newpage: replacement page
6671  *
6672  * Charge @newpage as a replacement page for @oldpage. @oldpage will
6673  * be uncharged upon free.
6674  *
6675  * Both pages must be locked, @newpage->mapping must be set up.
6676  */
6677 void mem_cgroup_migrate(struct page *oldpage, struct page *newpage)
6678 {
6679         struct mem_cgroup *memcg;
6680         unsigned int nr_pages;
6681         unsigned long flags;
6682
6683         VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
6684         VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
6685         VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
6686         VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
6687                        newpage);
6688
6689         if (mem_cgroup_disabled())
6690                 return;
6691
6692         /* Page cache replacement: new page already charged? */
6693         if (newpage->mem_cgroup)
6694                 return;
6695
6696         /* Swapcache readahead pages can get replaced before being charged */
6697         memcg = oldpage->mem_cgroup;
6698         if (!memcg)
6699                 return;
6700
6701         /* Force-charge the new page. The old one will be freed soon */
6702         nr_pages = hpage_nr_pages(newpage);
6703
6704         page_counter_charge(&memcg->memory, nr_pages);
6705         if (do_memsw_account())
6706                 page_counter_charge(&memcg->memsw, nr_pages);
6707         css_get_many(&memcg->css, nr_pages);
6708
6709         commit_charge(newpage, memcg);
6710
6711         local_irq_save(flags);
6712         mem_cgroup_charge_statistics(memcg, newpage, nr_pages);
6713         memcg_check_events(memcg, newpage);
6714         local_irq_restore(flags);
6715 }
6716
6717 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
6718 EXPORT_SYMBOL(memcg_sockets_enabled_key);
6719
6720 void mem_cgroup_sk_alloc(struct sock *sk)
6721 {
6722         struct mem_cgroup *memcg;
6723
6724         if (!mem_cgroup_sockets_enabled)
6725                 return;
6726
6727         /* Do not associate the sock with unrelated interrupted task's memcg. */
6728         if (in_interrupt())
6729                 return;
6730
6731         rcu_read_lock();
6732         memcg = mem_cgroup_from_task(current);
6733         if (memcg == root_mem_cgroup)
6734                 goto out;
6735         if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
6736                 goto out;
6737         if (css_tryget(&memcg->css))
6738                 sk->sk_memcg = memcg;
6739 out:
6740         rcu_read_unlock();
6741 }
6742
6743 void mem_cgroup_sk_free(struct sock *sk)
6744 {
6745         if (sk->sk_memcg)
6746                 css_put(&sk->sk_memcg->css);
6747 }
6748
6749 /**
6750  * mem_cgroup_charge_skmem - charge socket memory
6751  * @memcg: memcg to charge
6752  * @nr_pages: number of pages to charge
6753  *
6754  * Charges @nr_pages to @memcg. Returns %true if the charge fit within
6755  * @memcg's configured limit, %false if the charge had to be forced.
6756  */
6757 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
6758 {
6759         gfp_t gfp_mask = GFP_KERNEL;
6760
6761         if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
6762                 struct page_counter *fail;
6763
6764                 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
6765                         memcg->tcpmem_pressure = 0;
6766                         return true;
6767                 }
6768                 page_counter_charge(&memcg->tcpmem, nr_pages);
6769                 memcg->tcpmem_pressure = 1;
6770                 return false;
6771         }
6772
6773         /* Don't block in the packet receive path */
6774         if (in_softirq())
6775                 gfp_mask = GFP_NOWAIT;
6776
6777         mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
6778
6779         if (try_charge(memcg, gfp_mask, nr_pages) == 0)
6780                 return true;
6781
6782         try_charge(memcg, gfp_mask|__GFP_NOFAIL, nr_pages);
6783         return false;
6784 }
6785
6786 /**
6787  * mem_cgroup_uncharge_skmem - uncharge socket memory
6788  * @memcg: memcg to uncharge
6789  * @nr_pages: number of pages to uncharge
6790  */
6791 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
6792 {
6793         if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
6794                 page_counter_uncharge(&memcg->tcpmem, nr_pages);
6795                 return;
6796         }
6797
6798         mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
6799
6800         refill_stock(memcg, nr_pages);
6801 }
6802
6803 static int __init cgroup_memory(char *s)
6804 {
6805         char *token;
6806
6807         while ((token = strsep(&s, ",")) != NULL) {
6808                 if (!*token)
6809                         continue;
6810                 if (!strcmp(token, "nosocket"))
6811                         cgroup_memory_nosocket = true;
6812                 if (!strcmp(token, "nokmem"))
6813                         cgroup_memory_nokmem = true;
6814         }
6815         return 0;
6816 }
6817 __setup("cgroup.memory=", cgroup_memory);
6818
6819 /*
6820  * subsys_initcall() for memory controller.
6821  *
6822  * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
6823  * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
6824  * basically everything that doesn't depend on a specific mem_cgroup structure
6825  * should be initialized from here.
6826  */
6827 static int __init mem_cgroup_init(void)
6828 {
6829         int cpu, node;
6830
6831 #ifdef CONFIG_MEMCG_KMEM
6832         /*
6833          * Kmem cache creation is mostly done with the slab_mutex held,
6834          * so use a workqueue with limited concurrency to avoid stalling
6835          * all worker threads in case lots of cgroups are created and
6836          * destroyed simultaneously.
6837          */
6838         memcg_kmem_cache_wq = alloc_workqueue("memcg_kmem_cache", 0, 1);
6839         BUG_ON(!memcg_kmem_cache_wq);
6840 #endif
6841
6842         cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
6843                                   memcg_hotplug_cpu_dead);
6844
6845         for_each_possible_cpu(cpu)
6846                 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
6847                           drain_local_stock);
6848
6849         for_each_node(node) {
6850                 struct mem_cgroup_tree_per_node *rtpn;
6851
6852                 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
6853                                     node_online(node) ? node : NUMA_NO_NODE);
6854
6855                 rtpn->rb_root = RB_ROOT;
6856                 rtpn->rb_rightmost = NULL;
6857                 spin_lock_init(&rtpn->lock);
6858                 soft_limit_tree.rb_tree_per_node[node] = rtpn;
6859         }
6860
6861         return 0;
6862 }
6863 subsys_initcall(mem_cgroup_init);
6864
6865 #ifdef CONFIG_MEMCG_SWAP
6866 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
6867 {
6868         while (!refcount_inc_not_zero(&memcg->id.ref)) {
6869                 /*
6870                  * The root cgroup cannot be destroyed, so it's refcount must
6871                  * always be >= 1.
6872                  */
6873                 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
6874                         VM_BUG_ON(1);
6875                         break;
6876                 }
6877                 memcg = parent_mem_cgroup(memcg);
6878                 if (!memcg)
6879                         memcg = root_mem_cgroup;
6880         }
6881         return memcg;
6882 }
6883
6884 /**
6885  * mem_cgroup_swapout - transfer a memsw charge to swap
6886  * @page: page whose memsw charge to transfer
6887  * @entry: swap entry to move the charge to
6888  *
6889  * Transfer the memsw charge of @page to @entry.
6890  */
6891 void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
6892 {
6893         struct mem_cgroup *memcg, *swap_memcg;
6894         unsigned int nr_entries;
6895         unsigned short oldid;
6896
6897         VM_BUG_ON_PAGE(PageLRU(page), page);
6898         VM_BUG_ON_PAGE(page_count(page), page);
6899
6900         if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
6901                 return;
6902
6903         memcg = page->mem_cgroup;
6904
6905         /* Readahead page, never charged */
6906         if (!memcg)
6907                 return;
6908
6909         /*
6910          * In case the memcg owning these pages has been offlined and doesn't
6911          * have an ID allocated to it anymore, charge the closest online
6912          * ancestor for the swap instead and transfer the memory+swap charge.
6913          */
6914         swap_memcg = mem_cgroup_id_get_online(memcg);
6915         nr_entries = hpage_nr_pages(page);
6916         /* Get references for the tail pages, too */
6917         if (nr_entries > 1)
6918                 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
6919         oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
6920                                    nr_entries);
6921         VM_BUG_ON_PAGE(oldid, page);
6922         mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
6923
6924         page->mem_cgroup = NULL;
6925
6926         if (!mem_cgroup_is_root(memcg))
6927                 page_counter_uncharge(&memcg->memory, nr_entries);
6928
6929         if (!cgroup_memory_noswap && memcg != swap_memcg) {
6930                 if (!mem_cgroup_is_root(swap_memcg))
6931                         page_counter_charge(&swap_memcg->memsw, nr_entries);
6932                 page_counter_uncharge(&memcg->memsw, nr_entries);
6933         }
6934
6935         /*
6936          * Interrupts should be disabled here because the caller holds the
6937          * i_pages lock which is taken with interrupts-off. It is
6938          * important here to have the interrupts disabled because it is the
6939          * only synchronisation we have for updating the per-CPU variables.
6940          */
6941         VM_BUG_ON(!irqs_disabled());
6942         mem_cgroup_charge_statistics(memcg, page, -nr_entries);
6943         memcg_check_events(memcg, page);
6944
6945         if (!mem_cgroup_is_root(memcg))
6946                 css_put_many(&memcg->css, nr_entries);
6947 }
6948
6949 /**
6950  * mem_cgroup_try_charge_swap - try charging swap space for a page
6951  * @page: page being added to swap
6952  * @entry: swap entry to charge
6953  *
6954  * Try to charge @page's memcg for the swap space at @entry.
6955  *
6956  * Returns 0 on success, -ENOMEM on failure.
6957  */
6958 int mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry)
6959 {
6960         unsigned int nr_pages = hpage_nr_pages(page);
6961         struct page_counter *counter;
6962         struct mem_cgroup *memcg;
6963         unsigned short oldid;
6964
6965         if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
6966                 return 0;
6967
6968         memcg = page->mem_cgroup;
6969
6970         /* Readahead page, never charged */
6971         if (!memcg)
6972                 return 0;
6973
6974         if (!entry.val) {
6975                 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
6976                 return 0;
6977         }
6978
6979         memcg = mem_cgroup_id_get_online(memcg);
6980
6981         if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg) &&
6982             !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
6983                 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
6984                 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
6985                 mem_cgroup_id_put(memcg);
6986                 return -ENOMEM;
6987         }
6988
6989         /* Get references for the tail pages, too */
6990         if (nr_pages > 1)
6991                 mem_cgroup_id_get_many(memcg, nr_pages - 1);
6992         oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
6993         VM_BUG_ON_PAGE(oldid, page);
6994         mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
6995
6996         return 0;
6997 }
6998
6999 /**
7000  * mem_cgroup_uncharge_swap - uncharge swap space
7001  * @entry: swap entry to uncharge
7002  * @nr_pages: the amount of swap space to uncharge
7003  */
7004 void mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
7005 {
7006         struct mem_cgroup *memcg;
7007         unsigned short id;
7008
7009         id = swap_cgroup_record(entry, 0, nr_pages);
7010         rcu_read_lock();
7011         memcg = mem_cgroup_from_id(id);
7012         if (memcg) {
7013                 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg)) {
7014                         if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
7015                                 page_counter_uncharge(&memcg->swap, nr_pages);
7016                         else
7017                                 page_counter_uncharge(&memcg->memsw, nr_pages);
7018                 }
7019                 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
7020                 mem_cgroup_id_put_many(memcg, nr_pages);
7021         }
7022         rcu_read_unlock();
7023 }
7024
7025 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7026 {
7027         long nr_swap_pages = get_nr_swap_pages();
7028
7029         if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7030                 return nr_swap_pages;
7031         for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7032                 nr_swap_pages = min_t(long, nr_swap_pages,
7033                                       READ_ONCE(memcg->swap.max) -
7034                                       page_counter_read(&memcg->swap));
7035         return nr_swap_pages;
7036 }
7037
7038 bool mem_cgroup_swap_full(struct page *page)
7039 {
7040         struct mem_cgroup *memcg;
7041
7042         VM_BUG_ON_PAGE(!PageLocked(page), page);
7043
7044         if (vm_swap_full())
7045                 return true;
7046         if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
7047                 return false;
7048
7049         memcg = page->mem_cgroup;
7050         if (!memcg)
7051                 return false;
7052
7053         for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
7054                 unsigned long usage = page_counter_read(&memcg->swap);
7055
7056                 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7057                     usage * 2 >= READ_ONCE(memcg->swap.max))
7058                         return true;
7059         }
7060
7061         return false;
7062 }
7063
7064 static int __init setup_swap_account(char *s)
7065 {
7066         if (!strcmp(s, "1"))
7067                 cgroup_memory_noswap = 0;
7068         else if (!strcmp(s, "0"))
7069                 cgroup_memory_noswap = 1;
7070         return 1;
7071 }
7072 __setup("swapaccount=", setup_swap_account);
7073
7074 static u64 swap_current_read(struct cgroup_subsys_state *css,
7075                              struct cftype *cft)
7076 {
7077         struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7078
7079         return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7080 }
7081
7082 static int swap_high_show(struct seq_file *m, void *v)
7083 {
7084         return seq_puts_memcg_tunable(m,
7085                 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7086 }
7087
7088 static ssize_t swap_high_write(struct kernfs_open_file *of,
7089                                char *buf, size_t nbytes, loff_t off)
7090 {
7091         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7092         unsigned long high;
7093         int err;
7094
7095         buf = strstrip(buf);
7096         err = page_counter_memparse(buf, "max", &high);
7097         if (err)
7098                 return err;
7099
7100         page_counter_set_high(&memcg->swap, high);
7101
7102         return nbytes;
7103 }
7104
7105 static int swap_max_show(struct seq_file *m, void *v)
7106 {
7107         return seq_puts_memcg_tunable(m,
7108                 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
7109 }
7110
7111 static ssize_t swap_max_write(struct kernfs_open_file *of,
7112                               char *buf, size_t nbytes, loff_t off)
7113 {
7114         struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7115         unsigned long max;
7116         int err;
7117
7118         buf = strstrip(buf);
7119         err = page_counter_memparse(buf, "max", &max);
7120         if (err)
7121                 return err;
7122
7123         xchg(&memcg->swap.max, max);
7124
7125         return nbytes;
7126 }
7127
7128 static int swap_events_show(struct seq_file *m, void *v)
7129 {
7130         struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
7131
7132         seq_printf(m, "high %lu\n",
7133                    atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
7134         seq_printf(m, "max %lu\n",
7135                    atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7136         seq_printf(m, "fail %lu\n",
7137                    atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7138
7139         return 0;
7140 }
7141
7142 static struct cftype swap_files[] = {
7143         {
7144                 .name = "swap.current",
7145                 .flags = CFTYPE_NOT_ON_ROOT,
7146                 .read_u64 = swap_current_read,
7147         },
7148         {
7149                 .name = "swap.high",
7150                 .flags = CFTYPE_NOT_ON_ROOT,
7151                 .seq_show = swap_high_show,
7152                 .write = swap_high_write,
7153         },
7154         {
7155                 .name = "swap.max",
7156                 .flags = CFTYPE_NOT_ON_ROOT,
7157                 .seq_show = swap_max_show,
7158                 .write = swap_max_write,
7159         },
7160         {
7161                 .name = "swap.events",
7162                 .flags = CFTYPE_NOT_ON_ROOT,
7163                 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7164                 .seq_show = swap_events_show,
7165         },
7166         { }     /* terminate */
7167 };
7168
7169 static struct cftype memsw_files[] = {
7170         {
7171                 .name = "memsw.usage_in_bytes",
7172                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7173                 .read_u64 = mem_cgroup_read_u64,
7174         },
7175         {
7176                 .name = "memsw.max_usage_in_bytes",
7177                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7178                 .write = mem_cgroup_reset,
7179                 .read_u64 = mem_cgroup_read_u64,
7180         },
7181         {
7182                 .name = "memsw.limit_in_bytes",
7183                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7184                 .write = mem_cgroup_write,
7185                 .read_u64 = mem_cgroup_read_u64,
7186         },
7187         {
7188                 .name = "memsw.failcnt",
7189                 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7190                 .write = mem_cgroup_reset,
7191                 .read_u64 = mem_cgroup_read_u64,
7192         },
7193         { },    /* terminate */
7194 };
7195
7196 /*
7197  * If mem_cgroup_swap_init() is implemented as a subsys_initcall()
7198  * instead of a core_initcall(), this could mean cgroup_memory_noswap still
7199  * remains set to false even when memcg is disabled via "cgroup_disable=memory"
7200  * boot parameter. This may result in premature OOPS inside
7201  * mem_cgroup_get_nr_swap_pages() function in corner cases.
7202  */
7203 static int __init mem_cgroup_swap_init(void)
7204 {
7205         /* No memory control -> no swap control */
7206         if (mem_cgroup_disabled())
7207                 cgroup_memory_noswap = true;
7208
7209         if (cgroup_memory_noswap)
7210                 return 0;
7211
7212         WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7213         WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
7214
7215         return 0;
7216 }
7217 core_initcall(mem_cgroup_swap_init);
7218
7219 #endif /* CONFIG_MEMCG_SWAP */