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