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