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