xref: /linux/mm/memcontrol-v1.c (revision 0262a5ee845c9c6b0a68ee587fffd6df01da19b5)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 
3 #include <linux/memcontrol.h>
4 #include <linux/swap.h>
5 #include <linux/mm_inline.h>
6 #include <linux/pagewalk.h>
7 #include <linux/backing-dev.h>
8 #include <linux/eventfd.h>
9 #include <linux/log2.h>
10 #include <linux/poll.h>
11 #include <linux/sort.h>
12 #include <linux/file.h>
13 #include <linux/seq_buf.h>
14 
15 #include "internal.h"
16 #include "swap.h"
17 #include "swap_table.h"
18 #include "memcontrol-v1.h"
19 
20 /* for OOM */
21 struct mem_cgroup_eventfd_list {
22 	struct list_head list;
23 	struct eventfd_ctx *eventfd;
24 };
25 
26 /*
27  * cgroup_event represents events which userspace want to receive.
28  */
29 struct mem_cgroup_event {
30 	/*
31 	 * memcg which the event belongs to.
32 	 */
33 	struct mem_cgroup *memcg;
34 	/*
35 	 * eventfd to signal userspace about the event.
36 	 */
37 	struct eventfd_ctx *eventfd;
38 	/*
39 	 * Each of these stored in a list by the cgroup.
40 	 */
41 	struct list_head list;
42 	/*
43 	 * register_event() callback will be used to add new userspace
44 	 * waiter for changes related to this event.  Use eventfd_signal()
45 	 * on eventfd to send notification to userspace.
46 	 */
47 	int (*register_event)(struct mem_cgroup *memcg,
48 			      struct eventfd_ctx *eventfd, const char *args);
49 	/*
50 	 * unregister_event() callback will be called when userspace closes
51 	 * the eventfd or on cgroup removing.  This callback must be set,
52 	 * if you want provide notification functionality.
53 	 */
54 	void (*unregister_event)(struct mem_cgroup *memcg,
55 				 struct eventfd_ctx *eventfd);
56 	/*
57 	 * All fields below needed to unregister event when
58 	 * userspace closes eventfd.
59 	 */
60 	poll_table pt;
61 	wait_queue_head_t *wqh;
62 	wait_queue_entry_t wait;
63 	struct work_struct remove;
64 };
65 
66 #define MEMFILE_PRIVATE(x, val)	((x) << 16 | (val))
67 #define MEMFILE_TYPE(val)	((val) >> 16 & 0xffff)
68 #define MEMFILE_ATTR(val)	((val) & 0xffff)
69 
70 enum {
71 	RES_USAGE,
72 	RES_LIMIT,
73 	RES_MAX_USAGE,
74 	RES_FAILCNT,
75 };
76 
77 #ifdef CONFIG_LOCKDEP
78 static struct lockdep_map memcg_oom_lock_dep_map = {
79 	.name = "memcg_oom_lock",
80 };
81 #endif
82 
83 DEFINE_SPINLOCK(memcg_oom_lock);
84 
85 static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
86 				struct cftype *cft)
87 {
88 	return 0;
89 }
90 
91 #ifdef CONFIG_MMU
92 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
93 				 struct cftype *cft, u64 val)
94 {
95 	pr_warn_once("Cgroup memory moving (move_charge_at_immigrate) is deprecated. "
96 		     "Please report your usecase to linux-mm@kvack.org if you "
97 		     "depend on this functionality.\n");
98 
99 	if (val != 0)
100 		return -EINVAL;
101 	return 0;
102 }
103 #else
104 static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
105 				 struct cftype *cft, u64 val)
106 {
107 	return -ENOSYS;
108 }
109 #endif
110 
111 static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
112 {
113 	unsigned long val;
114 
115 	if (mem_cgroup_is_root(memcg)) {
116 		/*
117 		 * Approximate root's usage from global state. This isn't
118 		 * perfect, but the root usage was always an approximation.
119 		 */
120 		val = global_node_page_state(NR_FILE_PAGES) +
121 			global_node_page_state(NR_ANON_MAPPED);
122 		if (swap)
123 			val += total_swap_pages - get_nr_swap_pages();
124 	} else {
125 		if (!swap)
126 			val = page_counter_read(&memcg->memory);
127 		else
128 			val = page_counter_read(&memcg->memsw);
129 	}
130 	return val;
131 }
132 
133 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
134 {
135 	struct mem_cgroup_threshold_ary *t;
136 	unsigned long usage;
137 	int i;
138 
139 	rcu_read_lock();
140 	if (!swap)
141 		t = rcu_dereference(memcg->thresholds.primary);
142 	else
143 		t = rcu_dereference(memcg->memsw_thresholds.primary);
144 
145 	if (!t)
146 		goto unlock;
147 
148 	usage = mem_cgroup_usage(memcg, swap);
149 
150 	/*
151 	 * current_threshold points to threshold just below or equal to usage.
152 	 * If it's not true, a threshold was crossed after last
153 	 * call of __mem_cgroup_threshold().
154 	 */
155 	i = t->current_threshold;
156 
157 	/*
158 	 * Iterate backward over array of thresholds starting from
159 	 * current_threshold and check if a threshold is crossed.
160 	 * If none of thresholds below usage is crossed, we read
161 	 * only one element of the array here.
162 	 */
163 	for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
164 		eventfd_signal(t->entries[i].eventfd);
165 
166 	/* i = current_threshold + 1 */
167 	i++;
168 
169 	/*
170 	 * Iterate forward over array of thresholds starting from
171 	 * current_threshold+1 and check if a threshold is crossed.
172 	 * If none of thresholds above usage is crossed, we read
173 	 * only one element of the array here.
174 	 */
175 	for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
176 		eventfd_signal(t->entries[i].eventfd);
177 
178 	/* Update current_threshold */
179 	t->current_threshold = i - 1;
180 unlock:
181 	rcu_read_unlock();
182 }
183 
184 static void mem_cgroup_threshold(struct mem_cgroup *memcg)
185 {
186 	while (memcg) {
187 		__mem_cgroup_threshold(memcg, false);
188 		if (do_memsw_account())
189 			__mem_cgroup_threshold(memcg, true);
190 
191 		memcg = parent_mem_cgroup(memcg);
192 	}
193 }
194 
195 /* Cgroup1: threshold notifications */
196 
197 /*
198  * Per memcg event counter is incremented at every pagein/pageout. With THP,
199  * it will be incremented by the number of pages. This counter is used
200  * to trigger some periodic events. This is straightforward and better
201  * than using jiffies etc. to handle periodic memcg event.
202  */
203 struct memcg1_events_percpu {
204 	unsigned long nr_page_events;
205 	unsigned long threshold_target;
206 };
207 
208 static void memcg1_charge_statistics(struct mem_cgroup *memcg, int nr_pages)
209 {
210 	/* pagein of a big page is an event. So, ignore page size */
211 	if (nr_pages > 0)
212 		count_memcg_events(memcg, PGPGIN, 1);
213 	else {
214 		count_memcg_events(memcg, PGPGOUT, 1);
215 		nr_pages = -nr_pages; /* for event */
216 	}
217 
218 	__this_cpu_add(memcg->events_percpu->nr_page_events, nr_pages);
219 }
220 
221 #define THRESHOLDS_EVENTS_TARGET 128
222 
223 static bool memcg1_event_ratelimit(struct mem_cgroup *memcg)
224 {
225 	unsigned long val, next;
226 
227 	val = __this_cpu_read(memcg->events_percpu->nr_page_events);
228 	next = __this_cpu_read(memcg->events_percpu->threshold_target);
229 	/* from time_after() in jiffies.h */
230 	if ((long)(next - val) < 0) {
231 		__this_cpu_write(memcg->events_percpu->threshold_target,
232 				 val + THRESHOLDS_EVENTS_TARGET);
233 		return true;
234 	}
235 	return false;
236 }
237 
238 static void memcg1_check_events(struct mem_cgroup *memcg)
239 {
240 	if (IS_ENABLED(CONFIG_PREEMPT_RT))
241 		return;
242 
243 	if (unlikely(memcg1_event_ratelimit(memcg)))
244 		mem_cgroup_threshold(memcg);
245 }
246 
247 void memcg1_commit_charge(struct folio *folio, struct mem_cgroup *memcg)
248 {
249 	unsigned long flags;
250 
251 	local_irq_save(flags);
252 	memcg1_charge_statistics(memcg, folio_nr_pages(folio));
253 	memcg1_check_events(memcg);
254 	local_irq_restore(flags);
255 }
256 
257 #ifdef CONFIG_SWAP
258 /**
259  * __memcg1_swapout - transfer a memsw charge to swap
260  * @folio: folio whose memsw charge to transfer
261  * @ci: the locked swap cluster holding the swap entries
262  *
263  * Transfer the memsw charge of @folio to the swap entry stored in
264  * folio->swap.
265  *
266  * Context: folio must be isolated, unmapped, locked and is just about to
267  * be freed, and caller must disable IRQs and hold the swap cluster lock.
268  */
269 void __memcg1_swapout(struct folio *folio, struct swap_cluster_info *ci)
270 {
271 	struct mem_cgroup *memcg;
272 	struct obj_cgroup *objcg;
273 	unsigned int nr_entries;
274 	unsigned short private_id;
275 
276 	VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio);
277 	VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
278 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
279 	VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
280 
281 	if (mem_cgroup_disabled())
282 		return;
283 
284 	if (!do_memsw_account())
285 		return;
286 
287 	objcg = folio_objcg(folio);
288 	VM_WARN_ON_ONCE_FOLIO(!objcg, folio);
289 	if (!objcg)
290 		return;
291 
292 	rcu_read_lock();
293 	memcg = obj_cgroup_memcg(objcg);
294 	/*
295 	 * In case the memcg owning these pages has been offlined and doesn't
296 	 * have an ID allocated to it anymore, charge the closest online
297 	 * ancestor for the swap instead and cancel the memory+swap charge
298 	 * if the ID refers to the root memcg.
299 	 */
300 	nr_entries = folio_nr_pages(folio);
301 	private_id = mem_cgroup_private_id_get(memcg, nr_entries);
302 	mod_memcg_state(memcg, MEMCG_SWAP, nr_entries);
303 
304 	__swap_cgroup_set(ci, swp_cluster_offset(folio->swap), nr_entries, private_id);
305 
306 	folio_unqueue_deferred_split(folio);
307 	folio->memcg_data = 0;
308 
309 	if (!obj_cgroup_is_root(objcg)) {
310 		page_counter_uncharge(&memcg->memory, nr_entries);
311 
312 		if (mem_cgroup_private_id_is_root(private_id))
313 			page_counter_uncharge(&memcg->memsw, nr_entries);
314 	}
315 
316 	/*
317 	 * The caller must hold the swap cluster lock with IRQ off. It is
318 	 * important here to have the interrupts disabled because it is the
319 	 * only synchronisation we have for updating the per-CPU variables.
320 	 */
321 	preempt_disable_nested();
322 	VM_WARN_ON_IRQS_ENABLED();
323 	memcg1_charge_statistics(memcg, -folio_nr_pages(folio));
324 	preempt_enable_nested();
325 	memcg1_check_events(memcg);
326 
327 	rcu_read_unlock();
328 	obj_cgroup_put(objcg);
329 }
330 
331 /**
332  * memcg1_swapin - uncharge swap slot on swapin
333  * @folio: folio being swapped in
334  *
335  * Call this function after successfully adding the charged
336  * folio to swapcache.
337  *
338  * Context: The folio has to be in swap cache and locked.
339  */
340 void memcg1_swapin(struct folio *folio)
341 {
342 	struct swap_cluster_info *ci;
343 	unsigned long nr_pages;
344 	unsigned short id;
345 
346 	VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio);
347 	VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio);
348 
349 	/*
350 	 * Cgroup1's unified memory+swap counter has been charged with the
351 	 * new swapcache page, finish the transfer by uncharging the swap
352 	 * slot. The swap slot would also get uncharged when it dies, but
353 	 * it can stick around indefinitely and we'd count the page twice
354 	 * the entire time.
355 	 *
356 	 * Cgroup2 has separate resource counters for memory and swap,
357 	 * so this is a non-issue here. Memory and swap charge lifetimes
358 	 * correspond 1:1 to page and swap slot lifetimes: we charge the
359 	 * page to memory here, and uncharge swap when the slot is freed.
360 	 */
361 	if (!do_memsw_account())
362 		return;
363 
364 	/*
365 	 * The swap entry might not get freed for a long time,
366 	 * let's not wait for it.  The page already received a
367 	 * memory+swap charge, drop the swap entry duplicate.
368 	 */
369 	nr_pages = folio_nr_pages(folio);
370 	ci = swap_cluster_get_and_lock(folio);
371 	id = __swap_cgroup_clear(ci, swp_cluster_offset(folio->swap),
372 				 nr_pages);
373 	swap_cluster_unlock(ci);
374 	mem_cgroup_uncharge_swap(id, nr_pages);
375 }
376 #endif
377 
378 void memcg1_uncharge_batch(struct mem_cgroup *memcg, unsigned long pgpgout,
379 			   unsigned long nr_memory)
380 {
381 	unsigned long flags;
382 
383 	local_irq_save(flags);
384 	count_memcg_events(memcg, PGPGOUT, pgpgout);
385 	__this_cpu_add(memcg->events_percpu->nr_page_events, nr_memory);
386 	memcg1_check_events(memcg);
387 	local_irq_restore(flags);
388 }
389 
390 static int compare_thresholds(const void *a, const void *b)
391 {
392 	const struct mem_cgroup_threshold *_a = a;
393 	const struct mem_cgroup_threshold *_b = b;
394 
395 	if (_a->threshold > _b->threshold)
396 		return 1;
397 
398 	if (_a->threshold < _b->threshold)
399 		return -1;
400 
401 	return 0;
402 }
403 
404 static void mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
405 {
406 	struct mem_cgroup_eventfd_list *ev;
407 
408 	spin_lock(&memcg_oom_lock);
409 
410 	list_for_each_entry(ev, &memcg->oom_notify, list)
411 		eventfd_signal(ev->eventfd);
412 
413 	spin_unlock(&memcg_oom_lock);
414 }
415 
416 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
417 {
418 	struct mem_cgroup *iter;
419 
420 	for_each_mem_cgroup_tree(iter, memcg)
421 		mem_cgroup_oom_notify_cb(iter);
422 }
423 
424 static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
425 	struct eventfd_ctx *eventfd, const char *args, enum res_type type)
426 {
427 	struct mem_cgroup_thresholds *thresholds;
428 	struct mem_cgroup_threshold_ary *new;
429 	unsigned long threshold;
430 	unsigned long usage;
431 	int i, size, ret;
432 
433 	ret = page_counter_memparse(args, "-1", &threshold);
434 	if (ret)
435 		return ret;
436 
437 	mutex_lock(&memcg->thresholds_lock);
438 
439 	if (type == _MEM) {
440 		thresholds = &memcg->thresholds;
441 		usage = mem_cgroup_usage(memcg, false);
442 	} else if (type == _MEMSWAP) {
443 		thresholds = &memcg->memsw_thresholds;
444 		usage = mem_cgroup_usage(memcg, true);
445 	} else
446 		BUG();
447 
448 	/* Check if a threshold crossed before adding a new one */
449 	if (thresholds->primary)
450 		__mem_cgroup_threshold(memcg, type == _MEMSWAP);
451 
452 	size = thresholds->primary ? thresholds->primary->size + 1 : 1;
453 
454 	/* Allocate memory for new array of thresholds */
455 	new = kmalloc_flex(*new, entries, size, GFP_KERNEL_ACCOUNT);
456 	if (!new) {
457 		ret = -ENOMEM;
458 		goto unlock;
459 	}
460 	new->size = size;
461 
462 	/* Copy thresholds (if any) to new array */
463 	if (thresholds->primary)
464 		memcpy(new->entries, thresholds->primary->entries,
465 		       flex_array_size(new, entries, size - 1));
466 
467 	/* Add new threshold */
468 	new->entries[size - 1].eventfd = eventfd;
469 	new->entries[size - 1].threshold = threshold;
470 
471 	/* Sort thresholds. Registering of new threshold isn't time-critical */
472 	sort(new->entries, size, sizeof(*new->entries),
473 			compare_thresholds, NULL);
474 
475 	/* Find current threshold */
476 	new->current_threshold = -1;
477 	for (i = 0; i < size; i++) {
478 		if (new->entries[i].threshold <= usage) {
479 			/*
480 			 * new->current_threshold will not be used until
481 			 * rcu_assign_pointer(), so it's safe to increment
482 			 * it here.
483 			 */
484 			++new->current_threshold;
485 		} else
486 			break;
487 	}
488 
489 	/* Free old spare buffer and save old primary buffer as spare */
490 	kfree(thresholds->spare);
491 	thresholds->spare = thresholds->primary;
492 
493 	rcu_assign_pointer(thresholds->primary, new);
494 
495 	/* To be sure that nobody uses thresholds */
496 	synchronize_rcu();
497 
498 unlock:
499 	mutex_unlock(&memcg->thresholds_lock);
500 
501 	return ret;
502 }
503 
504 static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
505 	struct eventfd_ctx *eventfd, const char *args)
506 {
507 	return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
508 }
509 
510 static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
511 	struct eventfd_ctx *eventfd, const char *args)
512 {
513 	return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
514 }
515 
516 static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
517 	struct eventfd_ctx *eventfd, enum res_type type)
518 {
519 	struct mem_cgroup_thresholds *thresholds;
520 	struct mem_cgroup_threshold_ary *new;
521 	unsigned long usage;
522 	int i, j, size, entries;
523 
524 	mutex_lock(&memcg->thresholds_lock);
525 
526 	if (type == _MEM) {
527 		thresholds = &memcg->thresholds;
528 		usage = mem_cgroup_usage(memcg, false);
529 	} else if (type == _MEMSWAP) {
530 		thresholds = &memcg->memsw_thresholds;
531 		usage = mem_cgroup_usage(memcg, true);
532 	} else
533 		BUG();
534 
535 	if (!thresholds->primary)
536 		goto unlock;
537 
538 	/* Check if a threshold crossed before removing */
539 	__mem_cgroup_threshold(memcg, type == _MEMSWAP);
540 
541 	/* Calculate new number of threshold */
542 	size = entries = 0;
543 	for (i = 0; i < thresholds->primary->size; i++) {
544 		if (thresholds->primary->entries[i].eventfd != eventfd)
545 			size++;
546 		else
547 			entries++;
548 	}
549 
550 	new = thresholds->spare;
551 
552 	/* If no items related to eventfd have been cleared, nothing to do */
553 	if (!entries)
554 		goto unlock;
555 
556 	/* Set thresholds array to NULL if we don't have thresholds */
557 	if (!size) {
558 		kfree(new);
559 		new = NULL;
560 		goto swap_buffers;
561 	}
562 
563 	new->size = size;
564 
565 	/* Copy thresholds and find current threshold */
566 	new->current_threshold = -1;
567 	for (i = 0, j = 0; i < thresholds->primary->size; i++) {
568 		if (thresholds->primary->entries[i].eventfd == eventfd)
569 			continue;
570 
571 		new->entries[j] = thresholds->primary->entries[i];
572 		if (new->entries[j].threshold <= usage) {
573 			/*
574 			 * new->current_threshold will not be used
575 			 * until rcu_assign_pointer(), so it's safe to increment
576 			 * it here.
577 			 */
578 			++new->current_threshold;
579 		}
580 		j++;
581 	}
582 
583 swap_buffers:
584 	/* Swap primary and spare array */
585 	thresholds->spare = thresholds->primary;
586 
587 	rcu_assign_pointer(thresholds->primary, new);
588 
589 	/* To be sure that nobody uses thresholds */
590 	synchronize_rcu();
591 
592 	/* If all events are unregistered, free the spare array */
593 	if (!new) {
594 		kfree(thresholds->spare);
595 		thresholds->spare = NULL;
596 	}
597 unlock:
598 	mutex_unlock(&memcg->thresholds_lock);
599 }
600 
601 static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
602 	struct eventfd_ctx *eventfd)
603 {
604 	return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
605 }
606 
607 static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
608 	struct eventfd_ctx *eventfd)
609 {
610 	return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
611 }
612 
613 static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
614 	struct eventfd_ctx *eventfd, const char *args)
615 {
616 	struct mem_cgroup_eventfd_list *event;
617 
618 	event = kmalloc_obj(*event, GFP_KERNEL_ACCOUNT);
619 	if (!event)
620 		return -ENOMEM;
621 
622 	spin_lock(&memcg_oom_lock);
623 
624 	event->eventfd = eventfd;
625 	list_add(&event->list, &memcg->oom_notify);
626 
627 	/* already in OOM ? */
628 	if (memcg->under_oom)
629 		eventfd_signal(eventfd);
630 	spin_unlock(&memcg_oom_lock);
631 
632 	return 0;
633 }
634 
635 static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
636 	struct eventfd_ctx *eventfd)
637 {
638 	struct mem_cgroup_eventfd_list *ev, *tmp;
639 
640 	spin_lock(&memcg_oom_lock);
641 
642 	list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
643 		if (ev->eventfd == eventfd) {
644 			list_del(&ev->list);
645 			kfree(ev);
646 		}
647 	}
648 
649 	spin_unlock(&memcg_oom_lock);
650 }
651 
652 /*
653  * DO NOT USE IN NEW FILES.
654  *
655  * "cgroup.event_control" implementation.
656  *
657  * This is way over-engineered.  It tries to support fully configurable
658  * events for each user.  Such level of flexibility is completely
659  * unnecessary especially in the light of the planned unified hierarchy.
660  *
661  * Please deprecate this and replace with something simpler if at all
662  * possible.
663  */
664 
665 /*
666  * Unregister event and free resources.
667  *
668  * Gets called from workqueue.
669  */
670 static void memcg_event_remove(struct work_struct *work)
671 {
672 	struct mem_cgroup_event *event =
673 		container_of(work, struct mem_cgroup_event, remove);
674 	struct mem_cgroup *memcg = event->memcg;
675 
676 	remove_wait_queue(event->wqh, &event->wait);
677 
678 	event->unregister_event(memcg, event->eventfd);
679 
680 	/* Notify userspace the event is going away. */
681 	eventfd_signal(event->eventfd);
682 
683 	eventfd_ctx_put(event->eventfd);
684 	kfree(event);
685 	css_put(&memcg->css);
686 }
687 
688 /*
689  * Gets called on EPOLLHUP on eventfd when user closes it.
690  *
691  * Called with wqh->lock held and interrupts disabled.
692  */
693 static int memcg_event_wake(wait_queue_entry_t *wait, unsigned int mode,
694 			    int sync, void *key)
695 {
696 	struct mem_cgroup_event *event =
697 		container_of(wait, struct mem_cgroup_event, wait);
698 	struct mem_cgroup *memcg = event->memcg;
699 	__poll_t flags = key_to_poll(key);
700 
701 	if (flags & EPOLLHUP) {
702 		/*
703 		 * If the event has been detached at cgroup removal, we
704 		 * can simply return knowing the other side will cleanup
705 		 * for us.
706 		 *
707 		 * We can't race against event freeing since the other
708 		 * side will require wqh->lock via remove_wait_queue(),
709 		 * which we hold.
710 		 */
711 		spin_lock(&memcg->event_list_lock);
712 		if (!list_empty(&event->list)) {
713 			list_del_init(&event->list);
714 			/*
715 			 * We are in atomic context, but cgroup_event_remove()
716 			 * may sleep, so we have to call it in workqueue.
717 			 */
718 			schedule_work(&event->remove);
719 		}
720 		spin_unlock(&memcg->event_list_lock);
721 	}
722 
723 	return 0;
724 }
725 
726 static void memcg_event_ptable_queue_proc(struct file *file,
727 		wait_queue_head_t *wqh, poll_table *pt)
728 {
729 	struct mem_cgroup_event *event =
730 		container_of(pt, struct mem_cgroup_event, pt);
731 
732 	event->wqh = wqh;
733 	add_wait_queue(wqh, &event->wait);
734 }
735 
736 /*
737  * DO NOT USE IN NEW FILES.
738  *
739  * Parse input and register new cgroup event handler.
740  *
741  * Input must be in format '<event_fd> <control_fd> <args>'.
742  * Interpretation of args is defined by control file implementation.
743  */
744 static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
745 					 char *buf, size_t nbytes, loff_t off)
746 {
747 	struct cgroup_subsys_state *css = of_css(of);
748 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
749 	struct mem_cgroup_event *event;
750 	struct cgroup_subsys_state *cfile_css;
751 	unsigned int efd, cfd;
752 	struct dentry *cdentry;
753 	const char *name;
754 	char *endp;
755 	int ret;
756 
757 	if (IS_ENABLED(CONFIG_PREEMPT_RT))
758 		return -EOPNOTSUPP;
759 
760 	buf = strstrip(buf);
761 
762 	efd = simple_strtoul(buf, &endp, 10);
763 	if (*endp != ' ')
764 		return -EINVAL;
765 	buf = endp + 1;
766 
767 	cfd = simple_strtoul(buf, &endp, 10);
768 	if (*endp == '\0')
769 		buf = endp;
770 	else if (*endp == ' ')
771 		buf = endp + 1;
772 	else
773 		return -EINVAL;
774 
775 	CLASS(fd, efile)(efd);
776 	if (fd_empty(efile))
777 		return -EBADF;
778 
779 	CLASS(fd, cfile)(cfd);
780 
781 	event = kzalloc_obj(*event, GFP_KERNEL_ACCOUNT);
782 	if (!event)
783 		return -ENOMEM;
784 
785 	event->memcg = memcg;
786 	INIT_LIST_HEAD(&event->list);
787 	init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
788 	init_waitqueue_func_entry(&event->wait, memcg_event_wake);
789 	INIT_WORK(&event->remove, memcg_event_remove);
790 
791 	event->eventfd = eventfd_ctx_fileget(fd_file(efile));
792 	if (IS_ERR(event->eventfd)) {
793 		ret = PTR_ERR(event->eventfd);
794 		goto out_kfree;
795 	}
796 
797 	if (fd_empty(cfile)) {
798 		ret = -EBADF;
799 		goto out_put_eventfd;
800 	}
801 
802 	/* the process need read permission on control file */
803 	/* AV: shouldn't we check that it's been opened for read instead? */
804 	ret = file_permission(fd_file(cfile), MAY_READ);
805 	if (ret < 0)
806 		goto out_put_eventfd;
807 
808 	/*
809 	 * The control file must be a regular cgroup1 file. As a regular cgroup
810 	 * file can't be renamed, it's safe to access its name afterwards.
811 	 */
812 	cdentry = fd_file(cfile)->f_path.dentry;
813 	if (cdentry->d_sb->s_type != &cgroup_fs_type || !d_is_reg(cdentry)) {
814 		ret = -EINVAL;
815 		goto out_put_eventfd;
816 	}
817 
818 	/*
819 	 * Determine the event callbacks and set them in @event.  This used
820 	 * to be done via struct cftype but cgroup core no longer knows
821 	 * about these events.  The following is crude but the whole thing
822 	 * is for compatibility anyway.
823 	 *
824 	 * DO NOT ADD NEW FILES.
825 	 */
826 	name = cdentry->d_name.name;
827 
828 	if (!strcmp(name, "memory.usage_in_bytes")) {
829 		event->register_event = mem_cgroup_usage_register_event;
830 		event->unregister_event = mem_cgroup_usage_unregister_event;
831 	} else if (!strcmp(name, "memory.oom_control")) {
832 		pr_warn_once("oom_control is deprecated and will be removed. "
833 			     "Please report your usecase to linux-mm@kvack.org"
834 			     " if you depend on this functionality.\n");
835 		event->register_event = mem_cgroup_oom_register_event;
836 		event->unregister_event = mem_cgroup_oom_unregister_event;
837 	} else if (!strcmp(name, "memory.pressure_level")) {
838 		pr_warn_once("pressure_level is deprecated and will be removed. "
839 			     "Please report your usecase to linux-mm@kvack.org "
840 			     "if you depend on this functionality.\n");
841 		event->register_event = vmpressure_register_event;
842 		event->unregister_event = vmpressure_unregister_event;
843 	} else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
844 		event->register_event = memsw_cgroup_usage_register_event;
845 		event->unregister_event = memsw_cgroup_usage_unregister_event;
846 	} else {
847 		ret = -EINVAL;
848 		goto out_put_eventfd;
849 	}
850 
851 	/*
852 	 * Verify @cfile should belong to @css.  Also, remaining events are
853 	 * automatically removed on cgroup destruction but the removal is
854 	 * asynchronous, so take an extra ref on @css.
855 	 */
856 	cfile_css = css_tryget_online_from_dir(cdentry->d_parent,
857 					       &memory_cgrp_subsys);
858 	ret = -EINVAL;
859 	if (IS_ERR(cfile_css))
860 		goto out_put_eventfd;
861 	if (cfile_css != css)
862 		goto out_put_css;
863 
864 	ret = event->register_event(memcg, event->eventfd, buf);
865 	if (ret)
866 		goto out_put_css;
867 
868 	vfs_poll(fd_file(efile), &event->pt);
869 
870 	spin_lock_irq(&memcg->event_list_lock);
871 	list_add(&event->list, &memcg->event_list);
872 	spin_unlock_irq(&memcg->event_list_lock);
873 	return nbytes;
874 
875 out_put_css:
876 	css_put(cfile_css);
877 out_put_eventfd:
878 	eventfd_ctx_put(event->eventfd);
879 out_kfree:
880 	kfree(event);
881 	return ret;
882 }
883 
884 void memcg1_memcg_init(struct mem_cgroup *memcg)
885 {
886 	INIT_LIST_HEAD(&memcg->oom_notify);
887 	mutex_init(&memcg->thresholds_lock);
888 	INIT_LIST_HEAD(&memcg->event_list);
889 	spin_lock_init(&memcg->event_list_lock);
890 }
891 
892 void memcg1_css_offline(struct mem_cgroup *memcg)
893 {
894 	struct mem_cgroup_event *event, *tmp;
895 
896 	/*
897 	 * Unregister events and notify userspace.
898 	 * Notify userspace about cgroup removing only after rmdir of cgroup
899 	 * directory to avoid race between userspace and kernelspace.
900 	 */
901 	spin_lock_irq(&memcg->event_list_lock);
902 	list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
903 		list_del_init(&event->list);
904 		schedule_work(&event->remove);
905 	}
906 	spin_unlock_irq(&memcg->event_list_lock);
907 }
908 
909 /*
910  * Check OOM-Killer is already running under our hierarchy.
911  * If someone is running, return false.
912  */
913 static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
914 {
915 	struct mem_cgroup *iter, *failed = NULL;
916 
917 	spin_lock(&memcg_oom_lock);
918 
919 	for_each_mem_cgroup_tree(iter, memcg) {
920 		if (iter->oom_lock) {
921 			/*
922 			 * this subtree of our hierarchy is already locked
923 			 * so we cannot give a lock.
924 			 */
925 			failed = iter;
926 			mem_cgroup_iter_break(memcg, iter);
927 			break;
928 		}
929 		iter->oom_lock = true;
930 	}
931 
932 	if (failed) {
933 		/*
934 		 * OK, we failed to lock the whole subtree so we have
935 		 * to clean up what we set up to the failing subtree
936 		 */
937 		for_each_mem_cgroup_tree(iter, memcg) {
938 			if (iter == failed) {
939 				mem_cgroup_iter_break(memcg, iter);
940 				break;
941 			}
942 			iter->oom_lock = false;
943 		}
944 	} else
945 		mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
946 
947 	spin_unlock(&memcg_oom_lock);
948 
949 	return !failed;
950 }
951 
952 static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
953 {
954 	struct mem_cgroup *iter;
955 
956 	spin_lock(&memcg_oom_lock);
957 	mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
958 	for_each_mem_cgroup_tree(iter, memcg)
959 		iter->oom_lock = false;
960 	spin_unlock(&memcg_oom_lock);
961 }
962 
963 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
964 {
965 	struct mem_cgroup *iter;
966 
967 	spin_lock(&memcg_oom_lock);
968 	for_each_mem_cgroup_tree(iter, memcg)
969 		iter->under_oom++;
970 	spin_unlock(&memcg_oom_lock);
971 }
972 
973 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
974 {
975 	struct mem_cgroup *iter;
976 
977 	/*
978 	 * Be careful about under_oom underflows because a child memcg
979 	 * could have been added after mem_cgroup_mark_under_oom.
980 	 */
981 	spin_lock(&memcg_oom_lock);
982 	for_each_mem_cgroup_tree(iter, memcg)
983 		if (iter->under_oom > 0)
984 			iter->under_oom--;
985 	spin_unlock(&memcg_oom_lock);
986 }
987 
988 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
989 
990 struct oom_wait_info {
991 	struct mem_cgroup *memcg;
992 	wait_queue_entry_t	wait;
993 };
994 
995 static int memcg_oom_wake_function(wait_queue_entry_t *wait,
996 	unsigned int mode, int sync, void *arg)
997 {
998 	struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
999 	struct mem_cgroup *oom_wait_memcg;
1000 	struct oom_wait_info *oom_wait_info;
1001 
1002 	oom_wait_info = container_of(wait, struct oom_wait_info, wait);
1003 	oom_wait_memcg = oom_wait_info->memcg;
1004 
1005 	if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1006 	    !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
1007 		return 0;
1008 	return autoremove_wake_function(wait, mode, sync, arg);
1009 }
1010 
1011 void memcg1_oom_recover(struct mem_cgroup *memcg)
1012 {
1013 	/*
1014 	 * For the following lockless ->under_oom test, the only required
1015 	 * guarantee is that it must see the state asserted by an OOM when
1016 	 * this function is called as a result of userland actions
1017 	 * triggered by the notification of the OOM.  This is trivially
1018 	 * achieved by invoking mem_cgroup_mark_under_oom() before
1019 	 * triggering notification.
1020 	 */
1021 	if (memcg && memcg->under_oom)
1022 		__wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
1023 }
1024 
1025 /**
1026  * mem_cgroup_oom_synchronize - complete memcg OOM handling
1027  * @handle: actually kill/wait or just clean up the OOM state
1028  *
1029  * This has to be called at the end of a page fault if the memcg OOM
1030  * handler was enabled.
1031  *
1032  * Memcg supports userspace OOM handling where failed allocations must
1033  * sleep on a waitqueue until the userspace task resolves the
1034  * situation.  Sleeping directly in the charge context with all kinds
1035  * of locks held is not a good idea, instead we remember an OOM state
1036  * in the task and mem_cgroup_oom_synchronize() has to be called at
1037  * the end of the page fault to complete the OOM handling.
1038  *
1039  * Returns %true if an ongoing memcg OOM situation was detected and
1040  * completed, %false otherwise.
1041  */
1042 bool mem_cgroup_oom_synchronize(bool handle)
1043 {
1044 	struct mem_cgroup *memcg = current->memcg_in_oom;
1045 	struct oom_wait_info owait;
1046 	bool locked;
1047 
1048 	/* OOM is global, do not handle */
1049 	if (!memcg)
1050 		return false;
1051 
1052 	if (!handle)
1053 		goto cleanup;
1054 
1055 	owait.memcg = memcg;
1056 	owait.wait.flags = 0;
1057 	owait.wait.func = memcg_oom_wake_function;
1058 	owait.wait.private = current;
1059 	INIT_LIST_HEAD(&owait.wait.entry);
1060 
1061 	prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
1062 	mem_cgroup_mark_under_oom(memcg);
1063 
1064 	locked = mem_cgroup_oom_trylock(memcg);
1065 
1066 	if (locked)
1067 		mem_cgroup_oom_notify(memcg);
1068 
1069 	schedule();
1070 	mem_cgroup_unmark_under_oom(memcg);
1071 	finish_wait(&memcg_oom_waitq, &owait.wait);
1072 
1073 	if (locked)
1074 		mem_cgroup_oom_unlock(memcg);
1075 cleanup:
1076 	current->memcg_in_oom = NULL;
1077 	css_put(&memcg->css);
1078 	return true;
1079 }
1080 
1081 
1082 bool memcg1_oom_prepare(struct mem_cgroup *memcg, bool *locked)
1083 {
1084 	/*
1085 	 * We are in the middle of the charge context here, so we
1086 	 * don't want to block when potentially sitting on a callstack
1087 	 * that holds all kinds of filesystem and mm locks.
1088 	 *
1089 	 * cgroup1 allows disabling the OOM killer and waiting for outside
1090 	 * handling until the charge can succeed; remember the context and put
1091 	 * the task to sleep at the end of the page fault when all locks are
1092 	 * released.
1093 	 *
1094 	 * On the other hand, in-kernel OOM killer allows for an async victim
1095 	 * memory reclaim (oom_reaper) and that means that we are not solely
1096 	 * relying on the oom victim to make a forward progress and we can
1097 	 * invoke the oom killer here.
1098 	 *
1099 	 * Please note that mem_cgroup_out_of_memory might fail to find a
1100 	 * victim and then we have to bail out from the charge path.
1101 	 */
1102 	if (READ_ONCE(memcg->oom_kill_disable)) {
1103 		if (current->in_user_fault) {
1104 			css_get(&memcg->css);
1105 			current->memcg_in_oom = memcg;
1106 		}
1107 		return false;
1108 	}
1109 
1110 	mem_cgroup_mark_under_oom(memcg);
1111 
1112 	*locked = mem_cgroup_oom_trylock(memcg);
1113 
1114 	if (*locked)
1115 		mem_cgroup_oom_notify(memcg);
1116 
1117 	mem_cgroup_unmark_under_oom(memcg);
1118 
1119 	return true;
1120 }
1121 
1122 void memcg1_oom_finish(struct mem_cgroup *memcg, bool locked)
1123 {
1124 	if (locked)
1125 		mem_cgroup_oom_unlock(memcg);
1126 }
1127 
1128 /*
1129  * cgroup v1 userspace vmpressure interface (memory.pressure_level /
1130  * cgroup.event_control). Kept here so v2-only kernels (CONFIG_MEMCG_V1=n)
1131  * drop the whole eventfd accumulator, its work item, and the per-memcg
1132  * state it requires.
1133  *
1134  * When there are too little pages left to scan, vmpressure() may miss the
1135  * critical pressure as number of pages will be less than "window size".
1136  * However, in that case the vmscan priority will raise fast as the
1137  * reclaimer will try to scan LRUs more deeply.
1138  *
1139  * The vmscan logic considers these special priorities:
1140  *
1141  * prio == DEF_PRIORITY (12): reclaimer starts with that value
1142  * prio <= DEF_PRIORITY - 2 : kswapd becomes somewhat overwhelmed
1143  * prio == 0                : close to OOM, kernel scans every page in an lru
1144  *
1145  * Any value in this range is acceptable for this tunable (i.e. from 12 to
1146  * 0). Current value for the vmpressure_level_critical_prio is chosen
1147  * empirically, but the number, in essence, means that we consider
1148  * critical level when scanning depth is ~10% of the lru size (vmscan
1149  * scans 'lru_size >> prio' pages, so it is actually 12.5%, or one
1150  * eights).
1151  */
1152 static const unsigned int vmpressure_level_critical_prio = ilog2(100 / 10);
1153 
1154 enum vmpressure_modes {
1155 	VMPRESSURE_NO_PASSTHROUGH = 0,
1156 	VMPRESSURE_HIERARCHY,
1157 	VMPRESSURE_LOCAL,
1158 	VMPRESSURE_NUM_MODES,
1159 };
1160 
1161 static const char * const vmpressure_str_levels[] = {
1162 	[VMPRESSURE_LOW] = "low",
1163 	[VMPRESSURE_MEDIUM] = "medium",
1164 	[VMPRESSURE_CRITICAL] = "critical",
1165 };
1166 
1167 static const char * const vmpressure_str_modes[] = {
1168 	[VMPRESSURE_NO_PASSTHROUGH] = "default",
1169 	[VMPRESSURE_HIERARCHY] = "hierarchy",
1170 	[VMPRESSURE_LOCAL] = "local",
1171 };
1172 
1173 struct vmpressure_event {
1174 	struct eventfd_ctx *efd;
1175 	enum vmpressure_levels level;
1176 	enum vmpressure_modes mode;
1177 	struct list_head node;
1178 };
1179 
1180 static struct vmpressure *work_to_vmpressure(struct work_struct *work)
1181 {
1182 	return container_of(work, struct vmpressure, work);
1183 }
1184 
1185 static struct vmpressure *vmpressure_parent(struct vmpressure *vmpr)
1186 {
1187 	struct mem_cgroup *memcg = vmpressure_to_memcg(vmpr);
1188 
1189 	memcg = parent_mem_cgroup(memcg);
1190 	if (!memcg)
1191 		return NULL;
1192 	return memcg_to_vmpressure(memcg);
1193 }
1194 
1195 static bool vmpressure_event(struct vmpressure *vmpr,
1196 			     const enum vmpressure_levels level,
1197 			     bool ancestor, bool signalled)
1198 {
1199 	struct vmpressure_event *ev;
1200 	bool ret = false;
1201 
1202 	mutex_lock(&vmpr->events_lock);
1203 	list_for_each_entry(ev, &vmpr->events, node) {
1204 		if (ancestor && ev->mode == VMPRESSURE_LOCAL)
1205 			continue;
1206 		if (signalled && ev->mode == VMPRESSURE_NO_PASSTHROUGH)
1207 			continue;
1208 		if (level < ev->level)
1209 			continue;
1210 		eventfd_signal(ev->efd);
1211 		ret = true;
1212 	}
1213 	mutex_unlock(&vmpr->events_lock);
1214 
1215 	return ret;
1216 }
1217 
1218 static void vmpressure_work_fn(struct work_struct *work)
1219 {
1220 	struct vmpressure *vmpr = work_to_vmpressure(work);
1221 	unsigned long scanned;
1222 	unsigned long reclaimed;
1223 	enum vmpressure_levels level;
1224 	bool ancestor = false;
1225 	bool signalled = false;
1226 
1227 	spin_lock(&vmpr->sr_lock);
1228 	/*
1229 	 * Several contexts might be calling vmpressure(), so it is
1230 	 * possible that the work was rescheduled again before the old
1231 	 * work context cleared the counters. In that case we will run
1232 	 * just after the old work returns, but then scanned might be zero
1233 	 * here. No need for any locks here since we don't care if
1234 	 * vmpr->reclaimed is in sync.
1235 	 */
1236 	scanned = vmpr->tree_scanned;
1237 	if (!scanned) {
1238 		spin_unlock(&vmpr->sr_lock);
1239 		return;
1240 	}
1241 
1242 	reclaimed = vmpr->tree_reclaimed;
1243 	vmpr->tree_scanned = 0;
1244 	vmpr->tree_reclaimed = 0;
1245 	spin_unlock(&vmpr->sr_lock);
1246 
1247 	level = vmpressure_calc_level(scanned, reclaimed);
1248 
1249 	do {
1250 		if (vmpressure_event(vmpr, level, ancestor, signalled))
1251 			signalled = true;
1252 		ancestor = true;
1253 	} while ((vmpr = vmpressure_parent(vmpr)));
1254 }
1255 
1256 /*
1257  * Tree-mode accumulator: accumulate per-memcg scanned/reclaimed and
1258  * schedule the work that walks the parent chain and signals registered
1259  * eventfd listeners once we cross the window threshold.
1260  */
1261 void vmpressure_v1_account_tree(struct vmpressure *vmpr,
1262 				unsigned long scanned,
1263 				unsigned long reclaimed)
1264 {
1265 	spin_lock(&vmpr->sr_lock);
1266 	scanned = vmpr->tree_scanned += scanned;
1267 	vmpr->tree_reclaimed += reclaimed;
1268 	spin_unlock(&vmpr->sr_lock);
1269 
1270 	if (scanned < vmpressure_win)
1271 		return;
1272 	schedule_work(&vmpr->work);
1273 }
1274 
1275 void vmpressure_v1_init(struct vmpressure *vmpr)
1276 {
1277 	mutex_init(&vmpr->events_lock);
1278 	INIT_LIST_HEAD(&vmpr->events);
1279 	INIT_WORK(&vmpr->work, vmpressure_work_fn);
1280 }
1281 
1282 void vmpressure_v1_cleanup(struct vmpressure *vmpr)
1283 {
1284 	/*
1285 	 * Make sure there is no pending work before eventfd infrastructure
1286 	 * goes away.
1287 	 */
1288 	flush_work(&vmpr->work);
1289 }
1290 
1291 /**
1292  * vmpressure_prio() - Account memory pressure through reclaimer priority level
1293  * @gfp:	reclaimer's gfp mask
1294  * @memcg:	cgroup memory controller handle
1295  * @prio:	reclaimer's priority
1296  *
1297  * This function should be called from the reclaim path every time when
1298  * the vmscan's reclaiming priority (scanning depth) changes.
1299  *
1300  * This function does not return any value.
1301  */
1302 void vmpressure_prio(gfp_t gfp, struct mem_cgroup *memcg, int prio)
1303 {
1304 	/*
1305 	 * We only use prio for accounting critical level. For more info
1306 	 * see comment for vmpressure_level_critical_prio variable above.
1307 	 */
1308 	if (prio > vmpressure_level_critical_prio)
1309 		return;
1310 
1311 	/*
1312 	 * OK, the prio is below the threshold, updating vmpressure
1313 	 * information before shrinker dives into long shrinking of long
1314 	 * range vmscan. Passing scanned = vmpressure_win, reclaimed = 0
1315 	 * to the vmpressure() basically means that we signal 'critical'
1316 	 * level.
1317 	 */
1318 	vmpressure(gfp, 0, memcg, true, vmpressure_win, 0);
1319 }
1320 
1321 #define MAX_VMPRESSURE_ARGS_LEN	(strlen("critical") + strlen("hierarchy") + 2)
1322 
1323 /**
1324  * vmpressure_register_event() - Bind vmpressure notifications to an eventfd
1325  * @memcg:	memcg that is interested in vmpressure notifications
1326  * @eventfd:	eventfd context to link notifications with
1327  * @args:	event arguments (pressure level threshold, optional mode)
1328  *
1329  * This function associates eventfd context with the vmpressure
1330  * infrastructure, so that the notifications will be delivered to the
1331  * @eventfd. The @args parameter is a comma-delimited string that denotes a
1332  * pressure level threshold (one of vmpressure_str_levels, i.e. "low", "medium",
1333  * or "critical") and an optional mode (one of vmpressure_str_modes, i.e.
1334  * "hierarchy" or "local").
1335  *
1336  * To be used as memcg event method.
1337  *
1338  * Return: 0 on success, -ENOMEM on memory failure or -EINVAL if @args could
1339  * not be parsed.
1340  */
1341 int vmpressure_register_event(struct mem_cgroup *memcg,
1342 			      struct eventfd_ctx *eventfd, const char *args)
1343 {
1344 	struct vmpressure *vmpr = memcg_to_vmpressure(memcg);
1345 	struct vmpressure_event *ev;
1346 	enum vmpressure_modes mode = VMPRESSURE_NO_PASSTHROUGH;
1347 	enum vmpressure_levels level;
1348 	char *spec, *spec_orig;
1349 	char *token;
1350 	int ret = 0;
1351 
1352 	spec_orig = spec = kstrndup(args, MAX_VMPRESSURE_ARGS_LEN, GFP_KERNEL);
1353 	if (!spec)
1354 		return -ENOMEM;
1355 
1356 	/* Find required level */
1357 	token = strsep(&spec, ",");
1358 	ret = match_string(vmpressure_str_levels, VMPRESSURE_NUM_LEVELS, token);
1359 	if (ret < 0)
1360 		goto out;
1361 	level = ret;
1362 
1363 	/* Find optional mode */
1364 	token = strsep(&spec, ",");
1365 	if (token) {
1366 		ret = match_string(vmpressure_str_modes, VMPRESSURE_NUM_MODES, token);
1367 		if (ret < 0)
1368 			goto out;
1369 		mode = ret;
1370 	}
1371 
1372 	ev = kzalloc_obj(*ev, GFP_KERNEL_ACCOUNT);
1373 	if (!ev) {
1374 		ret = -ENOMEM;
1375 		goto out;
1376 	}
1377 
1378 	ev->efd = eventfd;
1379 	ev->level = level;
1380 	ev->mode = mode;
1381 
1382 	mutex_lock(&vmpr->events_lock);
1383 	list_add(&ev->node, &vmpr->events);
1384 	mutex_unlock(&vmpr->events_lock);
1385 	ret = 0;
1386 out:
1387 	kfree(spec_orig);
1388 	return ret;
1389 }
1390 
1391 /**
1392  * vmpressure_unregister_event() - Unbind eventfd from vmpressure
1393  * @memcg:	memcg handle
1394  * @eventfd:	eventfd context that was used to link vmpressure with the @cg
1395  *
1396  * This function does internal manipulations to detach the @eventfd from
1397  * the vmpressure notifications, and then frees internal resources
1398  * associated with the @eventfd (but the @eventfd itself is not freed).
1399  *
1400  * To be used as memcg event method.
1401  */
1402 void vmpressure_unregister_event(struct mem_cgroup *memcg,
1403 				 struct eventfd_ctx *eventfd)
1404 {
1405 	struct vmpressure *vmpr = memcg_to_vmpressure(memcg);
1406 	struct vmpressure_event *ev;
1407 
1408 	mutex_lock(&vmpr->events_lock);
1409 	list_for_each_entry(ev, &vmpr->events, node) {
1410 		if (ev->efd != eventfd)
1411 			continue;
1412 		list_del(&ev->node);
1413 		kfree(ev);
1414 		break;
1415 	}
1416 	mutex_unlock(&vmpr->events_lock);
1417 }
1418 
1419 static DEFINE_MUTEX(memcg_max_mutex);
1420 
1421 static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
1422 				 unsigned long max, bool memsw)
1423 {
1424 	bool enlarge = false;
1425 	bool drained = false;
1426 	int ret;
1427 	bool limits_invariant;
1428 	struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
1429 
1430 	do {
1431 		if (signal_pending(current)) {
1432 			ret = -EINTR;
1433 			break;
1434 		}
1435 
1436 		mutex_lock(&memcg_max_mutex);
1437 		/*
1438 		 * Make sure that the new limit (memsw or memory limit) doesn't
1439 		 * break our basic invariant rule memory.max <= memsw.max.
1440 		 */
1441 		limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
1442 					   max <= memcg->memsw.max;
1443 		if (!limits_invariant) {
1444 			mutex_unlock(&memcg_max_mutex);
1445 			ret = -EINVAL;
1446 			break;
1447 		}
1448 		if (max > counter->max)
1449 			enlarge = true;
1450 		ret = page_counter_set_max(counter, max);
1451 		mutex_unlock(&memcg_max_mutex);
1452 
1453 		if (!ret)
1454 			break;
1455 
1456 		/* cgroup_rmdir() waits for us with cgroup_mutex held. */
1457 		if (memcg_is_dying(memcg))
1458 			break;
1459 
1460 		if (!drained) {
1461 			drain_all_stock(memcg);
1462 			drained = true;
1463 			continue;
1464 		}
1465 
1466 		if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
1467 				memsw ? 0 : MEMCG_RECLAIM_MAY_SWAP, NULL)) {
1468 			ret = -EBUSY;
1469 			break;
1470 		}
1471 	} while (true);
1472 
1473 	if (!ret && enlarge)
1474 		memcg1_oom_recover(memcg);
1475 
1476 	return ret;
1477 }
1478 
1479 /*
1480  * Reclaims as many pages from the given memcg as possible.
1481  *
1482  * Caller is responsible for holding css reference for memcg.
1483  */
1484 static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
1485 {
1486 	int nr_retries = MAX_RECLAIM_RETRIES;
1487 
1488 	/* we call try-to-free pages for make this cgroup empty */
1489 	lru_add_drain_all();
1490 
1491 	drain_all_stock(memcg);
1492 
1493 	/* try to free all pages in this cgroup */
1494 	while (nr_retries && page_counter_read(&memcg->memory)) {
1495 		if (signal_pending(current))
1496 			return -EINTR;
1497 
1498 		/* cgroup_rmdir() waits for us with cgroup_mutex held. */
1499 		if (memcg_is_dying(memcg))
1500 			break;
1501 
1502 		if (!try_to_free_mem_cgroup_pages(memcg, 1, GFP_KERNEL,
1503 						  MEMCG_RECLAIM_MAY_SWAP, NULL))
1504 			nr_retries--;
1505 	}
1506 
1507 	return 0;
1508 }
1509 
1510 static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
1511 					    char *buf, size_t nbytes,
1512 					    loff_t off)
1513 {
1514 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
1515 
1516 	if (mem_cgroup_is_root(memcg))
1517 		return -EINVAL;
1518 	return mem_cgroup_force_empty(memcg) ?: nbytes;
1519 }
1520 
1521 static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
1522 				     struct cftype *cft)
1523 {
1524 	return 1;
1525 }
1526 
1527 static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
1528 				      struct cftype *cft, u64 val)
1529 {
1530 	if (val == 1)
1531 		return 0;
1532 
1533 	pr_warn_once("Non-hierarchical mode is deprecated. "
1534 		     "Please report your usecase to linux-mm@kvack.org if you "
1535 		     "depend on this functionality.\n");
1536 
1537 	return -EINVAL;
1538 }
1539 
1540 static u64 mem_cgroup_soft_limit_read(struct cgroup_subsys_state *css,
1541 				      struct cftype *cft)
1542 {
1543 	return (u64)PAGE_COUNTER_MAX * PAGE_SIZE;
1544 }
1545 
1546 static ssize_t mem_cgroup_soft_limit_write(struct kernfs_open_file *of,
1547 					   char *buf, size_t nbytes, loff_t off)
1548 {
1549 	unsigned long nr_pages;
1550 	int ret;
1551 
1552 	ret = page_counter_memparse(strstrip(buf), "-1", &nr_pages);
1553 	if (ret)
1554 		return ret;
1555 
1556 	pr_warn_once("soft_limit_in_bytes is deprecated and will be removed. "
1557 		     "Writing any value to this file has no effect. "
1558 		     "Please report your usecase to linux-mm@kvack.org if you "
1559 		     "depend on this functionality.\n");
1560 
1561 	return nbytes;
1562 }
1563 
1564 static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
1565 			       struct cftype *cft)
1566 {
1567 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
1568 	struct page_counter *counter;
1569 
1570 	switch (MEMFILE_TYPE(cft->private)) {
1571 	case _MEM:
1572 		counter = &memcg->memory;
1573 		break;
1574 	case _MEMSWAP:
1575 		counter = &memcg->memsw;
1576 		break;
1577 	case _KMEM:
1578 		counter = &memcg->kmem;
1579 		break;
1580 	case _TCP:
1581 		counter = &memcg->tcpmem;
1582 		break;
1583 	default:
1584 		BUG();
1585 	}
1586 
1587 	switch (MEMFILE_ATTR(cft->private)) {
1588 	case RES_USAGE:
1589 		if (counter == &memcg->memory)
1590 			return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
1591 		if (counter == &memcg->memsw)
1592 			return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
1593 		return (u64)page_counter_read(counter) * PAGE_SIZE;
1594 	case RES_LIMIT:
1595 		return (u64)counter->max * PAGE_SIZE;
1596 	case RES_MAX_USAGE:
1597 		return (u64)counter->watermark * PAGE_SIZE;
1598 	case RES_FAILCNT:
1599 		return counter->failcnt;
1600 	default:
1601 		BUG();
1602 	}
1603 }
1604 
1605 /*
1606  * This function doesn't do anything useful. Its only job is to provide a read
1607  * handler for a file so that cgroup_file_mode() will add read permissions.
1608  */
1609 static int mem_cgroup_dummy_seq_show(__always_unused struct seq_file *m,
1610 				     __always_unused void *v)
1611 {
1612 	return -EINVAL;
1613 }
1614 
1615 static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
1616 {
1617 	int ret;
1618 
1619 	mutex_lock(&memcg_max_mutex);
1620 
1621 	ret = page_counter_set_max(&memcg->tcpmem, max);
1622 	if (ret)
1623 		goto out;
1624 
1625 	if (!memcg->tcpmem_active) {
1626 		/*
1627 		 * The active flag needs to be written after the static_key
1628 		 * update. This is what guarantees that the socket activation
1629 		 * function is the last one to run. See mem_cgroup_sk_alloc()
1630 		 * for details, and note that we don't mark any socket as
1631 		 * belonging to this memcg until that flag is up.
1632 		 *
1633 		 * We need to do this, because static_keys will span multiple
1634 		 * sites, but we can't control their order. If we mark a socket
1635 		 * as accounted, but the accounting functions are not patched in
1636 		 * yet, we'll lose accounting.
1637 		 *
1638 		 * We never race with the readers in mem_cgroup_sk_alloc(),
1639 		 * because when this value change, the code to process it is not
1640 		 * patched in yet.
1641 		 */
1642 		static_branch_inc(&memcg_sockets_enabled_key);
1643 		memcg->tcpmem_active = true;
1644 	}
1645 out:
1646 	mutex_unlock(&memcg_max_mutex);
1647 	return ret;
1648 }
1649 
1650 /*
1651  * The user of this function is...
1652  * RES_LIMIT.
1653  */
1654 static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
1655 				char *buf, size_t nbytes, loff_t off)
1656 {
1657 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
1658 	unsigned long nr_pages;
1659 	int ret;
1660 
1661 	buf = strstrip(buf);
1662 	ret = page_counter_memparse(buf, "-1", &nr_pages);
1663 	if (ret)
1664 		return ret;
1665 
1666 	switch (MEMFILE_ATTR(of_cft(of)->private)) {
1667 	case RES_LIMIT:
1668 		if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
1669 			ret = -EINVAL;
1670 			break;
1671 		}
1672 		switch (MEMFILE_TYPE(of_cft(of)->private)) {
1673 		case _MEM:
1674 			ret = mem_cgroup_resize_max(memcg, nr_pages, false);
1675 			break;
1676 		case _MEMSWAP:
1677 			ret = mem_cgroup_resize_max(memcg, nr_pages, true);
1678 			break;
1679 		case _KMEM:
1680 			pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
1681 				     "Writing any value to this file has no effect. "
1682 				     "Please report your usecase to linux-mm@kvack.org if you "
1683 				     "depend on this functionality.\n");
1684 			ret = 0;
1685 			break;
1686 		case _TCP:
1687 			pr_warn_once("kmem.tcp.limit_in_bytes is deprecated and will be removed. "
1688 				     "Please report your usecase to linux-mm@kvack.org if you "
1689 				     "depend on this functionality.\n");
1690 			ret = memcg_update_tcp_max(memcg, nr_pages);
1691 			break;
1692 		}
1693 		break;
1694 	}
1695 	return ret ?: nbytes;
1696 }
1697 
1698 static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
1699 				size_t nbytes, loff_t off)
1700 {
1701 	struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
1702 	struct page_counter *counter;
1703 
1704 	switch (MEMFILE_TYPE(of_cft(of)->private)) {
1705 	case _MEM:
1706 		counter = &memcg->memory;
1707 		break;
1708 	case _MEMSWAP:
1709 		counter = &memcg->memsw;
1710 		break;
1711 	case _KMEM:
1712 		counter = &memcg->kmem;
1713 		break;
1714 	case _TCP:
1715 		counter = &memcg->tcpmem;
1716 		break;
1717 	default:
1718 		BUG();
1719 	}
1720 
1721 	switch (MEMFILE_ATTR(of_cft(of)->private)) {
1722 	case RES_MAX_USAGE:
1723 		page_counter_reset_watermark(counter);
1724 		break;
1725 	case RES_FAILCNT:
1726 		counter->failcnt = 0;
1727 		break;
1728 	default:
1729 		BUG();
1730 	}
1731 
1732 	return nbytes;
1733 }
1734 
1735 #ifdef CONFIG_NUMA
1736 
1737 #define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
1738 #define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
1739 #define LRU_ALL	     ((1 << NR_LRU_LISTS) - 1)
1740 
1741 static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
1742 				int nid, unsigned int lru_mask, bool tree)
1743 {
1744 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
1745 	unsigned long nr = 0;
1746 	enum lru_list lru;
1747 
1748 	VM_BUG_ON((unsigned int)nid >= nr_node_ids);
1749 
1750 	for_each_lru(lru) {
1751 		if (!(BIT(lru) & lru_mask))
1752 			continue;
1753 		if (tree)
1754 			nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
1755 		else
1756 			nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
1757 	}
1758 	return nr;
1759 }
1760 
1761 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
1762 					     unsigned int lru_mask,
1763 					     bool tree)
1764 {
1765 	unsigned long nr = 0;
1766 	enum lru_list lru;
1767 
1768 	for_each_lru(lru) {
1769 		if (!(BIT(lru) & lru_mask))
1770 			continue;
1771 		if (tree)
1772 			nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
1773 		else
1774 			nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
1775 	}
1776 	return nr;
1777 }
1778 
1779 static int memcg_numa_stat_show(struct seq_file *m, void *v)
1780 {
1781 	struct numa_stat {
1782 		const char *name;
1783 		unsigned int lru_mask;
1784 	};
1785 
1786 	static const struct numa_stat stats[] = {
1787 		{ "total", LRU_ALL },
1788 		{ "file", LRU_ALL_FILE },
1789 		{ "anon", LRU_ALL_ANON },
1790 		{ "unevictable", BIT(LRU_UNEVICTABLE) },
1791 	};
1792 	const struct numa_stat *stat;
1793 	int nid;
1794 	struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
1795 
1796 	mem_cgroup_flush_stats(memcg);
1797 
1798 	for (stat = stats; stat < ARRAY_END(stats); stat++) {
1799 		seq_printf(m, "%s=%lu", stat->name,
1800 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
1801 						   false));
1802 		for_each_node_state(nid, N_MEMORY)
1803 			seq_printf(m, " N%d=%lu", nid,
1804 				   mem_cgroup_node_nr_lru_pages(memcg, nid,
1805 							stat->lru_mask, false));
1806 		seq_putc(m, '\n');
1807 	}
1808 
1809 	for (stat = stats; stat < ARRAY_END(stats); stat++) {
1810 
1811 		seq_printf(m, "hierarchical_%s=%lu", stat->name,
1812 			   mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
1813 						   true));
1814 		for_each_node_state(nid, N_MEMORY)
1815 			seq_printf(m, " N%d=%lu", nid,
1816 				   mem_cgroup_node_nr_lru_pages(memcg, nid,
1817 							stat->lru_mask, true));
1818 		seq_putc(m, '\n');
1819 	}
1820 
1821 	return 0;
1822 }
1823 #endif /* CONFIG_NUMA */
1824 
1825 static const unsigned int memcg1_stats[] = {
1826 	NR_FILE_PAGES,
1827 	NR_ANON_MAPPED,
1828 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1829 	NR_ANON_THPS,
1830 #endif
1831 	NR_SHMEM,
1832 	NR_FILE_MAPPED,
1833 	NR_FILE_DIRTY,
1834 	NR_WRITEBACK,
1835 	WORKINGSET_REFAULT_ANON,
1836 	WORKINGSET_REFAULT_FILE,
1837 #ifdef CONFIG_SWAP
1838 	MEMCG_SWAP,
1839 	NR_SWAPCACHE,
1840 #endif
1841 };
1842 
1843 static const char *const memcg1_stat_names[] = {
1844 	"cache",
1845 	"rss",
1846 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1847 	"rss_huge",
1848 #endif
1849 	"shmem",
1850 	"mapped_file",
1851 	"dirty",
1852 	"writeback",
1853 	"workingset_refault_anon",
1854 	"workingset_refault_file",
1855 #ifdef CONFIG_SWAP
1856 	"swap",
1857 	"swapcached",
1858 #endif
1859 };
1860 
1861 /* Universal VM events cgroup1 shows, original sort order */
1862 static const unsigned int memcg1_events[] = {
1863 	PGPGIN,
1864 	PGPGOUT,
1865 	PGFAULT,
1866 	PGMAJFAULT,
1867 };
1868 
1869 void reparent_memcg1_state_local(struct mem_cgroup *memcg, struct mem_cgroup *parent)
1870 {
1871 	int i;
1872 
1873 	for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++)
1874 		reparent_memcg_state_local(memcg, parent, memcg1_stats[i]);
1875 }
1876 
1877 void reparent_memcg1_lruvec_state_local(struct mem_cgroup *memcg, struct mem_cgroup *parent)
1878 {
1879 	int i;
1880 
1881 	for (i = 0; i < NR_LRU_LISTS; i++)
1882 		reparent_memcg_lruvec_state_local(memcg, parent, i);
1883 }
1884 
1885 void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)
1886 {
1887 	unsigned long memory, memsw;
1888 	struct mem_cgroup *mi;
1889 	unsigned int i;
1890 
1891 	BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
1892 
1893 	mem_cgroup_flush_stats(memcg);
1894 
1895 	for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
1896 		unsigned long nr;
1897 
1898 		nr = memcg_page_state_local_output(memcg, memcg1_stats[i]);
1899 		seq_buf_printf(s, "%s %lu\n", memcg1_stat_names[i], nr);
1900 	}
1901 
1902 	for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
1903 		seq_buf_printf(s, "%s %lu\n", vm_event_name(memcg1_events[i]),
1904 			       memcg_events_local(memcg, memcg1_events[i]));
1905 
1906 	for (i = 0; i < NR_LRU_LISTS; i++)
1907 		seq_buf_printf(s, "%s %lu\n", lru_list_name(i),
1908 			       memcg_page_state_local(memcg, NR_LRU_BASE + i) *
1909 			       PAGE_SIZE);
1910 
1911 	/* Hierarchical information */
1912 	memory = memsw = PAGE_COUNTER_MAX;
1913 	for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
1914 		memory = min(memory, READ_ONCE(mi->memory.max));
1915 		memsw = min(memsw, READ_ONCE(mi->memsw.max));
1916 	}
1917 	seq_buf_printf(s, "hierarchical_memory_limit %llu\n",
1918 		       (u64)memory * PAGE_SIZE);
1919 	seq_buf_printf(s, "hierarchical_memsw_limit %llu\n",
1920 		       (u64)memsw * PAGE_SIZE);
1921 
1922 	for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
1923 		unsigned long nr;
1924 
1925 		nr = memcg_page_state_output(memcg, memcg1_stats[i]);
1926 		seq_buf_printf(s, "total_%s %llu\n", memcg1_stat_names[i],
1927 			       (u64)nr);
1928 	}
1929 
1930 	for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
1931 		seq_buf_printf(s, "total_%s %llu\n",
1932 			       vm_event_name(memcg1_events[i]),
1933 			       (u64)memcg_events(memcg, memcg1_events[i]));
1934 
1935 	for (i = 0; i < NR_LRU_LISTS; i++)
1936 		seq_buf_printf(s, "total_%s %llu\n", lru_list_name(i),
1937 			       (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
1938 			       PAGE_SIZE);
1939 
1940 #ifdef CONFIG_DEBUG_VM
1941 	{
1942 		pg_data_t *pgdat;
1943 		struct mem_cgroup_per_node *mz;
1944 		unsigned long anon_cost = 0;
1945 		unsigned long file_cost = 0;
1946 
1947 		for_each_online_pgdat(pgdat) {
1948 			mz = memcg->nodeinfo[pgdat->node_id];
1949 
1950 			anon_cost += mz->lruvec.cost[WORKINGSET_ANON].count;
1951 			file_cost += mz->lruvec.cost[WORKINGSET_FILE].count;
1952 		}
1953 		seq_buf_printf(s, "anon_cost %lu\n", anon_cost);
1954 		seq_buf_printf(s, "file_cost %lu\n", file_cost);
1955 	}
1956 #endif
1957 }
1958 
1959 static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
1960 				      struct cftype *cft)
1961 {
1962 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
1963 
1964 	return mem_cgroup_swappiness(memcg);
1965 }
1966 
1967 static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
1968 				       struct cftype *cft, u64 val)
1969 {
1970 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
1971 
1972 	if (val > MAX_SWAPPINESS)
1973 		return -EINVAL;
1974 
1975 	if (!mem_cgroup_is_root(memcg)) {
1976 		pr_info_once("Per memcg swappiness does not exist in cgroup v2. "
1977 			     "See memory.reclaim or memory.swap.max there\n ");
1978 		WRITE_ONCE(memcg->swappiness, val);
1979 	} else
1980 		WRITE_ONCE(vm_swappiness, val);
1981 
1982 	return 0;
1983 }
1984 
1985 static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
1986 {
1987 	struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
1988 
1989 	seq_printf(sf, "oom_kill_disable %d\n", READ_ONCE(memcg->oom_kill_disable));
1990 	seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
1991 	seq_printf(sf, "oom_kill %lu\n",
1992 		   atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
1993 	return 0;
1994 }
1995 
1996 static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
1997 	struct cftype *cft, u64 val)
1998 {
1999 	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
2000 
2001 	pr_warn_once("oom_control is deprecated and will be removed. "
2002 		     "Please report your usecase to linux-mm@kvack.org if you "
2003 		     "depend on this functionality.\n");
2004 
2005 	/* cannot set to root cgroup and only 0 and 1 are allowed */
2006 	if (mem_cgroup_is_root(memcg) || !((val == 0) || (val == 1)))
2007 		return -EINVAL;
2008 
2009 	WRITE_ONCE(memcg->oom_kill_disable, val);
2010 	if (!val)
2011 		memcg1_oom_recover(memcg);
2012 
2013 	return 0;
2014 }
2015 
2016 #ifdef CONFIG_SLUB_DEBUG
2017 static int mem_cgroup_slab_show(struct seq_file *m, void *p)
2018 {
2019 	/*
2020 	 * Deprecated.
2021 	 * Please, take a look at tools/cgroup/memcg_slabinfo.py .
2022 	 */
2023 	return 0;
2024 }
2025 #endif
2026 
2027 struct cftype mem_cgroup_legacy_files[] = {
2028 	{
2029 		.name = "usage_in_bytes",
2030 		.private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
2031 		.read_u64 = mem_cgroup_read_u64,
2032 	},
2033 	{
2034 		.name = "max_usage_in_bytes",
2035 		.private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
2036 		.write = mem_cgroup_reset,
2037 		.read_u64 = mem_cgroup_read_u64,
2038 	},
2039 	{
2040 		.name = "limit_in_bytes",
2041 		.private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
2042 		.write = mem_cgroup_write,
2043 		.read_u64 = mem_cgroup_read_u64,
2044 	},
2045 	{
2046 		.name = "soft_limit_in_bytes",
2047 		.write = mem_cgroup_soft_limit_write,
2048 		.read_u64 = mem_cgroup_soft_limit_read,
2049 	},
2050 	{
2051 		.name = "failcnt",
2052 		.private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
2053 		.write = mem_cgroup_reset,
2054 		.read_u64 = mem_cgroup_read_u64,
2055 	},
2056 	{
2057 		.name = "stat",
2058 		.seq_show = memory_stat_show,
2059 	},
2060 	{
2061 		.name = "force_empty",
2062 		.write = mem_cgroup_force_empty_write,
2063 	},
2064 	{
2065 		.name = "use_hierarchy",
2066 		.write_u64 = mem_cgroup_hierarchy_write,
2067 		.read_u64 = mem_cgroup_hierarchy_read,
2068 	},
2069 	{
2070 		.name = "cgroup.event_control",		/* XXX: for compat */
2071 		.write = memcg_write_event_control,
2072 		.flags = CFTYPE_NO_PREFIX,
2073 	},
2074 	{
2075 		.name = "swappiness",
2076 		.read_u64 = mem_cgroup_swappiness_read,
2077 		.write_u64 = mem_cgroup_swappiness_write,
2078 	},
2079 	{
2080 		.name = "move_charge_at_immigrate",
2081 		.read_u64 = mem_cgroup_move_charge_read,
2082 		.write_u64 = mem_cgroup_move_charge_write,
2083 	},
2084 	{
2085 		.name = "oom_control",
2086 		.seq_show = mem_cgroup_oom_control_read,
2087 		.write_u64 = mem_cgroup_oom_control_write,
2088 	},
2089 	{
2090 		.name = "pressure_level",
2091 		.seq_show = mem_cgroup_dummy_seq_show,
2092 	},
2093 #ifdef CONFIG_NUMA
2094 	{
2095 		.name = "numa_stat",
2096 		.seq_show = memcg_numa_stat_show,
2097 	},
2098 #endif
2099 	{
2100 		.name = "kmem.limit_in_bytes",
2101 		.private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
2102 		.write = mem_cgroup_write,
2103 		.read_u64 = mem_cgroup_read_u64,
2104 	},
2105 	{
2106 		.name = "kmem.usage_in_bytes",
2107 		.private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
2108 		.read_u64 = mem_cgroup_read_u64,
2109 	},
2110 	{
2111 		.name = "kmem.failcnt",
2112 		.private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
2113 		.write = mem_cgroup_reset,
2114 		.read_u64 = mem_cgroup_read_u64,
2115 	},
2116 	{
2117 		.name = "kmem.max_usage_in_bytes",
2118 		.private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
2119 		.write = mem_cgroup_reset,
2120 		.read_u64 = mem_cgroup_read_u64,
2121 	},
2122 #ifdef CONFIG_SLUB_DEBUG
2123 	{
2124 		.name = "kmem.slabinfo",
2125 		.seq_show = mem_cgroup_slab_show,
2126 	},
2127 #endif
2128 	{
2129 		.name = "kmem.tcp.limit_in_bytes",
2130 		.private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
2131 		.write = mem_cgroup_write,
2132 		.read_u64 = mem_cgroup_read_u64,
2133 	},
2134 	{
2135 		.name = "kmem.tcp.usage_in_bytes",
2136 		.private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
2137 		.read_u64 = mem_cgroup_read_u64,
2138 	},
2139 	{
2140 		.name = "kmem.tcp.failcnt",
2141 		.private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
2142 		.write = mem_cgroup_reset,
2143 		.read_u64 = mem_cgroup_read_u64,
2144 	},
2145 	{
2146 		.name = "kmem.tcp.max_usage_in_bytes",
2147 		.private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
2148 		.write = mem_cgroup_reset,
2149 		.read_u64 = mem_cgroup_read_u64,
2150 	},
2151 	{ },	/* terminate */
2152 };
2153 
2154 struct cftype memsw_files[] = {
2155 	{
2156 		.name = "memsw.usage_in_bytes",
2157 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
2158 		.read_u64 = mem_cgroup_read_u64,
2159 	},
2160 	{
2161 		.name = "memsw.max_usage_in_bytes",
2162 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
2163 		.write = mem_cgroup_reset,
2164 		.read_u64 = mem_cgroup_read_u64,
2165 	},
2166 	{
2167 		.name = "memsw.limit_in_bytes",
2168 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
2169 		.write = mem_cgroup_write,
2170 		.read_u64 = mem_cgroup_read_u64,
2171 	},
2172 	{
2173 		.name = "memsw.failcnt",
2174 		.private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
2175 		.write = mem_cgroup_reset,
2176 		.read_u64 = mem_cgroup_read_u64,
2177 	},
2178 	{ },	/* terminate */
2179 };
2180 
2181 void memcg1_account_kmem(struct mem_cgroup *memcg, int nr_pages)
2182 {
2183 	if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
2184 		if (nr_pages > 0)
2185 			page_counter_charge(&memcg->kmem, nr_pages);
2186 		else
2187 			page_counter_uncharge(&memcg->kmem, -nr_pages);
2188 	}
2189 }
2190 
2191 bool memcg1_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages,
2192 			 gfp_t gfp_mask)
2193 {
2194 	struct page_counter *fail;
2195 
2196 	if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
2197 		memcg->tcpmem_pressure = 0;
2198 		return true;
2199 	}
2200 	memcg->tcpmem_pressure = 1;
2201 	if (gfp_mask & __GFP_NOFAIL) {
2202 		page_counter_charge(&memcg->tcpmem, nr_pages);
2203 		return true;
2204 	}
2205 	return false;
2206 }
2207 
2208 bool memcg1_alloc_events(struct mem_cgroup *memcg)
2209 {
2210 	memcg->events_percpu = alloc_percpu_gfp(struct memcg1_events_percpu,
2211 						GFP_KERNEL_ACCOUNT);
2212 	return !!memcg->events_percpu;
2213 }
2214 
2215 void memcg1_free_events(struct mem_cgroup *memcg)
2216 {
2217 	free_percpu(memcg->events_percpu);
2218 }
2219