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