• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/cgroup-defs.h>
29 #include <linux/page_counter.h>
30 #include <linux/memcontrol.h>
31 #include <linux/cgroup.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/list.h>
46 #include <linux/mutex.h>
47 #include <linux/rbtree.h>
48 #include <linux/slab.h>
49 #include <linux/swapops.h>
50 #include <linux/spinlock.h>
51 #include <linux/fs.h>
52 #include <linux/seq_file.h>
53 #include <linux/parser.h>
54 #include <linux/vmpressure.h>
55 #include <linux/memremap.h>
56 #include <linux/mm_inline.h>
57 #include <linux/swap_cgroup.h>
58 #include <linux/cpu.h>
59 #include <linux/oom.h>
60 #include <linux/lockdep.h>
61 #include <linux/resume_user_mode.h>
62 #include <linux/psi.h>
63 #include <linux/seq_buf.h>
64 #include <linux/sched/isolation.h>
65 #include <linux/kmemleak.h>
66 #include "internal.h"
67 #include <net/sock.h>
68 #include <net/ip.h>
69 #include "slab.h"
70 #include "memcontrol-v1.h"
71 
72 #include <linux/uaccess.h>
73 
74 #include <trace/events/vmscan.h>
75 #include <trace/hooks/mm.h>
76 #include <trace/hooks/vmscan.h>
77 
78 struct cgroup_subsys memory_cgrp_subsys __read_mostly;
79 EXPORT_SYMBOL(memory_cgrp_subsys);
80 
81 struct mem_cgroup *root_mem_cgroup __read_mostly;
82 EXPORT_SYMBOL_GPL(root_mem_cgroup);
83 
84 /* Active memory cgroup to use from an interrupt context */
85 DEFINE_PER_CPU(struct mem_cgroup *, int_active_memcg);
86 EXPORT_PER_CPU_SYMBOL_GPL(int_active_memcg);
87 
88 /* Socket memory accounting disabled? */
89 static bool cgroup_memory_nosocket __ro_after_init;
90 
91 /* Kernel memory accounting disabled? */
92 static bool cgroup_memory_nokmem __ro_after_init;
93 
94 /* BPF memory accounting disabled? */
95 static bool cgroup_memory_nobpf __ro_after_init;
96 
97 static struct kmem_cache *memcg_cachep;
98 static struct kmem_cache *memcg_pn_cachep;
99 
100 #ifdef CONFIG_CGROUP_WRITEBACK
101 static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
102 #endif
103 
task_is_dying(void)104 static inline bool task_is_dying(void)
105 {
106 	return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
107 		(current->flags & PF_EXITING);
108 }
109 
110 /* Some nice accessors for the vmpressure. */
memcg_to_vmpressure(struct mem_cgroup * memcg)111 struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
112 {
113 	if (!memcg)
114 		memcg = root_mem_cgroup;
115 	return &memcg->vmpressure;
116 }
117 
vmpressure_to_memcg(struct vmpressure * vmpr)118 struct mem_cgroup *vmpressure_to_memcg(struct vmpressure *vmpr)
119 {
120 	return container_of(vmpr, struct mem_cgroup, vmpressure);
121 }
122 
123 /*
124  * trace_android_vh_use_vm_swappiness is called in include/linux/swap.h by
125  * including include/trace/hooks/vmscan.h, which will result to build-err.
126  * So we create func: _trace_android_vh_use_vm_swappiness.
127  */
_trace_android_vh_use_vm_swappiness(bool * use_vm_swappiness)128 void _trace_android_vh_use_vm_swappiness(bool *use_vm_swappiness)
129 {
130 	trace_android_vh_use_vm_swappiness(use_vm_swappiness);
131 }
132 
133 #define CURRENT_OBJCG_UPDATE_BIT 0
134 #define CURRENT_OBJCG_UPDATE_FLAG (1UL << CURRENT_OBJCG_UPDATE_BIT)
135 
136 static DEFINE_SPINLOCK(objcg_lock);
137 
mem_cgroup_kmem_disabled(void)138 bool mem_cgroup_kmem_disabled(void)
139 {
140 	return cgroup_memory_nokmem;
141 }
142 
143 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
144 				      unsigned int nr_pages);
145 
obj_cgroup_release(struct percpu_ref * ref)146 static void obj_cgroup_release(struct percpu_ref *ref)
147 {
148 	struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
149 	unsigned int nr_bytes;
150 	unsigned int nr_pages;
151 	unsigned long flags;
152 
153 	/*
154 	 * At this point all allocated objects are freed, and
155 	 * objcg->nr_charged_bytes can't have an arbitrary byte value.
156 	 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
157 	 *
158 	 * The following sequence can lead to it:
159 	 * 1) CPU0: objcg == stock->cached_objcg
160 	 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
161 	 *          PAGE_SIZE bytes are charged
162 	 * 3) CPU1: a process from another memcg is allocating something,
163 	 *          the stock if flushed,
164 	 *          objcg->nr_charged_bytes = PAGE_SIZE - 92
165 	 * 5) CPU0: we do release this object,
166 	 *          92 bytes are added to stock->nr_bytes
167 	 * 6) CPU0: stock is flushed,
168 	 *          92 bytes are added to objcg->nr_charged_bytes
169 	 *
170 	 * In the result, nr_charged_bytes == PAGE_SIZE.
171 	 * This page will be uncharged in obj_cgroup_release().
172 	 */
173 	nr_bytes = atomic_read(&objcg->nr_charged_bytes);
174 	WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
175 	nr_pages = nr_bytes >> PAGE_SHIFT;
176 
177 	if (nr_pages)
178 		obj_cgroup_uncharge_pages(objcg, nr_pages);
179 
180 	spin_lock_irqsave(&objcg_lock, flags);
181 	list_del(&objcg->list);
182 	spin_unlock_irqrestore(&objcg_lock, flags);
183 
184 	percpu_ref_exit(ref);
185 	kfree_rcu(objcg, rcu);
186 }
187 
obj_cgroup_alloc(void)188 static struct obj_cgroup *obj_cgroup_alloc(void)
189 {
190 	struct obj_cgroup *objcg;
191 	int ret;
192 
193 	objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
194 	if (!objcg)
195 		return NULL;
196 
197 	ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
198 			      GFP_KERNEL);
199 	if (ret) {
200 		kfree(objcg);
201 		return NULL;
202 	}
203 	INIT_LIST_HEAD(&objcg->list);
204 	return objcg;
205 }
206 
memcg_reparent_objcgs(struct mem_cgroup * memcg,struct mem_cgroup * parent)207 static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
208 				  struct mem_cgroup *parent)
209 {
210 	struct obj_cgroup *objcg, *iter;
211 
212 	objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
213 
214 	spin_lock_irq(&objcg_lock);
215 
216 	/* 1) Ready to reparent active objcg. */
217 	list_add(&objcg->list, &memcg->objcg_list);
218 	/* 2) Reparent active objcg and already reparented objcgs to parent. */
219 	list_for_each_entry(iter, &memcg->objcg_list, list)
220 		WRITE_ONCE(iter->memcg, parent);
221 	/* 3) Move already reparented objcgs to the parent's list */
222 	list_splice(&memcg->objcg_list, &parent->objcg_list);
223 
224 	spin_unlock_irq(&objcg_lock);
225 
226 	percpu_ref_kill(&objcg->refcnt);
227 }
228 
229 /*
230  * A lot of the calls to the cache allocation functions are expected to be
231  * inlined by the compiler. Since the calls to memcg_slab_post_alloc_hook() are
232  * conditional to this static branch, we'll have to allow modules that does
233  * kmem_cache_alloc and the such to see this symbol as well
234  */
235 DEFINE_STATIC_KEY_FALSE(memcg_kmem_online_key);
236 EXPORT_SYMBOL(memcg_kmem_online_key);
237 
238 DEFINE_STATIC_KEY_FALSE(memcg_bpf_enabled_key);
239 EXPORT_SYMBOL(memcg_bpf_enabled_key);
240 
241 /**
242  * mem_cgroup_css_from_folio - css of the memcg associated with a folio
243  * @folio: folio of interest
244  *
245  * If memcg is bound to the default hierarchy, css of the memcg associated
246  * with @folio is returned.  The returned css remains associated with @folio
247  * until it is released.
248  *
249  * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
250  * is returned.
251  */
mem_cgroup_css_from_folio(struct folio * folio)252 struct cgroup_subsys_state *mem_cgroup_css_from_folio(struct folio *folio)
253 {
254 	struct mem_cgroup *memcg = folio_memcg(folio);
255 
256 	if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
257 		memcg = root_mem_cgroup;
258 
259 	return &memcg->css;
260 }
261 
262 /**
263  * page_cgroup_ino - return inode number of the memcg a page is charged to
264  * @page: the page
265  *
266  * Look up the closest online ancestor of the memory cgroup @page is charged to
267  * and return its inode number or 0 if @page is not charged to any cgroup. It
268  * is safe to call this function without holding a reference to @page.
269  *
270  * Note, this function is inherently racy, because there is nothing to prevent
271  * the cgroup inode from getting torn down and potentially reallocated a moment
272  * after page_cgroup_ino() returns, so it only should be used by callers that
273  * do not care (such as procfs interfaces).
274  */
page_cgroup_ino(struct page * page)275 ino_t page_cgroup_ino(struct page *page)
276 {
277 	struct mem_cgroup *memcg;
278 	unsigned long ino = 0;
279 
280 	rcu_read_lock();
281 	/* page_folio() is racy here, but the entire function is racy anyway */
282 	memcg = folio_memcg_check(page_folio(page));
283 
284 	while (memcg && !(memcg->css.flags & CSS_ONLINE))
285 		memcg = parent_mem_cgroup(memcg);
286 	if (memcg)
287 		ino = cgroup_ino(memcg->css.cgroup);
288 	rcu_read_unlock();
289 	return ino;
290 }
291 
292 /* Subset of node_stat_item for memcg stats */
293 static const unsigned int memcg_node_stat_items[] = {
294 	NR_INACTIVE_ANON,
295 	NR_ACTIVE_ANON,
296 	NR_INACTIVE_FILE,
297 	NR_ACTIVE_FILE,
298 	NR_UNEVICTABLE,
299 	NR_SLAB_RECLAIMABLE_B,
300 	NR_SLAB_UNRECLAIMABLE_B,
301 	WORKINGSET_REFAULT_ANON,
302 	WORKINGSET_REFAULT_FILE,
303 	WORKINGSET_ACTIVATE_ANON,
304 	WORKINGSET_ACTIVATE_FILE,
305 	WORKINGSET_RESTORE_ANON,
306 	WORKINGSET_RESTORE_FILE,
307 	WORKINGSET_NODERECLAIM,
308 	NR_ANON_MAPPED,
309 	NR_FILE_MAPPED,
310 	NR_FILE_PAGES,
311 	NR_FILE_DIRTY,
312 	NR_WRITEBACK,
313 	NR_SHMEM,
314 	NR_SHMEM_THPS,
315 	NR_FILE_THPS,
316 	NR_ANON_THPS,
317 	NR_KERNEL_STACK_KB,
318 	NR_PAGETABLE,
319 	NR_SECONDARY_PAGETABLE,
320 #ifdef CONFIG_SWAP
321 	NR_SWAPCACHE,
322 #endif
323 #ifdef CONFIG_NUMA_BALANCING
324 	PGPROMOTE_SUCCESS,
325 #endif
326 	PGDEMOTE_KSWAPD,
327 	PGDEMOTE_DIRECT,
328 	PGDEMOTE_KHUGEPAGED,
329 };
330 
331 static const unsigned int memcg_stat_items[] = {
332 	MEMCG_SWAP,
333 	MEMCG_SOCK,
334 	MEMCG_PERCPU_B,
335 	MEMCG_VMALLOC,
336 	MEMCG_KMEM,
337 	MEMCG_ZSWAP_B,
338 	MEMCG_ZSWAPPED,
339 };
340 
341 #define NR_MEMCG_NODE_STAT_ITEMS ARRAY_SIZE(memcg_node_stat_items)
342 #define MEMCG_VMSTAT_SIZE (NR_MEMCG_NODE_STAT_ITEMS + \
343 			   ARRAY_SIZE(memcg_stat_items))
344 #define BAD_STAT_IDX(index) ((u32)(index) >= U8_MAX)
345 static u8 mem_cgroup_stats_index[MEMCG_NR_STAT] __read_mostly;
346 
init_memcg_stats(void)347 static void init_memcg_stats(void)
348 {
349 	u8 i, j = 0;
350 
351 	BUILD_BUG_ON(MEMCG_NR_STAT >= U8_MAX);
352 
353 	memset(mem_cgroup_stats_index, U8_MAX, sizeof(mem_cgroup_stats_index));
354 
355 	for (i = 0; i < NR_MEMCG_NODE_STAT_ITEMS; ++i, ++j)
356 		mem_cgroup_stats_index[memcg_node_stat_items[i]] = j;
357 
358 	for (i = 0; i < ARRAY_SIZE(memcg_stat_items); ++i, ++j)
359 		mem_cgroup_stats_index[memcg_stat_items[i]] = j;
360 }
361 
memcg_stats_index(int idx)362 static inline int memcg_stats_index(int idx)
363 {
364 	return mem_cgroup_stats_index[idx];
365 }
366 
367 struct lruvec_stats_percpu {
368 	/* Local (CPU and cgroup) state */
369 	long state[NR_MEMCG_NODE_STAT_ITEMS];
370 
371 	/* Delta calculation for lockless upward propagation */
372 	long state_prev[NR_MEMCG_NODE_STAT_ITEMS];
373 };
374 
375 struct lruvec_stats {
376 	/* Aggregated (CPU and subtree) state */
377 	long state[NR_MEMCG_NODE_STAT_ITEMS];
378 
379 	/* Non-hierarchical (CPU aggregated) state */
380 	long state_local[NR_MEMCG_NODE_STAT_ITEMS];
381 
382 	/* Pending child counts during tree propagation */
383 	long state_pending[NR_MEMCG_NODE_STAT_ITEMS];
384 };
385 
lruvec_page_state(struct lruvec * lruvec,enum node_stat_item idx)386 unsigned long lruvec_page_state(struct lruvec *lruvec, enum node_stat_item idx)
387 {
388 	struct mem_cgroup_per_node *pn;
389 	long x;
390 	int i;
391 
392 	if (mem_cgroup_disabled())
393 		return node_page_state(lruvec_pgdat(lruvec), idx);
394 
395 	i = memcg_stats_index(idx);
396 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
397 		return 0;
398 
399 	pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
400 	x = READ_ONCE(pn->lruvec_stats->state[i]);
401 #ifdef CONFIG_SMP
402 	if (x < 0)
403 		x = 0;
404 #endif
405 	return x;
406 }
407 EXPORT_SYMBOL_GPL(lruvec_page_state);
408 
lruvec_page_state_local(struct lruvec * lruvec,enum node_stat_item idx)409 unsigned long lruvec_page_state_local(struct lruvec *lruvec,
410 				      enum node_stat_item idx)
411 {
412 	struct mem_cgroup_per_node *pn;
413 	long x;
414 	int i;
415 
416 	if (mem_cgroup_disabled())
417 		return node_page_state(lruvec_pgdat(lruvec), idx);
418 
419 	i = memcg_stats_index(idx);
420 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
421 		return 0;
422 
423 	pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
424 	x = READ_ONCE(pn->lruvec_stats->state_local[i]);
425 #ifdef CONFIG_SMP
426 	if (x < 0)
427 		x = 0;
428 #endif
429 	return x;
430 }
431 
432 /* Subset of vm_event_item to report for memcg event stats */
433 static const unsigned int memcg_vm_event_stat[] = {
434 #ifdef CONFIG_MEMCG_V1
435 	PGPGIN,
436 	PGPGOUT,
437 #endif
438 	PGSCAN_KSWAPD,
439 	PGSCAN_DIRECT,
440 	PGSCAN_KHUGEPAGED,
441 	PGSTEAL_KSWAPD,
442 	PGSTEAL_DIRECT,
443 	PGSTEAL_KHUGEPAGED,
444 	PGFAULT,
445 	PGMAJFAULT,
446 	PGREFILL,
447 	PGACTIVATE,
448 	PGDEACTIVATE,
449 	PGLAZYFREE,
450 	PGLAZYFREED,
451 #ifdef CONFIG_SWAP
452 	SWPIN_ZERO,
453 	SWPOUT_ZERO,
454 #endif
455 #ifdef CONFIG_ZSWAP
456 	ZSWPIN,
457 	ZSWPOUT,
458 	ZSWPWB,
459 #endif
460 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
461 	THP_FAULT_ALLOC,
462 	THP_COLLAPSE_ALLOC,
463 	THP_SWPOUT,
464 	THP_SWPOUT_FALLBACK,
465 #endif
466 #ifdef CONFIG_NUMA_BALANCING
467 	NUMA_PAGE_MIGRATE,
468 	NUMA_PTE_UPDATES,
469 	NUMA_HINT_FAULTS,
470 #endif
471 };
472 
473 #define NR_MEMCG_EVENTS ARRAY_SIZE(memcg_vm_event_stat)
474 static u8 mem_cgroup_events_index[NR_VM_EVENT_ITEMS] __read_mostly;
475 
init_memcg_events(void)476 static void init_memcg_events(void)
477 {
478 	u8 i;
479 
480 	BUILD_BUG_ON(NR_VM_EVENT_ITEMS >= U8_MAX);
481 
482 	memset(mem_cgroup_events_index, U8_MAX,
483 	       sizeof(mem_cgroup_events_index));
484 
485 	for (i = 0; i < NR_MEMCG_EVENTS; ++i)
486 		mem_cgroup_events_index[memcg_vm_event_stat[i]] = i;
487 }
488 
memcg_events_index(enum vm_event_item idx)489 static inline int memcg_events_index(enum vm_event_item idx)
490 {
491 	return mem_cgroup_events_index[idx];
492 }
493 
494 struct memcg_vmstats_percpu {
495 	/* Stats updates since the last flush */
496 	unsigned int			stats_updates;
497 
498 	/* Cached pointers for fast iteration in memcg_rstat_updated() */
499 	struct memcg_vmstats_percpu	*parent;
500 	struct memcg_vmstats		*vmstats;
501 
502 	/* The above should fit a single cacheline for memcg_rstat_updated() */
503 
504 	/* Local (CPU and cgroup) page state & events */
505 	long			state[MEMCG_VMSTAT_SIZE];
506 	unsigned long		events[NR_MEMCG_EVENTS];
507 
508 	/* Delta calculation for lockless upward propagation */
509 	long			state_prev[MEMCG_VMSTAT_SIZE];
510 	unsigned long		events_prev[NR_MEMCG_EVENTS];
511 } ____cacheline_aligned;
512 
513 struct memcg_vmstats {
514 	/* Aggregated (CPU and subtree) page state & events */
515 	long			state[MEMCG_VMSTAT_SIZE];
516 	unsigned long		events[NR_MEMCG_EVENTS];
517 
518 	/* Non-hierarchical (CPU aggregated) page state & events */
519 	long			state_local[MEMCG_VMSTAT_SIZE];
520 	unsigned long		events_local[NR_MEMCG_EVENTS];
521 
522 	/* Pending child counts during tree propagation */
523 	long			state_pending[MEMCG_VMSTAT_SIZE];
524 	unsigned long		events_pending[NR_MEMCG_EVENTS];
525 
526 	/* Stats updates since the last flush */
527 	atomic64_t		stats_updates;
528 };
529 
530 /*
531  * memcg and lruvec stats flushing
532  *
533  * Many codepaths leading to stats update or read are performance sensitive and
534  * adding stats flushing in such codepaths is not desirable. So, to optimize the
535  * flushing the kernel does:
536  *
537  * 1) Periodically and asynchronously flush the stats every 2 seconds to not let
538  *    rstat update tree grow unbounded.
539  *
540  * 2) Flush the stats synchronously on reader side only when there are more than
541  *    (MEMCG_CHARGE_BATCH * nr_cpus) update events. Though this optimization
542  *    will let stats be out of sync by atmost (MEMCG_CHARGE_BATCH * nr_cpus) but
543  *    only for 2 seconds due to (1).
544  */
545 static void flush_memcg_stats_dwork(struct work_struct *w);
546 static DECLARE_DEFERRABLE_WORK(stats_flush_dwork, flush_memcg_stats_dwork);
547 static u64 flush_last_time;
548 
549 #define FLUSH_TIME (2UL*HZ)
550 
551 /*
552  * Accessors to ensure that preemption is disabled on PREEMPT_RT because it can
553  * not rely on this as part of an acquired spinlock_t lock. These functions are
554  * never used in hardirq context on PREEMPT_RT and therefore disabling preemtion
555  * is sufficient.
556  */
memcg_stats_lock(void)557 static void memcg_stats_lock(void)
558 {
559 	preempt_disable_nested();
560 	VM_WARN_ON_IRQS_ENABLED();
561 }
562 
__memcg_stats_lock(void)563 static void __memcg_stats_lock(void)
564 {
565 	preempt_disable_nested();
566 }
567 
memcg_stats_unlock(void)568 static void memcg_stats_unlock(void)
569 {
570 	preempt_enable_nested();
571 }
572 
573 
memcg_vmstats_needs_flush(struct memcg_vmstats * vmstats)574 static bool memcg_vmstats_needs_flush(struct memcg_vmstats *vmstats)
575 {
576 	return atomic64_read(&vmstats->stats_updates) >
577 		MEMCG_CHARGE_BATCH * num_online_cpus();
578 }
579 
memcg_rstat_updated(struct mem_cgroup * memcg,int val)580 static inline void memcg_rstat_updated(struct mem_cgroup *memcg, int val)
581 {
582 	struct memcg_vmstats_percpu *statc;
583 	int cpu = smp_processor_id();
584 	unsigned int stats_updates;
585 
586 	if (!val)
587 		return;
588 
589 	cgroup_rstat_updated(memcg->css.cgroup, cpu);
590 	statc = this_cpu_ptr(memcg->vmstats_percpu);
591 	for (; statc; statc = statc->parent) {
592 		stats_updates = READ_ONCE(statc->stats_updates) + abs(val);
593 		WRITE_ONCE(statc->stats_updates, stats_updates);
594 		if (stats_updates < MEMCG_CHARGE_BATCH)
595 			continue;
596 
597 		/*
598 		 * If @memcg is already flush-able, increasing stats_updates is
599 		 * redundant. Avoid the overhead of the atomic update.
600 		 */
601 		if (!memcg_vmstats_needs_flush(statc->vmstats))
602 			atomic64_add(stats_updates,
603 				     &statc->vmstats->stats_updates);
604 		WRITE_ONCE(statc->stats_updates, 0);
605 	}
606 }
607 
do_flush_stats(struct mem_cgroup * memcg)608 static void do_flush_stats(struct mem_cgroup *memcg)
609 {
610 	if (mem_cgroup_is_root(memcg))
611 		WRITE_ONCE(flush_last_time, jiffies_64);
612 
613 	cgroup_rstat_flush(memcg->css.cgroup);
614 }
615 
616 /*
617  * mem_cgroup_flush_stats - flush the stats of a memory cgroup subtree
618  * @memcg: root of the subtree to flush
619  *
620  * Flushing is serialized by the underlying global rstat lock. There is also a
621  * minimum amount of work to be done even if there are no stat updates to flush.
622  * Hence, we only flush the stats if the updates delta exceeds a threshold. This
623  * avoids unnecessary work and contention on the underlying lock.
624  */
mem_cgroup_flush_stats(struct mem_cgroup * memcg)625 void mem_cgroup_flush_stats(struct mem_cgroup *memcg)
626 {
627 	if (mem_cgroup_disabled())
628 		return;
629 
630 	if (!memcg)
631 		memcg = root_mem_cgroup;
632 
633 	if (memcg_vmstats_needs_flush(memcg->vmstats))
634 		do_flush_stats(memcg);
635 }
636 
mem_cgroup_flush_stats_ratelimited(struct mem_cgroup * memcg)637 void mem_cgroup_flush_stats_ratelimited(struct mem_cgroup *memcg)
638 {
639 	/* Only flush if the periodic flusher is one full cycle late */
640 	if (time_after64(jiffies_64, READ_ONCE(flush_last_time) + 2*FLUSH_TIME))
641 		mem_cgroup_flush_stats(memcg);
642 }
643 
flush_memcg_stats_dwork(struct work_struct * w)644 static void flush_memcg_stats_dwork(struct work_struct *w)
645 {
646 	/*
647 	 * Deliberately ignore memcg_vmstats_needs_flush() here so that flushing
648 	 * in latency-sensitive paths is as cheap as possible.
649 	 */
650 	do_flush_stats(root_mem_cgroup);
651 	queue_delayed_work(system_unbound_wq, &stats_flush_dwork, FLUSH_TIME);
652 }
653 
memcg_page_state(struct mem_cgroup * memcg,int idx)654 unsigned long memcg_page_state(struct mem_cgroup *memcg, int idx)
655 {
656 	long x;
657 	int i = memcg_stats_index(idx);
658 
659 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
660 		return 0;
661 
662 	x = READ_ONCE(memcg->vmstats->state[i]);
663 #ifdef CONFIG_SMP
664 	if (x < 0)
665 		x = 0;
666 #endif
667 	return x;
668 }
669 EXPORT_SYMBOL_GPL(memcg_page_state);
670 
671 /* For type visibility of memcg_page_state indices */
672 const enum node_stat_item ANDROID_GKI_node_stat_item;
673 EXPORT_SYMBOL_GPL(ANDROID_GKI_node_stat_item);
674 const enum memcg_stat_item ANDROID_GKI_memcg_stat_item;
675 EXPORT_SYMBOL_GPL(ANDROID_GKI_memcg_stat_item);
676 
677 static int memcg_page_state_unit(int item);
678 
679 /*
680  * Normalize the value passed into memcg_rstat_updated() to be in pages. Round
681  * up non-zero sub-page updates to 1 page as zero page updates are ignored.
682  */
memcg_state_val_in_pages(int idx,int val)683 static int memcg_state_val_in_pages(int idx, int val)
684 {
685 	int unit = memcg_page_state_unit(idx);
686 
687 	if (!val || unit == PAGE_SIZE)
688 		return val;
689 	else
690 		return max(val * unit / PAGE_SIZE, 1UL);
691 }
692 
693 /**
694  * __mod_memcg_state - update cgroup memory statistics
695  * @memcg: the memory cgroup
696  * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
697  * @val: delta to add to the counter, can be negative
698  */
__mod_memcg_state(struct mem_cgroup * memcg,enum memcg_stat_item idx,int val)699 void __mod_memcg_state(struct mem_cgroup *memcg, enum memcg_stat_item idx,
700 		       int val)
701 {
702 	int i = memcg_stats_index(idx);
703 
704 	if (mem_cgroup_disabled())
705 		return;
706 
707 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
708 		return;
709 
710 	__this_cpu_add(memcg->vmstats_percpu->state[i], val);
711 	memcg_rstat_updated(memcg, memcg_state_val_in_pages(idx, val));
712 }
713 
714 /* idx can be of type enum memcg_stat_item or node_stat_item. */
memcg_page_state_local(struct mem_cgroup * memcg,int idx)715 unsigned long memcg_page_state_local(struct mem_cgroup *memcg, int idx)
716 {
717 	long x;
718 	int i = memcg_stats_index(idx);
719 
720 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
721 		return 0;
722 
723 	x = READ_ONCE(memcg->vmstats->state_local[i]);
724 #ifdef CONFIG_SMP
725 	if (x < 0)
726 		x = 0;
727 #endif
728 	return x;
729 }
730 
__mod_memcg_lruvec_state(struct lruvec * lruvec,enum node_stat_item idx,int val)731 static void __mod_memcg_lruvec_state(struct lruvec *lruvec,
732 				     enum node_stat_item idx,
733 				     int val)
734 {
735 	struct mem_cgroup_per_node *pn;
736 	struct mem_cgroup *memcg;
737 	int i = memcg_stats_index(idx);
738 
739 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
740 		return;
741 
742 	pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
743 	memcg = pn->memcg;
744 
745 	/*
746 	 * The caller from rmap relies on disabled preemption because they never
747 	 * update their counter from in-interrupt context. For these two
748 	 * counters we check that the update is never performed from an
749 	 * interrupt context while other caller need to have disabled interrupt.
750 	 */
751 	__memcg_stats_lock();
752 	if (IS_ENABLED(CONFIG_DEBUG_VM)) {
753 		switch (idx) {
754 		case NR_ANON_MAPPED:
755 		case NR_FILE_MAPPED:
756 		case NR_ANON_THPS:
757 			WARN_ON_ONCE(!in_task());
758 			break;
759 		default:
760 			VM_WARN_ON_IRQS_ENABLED();
761 		}
762 	}
763 
764 	/* Update memcg */
765 	__this_cpu_add(memcg->vmstats_percpu->state[i], val);
766 
767 	/* Update lruvec */
768 	__this_cpu_add(pn->lruvec_stats_percpu->state[i], val);
769 
770 	memcg_rstat_updated(memcg, memcg_state_val_in_pages(idx, val));
771 	memcg_stats_unlock();
772 }
773 
774 /**
775  * __mod_lruvec_state - update lruvec memory statistics
776  * @lruvec: the lruvec
777  * @idx: the stat item
778  * @val: delta to add to the counter, can be negative
779  *
780  * The lruvec is the intersection of the NUMA node and a cgroup. This
781  * function updates the all three counters that are affected by a
782  * change of state at this level: per-node, per-cgroup, per-lruvec.
783  */
__mod_lruvec_state(struct lruvec * lruvec,enum node_stat_item idx,int val)784 void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
785 			int val)
786 {
787 	/* Update node */
788 	__mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
789 
790 	/* Update memcg and lruvec */
791 	if (!mem_cgroup_disabled())
792 		__mod_memcg_lruvec_state(lruvec, idx, val);
793 }
794 EXPORT_SYMBOL_GPL(__mod_lruvec_state);
795 
__lruvec_stat_mod_folio(struct folio * folio,enum node_stat_item idx,int val)796 void __lruvec_stat_mod_folio(struct folio *folio, enum node_stat_item idx,
797 			     int val)
798 {
799 	struct mem_cgroup *memcg;
800 	pg_data_t *pgdat = folio_pgdat(folio);
801 	struct lruvec *lruvec;
802 
803 	rcu_read_lock();
804 	memcg = folio_memcg(folio);
805 	/* Untracked pages have no memcg, no lruvec. Update only the node */
806 	if (!memcg) {
807 		rcu_read_unlock();
808 		__mod_node_page_state(pgdat, idx, val);
809 		return;
810 	}
811 
812 	lruvec = mem_cgroup_lruvec(memcg, pgdat);
813 	__mod_lruvec_state(lruvec, idx, val);
814 	rcu_read_unlock();
815 }
816 EXPORT_SYMBOL(__lruvec_stat_mod_folio);
817 
__mod_lruvec_kmem_state(void * p,enum node_stat_item idx,int val)818 void __mod_lruvec_kmem_state(void *p, enum node_stat_item idx, int val)
819 {
820 	pg_data_t *pgdat = page_pgdat(virt_to_page(p));
821 	struct mem_cgroup *memcg;
822 	struct lruvec *lruvec;
823 
824 	rcu_read_lock();
825 	memcg = mem_cgroup_from_slab_obj(p);
826 
827 	/*
828 	 * Untracked pages have no memcg, no lruvec. Update only the
829 	 * node. If we reparent the slab objects to the root memcg,
830 	 * when we free the slab object, we need to update the per-memcg
831 	 * vmstats to keep it correct for the root memcg.
832 	 */
833 	if (!memcg) {
834 		__mod_node_page_state(pgdat, idx, val);
835 	} else {
836 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
837 		__mod_lruvec_state(lruvec, idx, val);
838 	}
839 	rcu_read_unlock();
840 }
841 
842 /**
843  * __count_memcg_events - account VM events in a cgroup
844  * @memcg: the memory cgroup
845  * @idx: the event item
846  * @count: the number of events that occurred
847  */
__count_memcg_events(struct mem_cgroup * memcg,enum vm_event_item idx,unsigned long count)848 void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
849 			  unsigned long count)
850 {
851 	int i = memcg_events_index(idx);
852 
853 	if (mem_cgroup_disabled())
854 		return;
855 
856 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, idx))
857 		return;
858 
859 	memcg_stats_lock();
860 	__this_cpu_add(memcg->vmstats_percpu->events[i], count);
861 	memcg_rstat_updated(memcg, count);
862 	memcg_stats_unlock();
863 }
864 
memcg_events(struct mem_cgroup * memcg,int event)865 unsigned long memcg_events(struct mem_cgroup *memcg, int event)
866 {
867 	int i = memcg_events_index(event);
868 
869 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, event))
870 		return 0;
871 
872 	return READ_ONCE(memcg->vmstats->events[i]);
873 }
874 
memcg_events_local(struct mem_cgroup * memcg,int event)875 unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
876 {
877 	int i = memcg_events_index(event);
878 
879 	if (WARN_ONCE(BAD_STAT_IDX(i), "%s: missing stat item %d\n", __func__, event))
880 		return 0;
881 
882 	return READ_ONCE(memcg->vmstats->events_local[i]);
883 }
884 
mem_cgroup_from_task(struct task_struct * p)885 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
886 {
887 	/*
888 	 * mm_update_next_owner() may clear mm->owner to NULL
889 	 * if it races with swapoff, page migration, etc.
890 	 * So this can be called with p == NULL.
891 	 */
892 	if (unlikely(!p))
893 		return NULL;
894 
895 	return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
896 }
897 EXPORT_SYMBOL(mem_cgroup_from_task);
898 
active_memcg(void)899 static __always_inline struct mem_cgroup *active_memcg(void)
900 {
901 	if (!in_task())
902 		return this_cpu_read(int_active_memcg);
903 	else
904 		return current->active_memcg;
905 }
906 
907 /**
908  * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
909  * @mm: mm from which memcg should be extracted. It can be NULL.
910  *
911  * Obtain a reference on mm->memcg and returns it if successful. If mm
912  * is NULL, then the memcg is chosen as follows:
913  * 1) The active memcg, if set.
914  * 2) current->mm->memcg, if available
915  * 3) root memcg
916  * If mem_cgroup is disabled, NULL is returned.
917  */
get_mem_cgroup_from_mm(struct mm_struct * mm)918 struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
919 {
920 	struct mem_cgroup *memcg;
921 
922 	if (mem_cgroup_disabled())
923 		return NULL;
924 
925 	/*
926 	 * Page cache insertions can happen without an
927 	 * actual mm context, e.g. during disk probing
928 	 * on boot, loopback IO, acct() writes etc.
929 	 *
930 	 * No need to css_get on root memcg as the reference
931 	 * counting is disabled on the root level in the
932 	 * cgroup core. See CSS_NO_REF.
933 	 */
934 	if (unlikely(!mm)) {
935 		memcg = active_memcg();
936 		if (unlikely(memcg)) {
937 			/* remote memcg must hold a ref */
938 			css_get(&memcg->css);
939 			return memcg;
940 		}
941 		mm = current->mm;
942 		if (unlikely(!mm))
943 			return root_mem_cgroup;
944 	}
945 
946 	rcu_read_lock();
947 	do {
948 		memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
949 		if (unlikely(!memcg))
950 			memcg = root_mem_cgroup;
951 	} while (!css_tryget(&memcg->css));
952 	rcu_read_unlock();
953 	return memcg;
954 }
955 EXPORT_SYMBOL(get_mem_cgroup_from_mm);
956 
957 /**
958  * get_mem_cgroup_from_current - Obtain a reference on current task's memcg.
959  */
get_mem_cgroup_from_current(void)960 struct mem_cgroup *get_mem_cgroup_from_current(void)
961 {
962 	struct mem_cgroup *memcg;
963 
964 	if (mem_cgroup_disabled())
965 		return NULL;
966 
967 again:
968 	rcu_read_lock();
969 	memcg = mem_cgroup_from_task(current);
970 	if (!css_tryget(&memcg->css)) {
971 		rcu_read_unlock();
972 		goto again;
973 	}
974 	rcu_read_unlock();
975 	return memcg;
976 }
977 
978 /**
979  * get_mem_cgroup_from_folio - Obtain a reference on a given folio's memcg.
980  * @folio: folio from which memcg should be extracted.
981  */
get_mem_cgroup_from_folio(struct folio * folio)982 struct mem_cgroup *get_mem_cgroup_from_folio(struct folio *folio)
983 {
984 	struct mem_cgroup *memcg = folio_memcg(folio);
985 
986 	if (mem_cgroup_disabled())
987 		return NULL;
988 
989 	rcu_read_lock();
990 	if (!memcg || WARN_ON_ONCE(!css_tryget(&memcg->css)))
991 		memcg = root_mem_cgroup;
992 	rcu_read_unlock();
993 	return memcg;
994 }
995 
996 /**
997  * mem_cgroup_iter - iterate over memory cgroup hierarchy
998  * @root: hierarchy root
999  * @prev: previously returned memcg, NULL on first invocation
1000  * @reclaim: cookie for shared reclaim walks, NULL for full walks
1001  *
1002  * Returns references to children of the hierarchy below @root, or
1003  * @root itself, or %NULL after a full round-trip.
1004  *
1005  * Caller must pass the return value in @prev on subsequent
1006  * invocations for reference counting, or use mem_cgroup_iter_break()
1007  * to cancel a hierarchy walk before the round-trip is complete.
1008  *
1009  * Reclaimers can specify a node in @reclaim to divide up the memcgs
1010  * in the hierarchy among all concurrent reclaimers operating on the
1011  * same node.
1012  */
mem_cgroup_iter(struct mem_cgroup * root,struct mem_cgroup * prev,struct mem_cgroup_reclaim_cookie * reclaim)1013 struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1014 				   struct mem_cgroup *prev,
1015 				   struct mem_cgroup_reclaim_cookie *reclaim)
1016 {
1017 	struct mem_cgroup_reclaim_iter *iter;
1018 	struct cgroup_subsys_state *css;
1019 	struct mem_cgroup *pos;
1020 	struct mem_cgroup *next;
1021 
1022 	if (mem_cgroup_disabled())
1023 		return NULL;
1024 
1025 	if (!root)
1026 		root = root_mem_cgroup;
1027 
1028 	rcu_read_lock();
1029 restart:
1030 	next = NULL;
1031 
1032 	if (reclaim) {
1033 		int gen;
1034 		int nid = reclaim->pgdat->node_id;
1035 
1036 		iter = &root->nodeinfo[nid]->iter;
1037 		gen = atomic_read(&iter->generation);
1038 
1039 		/*
1040 		 * On start, join the current reclaim iteration cycle.
1041 		 * Exit when a concurrent walker completes it.
1042 		 */
1043 		if (!prev)
1044 			reclaim->generation = gen;
1045 		else if (reclaim->generation != gen)
1046 			goto out_unlock;
1047 
1048 		pos = READ_ONCE(iter->position);
1049 	} else
1050 		pos = prev;
1051 
1052 	css = pos ? &pos->css : NULL;
1053 
1054 	while ((css = css_next_descendant_pre(css, &root->css))) {
1055 		/*
1056 		 * Verify the css and acquire a reference.  The root
1057 		 * is provided by the caller, so we know it's alive
1058 		 * and kicking, and don't take an extra reference.
1059 		 */
1060 		if (css == &root->css || css_tryget(css))
1061 			break;
1062 	}
1063 
1064 	next = mem_cgroup_from_css(css);
1065 
1066 	if (reclaim) {
1067 		/*
1068 		 * The position could have already been updated by a competing
1069 		 * thread, so check that the value hasn't changed since we read
1070 		 * it to avoid reclaiming from the same cgroup twice.
1071 		 */
1072 		if (cmpxchg(&iter->position, pos, next) != pos) {
1073 			if (css && css != &root->css)
1074 				css_put(css);
1075 			goto restart;
1076 		}
1077 
1078 		if (!next) {
1079 			atomic_inc(&iter->generation);
1080 
1081 			/*
1082 			 * Reclaimers share the hierarchy walk, and a
1083 			 * new one might jump in right at the end of
1084 			 * the hierarchy - make sure they see at least
1085 			 * one group and restart from the beginning.
1086 			 */
1087 			if (!prev)
1088 				goto restart;
1089 		}
1090 	}
1091 
1092 out_unlock:
1093 	rcu_read_unlock();
1094 	if (prev && prev != root)
1095 		css_put(&prev->css);
1096 
1097 	return next;
1098 }
1099 
1100 /**
1101  * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1102  * @root: hierarchy root
1103  * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1104  */
mem_cgroup_iter_break(struct mem_cgroup * root,struct mem_cgroup * prev)1105 void mem_cgroup_iter_break(struct mem_cgroup *root,
1106 			   struct mem_cgroup *prev)
1107 {
1108 	if (!root)
1109 		root = root_mem_cgroup;
1110 	if (prev && prev != root)
1111 		css_put(&prev->css);
1112 }
1113 
__invalidate_reclaim_iterators(struct mem_cgroup * from,struct mem_cgroup * dead_memcg)1114 static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1115 					struct mem_cgroup *dead_memcg)
1116 {
1117 	struct mem_cgroup_reclaim_iter *iter;
1118 	struct mem_cgroup_per_node *mz;
1119 	int nid;
1120 
1121 	for_each_node(nid) {
1122 		mz = from->nodeinfo[nid];
1123 		iter = &mz->iter;
1124 		cmpxchg(&iter->position, dead_memcg, NULL);
1125 	}
1126 }
1127 
invalidate_reclaim_iterators(struct mem_cgroup * dead_memcg)1128 static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1129 {
1130 	struct mem_cgroup *memcg = dead_memcg;
1131 	struct mem_cgroup *last;
1132 
1133 	do {
1134 		__invalidate_reclaim_iterators(memcg, dead_memcg);
1135 		last = memcg;
1136 	} while ((memcg = parent_mem_cgroup(memcg)));
1137 
1138 	/*
1139 	 * When cgroup1 non-hierarchy mode is used,
1140 	 * parent_mem_cgroup() does not walk all the way up to the
1141 	 * cgroup root (root_mem_cgroup). So we have to handle
1142 	 * dead_memcg from cgroup root separately.
1143 	 */
1144 	if (!mem_cgroup_is_root(last))
1145 		__invalidate_reclaim_iterators(root_mem_cgroup,
1146 						dead_memcg);
1147 }
1148 
1149 /**
1150  * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1151  * @memcg: hierarchy root
1152  * @fn: function to call for each task
1153  * @arg: argument passed to @fn
1154  *
1155  * This function iterates over tasks attached to @memcg or to any of its
1156  * descendants and calls @fn for each task. If @fn returns a non-zero
1157  * value, the function breaks the iteration loop. Otherwise, it will iterate
1158  * over all tasks and return 0.
1159  *
1160  * This function must not be called for the root memory cgroup.
1161  */
mem_cgroup_scan_tasks(struct mem_cgroup * memcg,int (* fn)(struct task_struct *,void *),void * arg)1162 void mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1163 			   int (*fn)(struct task_struct *, void *), void *arg)
1164 {
1165 	struct mem_cgroup *iter;
1166 	int ret = 0;
1167 
1168 	BUG_ON(mem_cgroup_is_root(memcg));
1169 
1170 	for_each_mem_cgroup_tree(iter, memcg) {
1171 		struct css_task_iter it;
1172 		struct task_struct *task;
1173 
1174 		css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
1175 		while (!ret && (task = css_task_iter_next(&it))) {
1176 			ret = fn(task, arg);
1177 			/* Avoid potential softlockup warning */
1178 			cond_resched();
1179 		}
1180 		css_task_iter_end(&it);
1181 		if (ret) {
1182 			mem_cgroup_iter_break(memcg, iter);
1183 			break;
1184 		}
1185 	}
1186 }
1187 
1188 #ifdef CONFIG_DEBUG_VM
lruvec_memcg_debug(struct lruvec * lruvec,struct folio * folio)1189 void lruvec_memcg_debug(struct lruvec *lruvec, struct folio *folio)
1190 {
1191 	struct mem_cgroup *memcg;
1192 
1193 	if (mem_cgroup_disabled())
1194 		return;
1195 
1196 	memcg = folio_memcg(folio);
1197 
1198 	if (!memcg)
1199 		VM_BUG_ON_FOLIO(!mem_cgroup_is_root(lruvec_memcg(lruvec)), folio);
1200 	else
1201 		VM_BUG_ON_FOLIO(lruvec_memcg(lruvec) != memcg, folio);
1202 }
1203 #endif
1204 
1205 /**
1206  * folio_lruvec_lock - Lock the lruvec for a folio.
1207  * @folio: Pointer to the folio.
1208  *
1209  * These functions are safe to use under any of the following conditions:
1210  * - folio locked
1211  * - folio_test_lru false
1212  * - folio_memcg_lock()
1213  * - folio frozen (refcount of 0)
1214  *
1215  * Return: The lruvec this folio is on with its lock held.
1216  */
folio_lruvec_lock(struct folio * folio)1217 struct lruvec *folio_lruvec_lock(struct folio *folio)
1218 {
1219 	struct lruvec *lruvec = folio_lruvec(folio);
1220 
1221 	spin_lock(&lruvec->lru_lock);
1222 	lruvec_memcg_debug(lruvec, folio);
1223 
1224 	return lruvec;
1225 }
1226 
1227 /**
1228  * folio_lruvec_lock_irq - Lock the lruvec for a folio.
1229  * @folio: Pointer to the folio.
1230  *
1231  * These functions are safe to use under any of the following conditions:
1232  * - folio locked
1233  * - folio_test_lru false
1234  * - folio_memcg_lock()
1235  * - folio frozen (refcount of 0)
1236  *
1237  * Return: The lruvec this folio is on with its lock held and interrupts
1238  * disabled.
1239  */
folio_lruvec_lock_irq(struct folio * folio)1240 struct lruvec *folio_lruvec_lock_irq(struct folio *folio)
1241 {
1242 	struct lruvec *lruvec = folio_lruvec(folio);
1243 
1244 	spin_lock_irq(&lruvec->lru_lock);
1245 	lruvec_memcg_debug(lruvec, folio);
1246 
1247 	return lruvec;
1248 }
1249 
1250 /**
1251  * folio_lruvec_lock_irqsave - Lock the lruvec for a folio.
1252  * @folio: Pointer to the folio.
1253  * @flags: Pointer to irqsave flags.
1254  *
1255  * These functions are safe to use under any of the following conditions:
1256  * - folio locked
1257  * - folio_test_lru false
1258  * - folio_memcg_lock()
1259  * - folio frozen (refcount of 0)
1260  *
1261  * Return: The lruvec this folio is on with its lock held and interrupts
1262  * disabled.
1263  */
folio_lruvec_lock_irqsave(struct folio * folio,unsigned long * flags)1264 struct lruvec *folio_lruvec_lock_irqsave(struct folio *folio,
1265 		unsigned long *flags)
1266 {
1267 	struct lruvec *lruvec = folio_lruvec(folio);
1268 
1269 	spin_lock_irqsave(&lruvec->lru_lock, *flags);
1270 	lruvec_memcg_debug(lruvec, folio);
1271 
1272 	return lruvec;
1273 }
1274 
do_traversal_all_lruvec(int (* callback)(struct mem_cgroup * memcg,struct lruvec * lruvec,void * private),void * private)1275 void do_traversal_all_lruvec(int (*callback)(struct mem_cgroup *memcg,
1276 					     struct lruvec *lruvec,
1277 					     void *private),
1278 			     void *private)
1279 {
1280 	pg_data_t *pgdat;
1281 	int ret;
1282 
1283 	for_each_online_pgdat(pgdat) {
1284 		struct mem_cgroup *memcg = NULL;
1285 
1286 		memcg = mem_cgroup_iter(NULL, NULL, NULL);
1287 		do {
1288 			struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
1289 
1290 			ret = callback(memcg, lruvec, private);
1291 			if (ret) {
1292 				mem_cgroup_iter_break(NULL, memcg);
1293 				break;
1294 			}
1295 
1296 			memcg = mem_cgroup_iter(NULL, memcg, NULL);
1297 		} while (memcg);
1298 	}
1299 }
1300 EXPORT_SYMBOL_GPL(do_traversal_all_lruvec);
1301 
1302 
1303 /**
1304  * mem_cgroup_update_lru_size - account for adding or removing an lru page
1305  * @lruvec: mem_cgroup per zone lru vector
1306  * @lru: index of lru list the page is sitting on
1307  * @zid: zone id of the accounted pages
1308  * @nr_pages: positive when adding or negative when removing
1309  *
1310  * This function must be called under lru_lock, just before a page is added
1311  * to or just after a page is removed from an lru list.
1312  */
mem_cgroup_update_lru_size(struct lruvec * lruvec,enum lru_list lru,int zid,int nr_pages)1313 void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1314 				int zid, int nr_pages)
1315 {
1316 	struct mem_cgroup_per_node *mz;
1317 	unsigned long *lru_size;
1318 	long size;
1319 
1320 	if (mem_cgroup_disabled())
1321 		return;
1322 
1323 	mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1324 	lru_size = &mz->lru_zone_size[zid][lru];
1325 
1326 	if (nr_pages < 0)
1327 		*lru_size += nr_pages;
1328 
1329 	size = *lru_size;
1330 	if (WARN_ONCE(size < 0,
1331 		"%s(%p, %d, %d): lru_size %ld\n",
1332 		__func__, lruvec, lru, nr_pages, size)) {
1333 		VM_BUG_ON(1);
1334 		*lru_size = 0;
1335 	}
1336 
1337 	if (nr_pages > 0)
1338 		*lru_size += nr_pages;
1339 }
1340 EXPORT_SYMBOL_GPL(mem_cgroup_update_lru_size);
1341 
1342 /**
1343  * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1344  * @memcg: the memory cgroup
1345  *
1346  * Returns the maximum amount of memory @mem can be charged with, in
1347  * pages.
1348  */
mem_cgroup_margin(struct mem_cgroup * memcg)1349 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1350 {
1351 	unsigned long margin = 0;
1352 	unsigned long count;
1353 	unsigned long limit;
1354 
1355 	count = page_counter_read(&memcg->memory);
1356 	limit = READ_ONCE(memcg->memory.max);
1357 	if (count < limit)
1358 		margin = limit - count;
1359 
1360 	if (do_memsw_account()) {
1361 		count = page_counter_read(&memcg->memsw);
1362 		limit = READ_ONCE(memcg->memsw.max);
1363 		if (count < limit)
1364 			margin = min(margin, limit - count);
1365 		else
1366 			margin = 0;
1367 	}
1368 
1369 	return margin;
1370 }
1371 
1372 struct memory_stat {
1373 	const char *name;
1374 	unsigned int idx;
1375 };
1376 
1377 static const struct memory_stat memory_stats[] = {
1378 	{ "anon",			NR_ANON_MAPPED			},
1379 	{ "file",			NR_FILE_PAGES			},
1380 	{ "kernel",			MEMCG_KMEM			},
1381 	{ "kernel_stack",		NR_KERNEL_STACK_KB		},
1382 	{ "pagetables",			NR_PAGETABLE			},
1383 	{ "sec_pagetables",		NR_SECONDARY_PAGETABLE		},
1384 	{ "percpu",			MEMCG_PERCPU_B			},
1385 	{ "sock",			MEMCG_SOCK			},
1386 	{ "vmalloc",			MEMCG_VMALLOC			},
1387 	{ "shmem",			NR_SHMEM			},
1388 #ifdef CONFIG_ZSWAP
1389 	{ "zswap",			MEMCG_ZSWAP_B			},
1390 	{ "zswapped",			MEMCG_ZSWAPPED			},
1391 #endif
1392 	{ "file_mapped",		NR_FILE_MAPPED			},
1393 	{ "file_dirty",			NR_FILE_DIRTY			},
1394 	{ "file_writeback",		NR_WRITEBACK			},
1395 #ifdef CONFIG_SWAP
1396 	{ "swapcached",			NR_SWAPCACHE			},
1397 #endif
1398 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1399 	{ "anon_thp",			NR_ANON_THPS			},
1400 	{ "file_thp",			NR_FILE_THPS			},
1401 	{ "shmem_thp",			NR_SHMEM_THPS			},
1402 #endif
1403 	{ "inactive_anon",		NR_INACTIVE_ANON		},
1404 	{ "active_anon",		NR_ACTIVE_ANON			},
1405 	{ "inactive_file",		NR_INACTIVE_FILE		},
1406 	{ "active_file",		NR_ACTIVE_FILE			},
1407 	{ "unevictable",		NR_UNEVICTABLE			},
1408 	{ "slab_reclaimable",		NR_SLAB_RECLAIMABLE_B		},
1409 	{ "slab_unreclaimable",		NR_SLAB_UNRECLAIMABLE_B		},
1410 
1411 	/* The memory events */
1412 	{ "workingset_refault_anon",	WORKINGSET_REFAULT_ANON		},
1413 	{ "workingset_refault_file",	WORKINGSET_REFAULT_FILE		},
1414 	{ "workingset_activate_anon",	WORKINGSET_ACTIVATE_ANON	},
1415 	{ "workingset_activate_file",	WORKINGSET_ACTIVATE_FILE	},
1416 	{ "workingset_restore_anon",	WORKINGSET_RESTORE_ANON		},
1417 	{ "workingset_restore_file",	WORKINGSET_RESTORE_FILE		},
1418 	{ "workingset_nodereclaim",	WORKINGSET_NODERECLAIM		},
1419 
1420 	{ "pgdemote_kswapd",		PGDEMOTE_KSWAPD		},
1421 	{ "pgdemote_direct",		PGDEMOTE_DIRECT		},
1422 	{ "pgdemote_khugepaged",	PGDEMOTE_KHUGEPAGED	},
1423 #ifdef CONFIG_NUMA_BALANCING
1424 	{ "pgpromote_success",		PGPROMOTE_SUCCESS	},
1425 #endif
1426 };
1427 
1428 /* The actual unit of the state item, not the same as the output unit */
memcg_page_state_unit(int item)1429 static int memcg_page_state_unit(int item)
1430 {
1431 	switch (item) {
1432 	case MEMCG_PERCPU_B:
1433 	case MEMCG_ZSWAP_B:
1434 	case NR_SLAB_RECLAIMABLE_B:
1435 	case NR_SLAB_UNRECLAIMABLE_B:
1436 		return 1;
1437 	case NR_KERNEL_STACK_KB:
1438 		return SZ_1K;
1439 	default:
1440 		return PAGE_SIZE;
1441 	}
1442 }
1443 
1444 /* Translate stat items to the correct unit for memory.stat output */
memcg_page_state_output_unit(int item)1445 static int memcg_page_state_output_unit(int item)
1446 {
1447 	/*
1448 	 * Workingset state is actually in pages, but we export it to userspace
1449 	 * as a scalar count of events, so special case it here.
1450 	 *
1451 	 * Demotion and promotion activities are exported in pages, consistent
1452 	 * with their global counterparts.
1453 	 */
1454 	switch (item) {
1455 	case WORKINGSET_REFAULT_ANON:
1456 	case WORKINGSET_REFAULT_FILE:
1457 	case WORKINGSET_ACTIVATE_ANON:
1458 	case WORKINGSET_ACTIVATE_FILE:
1459 	case WORKINGSET_RESTORE_ANON:
1460 	case WORKINGSET_RESTORE_FILE:
1461 	case WORKINGSET_NODERECLAIM:
1462 	case PGDEMOTE_KSWAPD:
1463 	case PGDEMOTE_DIRECT:
1464 	case PGDEMOTE_KHUGEPAGED:
1465 #ifdef CONFIG_NUMA_BALANCING
1466 	case PGPROMOTE_SUCCESS:
1467 #endif
1468 		return 1;
1469 	default:
1470 		return memcg_page_state_unit(item);
1471 	}
1472 }
1473 
memcg_page_state_output(struct mem_cgroup * memcg,int item)1474 unsigned long memcg_page_state_output(struct mem_cgroup *memcg, int item)
1475 {
1476 	return memcg_page_state(memcg, item) *
1477 		memcg_page_state_output_unit(item);
1478 }
1479 
memcg_page_state_local_output(struct mem_cgroup * memcg,int item)1480 unsigned long memcg_page_state_local_output(struct mem_cgroup *memcg, int item)
1481 {
1482 	return memcg_page_state_local(memcg, item) *
1483 		memcg_page_state_output_unit(item);
1484 }
1485 
memcg_stat_format(struct mem_cgroup * memcg,struct seq_buf * s)1486 static void memcg_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1487 {
1488 	int i;
1489 
1490 	/*
1491 	 * Provide statistics on the state of the memory subsystem as
1492 	 * well as cumulative event counters that show past behavior.
1493 	 *
1494 	 * This list is ordered following a combination of these gradients:
1495 	 * 1) generic big picture -> specifics and details
1496 	 * 2) reflecting userspace activity -> reflecting kernel heuristics
1497 	 *
1498 	 * Current memory state:
1499 	 */
1500 	mem_cgroup_flush_stats(memcg);
1501 
1502 	for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
1503 		u64 size;
1504 
1505 		size = memcg_page_state_output(memcg, memory_stats[i].idx);
1506 		seq_buf_printf(s, "%s %llu\n", memory_stats[i].name, size);
1507 
1508 		if (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {
1509 			size += memcg_page_state_output(memcg,
1510 							NR_SLAB_RECLAIMABLE_B);
1511 			seq_buf_printf(s, "slab %llu\n", size);
1512 		}
1513 	}
1514 
1515 	/* Accumulated memory events */
1516 	seq_buf_printf(s, "pgscan %lu\n",
1517 		       memcg_events(memcg, PGSCAN_KSWAPD) +
1518 		       memcg_events(memcg, PGSCAN_DIRECT) +
1519 		       memcg_events(memcg, PGSCAN_KHUGEPAGED));
1520 	seq_buf_printf(s, "pgsteal %lu\n",
1521 		       memcg_events(memcg, PGSTEAL_KSWAPD) +
1522 		       memcg_events(memcg, PGSTEAL_DIRECT) +
1523 		       memcg_events(memcg, PGSTEAL_KHUGEPAGED));
1524 
1525 	for (i = 0; i < ARRAY_SIZE(memcg_vm_event_stat); i++) {
1526 #ifdef CONFIG_MEMCG_V1
1527 		if (memcg_vm_event_stat[i] == PGPGIN ||
1528 		    memcg_vm_event_stat[i] == PGPGOUT)
1529 			continue;
1530 #endif
1531 		seq_buf_printf(s, "%s %lu\n",
1532 			       vm_event_name(memcg_vm_event_stat[i]),
1533 			       memcg_events(memcg, memcg_vm_event_stat[i]));
1534 	}
1535 }
1536 
memory_stat_format(struct mem_cgroup * memcg,struct seq_buf * s)1537 static void memory_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1538 {
1539 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1540 		memcg_stat_format(memcg, s);
1541 	else
1542 		memcg1_stat_format(memcg, s);
1543 	if (seq_buf_has_overflowed(s))
1544 		pr_warn("%s: Warning, stat buffer overflow, please report\n", __func__);
1545 }
1546 
1547 /**
1548  * mem_cgroup_print_oom_context: Print OOM information relevant to
1549  * memory controller.
1550  * @memcg: The memory cgroup that went over limit
1551  * @p: Task that is going to be killed
1552  *
1553  * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1554  * enabled
1555  */
mem_cgroup_print_oom_context(struct mem_cgroup * memcg,struct task_struct * p)1556 void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1557 {
1558 	rcu_read_lock();
1559 
1560 	if (memcg) {
1561 		pr_cont(",oom_memcg=");
1562 		pr_cont_cgroup_path(memcg->css.cgroup);
1563 	} else
1564 		pr_cont(",global_oom");
1565 	if (p) {
1566 		pr_cont(",task_memcg=");
1567 		pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1568 	}
1569 	rcu_read_unlock();
1570 }
1571 
1572 /**
1573  * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1574  * memory controller.
1575  * @memcg: The memory cgroup that went over limit
1576  */
mem_cgroup_print_oom_meminfo(struct mem_cgroup * memcg)1577 void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
1578 {
1579 	/* Use static buffer, for the caller is holding oom_lock. */
1580 	static char buf[PAGE_SIZE];
1581 	struct seq_buf s;
1582 
1583 	lockdep_assert_held(&oom_lock);
1584 
1585 	pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1586 		K((u64)page_counter_read(&memcg->memory)),
1587 		K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
1588 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1589 		pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1590 			K((u64)page_counter_read(&memcg->swap)),
1591 			K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
1592 #ifdef CONFIG_MEMCG_V1
1593 	else {
1594 		pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1595 			K((u64)page_counter_read(&memcg->memsw)),
1596 			K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1597 		pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1598 			K((u64)page_counter_read(&memcg->kmem)),
1599 			K((u64)memcg->kmem.max), memcg->kmem.failcnt);
1600 	}
1601 #endif
1602 
1603 	pr_info("Memory cgroup stats for ");
1604 	pr_cont_cgroup_path(memcg->css.cgroup);
1605 	pr_cont(":");
1606 	seq_buf_init(&s, buf, sizeof(buf));
1607 	memory_stat_format(memcg, &s);
1608 	seq_buf_do_printk(&s, KERN_INFO);
1609 }
1610 
1611 /*
1612  * Return the memory (and swap, if configured) limit for a memcg.
1613  */
mem_cgroup_get_max(struct mem_cgroup * memcg)1614 unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
1615 {
1616 	unsigned long max = READ_ONCE(memcg->memory.max);
1617 
1618 	if (do_memsw_account()) {
1619 		if (mem_cgroup_swappiness(memcg)) {
1620 			/* Calculate swap excess capacity from memsw limit */
1621 			unsigned long swap = READ_ONCE(memcg->memsw.max) - max;
1622 
1623 			max += min(swap, (unsigned long)total_swap_pages);
1624 		}
1625 	} else {
1626 		if (mem_cgroup_swappiness(memcg))
1627 			max += min(READ_ONCE(memcg->swap.max),
1628 				   (unsigned long)total_swap_pages);
1629 	}
1630 	return max;
1631 }
1632 
mem_cgroup_size(struct mem_cgroup * memcg)1633 unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1634 {
1635 	return page_counter_read(&memcg->memory);
1636 }
1637 
mem_cgroup_out_of_memory(struct mem_cgroup * memcg,gfp_t gfp_mask,int order)1638 static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1639 				     int order)
1640 {
1641 	struct oom_control oc = {
1642 		.zonelist = NULL,
1643 		.nodemask = NULL,
1644 		.memcg = memcg,
1645 		.gfp_mask = gfp_mask,
1646 		.order = order,
1647 	};
1648 	bool ret = true;
1649 
1650 	if (mutex_lock_killable(&oom_lock))
1651 		return true;
1652 
1653 	if (mem_cgroup_margin(memcg) >= (1 << order))
1654 		goto unlock;
1655 
1656 	/*
1657 	 * A few threads which were not waiting at mutex_lock_killable() can
1658 	 * fail to bail out. Therefore, check again after holding oom_lock.
1659 	 */
1660 	ret = task_is_dying() || out_of_memory(&oc);
1661 
1662 unlock:
1663 	mutex_unlock(&oom_lock);
1664 	return ret;
1665 }
1666 
1667 /*
1668  * Returns true if successfully killed one or more processes. Though in some
1669  * corner cases it can return true even without killing any process.
1670  */
mem_cgroup_oom(struct mem_cgroup * memcg,gfp_t mask,int order)1671 static bool mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
1672 {
1673 	bool locked, ret;
1674 
1675 	if (order > PAGE_ALLOC_COSTLY_ORDER)
1676 		return false;
1677 
1678 	memcg_memory_event(memcg, MEMCG_OOM);
1679 
1680 	if (!memcg1_oom_prepare(memcg, &locked))
1681 		return false;
1682 
1683 	ret = mem_cgroup_out_of_memory(memcg, mask, order);
1684 
1685 	memcg1_oom_finish(memcg, locked);
1686 
1687 	return ret;
1688 }
1689 
1690 /**
1691  * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
1692  * @victim: task to be killed by the OOM killer
1693  * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
1694  *
1695  * Returns a pointer to a memory cgroup, which has to be cleaned up
1696  * by killing all belonging OOM-killable tasks.
1697  *
1698  * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
1699  */
mem_cgroup_get_oom_group(struct task_struct * victim,struct mem_cgroup * oom_domain)1700 struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
1701 					    struct mem_cgroup *oom_domain)
1702 {
1703 	struct mem_cgroup *oom_group = NULL;
1704 	struct mem_cgroup *memcg;
1705 
1706 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
1707 		return NULL;
1708 
1709 	if (!oom_domain)
1710 		oom_domain = root_mem_cgroup;
1711 
1712 	rcu_read_lock();
1713 
1714 	memcg = mem_cgroup_from_task(victim);
1715 	if (mem_cgroup_is_root(memcg))
1716 		goto out;
1717 
1718 	/*
1719 	 * If the victim task has been asynchronously moved to a different
1720 	 * memory cgroup, we might end up killing tasks outside oom_domain.
1721 	 * In this case it's better to ignore memory.group.oom.
1722 	 */
1723 	if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
1724 		goto out;
1725 
1726 	/*
1727 	 * Traverse the memory cgroup hierarchy from the victim task's
1728 	 * cgroup up to the OOMing cgroup (or root) to find the
1729 	 * highest-level memory cgroup with oom.group set.
1730 	 */
1731 	for (; memcg; memcg = parent_mem_cgroup(memcg)) {
1732 		if (READ_ONCE(memcg->oom_group))
1733 			oom_group = memcg;
1734 
1735 		if (memcg == oom_domain)
1736 			break;
1737 	}
1738 
1739 	if (oom_group)
1740 		css_get(&oom_group->css);
1741 out:
1742 	rcu_read_unlock();
1743 
1744 	return oom_group;
1745 }
1746 
mem_cgroup_print_oom_group(struct mem_cgroup * memcg)1747 void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
1748 {
1749 	pr_info("Tasks in ");
1750 	pr_cont_cgroup_path(memcg->css.cgroup);
1751 	pr_cont(" are going to be killed due to memory.oom.group set\n");
1752 }
1753 
1754 struct memcg_stock_pcp {
1755 	local_lock_t stock_lock;
1756 	struct mem_cgroup *cached; /* this never be root cgroup */
1757 	unsigned int nr_pages;
1758 
1759 	struct obj_cgroup *cached_objcg;
1760 	struct pglist_data *cached_pgdat;
1761 	unsigned int nr_bytes;
1762 	int nr_slab_reclaimable_b;
1763 	int nr_slab_unreclaimable_b;
1764 
1765 	struct work_struct work;
1766 	unsigned long flags;
1767 #define FLUSHING_CACHED_CHARGE	0
1768 };
1769 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock) = {
1770 	.stock_lock = INIT_LOCAL_LOCK(stock_lock),
1771 };
1772 static DEFINE_MUTEX(percpu_charge_mutex);
1773 
1774 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock);
1775 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
1776 				     struct mem_cgroup *root_memcg);
1777 
1778 /**
1779  * consume_stock: Try to consume stocked charge on this cpu.
1780  * @memcg: memcg to consume from.
1781  * @nr_pages: how many pages to charge.
1782  *
1783  * The charges will only happen if @memcg matches the current cpu's memcg
1784  * stock, and at least @nr_pages are available in that stock.  Failure to
1785  * service an allocation will refill the stock.
1786  *
1787  * returns true if successful, false otherwise.
1788  */
consume_stock(struct mem_cgroup * memcg,unsigned int nr_pages)1789 static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
1790 {
1791 	struct memcg_stock_pcp *stock;
1792 	unsigned int stock_pages;
1793 	unsigned long flags;
1794 	bool ret = false;
1795 
1796 	if (nr_pages > MEMCG_CHARGE_BATCH)
1797 		return ret;
1798 
1799 	local_lock_irqsave(&memcg_stock.stock_lock, flags);
1800 
1801 	stock = this_cpu_ptr(&memcg_stock);
1802 	stock_pages = READ_ONCE(stock->nr_pages);
1803 	if (memcg == READ_ONCE(stock->cached) && stock_pages >= nr_pages) {
1804 		WRITE_ONCE(stock->nr_pages, stock_pages - nr_pages);
1805 		ret = true;
1806 	}
1807 
1808 	local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
1809 
1810 	return ret;
1811 }
1812 
1813 /*
1814  * Returns stocks cached in percpu and reset cached information.
1815  */
drain_stock(struct memcg_stock_pcp * stock)1816 static void drain_stock(struct memcg_stock_pcp *stock)
1817 {
1818 	unsigned int stock_pages = READ_ONCE(stock->nr_pages);
1819 	struct mem_cgroup *old = READ_ONCE(stock->cached);
1820 
1821 	if (!old)
1822 		return;
1823 
1824 	if (stock_pages) {
1825 		page_counter_uncharge(&old->memory, stock_pages);
1826 		if (do_memsw_account())
1827 			page_counter_uncharge(&old->memsw, stock_pages);
1828 
1829 		WRITE_ONCE(stock->nr_pages, 0);
1830 	}
1831 
1832 	css_put(&old->css);
1833 	WRITE_ONCE(stock->cached, NULL);
1834 }
1835 
drain_local_stock(struct work_struct * dummy)1836 static void drain_local_stock(struct work_struct *dummy)
1837 {
1838 	struct memcg_stock_pcp *stock;
1839 	struct obj_cgroup *old = NULL;
1840 	unsigned long flags;
1841 
1842 	/*
1843 	 * The only protection from cpu hotplug (memcg_hotplug_cpu_dead) vs.
1844 	 * drain_stock races is that we always operate on local CPU stock
1845 	 * here with IRQ disabled
1846 	 */
1847 	local_lock_irqsave(&memcg_stock.stock_lock, flags);
1848 
1849 	stock = this_cpu_ptr(&memcg_stock);
1850 	old = drain_obj_stock(stock);
1851 	drain_stock(stock);
1852 	clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
1853 
1854 	local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
1855 	obj_cgroup_put(old);
1856 }
1857 
1858 /*
1859  * Cache charges(val) to local per_cpu area.
1860  * This will be consumed by consume_stock() function, later.
1861  */
__refill_stock(struct mem_cgroup * memcg,unsigned int nr_pages)1862 static void __refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
1863 {
1864 	struct memcg_stock_pcp *stock;
1865 	unsigned int stock_pages;
1866 
1867 	stock = this_cpu_ptr(&memcg_stock);
1868 	if (READ_ONCE(stock->cached) != memcg) { /* reset if necessary */
1869 		drain_stock(stock);
1870 		css_get(&memcg->css);
1871 		WRITE_ONCE(stock->cached, memcg);
1872 	}
1873 	stock_pages = READ_ONCE(stock->nr_pages) + nr_pages;
1874 	WRITE_ONCE(stock->nr_pages, stock_pages);
1875 
1876 	if (stock_pages > MEMCG_CHARGE_BATCH)
1877 		drain_stock(stock);
1878 }
1879 
refill_stock(struct mem_cgroup * memcg,unsigned int nr_pages)1880 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
1881 {
1882 	unsigned long flags;
1883 
1884 	local_lock_irqsave(&memcg_stock.stock_lock, flags);
1885 	__refill_stock(memcg, nr_pages);
1886 	local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
1887 }
1888 
1889 /*
1890  * Drains all per-CPU charge caches for given root_memcg resp. subtree
1891  * of the hierarchy under it.
1892  */
drain_all_stock(struct mem_cgroup * root_memcg)1893 void drain_all_stock(struct mem_cgroup *root_memcg)
1894 {
1895 	int cpu, curcpu;
1896 
1897 	/* If someone's already draining, avoid adding running more workers. */
1898 	if (!mutex_trylock(&percpu_charge_mutex))
1899 		return;
1900 	/*
1901 	 * Notify other cpus that system-wide "drain" is running
1902 	 * We do not care about races with the cpu hotplug because cpu down
1903 	 * as well as workers from this path always operate on the local
1904 	 * per-cpu data. CPU up doesn't touch memcg_stock at all.
1905 	 */
1906 	migrate_disable();
1907 	curcpu = smp_processor_id();
1908 	for_each_online_cpu(cpu) {
1909 		struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
1910 		struct mem_cgroup *memcg;
1911 		bool flush = false;
1912 
1913 		rcu_read_lock();
1914 		memcg = READ_ONCE(stock->cached);
1915 		if (memcg && READ_ONCE(stock->nr_pages) &&
1916 		    mem_cgroup_is_descendant(memcg, root_memcg))
1917 			flush = true;
1918 		else if (obj_stock_flush_required(stock, root_memcg))
1919 			flush = true;
1920 		rcu_read_unlock();
1921 
1922 		if (flush &&
1923 		    !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
1924 			if (cpu == curcpu)
1925 				drain_local_stock(&stock->work);
1926 			else if (!cpu_is_isolated(cpu))
1927 				schedule_work_on(cpu, &stock->work);
1928 		}
1929 	}
1930 	migrate_enable();
1931 	mutex_unlock(&percpu_charge_mutex);
1932 }
1933 
memcg_hotplug_cpu_dead(unsigned int cpu)1934 static int memcg_hotplug_cpu_dead(unsigned int cpu)
1935 {
1936 	struct memcg_stock_pcp *stock;
1937 	struct obj_cgroup *old;
1938 	unsigned long flags;
1939 
1940 	stock = &per_cpu(memcg_stock, cpu);
1941 
1942 	/* drain_obj_stock requires stock_lock */
1943 	local_lock_irqsave(&memcg_stock.stock_lock, flags);
1944 	old = drain_obj_stock(stock);
1945 	local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
1946 
1947 	drain_stock(stock);
1948 	obj_cgroup_put(old);
1949 
1950 	return 0;
1951 }
1952 
reclaim_high(struct mem_cgroup * memcg,unsigned int nr_pages,gfp_t gfp_mask)1953 static unsigned long reclaim_high(struct mem_cgroup *memcg,
1954 				  unsigned int nr_pages,
1955 				  gfp_t gfp_mask)
1956 {
1957 	unsigned long nr_reclaimed = 0;
1958 
1959 	do {
1960 		unsigned long pflags;
1961 
1962 		if (page_counter_read(&memcg->memory) <=
1963 		    READ_ONCE(memcg->memory.high))
1964 			continue;
1965 
1966 		memcg_memory_event(memcg, MEMCG_HIGH);
1967 
1968 		psi_memstall_enter(&pflags);
1969 		nr_reclaimed += try_to_free_mem_cgroup_pages(memcg, nr_pages,
1970 							gfp_mask,
1971 							MEMCG_RECLAIM_MAY_SWAP,
1972 							NULL);
1973 		psi_memstall_leave(&pflags);
1974 	} while ((memcg = parent_mem_cgroup(memcg)) &&
1975 		 !mem_cgroup_is_root(memcg));
1976 
1977 	return nr_reclaimed;
1978 }
1979 
high_work_func(struct work_struct * work)1980 static void high_work_func(struct work_struct *work)
1981 {
1982 	struct mem_cgroup *memcg;
1983 
1984 	memcg = container_of(work, struct mem_cgroup, high_work);
1985 	reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
1986 }
1987 
1988 /*
1989  * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
1990  * enough to still cause a significant slowdown in most cases, while still
1991  * allowing diagnostics and tracing to proceed without becoming stuck.
1992  */
1993 #define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
1994 
1995 /*
1996  * When calculating the delay, we use these either side of the exponentiation to
1997  * maintain precision and scale to a reasonable number of jiffies (see the table
1998  * below.
1999  *
2000  * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2001  *   overage ratio to a delay.
2002  * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down the
2003  *   proposed penalty in order to reduce to a reasonable number of jiffies, and
2004  *   to produce a reasonable delay curve.
2005  *
2006  * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2007  * reasonable delay curve compared to precision-adjusted overage, not
2008  * penalising heavily at first, but still making sure that growth beyond the
2009  * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2010  * example, with a high of 100 megabytes:
2011  *
2012  *  +-------+------------------------+
2013  *  | usage | time to allocate in ms |
2014  *  +-------+------------------------+
2015  *  | 100M  |                      0 |
2016  *  | 101M  |                      6 |
2017  *  | 102M  |                     25 |
2018  *  | 103M  |                     57 |
2019  *  | 104M  |                    102 |
2020  *  | 105M  |                    159 |
2021  *  | 106M  |                    230 |
2022  *  | 107M  |                    313 |
2023  *  | 108M  |                    409 |
2024  *  | 109M  |                    518 |
2025  *  | 110M  |                    639 |
2026  *  | 111M  |                    774 |
2027  *  | 112M  |                    921 |
2028  *  | 113M  |                   1081 |
2029  *  | 114M  |                   1254 |
2030  *  | 115M  |                   1439 |
2031  *  | 116M  |                   1638 |
2032  *  | 117M  |                   1849 |
2033  *  | 118M  |                   2000 |
2034  *  | 119M  |                   2000 |
2035  *  | 120M  |                   2000 |
2036  *  +-------+------------------------+
2037  */
2038  #define MEMCG_DELAY_PRECISION_SHIFT 20
2039  #define MEMCG_DELAY_SCALING_SHIFT 14
2040 
calculate_overage(unsigned long usage,unsigned long high)2041 static u64 calculate_overage(unsigned long usage, unsigned long high)
2042 {
2043 	u64 overage;
2044 
2045 	if (usage <= high)
2046 		return 0;
2047 
2048 	/*
2049 	 * Prevent division by 0 in overage calculation by acting as if
2050 	 * it was a threshold of 1 page
2051 	 */
2052 	high = max(high, 1UL);
2053 
2054 	overage = usage - high;
2055 	overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2056 	return div64_u64(overage, high);
2057 }
2058 
mem_find_max_overage(struct mem_cgroup * memcg)2059 static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2060 {
2061 	u64 overage, max_overage = 0;
2062 
2063 	do {
2064 		overage = calculate_overage(page_counter_read(&memcg->memory),
2065 					    READ_ONCE(memcg->memory.high));
2066 		max_overage = max(overage, max_overage);
2067 	} while ((memcg = parent_mem_cgroup(memcg)) &&
2068 		 !mem_cgroup_is_root(memcg));
2069 
2070 	return max_overage;
2071 }
2072 
swap_find_max_overage(struct mem_cgroup * memcg)2073 static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2074 {
2075 	u64 overage, max_overage = 0;
2076 
2077 	do {
2078 		overage = calculate_overage(page_counter_read(&memcg->swap),
2079 					    READ_ONCE(memcg->swap.high));
2080 		if (overage)
2081 			memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2082 		max_overage = max(overage, max_overage);
2083 	} while ((memcg = parent_mem_cgroup(memcg)) &&
2084 		 !mem_cgroup_is_root(memcg));
2085 
2086 	return max_overage;
2087 }
2088 
2089 /*
2090  * Get the number of jiffies that we should penalise a mischievous cgroup which
2091  * is exceeding its memory.high by checking both it and its ancestors.
2092  */
calculate_high_delay(struct mem_cgroup * memcg,unsigned int nr_pages,u64 max_overage)2093 static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
2094 					  unsigned int nr_pages,
2095 					  u64 max_overage)
2096 {
2097 	unsigned long penalty_jiffies;
2098 
2099 	if (!max_overage)
2100 		return 0;
2101 
2102 	/*
2103 	 * We use overage compared to memory.high to calculate the number of
2104 	 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2105 	 * fairly lenient on small overages, and increasingly harsh when the
2106 	 * memcg in question makes it clear that it has no intention of stopping
2107 	 * its crazy behaviour, so we exponentially increase the delay based on
2108 	 * overage amount.
2109 	 */
2110 	penalty_jiffies = max_overage * max_overage * HZ;
2111 	penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2112 	penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
2113 
2114 	/*
2115 	 * Factor in the task's own contribution to the overage, such that four
2116 	 * N-sized allocations are throttled approximately the same as one
2117 	 * 4N-sized allocation.
2118 	 *
2119 	 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2120 	 * larger the current charge patch is than that.
2121 	 */
2122 	return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
2123 }
2124 
2125 /*
2126  * Reclaims memory over the high limit. Called directly from
2127  * try_charge() (context permitting), as well as from the userland
2128  * return path where reclaim is always able to block.
2129  */
mem_cgroup_handle_over_high(gfp_t gfp_mask)2130 void mem_cgroup_handle_over_high(gfp_t gfp_mask)
2131 {
2132 	unsigned long penalty_jiffies;
2133 	unsigned long pflags;
2134 	unsigned long nr_reclaimed;
2135 	unsigned int nr_pages = current->memcg_nr_pages_over_high;
2136 	int nr_retries = MAX_RECLAIM_RETRIES;
2137 	struct mem_cgroup *memcg;
2138 	bool in_retry = false;
2139 
2140 	if (likely(!nr_pages))
2141 		return;
2142 
2143 	memcg = get_mem_cgroup_from_mm(current->mm);
2144 	current->memcg_nr_pages_over_high = 0;
2145 
2146 retry_reclaim:
2147 	/*
2148 	 * Bail if the task is already exiting. Unlike memory.max,
2149 	 * memory.high enforcement isn't as strict, and there is no
2150 	 * OOM killer involved, which means the excess could already
2151 	 * be much bigger (and still growing) than it could for
2152 	 * memory.max; the dying task could get stuck in fruitless
2153 	 * reclaim for a long time, which isn't desirable.
2154 	 */
2155 	if (task_is_dying())
2156 		goto out;
2157 
2158 	/*
2159 	 * The allocating task should reclaim at least the batch size, but for
2160 	 * subsequent retries we only want to do what's necessary to prevent oom
2161 	 * or breaching resource isolation.
2162 	 *
2163 	 * This is distinct from memory.max or page allocator behaviour because
2164 	 * memory.high is currently batched, whereas memory.max and the page
2165 	 * allocator run every time an allocation is made.
2166 	 */
2167 	nr_reclaimed = reclaim_high(memcg,
2168 				    in_retry ? SWAP_CLUSTER_MAX : nr_pages,
2169 				    gfp_mask);
2170 
2171 	/*
2172 	 * memory.high is breached and reclaim is unable to keep up. Throttle
2173 	 * allocators proactively to slow down excessive growth.
2174 	 */
2175 	penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2176 					       mem_find_max_overage(memcg));
2177 
2178 	penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2179 						swap_find_max_overage(memcg));
2180 
2181 	/*
2182 	 * Clamp the max delay per usermode return so as to still keep the
2183 	 * application moving forwards and also permit diagnostics, albeit
2184 	 * extremely slowly.
2185 	 */
2186 	penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2187 
2188 	/*
2189 	 * Don't sleep if the amount of jiffies this memcg owes us is so low
2190 	 * that it's not even worth doing, in an attempt to be nice to those who
2191 	 * go only a small amount over their memory.high value and maybe haven't
2192 	 * been aggressively reclaimed enough yet.
2193 	 */
2194 	if (penalty_jiffies <= HZ / 100)
2195 		goto out;
2196 
2197 	/*
2198 	 * If reclaim is making forward progress but we're still over
2199 	 * memory.high, we want to encourage that rather than doing allocator
2200 	 * throttling.
2201 	 */
2202 	if (nr_reclaimed || nr_retries--) {
2203 		in_retry = true;
2204 		goto retry_reclaim;
2205 	}
2206 
2207 	/*
2208 	 * Reclaim didn't manage to push usage below the limit, slow
2209 	 * this allocating task down.
2210 	 *
2211 	 * If we exit early, we're guaranteed to die (since
2212 	 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2213 	 * need to account for any ill-begotten jiffies to pay them off later.
2214 	 */
2215 	psi_memstall_enter(&pflags);
2216 	schedule_timeout_killable(penalty_jiffies);
2217 	psi_memstall_leave(&pflags);
2218 
2219 out:
2220 	css_put(&memcg->css);
2221 }
2222 
try_charge_memcg(struct mem_cgroup * memcg,gfp_t gfp_mask,unsigned int nr_pages)2223 int try_charge_memcg(struct mem_cgroup *memcg, gfp_t gfp_mask,
2224 		     unsigned int nr_pages)
2225 {
2226 	unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
2227 	int nr_retries = MAX_RECLAIM_RETRIES;
2228 	struct mem_cgroup *mem_over_limit;
2229 	struct page_counter *counter;
2230 	unsigned long nr_reclaimed;
2231 	bool passed_oom = false;
2232 	unsigned int reclaim_options = MEMCG_RECLAIM_MAY_SWAP;
2233 	bool drained = false;
2234 	bool raised_max_event = false;
2235 	unsigned long pflags;
2236 
2237 retry:
2238 	if (consume_stock(memcg, nr_pages))
2239 		return 0;
2240 
2241 	if (!do_memsw_account() ||
2242 	    page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2243 		if (page_counter_try_charge(&memcg->memory, batch, &counter))
2244 			goto done_restock;
2245 		if (do_memsw_account())
2246 			page_counter_uncharge(&memcg->memsw, batch);
2247 		mem_over_limit = mem_cgroup_from_counter(counter, memory);
2248 	} else {
2249 		mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2250 		reclaim_options &= ~MEMCG_RECLAIM_MAY_SWAP;
2251 	}
2252 
2253 	if (batch > nr_pages) {
2254 		batch = nr_pages;
2255 		goto retry;
2256 	}
2257 
2258 	/*
2259 	 * Prevent unbounded recursion when reclaim operations need to
2260 	 * allocate memory. This might exceed the limits temporarily,
2261 	 * but we prefer facilitating memory reclaim and getting back
2262 	 * under the limit over triggering OOM kills in these cases.
2263 	 */
2264 	if (unlikely(current->flags & PF_MEMALLOC))
2265 		goto force;
2266 
2267 	if (unlikely(task_in_memcg_oom(current)))
2268 		goto nomem;
2269 
2270 	if (!gfpflags_allow_blocking(gfp_mask))
2271 		goto nomem;
2272 
2273 	memcg_memory_event(mem_over_limit, MEMCG_MAX);
2274 	raised_max_event = true;
2275 
2276 	psi_memstall_enter(&pflags);
2277 	nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2278 						    gfp_mask, reclaim_options, NULL);
2279 	psi_memstall_leave(&pflags);
2280 
2281 	if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2282 		goto retry;
2283 
2284 	if (!drained) {
2285 		drain_all_stock(mem_over_limit);
2286 		drained = true;
2287 		goto retry;
2288 	}
2289 
2290 	if (gfp_mask & __GFP_NORETRY)
2291 		goto nomem;
2292 	/*
2293 	 * Even though the limit is exceeded at this point, reclaim
2294 	 * may have been able to free some pages.  Retry the charge
2295 	 * before killing the task.
2296 	 *
2297 	 * Only for regular pages, though: huge pages are rather
2298 	 * unlikely to succeed so close to the limit, and we fall back
2299 	 * to regular pages anyway in case of failure.
2300 	 */
2301 	if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
2302 		goto retry;
2303 	/*
2304 	 * At task move, charge accounts can be doubly counted. So, it's
2305 	 * better to wait until the end of task_move if something is going on.
2306 	 */
2307 	if (memcg1_wait_acct_move(mem_over_limit))
2308 		goto retry;
2309 
2310 	if (nr_retries--)
2311 		goto retry;
2312 
2313 	if (gfp_mask & __GFP_RETRY_MAYFAIL)
2314 		goto nomem;
2315 
2316 	/* Avoid endless loop for tasks bypassed by the oom killer */
2317 	if (passed_oom && task_is_dying())
2318 		goto nomem;
2319 
2320 	/*
2321 	 * keep retrying as long as the memcg oom killer is able to make
2322 	 * a forward progress or bypass the charge if the oom killer
2323 	 * couldn't make any progress.
2324 	 */
2325 	if (mem_cgroup_oom(mem_over_limit, gfp_mask,
2326 			   get_order(nr_pages * PAGE_SIZE))) {
2327 		passed_oom = true;
2328 		nr_retries = MAX_RECLAIM_RETRIES;
2329 		goto retry;
2330 	}
2331 nomem:
2332 	/*
2333 	 * Memcg doesn't have a dedicated reserve for atomic
2334 	 * allocations. But like the global atomic pool, we need to
2335 	 * put the burden of reclaim on regular allocation requests
2336 	 * and let these go through as privileged allocations.
2337 	 */
2338 	if (!(gfp_mask & (__GFP_NOFAIL | __GFP_HIGH)))
2339 		return -ENOMEM;
2340 force:
2341 	/*
2342 	 * If the allocation has to be enforced, don't forget to raise
2343 	 * a MEMCG_MAX event.
2344 	 */
2345 	if (!raised_max_event)
2346 		memcg_memory_event(mem_over_limit, MEMCG_MAX);
2347 
2348 	/*
2349 	 * The allocation either can't fail or will lead to more memory
2350 	 * being freed very soon.  Allow memory usage go over the limit
2351 	 * temporarily by force charging it.
2352 	 */
2353 	page_counter_charge(&memcg->memory, nr_pages);
2354 	if (do_memsw_account())
2355 		page_counter_charge(&memcg->memsw, nr_pages);
2356 
2357 	return 0;
2358 
2359 done_restock:
2360 	if (batch > nr_pages)
2361 		refill_stock(memcg, batch - nr_pages);
2362 
2363 	/*
2364 	 * If the hierarchy is above the normal consumption range, schedule
2365 	 * reclaim on returning to userland.  We can perform reclaim here
2366 	 * if __GFP_RECLAIM but let's always punt for simplicity and so that
2367 	 * GFP_KERNEL can consistently be used during reclaim.  @memcg is
2368 	 * not recorded as it most likely matches current's and won't
2369 	 * change in the meantime.  As high limit is checked again before
2370 	 * reclaim, the cost of mismatch is negligible.
2371 	 */
2372 	do {
2373 		bool mem_high, swap_high;
2374 
2375 		mem_high = page_counter_read(&memcg->memory) >
2376 			READ_ONCE(memcg->memory.high);
2377 		swap_high = page_counter_read(&memcg->swap) >
2378 			READ_ONCE(memcg->swap.high);
2379 
2380 		/* Don't bother a random interrupted task */
2381 		if (!in_task()) {
2382 			if (mem_high) {
2383 				schedule_work(&memcg->high_work);
2384 				break;
2385 			}
2386 			continue;
2387 		}
2388 
2389 		if (mem_high || swap_high) {
2390 			/*
2391 			 * The allocating tasks in this cgroup will need to do
2392 			 * reclaim or be throttled to prevent further growth
2393 			 * of the memory or swap footprints.
2394 			 *
2395 			 * Target some best-effort fairness between the tasks,
2396 			 * and distribute reclaim work and delay penalties
2397 			 * based on how much each task is actually allocating.
2398 			 */
2399 			current->memcg_nr_pages_over_high += batch;
2400 			set_notify_resume(current);
2401 			break;
2402 		}
2403 	} while ((memcg = parent_mem_cgroup(memcg)));
2404 
2405 	/*
2406 	 * Reclaim is set up above to be called from the userland
2407 	 * return path. But also attempt synchronous reclaim to avoid
2408 	 * excessive overrun while the task is still inside the
2409 	 * kernel. If this is successful, the return path will see it
2410 	 * when it rechecks the overage and simply bail out.
2411 	 */
2412 	if (current->memcg_nr_pages_over_high > MEMCG_CHARGE_BATCH &&
2413 	    !(current->flags & PF_MEMALLOC) &&
2414 	    gfpflags_allow_blocking(gfp_mask))
2415 		mem_cgroup_handle_over_high(gfp_mask);
2416 	return 0;
2417 }
2418 
2419 /**
2420  * mem_cgroup_cancel_charge() - cancel an uncommitted try_charge() call.
2421  * @memcg: memcg previously charged.
2422  * @nr_pages: number of pages previously charged.
2423  */
mem_cgroup_cancel_charge(struct mem_cgroup * memcg,unsigned int nr_pages)2424 void mem_cgroup_cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
2425 {
2426 	if (mem_cgroup_is_root(memcg))
2427 		return;
2428 
2429 	page_counter_uncharge(&memcg->memory, nr_pages);
2430 	if (do_memsw_account())
2431 		page_counter_uncharge(&memcg->memsw, nr_pages);
2432 }
2433 
commit_charge(struct folio * folio,struct mem_cgroup * memcg)2434 static void commit_charge(struct folio *folio, struct mem_cgroup *memcg)
2435 {
2436 	VM_BUG_ON_FOLIO(folio_memcg_charged(folio), folio);
2437 	/*
2438 	 * Any of the following ensures page's memcg stability:
2439 	 *
2440 	 * - the page lock
2441 	 * - LRU isolation
2442 	 * - folio_memcg_lock()
2443 	 * - exclusive reference
2444 	 * - mem_cgroup_trylock_pages()
2445 	 */
2446 	folio->memcg_data = (unsigned long)memcg;
2447 }
2448 
2449 /**
2450  * mem_cgroup_commit_charge - commit a previously successful try_charge().
2451  * @folio: folio to commit the charge to.
2452  * @memcg: memcg previously charged.
2453  */
mem_cgroup_commit_charge(struct folio * folio,struct mem_cgroup * memcg)2454 void mem_cgroup_commit_charge(struct folio *folio, struct mem_cgroup *memcg)
2455 {
2456 	css_get(&memcg->css);
2457 	commit_charge(folio, memcg);
2458 	memcg1_commit_charge(folio, memcg);
2459 }
2460 
__mod_objcg_mlstate(struct obj_cgroup * objcg,struct pglist_data * pgdat,enum node_stat_item idx,int nr)2461 static inline void __mod_objcg_mlstate(struct obj_cgroup *objcg,
2462 				       struct pglist_data *pgdat,
2463 				       enum node_stat_item idx, int nr)
2464 {
2465 	struct mem_cgroup *memcg;
2466 	struct lruvec *lruvec;
2467 
2468 	rcu_read_lock();
2469 	memcg = obj_cgroup_memcg(objcg);
2470 	lruvec = mem_cgroup_lruvec(memcg, pgdat);
2471 	__mod_memcg_lruvec_state(lruvec, idx, nr);
2472 	rcu_read_unlock();
2473 }
2474 
2475 static __always_inline
mem_cgroup_from_obj_folio(struct folio * folio,void * p)2476 struct mem_cgroup *mem_cgroup_from_obj_folio(struct folio *folio, void *p)
2477 {
2478 	/*
2479 	 * Slab objects are accounted individually, not per-page.
2480 	 * Memcg membership data for each individual object is saved in
2481 	 * slab->obj_exts.
2482 	 */
2483 	if (folio_test_slab(folio)) {
2484 		struct slabobj_ext *obj_exts;
2485 		struct slab *slab;
2486 		unsigned int off;
2487 
2488 		slab = folio_slab(folio);
2489 		obj_exts = slab_obj_exts(slab);
2490 		if (!obj_exts)
2491 			return NULL;
2492 
2493 		off = obj_to_index(slab->slab_cache, slab, p);
2494 		if (obj_exts[off].objcg)
2495 			return obj_cgroup_memcg(obj_exts[off].objcg);
2496 
2497 		return NULL;
2498 	}
2499 
2500 	/*
2501 	 * folio_memcg_check() is used here, because in theory we can encounter
2502 	 * a folio where the slab flag has been cleared already, but
2503 	 * slab->obj_exts has not been freed yet
2504 	 * folio_memcg_check() will guarantee that a proper memory
2505 	 * cgroup pointer or NULL will be returned.
2506 	 */
2507 	return folio_memcg_check(folio);
2508 }
2509 
2510 /*
2511  * Returns a pointer to the memory cgroup to which the kernel object is charged.
2512  * It is not suitable for objects allocated using vmalloc().
2513  *
2514  * A passed kernel object must be a slab object or a generic kernel page.
2515  *
2516  * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2517  * cgroup_mutex, etc.
2518  */
mem_cgroup_from_slab_obj(void * p)2519 struct mem_cgroup *mem_cgroup_from_slab_obj(void *p)
2520 {
2521 	if (mem_cgroup_disabled())
2522 		return NULL;
2523 
2524 	return mem_cgroup_from_obj_folio(virt_to_folio(p), p);
2525 }
2526 
__get_obj_cgroup_from_memcg(struct mem_cgroup * memcg)2527 static struct obj_cgroup *__get_obj_cgroup_from_memcg(struct mem_cgroup *memcg)
2528 {
2529 	struct obj_cgroup *objcg = NULL;
2530 
2531 	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
2532 		objcg = rcu_dereference(memcg->objcg);
2533 		if (likely(objcg && obj_cgroup_tryget(objcg)))
2534 			break;
2535 		objcg = NULL;
2536 	}
2537 	return objcg;
2538 }
2539 
current_objcg_update(void)2540 static struct obj_cgroup *current_objcg_update(void)
2541 {
2542 	struct mem_cgroup *memcg;
2543 	struct obj_cgroup *old, *objcg = NULL;
2544 
2545 	do {
2546 		/* Atomically drop the update bit. */
2547 		old = xchg(&current->objcg, NULL);
2548 		if (old) {
2549 			old = (struct obj_cgroup *)
2550 				((unsigned long)old & ~CURRENT_OBJCG_UPDATE_FLAG);
2551 			obj_cgroup_put(old);
2552 
2553 			old = NULL;
2554 		}
2555 
2556 		/* If new objcg is NULL, no reason for the second atomic update. */
2557 		if (!current->mm || (current->flags & PF_KTHREAD))
2558 			return NULL;
2559 
2560 		/*
2561 		 * Release the objcg pointer from the previous iteration,
2562 		 * if try_cmpxcg() below fails.
2563 		 */
2564 		if (unlikely(objcg)) {
2565 			obj_cgroup_put(objcg);
2566 			objcg = NULL;
2567 		}
2568 
2569 		/*
2570 		 * Obtain the new objcg pointer. The current task can be
2571 		 * asynchronously moved to another memcg and the previous
2572 		 * memcg can be offlined. So let's get the memcg pointer
2573 		 * and try get a reference to objcg under a rcu read lock.
2574 		 */
2575 
2576 		rcu_read_lock();
2577 		memcg = mem_cgroup_from_task(current);
2578 		objcg = __get_obj_cgroup_from_memcg(memcg);
2579 		rcu_read_unlock();
2580 
2581 		/*
2582 		 * Try set up a new objcg pointer atomically. If it
2583 		 * fails, it means the update flag was set concurrently, so
2584 		 * the whole procedure should be repeated.
2585 		 */
2586 	} while (!try_cmpxchg(&current->objcg, &old, objcg));
2587 
2588 	return objcg;
2589 }
2590 
current_obj_cgroup(void)2591 __always_inline struct obj_cgroup *current_obj_cgroup(void)
2592 {
2593 	struct mem_cgroup *memcg;
2594 	struct obj_cgroup *objcg;
2595 
2596 	if (in_task()) {
2597 		memcg = current->active_memcg;
2598 		if (unlikely(memcg))
2599 			goto from_memcg;
2600 
2601 		objcg = READ_ONCE(current->objcg);
2602 		if (unlikely((unsigned long)objcg & CURRENT_OBJCG_UPDATE_FLAG))
2603 			objcg = current_objcg_update();
2604 		/*
2605 		 * Objcg reference is kept by the task, so it's safe
2606 		 * to use the objcg by the current task.
2607 		 */
2608 		return objcg;
2609 	}
2610 
2611 	memcg = this_cpu_read(int_active_memcg);
2612 	if (unlikely(memcg))
2613 		goto from_memcg;
2614 
2615 	return NULL;
2616 
2617 from_memcg:
2618 	objcg = NULL;
2619 	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
2620 		/*
2621 		 * Memcg pointer is protected by scope (see set_active_memcg())
2622 		 * and is pinning the corresponding objcg, so objcg can't go
2623 		 * away and can be used within the scope without any additional
2624 		 * protection.
2625 		 */
2626 		objcg = rcu_dereference_check(memcg->objcg, 1);
2627 		if (likely(objcg))
2628 			break;
2629 	}
2630 
2631 	return objcg;
2632 }
2633 
get_obj_cgroup_from_folio(struct folio * folio)2634 struct obj_cgroup *get_obj_cgroup_from_folio(struct folio *folio)
2635 {
2636 	struct obj_cgroup *objcg;
2637 
2638 	if (!memcg_kmem_online())
2639 		return NULL;
2640 
2641 	if (folio_memcg_kmem(folio)) {
2642 		objcg = __folio_objcg(folio);
2643 		obj_cgroup_get(objcg);
2644 	} else {
2645 		struct mem_cgroup *memcg;
2646 
2647 		rcu_read_lock();
2648 		memcg = __folio_memcg(folio);
2649 		if (memcg)
2650 			objcg = __get_obj_cgroup_from_memcg(memcg);
2651 		else
2652 			objcg = NULL;
2653 		rcu_read_unlock();
2654 	}
2655 	return objcg;
2656 }
2657 
2658 /*
2659  * obj_cgroup_uncharge_pages: uncharge a number of kernel pages from a objcg
2660  * @objcg: object cgroup to uncharge
2661  * @nr_pages: number of pages to uncharge
2662  */
obj_cgroup_uncharge_pages(struct obj_cgroup * objcg,unsigned int nr_pages)2663 static void obj_cgroup_uncharge_pages(struct obj_cgroup *objcg,
2664 				      unsigned int nr_pages)
2665 {
2666 	struct mem_cgroup *memcg;
2667 
2668 	memcg = get_mem_cgroup_from_objcg(objcg);
2669 
2670 	mod_memcg_state(memcg, MEMCG_KMEM, -nr_pages);
2671 	memcg1_account_kmem(memcg, -nr_pages);
2672 	refill_stock(memcg, nr_pages);
2673 
2674 	css_put(&memcg->css);
2675 }
2676 
2677 /*
2678  * obj_cgroup_charge_pages: charge a number of kernel pages to a objcg
2679  * @objcg: object cgroup to charge
2680  * @gfp: reclaim mode
2681  * @nr_pages: number of pages to charge
2682  *
2683  * Returns 0 on success, an error code on failure.
2684  */
obj_cgroup_charge_pages(struct obj_cgroup * objcg,gfp_t gfp,unsigned int nr_pages)2685 static int obj_cgroup_charge_pages(struct obj_cgroup *objcg, gfp_t gfp,
2686 				   unsigned int nr_pages)
2687 {
2688 	struct mem_cgroup *memcg;
2689 	int ret;
2690 
2691 	memcg = get_mem_cgroup_from_objcg(objcg);
2692 
2693 	ret = try_charge_memcg(memcg, gfp, nr_pages);
2694 	if (ret)
2695 		goto out;
2696 
2697 	mod_memcg_state(memcg, MEMCG_KMEM, nr_pages);
2698 	memcg1_account_kmem(memcg, nr_pages);
2699 out:
2700 	css_put(&memcg->css);
2701 
2702 	return ret;
2703 }
2704 
2705 /**
2706  * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
2707  * @page: page to charge
2708  * @gfp: reclaim mode
2709  * @order: allocation order
2710  *
2711  * Returns 0 on success, an error code on failure.
2712  */
__memcg_kmem_charge_page(struct page * page,gfp_t gfp,int order)2713 int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
2714 {
2715 	struct obj_cgroup *objcg;
2716 	int ret = 0;
2717 
2718 	objcg = current_obj_cgroup();
2719 	if (objcg) {
2720 		ret = obj_cgroup_charge_pages(objcg, gfp, 1 << order);
2721 		if (!ret) {
2722 			obj_cgroup_get(objcg);
2723 			page->memcg_data = (unsigned long)objcg |
2724 				MEMCG_DATA_KMEM;
2725 			return 0;
2726 		}
2727 	}
2728 	return ret;
2729 }
2730 
2731 /**
2732  * __memcg_kmem_uncharge_page: uncharge a kmem page
2733  * @page: page to uncharge
2734  * @order: allocation order
2735  */
__memcg_kmem_uncharge_page(struct page * page,int order)2736 void __memcg_kmem_uncharge_page(struct page *page, int order)
2737 {
2738 	struct folio *folio = page_folio(page);
2739 	struct obj_cgroup *objcg;
2740 	unsigned int nr_pages = 1 << order;
2741 
2742 	if (!folio_memcg_kmem(folio))
2743 		return;
2744 
2745 	objcg = __folio_objcg(folio);
2746 	obj_cgroup_uncharge_pages(objcg, nr_pages);
2747 	folio->memcg_data = 0;
2748 	obj_cgroup_put(objcg);
2749 }
2750 
mod_objcg_state(struct obj_cgroup * objcg,struct pglist_data * pgdat,enum node_stat_item idx,int nr)2751 static void mod_objcg_state(struct obj_cgroup *objcg, struct pglist_data *pgdat,
2752 		     enum node_stat_item idx, int nr)
2753 {
2754 	struct memcg_stock_pcp *stock;
2755 	struct obj_cgroup *old = NULL;
2756 	unsigned long flags;
2757 	int *bytes;
2758 
2759 	local_lock_irqsave(&memcg_stock.stock_lock, flags);
2760 	stock = this_cpu_ptr(&memcg_stock);
2761 
2762 	/*
2763 	 * Save vmstat data in stock and skip vmstat array update unless
2764 	 * accumulating over a page of vmstat data or when pgdat or idx
2765 	 * changes.
2766 	 */
2767 	if (READ_ONCE(stock->cached_objcg) != objcg) {
2768 		old = drain_obj_stock(stock);
2769 		obj_cgroup_get(objcg);
2770 		stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
2771 				? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
2772 		WRITE_ONCE(stock->cached_objcg, objcg);
2773 		stock->cached_pgdat = pgdat;
2774 	} else if (stock->cached_pgdat != pgdat) {
2775 		/* Flush the existing cached vmstat data */
2776 		struct pglist_data *oldpg = stock->cached_pgdat;
2777 
2778 		if (stock->nr_slab_reclaimable_b) {
2779 			__mod_objcg_mlstate(objcg, oldpg, NR_SLAB_RECLAIMABLE_B,
2780 					  stock->nr_slab_reclaimable_b);
2781 			stock->nr_slab_reclaimable_b = 0;
2782 		}
2783 		if (stock->nr_slab_unreclaimable_b) {
2784 			__mod_objcg_mlstate(objcg, oldpg, NR_SLAB_UNRECLAIMABLE_B,
2785 					  stock->nr_slab_unreclaimable_b);
2786 			stock->nr_slab_unreclaimable_b = 0;
2787 		}
2788 		stock->cached_pgdat = pgdat;
2789 	}
2790 
2791 	bytes = (idx == NR_SLAB_RECLAIMABLE_B) ? &stock->nr_slab_reclaimable_b
2792 					       : &stock->nr_slab_unreclaimable_b;
2793 	/*
2794 	 * Even for large object >= PAGE_SIZE, the vmstat data will still be
2795 	 * cached locally at least once before pushing it out.
2796 	 */
2797 	if (!*bytes) {
2798 		*bytes = nr;
2799 		nr = 0;
2800 	} else {
2801 		*bytes += nr;
2802 		if (abs(*bytes) > PAGE_SIZE) {
2803 			nr = *bytes;
2804 			*bytes = 0;
2805 		} else {
2806 			nr = 0;
2807 		}
2808 	}
2809 	if (nr)
2810 		__mod_objcg_mlstate(objcg, pgdat, idx, nr);
2811 
2812 	local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2813 	obj_cgroup_put(old);
2814 }
2815 
consume_obj_stock(struct obj_cgroup * objcg,unsigned int nr_bytes)2816 static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
2817 {
2818 	struct memcg_stock_pcp *stock;
2819 	unsigned long flags;
2820 	bool ret = false;
2821 
2822 	local_lock_irqsave(&memcg_stock.stock_lock, flags);
2823 
2824 	stock = this_cpu_ptr(&memcg_stock);
2825 	if (objcg == READ_ONCE(stock->cached_objcg) && stock->nr_bytes >= nr_bytes) {
2826 		stock->nr_bytes -= nr_bytes;
2827 		ret = true;
2828 	}
2829 
2830 	local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2831 
2832 	return ret;
2833 }
2834 
drain_obj_stock(struct memcg_stock_pcp * stock)2835 static struct obj_cgroup *drain_obj_stock(struct memcg_stock_pcp *stock)
2836 {
2837 	struct obj_cgroup *old = READ_ONCE(stock->cached_objcg);
2838 
2839 	if (!old)
2840 		return NULL;
2841 
2842 	if (stock->nr_bytes) {
2843 		unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
2844 		unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
2845 
2846 		if (nr_pages) {
2847 			struct mem_cgroup *memcg;
2848 
2849 			memcg = get_mem_cgroup_from_objcg(old);
2850 
2851 			mod_memcg_state(memcg, MEMCG_KMEM, -nr_pages);
2852 			memcg1_account_kmem(memcg, -nr_pages);
2853 			__refill_stock(memcg, nr_pages);
2854 
2855 			css_put(&memcg->css);
2856 		}
2857 
2858 		/*
2859 		 * The leftover is flushed to the centralized per-memcg value.
2860 		 * On the next attempt to refill obj stock it will be moved
2861 		 * to a per-cpu stock (probably, on an other CPU), see
2862 		 * refill_obj_stock().
2863 		 *
2864 		 * How often it's flushed is a trade-off between the memory
2865 		 * limit enforcement accuracy and potential CPU contention,
2866 		 * so it might be changed in the future.
2867 		 */
2868 		atomic_add(nr_bytes, &old->nr_charged_bytes);
2869 		stock->nr_bytes = 0;
2870 	}
2871 
2872 	/*
2873 	 * Flush the vmstat data in current stock
2874 	 */
2875 	if (stock->nr_slab_reclaimable_b || stock->nr_slab_unreclaimable_b) {
2876 		if (stock->nr_slab_reclaimable_b) {
2877 			__mod_objcg_mlstate(old, stock->cached_pgdat,
2878 					  NR_SLAB_RECLAIMABLE_B,
2879 					  stock->nr_slab_reclaimable_b);
2880 			stock->nr_slab_reclaimable_b = 0;
2881 		}
2882 		if (stock->nr_slab_unreclaimable_b) {
2883 			__mod_objcg_mlstate(old, stock->cached_pgdat,
2884 					  NR_SLAB_UNRECLAIMABLE_B,
2885 					  stock->nr_slab_unreclaimable_b);
2886 			stock->nr_slab_unreclaimable_b = 0;
2887 		}
2888 		stock->cached_pgdat = NULL;
2889 	}
2890 
2891 	WRITE_ONCE(stock->cached_objcg, NULL);
2892 	/*
2893 	 * The `old' objects needs to be released by the caller via
2894 	 * obj_cgroup_put() outside of memcg_stock_pcp::stock_lock.
2895 	 */
2896 	return old;
2897 }
2898 
obj_stock_flush_required(struct memcg_stock_pcp * stock,struct mem_cgroup * root_memcg)2899 static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2900 				     struct mem_cgroup *root_memcg)
2901 {
2902 	struct obj_cgroup *objcg = READ_ONCE(stock->cached_objcg);
2903 	struct mem_cgroup *memcg;
2904 
2905 	if (objcg) {
2906 		memcg = obj_cgroup_memcg(objcg);
2907 		if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
2908 			return true;
2909 	}
2910 
2911 	return false;
2912 }
2913 
refill_obj_stock(struct obj_cgroup * objcg,unsigned int nr_bytes,bool allow_uncharge)2914 static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes,
2915 			     bool allow_uncharge)
2916 {
2917 	struct memcg_stock_pcp *stock;
2918 	struct obj_cgroup *old = NULL;
2919 	unsigned long flags;
2920 	unsigned int nr_pages = 0;
2921 
2922 	local_lock_irqsave(&memcg_stock.stock_lock, flags);
2923 
2924 	stock = this_cpu_ptr(&memcg_stock);
2925 	if (READ_ONCE(stock->cached_objcg) != objcg) { /* reset if necessary */
2926 		old = drain_obj_stock(stock);
2927 		obj_cgroup_get(objcg);
2928 		WRITE_ONCE(stock->cached_objcg, objcg);
2929 		stock->nr_bytes = atomic_read(&objcg->nr_charged_bytes)
2930 				? atomic_xchg(&objcg->nr_charged_bytes, 0) : 0;
2931 		allow_uncharge = true;	/* Allow uncharge when objcg changes */
2932 	}
2933 	stock->nr_bytes += nr_bytes;
2934 
2935 	if (allow_uncharge && (stock->nr_bytes > PAGE_SIZE)) {
2936 		nr_pages = stock->nr_bytes >> PAGE_SHIFT;
2937 		stock->nr_bytes &= (PAGE_SIZE - 1);
2938 	}
2939 
2940 	local_unlock_irqrestore(&memcg_stock.stock_lock, flags);
2941 	obj_cgroup_put(old);
2942 
2943 	if (nr_pages)
2944 		obj_cgroup_uncharge_pages(objcg, nr_pages);
2945 }
2946 
obj_cgroup_charge(struct obj_cgroup * objcg,gfp_t gfp,size_t size)2947 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
2948 {
2949 	unsigned int nr_pages, nr_bytes;
2950 	int ret;
2951 
2952 	if (consume_obj_stock(objcg, size))
2953 		return 0;
2954 
2955 	/*
2956 	 * In theory, objcg->nr_charged_bytes can have enough
2957 	 * pre-charged bytes to satisfy the allocation. However,
2958 	 * flushing objcg->nr_charged_bytes requires two atomic
2959 	 * operations, and objcg->nr_charged_bytes can't be big.
2960 	 * The shared objcg->nr_charged_bytes can also become a
2961 	 * performance bottleneck if all tasks of the same memcg are
2962 	 * trying to update it. So it's better to ignore it and try
2963 	 * grab some new pages. The stock's nr_bytes will be flushed to
2964 	 * objcg->nr_charged_bytes later on when objcg changes.
2965 	 *
2966 	 * The stock's nr_bytes may contain enough pre-charged bytes
2967 	 * to allow one less page from being charged, but we can't rely
2968 	 * on the pre-charged bytes not being changed outside of
2969 	 * consume_obj_stock() or refill_obj_stock(). So ignore those
2970 	 * pre-charged bytes as well when charging pages. To avoid a
2971 	 * page uncharge right after a page charge, we set the
2972 	 * allow_uncharge flag to false when calling refill_obj_stock()
2973 	 * to temporarily allow the pre-charged bytes to exceed the page
2974 	 * size limit. The maximum reachable value of the pre-charged
2975 	 * bytes is (sizeof(object) + PAGE_SIZE - 2) if there is no data
2976 	 * race.
2977 	 */
2978 	nr_pages = size >> PAGE_SHIFT;
2979 	nr_bytes = size & (PAGE_SIZE - 1);
2980 
2981 	if (nr_bytes)
2982 		nr_pages += 1;
2983 
2984 	ret = obj_cgroup_charge_pages(objcg, gfp, nr_pages);
2985 	if (!ret && nr_bytes)
2986 		refill_obj_stock(objcg, PAGE_SIZE - nr_bytes, false);
2987 
2988 	return ret;
2989 }
2990 
obj_cgroup_uncharge(struct obj_cgroup * objcg,size_t size)2991 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
2992 {
2993 	refill_obj_stock(objcg, size, true);
2994 }
2995 
obj_full_size(struct kmem_cache * s)2996 static inline size_t obj_full_size(struct kmem_cache *s)
2997 {
2998 	/*
2999 	 * For each accounted object there is an extra space which is used
3000 	 * to store obj_cgroup membership. Charge it too.
3001 	 */
3002 	return s->size + sizeof(struct obj_cgroup *);
3003 }
3004 
__memcg_slab_post_alloc_hook(struct kmem_cache * s,struct list_lru * lru,gfp_t flags,size_t size,void ** p)3005 bool __memcg_slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
3006 				  gfp_t flags, size_t size, void **p)
3007 {
3008 	struct obj_cgroup *objcg;
3009 	struct slab *slab;
3010 	unsigned long off;
3011 	size_t i;
3012 
3013 	/*
3014 	 * The obtained objcg pointer is safe to use within the current scope,
3015 	 * defined by current task or set_active_memcg() pair.
3016 	 * obj_cgroup_get() is used to get a permanent reference.
3017 	 */
3018 	objcg = current_obj_cgroup();
3019 	if (!objcg)
3020 		return true;
3021 
3022 	/*
3023 	 * slab_alloc_node() avoids the NULL check, so we might be called with a
3024 	 * single NULL object. kmem_cache_alloc_bulk() aborts if it can't fill
3025 	 * the whole requested size.
3026 	 * return success as there's nothing to free back
3027 	 */
3028 	if (unlikely(*p == NULL))
3029 		return true;
3030 
3031 	flags &= gfp_allowed_mask;
3032 
3033 	if (lru) {
3034 		int ret;
3035 		struct mem_cgroup *memcg;
3036 
3037 		memcg = get_mem_cgroup_from_objcg(objcg);
3038 		ret = memcg_list_lru_alloc(memcg, lru, flags);
3039 		css_put(&memcg->css);
3040 
3041 		if (ret)
3042 			return false;
3043 	}
3044 
3045 	if (obj_cgroup_charge(objcg, flags, size * obj_full_size(s)))
3046 		return false;
3047 
3048 	for (i = 0; i < size; i++) {
3049 		slab = virt_to_slab(p[i]);
3050 
3051 		if (!slab_obj_exts(slab) &&
3052 		    alloc_slab_obj_exts(slab, s, flags, false)) {
3053 			obj_cgroup_uncharge(objcg, obj_full_size(s));
3054 			continue;
3055 		}
3056 
3057 		off = obj_to_index(s, slab, p[i]);
3058 		obj_cgroup_get(objcg);
3059 		slab_obj_exts(slab)[off].objcg = objcg;
3060 		mod_objcg_state(objcg, slab_pgdat(slab),
3061 				cache_vmstat_idx(s), obj_full_size(s));
3062 	}
3063 
3064 	return true;
3065 }
3066 
__memcg_slab_free_hook(struct kmem_cache * s,struct slab * slab,void ** p,int objects,struct slabobj_ext * obj_exts)3067 void __memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab,
3068 			    void **p, int objects, struct slabobj_ext *obj_exts)
3069 {
3070 	for (int i = 0; i < objects; i++) {
3071 		struct obj_cgroup *objcg;
3072 		unsigned int off;
3073 
3074 		off = obj_to_index(s, slab, p[i]);
3075 		objcg = obj_exts[off].objcg;
3076 		if (!objcg)
3077 			continue;
3078 
3079 		obj_exts[off].objcg = NULL;
3080 		obj_cgroup_uncharge(objcg, obj_full_size(s));
3081 		mod_objcg_state(objcg, slab_pgdat(slab), cache_vmstat_idx(s),
3082 				-obj_full_size(s));
3083 		obj_cgroup_put(objcg);
3084 	}
3085 }
3086 
3087 /*
3088  * Because folio_memcg(head) is not set on tails, set it now.
3089  */
split_page_memcg(struct page * head,int old_order,int new_order)3090 void split_page_memcg(struct page *head, int old_order, int new_order)
3091 {
3092 	struct folio *folio = page_folio(head);
3093 	int i;
3094 	unsigned int old_nr = 1 << old_order;
3095 	unsigned int new_nr = 1 << new_order;
3096 
3097 	if (mem_cgroup_disabled() || !folio_memcg_charged(folio))
3098 		return;
3099 
3100 	for (i = new_nr; i < old_nr; i += new_nr)
3101 		folio_page(folio, i)->memcg_data = folio->memcg_data;
3102 
3103 	if (folio_memcg_kmem(folio))
3104 		obj_cgroup_get_many(__folio_objcg(folio), old_nr / new_nr - 1);
3105 	else
3106 		css_get_many(&folio_memcg(folio)->css, old_nr / new_nr - 1);
3107 }
3108 
mem_cgroup_usage(struct mem_cgroup * memcg,bool swap)3109 unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
3110 {
3111 	unsigned long val;
3112 
3113 	if (mem_cgroup_is_root(memcg)) {
3114 		/*
3115 		 * Approximate root's usage from global state. This isn't
3116 		 * perfect, but the root usage was always an approximation.
3117 		 */
3118 		val = global_node_page_state(NR_FILE_PAGES) +
3119 			global_node_page_state(NR_ANON_MAPPED);
3120 		if (swap)
3121 			val += total_swap_pages - get_nr_swap_pages();
3122 	} else {
3123 		if (!swap)
3124 			val = page_counter_read(&memcg->memory);
3125 		else
3126 			val = page_counter_read(&memcg->memsw);
3127 	}
3128 	return val;
3129 }
3130 
memcg_online_kmem(struct mem_cgroup * memcg)3131 static int memcg_online_kmem(struct mem_cgroup *memcg)
3132 {
3133 	struct obj_cgroup *objcg;
3134 
3135 	if (mem_cgroup_kmem_disabled())
3136 		return 0;
3137 
3138 	if (unlikely(mem_cgroup_is_root(memcg)))
3139 		return 0;
3140 
3141 	objcg = obj_cgroup_alloc();
3142 	if (!objcg)
3143 		return -ENOMEM;
3144 
3145 	objcg->memcg = memcg;
3146 	rcu_assign_pointer(memcg->objcg, objcg);
3147 	obj_cgroup_get(objcg);
3148 	memcg->orig_objcg = objcg;
3149 
3150 	static_branch_enable(&memcg_kmem_online_key);
3151 
3152 	memcg->kmemcg_id = memcg->id.id;
3153 
3154 	return 0;
3155 }
3156 
memcg_offline_kmem(struct mem_cgroup * memcg)3157 static void memcg_offline_kmem(struct mem_cgroup *memcg)
3158 {
3159 	struct mem_cgroup *parent;
3160 
3161 	if (mem_cgroup_kmem_disabled())
3162 		return;
3163 
3164 	if (unlikely(mem_cgroup_is_root(memcg)))
3165 		return;
3166 
3167 	parent = parent_mem_cgroup(memcg);
3168 	if (!parent)
3169 		parent = root_mem_cgroup;
3170 
3171 	memcg_reparent_objcgs(memcg, parent);
3172 
3173 	/*
3174 	 * After we have finished memcg_reparent_objcgs(), all list_lrus
3175 	 * corresponding to this cgroup are guaranteed to remain empty.
3176 	 * The ordering is imposed by list_lru_node->lock taken by
3177 	 * memcg_reparent_list_lrus().
3178 	 */
3179 	memcg_reparent_list_lrus(memcg, parent);
3180 }
3181 
3182 #ifdef CONFIG_CGROUP_WRITEBACK
3183 
3184 #include <trace/events/writeback.h>
3185 
memcg_wb_domain_init(struct mem_cgroup * memcg,gfp_t gfp)3186 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
3187 {
3188 	return wb_domain_init(&memcg->cgwb_domain, gfp);
3189 }
3190 
memcg_wb_domain_exit(struct mem_cgroup * memcg)3191 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
3192 {
3193 	wb_domain_exit(&memcg->cgwb_domain);
3194 }
3195 
memcg_wb_domain_size_changed(struct mem_cgroup * memcg)3196 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
3197 {
3198 	wb_domain_size_changed(&memcg->cgwb_domain);
3199 }
3200 
mem_cgroup_wb_domain(struct bdi_writeback * wb)3201 struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
3202 {
3203 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3204 
3205 	if (!memcg->css.parent)
3206 		return NULL;
3207 
3208 	return &memcg->cgwb_domain;
3209 }
3210 
3211 /**
3212  * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
3213  * @wb: bdi_writeback in question
3214  * @pfilepages: out parameter for number of file pages
3215  * @pheadroom: out parameter for number of allocatable pages according to memcg
3216  * @pdirty: out parameter for number of dirty pages
3217  * @pwriteback: out parameter for number of pages under writeback
3218  *
3219  * Determine the numbers of file, headroom, dirty, and writeback pages in
3220  * @wb's memcg.  File, dirty and writeback are self-explanatory.  Headroom
3221  * is a bit more involved.
3222  *
3223  * A memcg's headroom is "min(max, high) - used".  In the hierarchy, the
3224  * headroom is calculated as the lowest headroom of itself and the
3225  * ancestors.  Note that this doesn't consider the actual amount of
3226  * available memory in the system.  The caller should further cap
3227  * *@pheadroom accordingly.
3228  */
mem_cgroup_wb_stats(struct bdi_writeback * wb,unsigned long * pfilepages,unsigned long * pheadroom,unsigned long * pdirty,unsigned long * pwriteback)3229 void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
3230 			 unsigned long *pheadroom, unsigned long *pdirty,
3231 			 unsigned long *pwriteback)
3232 {
3233 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3234 	struct mem_cgroup *parent;
3235 
3236 	mem_cgroup_flush_stats_ratelimited(memcg);
3237 
3238 	*pdirty = memcg_page_state(memcg, NR_FILE_DIRTY);
3239 	*pwriteback = memcg_page_state(memcg, NR_WRITEBACK);
3240 	*pfilepages = memcg_page_state(memcg, NR_INACTIVE_FILE) +
3241 			memcg_page_state(memcg, NR_ACTIVE_FILE);
3242 
3243 	*pheadroom = PAGE_COUNTER_MAX;
3244 	while ((parent = parent_mem_cgroup(memcg))) {
3245 		unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
3246 					    READ_ONCE(memcg->memory.high));
3247 		unsigned long used = page_counter_read(&memcg->memory);
3248 
3249 		*pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
3250 		memcg = parent;
3251 	}
3252 }
3253 
3254 /*
3255  * Foreign dirty flushing
3256  *
3257  * There's an inherent mismatch between memcg and writeback.  The former
3258  * tracks ownership per-page while the latter per-inode.  This was a
3259  * deliberate design decision because honoring per-page ownership in the
3260  * writeback path is complicated, may lead to higher CPU and IO overheads
3261  * and deemed unnecessary given that write-sharing an inode across
3262  * different cgroups isn't a common use-case.
3263  *
3264  * Combined with inode majority-writer ownership switching, this works well
3265  * enough in most cases but there are some pathological cases.  For
3266  * example, let's say there are two cgroups A and B which keep writing to
3267  * different but confined parts of the same inode.  B owns the inode and
3268  * A's memory is limited far below B's.  A's dirty ratio can rise enough to
3269  * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
3270  * triggering background writeback.  A will be slowed down without a way to
3271  * make writeback of the dirty pages happen.
3272  *
3273  * Conditions like the above can lead to a cgroup getting repeatedly and
3274  * severely throttled after making some progress after each
3275  * dirty_expire_interval while the underlying IO device is almost
3276  * completely idle.
3277  *
3278  * Solving this problem completely requires matching the ownership tracking
3279  * granularities between memcg and writeback in either direction.  However,
3280  * the more egregious behaviors can be avoided by simply remembering the
3281  * most recent foreign dirtying events and initiating remote flushes on
3282  * them when local writeback isn't enough to keep the memory clean enough.
3283  *
3284  * The following two functions implement such mechanism.  When a foreign
3285  * page - a page whose memcg and writeback ownerships don't match - is
3286  * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
3287  * bdi_writeback on the page owning memcg.  When balance_dirty_pages()
3288  * decides that the memcg needs to sleep due to high dirty ratio, it calls
3289  * mem_cgroup_flush_foreign() which queues writeback on the recorded
3290  * foreign bdi_writebacks which haven't expired.  Both the numbers of
3291  * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
3292  * limited to MEMCG_CGWB_FRN_CNT.
3293  *
3294  * The mechanism only remembers IDs and doesn't hold any object references.
3295  * As being wrong occasionally doesn't matter, updates and accesses to the
3296  * records are lockless and racy.
3297  */
mem_cgroup_track_foreign_dirty_slowpath(struct folio * folio,struct bdi_writeback * wb)3298 void mem_cgroup_track_foreign_dirty_slowpath(struct folio *folio,
3299 					     struct bdi_writeback *wb)
3300 {
3301 	struct mem_cgroup *memcg = folio_memcg(folio);
3302 	struct memcg_cgwb_frn *frn;
3303 	u64 now = get_jiffies_64();
3304 	u64 oldest_at = now;
3305 	int oldest = -1;
3306 	int i;
3307 
3308 	trace_track_foreign_dirty(folio, wb);
3309 
3310 	/*
3311 	 * Pick the slot to use.  If there is already a slot for @wb, keep
3312 	 * using it.  If not replace the oldest one which isn't being
3313 	 * written out.
3314 	 */
3315 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
3316 		frn = &memcg->cgwb_frn[i];
3317 		if (frn->bdi_id == wb->bdi->id &&
3318 		    frn->memcg_id == wb->memcg_css->id)
3319 			break;
3320 		if (time_before64(frn->at, oldest_at) &&
3321 		    atomic_read(&frn->done.cnt) == 1) {
3322 			oldest = i;
3323 			oldest_at = frn->at;
3324 		}
3325 	}
3326 
3327 	if (i < MEMCG_CGWB_FRN_CNT) {
3328 		/*
3329 		 * Re-using an existing one.  Update timestamp lazily to
3330 		 * avoid making the cacheline hot.  We want them to be
3331 		 * reasonably up-to-date and significantly shorter than
3332 		 * dirty_expire_interval as that's what expires the record.
3333 		 * Use the shorter of 1s and dirty_expire_interval / 8.
3334 		 */
3335 		unsigned long update_intv =
3336 			min_t(unsigned long, HZ,
3337 			      msecs_to_jiffies(dirty_expire_interval * 10) / 8);
3338 
3339 		if (time_before64(frn->at, now - update_intv))
3340 			frn->at = now;
3341 	} else if (oldest >= 0) {
3342 		/* replace the oldest free one */
3343 		frn = &memcg->cgwb_frn[oldest];
3344 		frn->bdi_id = wb->bdi->id;
3345 		frn->memcg_id = wb->memcg_css->id;
3346 		frn->at = now;
3347 	}
3348 }
3349 
3350 /* issue foreign writeback flushes for recorded foreign dirtying events */
mem_cgroup_flush_foreign(struct bdi_writeback * wb)3351 void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
3352 {
3353 	struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
3354 	unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
3355 	u64 now = jiffies_64;
3356 	int i;
3357 
3358 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
3359 		struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
3360 
3361 		/*
3362 		 * If the record is older than dirty_expire_interval,
3363 		 * writeback on it has already started.  No need to kick it
3364 		 * off again.  Also, don't start a new one if there's
3365 		 * already one in flight.
3366 		 */
3367 		if (time_after64(frn->at, now - intv) &&
3368 		    atomic_read(&frn->done.cnt) == 1) {
3369 			frn->at = 0;
3370 			trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
3371 			cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id,
3372 					       WB_REASON_FOREIGN_FLUSH,
3373 					       &frn->done);
3374 		}
3375 	}
3376 }
3377 
3378 #else	/* CONFIG_CGROUP_WRITEBACK */
3379 
memcg_wb_domain_init(struct mem_cgroup * memcg,gfp_t gfp)3380 static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
3381 {
3382 	return 0;
3383 }
3384 
memcg_wb_domain_exit(struct mem_cgroup * memcg)3385 static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
3386 {
3387 }
3388 
memcg_wb_domain_size_changed(struct mem_cgroup * memcg)3389 static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
3390 {
3391 }
3392 
3393 #endif	/* CONFIG_CGROUP_WRITEBACK */
3394 
3395 /*
3396  * Private memory cgroup IDR
3397  *
3398  * Swap-out records and page cache shadow entries need to store memcg
3399  * references in constrained space, so we maintain an ID space that is
3400  * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
3401  * memory-controlled cgroups to 64k.
3402  *
3403  * However, there usually are many references to the offline CSS after
3404  * the cgroup has been destroyed, such as page cache or reclaimable
3405  * slab objects, that don't need to hang on to the ID. We want to keep
3406  * those dead CSS from occupying IDs, or we might quickly exhaust the
3407  * relatively small ID space and prevent the creation of new cgroups
3408  * even when there are much fewer than 64k cgroups - possibly none.
3409  *
3410  * Maintain a private 16-bit ID space for memcg, and allow the ID to
3411  * be freed and recycled when it's no longer needed, which is usually
3412  * when the CSS is offlined.
3413  *
3414  * The only exception to that are records of swapped out tmpfs/shmem
3415  * pages that need to be attributed to live ancestors on swapin. But
3416  * those references are manageable from userspace.
3417  */
3418 
3419 #define MEM_CGROUP_ID_MAX	((1UL << MEM_CGROUP_ID_SHIFT) - 1)
3420 static DEFINE_XARRAY_ALLOC1(mem_cgroup_ids);
3421 
mem_cgroup_id_remove(struct mem_cgroup * memcg)3422 static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
3423 {
3424 	if (memcg->id.id > 0) {
3425 		trace_android_vh_mem_cgroup_id_remove(memcg);
3426 		xa_erase(&mem_cgroup_ids, memcg->id.id);
3427 		memcg->id.id = 0;
3428 	}
3429 }
3430 
mem_cgroup_id_get_many(struct mem_cgroup * memcg,unsigned int n)3431 void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
3432 					   unsigned int n)
3433 {
3434 	refcount_add(n, &memcg->id.ref);
3435 }
3436 
mem_cgroup_id_put_many(struct mem_cgroup * memcg,unsigned int n)3437 void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
3438 {
3439 	if (refcount_sub_and_test(n, &memcg->id.ref)) {
3440 		mem_cgroup_id_remove(memcg);
3441 
3442 		/* Memcg ID pins CSS */
3443 		css_put(&memcg->css);
3444 	}
3445 }
3446 
mem_cgroup_id_put(struct mem_cgroup * memcg)3447 static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
3448 {
3449 	mem_cgroup_id_put_many(memcg, 1);
3450 }
3451 
3452 /**
3453  * mem_cgroup_from_id - look up a memcg from a memcg id
3454  * @id: the memcg id to look up
3455  *
3456  * Caller must hold rcu_read_lock().
3457  */
mem_cgroup_from_id(unsigned short id)3458 struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
3459 {
3460 	WARN_ON_ONCE(!rcu_read_lock_held());
3461 	return xa_load(&mem_cgroup_ids, id);
3462 }
3463 EXPORT_SYMBOL_GPL(mem_cgroup_from_id);
3464 
3465 #ifdef CONFIG_SHRINKER_DEBUG
mem_cgroup_get_from_ino(unsigned long ino)3466 struct mem_cgroup *mem_cgroup_get_from_ino(unsigned long ino)
3467 {
3468 	struct cgroup *cgrp;
3469 	struct cgroup_subsys_state *css;
3470 	struct mem_cgroup *memcg;
3471 
3472 	cgrp = cgroup_get_from_id(ino);
3473 	if (IS_ERR(cgrp))
3474 		return ERR_CAST(cgrp);
3475 
3476 	css = cgroup_get_e_css(cgrp, &memory_cgrp_subsys);
3477 	if (css)
3478 		memcg = container_of(css, struct mem_cgroup, css);
3479 	else
3480 		memcg = ERR_PTR(-ENOENT);
3481 
3482 	cgroup_put(cgrp);
3483 
3484 	return memcg;
3485 }
3486 #endif
3487 
alloc_mem_cgroup_per_node_info(struct mem_cgroup * memcg,int node)3488 static bool alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
3489 {
3490 	struct mem_cgroup_per_node *pn;
3491 
3492 	pn = kmem_cache_alloc_node(memcg_pn_cachep, GFP_KERNEL | __GFP_ZERO,
3493 				   node);
3494 	if (!pn)
3495 		return false;
3496 
3497 	pn->lruvec_stats = kzalloc_node(sizeof(struct lruvec_stats),
3498 					GFP_KERNEL_ACCOUNT, node);
3499 	if (!pn->lruvec_stats)
3500 		goto fail;
3501 
3502 	pn->lruvec_stats_percpu = alloc_percpu_gfp(struct lruvec_stats_percpu,
3503 						   GFP_KERNEL_ACCOUNT);
3504 	if (!pn->lruvec_stats_percpu)
3505 		goto fail;
3506 
3507 	lruvec_init(&pn->lruvec);
3508 	pn->memcg = memcg;
3509 
3510 	memcg->nodeinfo[node] = pn;
3511 	return true;
3512 fail:
3513 	kfree(pn->lruvec_stats);
3514 	kfree(pn);
3515 	return false;
3516 }
3517 
free_mem_cgroup_per_node_info(struct mem_cgroup * memcg,int node)3518 static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
3519 {
3520 	struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
3521 
3522 	if (!pn)
3523 		return;
3524 
3525 	free_percpu(pn->lruvec_stats_percpu);
3526 	kfree(pn->lruvec_stats);
3527 	kfree(pn);
3528 }
3529 
__mem_cgroup_free(struct mem_cgroup * memcg)3530 static void __mem_cgroup_free(struct mem_cgroup *memcg)
3531 {
3532 	int node;
3533 
3534 	trace_android_vh_mem_cgroup_free(memcg);
3535 	obj_cgroup_put(memcg->orig_objcg);
3536 
3537 	for_each_node(node)
3538 		free_mem_cgroup_per_node_info(memcg, node);
3539 	memcg1_free_events(memcg);
3540 	kfree(memcg->vmstats);
3541 	free_percpu(memcg->vmstats_percpu);
3542 	kfree(memcg);
3543 }
3544 
mem_cgroup_free(struct mem_cgroup * memcg)3545 static void mem_cgroup_free(struct mem_cgroup *memcg)
3546 {
3547 	lru_gen_exit_memcg(memcg);
3548 	memcg_wb_domain_exit(memcg);
3549 	__mem_cgroup_free(memcg);
3550 }
3551 
mem_cgroup_alloc(struct mem_cgroup * parent)3552 static struct mem_cgroup *mem_cgroup_alloc(struct mem_cgroup *parent)
3553 {
3554 	struct memcg_vmstats_percpu *statc, *pstatc;
3555 	struct mem_cgroup *memcg;
3556 	int node, cpu;
3557 	int __maybe_unused i;
3558 	long error;
3559 
3560 	memcg = kmem_cache_zalloc(memcg_cachep, GFP_KERNEL);
3561 	if (!memcg)
3562 		return ERR_PTR(-ENOMEM);
3563 
3564 	error = xa_alloc(&mem_cgroup_ids, &memcg->id.id, NULL,
3565 			 XA_LIMIT(1, MEM_CGROUP_ID_MAX), GFP_KERNEL);
3566 	if (error)
3567 		goto fail;
3568 	error = -ENOMEM;
3569 
3570 	memcg->vmstats = kzalloc(sizeof(struct memcg_vmstats),
3571 				 GFP_KERNEL_ACCOUNT);
3572 	if (!memcg->vmstats)
3573 		goto fail;
3574 
3575 	memcg->vmstats_percpu = alloc_percpu_gfp(struct memcg_vmstats_percpu,
3576 						 GFP_KERNEL_ACCOUNT);
3577 	if (!memcg->vmstats_percpu)
3578 		goto fail;
3579 
3580 	if (!memcg1_alloc_events(memcg))
3581 		goto fail;
3582 
3583 	for_each_possible_cpu(cpu) {
3584 		if (parent)
3585 			pstatc = per_cpu_ptr(parent->vmstats_percpu, cpu);
3586 		statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
3587 		statc->parent = parent ? pstatc : NULL;
3588 		statc->vmstats = memcg->vmstats;
3589 	}
3590 
3591 	for_each_node(node)
3592 		if (!alloc_mem_cgroup_per_node_info(memcg, node))
3593 			goto fail;
3594 
3595 	if (memcg_wb_domain_init(memcg, GFP_KERNEL))
3596 		goto fail;
3597 
3598 	INIT_WORK(&memcg->high_work, high_work_func);
3599 	vmpressure_init(&memcg->vmpressure);
3600 	INIT_LIST_HEAD(&memcg->memory_peaks);
3601 	INIT_LIST_HEAD(&memcg->swap_peaks);
3602 	spin_lock_init(&memcg->peaks_lock);
3603 	memcg->socket_pressure = jiffies;
3604 	memcg1_memcg_init(memcg);
3605 	memcg->kmemcg_id = -1;
3606 	INIT_LIST_HEAD(&memcg->objcg_list);
3607 #ifdef CONFIG_CGROUP_WRITEBACK
3608 	INIT_LIST_HEAD(&memcg->cgwb_list);
3609 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
3610 		memcg->cgwb_frn[i].done =
3611 			__WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
3612 #endif
3613 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3614 	spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
3615 	INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
3616 	memcg->deferred_split_queue.split_queue_len = 0;
3617 #endif
3618 	lru_gen_init_memcg(memcg);
3619 	trace_android_vh_mem_cgroup_alloc(memcg);
3620 	return memcg;
3621 fail:
3622 	mem_cgroup_id_remove(memcg);
3623 	__mem_cgroup_free(memcg);
3624 	return ERR_PTR(error);
3625 }
3626 
3627 static struct cgroup_subsys_state * __ref
mem_cgroup_css_alloc(struct cgroup_subsys_state * parent_css)3628 mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
3629 {
3630 	struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
3631 	struct mem_cgroup *memcg, *old_memcg;
3632 
3633 	old_memcg = set_active_memcg(parent);
3634 	memcg = mem_cgroup_alloc(parent);
3635 	set_active_memcg(old_memcg);
3636 	if (IS_ERR(memcg))
3637 		return ERR_CAST(memcg);
3638 
3639 	page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
3640 	memcg1_soft_limit_reset(memcg);
3641 #ifdef CONFIG_ZSWAP
3642 	memcg->zswap_max = PAGE_COUNTER_MAX;
3643 	WRITE_ONCE(memcg->zswap_writeback, true);
3644 #endif
3645 	page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
3646 	if (parent) {
3647 		WRITE_ONCE(memcg->swappiness, mem_cgroup_swappiness(parent));
3648 
3649 		page_counter_init(&memcg->memory, &parent->memory, true);
3650 		page_counter_init(&memcg->swap, &parent->swap, false);
3651 #ifdef CONFIG_MEMCG_V1
3652 		WRITE_ONCE(memcg->oom_kill_disable, READ_ONCE(parent->oom_kill_disable));
3653 		page_counter_init(&memcg->kmem, &parent->kmem, false);
3654 		page_counter_init(&memcg->tcpmem, &parent->tcpmem, false);
3655 #endif
3656 	} else {
3657 		init_memcg_stats();
3658 		init_memcg_events();
3659 		page_counter_init(&memcg->memory, NULL, true);
3660 		page_counter_init(&memcg->swap, NULL, false);
3661 #ifdef CONFIG_MEMCG_V1
3662 		page_counter_init(&memcg->kmem, NULL, false);
3663 		page_counter_init(&memcg->tcpmem, NULL, false);
3664 #endif
3665 		root_mem_cgroup = memcg;
3666 		return &memcg->css;
3667 	}
3668 
3669 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
3670 		static_branch_inc(&memcg_sockets_enabled_key);
3671 
3672 	if (!cgroup_memory_nobpf)
3673 		static_branch_inc(&memcg_bpf_enabled_key);
3674 
3675 	return &memcg->css;
3676 }
3677 
mem_cgroup_css_online(struct cgroup_subsys_state * css)3678 static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
3679 {
3680 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3681 
3682 	if (memcg_online_kmem(memcg))
3683 		goto remove_id;
3684 
3685 	/*
3686 	 * A memcg must be visible for expand_shrinker_info()
3687 	 * by the time the maps are allocated. So, we allocate maps
3688 	 * here, when for_each_mem_cgroup() can't skip it.
3689 	 */
3690 	if (alloc_shrinker_info(memcg))
3691 		goto offline_kmem;
3692 
3693 	if (unlikely(mem_cgroup_is_root(memcg)) && !mem_cgroup_disabled())
3694 		queue_delayed_work(system_unbound_wq, &stats_flush_dwork,
3695 				   FLUSH_TIME);
3696 	lru_gen_online_memcg(memcg);
3697 
3698 	/* Online state pins memcg ID, memcg ID pins CSS */
3699 	refcount_set(&memcg->id.ref, 1);
3700 	css_get(css);
3701 
3702 	/*
3703 	 * Ensure mem_cgroup_from_id() works once we're fully online.
3704 	 *
3705 	 * We could do this earlier and require callers to filter with
3706 	 * css_tryget_online(). But right now there are no users that
3707 	 * need earlier access, and the workingset code relies on the
3708 	 * cgroup tree linkage (mem_cgroup_get_nr_swap_pages()). So
3709 	 * publish it here at the end of onlining. This matches the
3710 	 * regular ID destruction during offlining.
3711 	 */
3712 	xa_store(&mem_cgroup_ids, memcg->id.id, memcg, GFP_KERNEL);
3713 	trace_android_vh_mem_cgroup_css_online(css, memcg);
3714 
3715 	return 0;
3716 offline_kmem:
3717 	memcg_offline_kmem(memcg);
3718 remove_id:
3719 	mem_cgroup_id_remove(memcg);
3720 	return -ENOMEM;
3721 }
3722 
mem_cgroup_css_offline(struct cgroup_subsys_state * css)3723 static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
3724 {
3725 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3726 
3727 	trace_android_vh_mem_cgroup_css_offline(css, memcg);
3728 	memcg1_css_offline(memcg);
3729 
3730 	page_counter_set_min(&memcg->memory, 0);
3731 	page_counter_set_low(&memcg->memory, 0);
3732 
3733 	zswap_memcg_offline_cleanup(memcg);
3734 
3735 	memcg_offline_kmem(memcg);
3736 	reparent_shrinker_deferred(memcg);
3737 	wb_memcg_offline(memcg);
3738 	lru_gen_offline_memcg(memcg);
3739 
3740 	drain_all_stock(memcg);
3741 
3742 	mem_cgroup_id_put(memcg);
3743 }
3744 
mem_cgroup_css_released(struct cgroup_subsys_state * css)3745 static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
3746 {
3747 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3748 
3749 	invalidate_reclaim_iterators(memcg);
3750 	lru_gen_release_memcg(memcg);
3751 }
3752 
mem_cgroup_css_free(struct cgroup_subsys_state * css)3753 static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
3754 {
3755 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3756 	int __maybe_unused i;
3757 
3758 #ifdef CONFIG_CGROUP_WRITEBACK
3759 	for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
3760 		wb_wait_for_completion(&memcg->cgwb_frn[i].done);
3761 #endif
3762 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
3763 		static_branch_dec(&memcg_sockets_enabled_key);
3764 
3765 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg1_tcpmem_active(memcg))
3766 		static_branch_dec(&memcg_sockets_enabled_key);
3767 
3768 	if (!cgroup_memory_nobpf)
3769 		static_branch_dec(&memcg_bpf_enabled_key);
3770 
3771 	vmpressure_cleanup(&memcg->vmpressure);
3772 	cancel_work_sync(&memcg->high_work);
3773 	memcg1_remove_from_trees(memcg);
3774 	free_shrinker_info(memcg);
3775 	mem_cgroup_free(memcg);
3776 }
3777 
3778 /**
3779  * mem_cgroup_css_reset - reset the states of a mem_cgroup
3780  * @css: the target css
3781  *
3782  * Reset the states of the mem_cgroup associated with @css.  This is
3783  * invoked when the userland requests disabling on the default hierarchy
3784  * but the memcg is pinned through dependency.  The memcg should stop
3785  * applying policies and should revert to the vanilla state as it may be
3786  * made visible again.
3787  *
3788  * The current implementation only resets the essential configurations.
3789  * This needs to be expanded to cover all the visible parts.
3790  */
mem_cgroup_css_reset(struct cgroup_subsys_state * css)3791 static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
3792 {
3793 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3794 
3795 	page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
3796 	page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
3797 #ifdef CONFIG_MEMCG_V1
3798 	page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
3799 	page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
3800 #endif
3801 	page_counter_set_min(&memcg->memory, 0);
3802 	page_counter_set_low(&memcg->memory, 0);
3803 	page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
3804 	memcg1_soft_limit_reset(memcg);
3805 	page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
3806 	memcg_wb_domain_size_changed(memcg);
3807 }
3808 
mem_cgroup_css_rstat_flush(struct cgroup_subsys_state * css,int cpu)3809 static void mem_cgroup_css_rstat_flush(struct cgroup_subsys_state *css, int cpu)
3810 {
3811 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3812 	struct mem_cgroup *parent = parent_mem_cgroup(memcg);
3813 	struct memcg_vmstats_percpu *statc;
3814 	long delta, delta_cpu, v;
3815 	int i, nid;
3816 
3817 	statc = per_cpu_ptr(memcg->vmstats_percpu, cpu);
3818 
3819 	for (i = 0; i < MEMCG_VMSTAT_SIZE; i++) {
3820 		/*
3821 		 * Collect the aggregated propagation counts of groups
3822 		 * below us. We're in a per-cpu loop here and this is
3823 		 * a global counter, so the first cycle will get them.
3824 		 */
3825 		delta = memcg->vmstats->state_pending[i];
3826 		if (delta)
3827 			memcg->vmstats->state_pending[i] = 0;
3828 
3829 		/* Add CPU changes on this level since the last flush */
3830 		delta_cpu = 0;
3831 		v = READ_ONCE(statc->state[i]);
3832 		if (v != statc->state_prev[i]) {
3833 			delta_cpu = v - statc->state_prev[i];
3834 			delta += delta_cpu;
3835 			statc->state_prev[i] = v;
3836 		}
3837 
3838 		/* Aggregate counts on this level and propagate upwards */
3839 		if (delta_cpu)
3840 			memcg->vmstats->state_local[i] += delta_cpu;
3841 
3842 		if (delta) {
3843 			memcg->vmstats->state[i] += delta;
3844 			if (parent)
3845 				parent->vmstats->state_pending[i] += delta;
3846 		}
3847 	}
3848 
3849 	for (i = 0; i < NR_MEMCG_EVENTS; i++) {
3850 		delta = memcg->vmstats->events_pending[i];
3851 		if (delta)
3852 			memcg->vmstats->events_pending[i] = 0;
3853 
3854 		delta_cpu = 0;
3855 		v = READ_ONCE(statc->events[i]);
3856 		if (v != statc->events_prev[i]) {
3857 			delta_cpu = v - statc->events_prev[i];
3858 			delta += delta_cpu;
3859 			statc->events_prev[i] = v;
3860 		}
3861 
3862 		if (delta_cpu)
3863 			memcg->vmstats->events_local[i] += delta_cpu;
3864 
3865 		if (delta) {
3866 			memcg->vmstats->events[i] += delta;
3867 			if (parent)
3868 				parent->vmstats->events_pending[i] += delta;
3869 		}
3870 	}
3871 
3872 	for_each_node_state(nid, N_MEMORY) {
3873 		struct mem_cgroup_per_node *pn = memcg->nodeinfo[nid];
3874 		struct lruvec_stats *lstats = pn->lruvec_stats;
3875 		struct lruvec_stats *plstats = NULL;
3876 		struct lruvec_stats_percpu *lstatc;
3877 
3878 		if (parent)
3879 			plstats = parent->nodeinfo[nid]->lruvec_stats;
3880 
3881 		lstatc = per_cpu_ptr(pn->lruvec_stats_percpu, cpu);
3882 
3883 		for (i = 0; i < NR_MEMCG_NODE_STAT_ITEMS; i++) {
3884 			delta = lstats->state_pending[i];
3885 			if (delta)
3886 				lstats->state_pending[i] = 0;
3887 
3888 			delta_cpu = 0;
3889 			v = READ_ONCE(lstatc->state[i]);
3890 			if (v != lstatc->state_prev[i]) {
3891 				delta_cpu = v - lstatc->state_prev[i];
3892 				delta += delta_cpu;
3893 				lstatc->state_prev[i] = v;
3894 			}
3895 
3896 			if (delta_cpu)
3897 				lstats->state_local[i] += delta_cpu;
3898 
3899 			if (delta) {
3900 				lstats->state[i] += delta;
3901 				if (plstats)
3902 					plstats->state_pending[i] += delta;
3903 			}
3904 		}
3905 	}
3906 	WRITE_ONCE(statc->stats_updates, 0);
3907 	/* We are in a per-cpu loop here, only do the atomic write once */
3908 	if (atomic64_read(&memcg->vmstats->stats_updates))
3909 		atomic64_set(&memcg->vmstats->stats_updates, 0);
3910 }
3911 
mem_cgroup_fork(struct task_struct * task)3912 static void mem_cgroup_fork(struct task_struct *task)
3913 {
3914 	/*
3915 	 * Set the update flag to cause task->objcg to be initialized lazily
3916 	 * on the first allocation. It can be done without any synchronization
3917 	 * because it's always performed on the current task, so does
3918 	 * current_objcg_update().
3919 	 */
3920 	task->objcg = (struct obj_cgroup *)CURRENT_OBJCG_UPDATE_FLAG;
3921 }
3922 
mem_cgroup_exit(struct task_struct * task)3923 static void mem_cgroup_exit(struct task_struct *task)
3924 {
3925 	struct obj_cgroup *objcg = task->objcg;
3926 
3927 	objcg = (struct obj_cgroup *)
3928 		((unsigned long)objcg & ~CURRENT_OBJCG_UPDATE_FLAG);
3929 	obj_cgroup_put(objcg);
3930 
3931 	/*
3932 	 * Some kernel allocations can happen after this point,
3933 	 * but let's ignore them. It can be done without any synchronization
3934 	 * because it's always performed on the current task, so does
3935 	 * current_objcg_update().
3936 	 */
3937 	task->objcg = NULL;
3938 }
3939 
3940 #ifdef CONFIG_LRU_GEN
mem_cgroup_lru_gen_attach(struct cgroup_taskset * tset)3941 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset)
3942 {
3943 	struct task_struct *task;
3944 	struct cgroup_subsys_state *css;
3945 
3946 	/* find the first leader if there is any */
3947 	cgroup_taskset_for_each_leader(task, css, tset)
3948 		break;
3949 
3950 	if (!task)
3951 		return;
3952 
3953 	task_lock(task);
3954 	if (task->mm && READ_ONCE(task->mm->owner) == task)
3955 		lru_gen_migrate_mm(task->mm);
3956 	task_unlock(task);
3957 }
3958 #else
mem_cgroup_lru_gen_attach(struct cgroup_taskset * tset)3959 static void mem_cgroup_lru_gen_attach(struct cgroup_taskset *tset) {}
3960 #endif /* CONFIG_LRU_GEN */
3961 
mem_cgroup_kmem_attach(struct cgroup_taskset * tset)3962 static void mem_cgroup_kmem_attach(struct cgroup_taskset *tset)
3963 {
3964 	struct task_struct *task;
3965 	struct cgroup_subsys_state *css;
3966 
3967 	cgroup_taskset_for_each(task, css, tset) {
3968 		/* atomically set the update bit */
3969 		set_bit(CURRENT_OBJCG_UPDATE_BIT, (unsigned long *)&task->objcg);
3970 	}
3971 }
3972 
mem_cgroup_attach(struct cgroup_taskset * tset)3973 static void mem_cgroup_attach(struct cgroup_taskset *tset)
3974 {
3975 	mem_cgroup_lru_gen_attach(tset);
3976 	mem_cgroup_kmem_attach(tset);
3977 }
3978 
seq_puts_memcg_tunable(struct seq_file * m,unsigned long value)3979 static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
3980 {
3981 	if (value == PAGE_COUNTER_MAX)
3982 		seq_puts(m, "max\n");
3983 	else
3984 		seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
3985 
3986 	return 0;
3987 }
3988 
memory_current_read(struct cgroup_subsys_state * css,struct cftype * cft)3989 static u64 memory_current_read(struct cgroup_subsys_state *css,
3990 			       struct cftype *cft)
3991 {
3992 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
3993 
3994 	return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
3995 }
3996 
3997 #define OFP_PEAK_UNSET (((-1UL)))
3998 
peak_show(struct seq_file * sf,void * v,struct page_counter * pc)3999 static int peak_show(struct seq_file *sf, void *v, struct page_counter *pc)
4000 {
4001 	struct cgroup_of_peak *ofp = of_peak(sf->private);
4002 	u64 fd_peak = READ_ONCE(ofp->value), peak;
4003 
4004 	/* User wants global or local peak? */
4005 	if (fd_peak == OFP_PEAK_UNSET)
4006 		peak = pc->watermark;
4007 	else
4008 		peak = max(fd_peak, READ_ONCE(pc->local_watermark));
4009 
4010 	seq_printf(sf, "%llu\n", peak * PAGE_SIZE);
4011 	return 0;
4012 }
4013 
memory_peak_show(struct seq_file * sf,void * v)4014 static int memory_peak_show(struct seq_file *sf, void *v)
4015 {
4016 	struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
4017 
4018 	return peak_show(sf, v, &memcg->memory);
4019 }
4020 
peak_open(struct kernfs_open_file * of)4021 static int peak_open(struct kernfs_open_file *of)
4022 {
4023 	struct cgroup_of_peak *ofp = of_peak(of);
4024 
4025 	ofp->value = OFP_PEAK_UNSET;
4026 	return 0;
4027 }
4028 
peak_release(struct kernfs_open_file * of)4029 static void peak_release(struct kernfs_open_file *of)
4030 {
4031 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4032 	struct cgroup_of_peak *ofp = of_peak(of);
4033 
4034 	if (ofp->value == OFP_PEAK_UNSET) {
4035 		/* fast path (no writes on this fd) */
4036 		return;
4037 	}
4038 	spin_lock(&memcg->peaks_lock);
4039 	list_del(&ofp->list);
4040 	spin_unlock(&memcg->peaks_lock);
4041 }
4042 
peak_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off,struct page_counter * pc,struct list_head * watchers)4043 static ssize_t peak_write(struct kernfs_open_file *of, char *buf, size_t nbytes,
4044 			  loff_t off, struct page_counter *pc,
4045 			  struct list_head *watchers)
4046 {
4047 	unsigned long usage;
4048 	struct cgroup_of_peak *peer_ctx;
4049 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4050 	struct cgroup_of_peak *ofp = of_peak(of);
4051 
4052 	spin_lock(&memcg->peaks_lock);
4053 
4054 	usage = page_counter_read(pc);
4055 	WRITE_ONCE(pc->local_watermark, usage);
4056 
4057 	list_for_each_entry(peer_ctx, watchers, list)
4058 		if (usage > peer_ctx->value)
4059 			WRITE_ONCE(peer_ctx->value, usage);
4060 
4061 	/* initial write, register watcher */
4062 	if (ofp->value == -1)
4063 		list_add(&ofp->list, watchers);
4064 
4065 	WRITE_ONCE(ofp->value, usage);
4066 	spin_unlock(&memcg->peaks_lock);
4067 
4068 	return nbytes;
4069 }
4070 
memory_peak_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)4071 static ssize_t memory_peak_write(struct kernfs_open_file *of, char *buf,
4072 				 size_t nbytes, loff_t off)
4073 {
4074 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4075 
4076 	return peak_write(of, buf, nbytes, off, &memcg->memory,
4077 			  &memcg->memory_peaks);
4078 }
4079 
4080 #undef OFP_PEAK_UNSET
4081 
memory_min_show(struct seq_file * m,void * v)4082 static int memory_min_show(struct seq_file *m, void *v)
4083 {
4084 	return seq_puts_memcg_tunable(m,
4085 		READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
4086 }
4087 
memory_min_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)4088 static ssize_t memory_min_write(struct kernfs_open_file *of,
4089 				char *buf, size_t nbytes, loff_t off)
4090 {
4091 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4092 	unsigned long min;
4093 	int err;
4094 
4095 	buf = strstrip(buf);
4096 	err = page_counter_memparse(buf, "max", &min);
4097 	if (err)
4098 		return err;
4099 
4100 	page_counter_set_min(&memcg->memory, min);
4101 
4102 	return nbytes;
4103 }
4104 
memory_low_show(struct seq_file * m,void * v)4105 static int memory_low_show(struct seq_file *m, void *v)
4106 {
4107 	return seq_puts_memcg_tunable(m,
4108 		READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
4109 }
4110 
memory_low_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)4111 static ssize_t memory_low_write(struct kernfs_open_file *of,
4112 				char *buf, size_t nbytes, loff_t off)
4113 {
4114 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4115 	unsigned long low;
4116 	int err;
4117 
4118 	buf = strstrip(buf);
4119 	err = page_counter_memparse(buf, "max", &low);
4120 	if (err)
4121 		return err;
4122 
4123 	page_counter_set_low(&memcg->memory, low);
4124 
4125 	return nbytes;
4126 }
4127 
memory_high_show(struct seq_file * m,void * v)4128 static int memory_high_show(struct seq_file *m, void *v)
4129 {
4130 	return seq_puts_memcg_tunable(m,
4131 		READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
4132 }
4133 
memory_high_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)4134 static ssize_t memory_high_write(struct kernfs_open_file *of,
4135 				 char *buf, size_t nbytes, loff_t off)
4136 {
4137 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4138 	unsigned int nr_retries = MAX_RECLAIM_RETRIES;
4139 	bool drained = false;
4140 	unsigned long high;
4141 	int err;
4142 
4143 	buf = strstrip(buf);
4144 	err = page_counter_memparse(buf, "max", &high);
4145 	if (err)
4146 		return err;
4147 
4148 	page_counter_set_high(&memcg->memory, high);
4149 
4150 	for (;;) {
4151 		unsigned long nr_pages = page_counter_read(&memcg->memory);
4152 		unsigned long reclaimed;
4153 
4154 		if (nr_pages <= high)
4155 			break;
4156 
4157 		if (signal_pending(current))
4158 			break;
4159 
4160 		if (!drained) {
4161 			drain_all_stock(memcg);
4162 			drained = true;
4163 			continue;
4164 		}
4165 
4166 		reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
4167 					GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL);
4168 
4169 		if (!reclaimed && !nr_retries--)
4170 			break;
4171 	}
4172 
4173 	memcg_wb_domain_size_changed(memcg);
4174 	return nbytes;
4175 }
4176 
memory_max_show(struct seq_file * m,void * v)4177 static int memory_max_show(struct seq_file *m, void *v)
4178 {
4179 	return seq_puts_memcg_tunable(m,
4180 		READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
4181 }
4182 
memory_max_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)4183 static ssize_t memory_max_write(struct kernfs_open_file *of,
4184 				char *buf, size_t nbytes, loff_t off)
4185 {
4186 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4187 	unsigned int nr_reclaims = MAX_RECLAIM_RETRIES;
4188 	bool drained = false;
4189 	unsigned long max;
4190 	int err;
4191 
4192 	buf = strstrip(buf);
4193 	err = page_counter_memparse(buf, "max", &max);
4194 	if (err)
4195 		return err;
4196 
4197 	xchg(&memcg->memory.max, max);
4198 
4199 	for (;;) {
4200 		unsigned long nr_pages = page_counter_read(&memcg->memory);
4201 
4202 		if (nr_pages <= max)
4203 			break;
4204 
4205 		if (signal_pending(current))
4206 			break;
4207 
4208 		if (!drained) {
4209 			drain_all_stock(memcg);
4210 			drained = true;
4211 			continue;
4212 		}
4213 
4214 		if (nr_reclaims) {
4215 			if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
4216 					GFP_KERNEL, MEMCG_RECLAIM_MAY_SWAP, NULL))
4217 				nr_reclaims--;
4218 			continue;
4219 		}
4220 
4221 		memcg_memory_event(memcg, MEMCG_OOM);
4222 		if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
4223 			break;
4224 	}
4225 
4226 	memcg_wb_domain_size_changed(memcg);
4227 	return nbytes;
4228 }
4229 
4230 /*
4231  * Note: don't forget to update the 'samples/cgroup/memcg_event_listener'
4232  * if any new events become available.
4233  */
__memory_events_show(struct seq_file * m,atomic_long_t * events)4234 static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
4235 {
4236 	seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
4237 	seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
4238 	seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
4239 	seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
4240 	seq_printf(m, "oom_kill %lu\n",
4241 		   atomic_long_read(&events[MEMCG_OOM_KILL]));
4242 	seq_printf(m, "oom_group_kill %lu\n",
4243 		   atomic_long_read(&events[MEMCG_OOM_GROUP_KILL]));
4244 }
4245 
memory_events_show(struct seq_file * m,void * v)4246 static int memory_events_show(struct seq_file *m, void *v)
4247 {
4248 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4249 
4250 	__memory_events_show(m, memcg->memory_events);
4251 	return 0;
4252 }
4253 
memory_events_local_show(struct seq_file * m,void * v)4254 static int memory_events_local_show(struct seq_file *m, void *v)
4255 {
4256 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4257 
4258 	__memory_events_show(m, memcg->memory_events_local);
4259 	return 0;
4260 }
4261 
memory_stat_show(struct seq_file * m,void * v)4262 int memory_stat_show(struct seq_file *m, void *v)
4263 {
4264 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4265 	char *buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4266 	struct seq_buf s;
4267 
4268 	if (!buf)
4269 		return -ENOMEM;
4270 	seq_buf_init(&s, buf, PAGE_SIZE);
4271 	memory_stat_format(memcg, &s);
4272 	seq_puts(m, buf);
4273 	kfree(buf);
4274 	return 0;
4275 }
4276 
4277 #ifdef CONFIG_NUMA
lruvec_page_state_output(struct lruvec * lruvec,int item)4278 static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,
4279 						     int item)
4280 {
4281 	return lruvec_page_state(lruvec, item) *
4282 		memcg_page_state_output_unit(item);
4283 }
4284 
memory_numa_stat_show(struct seq_file * m,void * v)4285 static int memory_numa_stat_show(struct seq_file *m, void *v)
4286 {
4287 	int i;
4288 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4289 
4290 	mem_cgroup_flush_stats(memcg);
4291 
4292 	for (i = 0; i < ARRAY_SIZE(memory_stats); i++) {
4293 		int nid;
4294 
4295 		if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS)
4296 			continue;
4297 
4298 		seq_printf(m, "%s", memory_stats[i].name);
4299 		for_each_node_state(nid, N_MEMORY) {
4300 			u64 size;
4301 			struct lruvec *lruvec;
4302 
4303 			lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
4304 			size = lruvec_page_state_output(lruvec,
4305 							memory_stats[i].idx);
4306 			seq_printf(m, " N%d=%llu", nid, size);
4307 		}
4308 		seq_putc(m, '\n');
4309 	}
4310 
4311 	return 0;
4312 }
4313 #endif
4314 
memory_oom_group_show(struct seq_file * m,void * v)4315 static int memory_oom_group_show(struct seq_file *m, void *v)
4316 {
4317 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
4318 
4319 	seq_printf(m, "%d\n", READ_ONCE(memcg->oom_group));
4320 
4321 	return 0;
4322 }
4323 
memory_oom_group_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)4324 static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
4325 				      char *buf, size_t nbytes, loff_t off)
4326 {
4327 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4328 	int ret, oom_group;
4329 
4330 	buf = strstrip(buf);
4331 	if (!buf)
4332 		return -EINVAL;
4333 
4334 	ret = kstrtoint(buf, 0, &oom_group);
4335 	if (ret)
4336 		return ret;
4337 
4338 	if (oom_group != 0 && oom_group != 1)
4339 		return -EINVAL;
4340 
4341 	WRITE_ONCE(memcg->oom_group, oom_group);
4342 
4343 	return nbytes;
4344 }
4345 
4346 enum {
4347 	MEMORY_RECLAIM_SWAPPINESS = 0,
4348 	MEMORY_RECLAIM_NULL,
4349 };
4350 
4351 static const match_table_t tokens = {
4352 	{ MEMORY_RECLAIM_SWAPPINESS, "swappiness=%d"},
4353 	{ MEMORY_RECLAIM_NULL, NULL },
4354 };
4355 
memory_reclaim(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)4356 static ssize_t memory_reclaim(struct kernfs_open_file *of, char *buf,
4357 			      size_t nbytes, loff_t off)
4358 {
4359 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
4360 	unsigned int nr_retries = MAX_RECLAIM_RETRIES;
4361 	unsigned long nr_to_reclaim, nr_reclaimed = 0;
4362 	int swappiness = -1;
4363 	unsigned int reclaim_options;
4364 	char *old_buf, *start;
4365 	substring_t args[MAX_OPT_ARGS];
4366 
4367 	buf = strstrip(buf);
4368 
4369 	old_buf = buf;
4370 	nr_to_reclaim = memparse(buf, &buf) / PAGE_SIZE;
4371 	if (buf == old_buf)
4372 		return -EINVAL;
4373 
4374 	buf = strstrip(buf);
4375 
4376 	while ((start = strsep(&buf, " ")) != NULL) {
4377 		if (!strlen(start))
4378 			continue;
4379 		switch (match_token(start, tokens, args)) {
4380 		case MEMORY_RECLAIM_SWAPPINESS:
4381 			if (match_int(&args[0], &swappiness))
4382 				return -EINVAL;
4383 			if (swappiness < MIN_SWAPPINESS || swappiness > MAX_SWAPPINESS)
4384 				return -EINVAL;
4385 			break;
4386 		default:
4387 			return -EINVAL;
4388 		}
4389 	}
4390 
4391 	reclaim_options	= MEMCG_RECLAIM_MAY_SWAP | MEMCG_RECLAIM_PROACTIVE;
4392 	while (nr_reclaimed < nr_to_reclaim) {
4393 		/* Will converge on zero, but reclaim enforces a minimum */
4394 		unsigned long batch_size = (nr_to_reclaim - nr_reclaimed) / 4;
4395 		unsigned long reclaimed;
4396 
4397 		if (signal_pending(current))
4398 			return -EINTR;
4399 
4400 		/*
4401 		 * This is the final attempt, drain percpu lru caches in the
4402 		 * hope of introducing more evictable pages for
4403 		 * try_to_free_mem_cgroup_pages().
4404 		 */
4405 		if (!nr_retries)
4406 			lru_add_drain_all();
4407 
4408 		reclaimed = try_to_free_mem_cgroup_pages(memcg,
4409 					batch_size, GFP_KERNEL,
4410 					reclaim_options,
4411 					swappiness == -1 ? NULL : &swappiness);
4412 
4413 		if (!reclaimed && !nr_retries--)
4414 			return -EAGAIN;
4415 
4416 		nr_reclaimed += reclaimed;
4417 	}
4418 
4419 	return nbytes;
4420 }
4421 
4422 static struct cftype memory_files[] = {
4423 	{
4424 		.name = "current",
4425 		.flags = CFTYPE_NOT_ON_ROOT,
4426 		.read_u64 = memory_current_read,
4427 	},
4428 	{
4429 		.name = "peak",
4430 		.flags = CFTYPE_NOT_ON_ROOT,
4431 		.open = peak_open,
4432 		.release = peak_release,
4433 		.seq_show = memory_peak_show,
4434 		.write = memory_peak_write,
4435 	},
4436 	{
4437 		.name = "min",
4438 		.flags = CFTYPE_NOT_ON_ROOT,
4439 		.seq_show = memory_min_show,
4440 		.write = memory_min_write,
4441 	},
4442 	{
4443 		.name = "low",
4444 		.flags = CFTYPE_NOT_ON_ROOT,
4445 		.seq_show = memory_low_show,
4446 		.write = memory_low_write,
4447 	},
4448 	{
4449 		.name = "high",
4450 		.flags = CFTYPE_NOT_ON_ROOT,
4451 		.seq_show = memory_high_show,
4452 		.write = memory_high_write,
4453 	},
4454 	{
4455 		.name = "max",
4456 		.flags = CFTYPE_NOT_ON_ROOT,
4457 		.seq_show = memory_max_show,
4458 		.write = memory_max_write,
4459 	},
4460 	{
4461 		.name = "events",
4462 		.flags = CFTYPE_NOT_ON_ROOT,
4463 		.file_offset = offsetof(struct mem_cgroup, events_file),
4464 		.seq_show = memory_events_show,
4465 	},
4466 	{
4467 		.name = "events.local",
4468 		.flags = CFTYPE_NOT_ON_ROOT,
4469 		.file_offset = offsetof(struct mem_cgroup, events_local_file),
4470 		.seq_show = memory_events_local_show,
4471 	},
4472 	{
4473 		.name = "stat",
4474 		.seq_show = memory_stat_show,
4475 	},
4476 #ifdef CONFIG_NUMA
4477 	{
4478 		.name = "numa_stat",
4479 		.seq_show = memory_numa_stat_show,
4480 	},
4481 #endif
4482 	{
4483 		.name = "oom.group",
4484 		.flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
4485 		.seq_show = memory_oom_group_show,
4486 		.write = memory_oom_group_write,
4487 	},
4488 	{
4489 		.name = "reclaim",
4490 		.flags = CFTYPE_NS_DELEGATABLE,
4491 		.write = memory_reclaim,
4492 	},
4493 	{ }	/* terminate */
4494 };
4495 
4496 struct cgroup_subsys memory_cgrp_subsys = {
4497 	.css_alloc = mem_cgroup_css_alloc,
4498 	.css_online = mem_cgroup_css_online,
4499 	.css_offline = mem_cgroup_css_offline,
4500 	.css_released = mem_cgroup_css_released,
4501 	.css_free = mem_cgroup_css_free,
4502 	.css_reset = mem_cgroup_css_reset,
4503 	.css_rstat_flush = mem_cgroup_css_rstat_flush,
4504 	.attach = mem_cgroup_attach,
4505 	.fork = mem_cgroup_fork,
4506 	.exit = mem_cgroup_exit,
4507 	.dfl_cftypes = memory_files,
4508 #ifdef CONFIG_MEMCG_V1
4509 	.can_attach = memcg1_can_attach,
4510 	.cancel_attach = memcg1_cancel_attach,
4511 	.post_attach = memcg1_move_task,
4512 	.legacy_cftypes = mem_cgroup_legacy_files,
4513 #endif
4514 	.early_init = 0,
4515 };
4516 
4517 /**
4518  * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
4519  * @root: the top ancestor of the sub-tree being checked
4520  * @memcg: the memory cgroup to check
4521  *
4522  * WARNING: This function is not stateless! It can only be used as part
4523  *          of a top-down tree iteration, not for isolated queries.
4524  */
mem_cgroup_calculate_protection(struct mem_cgroup * root,struct mem_cgroup * memcg)4525 void mem_cgroup_calculate_protection(struct mem_cgroup *root,
4526 				     struct mem_cgroup *memcg)
4527 {
4528 	bool recursive_protection =
4529 		cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT;
4530 
4531 	if (mem_cgroup_disabled())
4532 		return;
4533 
4534 	if (!root)
4535 		root = root_mem_cgroup;
4536 
4537 	page_counter_calculate_protection(&root->memory, &memcg->memory, recursive_protection);
4538 }
4539 
charge_memcg(struct folio * folio,struct mem_cgroup * memcg,gfp_t gfp)4540 static int charge_memcg(struct folio *folio, struct mem_cgroup *memcg,
4541 			gfp_t gfp)
4542 {
4543 	int ret;
4544 
4545 	ret = try_charge(memcg, gfp, folio_nr_pages(folio));
4546 	if (ret)
4547 		goto out;
4548 
4549 	mem_cgroup_commit_charge(folio, memcg);
4550 out:
4551 	return ret;
4552 }
4553 
__mem_cgroup_charge(struct folio * folio,struct mm_struct * mm,gfp_t gfp)4554 int __mem_cgroup_charge(struct folio *folio, struct mm_struct *mm, gfp_t gfp)
4555 {
4556 	struct mem_cgroup *memcg;
4557 	int ret;
4558 
4559 	memcg = get_mem_cgroup_from_mm(mm);
4560 	trace_android_vh_mem_cgroup_charge(folio, &memcg);
4561 	ret = charge_memcg(folio, memcg, gfp);
4562 	css_put(&memcg->css);
4563 
4564 	return ret;
4565 }
4566 
4567 /**
4568  * mem_cgroup_hugetlb_try_charge - try to charge the memcg for a hugetlb folio
4569  * @memcg: memcg to charge.
4570  * @gfp: reclaim mode.
4571  * @nr_pages: number of pages to charge.
4572  *
4573  * This function is called when allocating a huge page folio to determine if
4574  * the memcg has the capacity for it. It does not commit the charge yet,
4575  * as the hugetlb folio itself has not been obtained from the hugetlb pool.
4576  *
4577  * Once we have obtained the hugetlb folio, we can call
4578  * mem_cgroup_commit_charge() to commit the charge. If we fail to obtain the
4579  * folio, we should instead call mem_cgroup_cancel_charge() to undo the effect
4580  * of try_charge().
4581  *
4582  * Returns 0 on success. Otherwise, an error code is returned.
4583  */
mem_cgroup_hugetlb_try_charge(struct mem_cgroup * memcg,gfp_t gfp,long nr_pages)4584 int mem_cgroup_hugetlb_try_charge(struct mem_cgroup *memcg, gfp_t gfp,
4585 			long nr_pages)
4586 {
4587 	/*
4588 	 * If hugetlb memcg charging is not enabled, do not fail hugetlb allocation,
4589 	 * but do not attempt to commit charge later (or cancel on error) either.
4590 	 */
4591 	if (mem_cgroup_disabled() || !memcg ||
4592 		!cgroup_subsys_on_dfl(memory_cgrp_subsys) ||
4593 		!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING))
4594 		return -EOPNOTSUPP;
4595 
4596 	if (try_charge(memcg, gfp, nr_pages))
4597 		return -ENOMEM;
4598 
4599 	return 0;
4600 }
4601 
4602 /**
4603  * mem_cgroup_swapin_charge_folio - Charge a newly allocated folio for swapin.
4604  * @folio: folio to charge.
4605  * @mm: mm context of the victim
4606  * @gfp: reclaim mode
4607  * @entry: swap entry for which the folio is allocated
4608  *
4609  * This function charges a folio allocated for swapin. Please call this before
4610  * adding the folio to the swapcache.
4611  *
4612  * Returns 0 on success. Otherwise, an error code is returned.
4613  */
mem_cgroup_swapin_charge_folio(struct folio * folio,struct mm_struct * mm,gfp_t gfp,swp_entry_t entry)4614 int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm,
4615 				  gfp_t gfp, swp_entry_t entry)
4616 {
4617 	struct mem_cgroup *memcg;
4618 	unsigned short id;
4619 	int ret;
4620 
4621 	if (mem_cgroup_disabled())
4622 		return 0;
4623 
4624 	id = lookup_swap_cgroup_id(entry);
4625 	rcu_read_lock();
4626 	memcg = mem_cgroup_from_id(id);
4627 	if (!memcg || !css_tryget_online(&memcg->css))
4628 		memcg = get_mem_cgroup_from_mm(mm);
4629 	rcu_read_unlock();
4630 
4631 	ret = charge_memcg(folio, memcg, gfp);
4632 
4633 	css_put(&memcg->css);
4634 	return ret;
4635 }
4636 
4637 /*
4638  * mem_cgroup_swapin_uncharge_swap - uncharge swap slot
4639  * @entry: the first swap entry for which the pages are charged
4640  * @nr_pages: number of pages which will be uncharged
4641  *
4642  * Call this function after successfully adding the charged page to swapcache.
4643  *
4644  * Note: This function assumes the page for which swap slot is being uncharged
4645  * is order 0 page.
4646  */
mem_cgroup_swapin_uncharge_swap(swp_entry_t entry,unsigned int nr_pages)4647 void mem_cgroup_swapin_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
4648 {
4649 	/*
4650 	 * Cgroup1's unified memory+swap counter has been charged with the
4651 	 * new swapcache page, finish the transfer by uncharging the swap
4652 	 * slot. The swap slot would also get uncharged when it dies, but
4653 	 * it can stick around indefinitely and we'd count the page twice
4654 	 * the entire time.
4655 	 *
4656 	 * Cgroup2 has separate resource counters for memory and swap,
4657 	 * so this is a non-issue here. Memory and swap charge lifetimes
4658 	 * correspond 1:1 to page and swap slot lifetimes: we charge the
4659 	 * page to memory here, and uncharge swap when the slot is freed.
4660 	 */
4661 	if (!mem_cgroup_disabled() && do_memsw_account()) {
4662 		/*
4663 		 * The swap entry might not get freed for a long time,
4664 		 * let's not wait for it.  The page already received a
4665 		 * memory+swap charge, drop the swap entry duplicate.
4666 		 */
4667 		mem_cgroup_uncharge_swap(entry, nr_pages);
4668 	}
4669 }
4670 
4671 struct uncharge_gather {
4672 	struct mem_cgroup *memcg;
4673 	unsigned long nr_memory;
4674 	unsigned long pgpgout;
4675 	unsigned long nr_kmem;
4676 	int nid;
4677 };
4678 
uncharge_gather_clear(struct uncharge_gather * ug)4679 static inline void uncharge_gather_clear(struct uncharge_gather *ug)
4680 {
4681 	memset(ug, 0, sizeof(*ug));
4682 }
4683 
uncharge_batch(const struct uncharge_gather * ug)4684 static void uncharge_batch(const struct uncharge_gather *ug)
4685 {
4686 	if (ug->nr_memory) {
4687 		page_counter_uncharge(&ug->memcg->memory, ug->nr_memory);
4688 		if (do_memsw_account())
4689 			page_counter_uncharge(&ug->memcg->memsw, ug->nr_memory);
4690 		if (ug->nr_kmem) {
4691 			mod_memcg_state(ug->memcg, MEMCG_KMEM, -ug->nr_kmem);
4692 			memcg1_account_kmem(ug->memcg, -ug->nr_kmem);
4693 		}
4694 		memcg1_oom_recover(ug->memcg);
4695 	}
4696 
4697 	memcg1_uncharge_batch(ug->memcg, ug->pgpgout, ug->nr_memory, ug->nid);
4698 
4699 	/* drop reference from uncharge_folio */
4700 	css_put(&ug->memcg->css);
4701 }
4702 
uncharge_folio(struct folio * folio,struct uncharge_gather * ug)4703 static void uncharge_folio(struct folio *folio, struct uncharge_gather *ug)
4704 {
4705 	long nr_pages;
4706 	struct mem_cgroup *memcg;
4707 	struct obj_cgroup *objcg;
4708 
4709 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
4710 
4711 	/*
4712 	 * Nobody should be changing or seriously looking at
4713 	 * folio memcg or objcg at this point, we have fully
4714 	 * exclusive access to the folio.
4715 	 */
4716 	if (folio_memcg_kmem(folio)) {
4717 		objcg = __folio_objcg(folio);
4718 		/*
4719 		 * This get matches the put at the end of the function and
4720 		 * kmem pages do not hold memcg references anymore.
4721 		 */
4722 		memcg = get_mem_cgroup_from_objcg(objcg);
4723 	} else {
4724 		memcg = __folio_memcg(folio);
4725 	}
4726 
4727 	if (!memcg)
4728 		return;
4729 
4730 	if (ug->memcg != memcg) {
4731 		if (ug->memcg) {
4732 			uncharge_batch(ug);
4733 			uncharge_gather_clear(ug);
4734 		}
4735 		ug->memcg = memcg;
4736 		ug->nid = folio_nid(folio);
4737 
4738 		/* pairs with css_put in uncharge_batch */
4739 		css_get(&memcg->css);
4740 	}
4741 
4742 	nr_pages = folio_nr_pages(folio);
4743 
4744 	if (folio_memcg_kmem(folio)) {
4745 		ug->nr_memory += nr_pages;
4746 		ug->nr_kmem += nr_pages;
4747 
4748 		folio->memcg_data = 0;
4749 		obj_cgroup_put(objcg);
4750 	} else {
4751 		/* LRU pages aren't accounted at the root level */
4752 		if (!mem_cgroup_is_root(memcg))
4753 			ug->nr_memory += nr_pages;
4754 		ug->pgpgout++;
4755 
4756 		WARN_ON_ONCE(folio_unqueue_deferred_split(folio));
4757 		folio->memcg_data = 0;
4758 	}
4759 
4760 	css_put(&memcg->css);
4761 }
4762 
__mem_cgroup_uncharge(struct folio * folio)4763 void __mem_cgroup_uncharge(struct folio *folio)
4764 {
4765 	struct uncharge_gather ug;
4766 
4767 	/* Don't touch folio->lru of any random page, pre-check: */
4768 	if (!folio_memcg_charged(folio))
4769 		return;
4770 
4771 	uncharge_gather_clear(&ug);
4772 	uncharge_folio(folio, &ug);
4773 	uncharge_batch(&ug);
4774 }
4775 
__mem_cgroup_uncharge_folios(struct folio_batch * folios)4776 void __mem_cgroup_uncharge_folios(struct folio_batch *folios)
4777 {
4778 	struct uncharge_gather ug;
4779 	unsigned int i;
4780 
4781 	uncharge_gather_clear(&ug);
4782 	for (i = 0; i < folios->nr; i++)
4783 		uncharge_folio(folios->folios[i], &ug);
4784 	if (ug.memcg)
4785 		uncharge_batch(&ug);
4786 }
4787 
4788 /**
4789  * mem_cgroup_replace_folio - Charge a folio's replacement.
4790  * @old: Currently circulating folio.
4791  * @new: Replacement folio.
4792  *
4793  * Charge @new as a replacement folio for @old. @old will
4794  * be uncharged upon free.
4795  *
4796  * Both folios must be locked, @new->mapping must be set up.
4797  */
mem_cgroup_replace_folio(struct folio * old,struct folio * new)4798 void mem_cgroup_replace_folio(struct folio *old, struct folio *new)
4799 {
4800 	struct mem_cgroup *memcg;
4801 	long nr_pages = folio_nr_pages(new);
4802 
4803 	VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
4804 	VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
4805 	VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
4806 	VM_BUG_ON_FOLIO(folio_nr_pages(old) != nr_pages, new);
4807 
4808 	if (mem_cgroup_disabled())
4809 		return;
4810 
4811 	/* Page cache replacement: new folio already charged? */
4812 	if (folio_memcg_charged(new))
4813 		return;
4814 
4815 	memcg = folio_memcg(old);
4816 	VM_WARN_ON_ONCE_FOLIO(!memcg, old);
4817 	if (!memcg)
4818 		return;
4819 
4820 	/* Force-charge the new page. The old one will be freed soon */
4821 	if (!mem_cgroup_is_root(memcg)) {
4822 		page_counter_charge(&memcg->memory, nr_pages);
4823 		if (do_memsw_account())
4824 			page_counter_charge(&memcg->memsw, nr_pages);
4825 	}
4826 
4827 	css_get(&memcg->css);
4828 	commit_charge(new, memcg);
4829 	memcg1_commit_charge(new, memcg);
4830 }
4831 
4832 /**
4833  * mem_cgroup_migrate - Transfer the memcg data from the old to the new folio.
4834  * @old: Currently circulating folio.
4835  * @new: Replacement folio.
4836  *
4837  * Transfer the memcg data from the old folio to the new folio for migration.
4838  * The old folio's data info will be cleared. Note that the memory counters
4839  * will remain unchanged throughout the process.
4840  *
4841  * Both folios must be locked, @new->mapping must be set up.
4842  */
mem_cgroup_migrate(struct folio * old,struct folio * new)4843 void mem_cgroup_migrate(struct folio *old, struct folio *new)
4844 {
4845 	struct mem_cgroup *memcg;
4846 
4847 	VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
4848 	VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
4849 	VM_BUG_ON_FOLIO(folio_test_anon(old) != folio_test_anon(new), new);
4850 	VM_BUG_ON_FOLIO(folio_nr_pages(old) != folio_nr_pages(new), new);
4851 	VM_BUG_ON_FOLIO(folio_test_lru(old), old);
4852 
4853 	if (mem_cgroup_disabled())
4854 		return;
4855 
4856 	memcg = folio_memcg(old);
4857 	/*
4858 	 * Note that it is normal to see !memcg for a hugetlb folio.
4859 	 * For e.g, itt could have been allocated when memory_hugetlb_accounting
4860 	 * was not selected.
4861 	 */
4862 	VM_WARN_ON_ONCE_FOLIO(!folio_test_hugetlb(old) && !memcg, old);
4863 	if (!memcg)
4864 		return;
4865 
4866 	/* Transfer the charge and the css ref */
4867 	commit_charge(new, memcg);
4868 
4869 	/* Warning should never happen, so don't worry about refcount non-0 */
4870 	WARN_ON_ONCE(folio_unqueue_deferred_split(old));
4871 	old->memcg_data = 0;
4872 }
4873 
4874 DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
4875 EXPORT_SYMBOL(memcg_sockets_enabled_key);
4876 
mem_cgroup_sk_alloc(struct sock * sk)4877 void mem_cgroup_sk_alloc(struct sock *sk)
4878 {
4879 	struct mem_cgroup *memcg;
4880 
4881 	if (!mem_cgroup_sockets_enabled)
4882 		return;
4883 
4884 	/* Do not associate the sock with unrelated interrupted task's memcg. */
4885 	if (!in_task())
4886 		return;
4887 
4888 	rcu_read_lock();
4889 	memcg = mem_cgroup_from_task(current);
4890 	if (mem_cgroup_is_root(memcg))
4891 		goto out;
4892 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg1_tcpmem_active(memcg))
4893 		goto out;
4894 	if (css_tryget(&memcg->css))
4895 		sk->sk_memcg = memcg;
4896 out:
4897 	rcu_read_unlock();
4898 }
4899 
mem_cgroup_sk_free(struct sock * sk)4900 void mem_cgroup_sk_free(struct sock *sk)
4901 {
4902 	if (sk->sk_memcg)
4903 		css_put(&sk->sk_memcg->css);
4904 }
4905 
4906 /**
4907  * mem_cgroup_charge_skmem - charge socket memory
4908  * @memcg: memcg to charge
4909  * @nr_pages: number of pages to charge
4910  * @gfp_mask: reclaim mode
4911  *
4912  * Charges @nr_pages to @memcg. Returns %true if the charge fit within
4913  * @memcg's configured limit, %false if it doesn't.
4914  */
mem_cgroup_charge_skmem(struct mem_cgroup * memcg,unsigned int nr_pages,gfp_t gfp_mask)4915 bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
4916 			     gfp_t gfp_mask)
4917 {
4918 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
4919 		return memcg1_charge_skmem(memcg, nr_pages, gfp_mask);
4920 
4921 	if (try_charge(memcg, gfp_mask, nr_pages) == 0) {
4922 		mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
4923 		return true;
4924 	}
4925 
4926 	return false;
4927 }
4928 
4929 /**
4930  * mem_cgroup_uncharge_skmem - uncharge socket memory
4931  * @memcg: memcg to uncharge
4932  * @nr_pages: number of pages to uncharge
4933  */
mem_cgroup_uncharge_skmem(struct mem_cgroup * memcg,unsigned int nr_pages)4934 void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
4935 {
4936 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
4937 		memcg1_uncharge_skmem(memcg, nr_pages);
4938 		return;
4939 	}
4940 
4941 	mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
4942 
4943 	refill_stock(memcg, nr_pages);
4944 }
4945 
cgroup_memory(char * s)4946 static int __init cgroup_memory(char *s)
4947 {
4948 	char *token;
4949 
4950 	while ((token = strsep(&s, ",")) != NULL) {
4951 		if (!*token)
4952 			continue;
4953 		if (!strcmp(token, "nosocket"))
4954 			cgroup_memory_nosocket = true;
4955 		if (!strcmp(token, "nokmem"))
4956 			cgroup_memory_nokmem = true;
4957 		if (!strcmp(token, "nobpf"))
4958 			cgroup_memory_nobpf = true;
4959 	}
4960 	return 1;
4961 }
4962 __setup("cgroup.memory=", cgroup_memory);
4963 
4964 /*
4965  * Memory controller init before cgroup_init() initialize root_mem_cgroup.
4966  *
4967  * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
4968  * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
4969  * basically everything that doesn't depend on a specific mem_cgroup structure
4970  * should be initialized from here.
4971  */
mem_cgroup_init(void)4972 int __init mem_cgroup_init(void)
4973 {
4974 	unsigned int memcg_size;
4975 	int cpu;
4976 
4977 	/*
4978 	 * Currently s32 type (can refer to struct batched_lruvec_stat) is
4979 	 * used for per-memcg-per-cpu caching of per-node statistics. In order
4980 	 * to work fine, we should make sure that the overfill threshold can't
4981 	 * exceed S32_MAX / PAGE_SIZE.
4982 	 */
4983 	BUILD_BUG_ON(MEMCG_CHARGE_BATCH > S32_MAX / PAGE_SIZE);
4984 
4985 	cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
4986 				  memcg_hotplug_cpu_dead);
4987 
4988 	for_each_possible_cpu(cpu)
4989 		INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
4990 			  drain_local_stock);
4991 
4992 	memcg_size = struct_size_t(struct mem_cgroup, nodeinfo, nr_node_ids);
4993 	memcg_cachep = kmem_cache_create("mem_cgroup", memcg_size, 0,
4994 					 SLAB_PANIC | SLAB_HWCACHE_ALIGN, NULL);
4995 
4996 	memcg_pn_cachep = KMEM_CACHE(mem_cgroup_per_node,
4997 				     SLAB_PANIC | SLAB_HWCACHE_ALIGN);
4998 
4999 	return 0;
5000 }
5001 
5002 #ifdef CONFIG_SWAP
mem_cgroup_id_get_online(struct mem_cgroup * memcg)5003 static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
5004 {
5005 	while (!refcount_inc_not_zero(&memcg->id.ref)) {
5006 		/*
5007 		 * The root cgroup cannot be destroyed, so it's refcount must
5008 		 * always be >= 1.
5009 		 */
5010 		if (WARN_ON_ONCE(mem_cgroup_is_root(memcg))) {
5011 			VM_BUG_ON(1);
5012 			break;
5013 		}
5014 		memcg = parent_mem_cgroup(memcg);
5015 		if (!memcg)
5016 			memcg = root_mem_cgroup;
5017 	}
5018 	return memcg;
5019 }
5020 
5021 /**
5022  * mem_cgroup_swapout - transfer a memsw charge to swap
5023  * @folio: folio whose memsw charge to transfer
5024  * @entry: swap entry to move the charge to
5025  *
5026  * Transfer the memsw charge of @folio to @entry.
5027  */
mem_cgroup_swapout(struct folio * folio,swp_entry_t entry)5028 void mem_cgroup_swapout(struct folio *folio, swp_entry_t entry)
5029 {
5030 	struct mem_cgroup *memcg, *swap_memcg;
5031 	unsigned int nr_entries;
5032 	unsigned short oldid;
5033 
5034 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
5035 	VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
5036 
5037 	if (mem_cgroup_disabled())
5038 		return;
5039 
5040 	if (!do_memsw_account())
5041 		return;
5042 
5043 	memcg = folio_memcg(folio);
5044 
5045 	VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
5046 	if (!memcg)
5047 		return;
5048 
5049 	/*
5050 	 * In case the memcg owning these pages has been offlined and doesn't
5051 	 * have an ID allocated to it anymore, charge the closest online
5052 	 * ancestor for the swap instead and transfer the memory+swap charge.
5053 	 */
5054 	swap_memcg = mem_cgroup_id_get_online(memcg);
5055 	nr_entries = folio_nr_pages(folio);
5056 	/* Get references for the tail pages, too */
5057 	if (nr_entries > 1)
5058 		mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
5059 	oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
5060 				   nr_entries);
5061 	VM_BUG_ON_FOLIO(oldid, folio);
5062 	mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
5063 
5064 	folio_unqueue_deferred_split(folio);
5065 	folio->memcg_data = 0;
5066 
5067 	if (!mem_cgroup_is_root(memcg))
5068 		page_counter_uncharge(&memcg->memory, nr_entries);
5069 
5070 	if (memcg != swap_memcg) {
5071 		if (!mem_cgroup_is_root(swap_memcg))
5072 			page_counter_charge(&swap_memcg->memsw, nr_entries);
5073 		page_counter_uncharge(&memcg->memsw, nr_entries);
5074 	}
5075 
5076 	memcg1_swapout(folio, memcg);
5077 	css_put(&memcg->css);
5078 }
5079 
5080 /**
5081  * __mem_cgroup_try_charge_swap - try charging swap space for a folio
5082  * @folio: folio being added to swap
5083  * @entry: swap entry to charge
5084  *
5085  * Try to charge @folio's memcg for the swap space at @entry.
5086  *
5087  * Returns 0 on success, -ENOMEM on failure.
5088  */
__mem_cgroup_try_charge_swap(struct folio * folio,swp_entry_t entry)5089 int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
5090 {
5091 	unsigned int nr_pages = folio_nr_pages(folio);
5092 	struct page_counter *counter;
5093 	struct mem_cgroup *memcg;
5094 	unsigned short oldid;
5095 
5096 	if (do_memsw_account())
5097 		return 0;
5098 
5099 	memcg = folio_memcg(folio);
5100 
5101 	VM_WARN_ON_ONCE_FOLIO(!memcg, folio);
5102 	if (!memcg)
5103 		return 0;
5104 
5105 	if (!entry.val) {
5106 		memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
5107 		return 0;
5108 	}
5109 
5110 	memcg = mem_cgroup_id_get_online(memcg);
5111 
5112 	if (!mem_cgroup_is_root(memcg) &&
5113 	    !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
5114 		memcg_memory_event(memcg, MEMCG_SWAP_MAX);
5115 		memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
5116 		mem_cgroup_id_put(memcg);
5117 		return -ENOMEM;
5118 	}
5119 
5120 	/* Get references for the tail pages, too */
5121 	if (nr_pages > 1)
5122 		mem_cgroup_id_get_many(memcg, nr_pages - 1);
5123 	oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
5124 	VM_BUG_ON_FOLIO(oldid, folio);
5125 	mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
5126 
5127 	return 0;
5128 }
5129 
5130 /**
5131  * __mem_cgroup_uncharge_swap - uncharge swap space
5132  * @entry: swap entry to uncharge
5133  * @nr_pages: the amount of swap space to uncharge
5134  */
__mem_cgroup_uncharge_swap(swp_entry_t entry,unsigned int nr_pages)5135 void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
5136 {
5137 	struct mem_cgroup *memcg;
5138 	unsigned short id;
5139 
5140 	id = swap_cgroup_record(entry, 0, nr_pages);
5141 	rcu_read_lock();
5142 	memcg = mem_cgroup_from_id(id);
5143 	if (memcg) {
5144 		if (!mem_cgroup_is_root(memcg)) {
5145 			if (do_memsw_account())
5146 				page_counter_uncharge(&memcg->memsw, nr_pages);
5147 			else
5148 				page_counter_uncharge(&memcg->swap, nr_pages);
5149 		}
5150 		mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
5151 		mem_cgroup_id_put_many(memcg, nr_pages);
5152 	}
5153 	rcu_read_unlock();
5154 }
5155 
mem_cgroup_get_nr_swap_pages(struct mem_cgroup * memcg)5156 long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
5157 {
5158 	long nr_swap_pages = get_nr_swap_pages();
5159 
5160 	if (mem_cgroup_disabled() || do_memsw_account())
5161 		return nr_swap_pages;
5162 	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg))
5163 		nr_swap_pages = min_t(long, nr_swap_pages,
5164 				      READ_ONCE(memcg->swap.max) -
5165 				      page_counter_read(&memcg->swap));
5166 	return nr_swap_pages;
5167 }
5168 
mem_cgroup_swap_full(struct folio * folio)5169 bool mem_cgroup_swap_full(struct folio *folio)
5170 {
5171 	struct mem_cgroup *memcg;
5172 
5173 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
5174 
5175 	if (vm_swap_full())
5176 		return true;
5177 	if (do_memsw_account())
5178 		return false;
5179 
5180 	memcg = folio_memcg(folio);
5181 	if (!memcg)
5182 		return false;
5183 
5184 	for (; !mem_cgroup_is_root(memcg); memcg = parent_mem_cgroup(memcg)) {
5185 		unsigned long usage = page_counter_read(&memcg->swap);
5186 
5187 		if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
5188 		    usage * 2 >= READ_ONCE(memcg->swap.max))
5189 			return true;
5190 	}
5191 
5192 	return false;
5193 }
5194 
setup_swap_account(char * s)5195 static int __init setup_swap_account(char *s)
5196 {
5197 	bool res;
5198 
5199 	if (!kstrtobool(s, &res) && !res)
5200 		pr_warn_once("The swapaccount=0 commandline option is deprecated "
5201 			     "in favor of configuring swap control via cgroupfs. "
5202 			     "Please report your usecase to linux-mm@kvack.org if you "
5203 			     "depend on this functionality.\n");
5204 	return 1;
5205 }
5206 __setup("swapaccount=", setup_swap_account);
5207 
swap_current_read(struct cgroup_subsys_state * css,struct cftype * cft)5208 static u64 swap_current_read(struct cgroup_subsys_state *css,
5209 			     struct cftype *cft)
5210 {
5211 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5212 
5213 	return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
5214 }
5215 
swap_peak_show(struct seq_file * sf,void * v)5216 static int swap_peak_show(struct seq_file *sf, void *v)
5217 {
5218 	struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(sf));
5219 
5220 	return peak_show(sf, v, &memcg->swap);
5221 }
5222 
swap_peak_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)5223 static ssize_t swap_peak_write(struct kernfs_open_file *of, char *buf,
5224 			       size_t nbytes, loff_t off)
5225 {
5226 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5227 
5228 	return peak_write(of, buf, nbytes, off, &memcg->swap,
5229 			  &memcg->swap_peaks);
5230 }
5231 
swap_high_show(struct seq_file * m,void * v)5232 static int swap_high_show(struct seq_file *m, void *v)
5233 {
5234 	return seq_puts_memcg_tunable(m,
5235 		READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
5236 }
5237 
swap_high_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)5238 static ssize_t swap_high_write(struct kernfs_open_file *of,
5239 			       char *buf, size_t nbytes, loff_t off)
5240 {
5241 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5242 	unsigned long high;
5243 	int err;
5244 
5245 	buf = strstrip(buf);
5246 	err = page_counter_memparse(buf, "max", &high);
5247 	if (err)
5248 		return err;
5249 
5250 	page_counter_set_high(&memcg->swap, high);
5251 
5252 	return nbytes;
5253 }
5254 
swap_max_show(struct seq_file * m,void * v)5255 static int swap_max_show(struct seq_file *m, void *v)
5256 {
5257 	return seq_puts_memcg_tunable(m,
5258 		READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
5259 }
5260 
swap_max_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)5261 static ssize_t swap_max_write(struct kernfs_open_file *of,
5262 			      char *buf, size_t nbytes, loff_t off)
5263 {
5264 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5265 	unsigned long max;
5266 	int err;
5267 
5268 	buf = strstrip(buf);
5269 	err = page_counter_memparse(buf, "max", &max);
5270 	if (err)
5271 		return err;
5272 
5273 	xchg(&memcg->swap.max, max);
5274 
5275 	return nbytes;
5276 }
5277 
swap_events_show(struct seq_file * m,void * v)5278 static int swap_events_show(struct seq_file *m, void *v)
5279 {
5280 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
5281 
5282 	seq_printf(m, "high %lu\n",
5283 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
5284 	seq_printf(m, "max %lu\n",
5285 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
5286 	seq_printf(m, "fail %lu\n",
5287 		   atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
5288 
5289 	return 0;
5290 }
5291 
5292 static struct cftype swap_files[] = {
5293 	{
5294 		.name = "swap.current",
5295 		.flags = CFTYPE_NOT_ON_ROOT,
5296 		.read_u64 = swap_current_read,
5297 	},
5298 	{
5299 		.name = "swap.high",
5300 		.flags = CFTYPE_NOT_ON_ROOT,
5301 		.seq_show = swap_high_show,
5302 		.write = swap_high_write,
5303 	},
5304 	{
5305 		.name = "swap.max",
5306 		.flags = CFTYPE_NOT_ON_ROOT,
5307 		.seq_show = swap_max_show,
5308 		.write = swap_max_write,
5309 	},
5310 	{
5311 		.name = "swap.peak",
5312 		.flags = CFTYPE_NOT_ON_ROOT,
5313 		.open = peak_open,
5314 		.release = peak_release,
5315 		.seq_show = swap_peak_show,
5316 		.write = swap_peak_write,
5317 	},
5318 	{
5319 		.name = "swap.events",
5320 		.flags = CFTYPE_NOT_ON_ROOT,
5321 		.file_offset = offsetof(struct mem_cgroup, swap_events_file),
5322 		.seq_show = swap_events_show,
5323 	},
5324 	{ }	/* terminate */
5325 };
5326 
5327 #ifdef CONFIG_ZSWAP
5328 /**
5329  * obj_cgroup_may_zswap - check if this cgroup can zswap
5330  * @objcg: the object cgroup
5331  *
5332  * Check if the hierarchical zswap limit has been reached.
5333  *
5334  * This doesn't check for specific headroom, and it is not atomic
5335  * either. But with zswap, the size of the allocation is only known
5336  * once compression has occurred, and this optimistic pre-check avoids
5337  * spending cycles on compression when there is already no room left
5338  * or zswap is disabled altogether somewhere in the hierarchy.
5339  */
obj_cgroup_may_zswap(struct obj_cgroup * objcg)5340 bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
5341 {
5342 	struct mem_cgroup *memcg, *original_memcg;
5343 	bool ret = true;
5344 
5345 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
5346 		return true;
5347 
5348 	original_memcg = get_mem_cgroup_from_objcg(objcg);
5349 	for (memcg = original_memcg; !mem_cgroup_is_root(memcg);
5350 	     memcg = parent_mem_cgroup(memcg)) {
5351 		unsigned long max = READ_ONCE(memcg->zswap_max);
5352 		unsigned long pages;
5353 
5354 		if (max == PAGE_COUNTER_MAX)
5355 			continue;
5356 		if (max == 0) {
5357 			ret = false;
5358 			break;
5359 		}
5360 
5361 		/*
5362 		 * mem_cgroup_flush_stats() ignores small changes. Use
5363 		 * do_flush_stats() directly to get accurate stats for charging.
5364 		 */
5365 		do_flush_stats(memcg);
5366 		pages = memcg_page_state(memcg, MEMCG_ZSWAP_B) / PAGE_SIZE;
5367 		if (pages < max)
5368 			continue;
5369 		ret = false;
5370 		break;
5371 	}
5372 	mem_cgroup_put(original_memcg);
5373 	return ret;
5374 }
5375 
5376 /**
5377  * obj_cgroup_charge_zswap - charge compression backend memory
5378  * @objcg: the object cgroup
5379  * @size: size of compressed object
5380  *
5381  * This forces the charge after obj_cgroup_may_zswap() allowed
5382  * compression and storage in zwap for this cgroup to go ahead.
5383  */
obj_cgroup_charge_zswap(struct obj_cgroup * objcg,size_t size)5384 void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
5385 {
5386 	struct mem_cgroup *memcg;
5387 
5388 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
5389 		return;
5390 
5391 	VM_WARN_ON_ONCE(!(current->flags & PF_MEMALLOC));
5392 
5393 	/* PF_MEMALLOC context, charging must succeed */
5394 	if (obj_cgroup_charge(objcg, GFP_KERNEL, size))
5395 		VM_WARN_ON_ONCE(1);
5396 
5397 	rcu_read_lock();
5398 	memcg = obj_cgroup_memcg(objcg);
5399 	mod_memcg_state(memcg, MEMCG_ZSWAP_B, size);
5400 	mod_memcg_state(memcg, MEMCG_ZSWAPPED, 1);
5401 	rcu_read_unlock();
5402 }
5403 
5404 /**
5405  * obj_cgroup_uncharge_zswap - uncharge compression backend memory
5406  * @objcg: the object cgroup
5407  * @size: size of compressed object
5408  *
5409  * Uncharges zswap memory on page in.
5410  */
obj_cgroup_uncharge_zswap(struct obj_cgroup * objcg,size_t size)5411 void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
5412 {
5413 	struct mem_cgroup *memcg;
5414 
5415 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
5416 		return;
5417 
5418 	obj_cgroup_uncharge(objcg, size);
5419 
5420 	rcu_read_lock();
5421 	memcg = obj_cgroup_memcg(objcg);
5422 	mod_memcg_state(memcg, MEMCG_ZSWAP_B, -size);
5423 	mod_memcg_state(memcg, MEMCG_ZSWAPPED, -1);
5424 	rcu_read_unlock();
5425 }
5426 
mem_cgroup_zswap_writeback_enabled(struct mem_cgroup * memcg)5427 bool mem_cgroup_zswap_writeback_enabled(struct mem_cgroup *memcg)
5428 {
5429 	/* if zswap is disabled, do not block pages going to the swapping device */
5430 	if (!zswap_is_enabled())
5431 		return true;
5432 
5433 	for (; memcg; memcg = parent_mem_cgroup(memcg))
5434 		if (!READ_ONCE(memcg->zswap_writeback))
5435 			return false;
5436 
5437 	return true;
5438 }
5439 
zswap_current_read(struct cgroup_subsys_state * css,struct cftype * cft)5440 static u64 zswap_current_read(struct cgroup_subsys_state *css,
5441 			      struct cftype *cft)
5442 {
5443 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5444 
5445 	mem_cgroup_flush_stats(memcg);
5446 	return memcg_page_state(memcg, MEMCG_ZSWAP_B);
5447 }
5448 
zswap_max_show(struct seq_file * m,void * v)5449 static int zswap_max_show(struct seq_file *m, void *v)
5450 {
5451 	return seq_puts_memcg_tunable(m,
5452 		READ_ONCE(mem_cgroup_from_seq(m)->zswap_max));
5453 }
5454 
zswap_max_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)5455 static ssize_t zswap_max_write(struct kernfs_open_file *of,
5456 			       char *buf, size_t nbytes, loff_t off)
5457 {
5458 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5459 	unsigned long max;
5460 	int err;
5461 
5462 	buf = strstrip(buf);
5463 	err = page_counter_memparse(buf, "max", &max);
5464 	if (err)
5465 		return err;
5466 
5467 	xchg(&memcg->zswap_max, max);
5468 
5469 	return nbytes;
5470 }
5471 
zswap_writeback_show(struct seq_file * m,void * v)5472 static int zswap_writeback_show(struct seq_file *m, void *v)
5473 {
5474 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
5475 
5476 	seq_printf(m, "%d\n", READ_ONCE(memcg->zswap_writeback));
5477 	return 0;
5478 }
5479 
zswap_writeback_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)5480 static ssize_t zswap_writeback_write(struct kernfs_open_file *of,
5481 				char *buf, size_t nbytes, loff_t off)
5482 {
5483 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
5484 	int zswap_writeback;
5485 	ssize_t parse_ret = kstrtoint(strstrip(buf), 0, &zswap_writeback);
5486 
5487 	if (parse_ret)
5488 		return parse_ret;
5489 
5490 	if (zswap_writeback != 0 && zswap_writeback != 1)
5491 		return -EINVAL;
5492 
5493 	WRITE_ONCE(memcg->zswap_writeback, zswap_writeback);
5494 	return nbytes;
5495 }
5496 
5497 static struct cftype zswap_files[] = {
5498 	{
5499 		.name = "zswap.current",
5500 		.flags = CFTYPE_NOT_ON_ROOT,
5501 		.read_u64 = zswap_current_read,
5502 	},
5503 	{
5504 		.name = "zswap.max",
5505 		.flags = CFTYPE_NOT_ON_ROOT,
5506 		.seq_show = zswap_max_show,
5507 		.write = zswap_max_write,
5508 	},
5509 	{
5510 		.name = "zswap.writeback",
5511 		.seq_show = zswap_writeback_show,
5512 		.write = zswap_writeback_write,
5513 	},
5514 	{ }	/* terminate */
5515 };
5516 #endif /* CONFIG_ZSWAP */
5517 
mem_cgroup_swap_init(void)5518 static int __init mem_cgroup_swap_init(void)
5519 {
5520 	if (mem_cgroup_disabled())
5521 		return 0;
5522 
5523 	WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
5524 #ifdef CONFIG_MEMCG_V1
5525 	WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
5526 #endif
5527 #ifdef CONFIG_ZSWAP
5528 	WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, zswap_files));
5529 #endif
5530 	return 0;
5531 }
5532 subsys_initcall(mem_cgroup_swap_init);
5533 
5534 #endif /* CONFIG_SWAP */
5535