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