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