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