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