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