blob: 1cc784556e057f88ff200d8e5c7ab03437acb0eb [file] [log] [blame]
Thomas Gleixnerc942fdd2019-05-27 08:55:06 +02001// SPDX-License-Identifier: GPL-2.0-or-later
Balbir Singh8cdea7c2008-02-07 00:13:50 -08002/* memcontrol.c - Memory Controller
3 *
4 * Copyright IBM Corporation, 2007
5 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
6 *
Pavel Emelianov78fb7462008-02-07 00:13:51 -08007 * Copyright 2007 OpenVZ SWsoft Inc
8 * Author: Pavel Emelianov <xemul@openvz.org>
9 *
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -080010 * Memory thresholds
11 * Copyright (C) 2009 Nokia Corporation
12 * Author: Kirill A. Shutemov
13 *
Glauber Costa7ae1e1d2012-12-18 14:21:56 -080014 * Kernel Memory Controller
15 * Copyright (C) 2012 Parallels Inc. and Google Inc.
16 * Authors: Glauber Costa and Suleiman Souhlal
17 *
Johannes Weiner1575e682015-04-14 15:44:51 -070018 * 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
Balbir Singh8cdea7c2008-02-07 00:13:50 -080023 */
24
Johannes Weiner3e32cb22014-12-10 15:42:31 -080025#include <linux/page_counter.h>
Balbir Singh8cdea7c2008-02-07 00:13:50 -080026#include <linux/memcontrol.h>
27#include <linux/cgroup.h>
Christoph Hellwiga5201102019-08-28 16:19:53 +020028#include <linux/pagewalk.h>
Ingo Molnar6e84f312017-02-08 18:51:29 +010029#include <linux/sched/mm.h>
Hugh Dickins3a4f8a02017-02-24 14:59:36 -080030#include <linux/shmem_fs.h>
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -080031#include <linux/hugetlb.h>
KAMEZAWA Hiroyukid13d1442009-01-07 18:07:56 -080032#include <linux/pagemap.h>
Chris Down1ff9e6e2019-03-05 15:48:09 -080033#include <linux/vm_event_item.h>
KAMEZAWA Hiroyukid52aa412008-02-07 00:14:24 -080034#include <linux/smp.h>
Balbir Singh8a9f3cc2008-02-07 00:13:53 -080035#include <linux/page-flags.h>
Balbir Singh66e17072008-02-07 00:13:56 -080036#include <linux/backing-dev.h>
Balbir Singh8a9f3cc2008-02-07 00:13:53 -080037#include <linux/bit_spinlock.h>
38#include <linux/rcupdate.h>
Balbir Singhe2224322009-04-02 16:57:39 -070039#include <linux/limits.h>
Paul Gortmakerb9e15ba2011-05-26 16:00:52 -040040#include <linux/export.h>
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -080041#include <linux/mutex.h>
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -070042#include <linux/rbtree.h>
Balbir Singhb6ac57d2008-04-29 01:00:19 -070043#include <linux/slab.h>
Balbir Singh66e17072008-02-07 00:13:56 -080044#include <linux/swap.h>
Daisuke Nishimura02491442010-03-10 15:22:17 -080045#include <linux/swapops.h>
Balbir Singh66e17072008-02-07 00:13:56 -080046#include <linux/spinlock.h>
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -080047#include <linux/eventfd.h>
Tejun Heo79bd9812013-11-22 18:20:42 -050048#include <linux/poll.h>
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -080049#include <linux/sort.h>
Balbir Singh66e17072008-02-07 00:13:56 -080050#include <linux/fs.h>
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -080051#include <linux/seq_file.h>
Anton Vorontsov70ddf632013-04-29 15:08:31 -070052#include <linux/vmpressure.h>
Christoph Lameterb69408e2008-10-18 20:26:14 -070053#include <linux/mm_inline.h>
Johannes Weiner5d1ea482014-12-10 15:44:55 -080054#include <linux/swap_cgroup.h>
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -080055#include <linux/cpu.h>
KAMEZAWA Hiroyuki158e0a22010-08-10 18:03:00 -070056#include <linux/oom.h>
Johannes Weiner0056f4e2013-10-31 16:34:14 -070057#include <linux/lockdep.h>
Tejun Heo79bd9812013-11-22 18:20:42 -050058#include <linux/file.h>
Tejun Heob23afb92015-11-05 18:46:11 -080059#include <linux/tracehook.h>
Chris Down0e4b01d2019-09-23 15:34:55 -070060#include <linux/psi.h>
Johannes Weinerc8713d02019-07-11 20:55:59 -070061#include <linux/seq_buf.h>
KAMEZAWA Hiroyuki08e552c2009-01-07 18:08:01 -080062#include "internal.h"
Glauber Costad1a4c0b2011-12-11 21:47:04 +000063#include <net/sock.h>
Michal Hocko4bd2c1e2012-10-08 16:33:10 -070064#include <net/ip.h>
Qiang Huangf35c3a82013-11-12 15:08:22 -080065#include "slab.h"
Balbir Singh8cdea7c2008-02-07 00:13:50 -080066
Linus Torvalds7c0f6ba2016-12-24 11:46:01 -080067#include <linux/uaccess.h>
Balbir Singh8697d332008-02-07 00:13:59 -080068
KOSAKI Motohirocc8e9702010-08-09 17:19:57 -070069#include <trace/events/vmscan.h>
70
Tejun Heo073219e2014-02-08 10:36:58 -050071struct cgroup_subsys memory_cgrp_subsys __read_mostly;
72EXPORT_SYMBOL(memory_cgrp_subsys);
David Rientjes68ae5642012-12-12 13:51:57 -080073
Johannes Weiner7d828602016-01-14 15:20:56 -080074struct mem_cgroup *root_mem_cgroup __read_mostly;
75
KAMEZAWA Hiroyukia181b0e2008-07-25 01:47:08 -070076#define MEM_CGROUP_RECLAIM_RETRIES 5
Balbir Singh8cdea7c2008-02-07 00:13:50 -080077
Johannes Weinerf7e1cb62016-01-14 15:21:29 -080078/* Socket memory accounting disabled? */
79static bool cgroup_memory_nosocket;
80
Vladimir Davydov04823c82016-01-20 15:02:38 -080081/* Kernel memory accounting disabled? */
82static bool cgroup_memory_nokmem;
83
Johannes Weiner21afa382015-02-11 15:26:36 -080084/* Whether the swap controller is active */
Andrew Mortonc255a452012-07-31 16:43:02 -070085#ifdef CONFIG_MEMCG_SWAP
Johannes Weinereccb52e2020-06-03 16:02:11 -070086bool cgroup_memory_noswap __read_mostly;
KAMEZAWA Hiroyukic0777192009-01-07 18:07:57 -080087#else
Johannes Weinereccb52e2020-06-03 16:02:11 -070088#define cgroup_memory_noswap 1
Johannes Weiner2d1c4982020-06-03 16:02:14 -070089#endif
KAMEZAWA Hiroyukic0777192009-01-07 18:07:57 -080090
Tejun Heo97b27822019-08-26 09:06:56 -070091#ifdef CONFIG_CGROUP_WRITEBACK
92static DECLARE_WAIT_QUEUE_HEAD(memcg_cgwb_frn_waitq);
93#endif
94
Johannes Weiner7941d212016-01-14 15:21:23 -080095/* Whether legacy memory+swap accounting is active */
96static bool do_memsw_account(void)
97{
Johannes Weinereccb52e2020-06-03 16:02:11 -070098 return !cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_noswap;
Johannes Weiner7941d212016-01-14 15:21:23 -080099}
100
Kirill A. Shutemova0db00f2012-05-29 15:06:56 -0700101#define THRESHOLDS_EVENTS_TARGET 128
102#define SOFTLIMIT_EVENTS_TARGET 1024
Johannes Weinere9f89742011-03-23 16:42:37 -0700103
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700104/*
105 * Cgroups above their limits are maintained in a RB-Tree, independent of
106 * their hierarchy representation
107 */
108
Mel Gormanef8f2322016-07-28 15:46:05 -0700109struct mem_cgroup_tree_per_node {
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700110 struct rb_root rb_root;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700111 struct rb_node *rb_rightmost;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700112 spinlock_t lock;
113};
114
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700115struct mem_cgroup_tree {
116 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
117};
118
119static struct mem_cgroup_tree soft_limit_tree __read_mostly;
120
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -0700121/* for OOM */
122struct mem_cgroup_eventfd_list {
123 struct list_head list;
124 struct eventfd_ctx *eventfd;
125};
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -0800126
Tejun Heo79bd9812013-11-22 18:20:42 -0500127/*
128 * cgroup_event represents events which userspace want to receive.
129 */
Tejun Heo3bc942f2013-11-22 18:20:44 -0500130struct mem_cgroup_event {
Tejun Heo79bd9812013-11-22 18:20:42 -0500131 /*
Tejun Heo59b6f872013-11-22 18:20:43 -0500132 * memcg which the event belongs to.
Tejun Heo79bd9812013-11-22 18:20:42 -0500133 */
Tejun Heo59b6f872013-11-22 18:20:43 -0500134 struct mem_cgroup *memcg;
Tejun Heo79bd9812013-11-22 18:20:42 -0500135 /*
Tejun Heo79bd9812013-11-22 18:20:42 -0500136 * eventfd to signal userspace about the event.
137 */
138 struct eventfd_ctx *eventfd;
139 /*
140 * Each of these stored in a list by the cgroup.
141 */
142 struct list_head list;
143 /*
Tejun Heofba94802013-11-22 18:20:43 -0500144 * register_event() callback will be used to add new userspace
145 * waiter for changes related to this event. Use eventfd_signal()
146 * on eventfd to send notification to userspace.
147 */
Tejun Heo59b6f872013-11-22 18:20:43 -0500148 int (*register_event)(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -0500149 struct eventfd_ctx *eventfd, const char *args);
Tejun Heofba94802013-11-22 18:20:43 -0500150 /*
151 * unregister_event() callback will be called when userspace closes
152 * the eventfd or on cgroup removing. This callback must be set,
153 * if you want provide notification functionality.
154 */
Tejun Heo59b6f872013-11-22 18:20:43 -0500155 void (*unregister_event)(struct mem_cgroup *memcg,
Tejun Heofba94802013-11-22 18:20:43 -0500156 struct eventfd_ctx *eventfd);
157 /*
Tejun Heo79bd9812013-11-22 18:20:42 -0500158 * All fields below needed to unregister event when
159 * userspace closes eventfd.
160 */
161 poll_table pt;
162 wait_queue_head_t *wqh;
Ingo Molnarac6424b2017-06-20 12:06:13 +0200163 wait_queue_entry_t wait;
Tejun Heo79bd9812013-11-22 18:20:42 -0500164 struct work_struct remove;
165};
166
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -0700167static void mem_cgroup_threshold(struct mem_cgroup *memcg);
168static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -0800169
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -0800170/* Stuffs for move charges at task migration. */
171/*
Johannes Weiner1dfab5a2015-02-11 15:26:09 -0800172 * Types of charges to be moved.
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -0800173 */
Johannes Weiner1dfab5a2015-02-11 15:26:09 -0800174#define MOVE_ANON 0x1U
175#define MOVE_FILE 0x2U
176#define MOVE_MASK (MOVE_ANON | MOVE_FILE)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -0800177
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -0800178/* "mc" and its members are protected by cgroup_mutex */
179static struct move_charge_struct {
Daisuke Nishimurab1dd6932010-11-24 12:57:06 -0800180 spinlock_t lock; /* for from, to */
Tejun Heo264a0ae2016-04-21 19:09:02 -0400181 struct mm_struct *mm;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -0800182 struct mem_cgroup *from;
183 struct mem_cgroup *to;
Johannes Weiner1dfab5a2015-02-11 15:26:09 -0800184 unsigned long flags;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -0800185 unsigned long precharge;
Daisuke Nishimura854ffa82010-03-10 15:22:15 -0800186 unsigned long moved_charge;
Daisuke Nishimura483c30b2010-03-10 15:22:18 -0800187 unsigned long moved_swap;
Daisuke Nishimura8033b972010-03-10 15:22:16 -0800188 struct task_struct *moving_task; /* a task moving charges */
189 wait_queue_head_t waitq; /* a waitq for other context */
190} mc = {
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -0700191 .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
Daisuke Nishimura8033b972010-03-10 15:22:16 -0800192 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
193};
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -0800194
Balbir Singh4e416952009-09-23 15:56:39 -0700195/*
196 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
197 * limit reclaim to prevent infinite loops, if they ever occur.
198 */
Kirill A. Shutemova0db00f2012-05-29 15:06:56 -0700199#define MEM_CGROUP_MAX_RECLAIM_LOOPS 100
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700200#define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
Balbir Singh4e416952009-09-23 15:56:39 -0700201
KAMEZAWA Hiroyuki217bc312008-02-07 00:14:17 -0800202enum charge_type {
203 MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
Kamezawa Hiroyuki41326c12012-07-31 16:41:40 -0700204 MEM_CGROUP_CHARGE_TYPE_ANON,
KAMEZAWA Hiroyukid13d1442009-01-07 18:07:56 -0800205 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
KAMEZAWA Hiroyuki8a9478c2009-06-17 16:27:17 -0700206 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */
KAMEZAWA Hiroyukic05555b2008-10-18 20:28:11 -0700207 NR_CHARGE_TYPE,
208};
209
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -0800210/* for encoding cft->private value on file */
Glauber Costa86ae53e2012-12-18 14:21:45 -0800211enum res_type {
212 _MEM,
213 _MEMSWAP,
214 _OOM_TYPE,
Glauber Costa510fc4e2012-12-18 14:21:47 -0800215 _KMEM,
Vladimir Davydovd55f90b2016-01-20 15:02:44 -0800216 _TCP,
Glauber Costa86ae53e2012-12-18 14:21:45 -0800217};
218
Kirill A. Shutemova0db00f2012-05-29 15:06:56 -0700219#define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
220#define MEMFILE_TYPE(val) ((val) >> 16 & 0xffff)
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -0800221#define MEMFILE_ATTR(val) ((val) & 0xffff)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -0700222/* Used for OOM nofiier */
223#define OOM_CONTROL (0)
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -0800224
Kirill Tkhaib05706f2018-08-17 15:47:33 -0700225/*
226 * Iteration constructs for visiting all cgroups (under a tree). If
227 * loops are exited prematurely (break), mem_cgroup_iter_break() must
228 * be used for reference counting.
229 */
230#define for_each_mem_cgroup_tree(iter, root) \
231 for (iter = mem_cgroup_iter(root, NULL, NULL); \
232 iter != NULL; \
233 iter = mem_cgroup_iter(root, iter, NULL))
234
235#define for_each_mem_cgroup(iter) \
236 for (iter = mem_cgroup_iter(NULL, NULL, NULL); \
237 iter != NULL; \
238 iter = mem_cgroup_iter(NULL, iter, NULL))
239
Tetsuo Handa7775fac2019-03-05 15:46:47 -0800240static inline bool should_force_charge(void)
241{
242 return tsk_is_oom_victim(current) || fatal_signal_pending(current) ||
243 (current->flags & PF_EXITING);
244}
245
Anton Vorontsov70ddf632013-04-29 15:08:31 -0700246/* Some nice accessors for the vmpressure. */
247struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
248{
249 if (!memcg)
250 memcg = root_mem_cgroup;
251 return &memcg->vmpressure;
252}
253
254struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
255{
256 return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
257}
258
Kirill Tkhai84c07d12018-08-17 15:47:25 -0700259#ifdef CONFIG_MEMCG_KMEM
Roman Gushchinbf4f0592020-08-06 23:20:49 -0700260extern spinlock_t css_set_lock;
261
262static void obj_cgroup_release(struct percpu_ref *ref)
263{
264 struct obj_cgroup *objcg = container_of(ref, struct obj_cgroup, refcnt);
265 struct mem_cgroup *memcg;
266 unsigned int nr_bytes;
267 unsigned int nr_pages;
268 unsigned long flags;
269
270 /*
271 * At this point all allocated objects are freed, and
272 * objcg->nr_charged_bytes can't have an arbitrary byte value.
273 * However, it can be PAGE_SIZE or (x * PAGE_SIZE).
274 *
275 * The following sequence can lead to it:
276 * 1) CPU0: objcg == stock->cached_objcg
277 * 2) CPU1: we do a small allocation (e.g. 92 bytes),
278 * PAGE_SIZE bytes are charged
279 * 3) CPU1: a process from another memcg is allocating something,
280 * the stock if flushed,
281 * objcg->nr_charged_bytes = PAGE_SIZE - 92
282 * 5) CPU0: we do release this object,
283 * 92 bytes are added to stock->nr_bytes
284 * 6) CPU0: stock is flushed,
285 * 92 bytes are added to objcg->nr_charged_bytes
286 *
287 * In the result, nr_charged_bytes == PAGE_SIZE.
288 * This page will be uncharged in obj_cgroup_release().
289 */
290 nr_bytes = atomic_read(&objcg->nr_charged_bytes);
291 WARN_ON_ONCE(nr_bytes & (PAGE_SIZE - 1));
292 nr_pages = nr_bytes >> PAGE_SHIFT;
293
294 spin_lock_irqsave(&css_set_lock, flags);
295 memcg = obj_cgroup_memcg(objcg);
296 if (nr_pages)
297 __memcg_kmem_uncharge(memcg, nr_pages);
298 list_del(&objcg->list);
299 mem_cgroup_put(memcg);
300 spin_unlock_irqrestore(&css_set_lock, flags);
301
302 percpu_ref_exit(ref);
303 kfree_rcu(objcg, rcu);
304}
305
306static struct obj_cgroup *obj_cgroup_alloc(void)
307{
308 struct obj_cgroup *objcg;
309 int ret;
310
311 objcg = kzalloc(sizeof(struct obj_cgroup), GFP_KERNEL);
312 if (!objcg)
313 return NULL;
314
315 ret = percpu_ref_init(&objcg->refcnt, obj_cgroup_release, 0,
316 GFP_KERNEL);
317 if (ret) {
318 kfree(objcg);
319 return NULL;
320 }
321 INIT_LIST_HEAD(&objcg->list);
322 return objcg;
323}
324
325static void memcg_reparent_objcgs(struct mem_cgroup *memcg,
326 struct mem_cgroup *parent)
327{
328 struct obj_cgroup *objcg, *iter;
329
330 objcg = rcu_replace_pointer(memcg->objcg, NULL, true);
331
332 spin_lock_irq(&css_set_lock);
333
334 /* Move active objcg to the parent's list */
335 xchg(&objcg->memcg, parent);
336 css_get(&parent->css);
337 list_add(&objcg->list, &parent->objcg_list);
338
339 /* Move already reparented objcgs to the parent's list */
340 list_for_each_entry(iter, &memcg->objcg_list, list) {
341 css_get(&parent->css);
342 xchg(&iter->memcg, parent);
343 css_put(&memcg->css);
344 }
345 list_splice(&memcg->objcg_list, &parent->objcg_list);
346
347 spin_unlock_irq(&css_set_lock);
348
349 percpu_ref_kill(&objcg->refcnt);
350}
351
Glauber Costa55007d82012-12-18 14:22:38 -0800352/*
Vladimir Davydovf7ce3192015-02-12 14:59:20 -0800353 * This will be the memcg's index in each cache's ->memcg_params.memcg_caches.
Li Zefanb8627832013-09-23 16:56:47 +0800354 * The main reason for not using cgroup id for this:
355 * this works better in sparse environments, where we have a lot of memcgs,
356 * but only a few kmem-limited. Or also, if we have, for instance, 200
357 * memcgs, and none but the 200th is kmem-limited, we'd have to have a
358 * 200 entry array for that.
Glauber Costa55007d82012-12-18 14:22:38 -0800359 *
Vladimir Davydovdbcf73e2015-02-12 14:58:57 -0800360 * The current size of the caches array is stored in memcg_nr_cache_ids. It
361 * will double each time we have to increase it.
Glauber Costa55007d82012-12-18 14:22:38 -0800362 */
Vladimir Davydovdbcf73e2015-02-12 14:58:57 -0800363static DEFINE_IDA(memcg_cache_ida);
364int memcg_nr_cache_ids;
Glauber Costa749c5412012-12-18 14:23:01 -0800365
Vladimir Davydov05257a12015-02-12 14:59:01 -0800366/* Protects memcg_nr_cache_ids */
367static DECLARE_RWSEM(memcg_cache_ids_sem);
368
369void memcg_get_cache_ids(void)
370{
371 down_read(&memcg_cache_ids_sem);
372}
373
374void memcg_put_cache_ids(void)
375{
376 up_read(&memcg_cache_ids_sem);
377}
378
Glauber Costa55007d82012-12-18 14:22:38 -0800379/*
380 * MIN_SIZE is different than 1, because we would like to avoid going through
381 * the alloc/free process all the time. In a small machine, 4 kmem-limited
382 * cgroups is a reasonable guess. In the future, it could be a parameter or
383 * tunable, but that is strictly not necessary.
384 *
Li Zefanb8627832013-09-23 16:56:47 +0800385 * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
Glauber Costa55007d82012-12-18 14:22:38 -0800386 * this constant directly from cgroup, but it is understandable that this is
387 * better kept as an internal representation in cgroup.c. In any case, the
Li Zefanb8627832013-09-23 16:56:47 +0800388 * cgrp_id space is not getting any smaller, and we don't have to necessarily
Glauber Costa55007d82012-12-18 14:22:38 -0800389 * increase ours as well if it increases.
390 */
391#define MEMCG_CACHES_MIN_SIZE 4
Li Zefanb8627832013-09-23 16:56:47 +0800392#define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
Glauber Costa55007d82012-12-18 14:22:38 -0800393
Glauber Costad7f25f82012-12-18 14:22:40 -0800394/*
395 * A lot of the calls to the cache allocation functions are expected to be
396 * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
397 * conditional to this static branch, we'll have to allow modules that does
398 * kmem_cache_alloc and the such to see this symbol as well
399 */
Johannes Weineref129472016-01-14 15:21:34 -0800400DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
Glauber Costad7f25f82012-12-18 14:22:40 -0800401EXPORT_SYMBOL(memcg_kmem_enabled_key);
Glauber Costaa8964b92012-12-18 14:22:09 -0800402
Tejun Heo17cc4df2017-02-22 15:41:36 -0800403struct workqueue_struct *memcg_kmem_cache_wq;
Yang Shi0a432dc2019-09-23 15:38:12 -0700404#endif
Tejun Heo17cc4df2017-02-22 15:41:36 -0800405
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700406static int memcg_shrinker_map_size;
407static DEFINE_MUTEX(memcg_shrinker_map_mutex);
408
409static void memcg_free_shrinker_map_rcu(struct rcu_head *head)
410{
411 kvfree(container_of(head, struct memcg_shrinker_map, rcu));
412}
413
414static int memcg_expand_one_shrinker_map(struct mem_cgroup *memcg,
415 int size, int old_size)
416{
417 struct memcg_shrinker_map *new, *old;
418 int nid;
419
420 lockdep_assert_held(&memcg_shrinker_map_mutex);
421
422 for_each_node(nid) {
423 old = rcu_dereference_protected(
424 mem_cgroup_nodeinfo(memcg, nid)->shrinker_map, true);
425 /* Not yet online memcg */
426 if (!old)
427 return 0;
428
Kirill Tkhai86daf942020-04-01 21:06:33 -0700429 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700430 if (!new)
431 return -ENOMEM;
432
433 /* Set all old bits, clear all new bits */
434 memset(new->map, (int)0xff, old_size);
435 memset((void *)new->map + old_size, 0, size - old_size);
436
437 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, new);
438 call_rcu(&old->rcu, memcg_free_shrinker_map_rcu);
439 }
440
441 return 0;
442}
443
444static void memcg_free_shrinker_maps(struct mem_cgroup *memcg)
445{
446 struct mem_cgroup_per_node *pn;
447 struct memcg_shrinker_map *map;
448 int nid;
449
450 if (mem_cgroup_is_root(memcg))
451 return;
452
453 for_each_node(nid) {
454 pn = mem_cgroup_nodeinfo(memcg, nid);
455 map = rcu_dereference_protected(pn->shrinker_map, true);
456 if (map)
457 kvfree(map);
458 rcu_assign_pointer(pn->shrinker_map, NULL);
459 }
460}
461
462static int memcg_alloc_shrinker_maps(struct mem_cgroup *memcg)
463{
464 struct memcg_shrinker_map *map;
465 int nid, size, ret = 0;
466
467 if (mem_cgroup_is_root(memcg))
468 return 0;
469
470 mutex_lock(&memcg_shrinker_map_mutex);
471 size = memcg_shrinker_map_size;
472 for_each_node(nid) {
Kirill Tkhai86daf942020-04-01 21:06:33 -0700473 map = kvzalloc_node(sizeof(*map) + size, GFP_KERNEL, nid);
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700474 if (!map) {
475 memcg_free_shrinker_maps(memcg);
476 ret = -ENOMEM;
477 break;
478 }
479 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, map);
480 }
481 mutex_unlock(&memcg_shrinker_map_mutex);
482
483 return ret;
484}
485
486int memcg_expand_shrinker_maps(int new_id)
487{
488 int size, old_size, ret = 0;
489 struct mem_cgroup *memcg;
490
491 size = DIV_ROUND_UP(new_id + 1, BITS_PER_LONG) * sizeof(unsigned long);
492 old_size = memcg_shrinker_map_size;
493 if (size <= old_size)
494 return 0;
495
496 mutex_lock(&memcg_shrinker_map_mutex);
497 if (!root_mem_cgroup)
498 goto unlock;
499
500 for_each_mem_cgroup(memcg) {
501 if (mem_cgroup_is_root(memcg))
502 continue;
503 ret = memcg_expand_one_shrinker_map(memcg, size, old_size);
Vasily Averin75866af2020-02-20 20:04:18 -0800504 if (ret) {
505 mem_cgroup_iter_break(NULL, memcg);
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700506 goto unlock;
Vasily Averin75866af2020-02-20 20:04:18 -0800507 }
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700508 }
509unlock:
510 if (!ret)
511 memcg_shrinker_map_size = size;
512 mutex_unlock(&memcg_shrinker_map_mutex);
513 return ret;
514}
Kirill Tkhaifae91d62018-08-17 15:48:10 -0700515
516void memcg_set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
517{
518 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
519 struct memcg_shrinker_map *map;
520
521 rcu_read_lock();
522 map = rcu_dereference(memcg->nodeinfo[nid]->shrinker_map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700523 /* Pairs with smp mb in shrink_slab() */
524 smp_mb__before_atomic();
Kirill Tkhaifae91d62018-08-17 15:48:10 -0700525 set_bit(shrinker_id, map->map);
526 rcu_read_unlock();
527 }
528}
529
Tejun Heoad7fa852015-05-27 20:00:02 -0400530/**
531 * mem_cgroup_css_from_page - css of the memcg associated with a page
532 * @page: page of interest
533 *
534 * If memcg is bound to the default hierarchy, css of the memcg associated
535 * with @page is returned. The returned css remains associated with @page
536 * until it is released.
537 *
538 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
539 * is returned.
Tejun Heoad7fa852015-05-27 20:00:02 -0400540 */
541struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
542{
543 struct mem_cgroup *memcg;
544
Tejun Heoad7fa852015-05-27 20:00:02 -0400545 memcg = page->mem_cgroup;
546
Tejun Heo9e10a132015-09-18 11:56:28 -0400547 if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heoad7fa852015-05-27 20:00:02 -0400548 memcg = root_mem_cgroup;
549
Tejun Heoad7fa852015-05-27 20:00:02 -0400550 return &memcg->css;
551}
552
Vladimir Davydov2fc04522015-09-09 15:35:28 -0700553/**
554 * page_cgroup_ino - return inode number of the memcg a page is charged to
555 * @page: the page
556 *
557 * Look up the closest online ancestor of the memory cgroup @page is charged to
558 * and return its inode number or 0 if @page is not charged to any cgroup. It
559 * is safe to call this function without holding a reference to @page.
560 *
561 * Note, this function is inherently racy, because there is nothing to prevent
562 * the cgroup inode from getting torn down and potentially reallocated a moment
563 * after page_cgroup_ino() returns, so it only should be used by callers that
564 * do not care (such as procfs interfaces).
565 */
566ino_t page_cgroup_ino(struct page *page)
567{
568 struct mem_cgroup *memcg;
569 unsigned long ino = 0;
570
571 rcu_read_lock();
Roman Gushchin221ec5c2019-11-05 21:17:03 -0800572 if (PageSlab(page) && !PageTail(page))
Roman Gushchin4d96ba32019-07-11 20:56:31 -0700573 memcg = memcg_from_slab_page(page);
574 else
575 memcg = READ_ONCE(page->mem_cgroup);
Vladimir Davydov2fc04522015-09-09 15:35:28 -0700576 while (memcg && !(memcg->css.flags & CSS_ONLINE))
577 memcg = parent_mem_cgroup(memcg);
578 if (memcg)
579 ino = cgroup_ino(memcg->css.cgroup);
580 rcu_read_unlock();
581 return ino;
582}
583
Mel Gormanef8f2322016-07-28 15:46:05 -0700584static struct mem_cgroup_per_node *
585mem_cgroup_page_nodeinfo(struct mem_cgroup *memcg, struct page *page)
Balbir Singhf64c3f52009-09-23 15:56:37 -0700586{
Johannes Weiner97a6c372011-03-23 16:42:27 -0700587 int nid = page_to_nid(page);
Balbir Singhf64c3f52009-09-23 15:56:37 -0700588
Mel Gormanef8f2322016-07-28 15:46:05 -0700589 return memcg->nodeinfo[nid];
Balbir Singhf64c3f52009-09-23 15:56:37 -0700590}
591
Mel Gormanef8f2322016-07-28 15:46:05 -0700592static struct mem_cgroup_tree_per_node *
593soft_limit_tree_node(int nid)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700594{
Mel Gormanef8f2322016-07-28 15:46:05 -0700595 return soft_limit_tree.rb_tree_per_node[nid];
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700596}
597
Mel Gormanef8f2322016-07-28 15:46:05 -0700598static struct mem_cgroup_tree_per_node *
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700599soft_limit_tree_from_page(struct page *page)
600{
601 int nid = page_to_nid(page);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700602
Mel Gormanef8f2322016-07-28 15:46:05 -0700603 return soft_limit_tree.rb_tree_per_node[nid];
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700604}
605
Mel Gormanef8f2322016-07-28 15:46:05 -0700606static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
607 struct mem_cgroup_tree_per_node *mctz,
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800608 unsigned long new_usage_in_excess)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700609{
610 struct rb_node **p = &mctz->rb_root.rb_node;
611 struct rb_node *parent = NULL;
Mel Gormanef8f2322016-07-28 15:46:05 -0700612 struct mem_cgroup_per_node *mz_node;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700613 bool rightmost = true;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700614
615 if (mz->on_tree)
616 return;
617
618 mz->usage_in_excess = new_usage_in_excess;
619 if (!mz->usage_in_excess)
620 return;
621 while (*p) {
622 parent = *p;
Mel Gormanef8f2322016-07-28 15:46:05 -0700623 mz_node = rb_entry(parent, struct mem_cgroup_per_node,
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700624 tree_node);
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700625 if (mz->usage_in_excess < mz_node->usage_in_excess) {
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700626 p = &(*p)->rb_left;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700627 rightmost = false;
628 }
629
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700630 /*
631 * We can't avoid mem cgroups that are over their soft
632 * limit by the same amount
633 */
634 else if (mz->usage_in_excess >= mz_node->usage_in_excess)
635 p = &(*p)->rb_right;
636 }
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700637
638 if (rightmost)
639 mctz->rb_rightmost = &mz->tree_node;
640
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700641 rb_link_node(&mz->tree_node, parent, p);
642 rb_insert_color(&mz->tree_node, &mctz->rb_root);
643 mz->on_tree = true;
644}
645
Mel Gormanef8f2322016-07-28 15:46:05 -0700646static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
647 struct mem_cgroup_tree_per_node *mctz)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700648{
649 if (!mz->on_tree)
650 return;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700651
652 if (&mz->tree_node == mctz->rb_rightmost)
653 mctz->rb_rightmost = rb_prev(&mz->tree_node);
654
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700655 rb_erase(&mz->tree_node, &mctz->rb_root);
656 mz->on_tree = false;
657}
658
Mel Gormanef8f2322016-07-28 15:46:05 -0700659static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
660 struct mem_cgroup_tree_per_node *mctz)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700661{
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700662 unsigned long flags;
663
664 spin_lock_irqsave(&mctz->lock, flags);
Johannes Weinercf2c8122014-06-06 14:38:21 -0700665 __mem_cgroup_remove_exceeded(mz, mctz);
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700666 spin_unlock_irqrestore(&mctz->lock, flags);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700667}
668
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800669static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
670{
671 unsigned long nr_pages = page_counter_read(&memcg->memory);
Jason Low4db0c3c2015-04-15 16:14:08 -0700672 unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800673 unsigned long excess = 0;
674
675 if (nr_pages > soft_limit)
676 excess = nr_pages - soft_limit;
677
678 return excess;
679}
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700680
681static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
682{
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800683 unsigned long excess;
Mel Gormanef8f2322016-07-28 15:46:05 -0700684 struct mem_cgroup_per_node *mz;
685 struct mem_cgroup_tree_per_node *mctz;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700686
Jianyu Zhane2318752014-06-06 14:38:20 -0700687 mctz = soft_limit_tree_from_page(page);
Laurent Dufourbfc72282017-03-09 16:17:06 -0800688 if (!mctz)
689 return;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700690 /*
691 * Necessary to update all ancestors when hierarchy is used.
692 * because their event counter is not touched.
693 */
694 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
Mel Gormanef8f2322016-07-28 15:46:05 -0700695 mz = mem_cgroup_page_nodeinfo(memcg, page);
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800696 excess = soft_limit_excess(memcg);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700697 /*
698 * We have to update the tree if mz is on RB-tree or
699 * mem is over its softlimit.
700 */
701 if (excess || mz->on_tree) {
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700702 unsigned long flags;
703
704 spin_lock_irqsave(&mctz->lock, flags);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700705 /* if on-tree, remove it */
706 if (mz->on_tree)
Johannes Weinercf2c8122014-06-06 14:38:21 -0700707 __mem_cgroup_remove_exceeded(mz, mctz);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700708 /*
709 * Insert again. mz->usage_in_excess will be updated.
710 * If excess is 0, no tree ops.
711 */
Johannes Weinercf2c8122014-06-06 14:38:21 -0700712 __mem_cgroup_insert_exceeded(mz, mctz, excess);
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700713 spin_unlock_irqrestore(&mctz->lock, flags);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700714 }
715 }
716}
717
718static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
719{
Mel Gormanef8f2322016-07-28 15:46:05 -0700720 struct mem_cgroup_tree_per_node *mctz;
721 struct mem_cgroup_per_node *mz;
722 int nid;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700723
Jianyu Zhane2318752014-06-06 14:38:20 -0700724 for_each_node(nid) {
Mel Gormanef8f2322016-07-28 15:46:05 -0700725 mz = mem_cgroup_nodeinfo(memcg, nid);
726 mctz = soft_limit_tree_node(nid);
Laurent Dufourbfc72282017-03-09 16:17:06 -0800727 if (mctz)
728 mem_cgroup_remove_exceeded(mz, mctz);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700729 }
730}
731
Mel Gormanef8f2322016-07-28 15:46:05 -0700732static struct mem_cgroup_per_node *
733__mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700734{
Mel Gormanef8f2322016-07-28 15:46:05 -0700735 struct mem_cgroup_per_node *mz;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700736
737retry:
738 mz = NULL;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700739 if (!mctz->rb_rightmost)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700740 goto done; /* Nothing to reclaim from */
741
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -0700742 mz = rb_entry(mctz->rb_rightmost,
743 struct mem_cgroup_per_node, tree_node);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700744 /*
745 * Remove the node now but someone else can add it back,
746 * we will to add it back at the end of reclaim to its correct
747 * position in the tree.
748 */
Johannes Weinercf2c8122014-06-06 14:38:21 -0700749 __mem_cgroup_remove_exceeded(mz, mctz);
Johannes Weiner3e32cb22014-12-10 15:42:31 -0800750 if (!soft_limit_excess(mz->memcg) ||
Shakeel Butt8965aa22020-04-01 21:07:10 -0700751 !css_tryget(&mz->memcg->css))
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700752 goto retry;
753done:
754 return mz;
755}
756
Mel Gormanef8f2322016-07-28 15:46:05 -0700757static struct mem_cgroup_per_node *
758mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700759{
Mel Gormanef8f2322016-07-28 15:46:05 -0700760 struct mem_cgroup_per_node *mz;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700761
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700762 spin_lock_irq(&mctz->lock);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700763 mz = __mem_cgroup_largest_soft_limit_node(mctz);
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700764 spin_unlock_irq(&mctz->lock);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700765 return mz;
766}
767
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700768/**
769 * __mod_memcg_state - update cgroup memory statistics
770 * @memcg: the memory cgroup
771 * @idx: the stat item - can be enum memcg_stat_item or enum node_stat_item
772 * @val: delta to add to the counter, can be negative
773 */
774void __mod_memcg_state(struct mem_cgroup *memcg, int idx, int val)
775{
Roman Gushchinea426c22020-08-06 23:20:35 -0700776 long x, threshold = MEMCG_CHARGE_BATCH;
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700777
778 if (mem_cgroup_disabled())
779 return;
780
Roman Gushchinea426c22020-08-06 23:20:35 -0700781 if (vmstat_item_in_bytes(idx))
782 threshold <<= PAGE_SHIFT;
783
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700784 x = val + __this_cpu_read(memcg->vmstats_percpu->stat[idx]);
Roman Gushchinea426c22020-08-06 23:20:35 -0700785 if (unlikely(abs(x) > threshold)) {
Johannes Weiner42a30032019-05-14 15:47:12 -0700786 struct mem_cgroup *mi;
787
Yafang Shao766a4c12019-07-16 16:26:06 -0700788 /*
789 * Batch local counters to keep them in sync with
790 * the hierarchical ones.
791 */
792 __this_cpu_add(memcg->vmstats_local->stat[idx], x);
Johannes Weiner42a30032019-05-14 15:47:12 -0700793 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
794 atomic_long_add(x, &mi->vmstats[idx]);
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700795 x = 0;
796 }
797 __this_cpu_write(memcg->vmstats_percpu->stat[idx], x);
798}
799
Johannes Weiner42a30032019-05-14 15:47:12 -0700800static struct mem_cgroup_per_node *
801parent_nodeinfo(struct mem_cgroup_per_node *pn, int nid)
802{
803 struct mem_cgroup *parent;
804
805 parent = parent_mem_cgroup(pn->memcg);
806 if (!parent)
807 return NULL;
808 return mem_cgroup_nodeinfo(parent, nid);
809}
810
Roman Gushchineedc4e52020-08-06 23:20:32 -0700811void __mod_memcg_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
812 int val)
813{
814 struct mem_cgroup_per_node *pn;
815 struct mem_cgroup *memcg;
Roman Gushchinea426c22020-08-06 23:20:35 -0700816 long x, threshold = MEMCG_CHARGE_BATCH;
Roman Gushchineedc4e52020-08-06 23:20:32 -0700817
818 pn = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
819 memcg = pn->memcg;
820
821 /* Update memcg */
822 __mod_memcg_state(memcg, idx, val);
823
824 /* Update lruvec */
825 __this_cpu_add(pn->lruvec_stat_local->count[idx], val);
826
Roman Gushchinea426c22020-08-06 23:20:35 -0700827 if (vmstat_item_in_bytes(idx))
828 threshold <<= PAGE_SHIFT;
829
Roman Gushchineedc4e52020-08-06 23:20:32 -0700830 x = val + __this_cpu_read(pn->lruvec_stat_cpu->count[idx]);
Roman Gushchinea426c22020-08-06 23:20:35 -0700831 if (unlikely(abs(x) > threshold)) {
Roman Gushchineedc4e52020-08-06 23:20:32 -0700832 pg_data_t *pgdat = lruvec_pgdat(lruvec);
833 struct mem_cgroup_per_node *pi;
834
835 for (pi = pn; pi; pi = parent_nodeinfo(pi, pgdat->node_id))
836 atomic_long_add(x, &pi->lruvec_stat[idx]);
837 x = 0;
838 }
839 __this_cpu_write(pn->lruvec_stat_cpu->count[idx], x);
840}
841
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700842/**
843 * __mod_lruvec_state - update lruvec memory statistics
844 * @lruvec: the lruvec
845 * @idx: the stat item
846 * @val: delta to add to the counter, can be negative
847 *
848 * The lruvec is the intersection of the NUMA node and a cgroup. This
849 * function updates the all three counters that are affected by a
850 * change of state at this level: per-node, per-cgroup, per-lruvec.
851 */
852void __mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx,
853 int val)
854{
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700855 /* Update node */
Roman Gushchineedc4e52020-08-06 23:20:32 -0700856 __mod_node_page_state(lruvec_pgdat(lruvec), idx, val);
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700857
Roman Gushchineedc4e52020-08-06 23:20:32 -0700858 /* Update memcg and lruvec */
859 if (!mem_cgroup_disabled())
860 __mod_memcg_lruvec_state(lruvec, idx, val);
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700861}
862
Roman Gushchinec9f0232019-08-13 15:37:41 -0700863void __mod_lruvec_slab_state(void *p, enum node_stat_item idx, int val)
864{
Roman Gushchin4f103c62020-04-01 21:06:36 -0700865 pg_data_t *pgdat = page_pgdat(virt_to_page(p));
Roman Gushchinec9f0232019-08-13 15:37:41 -0700866 struct mem_cgroup *memcg;
867 struct lruvec *lruvec;
868
869 rcu_read_lock();
Roman Gushchin4f103c62020-04-01 21:06:36 -0700870 memcg = mem_cgroup_from_obj(p);
Roman Gushchinec9f0232019-08-13 15:37:41 -0700871
872 /* Untracked pages have no memcg, no lruvec. Update only the node */
873 if (!memcg || memcg == root_mem_cgroup) {
874 __mod_node_page_state(pgdat, idx, val);
875 } else {
Johannes Weiner867e5e12019-11-30 17:55:34 -0800876 lruvec = mem_cgroup_lruvec(memcg, pgdat);
Roman Gushchinec9f0232019-08-13 15:37:41 -0700877 __mod_lruvec_state(lruvec, idx, val);
878 }
879 rcu_read_unlock();
880}
881
Roman Gushchin8380ce42020-03-28 19:17:25 -0700882void mod_memcg_obj_state(void *p, int idx, int val)
883{
884 struct mem_cgroup *memcg;
885
886 rcu_read_lock();
887 memcg = mem_cgroup_from_obj(p);
888 if (memcg)
889 mod_memcg_state(memcg, idx, val);
890 rcu_read_unlock();
891}
892
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700893/**
894 * __count_memcg_events - account VM events in a cgroup
895 * @memcg: the memory cgroup
896 * @idx: the event item
897 * @count: the number of events that occured
898 */
899void __count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx,
900 unsigned long count)
901{
902 unsigned long x;
903
904 if (mem_cgroup_disabled())
905 return;
906
907 x = count + __this_cpu_read(memcg->vmstats_percpu->events[idx]);
908 if (unlikely(x > MEMCG_CHARGE_BATCH)) {
Johannes Weiner42a30032019-05-14 15:47:12 -0700909 struct mem_cgroup *mi;
910
Yafang Shao766a4c12019-07-16 16:26:06 -0700911 /*
912 * Batch local counters to keep them in sync with
913 * the hierarchical ones.
914 */
915 __this_cpu_add(memcg->vmstats_local->events[idx], x);
Johannes Weiner42a30032019-05-14 15:47:12 -0700916 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
917 atomic_long_add(x, &mi->vmevents[idx]);
Johannes Weinerdb9adbc2019-05-14 15:47:09 -0700918 x = 0;
919 }
920 __this_cpu_write(memcg->vmstats_percpu->events[idx], x);
921}
922
Johannes Weiner42a30032019-05-14 15:47:12 -0700923static unsigned long memcg_events(struct mem_cgroup *memcg, int event)
Johannes Weinere9f89742011-03-23 16:42:37 -0700924{
Chris Down871789d2019-05-14 15:46:57 -0700925 return atomic_long_read(&memcg->vmevents[event]);
Johannes Weinere9f89742011-03-23 16:42:37 -0700926}
927
Johannes Weiner42a30032019-05-14 15:47:12 -0700928static unsigned long memcg_events_local(struct mem_cgroup *memcg, int event)
929{
Johannes Weiner815744d2019-06-13 15:55:46 -0700930 long x = 0;
931 int cpu;
932
933 for_each_possible_cpu(cpu)
934 x += per_cpu(memcg->vmstats_local->events[event], cpu);
935 return x;
Johannes Weiner42a30032019-05-14 15:47:12 -0700936}
937
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -0700938static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
David Rientjesb070e652013-05-07 16:18:09 -0700939 struct page *page,
Johannes Weiner3fba69a2020-06-03 16:01:31 -0700940 int nr_pages)
KAMEZAWA Hiroyukid52aa412008-02-07 00:14:24 -0800941{
KAMEZAWA Hiroyukie401f172011-01-20 14:44:23 -0800942 /* pagein of a big page is an event. So, ignore page size */
943 if (nr_pages > 0)
Johannes Weinerc9019e92018-01-31 16:16:37 -0800944 __count_memcg_events(memcg, PGPGIN, 1);
KAMEZAWA Hiroyuki3751d602011-02-01 15:52:45 -0800945 else {
Johannes Weinerc9019e92018-01-31 16:16:37 -0800946 __count_memcg_events(memcg, PGPGOUT, 1);
KAMEZAWA Hiroyuki3751d602011-02-01 15:52:45 -0800947 nr_pages = -nr_pages; /* for event */
948 }
KAMEZAWA Hiroyukie401f172011-01-20 14:44:23 -0800949
Chris Down871789d2019-05-14 15:46:57 -0700950 __this_cpu_add(memcg->vmstats_percpu->nr_page_events, nr_pages);
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -0800951}
KAMEZAWA Hiroyukid52aa412008-02-07 00:14:24 -0800952
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800953static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
954 enum mem_cgroup_events_target target)
KAMEZAWA Hiroyukid2265e62010-03-10 15:22:31 -0800955{
Johannes Weiner7a159cc2011-03-23 16:42:38 -0700956 unsigned long val, next;
957
Chris Down871789d2019-05-14 15:46:57 -0700958 val = __this_cpu_read(memcg->vmstats_percpu->nr_page_events);
959 next = __this_cpu_read(memcg->vmstats_percpu->targets[target]);
Johannes Weiner7a159cc2011-03-23 16:42:38 -0700960 /* from time_after() in jiffies.h */
Michal Hocko6a1a8b82017-07-10 15:48:53 -0700961 if ((long)(next - val) < 0) {
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800962 switch (target) {
963 case MEM_CGROUP_TARGET_THRESH:
964 next = val + THRESHOLDS_EVENTS_TARGET;
965 break;
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700966 case MEM_CGROUP_TARGET_SOFTLIMIT:
967 next = val + SOFTLIMIT_EVENTS_TARGET;
968 break;
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800969 default:
970 break;
971 }
Chris Down871789d2019-05-14 15:46:57 -0700972 __this_cpu_write(memcg->vmstats_percpu->targets[target], next);
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800973 return true;
Johannes Weiner7a159cc2011-03-23 16:42:38 -0700974 }
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800975 return false;
KAMEZAWA Hiroyukid2265e62010-03-10 15:22:31 -0800976}
977
978/*
979 * Check events in order.
980 *
981 */
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -0700982static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
KAMEZAWA Hiroyukid2265e62010-03-10 15:22:31 -0800983{
984 /* threshold event is triggered in finer grain than soft limit */
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800985 if (unlikely(mem_cgroup_event_ratelimit(memcg,
986 MEM_CGROUP_TARGET_THRESH))) {
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700987 bool do_softlimit;
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800988
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700989 do_softlimit = mem_cgroup_event_ratelimit(memcg,
990 MEM_CGROUP_TARGET_SOFTLIMIT);
Johannes Weinerf53d7ce2012-01-12 17:18:23 -0800991 mem_cgroup_threshold(memcg);
Andrew Mortonbb4cc1a82013-09-24 15:27:40 -0700992 if (unlikely(do_softlimit))
993 mem_cgroup_update_tree(memcg, page);
Johannes Weiner0a31bc92014-08-08 14:19:22 -0700994 }
KAMEZAWA Hiroyukid2265e62010-03-10 15:22:31 -0800995}
996
Balbir Singhcf475ad2008-04-29 01:00:16 -0700997struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
Pavel Emelianov78fb7462008-02-07 00:13:51 -0800998{
Balbir Singh31a78f22008-09-28 23:09:31 +0100999 /*
1000 * mm_update_next_owner() may clear mm->owner to NULL
1001 * if it races with swapoff, page migration, etc.
1002 * So this can be called with p == NULL.
1003 */
1004 if (unlikely(!p))
1005 return NULL;
1006
Tejun Heo073219e2014-02-08 10:36:58 -05001007 return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
Pavel Emelianov78fb7462008-02-07 00:13:51 -08001008}
Michal Hocko33398cf2015-09-08 15:01:02 -07001009EXPORT_SYMBOL(mem_cgroup_from_task);
Pavel Emelianov78fb7462008-02-07 00:13:51 -08001010
Shakeel Buttd46eb14b2018-08-17 15:46:39 -07001011/**
1012 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
1013 * @mm: mm from which memcg should be extracted. It can be NULL.
1014 *
1015 * Obtain a reference on mm->memcg and returns it if successful. Otherwise
1016 * root_mem_cgroup is returned. However if mem_cgroup is disabled, NULL is
1017 * returned.
1018 */
1019struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
KAMEZAWA Hiroyuki54595fe2009-01-07 18:08:33 -08001020{
Shakeel Buttd46eb14b2018-08-17 15:46:39 -07001021 struct mem_cgroup *memcg;
1022
1023 if (mem_cgroup_disabled())
1024 return NULL;
KAMEZAWA Hiroyuki0b7f5692009-04-02 16:57:38 -07001025
KAMEZAWA Hiroyuki54595fe2009-01-07 18:08:33 -08001026 rcu_read_lock();
1027 do {
Michal Hocko6f6acb02014-05-22 11:54:19 -07001028 /*
1029 * Page cache insertions can happen withou an
1030 * actual mm context, e.g. during disk probing
1031 * on boot, loopback IO, acct() writes etc.
1032 */
1033 if (unlikely(!mm))
Johannes Weinerdf381972014-04-07 15:37:43 -07001034 memcg = root_mem_cgroup;
Michal Hocko6f6acb02014-05-22 11:54:19 -07001035 else {
1036 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1037 if (unlikely(!memcg))
1038 memcg = root_mem_cgroup;
1039 }
Roman Gushchin00d484f2019-11-15 17:34:43 -08001040 } while (!css_tryget(&memcg->css));
KAMEZAWA Hiroyuki54595fe2009-01-07 18:08:33 -08001041 rcu_read_unlock();
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001042 return memcg;
KAMEZAWA Hiroyuki54595fe2009-01-07 18:08:33 -08001043}
Shakeel Buttd46eb14b2018-08-17 15:46:39 -07001044EXPORT_SYMBOL(get_mem_cgroup_from_mm);
1045
1046/**
Shakeel Buttf745c6f2018-08-17 15:46:44 -07001047 * get_mem_cgroup_from_page: Obtain a reference on given page's memcg.
1048 * @page: page from which memcg should be extracted.
1049 *
1050 * Obtain a reference on page->memcg and returns it if successful. Otherwise
1051 * root_mem_cgroup is returned.
1052 */
1053struct mem_cgroup *get_mem_cgroup_from_page(struct page *page)
1054{
1055 struct mem_cgroup *memcg = page->mem_cgroup;
1056
1057 if (mem_cgroup_disabled())
1058 return NULL;
1059
1060 rcu_read_lock();
Shakeel Butt8965aa22020-04-01 21:07:10 -07001061 /* Page should not get uncharged and freed memcg under us. */
1062 if (!memcg || WARN_ON_ONCE(!css_tryget(&memcg->css)))
Shakeel Buttf745c6f2018-08-17 15:46:44 -07001063 memcg = root_mem_cgroup;
1064 rcu_read_unlock();
1065 return memcg;
1066}
1067EXPORT_SYMBOL(get_mem_cgroup_from_page);
1068
1069/**
Shakeel Buttd46eb14b2018-08-17 15:46:39 -07001070 * If current->active_memcg is non-NULL, do not fallback to current->mm->memcg.
1071 */
1072static __always_inline struct mem_cgroup *get_mem_cgroup_from_current(void)
1073{
1074 if (unlikely(current->active_memcg)) {
Shakeel Butt8965aa22020-04-01 21:07:10 -07001075 struct mem_cgroup *memcg;
Shakeel Buttd46eb14b2018-08-17 15:46:39 -07001076
1077 rcu_read_lock();
Shakeel Butt8965aa22020-04-01 21:07:10 -07001078 /* current->active_memcg must hold a ref. */
1079 if (WARN_ON_ONCE(!css_tryget(&current->active_memcg->css)))
1080 memcg = root_mem_cgroup;
1081 else
Shakeel Buttd46eb14b2018-08-17 15:46:39 -07001082 memcg = current->active_memcg;
1083 rcu_read_unlock();
1084 return memcg;
1085 }
1086 return get_mem_cgroup_from_mm(current->mm);
1087}
KAMEZAWA Hiroyuki54595fe2009-01-07 18:08:33 -08001088
Johannes Weiner56600482012-01-12 17:17:59 -08001089/**
1090 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1091 * @root: hierarchy root
1092 * @prev: previously returned memcg, NULL on first invocation
1093 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1094 *
1095 * Returns references to children of the hierarchy below @root, or
1096 * @root itself, or %NULL after a full round-trip.
1097 *
1098 * Caller must pass the return value in @prev on subsequent
1099 * invocations for reference counting, or use mem_cgroup_iter_break()
1100 * to cancel a hierarchy walk before the round-trip is complete.
1101 *
Honglei Wangb213b542018-03-28 16:01:12 -07001102 * Reclaimers can specify a node and a priority level in @reclaim to
Johannes Weiner56600482012-01-12 17:17:59 -08001103 * divide up the memcgs in the hierarchy among all concurrent
Honglei Wangb213b542018-03-28 16:01:12 -07001104 * reclaimers operating on the same node and priority.
Johannes Weiner56600482012-01-12 17:17:59 -08001105 */
Andrew Morton694fbc02013-09-24 15:27:37 -07001106struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
Johannes Weiner56600482012-01-12 17:17:59 -08001107 struct mem_cgroup *prev,
Andrew Morton694fbc02013-09-24 15:27:37 -07001108 struct mem_cgroup_reclaim_cookie *reclaim)
KAMEZAWA Hiroyuki14067bb2009-04-02 16:57:35 -07001109{
Kees Cook3f649ab2020-06-03 13:09:38 -07001110 struct mem_cgroup_reclaim_iter *iter;
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001111 struct cgroup_subsys_state *css = NULL;
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001112 struct mem_cgroup *memcg = NULL;
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001113 struct mem_cgroup *pos = NULL;
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07001114
Andrew Morton694fbc02013-09-24 15:27:37 -07001115 if (mem_cgroup_disabled())
1116 return NULL;
Johannes Weiner56600482012-01-12 17:17:59 -08001117
KAMEZAWA Hiroyuki711d3d22010-10-27 15:33:42 -07001118 if (!root)
1119 root = root_mem_cgroup;
1120
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001121 if (prev && !reclaim)
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001122 pos = prev;
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001123
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001124 if (!root->use_hierarchy && root != root_mem_cgroup) {
1125 if (prev)
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001126 goto out;
Andrew Morton694fbc02013-09-24 15:27:37 -07001127 return root;
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001128 }
1129
Michal Hocko542f85f2013-04-29 15:07:15 -07001130 rcu_read_lock();
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001131
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001132 if (reclaim) {
Mel Gormanef8f2322016-07-28 15:46:05 -07001133 struct mem_cgroup_per_node *mz;
Johannes Weiner527a5ec2012-01-12 17:17:55 -08001134
Mel Gormanef8f2322016-07-28 15:46:05 -07001135 mz = mem_cgroup_nodeinfo(root, reclaim->pgdat->node_id);
Yafang Shao9da83f32019-11-30 17:50:03 -08001136 iter = &mz->iter;
Michal Hocko5f578162013-04-29 15:07:17 -07001137
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001138 if (prev && reclaim->generation != iter->generation)
Michal Hocko542f85f2013-04-29 15:07:15 -07001139 goto out_unlock;
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001140
Vladimir Davydov6df38682015-12-29 14:54:10 -08001141 while (1) {
Jason Low4db0c3c2015-04-15 16:14:08 -07001142 pos = READ_ONCE(iter->position);
Vladimir Davydov6df38682015-12-29 14:54:10 -08001143 if (!pos || css_tryget(&pos->css))
1144 break;
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001145 /*
Vladimir Davydov6df38682015-12-29 14:54:10 -08001146 * css reference reached zero, so iter->position will
1147 * be cleared by ->css_released. However, we should not
1148 * rely on this happening soon, because ->css_released
1149 * is called from a work queue, and by busy-waiting we
1150 * might block it. So we clear iter->position right
1151 * away.
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001152 */
Vladimir Davydov6df38682015-12-29 14:54:10 -08001153 (void)cmpxchg(&iter->position, pos, NULL);
1154 }
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001155 }
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001156
1157 if (pos)
1158 css = &pos->css;
1159
1160 for (;;) {
1161 css = css_next_descendant_pre(css, &root->css);
1162 if (!css) {
1163 /*
1164 * Reclaimers share the hierarchy walk, and a
1165 * new one might jump in right at the end of
1166 * the hierarchy - make sure they see at least
1167 * one group and restart from the beginning.
1168 */
1169 if (!prev)
1170 continue;
1171 break;
1172 }
1173
1174 /*
1175 * Verify the css and acquire a reference. The root
1176 * is provided by the caller, so we know it's alive
1177 * and kicking, and don't take an extra reference.
1178 */
1179 memcg = mem_cgroup_from_css(css);
1180
1181 if (css == &root->css)
1182 break;
1183
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08001184 if (css_tryget(css))
1185 break;
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001186
1187 memcg = NULL;
1188 }
1189
1190 if (reclaim) {
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001191 /*
Vladimir Davydov6df38682015-12-29 14:54:10 -08001192 * The position could have already been updated by a competing
1193 * thread, so check that the value hasn't changed since we read
1194 * it to avoid reclaiming from the same cgroup twice.
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001195 */
Vladimir Davydov6df38682015-12-29 14:54:10 -08001196 (void)cmpxchg(&iter->position, pos, memcg);
1197
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001198 if (pos)
1199 css_put(&pos->css);
1200
1201 if (!memcg)
1202 iter->generation++;
1203 else if (!prev)
1204 reclaim->generation = iter->generation;
1205 }
1206
Michal Hocko542f85f2013-04-29 15:07:15 -07001207out_unlock:
1208 rcu_read_unlock();
Johannes Weiner5ac8fb32014-12-10 15:42:39 -08001209out:
Michal Hockoc40046f2013-04-29 15:07:14 -07001210 if (prev && prev != root)
1211 css_put(&prev->css);
1212
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001213 return memcg;
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07001214}
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001215
Johannes Weiner56600482012-01-12 17:17:59 -08001216/**
1217 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1218 * @root: hierarchy root
1219 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1220 */
1221void mem_cgroup_iter_break(struct mem_cgroup *root,
1222 struct mem_cgroup *prev)
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001223{
1224 if (!root)
1225 root = root_mem_cgroup;
1226 if (prev && prev != root)
1227 css_put(&prev->css);
1228}
1229
Miles Chen54a83d62019-08-13 15:37:28 -07001230static void __invalidate_reclaim_iterators(struct mem_cgroup *from,
1231 struct mem_cgroup *dead_memcg)
Vladimir Davydov6df38682015-12-29 14:54:10 -08001232{
Vladimir Davydov6df38682015-12-29 14:54:10 -08001233 struct mem_cgroup_reclaim_iter *iter;
Mel Gormanef8f2322016-07-28 15:46:05 -07001234 struct mem_cgroup_per_node *mz;
1235 int nid;
Vladimir Davydov6df38682015-12-29 14:54:10 -08001236
Miles Chen54a83d62019-08-13 15:37:28 -07001237 for_each_node(nid) {
1238 mz = mem_cgroup_nodeinfo(from, nid);
Yafang Shao9da83f32019-11-30 17:50:03 -08001239 iter = &mz->iter;
1240 cmpxchg(&iter->position, dead_memcg, NULL);
Vladimir Davydov6df38682015-12-29 14:54:10 -08001241 }
1242}
1243
Miles Chen54a83d62019-08-13 15:37:28 -07001244static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
1245{
1246 struct mem_cgroup *memcg = dead_memcg;
1247 struct mem_cgroup *last;
1248
1249 do {
1250 __invalidate_reclaim_iterators(memcg, dead_memcg);
1251 last = memcg;
1252 } while ((memcg = parent_mem_cgroup(memcg)));
1253
1254 /*
1255 * When cgruop1 non-hierarchy mode is used,
1256 * parent_mem_cgroup() does not walk all the way up to the
1257 * cgroup root (root_mem_cgroup). So we have to handle
1258 * dead_memcg from cgroup root separately.
1259 */
1260 if (last != root_mem_cgroup)
1261 __invalidate_reclaim_iterators(root_mem_cgroup,
1262 dead_memcg);
1263}
1264
Johannes Weiner925b7672012-01-12 17:18:15 -08001265/**
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001266 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
1267 * @memcg: hierarchy root
1268 * @fn: function to call for each task
1269 * @arg: argument passed to @fn
1270 *
1271 * This function iterates over tasks attached to @memcg or to any of its
1272 * descendants and calls @fn for each task. If @fn returns a non-zero
1273 * value, the function breaks the iteration loop and returns the value.
1274 * Otherwise, it will iterate over all tasks and return 0.
1275 *
1276 * This function must not be called for the root memory cgroup.
1277 */
1278int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
1279 int (*fn)(struct task_struct *, void *), void *arg)
1280{
1281 struct mem_cgroup *iter;
1282 int ret = 0;
1283
1284 BUG_ON(memcg == root_mem_cgroup);
1285
1286 for_each_mem_cgroup_tree(iter, memcg) {
1287 struct css_task_iter it;
1288 struct task_struct *task;
1289
Tetsuo Handaf168a9a2019-07-11 21:00:20 -07001290 css_task_iter_start(&iter->css, CSS_TASK_ITER_PROCS, &it);
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001291 while (!ret && (task = css_task_iter_next(&it)))
1292 ret = fn(task, arg);
1293 css_task_iter_end(&it);
1294 if (ret) {
1295 mem_cgroup_iter_break(memcg, iter);
1296 break;
1297 }
1298 }
1299 return ret;
1300}
1301
1302/**
Johannes Weinerdfe0e772014-12-10 15:43:43 -08001303 * mem_cgroup_page_lruvec - return lruvec for isolating/putting an LRU page
Johannes Weiner925b7672012-01-12 17:18:15 -08001304 * @page: the page
Mike Rapoportf144c392018-02-06 15:42:16 -08001305 * @pgdat: pgdat of the page
Johannes Weinerdfe0e772014-12-10 15:43:43 -08001306 *
Johannes Weinera0b5b412020-06-03 16:02:27 -07001307 * This function relies on page->mem_cgroup being stable - see the
1308 * access rules in commit_charge().
Minchan Kim3f58a822011-03-22 16:32:53 -07001309 */
Mel Gorman599d0c92016-07-28 15:45:31 -07001310struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct pglist_data *pgdat)
Minchan Kim3f58a822011-03-22 16:32:53 -07001311{
Mel Gormanef8f2322016-07-28 15:46:05 -07001312 struct mem_cgroup_per_node *mz;
Johannes Weiner925b7672012-01-12 17:18:15 -08001313 struct mem_cgroup *memcg;
Hugh Dickinsbea8c152012-11-16 14:14:54 -08001314 struct lruvec *lruvec;
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08001315
Hugh Dickinsbea8c152012-11-16 14:14:54 -08001316 if (mem_cgroup_disabled()) {
Johannes Weiner867e5e12019-11-30 17:55:34 -08001317 lruvec = &pgdat->__lruvec;
Hugh Dickinsbea8c152012-11-16 14:14:54 -08001318 goto out;
1319 }
Christoph Lameterb69408e2008-10-18 20:26:14 -07001320
Johannes Weiner1306a852014-12-10 15:44:52 -08001321 memcg = page->mem_cgroup;
Hugh Dickins75121022012-03-05 14:59:18 -08001322 /*
Johannes Weinerdfe0e772014-12-10 15:43:43 -08001323 * Swapcache readahead pages are added to the LRU - and
Johannes Weiner29833312014-12-10 15:44:02 -08001324 * possibly migrated - before they are charged.
Hugh Dickins75121022012-03-05 14:59:18 -08001325 */
Johannes Weiner29833312014-12-10 15:44:02 -08001326 if (!memcg)
1327 memcg = root_mem_cgroup;
Hugh Dickins75121022012-03-05 14:59:18 -08001328
Mel Gormanef8f2322016-07-28 15:46:05 -07001329 mz = mem_cgroup_page_nodeinfo(memcg, page);
Hugh Dickinsbea8c152012-11-16 14:14:54 -08001330 lruvec = &mz->lruvec;
1331out:
1332 /*
1333 * Since a node can be onlined after the mem_cgroup was created,
1334 * we have to be prepared to initialize lruvec->zone here;
1335 * and if offlined then reonlined, we need to reinitialize it.
1336 */
Mel Gorman599d0c92016-07-28 15:45:31 -07001337 if (unlikely(lruvec->pgdat != pgdat))
1338 lruvec->pgdat = pgdat;
Hugh Dickinsbea8c152012-11-16 14:14:54 -08001339 return lruvec;
Johannes Weiner925b7672012-01-12 17:18:15 -08001340}
1341
1342/**
Hugh Dickinsfa9add62012-05-29 15:07:09 -07001343 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1344 * @lruvec: mem_cgroup per zone lru vector
1345 * @lru: index of lru list the page is sitting on
Michal Hockob4536f0c82017-01-10 16:58:04 -08001346 * @zid: zone id of the accounted pages
Hugh Dickinsfa9add62012-05-29 15:07:09 -07001347 * @nr_pages: positive when adding or negative when removing
Johannes Weiner925b7672012-01-12 17:18:15 -08001348 *
Hugh Dickinsca707232016-05-19 17:12:35 -07001349 * This function must be called under lru_lock, just before a page is added
1350 * to or just after a page is removed from an lru list (that ordering being
1351 * so as to allow it to check that lru_size 0 is consistent with list_empty).
Johannes Weiner925b7672012-01-12 17:18:15 -08001352 */
Hugh Dickinsfa9add62012-05-29 15:07:09 -07001353void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001354 int zid, int nr_pages)
Johannes Weiner925b7672012-01-12 17:18:15 -08001355{
Mel Gormanef8f2322016-07-28 15:46:05 -07001356 struct mem_cgroup_per_node *mz;
Hugh Dickinsfa9add62012-05-29 15:07:09 -07001357 unsigned long *lru_size;
Hugh Dickinsca707232016-05-19 17:12:35 -07001358 long size;
Johannes Weiner925b7672012-01-12 17:18:15 -08001359
1360 if (mem_cgroup_disabled())
1361 return;
1362
Mel Gormanef8f2322016-07-28 15:46:05 -07001363 mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
Michal Hockob4536f0c82017-01-10 16:58:04 -08001364 lru_size = &mz->lru_zone_size[zid][lru];
Hugh Dickinsca707232016-05-19 17:12:35 -07001365
1366 if (nr_pages < 0)
1367 *lru_size += nr_pages;
1368
1369 size = *lru_size;
Michal Hockob4536f0c82017-01-10 16:58:04 -08001370 if (WARN_ONCE(size < 0,
1371 "%s(%p, %d, %d): lru_size %ld\n",
1372 __func__, lruvec, lru, nr_pages, size)) {
Hugh Dickinsca707232016-05-19 17:12:35 -07001373 VM_BUG_ON(1);
1374 *lru_size = 0;
1375 }
1376
1377 if (nr_pages > 0)
1378 *lru_size += nr_pages;
KAMEZAWA Hiroyuki08e552c2009-01-07 18:08:01 -08001379}
KAMEZAWA Hiroyuki544122e2009-01-07 18:08:34 -08001380
Johannes Weiner19942822011-02-01 15:52:43 -08001381/**
Johannes Weiner9d11ea92011-03-23 16:42:21 -07001382 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
Wanpeng Lidad75572012-06-20 12:53:01 -07001383 * @memcg: the memory cgroup
Johannes Weiner19942822011-02-01 15:52:43 -08001384 *
Johannes Weiner9d11ea92011-03-23 16:42:21 -07001385 * Returns the maximum amount of memory @mem can be charged with, in
Johannes Weiner7ec99d62011-03-23 16:42:36 -07001386 * pages.
Johannes Weiner19942822011-02-01 15:52:43 -08001387 */
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001388static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
Johannes Weiner19942822011-02-01 15:52:43 -08001389{
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001390 unsigned long margin = 0;
1391 unsigned long count;
1392 unsigned long limit;
Johannes Weiner9d11ea92011-03-23 16:42:21 -07001393
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001394 count = page_counter_read(&memcg->memory);
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001395 limit = READ_ONCE(memcg->memory.max);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001396 if (count < limit)
1397 margin = limit - count;
1398
Johannes Weiner7941d212016-01-14 15:21:23 -08001399 if (do_memsw_account()) {
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001400 count = page_counter_read(&memcg->memsw);
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001401 limit = READ_ONCE(memcg->memsw.max);
Kaixu Xia1c4448e2020-06-01 21:49:36 -07001402 if (count < limit)
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001403 margin = min(margin, limit - count);
Li RongQingcbedbac2016-05-27 14:27:43 -07001404 else
1405 margin = 0;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001406 }
1407
1408 return margin;
Johannes Weiner19942822011-02-01 15:52:43 -08001409}
1410
KAMEZAWA Hiroyuki619d0942012-03-21 16:34:23 -07001411/*
Qiang Huangbdcbb652014-06-04 16:08:21 -07001412 * A routine for checking "mem" is under move_account() or not.
KAMEZAWA Hiroyuki32047e22010-10-27 15:33:40 -07001413 *
Qiang Huangbdcbb652014-06-04 16:08:21 -07001414 * Checking a cgroup is mc.from or mc.to or under hierarchy of
1415 * moving cgroups. This is for waiting at high-memory pressure
1416 * caused by "move".
KAMEZAWA Hiroyuki32047e22010-10-27 15:33:40 -07001417 */
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001418static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07001419{
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07001420 struct mem_cgroup *from;
1421 struct mem_cgroup *to;
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07001422 bool ret = false;
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07001423 /*
1424 * Unlike task_move routines, we access mc.to, mc.from not under
1425 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1426 */
1427 spin_lock(&mc.lock);
1428 from = mc.from;
1429 to = mc.to;
1430 if (!from)
1431 goto unlock;
Michal Hocko3e920412011-07-26 16:08:29 -07001432
Johannes Weiner2314b422014-12-10 15:44:33 -08001433 ret = mem_cgroup_is_descendant(from, memcg) ||
1434 mem_cgroup_is_descendant(to, memcg);
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07001435unlock:
1436 spin_unlock(&mc.lock);
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07001437 return ret;
1438}
1439
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001440static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07001441{
1442 if (mc.moving_task && current != mc.moving_task) {
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001443 if (mem_cgroup_under_move(memcg)) {
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07001444 DEFINE_WAIT(wait);
1445 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1446 /* moving charge context might have finished. */
1447 if (mc.moving_task)
1448 schedule();
1449 finish_wait(&mc.waitq, &wait);
1450 return true;
1451 }
1452 }
1453 return false;
1454}
1455
Johannes Weinerc8713d02019-07-11 20:55:59 -07001456static char *memory_stat_format(struct mem_cgroup *memcg)
1457{
1458 struct seq_buf s;
1459 int i;
Johannes Weiner71cd3112017-05-03 14:55:13 -07001460
Johannes Weinerc8713d02019-07-11 20:55:59 -07001461 seq_buf_init(&s, kmalloc(PAGE_SIZE, GFP_KERNEL), PAGE_SIZE);
1462 if (!s.buffer)
1463 return NULL;
1464
1465 /*
1466 * Provide statistics on the state of the memory subsystem as
1467 * well as cumulative event counters that show past behavior.
1468 *
1469 * This list is ordered following a combination of these gradients:
1470 * 1) generic big picture -> specifics and details
1471 * 2) reflecting userspace activity -> reflecting kernel heuristics
1472 *
1473 * Current memory state:
1474 */
1475
1476 seq_buf_printf(&s, "anon %llu\n",
Johannes Weinerbe5d0a72020-06-03 16:01:57 -07001477 (u64)memcg_page_state(memcg, NR_ANON_MAPPED) *
Johannes Weinerc8713d02019-07-11 20:55:59 -07001478 PAGE_SIZE);
1479 seq_buf_printf(&s, "file %llu\n",
Johannes Weiner0d1c2072020-06-03 16:01:54 -07001480 (u64)memcg_page_state(memcg, NR_FILE_PAGES) *
Johannes Weinerc8713d02019-07-11 20:55:59 -07001481 PAGE_SIZE);
1482 seq_buf_printf(&s, "kernel_stack %llu\n",
1483 (u64)memcg_page_state(memcg, MEMCG_KERNEL_STACK_KB) *
1484 1024);
1485 seq_buf_printf(&s, "slab %llu\n",
Roman Gushchind42f3242020-08-06 23:20:39 -07001486 (u64)(memcg_page_state(memcg, NR_SLAB_RECLAIMABLE_B) +
1487 memcg_page_state(memcg, NR_SLAB_UNRECLAIMABLE_B)));
Johannes Weinerc8713d02019-07-11 20:55:59 -07001488 seq_buf_printf(&s, "sock %llu\n",
1489 (u64)memcg_page_state(memcg, MEMCG_SOCK) *
1490 PAGE_SIZE);
1491
1492 seq_buf_printf(&s, "shmem %llu\n",
1493 (u64)memcg_page_state(memcg, NR_SHMEM) *
1494 PAGE_SIZE);
1495 seq_buf_printf(&s, "file_mapped %llu\n",
1496 (u64)memcg_page_state(memcg, NR_FILE_MAPPED) *
1497 PAGE_SIZE);
1498 seq_buf_printf(&s, "file_dirty %llu\n",
1499 (u64)memcg_page_state(memcg, NR_FILE_DIRTY) *
1500 PAGE_SIZE);
1501 seq_buf_printf(&s, "file_writeback %llu\n",
1502 (u64)memcg_page_state(memcg, NR_WRITEBACK) *
1503 PAGE_SIZE);
1504
Johannes Weiner468c3982020-06-03 16:02:01 -07001505#ifdef CONFIG_TRANSPARENT_HUGEPAGE
Johannes Weinerc8713d02019-07-11 20:55:59 -07001506 seq_buf_printf(&s, "anon_thp %llu\n",
Johannes Weiner468c3982020-06-03 16:02:01 -07001507 (u64)memcg_page_state(memcg, NR_ANON_THPS) *
1508 HPAGE_PMD_SIZE);
1509#endif
Johannes Weinerc8713d02019-07-11 20:55:59 -07001510
1511 for (i = 0; i < NR_LRU_LISTS; i++)
Konstantin Khlebnikovebc5d83d2019-12-04 16:49:53 -08001512 seq_buf_printf(&s, "%s %llu\n", lru_list_name(i),
Johannes Weinerc8713d02019-07-11 20:55:59 -07001513 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
1514 PAGE_SIZE);
1515
1516 seq_buf_printf(&s, "slab_reclaimable %llu\n",
Roman Gushchind42f3242020-08-06 23:20:39 -07001517 (u64)memcg_page_state(memcg, NR_SLAB_RECLAIMABLE_B));
Johannes Weinerc8713d02019-07-11 20:55:59 -07001518 seq_buf_printf(&s, "slab_unreclaimable %llu\n",
Roman Gushchind42f3242020-08-06 23:20:39 -07001519 (u64)memcg_page_state(memcg, NR_SLAB_UNRECLAIMABLE_B));
Johannes Weinerc8713d02019-07-11 20:55:59 -07001520
1521 /* Accumulated memory events */
1522
Konstantin Khlebnikovebc5d83d2019-12-04 16:49:53 -08001523 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGFAULT),
1524 memcg_events(memcg, PGFAULT));
1525 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGMAJFAULT),
1526 memcg_events(memcg, PGMAJFAULT));
Johannes Weinerc8713d02019-07-11 20:55:59 -07001527
1528 seq_buf_printf(&s, "workingset_refault %lu\n",
1529 memcg_page_state(memcg, WORKINGSET_REFAULT));
1530 seq_buf_printf(&s, "workingset_activate %lu\n",
1531 memcg_page_state(memcg, WORKINGSET_ACTIVATE));
Yafang Shaoa6f55762020-06-01 21:49:32 -07001532 seq_buf_printf(&s, "workingset_restore %lu\n",
1533 memcg_page_state(memcg, WORKINGSET_RESTORE));
Johannes Weinerc8713d02019-07-11 20:55:59 -07001534 seq_buf_printf(&s, "workingset_nodereclaim %lu\n",
1535 memcg_page_state(memcg, WORKINGSET_NODERECLAIM));
1536
Konstantin Khlebnikovebc5d83d2019-12-04 16:49:53 -08001537 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGREFILL),
1538 memcg_events(memcg, PGREFILL));
Johannes Weinerc8713d02019-07-11 20:55:59 -07001539 seq_buf_printf(&s, "pgscan %lu\n",
1540 memcg_events(memcg, PGSCAN_KSWAPD) +
1541 memcg_events(memcg, PGSCAN_DIRECT));
1542 seq_buf_printf(&s, "pgsteal %lu\n",
1543 memcg_events(memcg, PGSTEAL_KSWAPD) +
1544 memcg_events(memcg, PGSTEAL_DIRECT));
Konstantin Khlebnikovebc5d83d2019-12-04 16:49:53 -08001545 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGACTIVATE),
1546 memcg_events(memcg, PGACTIVATE));
1547 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGDEACTIVATE),
1548 memcg_events(memcg, PGDEACTIVATE));
1549 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREE),
1550 memcg_events(memcg, PGLAZYFREE));
1551 seq_buf_printf(&s, "%s %lu\n", vm_event_name(PGLAZYFREED),
1552 memcg_events(memcg, PGLAZYFREED));
Johannes Weinerc8713d02019-07-11 20:55:59 -07001553
1554#ifdef CONFIG_TRANSPARENT_HUGEPAGE
Konstantin Khlebnikovebc5d83d2019-12-04 16:49:53 -08001555 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_FAULT_ALLOC),
Johannes Weinerc8713d02019-07-11 20:55:59 -07001556 memcg_events(memcg, THP_FAULT_ALLOC));
Konstantin Khlebnikovebc5d83d2019-12-04 16:49:53 -08001557 seq_buf_printf(&s, "%s %lu\n", vm_event_name(THP_COLLAPSE_ALLOC),
Johannes Weinerc8713d02019-07-11 20:55:59 -07001558 memcg_events(memcg, THP_COLLAPSE_ALLOC));
1559#endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1560
1561 /* The above should easily fit into one page */
1562 WARN_ON_ONCE(seq_buf_has_overflowed(&s));
1563
1564 return s.buffer;
1565}
Johannes Weiner71cd3112017-05-03 14:55:13 -07001566
Sha Zhengju58cf1882013-02-22 16:32:05 -08001567#define K(x) ((x) << (PAGE_SHIFT-10))
Balbir Singhe2224322009-04-02 16:57:39 -07001568/**
yuzhoujianf0c867d2018-12-28 00:36:10 -08001569 * mem_cgroup_print_oom_context: Print OOM information relevant to
1570 * memory controller.
Balbir Singhe2224322009-04-02 16:57:39 -07001571 * @memcg: The memory cgroup that went over limit
1572 * @p: Task that is going to be killed
1573 *
1574 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1575 * enabled
1576 */
yuzhoujianf0c867d2018-12-28 00:36:10 -08001577void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
1578{
1579 rcu_read_lock();
1580
1581 if (memcg) {
1582 pr_cont(",oom_memcg=");
1583 pr_cont_cgroup_path(memcg->css.cgroup);
1584 } else
1585 pr_cont(",global_oom");
1586 if (p) {
1587 pr_cont(",task_memcg=");
1588 pr_cont_cgroup_path(task_cgroup(p, memory_cgrp_id));
1589 }
1590 rcu_read_unlock();
1591}
1592
1593/**
1594 * mem_cgroup_print_oom_meminfo: Print OOM memory information relevant to
1595 * memory controller.
1596 * @memcg: The memory cgroup that went over limit
1597 */
1598void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
Balbir Singhe2224322009-04-02 16:57:39 -07001599{
Johannes Weinerc8713d02019-07-11 20:55:59 -07001600 char *buf;
Balbir Singhe2224322009-04-02 16:57:39 -07001601
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001602 pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1603 K((u64)page_counter_read(&memcg->memory)),
Chris Down15b42562020-04-01 21:07:20 -07001604 K((u64)READ_ONCE(memcg->memory.max)), memcg->memory.failcnt);
Johannes Weinerc8713d02019-07-11 20:55:59 -07001605 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
1606 pr_info("swap: usage %llukB, limit %llukB, failcnt %lu\n",
1607 K((u64)page_counter_read(&memcg->swap)),
Chris Down32d087c2020-04-01 21:07:30 -07001608 K((u64)READ_ONCE(memcg->swap.max)), memcg->swap.failcnt);
Johannes Weinerc8713d02019-07-11 20:55:59 -07001609 else {
1610 pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1611 K((u64)page_counter_read(&memcg->memsw)),
1612 K((u64)memcg->memsw.max), memcg->memsw.failcnt);
1613 pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1614 K((u64)page_counter_read(&memcg->kmem)),
1615 K((u64)memcg->kmem.max), memcg->kmem.failcnt);
Sha Zhengju58cf1882013-02-22 16:32:05 -08001616 }
Johannes Weinerc8713d02019-07-11 20:55:59 -07001617
1618 pr_info("Memory cgroup stats for ");
1619 pr_cont_cgroup_path(memcg->css.cgroup);
1620 pr_cont(":");
1621 buf = memory_stat_format(memcg);
1622 if (!buf)
1623 return;
1624 pr_info("%s", buf);
1625 kfree(buf);
Balbir Singhe2224322009-04-02 16:57:39 -07001626}
1627
KAMEZAWA Hiroyuki81d39c22009-04-02 16:57:36 -07001628/*
David Rientjesa63d83f2010-08-09 17:19:46 -07001629 * Return the memory (and swap, if configured) limit for a memcg.
1630 */
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001631unsigned long mem_cgroup_get_max(struct mem_cgroup *memcg)
David Rientjesa63d83f2010-08-09 17:19:46 -07001632{
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001633 unsigned long max;
David Rientjesa63d83f2010-08-09 17:19:46 -07001634
Chris Down15b42562020-04-01 21:07:20 -07001635 max = READ_ONCE(memcg->memory.max);
Michal Hocko9a5a8f12012-11-16 14:14:49 -08001636 if (mem_cgroup_swappiness(memcg)) {
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001637 unsigned long memsw_max;
1638 unsigned long swap_max;
Michal Hocko9a5a8f12012-11-16 14:14:49 -08001639
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001640 memsw_max = memcg->memsw.max;
Chris Down32d087c2020-04-01 21:07:30 -07001641 swap_max = READ_ONCE(memcg->swap.max);
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001642 swap_max = min(swap_max, (unsigned long)total_swap_pages);
1643 max = min(max + swap_max, memsw_max);
Michal Hocko9a5a8f12012-11-16 14:14:49 -08001644 }
Roman Gushchinbbec2e12018-06-07 17:06:18 -07001645 return max;
David Rientjesa63d83f2010-08-09 17:19:46 -07001646}
1647
Chris Down9783aa92019-10-06 17:58:32 -07001648unsigned long mem_cgroup_size(struct mem_cgroup *memcg)
1649{
1650 return page_counter_read(&memcg->memory);
1651}
1652
Johannes Weinerb6e6edc2016-03-17 14:20:28 -07001653static bool mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
David Rientjes19965462012-12-11 16:00:26 -08001654 int order)
David Rientjes9cbb78b2012-07-31 16:43:44 -07001655{
David Rientjes6e0fc462015-09-08 15:00:36 -07001656 struct oom_control oc = {
1657 .zonelist = NULL,
1658 .nodemask = NULL,
Vladimir Davydov2a966b72016-07-26 15:22:33 -07001659 .memcg = memcg,
David Rientjes6e0fc462015-09-08 15:00:36 -07001660 .gfp_mask = gfp_mask,
1661 .order = order,
David Rientjes6e0fc462015-09-08 15:00:36 -07001662 };
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001663 bool ret;
David Rientjes9cbb78b2012-07-31 16:43:44 -07001664
Tetsuo Handa7775fac2019-03-05 15:46:47 -08001665 if (mutex_lock_killable(&oom_lock))
1666 return true;
1667 /*
1668 * A few threads which were not waiting at mutex_lock_killable() can
1669 * fail to bail out. Therefore, check again after holding oom_lock.
1670 */
1671 ret = should_force_charge() || out_of_memory(&oc);
Johannes Weinerdc564012015-06-24 16:57:19 -07001672 mutex_unlock(&oom_lock);
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001673 return ret;
David Rientjes9cbb78b2012-07-31 16:43:44 -07001674}
1675
Andrew Morton0608f432013-09-24 15:27:41 -07001676static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
Mel Gormanef8f2322016-07-28 15:46:05 -07001677 pg_data_t *pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07001678 gfp_t gfp_mask,
1679 unsigned long *total_scanned)
Balbir Singh6d61ef42009-01-07 18:08:06 -08001680{
Andrew Morton0608f432013-09-24 15:27:41 -07001681 struct mem_cgroup *victim = NULL;
1682 int total = 0;
1683 int loop = 0;
1684 unsigned long excess;
1685 unsigned long nr_scanned;
1686 struct mem_cgroup_reclaim_cookie reclaim = {
Mel Gormanef8f2322016-07-28 15:46:05 -07001687 .pgdat = pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07001688 };
Johannes Weiner9d11ea92011-03-23 16:42:21 -07001689
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001690 excess = soft_limit_excess(root_memcg);
Balbir Singh6d61ef42009-01-07 18:08:06 -08001691
Andrew Morton0608f432013-09-24 15:27:41 -07001692 while (1) {
1693 victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
1694 if (!victim) {
1695 loop++;
1696 if (loop >= 2) {
1697 /*
1698 * If we have not been able to reclaim
1699 * anything, it might because there are
1700 * no reclaimable pages under this hierarchy
1701 */
1702 if (!total)
1703 break;
1704 /*
1705 * We want to do more targeted reclaim.
1706 * excess >> 2 is not to excessive so as to
1707 * reclaim too much, nor too less that we keep
1708 * coming back to reclaim from this cgroup
1709 */
1710 if (total >= (excess >> 2) ||
1711 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
1712 break;
1713 }
1714 continue;
1715 }
Mel Gormana9dd0a82016-07-28 15:46:02 -07001716 total += mem_cgroup_shrink_node(victim, gfp_mask, false,
Mel Gormanef8f2322016-07-28 15:46:05 -07001717 pgdat, &nr_scanned);
Andrew Morton0608f432013-09-24 15:27:41 -07001718 *total_scanned += nr_scanned;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08001719 if (!soft_limit_excess(root_memcg))
Andrew Morton0608f432013-09-24 15:27:41 -07001720 break;
Balbir Singh6d61ef42009-01-07 18:08:06 -08001721 }
Andrew Morton0608f432013-09-24 15:27:41 -07001722 mem_cgroup_iter_break(root_memcg, victim);
1723 return total;
Balbir Singh6d61ef42009-01-07 18:08:06 -08001724}
1725
Johannes Weiner0056f4e2013-10-31 16:34:14 -07001726#ifdef CONFIG_LOCKDEP
1727static struct lockdep_map memcg_oom_lock_dep_map = {
1728 .name = "memcg_oom_lock",
1729};
1730#endif
1731
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001732static DEFINE_SPINLOCK(memcg_oom_lock);
1733
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001734/*
1735 * Check OOM-Killer is already running under our hierarchy.
1736 * If someone is running, return false.
1737 */
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001738static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001739{
Michal Hocko79dfdac2011-07-26 16:08:23 -07001740 struct mem_cgroup *iter, *failed = NULL;
KAMEZAWA Hiroyukia636b322009-01-07 18:08:08 -08001741
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001742 spin_lock(&memcg_oom_lock);
1743
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001744 for_each_mem_cgroup_tree(iter, memcg) {
Johannes Weiner23751be2011-08-25 15:59:16 -07001745 if (iter->oom_lock) {
Michal Hocko79dfdac2011-07-26 16:08:23 -07001746 /*
1747 * this subtree of our hierarchy is already locked
1748 * so we cannot give a lock.
1749 */
Michal Hocko79dfdac2011-07-26 16:08:23 -07001750 failed = iter;
Johannes Weiner9f3a0d02012-01-12 17:17:48 -08001751 mem_cgroup_iter_break(memcg, iter);
1752 break;
Johannes Weiner23751be2011-08-25 15:59:16 -07001753 } else
1754 iter->oom_lock = true;
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07001755 }
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001756
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001757 if (failed) {
1758 /*
1759 * OK, we failed to lock the whole subtree so we have
1760 * to clean up what we set up to the failing subtree
1761 */
1762 for_each_mem_cgroup_tree(iter, memcg) {
1763 if (iter == failed) {
1764 mem_cgroup_iter_break(memcg, iter);
1765 break;
1766 }
1767 iter->oom_lock = false;
Michal Hocko79dfdac2011-07-26 16:08:23 -07001768 }
Johannes Weiner0056f4e2013-10-31 16:34:14 -07001769 } else
1770 mutex_acquire(&memcg_oom_lock_dep_map, 0, 1, _RET_IP_);
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001771
1772 spin_unlock(&memcg_oom_lock);
1773
1774 return !failed;
KAMEZAWA Hiroyukia636b322009-01-07 18:08:08 -08001775}
KAMEZAWA Hiroyuki0b7f5692009-04-02 16:57:38 -07001776
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001777static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki0b7f5692009-04-02 16:57:38 -07001778{
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07001779 struct mem_cgroup *iter;
1780
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001781 spin_lock(&memcg_oom_lock);
Qian Cai5facae42019-09-19 12:09:40 -04001782 mutex_release(&memcg_oom_lock_dep_map, _RET_IP_);
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001783 for_each_mem_cgroup_tree(iter, memcg)
Michal Hocko79dfdac2011-07-26 16:08:23 -07001784 iter->oom_lock = false;
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001785 spin_unlock(&memcg_oom_lock);
Michal Hocko79dfdac2011-07-26 16:08:23 -07001786}
1787
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001788static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
Michal Hocko79dfdac2011-07-26 16:08:23 -07001789{
1790 struct mem_cgroup *iter;
1791
Tejun Heoc2b42d32015-06-24 16:58:23 -07001792 spin_lock(&memcg_oom_lock);
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001793 for_each_mem_cgroup_tree(iter, memcg)
Tejun Heoc2b42d32015-06-24 16:58:23 -07001794 iter->under_oom++;
1795 spin_unlock(&memcg_oom_lock);
Michal Hocko79dfdac2011-07-26 16:08:23 -07001796}
1797
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001798static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
Michal Hocko79dfdac2011-07-26 16:08:23 -07001799{
1800 struct mem_cgroup *iter;
1801
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001802 /*
1803 * When a new child is created while the hierarchy is under oom,
Tejun Heoc2b42d32015-06-24 16:58:23 -07001804 * mem_cgroup_oom_lock() may not be called. Watch for underflow.
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001805 */
Tejun Heoc2b42d32015-06-24 16:58:23 -07001806 spin_lock(&memcg_oom_lock);
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001807 for_each_mem_cgroup_tree(iter, memcg)
Tejun Heoc2b42d32015-06-24 16:58:23 -07001808 if (iter->under_oom > 0)
1809 iter->under_oom--;
1810 spin_unlock(&memcg_oom_lock);
KAMEZAWA Hiroyuki0b7f5692009-04-02 16:57:38 -07001811}
1812
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001813static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
1814
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07001815struct oom_wait_info {
Hugh Dickinsd79154b2012-03-21 16:34:18 -07001816 struct mem_cgroup *memcg;
Ingo Molnarac6424b2017-06-20 12:06:13 +02001817 wait_queue_entry_t wait;
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07001818};
1819
Ingo Molnarac6424b2017-06-20 12:06:13 +02001820static int memcg_oom_wake_function(wait_queue_entry_t *wait,
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07001821 unsigned mode, int sync, void *arg)
1822{
Hugh Dickinsd79154b2012-03-21 16:34:18 -07001823 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
1824 struct mem_cgroup *oom_wait_memcg;
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07001825 struct oom_wait_info *oom_wait_info;
1826
1827 oom_wait_info = container_of(wait, struct oom_wait_info, wait);
Hugh Dickinsd79154b2012-03-21 16:34:18 -07001828 oom_wait_memcg = oom_wait_info->memcg;
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07001829
Johannes Weiner2314b422014-12-10 15:44:33 -08001830 if (!mem_cgroup_is_descendant(wake_memcg, oom_wait_memcg) &&
1831 !mem_cgroup_is_descendant(oom_wait_memcg, wake_memcg))
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07001832 return 0;
KAMEZAWA Hiroyukidc98df52010-05-26 14:42:36 -07001833 return autoremove_wake_function(wait, mode, sync, arg);
1834}
1835
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001836static void memcg_oom_recover(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07001837{
Tejun Heoc2b42d32015-06-24 16:58:23 -07001838 /*
1839 * For the following lockless ->under_oom test, the only required
1840 * guarantee is that it must see the state asserted by an OOM when
1841 * this function is called as a result of userland actions
1842 * triggered by the notification of the OOM. This is trivially
1843 * achieved by invoking mem_cgroup_mark_under_oom() before
1844 * triggering notification.
1845 */
1846 if (memcg && memcg->under_oom)
Tejun Heof4b90b702015-06-24 16:58:21 -07001847 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07001848}
1849
Michal Hocko29ef6802018-08-17 15:47:11 -07001850enum oom_status {
1851 OOM_SUCCESS,
1852 OOM_FAILED,
1853 OOM_ASYNC,
1854 OOM_SKIPPED
1855};
1856
1857static enum oom_status mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001858{
Michal Hocko7056d3a2018-12-28 00:39:57 -08001859 enum oom_status ret;
1860 bool locked;
1861
Michal Hocko29ef6802018-08-17 15:47:11 -07001862 if (order > PAGE_ALLOC_COSTLY_ORDER)
1863 return OOM_SKIPPED;
1864
Roman Gushchin7a1adfd2018-10-26 15:09:48 -07001865 memcg_memory_event(memcg, MEMCG_OOM);
1866
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001867 /*
Johannes Weiner49426422013-10-16 13:46:59 -07001868 * We are in the middle of the charge context here, so we
1869 * don't want to block when potentially sitting on a callstack
1870 * that holds all kinds of filesystem and mm locks.
1871 *
Michal Hocko29ef6802018-08-17 15:47:11 -07001872 * cgroup1 allows disabling the OOM killer and waiting for outside
1873 * handling until the charge can succeed; remember the context and put
1874 * the task to sleep at the end of the page fault when all locks are
1875 * released.
Johannes Weiner49426422013-10-16 13:46:59 -07001876 *
Michal Hocko29ef6802018-08-17 15:47:11 -07001877 * On the other hand, in-kernel OOM killer allows for an async victim
1878 * memory reclaim (oom_reaper) and that means that we are not solely
1879 * relying on the oom victim to make a forward progress and we can
1880 * invoke the oom killer here.
1881 *
1882 * Please note that mem_cgroup_out_of_memory might fail to find a
1883 * victim and then we have to bail out from the charge path.
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001884 */
Michal Hocko29ef6802018-08-17 15:47:11 -07001885 if (memcg->oom_kill_disable) {
1886 if (!current->in_user_fault)
1887 return OOM_SKIPPED;
1888 css_get(&memcg->css);
1889 current->memcg_in_oom = memcg;
1890 current->memcg_oom_gfp_mask = mask;
1891 current->memcg_oom_order = order;
1892
1893 return OOM_ASYNC;
1894 }
1895
Michal Hocko7056d3a2018-12-28 00:39:57 -08001896 mem_cgroup_mark_under_oom(memcg);
Michal Hocko29ef6802018-08-17 15:47:11 -07001897
Michal Hocko7056d3a2018-12-28 00:39:57 -08001898 locked = mem_cgroup_oom_trylock(memcg);
1899
1900 if (locked)
1901 mem_cgroup_oom_notify(memcg);
1902
1903 mem_cgroup_unmark_under_oom(memcg);
1904 if (mem_cgroup_out_of_memory(memcg, mask, order))
1905 ret = OOM_SUCCESS;
1906 else
1907 ret = OOM_FAILED;
1908
1909 if (locked)
1910 mem_cgroup_oom_unlock(memcg);
1911
1912 return ret;
Johannes Weiner49426422013-10-16 13:46:59 -07001913}
1914
1915/**
1916 * mem_cgroup_oom_synchronize - complete memcg OOM handling
1917 * @handle: actually kill/wait or just clean up the OOM state
1918 *
1919 * This has to be called at the end of a page fault if the memcg OOM
1920 * handler was enabled.
1921 *
1922 * Memcg supports userspace OOM handling where failed allocations must
1923 * sleep on a waitqueue until the userspace task resolves the
1924 * situation. Sleeping directly in the charge context with all kinds
1925 * of locks held is not a good idea, instead we remember an OOM state
1926 * in the task and mem_cgroup_oom_synchronize() has to be called at
1927 * the end of the page fault to complete the OOM handling.
1928 *
1929 * Returns %true if an ongoing memcg OOM situation was detected and
1930 * completed, %false otherwise.
1931 */
1932bool mem_cgroup_oom_synchronize(bool handle)
1933{
Tejun Heo626ebc42015-11-05 18:46:09 -08001934 struct mem_cgroup *memcg = current->memcg_in_oom;
Johannes Weiner49426422013-10-16 13:46:59 -07001935 struct oom_wait_info owait;
1936 bool locked;
1937
1938 /* OOM is global, do not handle */
1939 if (!memcg)
1940 return false;
1941
Vladimir Davydov7c5f64f2016-10-07 16:57:23 -07001942 if (!handle)
Johannes Weiner49426422013-10-16 13:46:59 -07001943 goto cleanup;
1944
1945 owait.memcg = memcg;
1946 owait.wait.flags = 0;
1947 owait.wait.func = memcg_oom_wake_function;
1948 owait.wait.private = current;
Ingo Molnar2055da92017-06-20 12:06:46 +02001949 INIT_LIST_HEAD(&owait.wait.entry);
Johannes Weiner49426422013-10-16 13:46:59 -07001950
1951 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001952 mem_cgroup_mark_under_oom(memcg);
1953
1954 locked = mem_cgroup_oom_trylock(memcg);
1955
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07001956 if (locked)
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07001957 mem_cgroup_oom_notify(memcg);
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001958
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001959 if (locked && !memcg->oom_kill_disable) {
1960 mem_cgroup_unmark_under_oom(memcg);
Johannes Weiner49426422013-10-16 13:46:59 -07001961 finish_wait(&memcg_oom_waitq, &owait.wait);
Tejun Heo626ebc42015-11-05 18:46:09 -08001962 mem_cgroup_out_of_memory(memcg, current->memcg_oom_gfp_mask,
1963 current->memcg_oom_order);
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07001964 } else {
Johannes Weiner3812c8c2013-09-12 15:13:44 -07001965 schedule();
Johannes Weiner49426422013-10-16 13:46:59 -07001966 mem_cgroup_unmark_under_oom(memcg);
1967 finish_wait(&memcg_oom_waitq, &owait.wait);
1968 }
1969
1970 if (locked) {
Johannes Weinerfb2a6fc2013-09-12 15:13:43 -07001971 mem_cgroup_oom_unlock(memcg);
1972 /*
1973 * There is no guarantee that an OOM-lock contender
1974 * sees the wakeups triggered by the OOM kill
1975 * uncharges. Wake any sleepers explicitely.
1976 */
1977 memcg_oom_recover(memcg);
1978 }
Johannes Weiner49426422013-10-16 13:46:59 -07001979cleanup:
Tejun Heo626ebc42015-11-05 18:46:09 -08001980 current->memcg_in_oom = NULL;
Johannes Weiner3812c8c2013-09-12 15:13:44 -07001981 css_put(&memcg->css);
KAMEZAWA Hiroyuki867578c2010-03-10 15:22:39 -08001982 return true;
KAMEZAWA Hiroyuki0b7f5692009-04-02 16:57:38 -07001983}
1984
Johannes Weinerd7365e72014-10-29 14:50:48 -07001985/**
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07001986 * mem_cgroup_get_oom_group - get a memory cgroup to clean up after OOM
1987 * @victim: task to be killed by the OOM killer
1988 * @oom_domain: memcg in case of memcg OOM, NULL in case of system-wide OOM
1989 *
1990 * Returns a pointer to a memory cgroup, which has to be cleaned up
1991 * by killing all belonging OOM-killable tasks.
1992 *
1993 * Caller has to call mem_cgroup_put() on the returned non-NULL memcg.
1994 */
1995struct mem_cgroup *mem_cgroup_get_oom_group(struct task_struct *victim,
1996 struct mem_cgroup *oom_domain)
1997{
1998 struct mem_cgroup *oom_group = NULL;
1999 struct mem_cgroup *memcg;
2000
2001 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
2002 return NULL;
2003
2004 if (!oom_domain)
2005 oom_domain = root_mem_cgroup;
2006
2007 rcu_read_lock();
2008
2009 memcg = mem_cgroup_from_task(victim);
2010 if (memcg == root_mem_cgroup)
2011 goto out;
2012
2013 /*
Roman Gushchin48fe2672020-04-01 21:07:39 -07002014 * If the victim task has been asynchronously moved to a different
2015 * memory cgroup, we might end up killing tasks outside oom_domain.
2016 * In this case it's better to ignore memory.group.oom.
2017 */
2018 if (unlikely(!mem_cgroup_is_descendant(memcg, oom_domain)))
2019 goto out;
2020
2021 /*
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07002022 * Traverse the memory cgroup hierarchy from the victim task's
2023 * cgroup up to the OOMing cgroup (or root) to find the
2024 * highest-level memory cgroup with oom.group set.
2025 */
2026 for (; memcg; memcg = parent_mem_cgroup(memcg)) {
2027 if (memcg->oom_group)
2028 oom_group = memcg;
2029
2030 if (memcg == oom_domain)
2031 break;
2032 }
2033
2034 if (oom_group)
2035 css_get(&oom_group->css);
2036out:
2037 rcu_read_unlock();
2038
2039 return oom_group;
2040}
2041
2042void mem_cgroup_print_oom_group(struct mem_cgroup *memcg)
2043{
2044 pr_info("Tasks in ");
2045 pr_cont_cgroup_path(memcg->css.cgroup);
2046 pr_cont(" are going to be killed due to memory.oom.group set\n");
2047}
2048
2049/**
Johannes Weiner81f8c3a2016-03-15 14:57:04 -07002050 * lock_page_memcg - lock a page->mem_cgroup binding
2051 * @page: the page
KAMEZAWA Hiroyuki32047e22010-10-27 15:33:40 -07002052 *
Johannes Weiner81f8c3a2016-03-15 14:57:04 -07002053 * This function protects unlocked LRU pages from being moved to
Johannes Weiner739f79f2017-08-18 15:15:48 -07002054 * another cgroup.
2055 *
2056 * It ensures lifetime of the returned memcg. Caller is responsible
2057 * for the lifetime of the page; __unlock_page_memcg() is available
2058 * when @page might get freed inside the locked section.
Balbir Singhd69b0422009-06-17 16:26:34 -07002059 */
Johannes Weiner739f79f2017-08-18 15:15:48 -07002060struct mem_cgroup *lock_page_memcg(struct page *page)
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002061{
Johannes Weiner9da7b522020-06-03 16:01:51 -07002062 struct page *head = compound_head(page); /* rmap on tail pages */
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002063 struct mem_cgroup *memcg;
Johannes Weiner6de22612015-02-11 15:25:01 -08002064 unsigned long flags;
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002065
Johannes Weiner6de22612015-02-11 15:25:01 -08002066 /*
2067 * The RCU lock is held throughout the transaction. The fast
2068 * path can get away without acquiring the memcg->move_lock
2069 * because page moving starts with an RCU grace period.
Johannes Weiner739f79f2017-08-18 15:15:48 -07002070 *
2071 * The RCU lock also protects the memcg from being freed when
2072 * the page state that is going to change is the only thing
2073 * preventing the page itself from being freed. E.g. writeback
2074 * doesn't hold a page reference and relies on PG_writeback to
2075 * keep off truncation, migration and so forth.
2076 */
Johannes Weinerd7365e72014-10-29 14:50:48 -07002077 rcu_read_lock();
2078
2079 if (mem_cgroup_disabled())
Johannes Weiner739f79f2017-08-18 15:15:48 -07002080 return NULL;
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002081again:
Johannes Weiner9da7b522020-06-03 16:01:51 -07002082 memcg = head->mem_cgroup;
Johannes Weiner29833312014-12-10 15:44:02 -08002083 if (unlikely(!memcg))
Johannes Weiner739f79f2017-08-18 15:15:48 -07002084 return NULL;
Johannes Weinerd7365e72014-10-29 14:50:48 -07002085
Qiang Huangbdcbb652014-06-04 16:08:21 -07002086 if (atomic_read(&memcg->moving_account) <= 0)
Johannes Weiner739f79f2017-08-18 15:15:48 -07002087 return memcg;
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002088
Johannes Weiner6de22612015-02-11 15:25:01 -08002089 spin_lock_irqsave(&memcg->move_lock, flags);
Johannes Weiner9da7b522020-06-03 16:01:51 -07002090 if (memcg != head->mem_cgroup) {
Johannes Weiner6de22612015-02-11 15:25:01 -08002091 spin_unlock_irqrestore(&memcg->move_lock, flags);
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002092 goto again;
2093 }
Johannes Weiner6de22612015-02-11 15:25:01 -08002094
2095 /*
2096 * When charge migration first begins, we can have locked and
2097 * unlocked page stat updates happening concurrently. Track
Johannes Weiner81f8c3a2016-03-15 14:57:04 -07002098 * the task who has the lock for unlock_page_memcg().
Johannes Weiner6de22612015-02-11 15:25:01 -08002099 */
2100 memcg->move_lock_task = current;
2101 memcg->move_lock_flags = flags;
Johannes Weinerd7365e72014-10-29 14:50:48 -07002102
Johannes Weiner739f79f2017-08-18 15:15:48 -07002103 return memcg;
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002104}
Johannes Weiner81f8c3a2016-03-15 14:57:04 -07002105EXPORT_SYMBOL(lock_page_memcg);
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002106
Johannes Weinerd7365e72014-10-29 14:50:48 -07002107/**
Johannes Weiner739f79f2017-08-18 15:15:48 -07002108 * __unlock_page_memcg - unlock and unpin a memcg
2109 * @memcg: the memcg
2110 *
2111 * Unlock and unpin a memcg returned by lock_page_memcg().
Johannes Weinerd7365e72014-10-29 14:50:48 -07002112 */
Johannes Weiner739f79f2017-08-18 15:15:48 -07002113void __unlock_page_memcg(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002114{
Johannes Weiner6de22612015-02-11 15:25:01 -08002115 if (memcg && memcg->move_lock_task == current) {
2116 unsigned long flags = memcg->move_lock_flags;
2117
2118 memcg->move_lock_task = NULL;
2119 memcg->move_lock_flags = 0;
2120
2121 spin_unlock_irqrestore(&memcg->move_lock, flags);
2122 }
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002123
Johannes Weinerd7365e72014-10-29 14:50:48 -07002124 rcu_read_unlock();
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002125}
Johannes Weiner739f79f2017-08-18 15:15:48 -07002126
2127/**
2128 * unlock_page_memcg - unlock a page->mem_cgroup binding
2129 * @page: the page
2130 */
2131void unlock_page_memcg(struct page *page)
2132{
Johannes Weiner9da7b522020-06-03 16:01:51 -07002133 struct page *head = compound_head(page);
2134
2135 __unlock_page_memcg(head->mem_cgroup);
Johannes Weiner739f79f2017-08-18 15:15:48 -07002136}
Johannes Weiner81f8c3a2016-03-15 14:57:04 -07002137EXPORT_SYMBOL(unlock_page_memcg);
KAMEZAWA Hiroyuki89c06bd2012-03-21 16:34:25 -07002138
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002139struct memcg_stock_pcp {
2140 struct mem_cgroup *cached; /* this never be root cgroup */
Johannes Weiner11c9ea42011-03-23 16:42:34 -07002141 unsigned int nr_pages;
Roman Gushchinbf4f0592020-08-06 23:20:49 -07002142
2143#ifdef CONFIG_MEMCG_KMEM
2144 struct obj_cgroup *cached_objcg;
2145 unsigned int nr_bytes;
2146#endif
2147
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002148 struct work_struct work;
KAMEZAWA Hiroyuki26fe6162011-06-15 15:08:45 -07002149 unsigned long flags;
Kirill A. Shutemova0db00f2012-05-29 15:06:56 -07002150#define FLUSHING_CACHED_CHARGE 0
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002151};
2152static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
Michal Hocko9f50fad2011-08-09 11:56:26 +02002153static DEFINE_MUTEX(percpu_charge_mutex);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002154
Roman Gushchinbf4f0592020-08-06 23:20:49 -07002155#ifdef CONFIG_MEMCG_KMEM
2156static void drain_obj_stock(struct memcg_stock_pcp *stock);
2157static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2158 struct mem_cgroup *root_memcg);
2159
2160#else
2161static inline void drain_obj_stock(struct memcg_stock_pcp *stock)
2162{
2163}
2164static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
2165 struct mem_cgroup *root_memcg)
2166{
2167 return false;
2168}
2169#endif
2170
Suleiman Souhlala0956d52012-12-18 14:21:36 -08002171/**
2172 * consume_stock: Try to consume stocked charge on this cpu.
2173 * @memcg: memcg to consume from.
2174 * @nr_pages: how many pages to charge.
2175 *
2176 * The charges will only happen if @memcg matches the current cpu's memcg
2177 * stock, and at least @nr_pages are available in that stock. Failure to
2178 * service an allocation will refill the stock.
2179 *
2180 * returns true if successful, false otherwise.
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002181 */
Suleiman Souhlala0956d52012-12-18 14:21:36 -08002182static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002183{
2184 struct memcg_stock_pcp *stock;
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002185 unsigned long flags;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002186 bool ret = false;
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002187
Johannes Weinera983b5e2018-01-31 16:16:45 -08002188 if (nr_pages > MEMCG_CHARGE_BATCH)
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002189 return ret;
Suleiman Souhlala0956d52012-12-18 14:21:36 -08002190
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002191 local_irq_save(flags);
2192
2193 stock = this_cpu_ptr(&memcg_stock);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002194 if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
Suleiman Souhlala0956d52012-12-18 14:21:36 -08002195 stock->nr_pages -= nr_pages;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002196 ret = true;
2197 }
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002198
2199 local_irq_restore(flags);
2200
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002201 return ret;
2202}
2203
2204/*
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002205 * Returns stocks cached in percpu and reset cached information.
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002206 */
2207static void drain_stock(struct memcg_stock_pcp *stock)
2208{
2209 struct mem_cgroup *old = stock->cached;
2210
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07002211 if (!old)
2212 return;
2213
Johannes Weiner11c9ea42011-03-23 16:42:34 -07002214 if (stock->nr_pages) {
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002215 page_counter_uncharge(&old->memory, stock->nr_pages);
Johannes Weiner7941d212016-01-14 15:21:23 -08002216 if (do_memsw_account())
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002217 page_counter_uncharge(&old->memsw, stock->nr_pages);
Johannes Weiner11c9ea42011-03-23 16:42:34 -07002218 stock->nr_pages = 0;
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002219 }
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07002220
2221 css_put(&old->css);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002222 stock->cached = NULL;
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002223}
2224
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002225static void drain_local_stock(struct work_struct *dummy)
2226{
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002227 struct memcg_stock_pcp *stock;
2228 unsigned long flags;
2229
Michal Hocko72f01842017-10-03 16:14:53 -07002230 /*
2231 * The only protection from memory hotplug vs. drain_stock races is
2232 * that we always operate on local CPU stock here with IRQ disabled
2233 */
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002234 local_irq_save(flags);
2235
2236 stock = this_cpu_ptr(&memcg_stock);
Roman Gushchinbf4f0592020-08-06 23:20:49 -07002237 drain_obj_stock(stock);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002238 drain_stock(stock);
KAMEZAWA Hiroyuki26fe6162011-06-15 15:08:45 -07002239 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002240
2241 local_irq_restore(flags);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002242}
2243
2244/*
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002245 * Cache charges(val) to local per_cpu area.
Greg Thelen320cc512010-03-15 15:27:28 +01002246 * This will be consumed by consume_stock() function, later.
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002247 */
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002248static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002249{
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002250 struct memcg_stock_pcp *stock;
2251 unsigned long flags;
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002252
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002253 local_irq_save(flags);
2254
2255 stock = this_cpu_ptr(&memcg_stock);
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002256 if (stock->cached != memcg) { /* reset if necessary */
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002257 drain_stock(stock);
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07002258 css_get(&memcg->css);
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002259 stock->cached = memcg;
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002260 }
Johannes Weiner11c9ea42011-03-23 16:42:34 -07002261 stock->nr_pages += nr_pages;
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002262
Johannes Weinera983b5e2018-01-31 16:16:45 -08002263 if (stock->nr_pages > MEMCG_CHARGE_BATCH)
Roman Gushchin475d0482017-09-08 16:13:09 -07002264 drain_stock(stock);
2265
Johannes Weinerdb2ba40c2016-09-19 14:44:36 -07002266 local_irq_restore(flags);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002267}
2268
2269/*
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002270 * Drains all per-CPU charge caches for given root_memcg resp. subtree
Johannes Weiner6d3d6aa2014-12-10 15:42:50 -08002271 * of the hierarchy under it.
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002272 */
Johannes Weiner6d3d6aa2014-12-10 15:42:50 -08002273static void drain_all_stock(struct mem_cgroup *root_memcg)
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002274{
KAMEZAWA Hiroyuki26fe6162011-06-15 15:08:45 -07002275 int cpu, curcpu;
Michal Hockod38144b2011-07-26 16:08:28 -07002276
Johannes Weiner6d3d6aa2014-12-10 15:42:50 -08002277 /* If someone's already draining, avoid adding running more workers. */
2278 if (!mutex_trylock(&percpu_charge_mutex))
2279 return;
Michal Hocko72f01842017-10-03 16:14:53 -07002280 /*
2281 * Notify other cpus that system-wide "drain" is running
2282 * We do not care about races with the cpu hotplug because cpu down
2283 * as well as workers from this path always operate on the local
2284 * per-cpu data. CPU up doesn't touch memcg_stock at all.
2285 */
Johannes Weiner5af12d02011-08-25 15:59:07 -07002286 curcpu = get_cpu();
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002287 for_each_online_cpu(cpu) {
2288 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002289 struct mem_cgroup *memcg;
Roman Gushchine1a366b2019-09-23 15:34:58 -07002290 bool flush = false;
KAMEZAWA Hiroyuki26fe6162011-06-15 15:08:45 -07002291
Roman Gushchine1a366b2019-09-23 15:34:58 -07002292 rcu_read_lock();
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07002293 memcg = stock->cached;
Roman Gushchine1a366b2019-09-23 15:34:58 -07002294 if (memcg && stock->nr_pages &&
2295 mem_cgroup_is_descendant(memcg, root_memcg))
2296 flush = true;
Roman Gushchinbf4f0592020-08-06 23:20:49 -07002297 if (obj_stock_flush_required(stock, root_memcg))
2298 flush = true;
Roman Gushchine1a366b2019-09-23 15:34:58 -07002299 rcu_read_unlock();
2300
2301 if (flush &&
2302 !test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
Michal Hockod1a05b62011-07-26 16:08:27 -07002303 if (cpu == curcpu)
2304 drain_local_stock(&stock->work);
2305 else
2306 schedule_work_on(cpu, &stock->work);
2307 }
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002308 }
Johannes Weiner5af12d02011-08-25 15:59:07 -07002309 put_cpu();
Michal Hocko9f50fad2011-08-09 11:56:26 +02002310 mutex_unlock(&percpu_charge_mutex);
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002311}
2312
Sebastian Andrzej Siewior308167f2016-11-03 15:49:59 +01002313static int memcg_hotplug_cpu_dead(unsigned int cpu)
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002314{
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002315 struct memcg_stock_pcp *stock;
Johannes Weiner42a30032019-05-14 15:47:12 -07002316 struct mem_cgroup *memcg, *mi;
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002317
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002318 stock = &per_cpu(memcg_stock, cpu);
2319 drain_stock(stock);
Johannes Weinera983b5e2018-01-31 16:16:45 -08002320
2321 for_each_mem_cgroup(memcg) {
2322 int i;
2323
2324 for (i = 0; i < MEMCG_NR_STAT; i++) {
2325 int nid;
2326 long x;
2327
Chris Down871789d2019-05-14 15:46:57 -07002328 x = this_cpu_xchg(memcg->vmstats_percpu->stat[i], 0);
Johannes Weiner815744d2019-06-13 15:55:46 -07002329 if (x)
Johannes Weiner42a30032019-05-14 15:47:12 -07002330 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2331 atomic_long_add(x, &memcg->vmstats[i]);
Johannes Weinera983b5e2018-01-31 16:16:45 -08002332
2333 if (i >= NR_VM_NODE_STAT_ITEMS)
2334 continue;
2335
2336 for_each_node(nid) {
2337 struct mem_cgroup_per_node *pn;
2338
2339 pn = mem_cgroup_nodeinfo(memcg, nid);
2340 x = this_cpu_xchg(pn->lruvec_stat_cpu->count[i], 0);
Johannes Weiner815744d2019-06-13 15:55:46 -07002341 if (x)
Johannes Weiner42a30032019-05-14 15:47:12 -07002342 do {
2343 atomic_long_add(x, &pn->lruvec_stat[i]);
2344 } while ((pn = parent_nodeinfo(pn, nid)));
Johannes Weinera983b5e2018-01-31 16:16:45 -08002345 }
2346 }
2347
Johannes Weinere27be242018-04-10 16:29:45 -07002348 for (i = 0; i < NR_VM_EVENT_ITEMS; i++) {
Johannes Weinera983b5e2018-01-31 16:16:45 -08002349 long x;
2350
Chris Down871789d2019-05-14 15:46:57 -07002351 x = this_cpu_xchg(memcg->vmstats_percpu->events[i], 0);
Johannes Weiner815744d2019-06-13 15:55:46 -07002352 if (x)
Johannes Weiner42a30032019-05-14 15:47:12 -07002353 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
2354 atomic_long_add(x, &memcg->vmevents[i]);
Johannes Weinera983b5e2018-01-31 16:16:45 -08002355 }
2356 }
2357
Sebastian Andrzej Siewior308167f2016-11-03 15:49:59 +01002358 return 0;
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002359}
2360
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08002361static void reclaim_high(struct mem_cgroup *memcg,
2362 unsigned int nr_pages,
2363 gfp_t gfp_mask)
2364{
2365 do {
Jakub Kicinskid1663a92020-06-01 21:49:49 -07002366 if (page_counter_read(&memcg->memory) <=
2367 READ_ONCE(memcg->memory.high))
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08002368 continue;
Johannes Weinere27be242018-04-10 16:29:45 -07002369 memcg_memory_event(memcg, MEMCG_HIGH);
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08002370 try_to_free_mem_cgroup_pages(memcg, nr_pages, gfp_mask, true);
Chris Down4bf17302020-04-06 20:03:30 -07002371 } while ((memcg = parent_mem_cgroup(memcg)) &&
2372 !mem_cgroup_is_root(memcg));
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08002373}
2374
2375static void high_work_func(struct work_struct *work)
2376{
2377 struct mem_cgroup *memcg;
2378
2379 memcg = container_of(work, struct mem_cgroup, high_work);
Johannes Weinera983b5e2018-01-31 16:16:45 -08002380 reclaim_high(memcg, MEMCG_CHARGE_BATCH, GFP_KERNEL);
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08002381}
2382
Tejun Heob23afb92015-11-05 18:46:11 -08002383/*
Chris Down0e4b01d2019-09-23 15:34:55 -07002384 * Clamp the maximum sleep time per allocation batch to 2 seconds. This is
2385 * enough to still cause a significant slowdown in most cases, while still
2386 * allowing diagnostics and tracing to proceed without becoming stuck.
2387 */
2388#define MEMCG_MAX_HIGH_DELAY_JIFFIES (2UL*HZ)
2389
2390/*
2391 * When calculating the delay, we use these either side of the exponentiation to
2392 * maintain precision and scale to a reasonable number of jiffies (see the table
2393 * below.
2394 *
2395 * - MEMCG_DELAY_PRECISION_SHIFT: Extra precision bits while translating the
2396 * overage ratio to a delay.
2397 * - MEMCG_DELAY_SCALING_SHIFT: The number of bits to scale down down the
2398 * proposed penalty in order to reduce to a reasonable number of jiffies, and
2399 * to produce a reasonable delay curve.
2400 *
2401 * MEMCG_DELAY_SCALING_SHIFT just happens to be a number that produces a
2402 * reasonable delay curve compared to precision-adjusted overage, not
2403 * penalising heavily at first, but still making sure that growth beyond the
2404 * limit penalises misbehaviour cgroups by slowing them down exponentially. For
2405 * example, with a high of 100 megabytes:
2406 *
2407 * +-------+------------------------+
2408 * | usage | time to allocate in ms |
2409 * +-------+------------------------+
2410 * | 100M | 0 |
2411 * | 101M | 6 |
2412 * | 102M | 25 |
2413 * | 103M | 57 |
2414 * | 104M | 102 |
2415 * | 105M | 159 |
2416 * | 106M | 230 |
2417 * | 107M | 313 |
2418 * | 108M | 409 |
2419 * | 109M | 518 |
2420 * | 110M | 639 |
2421 * | 111M | 774 |
2422 * | 112M | 921 |
2423 * | 113M | 1081 |
2424 * | 114M | 1254 |
2425 * | 115M | 1439 |
2426 * | 116M | 1638 |
2427 * | 117M | 1849 |
2428 * | 118M | 2000 |
2429 * | 119M | 2000 |
2430 * | 120M | 2000 |
2431 * +-------+------------------------+
2432 */
2433 #define MEMCG_DELAY_PRECISION_SHIFT 20
2434 #define MEMCG_DELAY_SCALING_SHIFT 14
2435
Jakub Kicinski8a5dbc62020-06-01 21:49:42 -07002436static u64 calculate_overage(unsigned long usage, unsigned long high)
2437{
2438 u64 overage;
2439
2440 if (usage <= high)
2441 return 0;
2442
2443 /*
2444 * Prevent division by 0 in overage calculation by acting as if
2445 * it was a threshold of 1 page
2446 */
2447 high = max(high, 1UL);
2448
2449 overage = usage - high;
2450 overage <<= MEMCG_DELAY_PRECISION_SHIFT;
2451 return div64_u64(overage, high);
2452}
2453
2454static u64 mem_find_max_overage(struct mem_cgroup *memcg)
2455{
2456 u64 overage, max_overage = 0;
2457
2458 do {
2459 overage = calculate_overage(page_counter_read(&memcg->memory),
Jakub Kicinskid1663a92020-06-01 21:49:49 -07002460 READ_ONCE(memcg->memory.high));
Jakub Kicinski8a5dbc62020-06-01 21:49:42 -07002461 max_overage = max(overage, max_overage);
2462 } while ((memcg = parent_mem_cgroup(memcg)) &&
2463 !mem_cgroup_is_root(memcg));
2464
2465 return max_overage;
2466}
2467
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07002468static u64 swap_find_max_overage(struct mem_cgroup *memcg)
2469{
2470 u64 overage, max_overage = 0;
2471
2472 do {
2473 overage = calculate_overage(page_counter_read(&memcg->swap),
2474 READ_ONCE(memcg->swap.high));
2475 if (overage)
2476 memcg_memory_event(memcg, MEMCG_SWAP_HIGH);
2477 max_overage = max(overage, max_overage);
2478 } while ((memcg = parent_mem_cgroup(memcg)) &&
2479 !mem_cgroup_is_root(memcg));
2480
2481 return max_overage;
2482}
2483
Chris Down0e4b01d2019-09-23 15:34:55 -07002484/*
Chris Downe26733e2020-03-21 18:22:23 -07002485 * Get the number of jiffies that we should penalise a mischievous cgroup which
2486 * is exceeding its memory.high by checking both it and its ancestors.
Tejun Heob23afb92015-11-05 18:46:11 -08002487 */
Chris Downe26733e2020-03-21 18:22:23 -07002488static unsigned long calculate_high_delay(struct mem_cgroup *memcg,
Jakub Kicinski8a5dbc62020-06-01 21:49:42 -07002489 unsigned int nr_pages,
2490 u64 max_overage)
Tejun Heob23afb92015-11-05 18:46:11 -08002491{
Chris Downe26733e2020-03-21 18:22:23 -07002492 unsigned long penalty_jiffies;
Chris Downe26733e2020-03-21 18:22:23 -07002493
2494 if (!max_overage)
2495 return 0;
Chris Down0e4b01d2019-09-23 15:34:55 -07002496
2497 /*
Chris Down0e4b01d2019-09-23 15:34:55 -07002498 * We use overage compared to memory.high to calculate the number of
2499 * jiffies to sleep (penalty_jiffies). Ideally this value should be
2500 * fairly lenient on small overages, and increasingly harsh when the
2501 * memcg in question makes it clear that it has no intention of stopping
2502 * its crazy behaviour, so we exponentially increase the delay based on
2503 * overage amount.
2504 */
Chris Downe26733e2020-03-21 18:22:23 -07002505 penalty_jiffies = max_overage * max_overage * HZ;
2506 penalty_jiffies >>= MEMCG_DELAY_PRECISION_SHIFT;
2507 penalty_jiffies >>= MEMCG_DELAY_SCALING_SHIFT;
Chris Down0e4b01d2019-09-23 15:34:55 -07002508
2509 /*
2510 * Factor in the task's own contribution to the overage, such that four
2511 * N-sized allocations are throttled approximately the same as one
2512 * 4N-sized allocation.
2513 *
2514 * MEMCG_CHARGE_BATCH pages is nominal, so work out how much smaller or
2515 * larger the current charge patch is than that.
2516 */
Jakub Kicinskiff144e62020-06-01 21:49:45 -07002517 return penalty_jiffies * nr_pages / MEMCG_CHARGE_BATCH;
Chris Downe26733e2020-03-21 18:22:23 -07002518}
2519
2520/*
2521 * Scheduled by try_charge() to be executed from the userland return path
2522 * and reclaims memory over the high limit.
2523 */
2524void mem_cgroup_handle_over_high(void)
2525{
2526 unsigned long penalty_jiffies;
2527 unsigned long pflags;
2528 unsigned int nr_pages = current->memcg_nr_pages_over_high;
2529 struct mem_cgroup *memcg;
2530
2531 if (likely(!nr_pages))
2532 return;
2533
2534 memcg = get_mem_cgroup_from_mm(current->mm);
2535 reclaim_high(memcg, nr_pages, GFP_KERNEL);
2536 current->memcg_nr_pages_over_high = 0;
2537
2538 /*
2539 * memory.high is breached and reclaim is unable to keep up. Throttle
2540 * allocators proactively to slow down excessive growth.
2541 */
Jakub Kicinski8a5dbc62020-06-01 21:49:42 -07002542 penalty_jiffies = calculate_high_delay(memcg, nr_pages,
2543 mem_find_max_overage(memcg));
Chris Down0e4b01d2019-09-23 15:34:55 -07002544
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07002545 penalty_jiffies += calculate_high_delay(memcg, nr_pages,
2546 swap_find_max_overage(memcg));
2547
Chris Down0e4b01d2019-09-23 15:34:55 -07002548 /*
Jakub Kicinskiff144e62020-06-01 21:49:45 -07002549 * Clamp the max delay per usermode return so as to still keep the
2550 * application moving forwards and also permit diagnostics, albeit
2551 * extremely slowly.
2552 */
2553 penalty_jiffies = min(penalty_jiffies, MEMCG_MAX_HIGH_DELAY_JIFFIES);
2554
2555 /*
Chris Down0e4b01d2019-09-23 15:34:55 -07002556 * Don't sleep if the amount of jiffies this memcg owes us is so low
2557 * that it's not even worth doing, in an attempt to be nice to those who
2558 * go only a small amount over their memory.high value and maybe haven't
2559 * been aggressively reclaimed enough yet.
2560 */
2561 if (penalty_jiffies <= HZ / 100)
2562 goto out;
2563
2564 /*
2565 * If we exit early, we're guaranteed to die (since
2566 * schedule_timeout_killable sets TASK_KILLABLE). This means we don't
2567 * need to account for any ill-begotten jiffies to pay them off later.
2568 */
2569 psi_memstall_enter(&pflags);
2570 schedule_timeout_killable(penalty_jiffies);
2571 psi_memstall_leave(&pflags);
2572
2573out:
2574 css_put(&memcg->css);
Tejun Heob23afb92015-11-05 18:46:11 -08002575}
2576
Johannes Weiner00501b52014-08-08 14:19:20 -07002577static int try_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2578 unsigned int nr_pages)
Balbir Singh8a9f3cc2008-02-07 00:13:53 -08002579{
Johannes Weinera983b5e2018-01-31 16:16:45 -08002580 unsigned int batch = max(MEMCG_CHARGE_BATCH, nr_pages);
Johannes Weiner9b130612014-08-06 16:05:51 -07002581 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
Johannes Weiner6539cc02014-08-06 16:05:42 -07002582 struct mem_cgroup *mem_over_limit;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002583 struct page_counter *counter;
Johannes Weiner6539cc02014-08-06 16:05:42 -07002584 unsigned long nr_reclaimed;
Johannes Weinerb70a2a22014-10-09 15:28:56 -07002585 bool may_swap = true;
2586 bool drained = false;
Michal Hocko29ef6802018-08-17 15:47:11 -07002587 enum oom_status oom_status;
KAMEZAWA Hiroyukia636b322009-01-07 18:08:08 -08002588
Johannes Weinerce00a962014-09-05 08:43:57 -04002589 if (mem_cgroup_is_root(memcg))
Tejun Heo10d53c72015-11-05 18:46:17 -08002590 return 0;
Johannes Weiner6539cc02014-08-06 16:05:42 -07002591retry:
Michal Hockob6b6cc72014-04-07 15:37:44 -07002592 if (consume_stock(memcg, nr_pages))
Tejun Heo10d53c72015-11-05 18:46:17 -08002593 return 0;
Balbir Singh8a9f3cc2008-02-07 00:13:53 -08002594
Johannes Weiner7941d212016-01-14 15:21:23 -08002595 if (!do_memsw_account() ||
Johannes Weiner6071ca52015-11-05 18:50:26 -08002596 page_counter_try_charge(&memcg->memsw, batch, &counter)) {
2597 if (page_counter_try_charge(&memcg->memory, batch, &counter))
Johannes Weiner6539cc02014-08-06 16:05:42 -07002598 goto done_restock;
Johannes Weiner7941d212016-01-14 15:21:23 -08002599 if (do_memsw_account())
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002600 page_counter_uncharge(&memcg->memsw, batch);
2601 mem_over_limit = mem_cgroup_from_counter(counter, memory);
Johannes Weiner3fbe7242014-10-09 15:28:54 -07002602 } else {
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002603 mem_over_limit = mem_cgroup_from_counter(counter, memsw);
Johannes Weinerb70a2a22014-10-09 15:28:56 -07002604 may_swap = false;
Johannes Weiner3fbe7242014-10-09 15:28:54 -07002605 }
KAMEZAWA Hiroyuki7a81b882009-01-07 18:07:48 -08002606
Johannes Weiner6539cc02014-08-06 16:05:42 -07002607 if (batch > nr_pages) {
2608 batch = nr_pages;
2609 goto retry;
2610 }
KAMEZAWA Hiroyukicdec2e42009-12-15 16:47:08 -08002611
Johannes Weiner06b078f2014-08-06 16:05:44 -07002612 /*
Johannes Weiner869712f2019-11-05 21:17:13 -08002613 * Memcg doesn't have a dedicated reserve for atomic
2614 * allocations. But like the global atomic pool, we need to
2615 * put the burden of reclaim on regular allocation requests
2616 * and let these go through as privileged allocations.
2617 */
2618 if (gfp_mask & __GFP_ATOMIC)
2619 goto force;
2620
2621 /*
Johannes Weiner06b078f2014-08-06 16:05:44 -07002622 * Unlike in global OOM situations, memcg is not in a physical
2623 * memory shortage. Allow dying and OOM-killed tasks to
2624 * bypass the last charges so that they can exit quickly and
2625 * free their memory.
2626 */
Tetsuo Handa7775fac2019-03-05 15:46:47 -08002627 if (unlikely(should_force_charge()))
Tejun Heo10d53c72015-11-05 18:46:17 -08002628 goto force;
Johannes Weiner06b078f2014-08-06 16:05:44 -07002629
Johannes Weiner89a28482016-10-27 17:46:56 -07002630 /*
2631 * Prevent unbounded recursion when reclaim operations need to
2632 * allocate memory. This might exceed the limits temporarily,
2633 * but we prefer facilitating memory reclaim and getting back
2634 * under the limit over triggering OOM kills in these cases.
2635 */
2636 if (unlikely(current->flags & PF_MEMALLOC))
2637 goto force;
2638
Johannes Weiner06b078f2014-08-06 16:05:44 -07002639 if (unlikely(task_in_memcg_oom(current)))
2640 goto nomem;
2641
Mel Gormand0164ad2015-11-06 16:28:21 -08002642 if (!gfpflags_allow_blocking(gfp_mask))
Johannes Weiner6539cc02014-08-06 16:05:42 -07002643 goto nomem;
KAMEZAWA Hiroyuki4b534332010-08-10 18:02:57 -07002644
Johannes Weinere27be242018-04-10 16:29:45 -07002645 memcg_memory_event(mem_over_limit, MEMCG_MAX);
Johannes Weiner241994ed2015-02-11 15:26:06 -08002646
Johannes Weinerb70a2a22014-10-09 15:28:56 -07002647 nr_reclaimed = try_to_free_mem_cgroup_pages(mem_over_limit, nr_pages,
2648 gfp_mask, may_swap);
Johannes Weiner6539cc02014-08-06 16:05:42 -07002649
Johannes Weiner61e02c72014-08-06 16:08:16 -07002650 if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
Johannes Weiner6539cc02014-08-06 16:05:42 -07002651 goto retry;
Johannes Weiner28c34c22014-08-06 16:05:47 -07002652
Johannes Weinerb70a2a22014-10-09 15:28:56 -07002653 if (!drained) {
Johannes Weiner6d3d6aa2014-12-10 15:42:50 -08002654 drain_all_stock(mem_over_limit);
Johannes Weinerb70a2a22014-10-09 15:28:56 -07002655 drained = true;
2656 goto retry;
2657 }
2658
Johannes Weiner28c34c22014-08-06 16:05:47 -07002659 if (gfp_mask & __GFP_NORETRY)
2660 goto nomem;
Johannes Weiner6539cc02014-08-06 16:05:42 -07002661 /*
2662 * Even though the limit is exceeded at this point, reclaim
2663 * may have been able to free some pages. Retry the charge
2664 * before killing the task.
2665 *
2666 * Only for regular pages, though: huge pages are rather
2667 * unlikely to succeed so close to the limit, and we fall back
2668 * to regular pages anyway in case of failure.
2669 */
Johannes Weiner61e02c72014-08-06 16:08:16 -07002670 if (nr_reclaimed && nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER))
Johannes Weiner6539cc02014-08-06 16:05:42 -07002671 goto retry;
2672 /*
2673 * At task move, charge accounts can be doubly counted. So, it's
2674 * better to wait until the end of task_move if something is going on.
2675 */
2676 if (mem_cgroup_wait_acct_move(mem_over_limit))
2677 goto retry;
2678
Johannes Weiner9b130612014-08-06 16:05:51 -07002679 if (nr_retries--)
2680 goto retry;
2681
Shakeel Butt38d38492019-07-11 20:55:48 -07002682 if (gfp_mask & __GFP_RETRY_MAYFAIL)
Michal Hocko29ef6802018-08-17 15:47:11 -07002683 goto nomem;
2684
Johannes Weiner06b078f2014-08-06 16:05:44 -07002685 if (gfp_mask & __GFP_NOFAIL)
Tejun Heo10d53c72015-11-05 18:46:17 -08002686 goto force;
Johannes Weiner06b078f2014-08-06 16:05:44 -07002687
Johannes Weiner6539cc02014-08-06 16:05:42 -07002688 if (fatal_signal_pending(current))
Tejun Heo10d53c72015-11-05 18:46:17 -08002689 goto force;
Johannes Weiner6539cc02014-08-06 16:05:42 -07002690
Michal Hocko29ef6802018-08-17 15:47:11 -07002691 /*
2692 * keep retrying as long as the memcg oom killer is able to make
2693 * a forward progress or bypass the charge if the oom killer
2694 * couldn't make any progress.
2695 */
2696 oom_status = mem_cgroup_oom(mem_over_limit, gfp_mask,
Jerome Marchand3608de02015-11-05 18:47:29 -08002697 get_order(nr_pages * PAGE_SIZE));
Michal Hocko29ef6802018-08-17 15:47:11 -07002698 switch (oom_status) {
2699 case OOM_SUCCESS:
2700 nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
Michal Hocko29ef6802018-08-17 15:47:11 -07002701 goto retry;
2702 case OOM_FAILED:
2703 goto force;
2704 default:
2705 goto nomem;
2706 }
KAMEZAWA Hiroyuki7a81b882009-01-07 18:07:48 -08002707nomem:
Johannes Weiner6d1fdc42014-04-07 15:37:45 -07002708 if (!(gfp_mask & __GFP_NOFAIL))
Johannes Weiner3168ecb2013-10-31 16:34:13 -07002709 return -ENOMEM;
Tejun Heo10d53c72015-11-05 18:46:17 -08002710force:
2711 /*
2712 * The allocation either can't fail or will lead to more memory
2713 * being freed very soon. Allow memory usage go over the limit
2714 * temporarily by force charging it.
2715 */
2716 page_counter_charge(&memcg->memory, nr_pages);
Johannes Weiner7941d212016-01-14 15:21:23 -08002717 if (do_memsw_account())
Tejun Heo10d53c72015-11-05 18:46:17 -08002718 page_counter_charge(&memcg->memsw, nr_pages);
Tejun Heo10d53c72015-11-05 18:46:17 -08002719
2720 return 0;
Johannes Weiner6539cc02014-08-06 16:05:42 -07002721
2722done_restock:
2723 if (batch > nr_pages)
2724 refill_stock(memcg, batch - nr_pages);
Tejun Heob23afb92015-11-05 18:46:11 -08002725
Johannes Weiner241994ed2015-02-11 15:26:06 -08002726 /*
Tejun Heob23afb92015-11-05 18:46:11 -08002727 * If the hierarchy is above the normal consumption range, schedule
2728 * reclaim on returning to userland. We can perform reclaim here
Mel Gorman71baba42015-11-06 16:28:28 -08002729 * if __GFP_RECLAIM but let's always punt for simplicity and so that
Tejun Heob23afb92015-11-05 18:46:11 -08002730 * GFP_KERNEL can consistently be used during reclaim. @memcg is
2731 * not recorded as it most likely matches current's and won't
2732 * change in the meantime. As high limit is checked again before
2733 * reclaim, the cost of mismatch is negligible.
Johannes Weiner241994ed2015-02-11 15:26:06 -08002734 */
2735 do {
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07002736 bool mem_high, swap_high;
2737
2738 mem_high = page_counter_read(&memcg->memory) >
2739 READ_ONCE(memcg->memory.high);
2740 swap_high = page_counter_read(&memcg->swap) >
2741 READ_ONCE(memcg->swap.high);
2742
2743 /* Don't bother a random interrupted task */
2744 if (in_interrupt()) {
2745 if (mem_high) {
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08002746 schedule_work(&memcg->high_work);
2747 break;
2748 }
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07002749 continue;
2750 }
2751
2752 if (mem_high || swap_high) {
2753 /*
2754 * The allocating tasks in this cgroup will need to do
2755 * reclaim or be throttled to prevent further growth
2756 * of the memory or swap footprints.
2757 *
2758 * Target some best-effort fairness between the tasks,
2759 * and distribute reclaim work and delay penalties
2760 * based on how much each task is actually allocating.
2761 */
Vladimir Davydov9516a182015-12-11 13:40:24 -08002762 current->memcg_nr_pages_over_high += batch;
Tejun Heob23afb92015-11-05 18:46:11 -08002763 set_notify_resume(current);
2764 break;
2765 }
Johannes Weiner241994ed2015-02-11 15:26:06 -08002766 } while ((memcg = parent_mem_cgroup(memcg)));
Tejun Heo10d53c72015-11-05 18:46:17 -08002767
2768 return 0;
KAMEZAWA Hiroyuki7a81b882009-01-07 18:07:48 -08002769}
Balbir Singh8a9f3cc2008-02-07 00:13:53 -08002770
Johannes Weinerf0e45fb2020-06-03 16:02:07 -07002771#if defined(CONFIG_MEMCG_KMEM) || defined(CONFIG_MMU)
Johannes Weiner00501b52014-08-08 14:19:20 -07002772static void cancel_charge(struct mem_cgroup *memcg, unsigned int nr_pages)
Daisuke Nishimuraa3032a22009-12-15 16:47:10 -08002773{
Johannes Weinerce00a962014-09-05 08:43:57 -04002774 if (mem_cgroup_is_root(memcg))
2775 return;
2776
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002777 page_counter_uncharge(&memcg->memory, nr_pages);
Johannes Weiner7941d212016-01-14 15:21:23 -08002778 if (do_memsw_account())
Johannes Weiner3e32cb22014-12-10 15:42:31 -08002779 page_counter_uncharge(&memcg->memsw, nr_pages);
KAMEZAWA Hiroyukid01dd172012-05-29 15:07:03 -07002780}
Johannes Weinerf0e45fb2020-06-03 16:02:07 -07002781#endif
KAMEZAWA Hiroyukid01dd172012-05-29 15:07:03 -07002782
Johannes Weinerd9eb1ea2020-06-03 16:02:24 -07002783static void commit_charge(struct page *page, struct mem_cgroup *memcg)
Johannes Weiner0a31bc92014-08-08 14:19:22 -07002784{
Johannes Weiner1306a852014-12-10 15:44:52 -08002785 VM_BUG_ON_PAGE(page->mem_cgroup, page);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07002786 /*
Johannes Weinera0b5b412020-06-03 16:02:27 -07002787 * Any of the following ensures page->mem_cgroup stability:
Johannes Weiner0a31bc92014-08-08 14:19:22 -07002788 *
Johannes Weinera0b5b412020-06-03 16:02:27 -07002789 * - the page lock
2790 * - LRU isolation
2791 * - lock_page_memcg()
2792 * - exclusive reference
Johannes Weiner0a31bc92014-08-08 14:19:22 -07002793 */
Johannes Weiner1306a852014-12-10 15:44:52 -08002794 page->mem_cgroup = memcg;
Balbir Singh8a9f3cc2008-02-07 00:13:53 -08002795}
2796
Kirill Tkhai84c07d12018-08-17 15:47:25 -07002797#ifdef CONFIG_MEMCG_KMEM
Roman Gushchin8380ce42020-03-28 19:17:25 -07002798/*
2799 * Returns a pointer to the memory cgroup to which the kernel object is charged.
2800 *
2801 * The caller must ensure the memcg lifetime, e.g. by taking rcu_read_lock(),
2802 * cgroup_mutex, etc.
2803 */
2804struct mem_cgroup *mem_cgroup_from_obj(void *p)
2805{
2806 struct page *page;
2807
2808 if (mem_cgroup_disabled())
2809 return NULL;
2810
2811 page = virt_to_head_page(p);
2812
2813 /*
2814 * Slab pages don't have page->mem_cgroup set because corresponding
2815 * kmem caches can be reparented during the lifetime. That's why
2816 * memcg_from_slab_page() should be used instead.
2817 */
2818 if (PageSlab(page))
2819 return memcg_from_slab_page(page);
2820
2821 /* All other pages use page->mem_cgroup */
2822 return page->mem_cgroup;
2823}
2824
Roman Gushchinbf4f0592020-08-06 23:20:49 -07002825__always_inline struct obj_cgroup *get_obj_cgroup_from_current(void)
2826{
2827 struct obj_cgroup *objcg = NULL;
2828 struct mem_cgroup *memcg;
2829
2830 if (unlikely(!current->mm && !current->active_memcg))
2831 return NULL;
2832
2833 rcu_read_lock();
2834 if (unlikely(current->active_memcg))
2835 memcg = rcu_dereference(current->active_memcg);
2836 else
2837 memcg = mem_cgroup_from_task(current);
2838
2839 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
2840 objcg = rcu_dereference(memcg->objcg);
2841 if (objcg && obj_cgroup_tryget(objcg))
2842 break;
2843 }
2844 rcu_read_unlock();
2845
2846 return objcg;
2847}
2848
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07002849static int memcg_alloc_cache_id(void)
Glauber Costa55007d82012-12-18 14:22:38 -08002850{
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07002851 int id, size;
2852 int err;
Glauber Costa55007d82012-12-18 14:22:38 -08002853
Vladimir Davydovdbcf73e2015-02-12 14:58:57 -08002854 id = ida_simple_get(&memcg_cache_ida,
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07002855 0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
2856 if (id < 0)
2857 return id;
2858
Vladimir Davydovdbcf73e2015-02-12 14:58:57 -08002859 if (id < memcg_nr_cache_ids)
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07002860 return id;
2861
2862 /*
2863 * There's no space for the new id in memcg_caches arrays,
2864 * so we have to grow them.
2865 */
Vladimir Davydov05257a12015-02-12 14:59:01 -08002866 down_write(&memcg_cache_ids_sem);
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07002867
2868 size = 2 * (id + 1);
Glauber Costa55007d82012-12-18 14:22:38 -08002869 if (size < MEMCG_CACHES_MIN_SIZE)
2870 size = MEMCG_CACHES_MIN_SIZE;
2871 else if (size > MEMCG_CACHES_MAX_SIZE)
2872 size = MEMCG_CACHES_MAX_SIZE;
2873
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07002874 err = memcg_update_all_caches(size);
Vladimir Davydov05257a12015-02-12 14:59:01 -08002875 if (!err)
Vladimir Davydov60d3fd32015-02-12 14:59:10 -08002876 err = memcg_update_all_list_lrus(size);
2877 if (!err)
Vladimir Davydov05257a12015-02-12 14:59:01 -08002878 memcg_nr_cache_ids = size;
2879
2880 up_write(&memcg_cache_ids_sem);
2881
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07002882 if (err) {
Vladimir Davydovdbcf73e2015-02-12 14:58:57 -08002883 ida_simple_remove(&memcg_cache_ida, id);
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07002884 return err;
2885 }
2886 return id;
2887}
2888
2889static void memcg_free_cache_id(int id)
2890{
Vladimir Davydovdbcf73e2015-02-12 14:58:57 -08002891 ida_simple_remove(&memcg_cache_ida, id);
Glauber Costa55007d82012-12-18 14:22:38 -08002892}
2893
Vladimir Davydovd5b3cf72015-02-10 14:11:47 -08002894struct memcg_kmem_cache_create_work {
Vladimir Davydov5722d092014-04-07 15:39:24 -07002895 struct mem_cgroup *memcg;
2896 struct kmem_cache *cachep;
2897 struct work_struct work;
2898};
2899
Vladimir Davydovd5b3cf72015-02-10 14:11:47 -08002900static void memcg_kmem_cache_create_func(struct work_struct *w)
Glauber Costad7f25f82012-12-18 14:22:40 -08002901{
Vladimir Davydovd5b3cf72015-02-10 14:11:47 -08002902 struct memcg_kmem_cache_create_work *cw =
2903 container_of(w, struct memcg_kmem_cache_create_work, work);
Vladimir Davydov5722d092014-04-07 15:39:24 -07002904 struct mem_cgroup *memcg = cw->memcg;
2905 struct kmem_cache *cachep = cw->cachep;
Glauber Costad7f25f82012-12-18 14:22:40 -08002906
Vladimir Davydovd5b3cf72015-02-10 14:11:47 -08002907 memcg_create_kmem_cache(memcg, cachep);
Vladimir Davydovbd673142014-06-04 16:07:40 -07002908
Vladimir Davydov5722d092014-04-07 15:39:24 -07002909 css_put(&memcg->css);
Glauber Costad7f25f82012-12-18 14:22:40 -08002910 kfree(cw);
2911}
2912
2913/*
2914 * Enqueue the creation of a per-memcg kmem_cache.
Glauber Costad7f25f82012-12-18 14:22:40 -08002915 */
Shakeel Butt85cfb242018-10-26 15:07:41 -07002916static void memcg_schedule_kmem_cache_create(struct mem_cgroup *memcg,
Vladimir Davydovd5b3cf72015-02-10 14:11:47 -08002917 struct kmem_cache *cachep)
Glauber Costad7f25f82012-12-18 14:22:40 -08002918{
Vladimir Davydovd5b3cf72015-02-10 14:11:47 -08002919 struct memcg_kmem_cache_create_work *cw;
Glauber Costad7f25f82012-12-18 14:22:40 -08002920
Roman Gushchinf0a3a242019-07-11 20:56:27 -07002921 if (!css_tryget_online(&memcg->css))
2922 return;
2923
Minchan Kimc892fd82018-04-20 14:56:17 -07002924 cw = kmalloc(sizeof(*cw), GFP_NOWAIT | __GFP_NOWARN);
Muchun Song3a989902020-06-25 20:30:19 -07002925 if (!cw) {
2926 css_put(&memcg->css);
Glauber Costad7f25f82012-12-18 14:22:40 -08002927 return;
Muchun Song3a989902020-06-25 20:30:19 -07002928 }
Vladimir Davydov8135be52014-12-12 16:56:38 -08002929
Glauber Costad7f25f82012-12-18 14:22:40 -08002930 cw->memcg = memcg;
2931 cw->cachep = cachep;
Vladimir Davydovd5b3cf72015-02-10 14:11:47 -08002932 INIT_WORK(&cw->work, memcg_kmem_cache_create_func);
Glauber Costad7f25f82012-12-18 14:22:40 -08002933
Tejun Heo17cc4df2017-02-22 15:41:36 -08002934 queue_work(memcg_kmem_cache_wq, &cw->work);
Glauber Costad7f25f82012-12-18 14:22:40 -08002935}
2936
Vladimir Davydov45264772016-07-26 15:24:21 -07002937static inline bool memcg_kmem_bypass(void)
2938{
Zefan Li50d53d72020-06-01 21:49:55 -07002939 if (in_interrupt())
2940 return true;
2941
2942 /* Allow remote memcg charging in kthread contexts. */
2943 if ((!current->mm || (current->flags & PF_KTHREAD)) &&
2944 !current->active_memcg)
Vladimir Davydov45264772016-07-26 15:24:21 -07002945 return true;
2946 return false;
2947}
2948
2949/**
2950 * memcg_kmem_get_cache: select the correct per-memcg cache for allocation
2951 * @cachep: the original global kmem cache
2952 *
Glauber Costad7f25f82012-12-18 14:22:40 -08002953 * Return the kmem_cache we're supposed to use for a slab allocation.
2954 * We try to use the current memcg's version of the cache.
2955 *
Vladimir Davydov45264772016-07-26 15:24:21 -07002956 * If the cache does not exist yet, if we are the first user of it, we
2957 * create it asynchronously in a workqueue and let the current allocation
2958 * go through with the original cache.
Glauber Costad7f25f82012-12-18 14:22:40 -08002959 *
Vladimir Davydov45264772016-07-26 15:24:21 -07002960 * This function takes a reference to the cache it returns to assure it
2961 * won't get destroyed while we are working with it. Once the caller is
2962 * done with it, memcg_kmem_put_cache() must be called to release the
2963 * reference.
Glauber Costad7f25f82012-12-18 14:22:40 -08002964 */
Vladimir Davydov45264772016-07-26 15:24:21 -07002965struct kmem_cache *memcg_kmem_get_cache(struct kmem_cache *cachep)
Glauber Costad7f25f82012-12-18 14:22:40 -08002966{
2967 struct mem_cgroup *memcg;
Vladimir Davydov959c8962014-01-23 15:52:59 -08002968 struct kmem_cache *memcg_cachep;
Roman Gushchinf0a3a242019-07-11 20:56:27 -07002969 struct memcg_cache_array *arr;
Vladimir Davydov2a4db7e2015-02-12 14:59:32 -08002970 int kmemcg_id;
Glauber Costad7f25f82012-12-18 14:22:40 -08002971
Vladimir Davydovf7ce3192015-02-12 14:59:20 -08002972 VM_BUG_ON(!is_root_cache(cachep));
Glauber Costad7f25f82012-12-18 14:22:40 -08002973
Vladimir Davydov45264772016-07-26 15:24:21 -07002974 if (memcg_kmem_bypass())
Vladimir Davydov230e9fc2016-01-14 15:18:15 -08002975 return cachep;
2976
Roman Gushchinf0a3a242019-07-11 20:56:27 -07002977 rcu_read_lock();
2978
2979 if (unlikely(current->active_memcg))
2980 memcg = current->active_memcg;
2981 else
2982 memcg = mem_cgroup_from_task(current);
2983
2984 if (!memcg || memcg == root_mem_cgroup)
2985 goto out_unlock;
2986
Jason Low4db0c3c2015-04-15 16:14:08 -07002987 kmemcg_id = READ_ONCE(memcg->kmemcg_id);
Vladimir Davydov2a4db7e2015-02-12 14:59:32 -08002988 if (kmemcg_id < 0)
Roman Gushchinf0a3a242019-07-11 20:56:27 -07002989 goto out_unlock;
Glauber Costad7f25f82012-12-18 14:22:40 -08002990
Roman Gushchinf0a3a242019-07-11 20:56:27 -07002991 arr = rcu_dereference(cachep->memcg_params.memcg_caches);
2992
2993 /*
2994 * Make sure we will access the up-to-date value. The code updating
2995 * memcg_caches issues a write barrier to match the data dependency
2996 * barrier inside READ_ONCE() (see memcg_create_kmem_cache()).
2997 */
2998 memcg_cachep = READ_ONCE(arr->entries[kmemcg_id]);
Li Zefanca0dde92013-04-29 15:08:57 -07002999
3000 /*
3001 * If we are in a safe context (can wait, and not in interrupt
3002 * context), we could be be predictable and return right away.
3003 * This would guarantee that the allocation being performed
3004 * already belongs in the new cache.
3005 *
3006 * However, there are some clashes that can arrive from locking.
3007 * For instance, because we acquire the slab_mutex while doing
Vladimir Davydov776ed0f2014-06-04 16:10:02 -07003008 * memcg_create_kmem_cache, this means no further allocation
3009 * could happen with the slab_mutex held. So it's better to
3010 * defer everything.
Roman Gushchinf0a3a242019-07-11 20:56:27 -07003011 *
3012 * If the memcg is dying or memcg_cache is about to be released,
3013 * don't bother creating new kmem_caches. Because memcg_cachep
3014 * is ZEROed as the fist step of kmem offlining, we don't need
3015 * percpu_ref_tryget_live() here. css_tryget_online() check in
3016 * memcg_schedule_kmem_cache_create() will prevent us from
3017 * creation of a new kmem_cache.
Li Zefanca0dde92013-04-29 15:08:57 -07003018 */
Roman Gushchinf0a3a242019-07-11 20:56:27 -07003019 if (unlikely(!memcg_cachep))
3020 memcg_schedule_kmem_cache_create(memcg, cachep);
3021 else if (percpu_ref_tryget(&memcg_cachep->memcg_params.refcnt))
3022 cachep = memcg_cachep;
3023out_unlock:
3024 rcu_read_unlock();
Li Zefanca0dde92013-04-29 15:08:57 -07003025 return cachep;
Glauber Costad7f25f82012-12-18 14:22:40 -08003026}
Glauber Costad7f25f82012-12-18 14:22:40 -08003027
Vladimir Davydov45264772016-07-26 15:24:21 -07003028/**
3029 * memcg_kmem_put_cache: drop reference taken by memcg_kmem_get_cache
3030 * @cachep: the cache returned by memcg_kmem_get_cache
3031 */
3032void memcg_kmem_put_cache(struct kmem_cache *cachep)
Vladimir Davydov8135be52014-12-12 16:56:38 -08003033{
3034 if (!is_root_cache(cachep))
Roman Gushchinf0a3a242019-07-11 20:56:27 -07003035 percpu_ref_put(&cachep->memcg_params.refcnt);
Vladimir Davydov8135be52014-12-12 16:56:38 -08003036}
3037
Vladimir Davydov45264772016-07-26 15:24:21 -07003038/**
Roman Gushchin4b13f642020-04-01 21:06:56 -07003039 * __memcg_kmem_charge: charge a number of kernel pages to a memcg
Roman Gushchin10eaec22020-04-01 21:06:39 -07003040 * @memcg: memory cgroup to charge
Vladimir Davydov45264772016-07-26 15:24:21 -07003041 * @gfp: reclaim mode
Roman Gushchin92d0510c2020-04-01 21:06:49 -07003042 * @nr_pages: number of pages to charge
Vladimir Davydov45264772016-07-26 15:24:21 -07003043 *
3044 * Returns 0 on success, an error code on failure.
3045 */
Roman Gushchin4b13f642020-04-01 21:06:56 -07003046int __memcg_kmem_charge(struct mem_cgroup *memcg, gfp_t gfp,
3047 unsigned int nr_pages)
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08003048{
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08003049 struct page_counter *counter;
Johannes Weiner6071ca52015-11-05 18:50:26 -08003050 int ret;
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08003051
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08003052 ret = try_charge(memcg, gfp, nr_pages);
Johannes Weiner52c29b02016-01-20 15:02:35 -08003053 if (ret)
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08003054 return ret;
Johannes Weiner52c29b02016-01-20 15:02:35 -08003055
3056 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) &&
3057 !page_counter_try_charge(&memcg->kmem, nr_pages, &counter)) {
Michal Hockoe55d9d92019-09-25 16:45:53 -07003058
3059 /*
3060 * Enforce __GFP_NOFAIL allocation because callers are not
3061 * prepared to see failures and likely do not have any failure
3062 * handling code.
3063 */
3064 if (gfp & __GFP_NOFAIL) {
3065 page_counter_charge(&memcg->kmem, nr_pages);
3066 return 0;
3067 }
Johannes Weiner52c29b02016-01-20 15:02:35 -08003068 cancel_charge(memcg, nr_pages);
3069 return -ENOMEM;
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08003070 }
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08003071 return 0;
3072}
3073
Vladimir Davydov45264772016-07-26 15:24:21 -07003074/**
Roman Gushchin4b13f642020-04-01 21:06:56 -07003075 * __memcg_kmem_uncharge: uncharge a number of kernel pages from a memcg
3076 * @memcg: memcg to uncharge
3077 * @nr_pages: number of pages to uncharge
3078 */
3079void __memcg_kmem_uncharge(struct mem_cgroup *memcg, unsigned int nr_pages)
3080{
3081 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
3082 page_counter_uncharge(&memcg->kmem, nr_pages);
3083
3084 page_counter_uncharge(&memcg->memory, nr_pages);
3085 if (do_memsw_account())
3086 page_counter_uncharge(&memcg->memsw, nr_pages);
3087}
3088
3089/**
Roman Gushchinf4b00ea2020-04-01 21:06:46 -07003090 * __memcg_kmem_charge_page: charge a kmem page to the current memory cgroup
Vladimir Davydov45264772016-07-26 15:24:21 -07003091 * @page: page to charge
3092 * @gfp: reclaim mode
3093 * @order: allocation order
3094 *
3095 * Returns 0 on success, an error code on failure.
3096 */
Roman Gushchinf4b00ea2020-04-01 21:06:46 -07003097int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003098{
3099 struct mem_cgroup *memcg;
Vladimir Davydovfcff7d72016-03-17 14:17:29 -07003100 int ret = 0;
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003101
Shakeel Butt60cd4bc2019-03-05 15:43:13 -08003102 if (memcg_kmem_bypass())
Vladimir Davydov45264772016-07-26 15:24:21 -07003103 return 0;
3104
Shakeel Buttd46eb14b2018-08-17 15:46:39 -07003105 memcg = get_mem_cgroup_from_current();
Vladimir Davydovc4159a72016-08-08 23:03:12 +03003106 if (!mem_cgroup_is_root(memcg)) {
Roman Gushchin4b13f642020-04-01 21:06:56 -07003107 ret = __memcg_kmem_charge(memcg, gfp, 1 << order);
Roman Gushchin4d96ba32019-07-11 20:56:31 -07003108 if (!ret) {
3109 page->mem_cgroup = memcg;
Vladimir Davydovc4159a72016-08-08 23:03:12 +03003110 __SetPageKmemcg(page);
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07003111 return 0;
Roman Gushchin4d96ba32019-07-11 20:56:31 -07003112 }
Vladimir Davydovc4159a72016-08-08 23:03:12 +03003113 }
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003114 css_put(&memcg->css);
Vladimir Davydovd05e83a2015-11-05 18:48:59 -08003115 return ret;
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003116}
Roman Gushchin49a18ea2019-07-11 20:56:13 -07003117
3118/**
Roman Gushchinf4b00ea2020-04-01 21:06:46 -07003119 * __memcg_kmem_uncharge_page: uncharge a kmem page
Vladimir Davydov45264772016-07-26 15:24:21 -07003120 * @page: page to uncharge
3121 * @order: allocation order
3122 */
Roman Gushchinf4b00ea2020-04-01 21:06:46 -07003123void __memcg_kmem_uncharge_page(struct page *page, int order)
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003124{
Johannes Weiner1306a852014-12-10 15:44:52 -08003125 struct mem_cgroup *memcg = page->mem_cgroup;
Vladimir Davydovf3ccb2c42015-11-05 18:49:01 -08003126 unsigned int nr_pages = 1 << order;
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003127
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003128 if (!memcg)
3129 return;
3130
Sasha Levin309381fea2014-01-23 15:52:54 -08003131 VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
Roman Gushchin4b13f642020-04-01 21:06:56 -07003132 __memcg_kmem_uncharge(memcg, nr_pages);
Johannes Weiner1306a852014-12-10 15:44:52 -08003133 page->mem_cgroup = NULL;
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07003134 css_put(&memcg->css);
Vladimir Davydovc4159a72016-08-08 23:03:12 +03003135
3136 /* slab pages do not have PageKmemcg flag set */
3137 if (PageKmemcg(page))
3138 __ClearPageKmemcg(page);
Vladimir Davydov60d3fd32015-02-12 14:59:10 -08003139}
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003140
3141static bool consume_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3142{
3143 struct memcg_stock_pcp *stock;
3144 unsigned long flags;
3145 bool ret = false;
3146
3147 local_irq_save(flags);
3148
3149 stock = this_cpu_ptr(&memcg_stock);
3150 if (objcg == stock->cached_objcg && stock->nr_bytes >= nr_bytes) {
3151 stock->nr_bytes -= nr_bytes;
3152 ret = true;
3153 }
3154
3155 local_irq_restore(flags);
3156
3157 return ret;
3158}
3159
3160static void drain_obj_stock(struct memcg_stock_pcp *stock)
3161{
3162 struct obj_cgroup *old = stock->cached_objcg;
3163
3164 if (!old)
3165 return;
3166
3167 if (stock->nr_bytes) {
3168 unsigned int nr_pages = stock->nr_bytes >> PAGE_SHIFT;
3169 unsigned int nr_bytes = stock->nr_bytes & (PAGE_SIZE - 1);
3170
3171 if (nr_pages) {
3172 rcu_read_lock();
3173 __memcg_kmem_uncharge(obj_cgroup_memcg(old), nr_pages);
3174 rcu_read_unlock();
3175 }
3176
3177 /*
3178 * The leftover is flushed to the centralized per-memcg value.
3179 * On the next attempt to refill obj stock it will be moved
3180 * to a per-cpu stock (probably, on an other CPU), see
3181 * refill_obj_stock().
3182 *
3183 * How often it's flushed is a trade-off between the memory
3184 * limit enforcement accuracy and potential CPU contention,
3185 * so it might be changed in the future.
3186 */
3187 atomic_add(nr_bytes, &old->nr_charged_bytes);
3188 stock->nr_bytes = 0;
3189 }
3190
3191 obj_cgroup_put(old);
3192 stock->cached_objcg = NULL;
3193}
3194
3195static bool obj_stock_flush_required(struct memcg_stock_pcp *stock,
3196 struct mem_cgroup *root_memcg)
3197{
3198 struct mem_cgroup *memcg;
3199
3200 if (stock->cached_objcg) {
3201 memcg = obj_cgroup_memcg(stock->cached_objcg);
3202 if (memcg && mem_cgroup_is_descendant(memcg, root_memcg))
3203 return true;
3204 }
3205
3206 return false;
3207}
3208
3209static void refill_obj_stock(struct obj_cgroup *objcg, unsigned int nr_bytes)
3210{
3211 struct memcg_stock_pcp *stock;
3212 unsigned long flags;
3213
3214 local_irq_save(flags);
3215
3216 stock = this_cpu_ptr(&memcg_stock);
3217 if (stock->cached_objcg != objcg) { /* reset if necessary */
3218 drain_obj_stock(stock);
3219 obj_cgroup_get(objcg);
3220 stock->cached_objcg = objcg;
3221 stock->nr_bytes = atomic_xchg(&objcg->nr_charged_bytes, 0);
3222 }
3223 stock->nr_bytes += nr_bytes;
3224
3225 if (stock->nr_bytes > PAGE_SIZE)
3226 drain_obj_stock(stock);
3227
3228 local_irq_restore(flags);
3229}
3230
3231int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size)
3232{
3233 struct mem_cgroup *memcg;
3234 unsigned int nr_pages, nr_bytes;
3235 int ret;
3236
3237 if (consume_obj_stock(objcg, size))
3238 return 0;
3239
3240 /*
3241 * In theory, memcg->nr_charged_bytes can have enough
3242 * pre-charged bytes to satisfy the allocation. However,
3243 * flushing memcg->nr_charged_bytes requires two atomic
3244 * operations, and memcg->nr_charged_bytes can't be big,
3245 * so it's better to ignore it and try grab some new pages.
3246 * memcg->nr_charged_bytes will be flushed in
3247 * refill_obj_stock(), called from this function or
3248 * independently later.
3249 */
3250 rcu_read_lock();
3251 memcg = obj_cgroup_memcg(objcg);
3252 css_get(&memcg->css);
3253 rcu_read_unlock();
3254
3255 nr_pages = size >> PAGE_SHIFT;
3256 nr_bytes = size & (PAGE_SIZE - 1);
3257
3258 if (nr_bytes)
3259 nr_pages += 1;
3260
3261 ret = __memcg_kmem_charge(memcg, gfp, nr_pages);
3262 if (!ret && nr_bytes)
3263 refill_obj_stock(objcg, PAGE_SIZE - nr_bytes);
3264
3265 css_put(&memcg->css);
3266 return ret;
3267}
3268
3269void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size)
3270{
3271 refill_obj_stock(objcg, size);
3272}
3273
Kirill Tkhai84c07d12018-08-17 15:47:25 -07003274#endif /* CONFIG_MEMCG_KMEM */
Glauber Costa7ae1e1d2012-12-18 14:21:56 -08003275
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003276#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3277
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003278/*
3279 * Because tail pages are not marked as "used", set it. We're under
Andrey Ryabininf4b7e272019-03-05 15:49:39 -08003280 * pgdat->lru_lock and migration entries setup in all page mappings.
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003281 */
KAMEZAWA Hiroyukie94c8a92012-01-12 17:18:20 -08003282void mem_cgroup_split_huge_fixup(struct page *head)
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003283{
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07003284 struct mem_cgroup *memcg = head->mem_cgroup;
KAMEZAWA Hiroyukie94c8a92012-01-12 17:18:20 -08003285 int i;
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003286
KAMEZAWA Hiroyuki3d37c4a2011-01-25 15:07:28 -08003287 if (mem_cgroup_disabled())
3288 return;
David Rientjesb070e652013-05-07 16:18:09 -07003289
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07003290 for (i = 1; i < HPAGE_PMD_NR; i++) {
3291 css_get(&memcg->css);
3292 head[i].mem_cgroup = memcg;
3293 }
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003294}
Hugh Dickins12d27102012-01-12 17:19:52 -08003295#endif /* CONFIG_TRANSPARENT_HUGEPAGE */
KAMEZAWA Hiroyukica3e0212011-01-20 14:44:24 -08003296
Andrew Mortonc255a452012-07-31 16:43:02 -07003297#ifdef CONFIG_MEMCG_SWAP
Daisuke Nishimura02491442010-03-10 15:22:17 -08003298/**
3299 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
3300 * @entry: swap entry to be moved
3301 * @from: mem_cgroup which the entry is moved from
3302 * @to: mem_cgroup which the entry is moved to
3303 *
3304 * It succeeds only when the swap_cgroup's record for this entry is the same
3305 * as the mem_cgroup's id of @from.
3306 *
3307 * Returns 0 on success, -EINVAL on failure.
3308 *
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003309 * The caller must have charged to @to, IOW, called page_counter_charge() about
Daisuke Nishimura02491442010-03-10 15:22:17 -08003310 * both res and memsw, and called css_get().
3311 */
3312static int mem_cgroup_move_swap_account(swp_entry_t entry,
Hugh Dickinse91cbb42012-05-29 15:06:51 -07003313 struct mem_cgroup *from, struct mem_cgroup *to)
Daisuke Nishimura02491442010-03-10 15:22:17 -08003314{
3315 unsigned short old_id, new_id;
3316
Li Zefan34c00c32013-09-23 16:56:01 +08003317 old_id = mem_cgroup_id(from);
3318 new_id = mem_cgroup_id(to);
Daisuke Nishimura02491442010-03-10 15:22:17 -08003319
3320 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
Johannes Weinerc9019e92018-01-31 16:16:37 -08003321 mod_memcg_state(from, MEMCG_SWAP, -1);
3322 mod_memcg_state(to, MEMCG_SWAP, 1);
Daisuke Nishimura02491442010-03-10 15:22:17 -08003323 return 0;
3324 }
3325 return -EINVAL;
3326}
3327#else
3328static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
Hugh Dickinse91cbb42012-05-29 15:06:51 -07003329 struct mem_cgroup *from, struct mem_cgroup *to)
Daisuke Nishimura02491442010-03-10 15:22:17 -08003330{
3331 return -EINVAL;
3332}
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08003333#endif
3334
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003335static DEFINE_MUTEX(memcg_max_mutex);
Daisuke Nishimuraf212ad72011-03-23 16:42:25 -07003336
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003337static int mem_cgroup_resize_max(struct mem_cgroup *memcg,
3338 unsigned long max, bool memsw)
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003339{
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003340 bool enlarge = false;
Shakeel Buttbb4a7ea2018-06-07 17:07:27 -07003341 bool drained = false;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003342 int ret;
Yu Zhaoc054a782018-01-31 16:20:02 -08003343 bool limits_invariant;
3344 struct page_counter *counter = memsw ? &memcg->memsw : &memcg->memory;
KAMEZAWA Hiroyuki81d39c22009-04-02 16:57:36 -07003345
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003346 do {
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003347 if (signal_pending(current)) {
3348 ret = -EINTR;
3349 break;
3350 }
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003351
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003352 mutex_lock(&memcg_max_mutex);
Yu Zhaoc054a782018-01-31 16:20:02 -08003353 /*
3354 * Make sure that the new limit (memsw or memory limit) doesn't
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003355 * break our basic invariant rule memory.max <= memsw.max.
Yu Zhaoc054a782018-01-31 16:20:02 -08003356 */
Chris Down15b42562020-04-01 21:07:20 -07003357 limits_invariant = memsw ? max >= READ_ONCE(memcg->memory.max) :
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003358 max <= memcg->memsw.max;
Yu Zhaoc054a782018-01-31 16:20:02 -08003359 if (!limits_invariant) {
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003360 mutex_unlock(&memcg_max_mutex);
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08003361 ret = -EINVAL;
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003362 break;
3363 }
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003364 if (max > counter->max)
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003365 enlarge = true;
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003366 ret = page_counter_set_max(counter, max);
3367 mutex_unlock(&memcg_max_mutex);
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08003368
3369 if (!ret)
3370 break;
3371
Shakeel Buttbb4a7ea2018-06-07 17:07:27 -07003372 if (!drained) {
3373 drain_all_stock(memcg);
3374 drained = true;
3375 continue;
3376 }
3377
Andrey Ryabinin1ab5c052018-01-31 16:20:37 -08003378 if (!try_to_free_mem_cgroup_pages(memcg, 1,
3379 GFP_KERNEL, !memsw)) {
3380 ret = -EBUSY;
3381 break;
3382 }
3383 } while (true);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003384
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07003385 if (!ret && enlarge)
3386 memcg_oom_recover(memcg);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003387
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003388 return ret;
3389}
3390
Mel Gormanef8f2322016-07-28 15:46:05 -07003391unsigned long mem_cgroup_soft_limit_reclaim(pg_data_t *pgdat, int order,
Andrew Morton0608f432013-09-24 15:27:41 -07003392 gfp_t gfp_mask,
3393 unsigned long *total_scanned)
3394{
3395 unsigned long nr_reclaimed = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07003396 struct mem_cgroup_per_node *mz, *next_mz = NULL;
Andrew Morton0608f432013-09-24 15:27:41 -07003397 unsigned long reclaimed;
3398 int loop = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07003399 struct mem_cgroup_tree_per_node *mctz;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003400 unsigned long excess;
Andrew Morton0608f432013-09-24 15:27:41 -07003401 unsigned long nr_scanned;
3402
3403 if (order > 0)
3404 return 0;
3405
Mel Gormanef8f2322016-07-28 15:46:05 -07003406 mctz = soft_limit_tree_node(pgdat->node_id);
Michal Hockod6507ff2016-08-02 14:02:37 -07003407
3408 /*
3409 * Do not even bother to check the largest node if the root
3410 * is empty. Do it lockless to prevent lock bouncing. Races
3411 * are acceptable as soft limit is best effort anyway.
3412 */
Laurent Dufourbfc72282017-03-09 16:17:06 -08003413 if (!mctz || RB_EMPTY_ROOT(&mctz->rb_root))
Michal Hockod6507ff2016-08-02 14:02:37 -07003414 return 0;
3415
Andrew Morton0608f432013-09-24 15:27:41 -07003416 /*
3417 * This loop can run a while, specially if mem_cgroup's continuously
3418 * keep exceeding their soft limit and putting the system under
3419 * pressure
3420 */
3421 do {
3422 if (next_mz)
3423 mz = next_mz;
3424 else
3425 mz = mem_cgroup_largest_soft_limit_node(mctz);
3426 if (!mz)
3427 break;
3428
3429 nr_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07003430 reclaimed = mem_cgroup_soft_reclaim(mz->memcg, pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07003431 gfp_mask, &nr_scanned);
3432 nr_reclaimed += reclaimed;
3433 *total_scanned += nr_scanned;
Johannes Weiner0a31bc92014-08-08 14:19:22 -07003434 spin_lock_irq(&mctz->lock);
Vladimir Davydovbc2f2e72014-12-10 15:43:40 -08003435 __mem_cgroup_remove_exceeded(mz, mctz);
Andrew Morton0608f432013-09-24 15:27:41 -07003436
3437 /*
3438 * If we failed to reclaim anything from this memory cgroup
3439 * it is time to move on to the next cgroup
3440 */
3441 next_mz = NULL;
Vladimir Davydovbc2f2e72014-12-10 15:43:40 -08003442 if (!reclaimed)
3443 next_mz = __mem_cgroup_largest_soft_limit_node(mctz);
3444
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003445 excess = soft_limit_excess(mz->memcg);
Andrew Morton0608f432013-09-24 15:27:41 -07003446 /*
3447 * One school of thought says that we should not add
3448 * back the node to the tree if reclaim returns 0.
3449 * But our reclaim could return 0, simply because due
3450 * to priority we are exposing a smaller subset of
3451 * memory to reclaim from. Consider this as a longer
3452 * term TODO.
3453 */
3454 /* If excess == 0, no tree ops */
Johannes Weinercf2c8122014-06-06 14:38:21 -07003455 __mem_cgroup_insert_exceeded(mz, mctz, excess);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07003456 spin_unlock_irq(&mctz->lock);
Andrew Morton0608f432013-09-24 15:27:41 -07003457 css_put(&mz->memcg->css);
3458 loop++;
3459 /*
3460 * Could not reclaim anything and there are no more
3461 * mem cgroups to try or we seem to be looping without
3462 * reclaiming anything.
3463 */
3464 if (!nr_reclaimed &&
3465 (next_mz == NULL ||
3466 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
3467 break;
3468 } while (!nr_reclaimed);
3469 if (next_mz)
3470 css_put(&next_mz->memcg->css);
3471 return nr_reclaimed;
3472}
3473
Tejun Heoea280e72014-05-16 13:22:48 -04003474/*
3475 * Test whether @memcg has children, dead or alive. Note that this
3476 * function doesn't care whether @memcg has use_hierarchy enabled and
3477 * returns %true if there are child csses according to the cgroup
Ethon Paulb8f29352020-06-04 16:49:28 -07003478 * hierarchy. Testing use_hierarchy is the caller's responsibility.
Tejun Heoea280e72014-05-16 13:22:48 -04003479 */
Glauber Costab5f99b52013-02-22 16:34:53 -08003480static inline bool memcg_has_children(struct mem_cgroup *memcg)
3481{
Tejun Heoea280e72014-05-16 13:22:48 -04003482 bool ret;
3483
Tejun Heoea280e72014-05-16 13:22:48 -04003484 rcu_read_lock();
3485 ret = css_next_child(NULL, &memcg->css);
3486 rcu_read_unlock();
3487 return ret;
Glauber Costab5f99b52013-02-22 16:34:53 -08003488}
3489
3490/*
Greg Thelen51038172016-05-20 16:58:18 -07003491 * Reclaims as many pages from the given memcg as possible.
Michal Hockoc26251f2012-10-26 13:37:28 +02003492 *
3493 * Caller is responsible for holding css reference for memcg.
3494 */
3495static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
3496{
3497 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
Michal Hockoc26251f2012-10-26 13:37:28 +02003498
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08003499 /* we call try-to-free pages for make this cgroup empty */
3500 lru_add_drain_all();
Junaid Shahidd12c60f2018-06-07 17:07:31 -07003501
3502 drain_all_stock(memcg);
3503
KAMEZAWA Hiroyukif817ed42009-01-07 18:07:53 -08003504 /* try to free all pages in this cgroup */
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003505 while (nr_retries && page_counter_read(&memcg->memory)) {
KAMEZAWA Hiroyukif817ed42009-01-07 18:07:53 -08003506 int progress;
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08003507
Michal Hockoc26251f2012-10-26 13:37:28 +02003508 if (signal_pending(current))
3509 return -EINTR;
3510
Johannes Weinerb70a2a22014-10-09 15:28:56 -07003511 progress = try_to_free_mem_cgroup_pages(memcg, 1,
3512 GFP_KERNEL, true);
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08003513 if (!progress) {
KAMEZAWA Hiroyukif817ed42009-01-07 18:07:53 -08003514 nr_retries--;
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08003515 /* maybe some writeback is necessary */
Jens Axboe8aa7e842009-07-09 14:52:32 +02003516 congestion_wait(BLK_RW_ASYNC, HZ/10);
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08003517 }
KAMEZAWA Hiroyukif817ed42009-01-07 18:07:53 -08003518
3519 }
Michal Hockoab5196c2012-10-26 13:37:32 +02003520
3521 return 0;
KAMEZAWA Hiroyukicc847582008-02-07 00:14:16 -08003522}
3523
Tejun Heo6770c642014-05-13 12:16:21 -04003524static ssize_t mem_cgroup_force_empty_write(struct kernfs_open_file *of,
3525 char *buf, size_t nbytes,
3526 loff_t off)
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08003527{
Tejun Heo6770c642014-05-13 12:16:21 -04003528 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
Michal Hockoc26251f2012-10-26 13:37:28 +02003529
Michal Hockod8423012012-10-26 13:37:29 +02003530 if (mem_cgroup_is_root(memcg))
3531 return -EINVAL;
Tejun Heo6770c642014-05-13 12:16:21 -04003532 return mem_cgroup_force_empty(memcg) ?: nbytes;
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08003533}
3534
Tejun Heo182446d2013-08-08 20:11:24 -04003535static u64 mem_cgroup_hierarchy_read(struct cgroup_subsys_state *css,
3536 struct cftype *cft)
Balbir Singh18f59ea2009-01-07 18:08:07 -08003537{
Tejun Heo182446d2013-08-08 20:11:24 -04003538 return mem_cgroup_from_css(css)->use_hierarchy;
Balbir Singh18f59ea2009-01-07 18:08:07 -08003539}
3540
Tejun Heo182446d2013-08-08 20:11:24 -04003541static int mem_cgroup_hierarchy_write(struct cgroup_subsys_state *css,
3542 struct cftype *cft, u64 val)
Balbir Singh18f59ea2009-01-07 18:08:07 -08003543{
3544 int retval = 0;
Tejun Heo182446d2013-08-08 20:11:24 -04003545 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Tejun Heo5c9d5352014-05-16 13:22:48 -04003546 struct mem_cgroup *parent_memcg = mem_cgroup_from_css(memcg->css.parent);
Balbir Singh18f59ea2009-01-07 18:08:07 -08003547
Glauber Costa567fb432012-07-31 16:43:07 -07003548 if (memcg->use_hierarchy == val)
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08003549 return 0;
Glauber Costa567fb432012-07-31 16:43:07 -07003550
Balbir Singh18f59ea2009-01-07 18:08:07 -08003551 /*
André Goddard Rosaaf901ca2009-11-14 13:09:05 -02003552 * If parent's use_hierarchy is set, we can't make any modifications
Balbir Singh18f59ea2009-01-07 18:08:07 -08003553 * in the child subtrees. If it is unset, then the change can
3554 * occur, provided the current cgroup has no children.
3555 *
3556 * For the root cgroup, parent_mem is NULL, we allow value to be
3557 * set if there are no children.
3558 */
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07003559 if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
Balbir Singh18f59ea2009-01-07 18:08:07 -08003560 (val == 1 || val == 0)) {
Tejun Heoea280e72014-05-16 13:22:48 -04003561 if (!memcg_has_children(memcg))
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07003562 memcg->use_hierarchy = val;
Balbir Singh18f59ea2009-01-07 18:08:07 -08003563 else
3564 retval = -EBUSY;
3565 } else
3566 retval = -EINVAL;
Glauber Costa567fb432012-07-31 16:43:07 -07003567
Balbir Singh18f59ea2009-01-07 18:08:07 -08003568 return retval;
3569}
3570
Andrew Morton6f646152015-11-06 16:28:58 -08003571static unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
Johannes Weinerce00a962014-09-05 08:43:57 -04003572{
Johannes Weiner42a30032019-05-14 15:47:12 -07003573 unsigned long val;
Johannes Weinerce00a962014-09-05 08:43:57 -04003574
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003575 if (mem_cgroup_is_root(memcg)) {
Johannes Weiner0d1c2072020-06-03 16:01:54 -07003576 val = memcg_page_state(memcg, NR_FILE_PAGES) +
Johannes Weinerbe5d0a72020-06-03 16:01:57 -07003577 memcg_page_state(memcg, NR_ANON_MAPPED);
Johannes Weiner42a30032019-05-14 15:47:12 -07003578 if (swap)
3579 val += memcg_page_state(memcg, MEMCG_SWAP);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003580 } else {
Johannes Weinerce00a962014-09-05 08:43:57 -04003581 if (!swap)
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003582 val = page_counter_read(&memcg->memory);
Johannes Weinerce00a962014-09-05 08:43:57 -04003583 else
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003584 val = page_counter_read(&memcg->memsw);
Johannes Weinerce00a962014-09-05 08:43:57 -04003585 }
Michal Hockoc12176d2015-11-05 18:50:29 -08003586 return val;
Johannes Weinerce00a962014-09-05 08:43:57 -04003587}
3588
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003589enum {
3590 RES_USAGE,
3591 RES_LIMIT,
3592 RES_MAX_USAGE,
3593 RES_FAILCNT,
3594 RES_SOFT_LIMIT,
3595};
Johannes Weinerce00a962014-09-05 08:43:57 -04003596
Tejun Heo791badb2013-12-05 12:28:02 -05003597static u64 mem_cgroup_read_u64(struct cgroup_subsys_state *css,
Johannes Weiner05b84302014-08-06 16:05:59 -07003598 struct cftype *cft)
Balbir Singh8cdea7c2008-02-07 00:13:50 -08003599{
Tejun Heo182446d2013-08-08 20:11:24 -04003600 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003601 struct page_counter *counter;
Tejun Heoaf36f902012-04-01 12:09:55 -07003602
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003603 switch (MEMFILE_TYPE(cft->private)) {
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08003604 case _MEM:
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003605 counter = &memcg->memory;
Glauber Costa510fc4e2012-12-18 14:21:47 -08003606 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003607 case _MEMSWAP:
3608 counter = &memcg->memsw;
3609 break;
3610 case _KMEM:
3611 counter = &memcg->kmem;
3612 break;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003613 case _TCP:
Johannes Weiner0db15292016-01-20 15:02:50 -08003614 counter = &memcg->tcpmem;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003615 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003616 default:
3617 BUG();
3618 }
3619
3620 switch (MEMFILE_ATTR(cft->private)) {
3621 case RES_USAGE:
3622 if (counter == &memcg->memory)
Michal Hockoc12176d2015-11-05 18:50:29 -08003623 return (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003624 if (counter == &memcg->memsw)
Michal Hockoc12176d2015-11-05 18:50:29 -08003625 return (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003626 return (u64)page_counter_read(counter) * PAGE_SIZE;
3627 case RES_LIMIT:
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003628 return (u64)counter->max * PAGE_SIZE;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003629 case RES_MAX_USAGE:
3630 return (u64)counter->watermark * PAGE_SIZE;
3631 case RES_FAILCNT:
3632 return counter->failcnt;
3633 case RES_SOFT_LIMIT:
3634 return (u64)memcg->soft_limit * PAGE_SIZE;
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08003635 default:
3636 BUG();
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08003637 }
Balbir Singh8cdea7c2008-02-07 00:13:50 -08003638}
Glauber Costa510fc4e2012-12-18 14:21:47 -08003639
Roman Gushchin4a87e2a2020-01-13 16:29:16 -08003640static void memcg_flush_percpu_vmstats(struct mem_cgroup *memcg)
Roman Gushchinc350a992019-08-24 17:54:47 -07003641{
Roman Gushchin4a87e2a2020-01-13 16:29:16 -08003642 unsigned long stat[MEMCG_NR_STAT] = {0};
Roman Gushchinc350a992019-08-24 17:54:47 -07003643 struct mem_cgroup *mi;
3644 int node, cpu, i;
Roman Gushchinc350a992019-08-24 17:54:47 -07003645
3646 for_each_online_cpu(cpu)
Roman Gushchin4a87e2a2020-01-13 16:29:16 -08003647 for (i = 0; i < MEMCG_NR_STAT; i++)
Shakeel Butt6c1c2802019-08-30 16:04:53 -07003648 stat[i] += per_cpu(memcg->vmstats_percpu->stat[i], cpu);
Roman Gushchinc350a992019-08-24 17:54:47 -07003649
3650 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
Roman Gushchin4a87e2a2020-01-13 16:29:16 -08003651 for (i = 0; i < MEMCG_NR_STAT; i++)
Roman Gushchinc350a992019-08-24 17:54:47 -07003652 atomic_long_add(stat[i], &mi->vmstats[i]);
3653
3654 for_each_node(node) {
3655 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
3656 struct mem_cgroup_per_node *pi;
3657
Roman Gushchin4a87e2a2020-01-13 16:29:16 -08003658 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
Roman Gushchinc350a992019-08-24 17:54:47 -07003659 stat[i] = 0;
3660
3661 for_each_online_cpu(cpu)
Roman Gushchin4a87e2a2020-01-13 16:29:16 -08003662 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
Shakeel Butt6c1c2802019-08-30 16:04:53 -07003663 stat[i] += per_cpu(
3664 pn->lruvec_stat_cpu->count[i], cpu);
Roman Gushchinc350a992019-08-24 17:54:47 -07003665
3666 for (pi = pn; pi; pi = parent_nodeinfo(pi, node))
Roman Gushchin4a87e2a2020-01-13 16:29:16 -08003667 for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
Roman Gushchinc350a992019-08-24 17:54:47 -07003668 atomic_long_add(stat[i], &pi->lruvec_stat[i]);
3669 }
3670}
3671
Roman Gushchinbb65f892019-08-24 17:54:50 -07003672static void memcg_flush_percpu_vmevents(struct mem_cgroup *memcg)
3673{
3674 unsigned long events[NR_VM_EVENT_ITEMS];
3675 struct mem_cgroup *mi;
3676 int cpu, i;
3677
3678 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3679 events[i] = 0;
3680
3681 for_each_online_cpu(cpu)
3682 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
Shakeel Butt6c1c2802019-08-30 16:04:53 -07003683 events[i] += per_cpu(memcg->vmstats_percpu->events[i],
3684 cpu);
Roman Gushchinbb65f892019-08-24 17:54:50 -07003685
3686 for (mi = memcg; mi; mi = parent_mem_cgroup(mi))
3687 for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
3688 atomic_long_add(events[i], &mi->vmevents[i]);
3689}
3690
Kirill Tkhai84c07d12018-08-17 15:47:25 -07003691#ifdef CONFIG_MEMCG_KMEM
Johannes Weiner567e9ab2016-01-20 15:02:24 -08003692static int memcg_online_kmem(struct mem_cgroup *memcg)
Vladimir Davydovd6441632014-01-23 15:53:09 -08003693{
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003694 struct obj_cgroup *objcg;
Vladimir Davydovd6441632014-01-23 15:53:09 -08003695 int memcg_id;
3696
Vladimir Davydovb313aee2016-03-17 14:18:27 -07003697 if (cgroup_memory_nokmem)
3698 return 0;
3699
Vladimir Davydov2a4db7e2015-02-12 14:59:32 -08003700 BUG_ON(memcg->kmemcg_id >= 0);
Johannes Weiner567e9ab2016-01-20 15:02:24 -08003701 BUG_ON(memcg->kmem_state);
Vladimir Davydovd6441632014-01-23 15:53:09 -08003702
Vladimir Davydovf3bb3042014-10-09 15:28:45 -07003703 memcg_id = memcg_alloc_cache_id();
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08003704 if (memcg_id < 0)
3705 return memcg_id;
Vladimir Davydovd6441632014-01-23 15:53:09 -08003706
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003707 objcg = obj_cgroup_alloc();
3708 if (!objcg) {
3709 memcg_free_cache_id(memcg_id);
3710 return -ENOMEM;
3711 }
3712 objcg->memcg = memcg;
3713 rcu_assign_pointer(memcg->objcg, objcg);
3714
Roman Gushchind648bcc2020-08-06 23:20:28 -07003715 static_branch_enable(&memcg_kmem_enabled_key);
3716
Vladimir Davydovd6441632014-01-23 15:53:09 -08003717 /*
Johannes Weiner567e9ab2016-01-20 15:02:24 -08003718 * A memory cgroup is considered kmem-online as soon as it gets
Vladimir Davydov900a38f2014-12-12 16:55:10 -08003719 * kmemcg_id. Setting the id after enabling static branching will
Vladimir Davydovd6441632014-01-23 15:53:09 -08003720 * guarantee no one starts accounting before all call sites are
3721 * patched.
3722 */
Vladimir Davydov900a38f2014-12-12 16:55:10 -08003723 memcg->kmemcg_id = memcg_id;
Johannes Weiner567e9ab2016-01-20 15:02:24 -08003724 memcg->kmem_state = KMEM_ONLINE;
Tejun Heobc2791f2017-02-22 15:41:21 -08003725 INIT_LIST_HEAD(&memcg->kmem_caches);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08003726
3727 return 0;
Vladimir Davydovd6441632014-01-23 15:53:09 -08003728}
3729
Johannes Weiner8e0a8912016-01-20 15:02:26 -08003730static void memcg_offline_kmem(struct mem_cgroup *memcg)
3731{
3732 struct cgroup_subsys_state *css;
3733 struct mem_cgroup *parent, *child;
3734 int kmemcg_id;
3735
3736 if (memcg->kmem_state != KMEM_ONLINE)
3737 return;
3738 /*
3739 * Clear the online state before clearing memcg_caches array
3740 * entries. The slab_mutex in memcg_deactivate_kmem_caches()
3741 * guarantees that no cache will be created for this cgroup
3742 * after we are done (see memcg_create_kmem_cache()).
3743 */
3744 memcg->kmem_state = KMEM_ALLOCATED;
3745
Johannes Weiner8e0a8912016-01-20 15:02:26 -08003746 parent = parent_mem_cgroup(memcg);
3747 if (!parent)
3748 parent = root_mem_cgroup;
3749
Roman Gushchinbee07b32019-08-30 16:04:32 -07003750 /*
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003751 * Deactivate and reparent kmem_caches and objcgs.
Roman Gushchinbee07b32019-08-30 16:04:32 -07003752 */
Roman Gushchinfb2f2b02019-07-11 20:56:34 -07003753 memcg_deactivate_kmem_caches(memcg, parent);
Roman Gushchinbf4f0592020-08-06 23:20:49 -07003754 memcg_reparent_objcgs(memcg, parent);
Roman Gushchinfb2f2b02019-07-11 20:56:34 -07003755
3756 kmemcg_id = memcg->kmemcg_id;
3757 BUG_ON(kmemcg_id < 0);
3758
Johannes Weiner8e0a8912016-01-20 15:02:26 -08003759 /*
3760 * Change kmemcg_id of this cgroup and all its descendants to the
3761 * parent's id, and then move all entries from this cgroup's list_lrus
3762 * to ones of the parent. After we have finished, all list_lrus
3763 * corresponding to this cgroup are guaranteed to remain empty. The
3764 * ordering is imposed by list_lru_node->lock taken by
3765 * memcg_drain_all_list_lrus().
3766 */
Tejun Heo3a06bb72016-06-03 14:55:44 -07003767 rcu_read_lock(); /* can be called from css_free w/o cgroup_mutex */
Johannes Weiner8e0a8912016-01-20 15:02:26 -08003768 css_for_each_descendant_pre(css, &memcg->css) {
3769 child = mem_cgroup_from_css(css);
3770 BUG_ON(child->kmemcg_id != kmemcg_id);
3771 child->kmemcg_id = parent->kmemcg_id;
3772 if (!memcg->use_hierarchy)
3773 break;
3774 }
Tejun Heo3a06bb72016-06-03 14:55:44 -07003775 rcu_read_unlock();
3776
Kirill Tkhai9bec5c32018-08-17 15:47:58 -07003777 memcg_drain_all_list_lrus(kmemcg_id, parent);
Johannes Weiner8e0a8912016-01-20 15:02:26 -08003778
3779 memcg_free_cache_id(kmemcg_id);
3780}
3781
3782static void memcg_free_kmem(struct mem_cgroup *memcg)
3783{
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08003784 /* css_alloc() failed, offlining didn't happen */
3785 if (unlikely(memcg->kmem_state == KMEM_ONLINE))
3786 memcg_offline_kmem(memcg);
Johannes Weiner8e0a8912016-01-20 15:02:26 -08003787}
Vladimir Davydovd6441632014-01-23 15:53:09 -08003788#else
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08003789static int memcg_online_kmem(struct mem_cgroup *memcg)
Johannes Weiner127424c2016-01-20 15:02:32 -08003790{
3791 return 0;
3792}
3793static void memcg_offline_kmem(struct mem_cgroup *memcg)
3794{
3795}
3796static void memcg_free_kmem(struct mem_cgroup *memcg)
3797{
3798}
Kirill Tkhai84c07d12018-08-17 15:47:25 -07003799#endif /* CONFIG_MEMCG_KMEM */
Johannes Weiner127424c2016-01-20 15:02:32 -08003800
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003801static int memcg_update_kmem_max(struct mem_cgroup *memcg,
3802 unsigned long max)
Johannes Weiner127424c2016-01-20 15:02:32 -08003803{
Vladimir Davydovb313aee2016-03-17 14:18:27 -07003804 int ret;
Johannes Weiner127424c2016-01-20 15:02:32 -08003805
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003806 mutex_lock(&memcg_max_mutex);
3807 ret = page_counter_set_max(&memcg->kmem, max);
3808 mutex_unlock(&memcg_max_mutex);
Johannes Weiner127424c2016-01-20 15:02:32 -08003809 return ret;
3810}
Glauber Costa510fc4e2012-12-18 14:21:47 -08003811
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003812static int memcg_update_tcp_max(struct mem_cgroup *memcg, unsigned long max)
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003813{
3814 int ret;
3815
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003816 mutex_lock(&memcg_max_mutex);
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003817
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003818 ret = page_counter_set_max(&memcg->tcpmem, max);
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003819 if (ret)
3820 goto out;
3821
Johannes Weiner0db15292016-01-20 15:02:50 -08003822 if (!memcg->tcpmem_active) {
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003823 /*
3824 * The active flag needs to be written after the static_key
3825 * update. This is what guarantees that the socket activation
Johannes Weiner2d758072016-10-07 17:00:58 -07003826 * function is the last one to run. See mem_cgroup_sk_alloc()
3827 * for details, and note that we don't mark any socket as
3828 * belonging to this memcg until that flag is up.
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003829 *
3830 * We need to do this, because static_keys will span multiple
3831 * sites, but we can't control their order. If we mark a socket
3832 * as accounted, but the accounting functions are not patched in
3833 * yet, we'll lose accounting.
3834 *
Johannes Weiner2d758072016-10-07 17:00:58 -07003835 * We never race with the readers in mem_cgroup_sk_alloc(),
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003836 * because when this value change, the code to process it is not
3837 * patched in yet.
3838 */
3839 static_branch_inc(&memcg_sockets_enabled_key);
Johannes Weiner0db15292016-01-20 15:02:50 -08003840 memcg->tcpmem_active = true;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003841 }
3842out:
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003843 mutex_unlock(&memcg_max_mutex);
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003844 return ret;
3845}
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003846
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003847/*
3848 * The user of this function is...
3849 * RES_LIMIT.
3850 */
Tejun Heo451af502014-05-13 12:16:21 -04003851static ssize_t mem_cgroup_write(struct kernfs_open_file *of,
3852 char *buf, size_t nbytes, loff_t off)
Balbir Singh8cdea7c2008-02-07 00:13:50 -08003853{
Tejun Heo451af502014-05-13 12:16:21 -04003854 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003855 unsigned long nr_pages;
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003856 int ret;
3857
Tejun Heo451af502014-05-13 12:16:21 -04003858 buf = strstrip(buf);
Johannes Weiner650c5e52015-02-11 15:26:03 -08003859 ret = page_counter_memparse(buf, "-1", &nr_pages);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003860 if (ret)
3861 return ret;
Tejun Heoaf36f902012-04-01 12:09:55 -07003862
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003863 switch (MEMFILE_ATTR(of_cft(of)->private)) {
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003864 case RES_LIMIT:
Balbir Singh4b3bde42009-09-23 15:56:32 -07003865 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
3866 ret = -EINVAL;
3867 break;
3868 }
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003869 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3870 case _MEM:
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003871 ret = mem_cgroup_resize_max(memcg, nr_pages, false);
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08003872 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003873 case _MEMSWAP:
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003874 ret = mem_cgroup_resize_max(memcg, nr_pages, true);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003875 break;
3876 case _KMEM:
Michal Hocko01581152019-09-23 15:37:22 -07003877 pr_warn_once("kmem.limit_in_bytes is deprecated and will be removed. "
3878 "Please report your usecase to linux-mm@kvack.org if you "
3879 "depend on this functionality.\n");
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003880 ret = memcg_update_kmem_max(memcg, nr_pages);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003881 break;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003882 case _TCP:
Roman Gushchinbbec2e12018-06-07 17:06:18 -07003883 ret = memcg_update_tcp_max(memcg, nr_pages);
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003884 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003885 }
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003886 break;
Balbir Singh296c81d2009-09-23 15:56:36 -07003887 case RES_SOFT_LIMIT:
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003888 memcg->soft_limit = nr_pages;
3889 ret = 0;
KAMEZAWA Hiroyuki628f4232008-07-25 01:47:20 -07003890 break;
3891 }
Tejun Heo451af502014-05-13 12:16:21 -04003892 return ret ?: nbytes;
Balbir Singh8cdea7c2008-02-07 00:13:50 -08003893}
3894
Tejun Heo6770c642014-05-13 12:16:21 -04003895static ssize_t mem_cgroup_reset(struct kernfs_open_file *of, char *buf,
3896 size_t nbytes, loff_t off)
Pavel Emelyanovc84872e2008-04-29 01:00:17 -07003897{
Tejun Heo6770c642014-05-13 12:16:21 -04003898 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003899 struct page_counter *counter;
Pavel Emelyanovc84872e2008-04-29 01:00:17 -07003900
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003901 switch (MEMFILE_TYPE(of_cft(of)->private)) {
3902 case _MEM:
3903 counter = &memcg->memory;
3904 break;
3905 case _MEMSWAP:
3906 counter = &memcg->memsw;
3907 break;
3908 case _KMEM:
3909 counter = &memcg->kmem;
3910 break;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003911 case _TCP:
Johannes Weiner0db15292016-01-20 15:02:50 -08003912 counter = &memcg->tcpmem;
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08003913 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003914 default:
3915 BUG();
3916 }
Tejun Heoaf36f902012-04-01 12:09:55 -07003917
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003918 switch (MEMFILE_ATTR(of_cft(of)->private)) {
Pavel Emelyanov29f2a4d2008-04-29 01:00:21 -07003919 case RES_MAX_USAGE:
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003920 page_counter_reset_watermark(counter);
Pavel Emelyanov29f2a4d2008-04-29 01:00:21 -07003921 break;
3922 case RES_FAILCNT:
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003923 counter->failcnt = 0;
Pavel Emelyanov29f2a4d2008-04-29 01:00:21 -07003924 break;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08003925 default:
3926 BUG();
Pavel Emelyanov29f2a4d2008-04-29 01:00:21 -07003927 }
Balbir Singhf64c3f52009-09-23 15:56:37 -07003928
Tejun Heo6770c642014-05-13 12:16:21 -04003929 return nbytes;
Pavel Emelyanovc84872e2008-04-29 01:00:17 -07003930}
3931
Tejun Heo182446d2013-08-08 20:11:24 -04003932static u64 mem_cgroup_move_charge_read(struct cgroup_subsys_state *css,
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08003933 struct cftype *cft)
3934{
Tejun Heo182446d2013-08-08 20:11:24 -04003935 return mem_cgroup_from_css(css)->move_charge_at_immigrate;
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08003936}
3937
Daisuke Nishimura02491442010-03-10 15:22:17 -08003938#ifdef CONFIG_MMU
Tejun Heo182446d2013-08-08 20:11:24 -04003939static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08003940 struct cftype *cft, u64 val)
3941{
Tejun Heo182446d2013-08-08 20:11:24 -04003942 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08003943
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08003944 if (val & ~MOVE_MASK)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08003945 return -EINVAL;
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08003946
Glauber Costaee5e8472013-02-22 16:34:50 -08003947 /*
3948 * No kind of locking is needed in here, because ->can_attach() will
3949 * check this value once in the beginning of the process, and then carry
3950 * on with stale data. This means that changes to this value will only
3951 * affect task migrations starting after the change.
3952 */
3953 memcg->move_charge_at_immigrate = val;
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08003954 return 0;
3955}
Daisuke Nishimura02491442010-03-10 15:22:17 -08003956#else
Tejun Heo182446d2013-08-08 20:11:24 -04003957static int mem_cgroup_move_charge_write(struct cgroup_subsys_state *css,
Daisuke Nishimura02491442010-03-10 15:22:17 -08003958 struct cftype *cft, u64 val)
3959{
3960 return -ENOSYS;
3961}
3962#endif
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08003963
Ying Han406eb0c2011-05-26 16:25:37 -07003964#ifdef CONFIG_NUMA
Johannes Weiner113b7df2019-05-13 17:18:11 -07003965
3966#define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
3967#define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
3968#define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
3969
3970static unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
Shakeel Buttdd8657b2020-06-03 15:56:24 -07003971 int nid, unsigned int lru_mask, bool tree)
Johannes Weiner113b7df2019-05-13 17:18:11 -07003972{
Johannes Weiner867e5e12019-11-30 17:55:34 -08003973 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
Johannes Weiner113b7df2019-05-13 17:18:11 -07003974 unsigned long nr = 0;
3975 enum lru_list lru;
3976
3977 VM_BUG_ON((unsigned)nid >= nr_node_ids);
3978
3979 for_each_lru(lru) {
3980 if (!(BIT(lru) & lru_mask))
3981 continue;
Shakeel Buttdd8657b2020-06-03 15:56:24 -07003982 if (tree)
3983 nr += lruvec_page_state(lruvec, NR_LRU_BASE + lru);
3984 else
3985 nr += lruvec_page_state_local(lruvec, NR_LRU_BASE + lru);
Johannes Weiner113b7df2019-05-13 17:18:11 -07003986 }
3987 return nr;
3988}
3989
3990static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
Shakeel Buttdd8657b2020-06-03 15:56:24 -07003991 unsigned int lru_mask,
3992 bool tree)
Johannes Weiner113b7df2019-05-13 17:18:11 -07003993{
3994 unsigned long nr = 0;
3995 enum lru_list lru;
3996
3997 for_each_lru(lru) {
3998 if (!(BIT(lru) & lru_mask))
3999 continue;
Shakeel Buttdd8657b2020-06-03 15:56:24 -07004000 if (tree)
4001 nr += memcg_page_state(memcg, NR_LRU_BASE + lru);
4002 else
4003 nr += memcg_page_state_local(memcg, NR_LRU_BASE + lru);
Johannes Weiner113b7df2019-05-13 17:18:11 -07004004 }
4005 return nr;
4006}
4007
Tejun Heo2da8ca82013-12-05 12:28:04 -05004008static int memcg_numa_stat_show(struct seq_file *m, void *v)
Ying Han406eb0c2011-05-26 16:25:37 -07004009{
Greg Thelen25485de2013-11-12 15:07:40 -08004010 struct numa_stat {
4011 const char *name;
4012 unsigned int lru_mask;
4013 };
4014
4015 static const struct numa_stat stats[] = {
4016 { "total", LRU_ALL },
4017 { "file", LRU_ALL_FILE },
4018 { "anon", LRU_ALL_ANON },
4019 { "unevictable", BIT(LRU_UNEVICTABLE) },
4020 };
4021 const struct numa_stat *stat;
Ying Han406eb0c2011-05-26 16:25:37 -07004022 int nid;
Chris Downaa9694b2019-03-05 15:45:52 -08004023 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
Ying Han406eb0c2011-05-26 16:25:37 -07004024
Greg Thelen25485de2013-11-12 15:07:40 -08004025 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
Shakeel Buttdd8657b2020-06-03 15:56:24 -07004026 seq_printf(m, "%s=%lu", stat->name,
4027 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4028 false));
4029 for_each_node_state(nid, N_MEMORY)
4030 seq_printf(m, " N%d=%lu", nid,
4031 mem_cgroup_node_nr_lru_pages(memcg, nid,
4032 stat->lru_mask, false));
Greg Thelen25485de2013-11-12 15:07:40 -08004033 seq_putc(m, '\n');
Ying Han406eb0c2011-05-26 16:25:37 -07004034 }
Ying Han406eb0c2011-05-26 16:25:37 -07004035
Ying Han071aee12013-11-12 15:07:41 -08004036 for (stat = stats; stat < stats + ARRAY_SIZE(stats); stat++) {
Ying Han406eb0c2011-05-26 16:25:37 -07004037
Shakeel Buttdd8657b2020-06-03 15:56:24 -07004038 seq_printf(m, "hierarchical_%s=%lu", stat->name,
4039 mem_cgroup_nr_lru_pages(memcg, stat->lru_mask,
4040 true));
4041 for_each_node_state(nid, N_MEMORY)
4042 seq_printf(m, " N%d=%lu", nid,
4043 mem_cgroup_node_nr_lru_pages(memcg, nid,
4044 stat->lru_mask, true));
Ying Han071aee12013-11-12 15:07:41 -08004045 seq_putc(m, '\n');
Ying Han406eb0c2011-05-26 16:25:37 -07004046 }
Ying Han406eb0c2011-05-26 16:25:37 -07004047
Ying Han406eb0c2011-05-26 16:25:37 -07004048 return 0;
4049}
4050#endif /* CONFIG_NUMA */
4051
Johannes Weinerc8713d02019-07-11 20:55:59 -07004052static const unsigned int memcg1_stats[] = {
Johannes Weiner0d1c2072020-06-03 16:01:54 -07004053 NR_FILE_PAGES,
Johannes Weinerbe5d0a72020-06-03 16:01:57 -07004054 NR_ANON_MAPPED,
Johannes Weiner468c3982020-06-03 16:02:01 -07004055#ifdef CONFIG_TRANSPARENT_HUGEPAGE
4056 NR_ANON_THPS,
4057#endif
Johannes Weinerc8713d02019-07-11 20:55:59 -07004058 NR_SHMEM,
4059 NR_FILE_MAPPED,
4060 NR_FILE_DIRTY,
4061 NR_WRITEBACK,
4062 MEMCG_SWAP,
4063};
4064
4065static const char *const memcg1_stat_names[] = {
4066 "cache",
4067 "rss",
Johannes Weiner468c3982020-06-03 16:02:01 -07004068#ifdef CONFIG_TRANSPARENT_HUGEPAGE
Johannes Weinerc8713d02019-07-11 20:55:59 -07004069 "rss_huge",
Johannes Weiner468c3982020-06-03 16:02:01 -07004070#endif
Johannes Weinerc8713d02019-07-11 20:55:59 -07004071 "shmem",
4072 "mapped_file",
4073 "dirty",
4074 "writeback",
4075 "swap",
4076};
4077
Johannes Weinerdf0e53d2017-05-03 14:55:10 -07004078/* Universal VM events cgroup1 shows, original sort order */
Greg Thelen8dd53fd2018-06-07 17:07:23 -07004079static const unsigned int memcg1_events[] = {
Johannes Weinerdf0e53d2017-05-03 14:55:10 -07004080 PGPGIN,
4081 PGPGOUT,
4082 PGFAULT,
4083 PGMAJFAULT,
4084};
4085
Tejun Heo2da8ca82013-12-05 12:28:04 -05004086static int memcg_stat_show(struct seq_file *m, void *v)
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -08004087{
Chris Downaa9694b2019-03-05 15:45:52 -08004088 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004089 unsigned long memory, memsw;
Johannes Weineraf7c4b02012-05-29 15:07:08 -07004090 struct mem_cgroup *mi;
4091 unsigned int i;
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -08004092
Johannes Weiner71cd3112017-05-03 14:55:13 -07004093 BUILD_BUG_ON(ARRAY_SIZE(memcg1_stat_names) != ARRAY_SIZE(memcg1_stats));
Rickard Strandqvist70bc0682014-12-12 16:56:41 -08004094
Johannes Weiner71cd3112017-05-03 14:55:13 -07004095 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
Johannes Weiner468c3982020-06-03 16:02:01 -07004096 unsigned long nr;
4097
Johannes Weiner71cd3112017-05-03 14:55:13 -07004098 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
Daisuke Nishimura1dd3a272009-09-23 15:56:43 -07004099 continue;
Johannes Weiner468c3982020-06-03 16:02:01 -07004100 nr = memcg_page_state_local(memcg, memcg1_stats[i]);
4101#ifdef CONFIG_TRANSPARENT_HUGEPAGE
4102 if (memcg1_stats[i] == NR_ANON_THPS)
4103 nr *= HPAGE_PMD_NR;
4104#endif
4105 seq_printf(m, "%s %lu\n", memcg1_stat_names[i], nr * PAGE_SIZE);
Daisuke Nishimura1dd3a272009-09-23 15:56:43 -07004106 }
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08004107
Johannes Weinerdf0e53d2017-05-03 14:55:10 -07004108 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
Konstantin Khlebnikovebc5d83d2019-12-04 16:49:53 -08004109 seq_printf(m, "%s %lu\n", vm_event_name(memcg1_events[i]),
Johannes Weiner205b20c2019-05-14 15:47:06 -07004110 memcg_events_local(memcg, memcg1_events[i]));
Johannes Weineraf7c4b02012-05-29 15:07:08 -07004111
4112 for (i = 0; i < NR_LRU_LISTS; i++)
Konstantin Khlebnikovebc5d83d2019-12-04 16:49:53 -08004113 seq_printf(m, "%s %lu\n", lru_list_name(i),
Johannes Weiner205b20c2019-05-14 15:47:06 -07004114 memcg_page_state_local(memcg, NR_LRU_BASE + i) *
Johannes Weiner21d89d12019-05-13 17:18:08 -07004115 PAGE_SIZE);
Johannes Weineraf7c4b02012-05-29 15:07:08 -07004116
KAMEZAWA Hiroyuki14067bb2009-04-02 16:57:35 -07004117 /* Hierarchical information */
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004118 memory = memsw = PAGE_COUNTER_MAX;
4119 for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
Chris Down15b42562020-04-01 21:07:20 -07004120 memory = min(memory, READ_ONCE(mi->memory.max));
4121 memsw = min(memsw, READ_ONCE(mi->memsw.max));
KAMEZAWA Hiroyukifee7b542009-01-07 18:08:26 -08004122 }
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004123 seq_printf(m, "hierarchical_memory_limit %llu\n",
4124 (u64)memory * PAGE_SIZE);
Johannes Weiner7941d212016-01-14 15:21:23 -08004125 if (do_memsw_account())
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004126 seq_printf(m, "hierarchical_memsw_limit %llu\n",
4127 (u64)memsw * PAGE_SIZE);
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08004128
Shakeel Butt8de7ecc62018-08-21 21:53:17 -07004129 for (i = 0; i < ARRAY_SIZE(memcg1_stats); i++) {
Johannes Weiner71cd3112017-05-03 14:55:13 -07004130 if (memcg1_stats[i] == MEMCG_SWAP && !do_memsw_account())
Daisuke Nishimura1dd3a272009-09-23 15:56:43 -07004131 continue;
Shakeel Butt8de7ecc62018-08-21 21:53:17 -07004132 seq_printf(m, "total_%s %llu\n", memcg1_stat_names[i],
Yafang Shaodd923992019-07-11 20:52:11 -07004133 (u64)memcg_page_state(memcg, memcg1_stats[i]) *
4134 PAGE_SIZE);
Johannes Weineraf7c4b02012-05-29 15:07:08 -07004135 }
4136
Shakeel Butt8de7ecc62018-08-21 21:53:17 -07004137 for (i = 0; i < ARRAY_SIZE(memcg1_events); i++)
Konstantin Khlebnikovebc5d83d2019-12-04 16:49:53 -08004138 seq_printf(m, "total_%s %llu\n",
4139 vm_event_name(memcg1_events[i]),
Yafang Shaodd923992019-07-11 20:52:11 -07004140 (u64)memcg_events(memcg, memcg1_events[i]));
Johannes Weineraf7c4b02012-05-29 15:07:08 -07004141
Shakeel Butt8de7ecc62018-08-21 21:53:17 -07004142 for (i = 0; i < NR_LRU_LISTS; i++)
Konstantin Khlebnikovebc5d83d2019-12-04 16:49:53 -08004143 seq_printf(m, "total_%s %llu\n", lru_list_name(i),
Johannes Weiner42a30032019-05-14 15:47:12 -07004144 (u64)memcg_page_state(memcg, NR_LRU_BASE + i) *
4145 PAGE_SIZE);
KAMEZAWA Hiroyuki14067bb2009-04-02 16:57:35 -07004146
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08004147#ifdef CONFIG_DEBUG_VM
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08004148 {
Mel Gormanef8f2322016-07-28 15:46:05 -07004149 pg_data_t *pgdat;
4150 struct mem_cgroup_per_node *mz;
Johannes Weiner1431d4d2020-06-03 16:02:53 -07004151 unsigned long anon_cost = 0;
4152 unsigned long file_cost = 0;
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08004153
Mel Gormanef8f2322016-07-28 15:46:05 -07004154 for_each_online_pgdat(pgdat) {
4155 mz = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08004156
Johannes Weiner1431d4d2020-06-03 16:02:53 -07004157 anon_cost += mz->lruvec.anon_cost;
4158 file_cost += mz->lruvec.file_cost;
Mel Gormanef8f2322016-07-28 15:46:05 -07004159 }
Johannes Weiner1431d4d2020-06-03 16:02:53 -07004160 seq_printf(m, "anon_cost %lu\n", anon_cost);
4161 seq_printf(m, "file_cost %lu\n", file_cost);
KOSAKI Motohiro7f016ee2009-01-07 18:08:22 -08004162 }
4163#endif
4164
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -08004165 return 0;
4166}
4167
Tejun Heo182446d2013-08-08 20:11:24 -04004168static u64 mem_cgroup_swappiness_read(struct cgroup_subsys_state *css,
4169 struct cftype *cft)
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08004170{
Tejun Heo182446d2013-08-08 20:11:24 -04004171 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08004172
KAMEZAWA Hiroyuki1f4c0252011-07-26 16:08:21 -07004173 return mem_cgroup_swappiness(memcg);
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08004174}
4175
Tejun Heo182446d2013-08-08 20:11:24 -04004176static int mem_cgroup_swappiness_write(struct cgroup_subsys_state *css,
4177 struct cftype *cft, u64 val)
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08004178{
Tejun Heo182446d2013-08-08 20:11:24 -04004179 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Li Zefan068b38c2009-01-15 13:51:26 -08004180
Johannes Weiner3dae7fe2014-06-04 16:07:01 -07004181 if (val > 100)
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08004182 return -EINVAL;
4183
Linus Torvalds14208b02014-06-09 15:03:33 -07004184 if (css->parent)
Johannes Weiner3dae7fe2014-06-04 16:07:01 -07004185 memcg->swappiness = val;
4186 else
4187 vm_swappiness = val;
Li Zefan068b38c2009-01-15 13:51:26 -08004188
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08004189 return 0;
4190}
4191
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004192static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
4193{
4194 struct mem_cgroup_threshold_ary *t;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004195 unsigned long usage;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004196 int i;
4197
4198 rcu_read_lock();
4199 if (!swap)
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004200 t = rcu_dereference(memcg->thresholds.primary);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004201 else
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004202 t = rcu_dereference(memcg->memsw_thresholds.primary);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004203
4204 if (!t)
4205 goto unlock;
4206
Johannes Weinerce00a962014-09-05 08:43:57 -04004207 usage = mem_cgroup_usage(memcg, swap);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004208
4209 /*
Sha Zhengju748dad32012-05-29 15:06:57 -07004210 * current_threshold points to threshold just below or equal to usage.
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004211 * If it's not true, a threshold was crossed after last
4212 * call of __mem_cgroup_threshold().
4213 */
Phil Carmody5407a562010-05-26 14:42:42 -07004214 i = t->current_threshold;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004215
4216 /*
4217 * Iterate backward over array of thresholds starting from
4218 * current_threshold and check if a threshold is crossed.
4219 * If none of thresholds below usage is crossed, we read
4220 * only one element of the array here.
4221 */
4222 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
4223 eventfd_signal(t->entries[i].eventfd, 1);
4224
4225 /* i = current_threshold + 1 */
4226 i++;
4227
4228 /*
4229 * Iterate forward over array of thresholds starting from
4230 * current_threshold+1 and check if a threshold is crossed.
4231 * If none of thresholds above usage is crossed, we read
4232 * only one element of the array here.
4233 */
4234 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
4235 eventfd_signal(t->entries[i].eventfd, 1);
4236
4237 /* Update current_threshold */
Phil Carmody5407a562010-05-26 14:42:42 -07004238 t->current_threshold = i - 1;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004239unlock:
4240 rcu_read_unlock();
4241}
4242
4243static void mem_cgroup_threshold(struct mem_cgroup *memcg)
4244{
Kirill A. Shutemovad4ca5f2010-10-07 12:59:27 -07004245 while (memcg) {
4246 __mem_cgroup_threshold(memcg, false);
Johannes Weiner7941d212016-01-14 15:21:23 -08004247 if (do_memsw_account())
Kirill A. Shutemovad4ca5f2010-10-07 12:59:27 -07004248 __mem_cgroup_threshold(memcg, true);
4249
4250 memcg = parent_mem_cgroup(memcg);
4251 }
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004252}
4253
4254static int compare_thresholds(const void *a, const void *b)
4255{
4256 const struct mem_cgroup_threshold *_a = a;
4257 const struct mem_cgroup_threshold *_b = b;
4258
Greg Thelen2bff24a2013-09-11 14:23:08 -07004259 if (_a->threshold > _b->threshold)
4260 return 1;
4261
4262 if (_a->threshold < _b->threshold)
4263 return -1;
4264
4265 return 0;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004266}
4267
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004268static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004269{
4270 struct mem_cgroup_eventfd_list *ev;
4271
Michal Hocko2bcf2e92014-07-30 16:08:33 -07004272 spin_lock(&memcg_oom_lock);
4273
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004274 list_for_each_entry(ev, &memcg->oom_notify, list)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004275 eventfd_signal(ev->eventfd, 1);
Michal Hocko2bcf2e92014-07-30 16:08:33 -07004276
4277 spin_unlock(&memcg_oom_lock);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004278 return 0;
4279}
4280
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004281static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004282{
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07004283 struct mem_cgroup *iter;
4284
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004285 for_each_mem_cgroup_tree(iter, memcg)
KAMEZAWA Hiroyuki7d74b062010-10-27 15:33:41 -07004286 mem_cgroup_oom_notify_cb(iter);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004287}
4288
Tejun Heo59b6f872013-11-22 18:20:43 -05004289static int __mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004290 struct eventfd_ctx *eventfd, const char *args, enum res_type type)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004291{
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004292 struct mem_cgroup_thresholds *thresholds;
4293 struct mem_cgroup_threshold_ary *new;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004294 unsigned long threshold;
4295 unsigned long usage;
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004296 int i, size, ret;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004297
Johannes Weiner650c5e52015-02-11 15:26:03 -08004298 ret = page_counter_memparse(args, "-1", &threshold);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004299 if (ret)
4300 return ret;
4301
4302 mutex_lock(&memcg->thresholds_lock);
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004303
Johannes Weiner05b84302014-08-06 16:05:59 -07004304 if (type == _MEM) {
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004305 thresholds = &memcg->thresholds;
Johannes Weinerce00a962014-09-05 08:43:57 -04004306 usage = mem_cgroup_usage(memcg, false);
Johannes Weiner05b84302014-08-06 16:05:59 -07004307 } else if (type == _MEMSWAP) {
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004308 thresholds = &memcg->memsw_thresholds;
Johannes Weinerce00a962014-09-05 08:43:57 -04004309 usage = mem_cgroup_usage(memcg, true);
Johannes Weiner05b84302014-08-06 16:05:59 -07004310 } else
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004311 BUG();
4312
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004313 /* Check if a threshold crossed before adding a new one */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004314 if (thresholds->primary)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004315 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4316
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004317 size = thresholds->primary ? thresholds->primary->size + 1 : 1;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004318
4319 /* Allocate memory for new array of thresholds */
Gustavo A. R. Silva67b80462019-03-05 15:44:05 -08004320 new = kmalloc(struct_size(new, entries, size), GFP_KERNEL);
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004321 if (!new) {
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004322 ret = -ENOMEM;
4323 goto unlock;
4324 }
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004325 new->size = size;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004326
4327 /* Copy thresholds (if any) to new array */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004328 if (thresholds->primary) {
4329 memcpy(new->entries, thresholds->primary->entries, (size - 1) *
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004330 sizeof(struct mem_cgroup_threshold));
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004331 }
4332
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004333 /* Add new threshold */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004334 new->entries[size - 1].eventfd = eventfd;
4335 new->entries[size - 1].threshold = threshold;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004336
4337 /* Sort thresholds. Registering of new threshold isn't time-critical */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004338 sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004339 compare_thresholds, NULL);
4340
4341 /* Find current threshold */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004342 new->current_threshold = -1;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004343 for (i = 0; i < size; i++) {
Sha Zhengju748dad32012-05-29 15:06:57 -07004344 if (new->entries[i].threshold <= usage) {
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004345 /*
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004346 * new->current_threshold will not be used until
4347 * rcu_assign_pointer(), so it's safe to increment
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004348 * it here.
4349 */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004350 ++new->current_threshold;
Sha Zhengju748dad32012-05-29 15:06:57 -07004351 } else
4352 break;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004353 }
4354
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004355 /* Free old spare buffer and save old primary buffer as spare */
4356 kfree(thresholds->spare);
4357 thresholds->spare = thresholds->primary;
4358
4359 rcu_assign_pointer(thresholds->primary, new);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004360
Kirill A. Shutemov907860e2010-05-26 14:42:46 -07004361 /* To be sure that nobody uses thresholds */
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004362 synchronize_rcu();
4363
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004364unlock:
4365 mutex_unlock(&memcg->thresholds_lock);
4366
4367 return ret;
4368}
4369
Tejun Heo59b6f872013-11-22 18:20:43 -05004370static int mem_cgroup_usage_register_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004371 struct eventfd_ctx *eventfd, const char *args)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004372{
Tejun Heo59b6f872013-11-22 18:20:43 -05004373 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEM);
Tejun Heo347c4a82013-11-22 18:20:43 -05004374}
4375
Tejun Heo59b6f872013-11-22 18:20:43 -05004376static int memsw_cgroup_usage_register_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004377 struct eventfd_ctx *eventfd, const char *args)
4378{
Tejun Heo59b6f872013-11-22 18:20:43 -05004379 return __mem_cgroup_usage_register_event(memcg, eventfd, args, _MEMSWAP);
Tejun Heo347c4a82013-11-22 18:20:43 -05004380}
4381
Tejun Heo59b6f872013-11-22 18:20:43 -05004382static void __mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004383 struct eventfd_ctx *eventfd, enum res_type type)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004384{
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004385 struct mem_cgroup_thresholds *thresholds;
4386 struct mem_cgroup_threshold_ary *new;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08004387 unsigned long usage;
Chunguang Xu7d366652020-03-21 18:22:10 -07004388 int i, j, size, entries;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004389
4390 mutex_lock(&memcg->thresholds_lock);
Johannes Weiner05b84302014-08-06 16:05:59 -07004391
4392 if (type == _MEM) {
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004393 thresholds = &memcg->thresholds;
Johannes Weinerce00a962014-09-05 08:43:57 -04004394 usage = mem_cgroup_usage(memcg, false);
Johannes Weiner05b84302014-08-06 16:05:59 -07004395 } else if (type == _MEMSWAP) {
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004396 thresholds = &memcg->memsw_thresholds;
Johannes Weinerce00a962014-09-05 08:43:57 -04004397 usage = mem_cgroup_usage(memcg, true);
Johannes Weiner05b84302014-08-06 16:05:59 -07004398 } else
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004399 BUG();
4400
Anton Vorontsov371528c2012-02-24 05:14:46 +04004401 if (!thresholds->primary)
4402 goto unlock;
4403
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004404 /* Check if a threshold crossed before removing */
4405 __mem_cgroup_threshold(memcg, type == _MEMSWAP);
4406
4407 /* Calculate new number of threshold */
Chunguang Xu7d366652020-03-21 18:22:10 -07004408 size = entries = 0;
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004409 for (i = 0; i < thresholds->primary->size; i++) {
4410 if (thresholds->primary->entries[i].eventfd != eventfd)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004411 size++;
Chunguang Xu7d366652020-03-21 18:22:10 -07004412 else
4413 entries++;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004414 }
4415
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004416 new = thresholds->spare;
Kirill A. Shutemov907860e2010-05-26 14:42:46 -07004417
Chunguang Xu7d366652020-03-21 18:22:10 -07004418 /* If no items related to eventfd have been cleared, nothing to do */
4419 if (!entries)
4420 goto unlock;
4421
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004422 /* Set thresholds array to NULL if we don't have thresholds */
4423 if (!size) {
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004424 kfree(new);
4425 new = NULL;
Kirill A. Shutemov907860e2010-05-26 14:42:46 -07004426 goto swap_buffers;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004427 }
4428
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004429 new->size = size;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004430
4431 /* Copy thresholds and find current threshold */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004432 new->current_threshold = -1;
4433 for (i = 0, j = 0; i < thresholds->primary->size; i++) {
4434 if (thresholds->primary->entries[i].eventfd == eventfd)
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004435 continue;
4436
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004437 new->entries[j] = thresholds->primary->entries[i];
Sha Zhengju748dad32012-05-29 15:06:57 -07004438 if (new->entries[j].threshold <= usage) {
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004439 /*
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004440 * new->current_threshold will not be used
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004441 * until rcu_assign_pointer(), so it's safe to increment
4442 * it here.
4443 */
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004444 ++new->current_threshold;
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004445 }
4446 j++;
4447 }
4448
Kirill A. Shutemov907860e2010-05-26 14:42:46 -07004449swap_buffers:
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004450 /* Swap primary and spare array */
4451 thresholds->spare = thresholds->primary;
Sha Zhengju8c757762012-05-10 13:01:45 -07004452
Kirill A. Shutemov2c488db2010-05-26 14:42:47 -07004453 rcu_assign_pointer(thresholds->primary, new);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004454
Kirill A. Shutemov907860e2010-05-26 14:42:46 -07004455 /* To be sure that nobody uses thresholds */
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004456 synchronize_rcu();
Martijn Coenen6611d8d2016-01-15 16:57:49 -08004457
4458 /* If all events are unregistered, free the spare array */
4459 if (!new) {
4460 kfree(thresholds->spare);
4461 thresholds->spare = NULL;
4462 }
Anton Vorontsov371528c2012-02-24 05:14:46 +04004463unlock:
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004464 mutex_unlock(&memcg->thresholds_lock);
Kirill A. Shutemov2e72b632010-03-10 15:22:24 -08004465}
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08004466
Tejun Heo59b6f872013-11-22 18:20:43 -05004467static void mem_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004468 struct eventfd_ctx *eventfd)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004469{
Tejun Heo59b6f872013-11-22 18:20:43 -05004470 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEM);
Tejun Heo347c4a82013-11-22 18:20:43 -05004471}
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004472
Tejun Heo59b6f872013-11-22 18:20:43 -05004473static void memsw_cgroup_usage_unregister_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004474 struct eventfd_ctx *eventfd)
4475{
Tejun Heo59b6f872013-11-22 18:20:43 -05004476 return __mem_cgroup_usage_unregister_event(memcg, eventfd, _MEMSWAP);
Tejun Heo347c4a82013-11-22 18:20:43 -05004477}
4478
Tejun Heo59b6f872013-11-22 18:20:43 -05004479static int mem_cgroup_oom_register_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004480 struct eventfd_ctx *eventfd, const char *args)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004481{
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004482 struct mem_cgroup_eventfd_list *event;
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004483
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004484 event = kmalloc(sizeof(*event), GFP_KERNEL);
4485 if (!event)
4486 return -ENOMEM;
4487
Michal Hocko1af8efe2011-07-26 16:08:24 -07004488 spin_lock(&memcg_oom_lock);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004489
4490 event->eventfd = eventfd;
4491 list_add(&event->list, &memcg->oom_notify);
4492
4493 /* already in OOM ? */
Tejun Heoc2b42d32015-06-24 16:58:23 -07004494 if (memcg->under_oom)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004495 eventfd_signal(eventfd, 1);
Michal Hocko1af8efe2011-07-26 16:08:24 -07004496 spin_unlock(&memcg_oom_lock);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004497
4498 return 0;
4499}
4500
Tejun Heo59b6f872013-11-22 18:20:43 -05004501static void mem_cgroup_oom_unregister_event(struct mem_cgroup *memcg,
Tejun Heo347c4a82013-11-22 18:20:43 -05004502 struct eventfd_ctx *eventfd)
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004503{
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004504 struct mem_cgroup_eventfd_list *ev, *tmp;
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004505
Michal Hocko1af8efe2011-07-26 16:08:24 -07004506 spin_lock(&memcg_oom_lock);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004507
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004508 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004509 if (ev->eventfd == eventfd) {
4510 list_del(&ev->list);
4511 kfree(ev);
4512 }
4513 }
4514
Michal Hocko1af8efe2011-07-26 16:08:24 -07004515 spin_unlock(&memcg_oom_lock);
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07004516}
4517
Tejun Heo2da8ca82013-12-05 12:28:04 -05004518static int mem_cgroup_oom_control_read(struct seq_file *sf, void *v)
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004519{
Chris Downaa9694b2019-03-05 15:45:52 -08004520 struct mem_cgroup *memcg = mem_cgroup_from_seq(sf);
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004521
Tejun Heo791badb2013-12-05 12:28:02 -05004522 seq_printf(sf, "oom_kill_disable %d\n", memcg->oom_kill_disable);
Tejun Heoc2b42d32015-06-24 16:58:23 -07004523 seq_printf(sf, "under_oom %d\n", (bool)memcg->under_oom);
Roman Gushchinfe6bdfc2018-06-14 15:28:05 -07004524 seq_printf(sf, "oom_kill %lu\n",
4525 atomic_long_read(&memcg->memory_events[MEMCG_OOM_KILL]));
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004526 return 0;
4527}
4528
Tejun Heo182446d2013-08-08 20:11:24 -04004529static int mem_cgroup_oom_control_write(struct cgroup_subsys_state *css,
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004530 struct cftype *cft, u64 val)
4531{
Tejun Heo182446d2013-08-08 20:11:24 -04004532 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004533
4534 /* cannot set to root cgroup and only 0 and 1 are allowed */
Linus Torvalds14208b02014-06-09 15:03:33 -07004535 if (!css->parent || !((val == 0) || (val == 1)))
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004536 return -EINVAL;
4537
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004538 memcg->oom_kill_disable = val;
KAMEZAWA Hiroyuki4d845eb2010-06-29 15:05:18 -07004539 if (!val)
Raghavendra K Tc0ff4b82011-11-02 13:38:15 -07004540 memcg_oom_recover(memcg);
Johannes Weiner3dae7fe2014-06-04 16:07:01 -07004541
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07004542 return 0;
4543}
4544
Tejun Heo52ebea72015-05-22 17:13:37 -04004545#ifdef CONFIG_CGROUP_WRITEBACK
4546
Tejun Heo3a8e9ac2019-08-29 15:47:19 -07004547#include <trace/events/writeback.h>
4548
Tejun Heo841710a2015-05-22 18:23:33 -04004549static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4550{
4551 return wb_domain_init(&memcg->cgwb_domain, gfp);
4552}
4553
4554static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4555{
4556 wb_domain_exit(&memcg->cgwb_domain);
4557}
4558
Tejun Heo2529bb32015-05-22 18:23:34 -04004559static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4560{
4561 wb_domain_size_changed(&memcg->cgwb_domain);
4562}
4563
Tejun Heo841710a2015-05-22 18:23:33 -04004564struct wb_domain *mem_cgroup_wb_domain(struct bdi_writeback *wb)
4565{
4566 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4567
4568 if (!memcg->css.parent)
4569 return NULL;
4570
4571 return &memcg->cgwb_domain;
4572}
4573
Greg Thelen0b3d6e62019-04-05 18:39:18 -07004574/*
4575 * idx can be of type enum memcg_stat_item or node_stat_item.
4576 * Keep in sync with memcg_exact_page().
4577 */
4578static unsigned long memcg_exact_page_state(struct mem_cgroup *memcg, int idx)
4579{
Chris Down871789d2019-05-14 15:46:57 -07004580 long x = atomic_long_read(&memcg->vmstats[idx]);
Greg Thelen0b3d6e62019-04-05 18:39:18 -07004581 int cpu;
4582
4583 for_each_online_cpu(cpu)
Chris Down871789d2019-05-14 15:46:57 -07004584 x += per_cpu_ptr(memcg->vmstats_percpu, cpu)->stat[idx];
Greg Thelen0b3d6e62019-04-05 18:39:18 -07004585 if (x < 0)
4586 x = 0;
4587 return x;
4588}
4589
Tejun Heoc2aa7232015-05-22 18:23:35 -04004590/**
4591 * mem_cgroup_wb_stats - retrieve writeback related stats from its memcg
4592 * @wb: bdi_writeback in question
Tejun Heoc5edf9c2015-09-29 13:04:26 -04004593 * @pfilepages: out parameter for number of file pages
4594 * @pheadroom: out parameter for number of allocatable pages according to memcg
Tejun Heoc2aa7232015-05-22 18:23:35 -04004595 * @pdirty: out parameter for number of dirty pages
4596 * @pwriteback: out parameter for number of pages under writeback
4597 *
Tejun Heoc5edf9c2015-09-29 13:04:26 -04004598 * Determine the numbers of file, headroom, dirty, and writeback pages in
4599 * @wb's memcg. File, dirty and writeback are self-explanatory. Headroom
4600 * is a bit more involved.
Tejun Heoc2aa7232015-05-22 18:23:35 -04004601 *
Tejun Heoc5edf9c2015-09-29 13:04:26 -04004602 * A memcg's headroom is "min(max, high) - used". In the hierarchy, the
4603 * headroom is calculated as the lowest headroom of itself and the
4604 * ancestors. Note that this doesn't consider the actual amount of
4605 * available memory in the system. The caller should further cap
4606 * *@pheadroom accordingly.
Tejun Heoc2aa7232015-05-22 18:23:35 -04004607 */
Tejun Heoc5edf9c2015-09-29 13:04:26 -04004608void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages,
4609 unsigned long *pheadroom, unsigned long *pdirty,
4610 unsigned long *pwriteback)
Tejun Heoc2aa7232015-05-22 18:23:35 -04004611{
4612 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4613 struct mem_cgroup *parent;
Tejun Heoc2aa7232015-05-22 18:23:35 -04004614
Greg Thelen0b3d6e62019-04-05 18:39:18 -07004615 *pdirty = memcg_exact_page_state(memcg, NR_FILE_DIRTY);
Tejun Heoc2aa7232015-05-22 18:23:35 -04004616
Greg Thelen0b3d6e62019-04-05 18:39:18 -07004617 *pwriteback = memcg_exact_page_state(memcg, NR_WRITEBACK);
Johannes Weiner21d89d12019-05-13 17:18:08 -07004618 *pfilepages = memcg_exact_page_state(memcg, NR_INACTIVE_FILE) +
4619 memcg_exact_page_state(memcg, NR_ACTIVE_FILE);
Tejun Heoc5edf9c2015-09-29 13:04:26 -04004620 *pheadroom = PAGE_COUNTER_MAX;
Tejun Heoc2aa7232015-05-22 18:23:35 -04004621
Tejun Heoc2aa7232015-05-22 18:23:35 -04004622 while ((parent = parent_mem_cgroup(memcg))) {
Chris Down15b42562020-04-01 21:07:20 -07004623 unsigned long ceiling = min(READ_ONCE(memcg->memory.max),
Jakub Kicinskid1663a92020-06-01 21:49:49 -07004624 READ_ONCE(memcg->memory.high));
Tejun Heoc2aa7232015-05-22 18:23:35 -04004625 unsigned long used = page_counter_read(&memcg->memory);
4626
Tejun Heoc5edf9c2015-09-29 13:04:26 -04004627 *pheadroom = min(*pheadroom, ceiling - min(ceiling, used));
Tejun Heoc2aa7232015-05-22 18:23:35 -04004628 memcg = parent;
4629 }
Tejun Heoc2aa7232015-05-22 18:23:35 -04004630}
4631
Tejun Heo97b27822019-08-26 09:06:56 -07004632/*
4633 * Foreign dirty flushing
4634 *
4635 * There's an inherent mismatch between memcg and writeback. The former
4636 * trackes ownership per-page while the latter per-inode. This was a
4637 * deliberate design decision because honoring per-page ownership in the
4638 * writeback path is complicated, may lead to higher CPU and IO overheads
4639 * and deemed unnecessary given that write-sharing an inode across
4640 * different cgroups isn't a common use-case.
4641 *
4642 * Combined with inode majority-writer ownership switching, this works well
4643 * enough in most cases but there are some pathological cases. For
4644 * example, let's say there are two cgroups A and B which keep writing to
4645 * different but confined parts of the same inode. B owns the inode and
4646 * A's memory is limited far below B's. A's dirty ratio can rise enough to
4647 * trigger balance_dirty_pages() sleeps but B's can be low enough to avoid
4648 * triggering background writeback. A will be slowed down without a way to
4649 * make writeback of the dirty pages happen.
4650 *
4651 * Conditions like the above can lead to a cgroup getting repatedly and
4652 * severely throttled after making some progress after each
4653 * dirty_expire_interval while the underyling IO device is almost
4654 * completely idle.
4655 *
4656 * Solving this problem completely requires matching the ownership tracking
4657 * granularities between memcg and writeback in either direction. However,
4658 * the more egregious behaviors can be avoided by simply remembering the
4659 * most recent foreign dirtying events and initiating remote flushes on
4660 * them when local writeback isn't enough to keep the memory clean enough.
4661 *
4662 * The following two functions implement such mechanism. When a foreign
4663 * page - a page whose memcg and writeback ownerships don't match - is
4664 * dirtied, mem_cgroup_track_foreign_dirty() records the inode owning
4665 * bdi_writeback on the page owning memcg. When balance_dirty_pages()
4666 * decides that the memcg needs to sleep due to high dirty ratio, it calls
4667 * mem_cgroup_flush_foreign() which queues writeback on the recorded
4668 * foreign bdi_writebacks which haven't expired. Both the numbers of
4669 * recorded bdi_writebacks and concurrent in-flight foreign writebacks are
4670 * limited to MEMCG_CGWB_FRN_CNT.
4671 *
4672 * The mechanism only remembers IDs and doesn't hold any object references.
4673 * As being wrong occasionally doesn't matter, updates and accesses to the
4674 * records are lockless and racy.
4675 */
4676void mem_cgroup_track_foreign_dirty_slowpath(struct page *page,
4677 struct bdi_writeback *wb)
4678{
4679 struct mem_cgroup *memcg = page->mem_cgroup;
4680 struct memcg_cgwb_frn *frn;
4681 u64 now = get_jiffies_64();
4682 u64 oldest_at = now;
4683 int oldest = -1;
4684 int i;
4685
Tejun Heo3a8e9ac2019-08-29 15:47:19 -07004686 trace_track_foreign_dirty(page, wb);
4687
Tejun Heo97b27822019-08-26 09:06:56 -07004688 /*
4689 * Pick the slot to use. If there is already a slot for @wb, keep
4690 * using it. If not replace the oldest one which isn't being
4691 * written out.
4692 */
4693 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4694 frn = &memcg->cgwb_frn[i];
4695 if (frn->bdi_id == wb->bdi->id &&
4696 frn->memcg_id == wb->memcg_css->id)
4697 break;
4698 if (time_before64(frn->at, oldest_at) &&
4699 atomic_read(&frn->done.cnt) == 1) {
4700 oldest = i;
4701 oldest_at = frn->at;
4702 }
4703 }
4704
4705 if (i < MEMCG_CGWB_FRN_CNT) {
4706 /*
4707 * Re-using an existing one. Update timestamp lazily to
4708 * avoid making the cacheline hot. We want them to be
4709 * reasonably up-to-date and significantly shorter than
4710 * dirty_expire_interval as that's what expires the record.
4711 * Use the shorter of 1s and dirty_expire_interval / 8.
4712 */
4713 unsigned long update_intv =
4714 min_t(unsigned long, HZ,
4715 msecs_to_jiffies(dirty_expire_interval * 10) / 8);
4716
4717 if (time_before64(frn->at, now - update_intv))
4718 frn->at = now;
4719 } else if (oldest >= 0) {
4720 /* replace the oldest free one */
4721 frn = &memcg->cgwb_frn[oldest];
4722 frn->bdi_id = wb->bdi->id;
4723 frn->memcg_id = wb->memcg_css->id;
4724 frn->at = now;
4725 }
4726}
4727
4728/* issue foreign writeback flushes for recorded foreign dirtying events */
4729void mem_cgroup_flush_foreign(struct bdi_writeback *wb)
4730{
4731 struct mem_cgroup *memcg = mem_cgroup_from_css(wb->memcg_css);
4732 unsigned long intv = msecs_to_jiffies(dirty_expire_interval * 10);
4733 u64 now = jiffies_64;
4734 int i;
4735
4736 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++) {
4737 struct memcg_cgwb_frn *frn = &memcg->cgwb_frn[i];
4738
4739 /*
4740 * If the record is older than dirty_expire_interval,
4741 * writeback on it has already started. No need to kick it
4742 * off again. Also, don't start a new one if there's
4743 * already one in flight.
4744 */
4745 if (time_after64(frn->at, now - intv) &&
4746 atomic_read(&frn->done.cnt) == 1) {
4747 frn->at = 0;
Tejun Heo3a8e9ac2019-08-29 15:47:19 -07004748 trace_flush_foreign(wb, frn->bdi_id, frn->memcg_id);
Tejun Heo97b27822019-08-26 09:06:56 -07004749 cgroup_writeback_by_id(frn->bdi_id, frn->memcg_id, 0,
4750 WB_REASON_FOREIGN_FLUSH,
4751 &frn->done);
4752 }
4753 }
4754}
4755
Tejun Heo841710a2015-05-22 18:23:33 -04004756#else /* CONFIG_CGROUP_WRITEBACK */
4757
4758static int memcg_wb_domain_init(struct mem_cgroup *memcg, gfp_t gfp)
4759{
4760 return 0;
4761}
4762
4763static void memcg_wb_domain_exit(struct mem_cgroup *memcg)
4764{
4765}
4766
Tejun Heo2529bb32015-05-22 18:23:34 -04004767static void memcg_wb_domain_size_changed(struct mem_cgroup *memcg)
4768{
4769}
4770
Tejun Heo52ebea72015-05-22 17:13:37 -04004771#endif /* CONFIG_CGROUP_WRITEBACK */
4772
Tejun Heo79bd9812013-11-22 18:20:42 -05004773/*
Tejun Heo3bc942f2013-11-22 18:20:44 -05004774 * DO NOT USE IN NEW FILES.
4775 *
4776 * "cgroup.event_control" implementation.
4777 *
4778 * This is way over-engineered. It tries to support fully configurable
4779 * events for each user. Such level of flexibility is completely
4780 * unnecessary especially in the light of the planned unified hierarchy.
4781 *
4782 * Please deprecate this and replace with something simpler if at all
4783 * possible.
4784 */
4785
4786/*
Tejun Heo79bd9812013-11-22 18:20:42 -05004787 * Unregister event and free resources.
4788 *
4789 * Gets called from workqueue.
4790 */
Tejun Heo3bc942f2013-11-22 18:20:44 -05004791static void memcg_event_remove(struct work_struct *work)
Tejun Heo79bd9812013-11-22 18:20:42 -05004792{
Tejun Heo3bc942f2013-11-22 18:20:44 -05004793 struct mem_cgroup_event *event =
4794 container_of(work, struct mem_cgroup_event, remove);
Tejun Heo59b6f872013-11-22 18:20:43 -05004795 struct mem_cgroup *memcg = event->memcg;
Tejun Heo79bd9812013-11-22 18:20:42 -05004796
4797 remove_wait_queue(event->wqh, &event->wait);
4798
Tejun Heo59b6f872013-11-22 18:20:43 -05004799 event->unregister_event(memcg, event->eventfd);
Tejun Heo79bd9812013-11-22 18:20:42 -05004800
4801 /* Notify userspace the event is going away. */
4802 eventfd_signal(event->eventfd, 1);
4803
4804 eventfd_ctx_put(event->eventfd);
4805 kfree(event);
Tejun Heo59b6f872013-11-22 18:20:43 -05004806 css_put(&memcg->css);
Tejun Heo79bd9812013-11-22 18:20:42 -05004807}
4808
4809/*
Linus Torvaldsa9a08842018-02-11 14:34:03 -08004810 * Gets called on EPOLLHUP on eventfd when user closes it.
Tejun Heo79bd9812013-11-22 18:20:42 -05004811 *
4812 * Called with wqh->lock held and interrupts disabled.
4813 */
Ingo Molnarac6424b2017-06-20 12:06:13 +02004814static int memcg_event_wake(wait_queue_entry_t *wait, unsigned mode,
Tejun Heo3bc942f2013-11-22 18:20:44 -05004815 int sync, void *key)
Tejun Heo79bd9812013-11-22 18:20:42 -05004816{
Tejun Heo3bc942f2013-11-22 18:20:44 -05004817 struct mem_cgroup_event *event =
4818 container_of(wait, struct mem_cgroup_event, wait);
Tejun Heo59b6f872013-11-22 18:20:43 -05004819 struct mem_cgroup *memcg = event->memcg;
Al Viro3ad6f932017-07-03 20:14:56 -04004820 __poll_t flags = key_to_poll(key);
Tejun Heo79bd9812013-11-22 18:20:42 -05004821
Linus Torvaldsa9a08842018-02-11 14:34:03 -08004822 if (flags & EPOLLHUP) {
Tejun Heo79bd9812013-11-22 18:20:42 -05004823 /*
4824 * If the event has been detached at cgroup removal, we
4825 * can simply return knowing the other side will cleanup
4826 * for us.
4827 *
4828 * We can't race against event freeing since the other
4829 * side will require wqh->lock via remove_wait_queue(),
4830 * which we hold.
4831 */
Tejun Heofba94802013-11-22 18:20:43 -05004832 spin_lock(&memcg->event_list_lock);
Tejun Heo79bd9812013-11-22 18:20:42 -05004833 if (!list_empty(&event->list)) {
4834 list_del_init(&event->list);
4835 /*
4836 * We are in atomic context, but cgroup_event_remove()
4837 * may sleep, so we have to call it in workqueue.
4838 */
4839 schedule_work(&event->remove);
4840 }
Tejun Heofba94802013-11-22 18:20:43 -05004841 spin_unlock(&memcg->event_list_lock);
Tejun Heo79bd9812013-11-22 18:20:42 -05004842 }
4843
4844 return 0;
4845}
4846
Tejun Heo3bc942f2013-11-22 18:20:44 -05004847static void memcg_event_ptable_queue_proc(struct file *file,
Tejun Heo79bd9812013-11-22 18:20:42 -05004848 wait_queue_head_t *wqh, poll_table *pt)
4849{
Tejun Heo3bc942f2013-11-22 18:20:44 -05004850 struct mem_cgroup_event *event =
4851 container_of(pt, struct mem_cgroup_event, pt);
Tejun Heo79bd9812013-11-22 18:20:42 -05004852
4853 event->wqh = wqh;
4854 add_wait_queue(wqh, &event->wait);
4855}
4856
4857/*
Tejun Heo3bc942f2013-11-22 18:20:44 -05004858 * DO NOT USE IN NEW FILES.
4859 *
Tejun Heo79bd9812013-11-22 18:20:42 -05004860 * Parse input and register new cgroup event handler.
4861 *
4862 * Input must be in format '<event_fd> <control_fd> <args>'.
4863 * Interpretation of args is defined by control file implementation.
4864 */
Tejun Heo451af502014-05-13 12:16:21 -04004865static ssize_t memcg_write_event_control(struct kernfs_open_file *of,
4866 char *buf, size_t nbytes, loff_t off)
Tejun Heo79bd9812013-11-22 18:20:42 -05004867{
Tejun Heo451af502014-05-13 12:16:21 -04004868 struct cgroup_subsys_state *css = of_css(of);
Tejun Heofba94802013-11-22 18:20:43 -05004869 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Tejun Heo3bc942f2013-11-22 18:20:44 -05004870 struct mem_cgroup_event *event;
Tejun Heo79bd9812013-11-22 18:20:42 -05004871 struct cgroup_subsys_state *cfile_css;
4872 unsigned int efd, cfd;
4873 struct fd efile;
4874 struct fd cfile;
Tejun Heofba94802013-11-22 18:20:43 -05004875 const char *name;
Tejun Heo79bd9812013-11-22 18:20:42 -05004876 char *endp;
4877 int ret;
4878
Tejun Heo451af502014-05-13 12:16:21 -04004879 buf = strstrip(buf);
4880
4881 efd = simple_strtoul(buf, &endp, 10);
Tejun Heo79bd9812013-11-22 18:20:42 -05004882 if (*endp != ' ')
4883 return -EINVAL;
Tejun Heo451af502014-05-13 12:16:21 -04004884 buf = endp + 1;
Tejun Heo79bd9812013-11-22 18:20:42 -05004885
Tejun Heo451af502014-05-13 12:16:21 -04004886 cfd = simple_strtoul(buf, &endp, 10);
Tejun Heo79bd9812013-11-22 18:20:42 -05004887 if ((*endp != ' ') && (*endp != '\0'))
4888 return -EINVAL;
Tejun Heo451af502014-05-13 12:16:21 -04004889 buf = endp + 1;
Tejun Heo79bd9812013-11-22 18:20:42 -05004890
4891 event = kzalloc(sizeof(*event), GFP_KERNEL);
4892 if (!event)
4893 return -ENOMEM;
4894
Tejun Heo59b6f872013-11-22 18:20:43 -05004895 event->memcg = memcg;
Tejun Heo79bd9812013-11-22 18:20:42 -05004896 INIT_LIST_HEAD(&event->list);
Tejun Heo3bc942f2013-11-22 18:20:44 -05004897 init_poll_funcptr(&event->pt, memcg_event_ptable_queue_proc);
4898 init_waitqueue_func_entry(&event->wait, memcg_event_wake);
4899 INIT_WORK(&event->remove, memcg_event_remove);
Tejun Heo79bd9812013-11-22 18:20:42 -05004900
4901 efile = fdget(efd);
4902 if (!efile.file) {
4903 ret = -EBADF;
4904 goto out_kfree;
4905 }
4906
4907 event->eventfd = eventfd_ctx_fileget(efile.file);
4908 if (IS_ERR(event->eventfd)) {
4909 ret = PTR_ERR(event->eventfd);
4910 goto out_put_efile;
4911 }
4912
4913 cfile = fdget(cfd);
4914 if (!cfile.file) {
4915 ret = -EBADF;
4916 goto out_put_eventfd;
4917 }
4918
4919 /* the process need read permission on control file */
4920 /* AV: shouldn't we check that it's been opened for read instead? */
4921 ret = inode_permission(file_inode(cfile.file), MAY_READ);
4922 if (ret < 0)
4923 goto out_put_cfile;
4924
Tejun Heo79bd9812013-11-22 18:20:42 -05004925 /*
Tejun Heofba94802013-11-22 18:20:43 -05004926 * Determine the event callbacks and set them in @event. This used
4927 * to be done via struct cftype but cgroup core no longer knows
4928 * about these events. The following is crude but the whole thing
4929 * is for compatibility anyway.
Tejun Heo3bc942f2013-11-22 18:20:44 -05004930 *
4931 * DO NOT ADD NEW FILES.
Tejun Heofba94802013-11-22 18:20:43 -05004932 */
Al Virob5830432014-10-31 01:22:04 -04004933 name = cfile.file->f_path.dentry->d_name.name;
Tejun Heofba94802013-11-22 18:20:43 -05004934
4935 if (!strcmp(name, "memory.usage_in_bytes")) {
4936 event->register_event = mem_cgroup_usage_register_event;
4937 event->unregister_event = mem_cgroup_usage_unregister_event;
4938 } else if (!strcmp(name, "memory.oom_control")) {
4939 event->register_event = mem_cgroup_oom_register_event;
4940 event->unregister_event = mem_cgroup_oom_unregister_event;
4941 } else if (!strcmp(name, "memory.pressure_level")) {
4942 event->register_event = vmpressure_register_event;
4943 event->unregister_event = vmpressure_unregister_event;
4944 } else if (!strcmp(name, "memory.memsw.usage_in_bytes")) {
Tejun Heo347c4a82013-11-22 18:20:43 -05004945 event->register_event = memsw_cgroup_usage_register_event;
4946 event->unregister_event = memsw_cgroup_usage_unregister_event;
Tejun Heofba94802013-11-22 18:20:43 -05004947 } else {
4948 ret = -EINVAL;
4949 goto out_put_cfile;
4950 }
4951
4952 /*
Tejun Heob5557c42013-11-22 18:20:42 -05004953 * Verify @cfile should belong to @css. Also, remaining events are
4954 * automatically removed on cgroup destruction but the removal is
4955 * asynchronous, so take an extra ref on @css.
Tejun Heo79bd9812013-11-22 18:20:42 -05004956 */
Al Virob5830432014-10-31 01:22:04 -04004957 cfile_css = css_tryget_online_from_dir(cfile.file->f_path.dentry->d_parent,
Tejun Heoec903c02014-05-13 12:11:01 -04004958 &memory_cgrp_subsys);
Tejun Heo79bd9812013-11-22 18:20:42 -05004959 ret = -EINVAL;
Tejun Heo5a17f542014-02-11 11:52:47 -05004960 if (IS_ERR(cfile_css))
Tejun Heo79bd9812013-11-22 18:20:42 -05004961 goto out_put_cfile;
Tejun Heo5a17f542014-02-11 11:52:47 -05004962 if (cfile_css != css) {
4963 css_put(cfile_css);
4964 goto out_put_cfile;
4965 }
Tejun Heo79bd9812013-11-22 18:20:42 -05004966
Tejun Heo451af502014-05-13 12:16:21 -04004967 ret = event->register_event(memcg, event->eventfd, buf);
Tejun Heo79bd9812013-11-22 18:20:42 -05004968 if (ret)
4969 goto out_put_css;
4970
Christoph Hellwig9965ed172018-03-05 07:26:05 -08004971 vfs_poll(efile.file, &event->pt);
Tejun Heo79bd9812013-11-22 18:20:42 -05004972
Tejun Heofba94802013-11-22 18:20:43 -05004973 spin_lock(&memcg->event_list_lock);
4974 list_add(&event->list, &memcg->event_list);
4975 spin_unlock(&memcg->event_list_lock);
Tejun Heo79bd9812013-11-22 18:20:42 -05004976
4977 fdput(cfile);
4978 fdput(efile);
4979
Tejun Heo451af502014-05-13 12:16:21 -04004980 return nbytes;
Tejun Heo79bd9812013-11-22 18:20:42 -05004981
4982out_put_css:
Tejun Heob5557c42013-11-22 18:20:42 -05004983 css_put(css);
Tejun Heo79bd9812013-11-22 18:20:42 -05004984out_put_cfile:
4985 fdput(cfile);
4986out_put_eventfd:
4987 eventfd_ctx_put(event->eventfd);
4988out_put_efile:
4989 fdput(efile);
4990out_kfree:
4991 kfree(event);
4992
4993 return ret;
4994}
4995
Johannes Weiner241994ed2015-02-11 15:26:06 -08004996static struct cftype mem_cgroup_legacy_files[] = {
Balbir Singh8cdea7c2008-02-07 00:13:50 -08004997 {
Balbir Singh0eea1032008-02-07 00:13:57 -08004998 .name = "usage_in_bytes",
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08004999 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
Tejun Heo791badb2013-12-05 12:28:02 -05005000 .read_u64 = mem_cgroup_read_u64,
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005001 },
5002 {
Pavel Emelyanovc84872e2008-04-29 01:00:17 -07005003 .name = "max_usage_in_bytes",
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08005004 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
Tejun Heo6770c642014-05-13 12:16:21 -04005005 .write = mem_cgroup_reset,
Tejun Heo791badb2013-12-05 12:28:02 -05005006 .read_u64 = mem_cgroup_read_u64,
Pavel Emelyanovc84872e2008-04-29 01:00:17 -07005007 },
5008 {
Balbir Singh0eea1032008-02-07 00:13:57 -08005009 .name = "limit_in_bytes",
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08005010 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
Tejun Heo451af502014-05-13 12:16:21 -04005011 .write = mem_cgroup_write,
Tejun Heo791badb2013-12-05 12:28:02 -05005012 .read_u64 = mem_cgroup_read_u64,
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005013 },
5014 {
Balbir Singh296c81d2009-09-23 15:56:36 -07005015 .name = "soft_limit_in_bytes",
5016 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
Tejun Heo451af502014-05-13 12:16:21 -04005017 .write = mem_cgroup_write,
Tejun Heo791badb2013-12-05 12:28:02 -05005018 .read_u64 = mem_cgroup_read_u64,
Balbir Singh296c81d2009-09-23 15:56:36 -07005019 },
5020 {
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005021 .name = "failcnt",
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08005022 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
Tejun Heo6770c642014-05-13 12:16:21 -04005023 .write = mem_cgroup_reset,
Tejun Heo791badb2013-12-05 12:28:02 -05005024 .read_u64 = mem_cgroup_read_u64,
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005025 },
Balbir Singh8697d332008-02-07 00:13:59 -08005026 {
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -08005027 .name = "stat",
Tejun Heo2da8ca82013-12-05 12:28:04 -05005028 .seq_show = memcg_stat_show,
KAMEZAWA Hiroyukid2ceb9b2008-02-07 00:14:25 -08005029 },
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08005030 {
5031 .name = "force_empty",
Tejun Heo6770c642014-05-13 12:16:21 -04005032 .write = mem_cgroup_force_empty_write,
KAMEZAWA Hiroyukic1e862c2009-01-07 18:07:55 -08005033 },
Balbir Singh18f59ea2009-01-07 18:08:07 -08005034 {
5035 .name = "use_hierarchy",
5036 .write_u64 = mem_cgroup_hierarchy_write,
5037 .read_u64 = mem_cgroup_hierarchy_read,
5038 },
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08005039 {
Tejun Heo3bc942f2013-11-22 18:20:44 -05005040 .name = "cgroup.event_control", /* XXX: for compat */
Tejun Heo451af502014-05-13 12:16:21 -04005041 .write = memcg_write_event_control,
Tejun Heo7dbdb192015-09-18 17:54:23 -04005042 .flags = CFTYPE_NO_PREFIX | CFTYPE_WORLD_WRITABLE,
Tejun Heo79bd9812013-11-22 18:20:42 -05005043 },
5044 {
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08005045 .name = "swappiness",
5046 .read_u64 = mem_cgroup_swappiness_read,
5047 .write_u64 = mem_cgroup_swappiness_write,
5048 },
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005049 {
5050 .name = "move_charge_at_immigrate",
5051 .read_u64 = mem_cgroup_move_charge_read,
5052 .write_u64 = mem_cgroup_move_charge_write,
5053 },
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07005054 {
5055 .name = "oom_control",
Tejun Heo2da8ca82013-12-05 12:28:04 -05005056 .seq_show = mem_cgroup_oom_control_read,
KAMEZAWA Hiroyuki3c11ecf2010-05-26 14:42:37 -07005057 .write_u64 = mem_cgroup_oom_control_write,
KAMEZAWA Hiroyuki9490ff22010-05-26 14:42:36 -07005058 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
5059 },
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005060 {
5061 .name = "pressure_level",
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005062 },
Ying Han406eb0c2011-05-26 16:25:37 -07005063#ifdef CONFIG_NUMA
5064 {
5065 .name = "numa_stat",
Tejun Heo2da8ca82013-12-05 12:28:04 -05005066 .seq_show = memcg_numa_stat_show,
Ying Han406eb0c2011-05-26 16:25:37 -07005067 },
5068#endif
Glauber Costa510fc4e2012-12-18 14:21:47 -08005069 {
5070 .name = "kmem.limit_in_bytes",
5071 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
Tejun Heo451af502014-05-13 12:16:21 -04005072 .write = mem_cgroup_write,
Tejun Heo791badb2013-12-05 12:28:02 -05005073 .read_u64 = mem_cgroup_read_u64,
Glauber Costa510fc4e2012-12-18 14:21:47 -08005074 },
5075 {
5076 .name = "kmem.usage_in_bytes",
5077 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
Tejun Heo791badb2013-12-05 12:28:02 -05005078 .read_u64 = mem_cgroup_read_u64,
Glauber Costa510fc4e2012-12-18 14:21:47 -08005079 },
5080 {
5081 .name = "kmem.failcnt",
5082 .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
Tejun Heo6770c642014-05-13 12:16:21 -04005083 .write = mem_cgroup_reset,
Tejun Heo791badb2013-12-05 12:28:02 -05005084 .read_u64 = mem_cgroup_read_u64,
Glauber Costa510fc4e2012-12-18 14:21:47 -08005085 },
5086 {
5087 .name = "kmem.max_usage_in_bytes",
5088 .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
Tejun Heo6770c642014-05-13 12:16:21 -04005089 .write = mem_cgroup_reset,
Tejun Heo791badb2013-12-05 12:28:02 -05005090 .read_u64 = mem_cgroup_read_u64,
Glauber Costa510fc4e2012-12-18 14:21:47 -08005091 },
Yafang Shaoa87425a2020-04-01 21:06:30 -07005092#if defined(CONFIG_MEMCG_KMEM) && \
5093 (defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG))
Glauber Costa749c5412012-12-18 14:23:01 -08005094 {
5095 .name = "kmem.slabinfo",
Tejun Heobc2791f2017-02-22 15:41:21 -08005096 .seq_start = memcg_slab_start,
5097 .seq_next = memcg_slab_next,
5098 .seq_stop = memcg_slab_stop,
Vladimir Davydovb0475012014-12-10 15:44:19 -08005099 .seq_show = memcg_slab_show,
Glauber Costa749c5412012-12-18 14:23:01 -08005100 },
5101#endif
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08005102 {
5103 .name = "kmem.tcp.limit_in_bytes",
5104 .private = MEMFILE_PRIVATE(_TCP, RES_LIMIT),
5105 .write = mem_cgroup_write,
5106 .read_u64 = mem_cgroup_read_u64,
5107 },
5108 {
5109 .name = "kmem.tcp.usage_in_bytes",
5110 .private = MEMFILE_PRIVATE(_TCP, RES_USAGE),
5111 .read_u64 = mem_cgroup_read_u64,
5112 },
5113 {
5114 .name = "kmem.tcp.failcnt",
5115 .private = MEMFILE_PRIVATE(_TCP, RES_FAILCNT),
5116 .write = mem_cgroup_reset,
5117 .read_u64 = mem_cgroup_read_u64,
5118 },
5119 {
5120 .name = "kmem.tcp.max_usage_in_bytes",
5121 .private = MEMFILE_PRIVATE(_TCP, RES_MAX_USAGE),
5122 .write = mem_cgroup_reset,
5123 .read_u64 = mem_cgroup_read_u64,
5124 },
Tejun Heo6bc10342012-04-01 12:09:55 -07005125 { }, /* terminate */
Tejun Heoaf36f902012-04-01 12:09:55 -07005126};
KAMEZAWA Hiroyuki8c7c6e342009-01-07 18:08:00 -08005127
Johannes Weiner73f576c2016-07-20 15:44:57 -07005128/*
5129 * Private memory cgroup IDR
5130 *
5131 * Swap-out records and page cache shadow entries need to store memcg
5132 * references in constrained space, so we maintain an ID space that is
5133 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
5134 * memory-controlled cgroups to 64k.
5135 *
Ethon Paulb8f29352020-06-04 16:49:28 -07005136 * However, there usually are many references to the offline CSS after
Johannes Weiner73f576c2016-07-20 15:44:57 -07005137 * the cgroup has been destroyed, such as page cache or reclaimable
5138 * slab objects, that don't need to hang on to the ID. We want to keep
5139 * those dead CSS from occupying IDs, or we might quickly exhaust the
5140 * relatively small ID space and prevent the creation of new cgroups
5141 * even when there are much fewer than 64k cgroups - possibly none.
5142 *
5143 * Maintain a private 16-bit ID space for memcg, and allow the ID to
5144 * be freed and recycled when it's no longer needed, which is usually
5145 * when the CSS is offlined.
5146 *
5147 * The only exception to that are records of swapped out tmpfs/shmem
5148 * pages that need to be attributed to live ancestors on swapin. But
5149 * those references are manageable from userspace.
5150 */
5151
5152static DEFINE_IDR(mem_cgroup_idr);
5153
Kirill Tkhai7e97de02018-08-02 15:36:01 -07005154static void mem_cgroup_id_remove(struct mem_cgroup *memcg)
5155{
5156 if (memcg->id.id > 0) {
5157 idr_remove(&mem_cgroup_idr, memcg->id.id);
5158 memcg->id.id = 0;
5159 }
5160}
5161
Vincenzo Frascinoc1514c02020-04-01 21:07:13 -07005162static void __maybe_unused mem_cgroup_id_get_many(struct mem_cgroup *memcg,
5163 unsigned int n)
Johannes Weiner73f576c2016-07-20 15:44:57 -07005164{
Kirill Tkhai1c2d4792018-10-26 15:09:28 -07005165 refcount_add(n, &memcg->id.ref);
Johannes Weiner73f576c2016-07-20 15:44:57 -07005166}
5167
Vladimir Davydov615d66c2016-08-11 15:33:03 -07005168static void mem_cgroup_id_put_many(struct mem_cgroup *memcg, unsigned int n)
Johannes Weiner73f576c2016-07-20 15:44:57 -07005169{
Kirill Tkhai1c2d4792018-10-26 15:09:28 -07005170 if (refcount_sub_and_test(n, &memcg->id.ref)) {
Kirill Tkhai7e97de02018-08-02 15:36:01 -07005171 mem_cgroup_id_remove(memcg);
Johannes Weiner73f576c2016-07-20 15:44:57 -07005172
5173 /* Memcg ID pins CSS */
5174 css_put(&memcg->css);
5175 }
5176}
5177
Vladimir Davydov615d66c2016-08-11 15:33:03 -07005178static inline void mem_cgroup_id_put(struct mem_cgroup *memcg)
5179{
5180 mem_cgroup_id_put_many(memcg, 1);
5181}
5182
Johannes Weiner73f576c2016-07-20 15:44:57 -07005183/**
5184 * mem_cgroup_from_id - look up a memcg from a memcg id
5185 * @id: the memcg id to look up
5186 *
5187 * Caller must hold rcu_read_lock().
5188 */
5189struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
5190{
5191 WARN_ON_ONCE(!rcu_read_lock_held());
5192 return idr_find(&mem_cgroup_idr, id);
5193}
5194
Mel Gormanef8f2322016-07-28 15:46:05 -07005195static int alloc_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08005196{
5197 struct mem_cgroup_per_node *pn;
Mel Gormanef8f2322016-07-28 15:46:05 -07005198 int tmp = node;
KAMEZAWA Hiroyuki1ecaab22008-02-07 00:14:38 -08005199 /*
5200 * This routine is called against possible nodes.
5201 * But it's BUG to call kmalloc() against offline node.
5202 *
5203 * TODO: this routine can waste much memory for nodes which will
5204 * never be onlined. It's better to use memory hotplug callback
5205 * function.
5206 */
KAMEZAWA Hiroyuki41e33552008-04-08 17:41:54 -07005207 if (!node_state(node, N_NORMAL_MEMORY))
5208 tmp = -1;
Jesper Juhl17295c82011-01-13 15:47:42 -08005209 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08005210 if (!pn)
5211 return 1;
KAMEZAWA Hiroyuki1ecaab22008-02-07 00:14:38 -08005212
Johannes Weiner815744d2019-06-13 15:55:46 -07005213 pn->lruvec_stat_local = alloc_percpu(struct lruvec_stat);
5214 if (!pn->lruvec_stat_local) {
5215 kfree(pn);
5216 return 1;
5217 }
5218
Johannes Weinera983b5e2018-01-31 16:16:45 -08005219 pn->lruvec_stat_cpu = alloc_percpu(struct lruvec_stat);
5220 if (!pn->lruvec_stat_cpu) {
Johannes Weiner815744d2019-06-13 15:55:46 -07005221 free_percpu(pn->lruvec_stat_local);
Johannes Weiner00f3ca22017-07-06 15:40:52 -07005222 kfree(pn);
5223 return 1;
5224 }
5225
Mel Gormanef8f2322016-07-28 15:46:05 -07005226 lruvec_init(&pn->lruvec);
5227 pn->usage_in_excess = 0;
5228 pn->on_tree = false;
5229 pn->memcg = memcg;
5230
Johannes Weiner54f72fe2013-07-08 15:59:49 -07005231 memcg->nodeinfo[node] = pn;
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08005232 return 0;
5233}
5234
Mel Gormanef8f2322016-07-28 15:46:05 -07005235static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
KAMEZAWA Hiroyuki1ecaab22008-02-07 00:14:38 -08005236{
Johannes Weiner00f3ca22017-07-06 15:40:52 -07005237 struct mem_cgroup_per_node *pn = memcg->nodeinfo[node];
5238
Michal Hocko4eaf4312018-04-10 16:29:52 -07005239 if (!pn)
5240 return;
5241
Johannes Weinera983b5e2018-01-31 16:16:45 -08005242 free_percpu(pn->lruvec_stat_cpu);
Johannes Weiner815744d2019-06-13 15:55:46 -07005243 free_percpu(pn->lruvec_stat_local);
Johannes Weiner00f3ca22017-07-06 15:40:52 -07005244 kfree(pn);
KAMEZAWA Hiroyuki1ecaab22008-02-07 00:14:38 -08005245}
5246
Tahsin Erdogan40e952f2017-03-09 16:17:26 -08005247static void __mem_cgroup_free(struct mem_cgroup *memcg)
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005248{
5249 int node;
5250
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005251 for_each_node(node)
Mel Gormanef8f2322016-07-28 15:46:05 -07005252 free_mem_cgroup_per_node_info(memcg, node);
Chris Down871789d2019-05-14 15:46:57 -07005253 free_percpu(memcg->vmstats_percpu);
Johannes Weiner815744d2019-06-13 15:55:46 -07005254 free_percpu(memcg->vmstats_local);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005255 kfree(memcg);
5256}
5257
Tahsin Erdogan40e952f2017-03-09 16:17:26 -08005258static void mem_cgroup_free(struct mem_cgroup *memcg)
5259{
5260 memcg_wb_domain_exit(memcg);
Shakeel Butt7961eee2019-11-05 21:16:21 -08005261 /*
5262 * Flush percpu vmstats and vmevents to guarantee the value correctness
5263 * on parent's and all ancestor levels.
5264 */
Roman Gushchin4a87e2a2020-01-13 16:29:16 -08005265 memcg_flush_percpu_vmstats(memcg);
Shakeel Butt7961eee2019-11-05 21:16:21 -08005266 memcg_flush_percpu_vmevents(memcg);
Tahsin Erdogan40e952f2017-03-09 16:17:26 -08005267 __mem_cgroup_free(memcg);
5268}
5269
KAMEZAWA Hiroyuki33327942008-04-29 01:00:24 -07005270static struct mem_cgroup *mem_cgroup_alloc(void)
5271{
Hugh Dickinsd79154b2012-03-21 16:34:18 -07005272 struct mem_cgroup *memcg;
Alexey Dobriyanb9726c22019-03-05 15:48:26 -08005273 unsigned int size;
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005274 int node;
Tejun Heo97b27822019-08-26 09:06:56 -07005275 int __maybe_unused i;
Yafang Shao11d67612020-05-07 18:35:43 -07005276 long error = -ENOMEM;
KAMEZAWA Hiroyuki33327942008-04-29 01:00:24 -07005277
Vladimir Davydov8ff69e22014-01-23 15:52:52 -08005278 size = sizeof(struct mem_cgroup);
5279 size += nr_node_ids * sizeof(struct mem_cgroup_per_node *);
KAMEZAWA Hiroyuki33327942008-04-29 01:00:24 -07005280
Vladimir Davydov8ff69e22014-01-23 15:52:52 -08005281 memcg = kzalloc(size, GFP_KERNEL);
Hugh Dickinsd79154b2012-03-21 16:34:18 -07005282 if (!memcg)
Yafang Shao11d67612020-05-07 18:35:43 -07005283 return ERR_PTR(error);
Dan Carpentere7bbcdf2010-03-23 13:35:12 -07005284
Johannes Weiner73f576c2016-07-20 15:44:57 -07005285 memcg->id.id = idr_alloc(&mem_cgroup_idr, NULL,
5286 1, MEM_CGROUP_ID_MAX,
5287 GFP_KERNEL);
Yafang Shao11d67612020-05-07 18:35:43 -07005288 if (memcg->id.id < 0) {
5289 error = memcg->id.id;
Johannes Weiner73f576c2016-07-20 15:44:57 -07005290 goto fail;
Yafang Shao11d67612020-05-07 18:35:43 -07005291 }
Johannes Weiner73f576c2016-07-20 15:44:57 -07005292
Johannes Weiner815744d2019-06-13 15:55:46 -07005293 memcg->vmstats_local = alloc_percpu(struct memcg_vmstats_percpu);
5294 if (!memcg->vmstats_local)
5295 goto fail;
5296
Chris Down871789d2019-05-14 15:46:57 -07005297 memcg->vmstats_percpu = alloc_percpu(struct memcg_vmstats_percpu);
5298 if (!memcg->vmstats_percpu)
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005299 goto fail;
Pavel Emelianov78fb7462008-02-07 00:13:51 -08005300
Bob Liu3ed28fa2012-01-12 17:19:04 -08005301 for_each_node(node)
Mel Gormanef8f2322016-07-28 15:46:05 -07005302 if (alloc_mem_cgroup_per_node_info(memcg, node))
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005303 goto fail;
Balbir Singhf64c3f52009-09-23 15:56:37 -07005304
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005305 if (memcg_wb_domain_init(memcg, GFP_KERNEL))
5306 goto fail;
Balbir Singh28dbc4b2009-01-07 18:08:05 -08005307
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08005308 INIT_WORK(&memcg->high_work, high_work_func);
Glauber Costad142e3e2013-02-22 16:34:52 -08005309 INIT_LIST_HEAD(&memcg->oom_notify);
Glauber Costad142e3e2013-02-22 16:34:52 -08005310 mutex_init(&memcg->thresholds_lock);
5311 spin_lock_init(&memcg->move_lock);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005312 vmpressure_init(&memcg->vmpressure);
Tejun Heofba94802013-11-22 18:20:43 -05005313 INIT_LIST_HEAD(&memcg->event_list);
5314 spin_lock_init(&memcg->event_list_lock);
Johannes Weinerd886f4e2016-01-20 15:02:47 -08005315 memcg->socket_pressure = jiffies;
Kirill Tkhai84c07d12018-08-17 15:47:25 -07005316#ifdef CONFIG_MEMCG_KMEM
Vladimir Davydov900a38f2014-12-12 16:55:10 -08005317 memcg->kmemcg_id = -1;
Roman Gushchinbf4f0592020-08-06 23:20:49 -07005318 INIT_LIST_HEAD(&memcg->objcg_list);
Vladimir Davydov900a38f2014-12-12 16:55:10 -08005319#endif
Tejun Heo52ebea72015-05-22 17:13:37 -04005320#ifdef CONFIG_CGROUP_WRITEBACK
5321 INIT_LIST_HEAD(&memcg->cgwb_list);
Tejun Heo97b27822019-08-26 09:06:56 -07005322 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5323 memcg->cgwb_frn[i].done =
5324 __WB_COMPLETION_INIT(&memcg_cgwb_frn_waitq);
Tejun Heo52ebea72015-05-22 17:13:37 -04005325#endif
Yang Shi87eaceb2019-09-23 15:38:15 -07005326#ifdef CONFIG_TRANSPARENT_HUGEPAGE
5327 spin_lock_init(&memcg->deferred_split_queue.split_queue_lock);
5328 INIT_LIST_HEAD(&memcg->deferred_split_queue.split_queue);
5329 memcg->deferred_split_queue.split_queue_len = 0;
5330#endif
Johannes Weiner73f576c2016-07-20 15:44:57 -07005331 idr_replace(&mem_cgroup_idr, memcg, memcg->id.id);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005332 return memcg;
5333fail:
Kirill Tkhai7e97de02018-08-02 15:36:01 -07005334 mem_cgroup_id_remove(memcg);
Tahsin Erdogan40e952f2017-03-09 16:17:26 -08005335 __mem_cgroup_free(memcg);
Yafang Shao11d67612020-05-07 18:35:43 -07005336 return ERR_PTR(error);
Glauber Costad142e3e2013-02-22 16:34:52 -08005337}
5338
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005339static struct cgroup_subsys_state * __ref
5340mem_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
Glauber Costad142e3e2013-02-22 16:34:52 -08005341{
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005342 struct mem_cgroup *parent = mem_cgroup_from_css(parent_css);
5343 struct mem_cgroup *memcg;
5344 long error = -ENOMEM;
Glauber Costad142e3e2013-02-22 16:34:52 -08005345
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005346 memcg = mem_cgroup_alloc();
Yafang Shao11d67612020-05-07 18:35:43 -07005347 if (IS_ERR(memcg))
5348 return ERR_CAST(memcg);
Li Zefan4219b2d2013-09-23 16:56:29 +08005349
Jakub Kicinskid1663a92020-06-01 21:49:49 -07005350 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005351 memcg->soft_limit = PAGE_COUNTER_MAX;
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07005352 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005353 if (parent) {
5354 memcg->swappiness = mem_cgroup_swappiness(parent);
5355 memcg->oom_kill_disable = parent->oom_kill_disable;
5356 }
5357 if (parent && parent->use_hierarchy) {
5358 memcg->use_hierarchy = true;
Johannes Weiner3e32cb22014-12-10 15:42:31 -08005359 page_counter_init(&memcg->memory, &parent->memory);
Vladimir Davydov37e84352016-01-20 15:02:56 -08005360 page_counter_init(&memcg->swap, &parent->swap);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08005361 page_counter_init(&memcg->memsw, &parent->memsw);
5362 page_counter_init(&memcg->kmem, &parent->kmem);
Johannes Weiner0db15292016-01-20 15:02:50 -08005363 page_counter_init(&memcg->tcpmem, &parent->tcpmem);
Balbir Singh18f59ea2009-01-07 18:08:07 -08005364 } else {
Johannes Weiner3e32cb22014-12-10 15:42:31 -08005365 page_counter_init(&memcg->memory, NULL);
Vladimir Davydov37e84352016-01-20 15:02:56 -08005366 page_counter_init(&memcg->swap, NULL);
Johannes Weiner3e32cb22014-12-10 15:42:31 -08005367 page_counter_init(&memcg->memsw, NULL);
5368 page_counter_init(&memcg->kmem, NULL);
Johannes Weiner0db15292016-01-20 15:02:50 -08005369 page_counter_init(&memcg->tcpmem, NULL);
Tejun Heo8c7f6ed2012-09-13 12:20:58 -07005370 /*
5371 * Deeper hierachy with use_hierarchy == false doesn't make
5372 * much sense so let cgroup subsystem know about this
5373 * unfortunate state in our controller.
5374 */
Glauber Costad142e3e2013-02-22 16:34:52 -08005375 if (parent != root_mem_cgroup)
Tejun Heo073219e2014-02-08 10:36:58 -05005376 memory_cgrp_subsys.broken_hierarchy = true;
Balbir Singh18f59ea2009-01-07 18:08:07 -08005377 }
Vladimir Davydovd6441632014-01-23 15:53:09 -08005378
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005379 /* The following stuff does not apply to the root */
5380 if (!parent) {
Roman Gushchinfb2f2b02019-07-11 20:56:34 -07005381#ifdef CONFIG_MEMCG_KMEM
5382 INIT_LIST_HEAD(&memcg->kmem_caches);
5383#endif
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005384 root_mem_cgroup = memcg;
5385 return &memcg->css;
5386 }
5387
Vladimir Davydovb313aee2016-03-17 14:18:27 -07005388 error = memcg_online_kmem(memcg);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005389 if (error)
5390 goto fail;
Johannes Weiner127424c2016-01-20 15:02:32 -08005391
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08005392 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
Johannes Weineref129472016-01-14 15:21:34 -08005393 static_branch_inc(&memcg_sockets_enabled_key);
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08005394
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005395 return &memcg->css;
5396fail:
Kirill Tkhai7e97de02018-08-02 15:36:01 -07005397 mem_cgroup_id_remove(memcg);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005398 mem_cgroup_free(memcg);
Yafang Shao11d67612020-05-07 18:35:43 -07005399 return ERR_PTR(error);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005400}
5401
Johannes Weiner73f576c2016-07-20 15:44:57 -07005402static int mem_cgroup_css_online(struct cgroup_subsys_state *css)
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005403{
Vladimir Davydov58fa2a52016-10-07 16:57:29 -07005404 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5405
Kirill Tkhai0a4465d2018-08-17 15:47:37 -07005406 /*
5407 * A memcg must be visible for memcg_expand_shrinker_maps()
5408 * by the time the maps are allocated. So, we allocate maps
5409 * here, when for_each_mem_cgroup() can't skip it.
5410 */
5411 if (memcg_alloc_shrinker_maps(memcg)) {
5412 mem_cgroup_id_remove(memcg);
5413 return -ENOMEM;
5414 }
5415
Johannes Weiner73f576c2016-07-20 15:44:57 -07005416 /* Online state pins memcg ID, memcg ID pins CSS */
Kirill Tkhai1c2d4792018-10-26 15:09:28 -07005417 refcount_set(&memcg->id.ref, 1);
Johannes Weiner73f576c2016-07-20 15:44:57 -07005418 css_get(css);
Johannes Weiner2f7dd7a2014-10-02 16:16:57 -07005419 return 0;
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005420}
5421
Tejun Heoeb954192013-08-08 20:11:23 -04005422static void mem_cgroup_css_offline(struct cgroup_subsys_state *css)
KAMEZAWA Hiroyukidf878fb2008-02-07 00:14:28 -08005423{
Tejun Heoeb954192013-08-08 20:11:23 -04005424 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Tejun Heo3bc942f2013-11-22 18:20:44 -05005425 struct mem_cgroup_event *event, *tmp;
Tejun Heo79bd9812013-11-22 18:20:42 -05005426
5427 /*
5428 * Unregister events and notify userspace.
5429 * Notify userspace about cgroup removing only after rmdir of cgroup
5430 * directory to avoid race between userspace and kernelspace.
5431 */
Tejun Heofba94802013-11-22 18:20:43 -05005432 spin_lock(&memcg->event_list_lock);
5433 list_for_each_entry_safe(event, tmp, &memcg->event_list, list) {
Tejun Heo79bd9812013-11-22 18:20:42 -05005434 list_del_init(&event->list);
5435 schedule_work(&event->remove);
5436 }
Tejun Heofba94802013-11-22 18:20:43 -05005437 spin_unlock(&memcg->event_list_lock);
KAMEZAWA Hiroyukiec64f512009-04-02 16:57:26 -07005438
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005439 page_counter_set_min(&memcg->memory, 0);
Roman Gushchin23067152018-06-07 17:06:22 -07005440 page_counter_set_low(&memcg->memory, 0);
Roman Gushchin63677c742017-09-06 16:21:47 -07005441
Johannes Weiner567e9ab2016-01-20 15:02:24 -08005442 memcg_offline_kmem(memcg);
Tejun Heo52ebea72015-05-22 17:13:37 -04005443 wb_memcg_offline(memcg);
Johannes Weiner73f576c2016-07-20 15:44:57 -07005444
Roman Gushchin591edfb2018-10-26 15:03:23 -07005445 drain_all_stock(memcg);
5446
Johannes Weiner73f576c2016-07-20 15:44:57 -07005447 mem_cgroup_id_put(memcg);
KAMEZAWA Hiroyukidf878fb2008-02-07 00:14:28 -08005448}
5449
Vladimir Davydov6df38682015-12-29 14:54:10 -08005450static void mem_cgroup_css_released(struct cgroup_subsys_state *css)
5451{
5452 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5453
5454 invalidate_reclaim_iterators(memcg);
5455}
5456
Tejun Heoeb954192013-08-08 20:11:23 -04005457static void mem_cgroup_css_free(struct cgroup_subsys_state *css)
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005458{
Tejun Heoeb954192013-08-08 20:11:23 -04005459 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
Tejun Heo97b27822019-08-26 09:06:56 -07005460 int __maybe_unused i;
Daisuke Nishimurac268e992009-01-15 13:51:13 -08005461
Tejun Heo97b27822019-08-26 09:06:56 -07005462#ifdef CONFIG_CGROUP_WRITEBACK
5463 for (i = 0; i < MEMCG_CGWB_FRN_CNT; i++)
5464 wb_wait_for_completion(&memcg->cgwb_frn[i].done);
5465#endif
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08005466 if (cgroup_subsys_on_dfl(memory_cgrp_subsys) && !cgroup_memory_nosocket)
Johannes Weineref129472016-01-14 15:21:34 -08005467 static_branch_dec(&memcg_sockets_enabled_key);
Johannes Weiner3893e302016-01-20 15:02:29 -08005468
Johannes Weiner0db15292016-01-20 15:02:50 -08005469 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && memcg->tcpmem_active)
Vladimir Davydovd55f90b2016-01-20 15:02:44 -08005470 static_branch_dec(&memcg_sockets_enabled_key);
Johannes Weiner3893e302016-01-20 15:02:29 -08005471
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005472 vmpressure_cleanup(&memcg->vmpressure);
5473 cancel_work_sync(&memcg->high_work);
5474 mem_cgroup_remove_from_trees(memcg);
Kirill Tkhai0a4465d2018-08-17 15:47:37 -07005475 memcg_free_shrinker_maps(memcg);
Johannes Weinerd886f4e2016-01-20 15:02:47 -08005476 memcg_free_kmem(memcg);
Johannes Weiner0b8f73e2016-01-20 15:02:53 -08005477 mem_cgroup_free(memcg);
Balbir Singh8cdea7c2008-02-07 00:13:50 -08005478}
5479
Tejun Heo1ced9532014-07-08 18:02:57 -04005480/**
5481 * mem_cgroup_css_reset - reset the states of a mem_cgroup
5482 * @css: the target css
5483 *
5484 * Reset the states of the mem_cgroup associated with @css. This is
5485 * invoked when the userland requests disabling on the default hierarchy
5486 * but the memcg is pinned through dependency. The memcg should stop
5487 * applying policies and should revert to the vanilla state as it may be
5488 * made visible again.
5489 *
5490 * The current implementation only resets the essential configurations.
5491 * This needs to be expanded to cover all the visible parts.
5492 */
5493static void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
5494{
5495 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
5496
Roman Gushchinbbec2e12018-06-07 17:06:18 -07005497 page_counter_set_max(&memcg->memory, PAGE_COUNTER_MAX);
5498 page_counter_set_max(&memcg->swap, PAGE_COUNTER_MAX);
5499 page_counter_set_max(&memcg->memsw, PAGE_COUNTER_MAX);
5500 page_counter_set_max(&memcg->kmem, PAGE_COUNTER_MAX);
5501 page_counter_set_max(&memcg->tcpmem, PAGE_COUNTER_MAX);
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005502 page_counter_set_min(&memcg->memory, 0);
Roman Gushchin23067152018-06-07 17:06:22 -07005503 page_counter_set_low(&memcg->memory, 0);
Jakub Kicinskid1663a92020-06-01 21:49:49 -07005504 page_counter_set_high(&memcg->memory, PAGE_COUNTER_MAX);
Johannes Weiner24d404d2015-01-08 14:32:35 -08005505 memcg->soft_limit = PAGE_COUNTER_MAX;
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07005506 page_counter_set_high(&memcg->swap, PAGE_COUNTER_MAX);
Tejun Heo2529bb32015-05-22 18:23:34 -04005507 memcg_wb_domain_size_changed(memcg);
Tejun Heo1ced9532014-07-08 18:02:57 -04005508}
5509
Daisuke Nishimura02491442010-03-10 15:22:17 -08005510#ifdef CONFIG_MMU
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005511/* Handlers for move charge at task migration. */
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005512static int mem_cgroup_do_precharge(unsigned long count)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005513{
Johannes Weiner05b84302014-08-06 16:05:59 -07005514 int ret;
Johannes Weiner9476db92014-08-06 16:05:55 -07005515
Mel Gormand0164ad2015-11-06 16:28:21 -08005516 /* Try a single bulk charge without reclaim first, kswapd may wake */
5517 ret = try_charge(mc.to, GFP_KERNEL & ~__GFP_DIRECT_RECLAIM, count);
Johannes Weiner9476db92014-08-06 16:05:55 -07005518 if (!ret) {
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005519 mc.precharge += count;
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005520 return ret;
5521 }
Johannes Weiner9476db92014-08-06 16:05:55 -07005522
David Rientjes36745342017-01-24 15:18:10 -08005523 /* Try charges one by one with reclaim, but do not retry */
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005524 while (count--) {
David Rientjes36745342017-01-24 15:18:10 -08005525 ret = try_charge(mc.to, GFP_KERNEL | __GFP_NORETRY, 1);
KAMEZAWA Hiroyuki38c5d722012-01-12 17:19:01 -08005526 if (ret)
KAMEZAWA Hiroyuki38c5d722012-01-12 17:19:01 -08005527 return ret;
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005528 mc.precharge++;
Johannes Weiner9476db92014-08-06 16:05:55 -07005529 cond_resched();
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005530 }
Johannes Weiner9476db92014-08-06 16:05:55 -07005531 return 0;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005532}
5533
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005534union mc_target {
5535 struct page *page;
Daisuke Nishimura02491442010-03-10 15:22:17 -08005536 swp_entry_t ent;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005537};
5538
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005539enum mc_target_type {
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07005540 MC_TARGET_NONE = 0,
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005541 MC_TARGET_PAGE,
Daisuke Nishimura02491442010-03-10 15:22:17 -08005542 MC_TARGET_SWAP,
Jérôme Glissec733a822017-09-08 16:11:54 -07005543 MC_TARGET_DEVICE,
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005544};
5545
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005546static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
5547 unsigned long addr, pte_t ptent)
5548{
Christoph Hellwig25b29952019-06-13 22:50:49 +02005549 struct page *page = vm_normal_page(vma, addr, ptent);
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005550
5551 if (!page || !page_mapped(page))
5552 return NULL;
5553 if (PageAnon(page)) {
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08005554 if (!(mc.flags & MOVE_ANON))
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005555 return NULL;
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08005556 } else {
5557 if (!(mc.flags & MOVE_FILE))
5558 return NULL;
5559 }
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005560 if (!get_page_unless_zero(page))
5561 return NULL;
5562
5563 return page;
5564}
5565
Jérôme Glissec733a822017-09-08 16:11:54 -07005566#if defined(CONFIG_SWAP) || defined(CONFIG_DEVICE_PRIVATE)
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005567static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
Li RongQing48406ef2016-07-26 15:22:14 -07005568 pte_t ptent, swp_entry_t *entry)
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005569{
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005570 struct page *page = NULL;
5571 swp_entry_t ent = pte_to_swp_entry(ptent);
5572
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08005573 if (!(mc.flags & MOVE_ANON) || non_swap_entry(ent))
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005574 return NULL;
Jérôme Glissec733a822017-09-08 16:11:54 -07005575
5576 /*
5577 * Handle MEMORY_DEVICE_PRIVATE which are ZONE_DEVICE page belonging to
5578 * a device and because they are not accessible by CPU they are store
5579 * as special swap entry in the CPU page table.
5580 */
5581 if (is_device_private_entry(ent)) {
5582 page = device_private_entry_to_page(ent);
5583 /*
5584 * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have
5585 * a refcount of 1 when free (unlike normal page)
5586 */
5587 if (!page_ref_add_unless(page, 1, 1))
5588 return NULL;
5589 return page;
5590 }
5591
KAMEZAWA Hiroyuki4b913552012-05-29 15:06:51 -07005592 /*
5593 * Because lookup_swap_cache() updates some statistics counter,
5594 * we call find_get_page() with swapper_space directly.
5595 */
Huang Yingf6ab1f72016-10-07 17:00:21 -07005596 page = find_get_page(swap_address_space(ent), swp_offset(ent));
Johannes Weiner2d1c4982020-06-03 16:02:14 -07005597 entry->val = ent.val;
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005598
5599 return page;
5600}
KAMEZAWA Hiroyuki4b913552012-05-29 15:06:51 -07005601#else
5602static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
Li RongQing48406ef2016-07-26 15:22:14 -07005603 pte_t ptent, swp_entry_t *entry)
KAMEZAWA Hiroyuki4b913552012-05-29 15:06:51 -07005604{
5605 return NULL;
5606}
5607#endif
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005608
Daisuke Nishimura87946a72010-05-26 14:42:39 -07005609static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
5610 unsigned long addr, pte_t ptent, swp_entry_t *entry)
5611{
5612 struct page *page = NULL;
Daisuke Nishimura87946a72010-05-26 14:42:39 -07005613 struct address_space *mapping;
5614 pgoff_t pgoff;
5615
5616 if (!vma->vm_file) /* anonymous vma */
5617 return NULL;
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08005618 if (!(mc.flags & MOVE_FILE))
Daisuke Nishimura87946a72010-05-26 14:42:39 -07005619 return NULL;
5620
Daisuke Nishimura87946a72010-05-26 14:42:39 -07005621 mapping = vma->vm_file->f_mapping;
Kirill A. Shutemov0661a332015-02-10 14:10:04 -08005622 pgoff = linear_page_index(vma, addr);
Daisuke Nishimura87946a72010-05-26 14:42:39 -07005623
5624 /* page is moved even if it's not RSS of this task(page-faulted). */
Hugh Dickinsaa3b1892011-08-03 16:21:24 -07005625#ifdef CONFIG_SWAP
5626 /* shmem/tmpfs may report page out on swap: account for that too. */
Johannes Weiner139b6a62014-05-06 12:50:05 -07005627 if (shmem_mapping(mapping)) {
5628 page = find_get_entry(mapping, pgoff);
Matthew Wilcox3159f942017-11-03 13:30:42 -04005629 if (xa_is_value(page)) {
Johannes Weiner139b6a62014-05-06 12:50:05 -07005630 swp_entry_t swp = radix_to_swp_entry(page);
Johannes Weiner2d1c4982020-06-03 16:02:14 -07005631 *entry = swp;
Huang Yingf6ab1f72016-10-07 17:00:21 -07005632 page = find_get_page(swap_address_space(swp),
5633 swp_offset(swp));
Johannes Weiner139b6a62014-05-06 12:50:05 -07005634 }
5635 } else
5636 page = find_get_page(mapping, pgoff);
5637#else
5638 page = find_get_page(mapping, pgoff);
Hugh Dickinsaa3b1892011-08-03 16:21:24 -07005639#endif
Daisuke Nishimura87946a72010-05-26 14:42:39 -07005640 return page;
5641}
5642
Chen Gangb1b0dea2015-04-14 15:47:35 -07005643/**
5644 * mem_cgroup_move_account - move account of the page
5645 * @page: the page
Li RongQing25843c22016-07-26 15:26:56 -07005646 * @compound: charge the page as compound or small page
Chen Gangb1b0dea2015-04-14 15:47:35 -07005647 * @from: mem_cgroup which the page is moved from.
5648 * @to: mem_cgroup which the page is moved to. @from != @to.
5649 *
Kirill A. Shutemov3ac808f2016-01-15 16:53:07 -08005650 * The caller must make sure the page is not on LRU (isolate_page() is useful.)
Chen Gangb1b0dea2015-04-14 15:47:35 -07005651 *
5652 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
5653 * from old cgroup.
5654 */
5655static int mem_cgroup_move_account(struct page *page,
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08005656 bool compound,
Chen Gangb1b0dea2015-04-14 15:47:35 -07005657 struct mem_cgroup *from,
5658 struct mem_cgroup *to)
5659{
Konstantin Khlebnikovae8af432019-10-18 20:20:11 -07005660 struct lruvec *from_vec, *to_vec;
5661 struct pglist_data *pgdat;
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08005662 unsigned int nr_pages = compound ? hpage_nr_pages(page) : 1;
Chen Gangb1b0dea2015-04-14 15:47:35 -07005663 int ret;
5664
5665 VM_BUG_ON(from == to);
5666 VM_BUG_ON_PAGE(PageLRU(page), page);
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08005667 VM_BUG_ON(compound && !PageTransHuge(page));
Chen Gangb1b0dea2015-04-14 15:47:35 -07005668
5669 /*
Johannes Weiner6a93ca82016-03-15 14:57:19 -07005670 * Prevent mem_cgroup_migrate() from looking at
Hugh Dickins45637ba2015-11-05 18:49:40 -08005671 * page->mem_cgroup of its source page while we change it.
Chen Gangb1b0dea2015-04-14 15:47:35 -07005672 */
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08005673 ret = -EBUSY;
Chen Gangb1b0dea2015-04-14 15:47:35 -07005674 if (!trylock_page(page))
5675 goto out;
5676
5677 ret = -EINVAL;
5678 if (page->mem_cgroup != from)
5679 goto out_unlock;
5680
Konstantin Khlebnikovae8af432019-10-18 20:20:11 -07005681 pgdat = page_pgdat(page);
Johannes Weiner867e5e12019-11-30 17:55:34 -08005682 from_vec = mem_cgroup_lruvec(from, pgdat);
5683 to_vec = mem_cgroup_lruvec(to, pgdat);
Konstantin Khlebnikovae8af432019-10-18 20:20:11 -07005684
Johannes Weinerabb242f2020-06-03 16:01:28 -07005685 lock_page_memcg(page);
Chen Gangb1b0dea2015-04-14 15:47:35 -07005686
Johannes Weinerbe5d0a72020-06-03 16:01:57 -07005687 if (PageAnon(page)) {
5688 if (page_mapped(page)) {
5689 __mod_lruvec_state(from_vec, NR_ANON_MAPPED, -nr_pages);
5690 __mod_lruvec_state(to_vec, NR_ANON_MAPPED, nr_pages);
Johannes Weiner468c3982020-06-03 16:02:01 -07005691 if (PageTransHuge(page)) {
5692 __mod_lruvec_state(from_vec, NR_ANON_THPS,
5693 -nr_pages);
5694 __mod_lruvec_state(to_vec, NR_ANON_THPS,
5695 nr_pages);
5696 }
5697
Johannes Weinerbe5d0a72020-06-03 16:01:57 -07005698 }
5699 } else {
Johannes Weiner0d1c2072020-06-03 16:01:54 -07005700 __mod_lruvec_state(from_vec, NR_FILE_PAGES, -nr_pages);
5701 __mod_lruvec_state(to_vec, NR_FILE_PAGES, nr_pages);
5702
5703 if (PageSwapBacked(page)) {
5704 __mod_lruvec_state(from_vec, NR_SHMEM, -nr_pages);
5705 __mod_lruvec_state(to_vec, NR_SHMEM, nr_pages);
5706 }
5707
Johannes Weiner49e50d22020-06-03 16:01:47 -07005708 if (page_mapped(page)) {
5709 __mod_lruvec_state(from_vec, NR_FILE_MAPPED, -nr_pages);
5710 __mod_lruvec_state(to_vec, NR_FILE_MAPPED, nr_pages);
5711 }
Chen Gangb1b0dea2015-04-14 15:47:35 -07005712
Johannes Weiner49e50d22020-06-03 16:01:47 -07005713 if (PageDirty(page)) {
5714 struct address_space *mapping = page_mapping(page);
Greg Thelenc4843a72015-05-22 17:13:16 -04005715
Johannes Weiner49e50d22020-06-03 16:01:47 -07005716 if (mapping_cap_account_dirty(mapping)) {
5717 __mod_lruvec_state(from_vec, NR_FILE_DIRTY,
5718 -nr_pages);
5719 __mod_lruvec_state(to_vec, NR_FILE_DIRTY,
5720 nr_pages);
5721 }
Greg Thelenc4843a72015-05-22 17:13:16 -04005722 }
5723 }
5724
Chen Gangb1b0dea2015-04-14 15:47:35 -07005725 if (PageWriteback(page)) {
Konstantin Khlebnikovae8af432019-10-18 20:20:11 -07005726 __mod_lruvec_state(from_vec, NR_WRITEBACK, -nr_pages);
5727 __mod_lruvec_state(to_vec, NR_WRITEBACK, nr_pages);
Chen Gangb1b0dea2015-04-14 15:47:35 -07005728 }
5729
5730 /*
Johannes Weinerabb242f2020-06-03 16:01:28 -07005731 * All state has been migrated, let's switch to the new memcg.
5732 *
Chen Gangb1b0dea2015-04-14 15:47:35 -07005733 * It is safe to change page->mem_cgroup here because the page
Johannes Weinerabb242f2020-06-03 16:01:28 -07005734 * is referenced, charged, isolated, and locked: we can't race
5735 * with (un)charging, migration, LRU putback, or anything else
5736 * that would rely on a stable page->mem_cgroup.
5737 *
5738 * Note that lock_page_memcg is a memcg lock, not a page lock,
5739 * to save space. As soon as we switch page->mem_cgroup to a
5740 * new memcg that isn't locked, the above state can change
5741 * concurrently again. Make sure we're truly done with it.
Chen Gangb1b0dea2015-04-14 15:47:35 -07005742 */
Johannes Weinerabb242f2020-06-03 16:01:28 -07005743 smp_mb();
Chen Gangb1b0dea2015-04-14 15:47:35 -07005744
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07005745 css_get(&to->css);
5746 css_put(&from->css);
5747
5748 page->mem_cgroup = to;
Yang Shi87eaceb2019-09-23 15:38:15 -07005749
Johannes Weinerabb242f2020-06-03 16:01:28 -07005750 __unlock_page_memcg(from);
Chen Gangb1b0dea2015-04-14 15:47:35 -07005751
5752 ret = 0;
5753
5754 local_irq_disable();
Johannes Weiner3fba69a2020-06-03 16:01:31 -07005755 mem_cgroup_charge_statistics(to, page, nr_pages);
Chen Gangb1b0dea2015-04-14 15:47:35 -07005756 memcg_check_events(to, page);
Johannes Weiner3fba69a2020-06-03 16:01:31 -07005757 mem_cgroup_charge_statistics(from, page, -nr_pages);
Chen Gangb1b0dea2015-04-14 15:47:35 -07005758 memcg_check_events(from, page);
5759 local_irq_enable();
5760out_unlock:
5761 unlock_page(page);
5762out:
5763 return ret;
5764}
5765
Li RongQing7cf78062016-05-27 14:27:46 -07005766/**
5767 * get_mctgt_type - get target type of moving charge
5768 * @vma: the vma the pte to be checked belongs
5769 * @addr: the address corresponding to the pte to be checked
5770 * @ptent: the pte to be checked
5771 * @target: the pointer the target page or swap ent will be stored(can be NULL)
5772 *
5773 * Returns
5774 * 0(MC_TARGET_NONE): if the pte is not a target for move charge.
5775 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
5776 * move charge. if @target is not NULL, the page is stored in target->page
5777 * with extra refcnt got(Callers should handle it).
5778 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
5779 * target for charge migration. if @target is not NULL, the entry is stored
5780 * in target->ent.
Christoph Hellwig25b29952019-06-13 22:50:49 +02005781 * 3(MC_TARGET_DEVICE): like MC_TARGET_PAGE but page is MEMORY_DEVICE_PRIVATE
5782 * (so ZONE_DEVICE page and thus not on the lru).
Jérôme Glissedf6ad692017-09-08 16:12:24 -07005783 * For now we such page is charge like a regular page would be as for all
5784 * intent and purposes it is just special memory taking the place of a
5785 * regular page.
Jérôme Glissec733a822017-09-08 16:11:54 -07005786 *
5787 * See Documentations/vm/hmm.txt and include/linux/hmm.h
Li RongQing7cf78062016-05-27 14:27:46 -07005788 *
5789 * Called with pte lock held.
5790 */
5791
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07005792static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005793 unsigned long addr, pte_t ptent, union mc_target *target)
5794{
Daisuke Nishimura02491442010-03-10 15:22:17 -08005795 struct page *page = NULL;
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07005796 enum mc_target_type ret = MC_TARGET_NONE;
Daisuke Nishimura02491442010-03-10 15:22:17 -08005797 swp_entry_t ent = { .val = 0 };
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005798
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005799 if (pte_present(ptent))
5800 page = mc_handle_present_pte(vma, addr, ptent);
5801 else if (is_swap_pte(ptent))
Li RongQing48406ef2016-07-26 15:22:14 -07005802 page = mc_handle_swap_pte(vma, ptent, &ent);
Kirill A. Shutemov0661a332015-02-10 14:10:04 -08005803 else if (pte_none(ptent))
Daisuke Nishimura87946a72010-05-26 14:42:39 -07005804 page = mc_handle_file_pte(vma, addr, ptent, &ent);
Daisuke Nishimura90254a62010-05-26 14:42:38 -07005805
5806 if (!page && !ent.val)
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07005807 return ret;
Daisuke Nishimura02491442010-03-10 15:22:17 -08005808 if (page) {
Daisuke Nishimura02491442010-03-10 15:22:17 -08005809 /*
Johannes Weiner0a31bc92014-08-08 14:19:22 -07005810 * Do only loose check w/o serialization.
Johannes Weiner1306a852014-12-10 15:44:52 -08005811 * mem_cgroup_move_account() checks the page is valid or
Johannes Weiner0a31bc92014-08-08 14:19:22 -07005812 * not under LRU exclusion.
Daisuke Nishimura02491442010-03-10 15:22:17 -08005813 */
Johannes Weiner1306a852014-12-10 15:44:52 -08005814 if (page->mem_cgroup == mc.from) {
Daisuke Nishimura02491442010-03-10 15:22:17 -08005815 ret = MC_TARGET_PAGE;
Christoph Hellwig25b29952019-06-13 22:50:49 +02005816 if (is_device_private_page(page))
Jérôme Glissec733a822017-09-08 16:11:54 -07005817 ret = MC_TARGET_DEVICE;
Daisuke Nishimura02491442010-03-10 15:22:17 -08005818 if (target)
5819 target->page = page;
5820 }
5821 if (!ret || !target)
5822 put_page(page);
5823 }
Huang Ying3e14a572017-09-06 16:22:37 -07005824 /*
5825 * There is a swap entry and a page doesn't exist or isn't charged.
5826 * But we cannot move a tail-page in a THP.
5827 */
5828 if (ent.val && !ret && (!page || !PageTransCompound(page)) &&
Li Zefan34c00c32013-09-23 16:56:01 +08005829 mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
KAMEZAWA Hiroyuki7f0f1542010-05-11 14:06:58 -07005830 ret = MC_TARGET_SWAP;
5831 if (target)
5832 target->ent = ent;
Daisuke Nishimura02491442010-03-10 15:22:17 -08005833 }
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005834 return ret;
5835}
5836
Naoya Horiguchi12724852012-03-21 16:34:28 -07005837#ifdef CONFIG_TRANSPARENT_HUGEPAGE
5838/*
Huang Yingd6810d72017-09-06 16:22:45 -07005839 * We don't consider PMD mapped swapping or file mapped pages because THP does
5840 * not support them for now.
Naoya Horiguchi12724852012-03-21 16:34:28 -07005841 * Caller should make sure that pmd_trans_huge(pmd) is true.
5842 */
5843static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5844 unsigned long addr, pmd_t pmd, union mc_target *target)
5845{
5846 struct page *page = NULL;
Naoya Horiguchi12724852012-03-21 16:34:28 -07005847 enum mc_target_type ret = MC_TARGET_NONE;
5848
Zi Yan84c3fc42017-09-08 16:11:01 -07005849 if (unlikely(is_swap_pmd(pmd))) {
5850 VM_BUG_ON(thp_migration_supported() &&
5851 !is_pmd_migration_entry(pmd));
5852 return ret;
5853 }
Naoya Horiguchi12724852012-03-21 16:34:28 -07005854 page = pmd_page(pmd);
Sasha Levin309381fea2014-01-23 15:52:54 -08005855 VM_BUG_ON_PAGE(!page || !PageHead(page), page);
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08005856 if (!(mc.flags & MOVE_ANON))
Naoya Horiguchi12724852012-03-21 16:34:28 -07005857 return ret;
Johannes Weiner1306a852014-12-10 15:44:52 -08005858 if (page->mem_cgroup == mc.from) {
Naoya Horiguchi12724852012-03-21 16:34:28 -07005859 ret = MC_TARGET_PAGE;
5860 if (target) {
5861 get_page(page);
5862 target->page = page;
5863 }
5864 }
5865 return ret;
5866}
5867#else
5868static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
5869 unsigned long addr, pmd_t pmd, union mc_target *target)
5870{
5871 return MC_TARGET_NONE;
5872}
5873#endif
5874
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005875static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
5876 unsigned long addr, unsigned long end,
5877 struct mm_walk *walk)
5878{
Naoya Horiguchi26bcd642015-02-11 15:27:57 -08005879 struct vm_area_struct *vma = walk->vma;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005880 pte_t *pte;
5881 spinlock_t *ptl;
5882
Kirill A. Shutemovb6ec57f2016-01-21 16:40:25 -08005883 ptl = pmd_trans_huge_lock(pmd, vma);
5884 if (ptl) {
Jérôme Glissec733a822017-09-08 16:11:54 -07005885 /*
5886 * Note their can not be MC_TARGET_DEVICE for now as we do not
Christoph Hellwig25b29952019-06-13 22:50:49 +02005887 * support transparent huge page with MEMORY_DEVICE_PRIVATE but
5888 * this might change.
Jérôme Glissec733a822017-09-08 16:11:54 -07005889 */
Naoya Horiguchi12724852012-03-21 16:34:28 -07005890 if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
5891 mc.precharge += HPAGE_PMD_NR;
Kirill A. Shutemovbf929152013-11-14 14:30:54 -08005892 spin_unlock(ptl);
Andrea Arcangeli1a5a9902012-03-21 16:33:42 -07005893 return 0;
Naoya Horiguchi12724852012-03-21 16:34:28 -07005894 }
Dave Hansen03319322011-03-22 16:32:56 -07005895
Andrea Arcangeli45f83ce2012-03-28 14:42:40 -07005896 if (pmd_trans_unstable(pmd))
5897 return 0;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005898 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
5899 for (; addr != end; pte++, addr += PAGE_SIZE)
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07005900 if (get_mctgt_type(vma, addr, *pte, NULL))
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005901 mc.precharge++; /* increment precharge temporarily */
5902 pte_unmap_unlock(pte - 1, ptl);
5903 cond_resched();
5904
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005905 return 0;
5906}
5907
Christoph Hellwig7b86ac32019-08-28 16:19:54 +02005908static const struct mm_walk_ops precharge_walk_ops = {
5909 .pmd_entry = mem_cgroup_count_precharge_pte_range,
5910};
5911
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005912static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
5913{
5914 unsigned long precharge;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005915
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07005916 mmap_read_lock(mm);
Christoph Hellwig7b86ac32019-08-28 16:19:54 +02005917 walk_page_range(mm, 0, mm->highest_vm_end, &precharge_walk_ops, NULL);
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07005918 mmap_read_unlock(mm);
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005919
5920 precharge = mc.precharge;
5921 mc.precharge = 0;
5922
5923 return precharge;
5924}
5925
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005926static int mem_cgroup_precharge_mc(struct mm_struct *mm)
5927{
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08005928 unsigned long precharge = mem_cgroup_count_precharge(mm);
5929
5930 VM_BUG_ON(mc.moving_task);
5931 mc.moving_task = current;
5932 return mem_cgroup_do_precharge(precharge);
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005933}
5934
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08005935/* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
5936static void __mem_cgroup_clear_mc(void)
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005937{
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07005938 struct mem_cgroup *from = mc.from;
5939 struct mem_cgroup *to = mc.to;
5940
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005941 /* we must uncharge all the leftover precharges from mc.to */
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005942 if (mc.precharge) {
Johannes Weiner00501b52014-08-08 14:19:20 -07005943 cancel_charge(mc.to, mc.precharge);
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005944 mc.precharge = 0;
5945 }
5946 /*
5947 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
5948 * we must uncharge here.
5949 */
5950 if (mc.moved_charge) {
Johannes Weiner00501b52014-08-08 14:19:20 -07005951 cancel_charge(mc.from, mc.moved_charge);
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08005952 mc.moved_charge = 0;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005953 }
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08005954 /* we must fixup refcnts and charges */
5955 if (mc.moved_swap) {
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08005956 /* uncharge swap account from the old cgroup */
Johannes Weinerce00a962014-09-05 08:43:57 -04005957 if (!mem_cgroup_is_root(mc.from))
Johannes Weiner3e32cb22014-12-10 15:42:31 -08005958 page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08005959
Vladimir Davydov615d66c2016-08-11 15:33:03 -07005960 mem_cgroup_id_put_many(mc.from, mc.moved_swap);
5961
Johannes Weiner05b84302014-08-06 16:05:59 -07005962 /*
Johannes Weiner3e32cb22014-12-10 15:42:31 -08005963 * we charged both to->memory and to->memsw, so we
5964 * should uncharge to->memory.
Johannes Weiner05b84302014-08-06 16:05:59 -07005965 */
Johannes Weinerce00a962014-09-05 08:43:57 -04005966 if (!mem_cgroup_is_root(mc.to))
Johannes Weiner3e32cb22014-12-10 15:42:31 -08005967 page_counter_uncharge(&mc.to->memory, mc.moved_swap);
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08005968
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08005969 mc.moved_swap = 0;
5970 }
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08005971 memcg_oom_recover(from);
5972 memcg_oom_recover(to);
5973 wake_up_all(&mc.waitq);
5974}
5975
5976static void mem_cgroup_clear_mc(void)
5977{
Tejun Heo264a0ae2016-04-21 19:09:02 -04005978 struct mm_struct *mm = mc.mm;
5979
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08005980 /*
5981 * we must clear moving_task before waking up waiters at the end of
5982 * task migration.
5983 */
5984 mc.moving_task = NULL;
5985 __mem_cgroup_clear_mc();
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07005986 spin_lock(&mc.lock);
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005987 mc.from = NULL;
5988 mc.to = NULL;
Tejun Heo264a0ae2016-04-21 19:09:02 -04005989 mc.mm = NULL;
KAMEZAWA Hiroyuki2bd9bb22010-08-10 18:02:58 -07005990 spin_unlock(&mc.lock);
Tejun Heo264a0ae2016-04-21 19:09:02 -04005991
5992 mmput(mm);
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08005993}
5994
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05005995static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08005996{
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05005997 struct cgroup_subsys_state *css;
Ross Zwislereed67d72015-12-23 14:53:27 -07005998 struct mem_cgroup *memcg = NULL; /* unneeded init to make gcc happy */
Tejun Heo9f2115f2015-09-08 15:01:10 -07005999 struct mem_cgroup *from;
Tejun Heo4530edd2015-09-11 15:00:19 -04006000 struct task_struct *leader, *p;
Tejun Heo9f2115f2015-09-08 15:01:10 -07006001 struct mm_struct *mm;
Johannes Weiner1dfab5a2015-02-11 15:26:09 -08006002 unsigned long move_flags;
Tejun Heo9f2115f2015-09-08 15:01:10 -07006003 int ret = 0;
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006004
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006005 /* charge immigration isn't supported on the default hierarchy */
6006 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo9f2115f2015-09-08 15:01:10 -07006007 return 0;
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006008
Tejun Heo4530edd2015-09-11 15:00:19 -04006009 /*
6010 * Multi-process migrations only happen on the default hierarchy
6011 * where charge immigration is not used. Perform charge
6012 * immigration if @tset contains a leader and whine if there are
6013 * multiple.
6014 */
6015 p = NULL;
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006016 cgroup_taskset_for_each_leader(leader, css, tset) {
Tejun Heo4530edd2015-09-11 15:00:19 -04006017 WARN_ON_ONCE(p);
6018 p = leader;
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006019 memcg = mem_cgroup_from_css(css);
Tejun Heo4530edd2015-09-11 15:00:19 -04006020 }
6021 if (!p)
6022 return 0;
6023
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006024 /*
6025 * We are now commited to this value whatever it is. Changes in this
6026 * tunable will only affect upcoming migrations, not the current one.
6027 * So we need to save it, and keep it going.
6028 */
6029 move_flags = READ_ONCE(memcg->move_charge_at_immigrate);
6030 if (!move_flags)
6031 return 0;
6032
Tejun Heo9f2115f2015-09-08 15:01:10 -07006033 from = mem_cgroup_from_task(p);
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006034
Tejun Heo9f2115f2015-09-08 15:01:10 -07006035 VM_BUG_ON(from == memcg);
Johannes Weiner247b1442014-12-10 15:44:11 -08006036
Tejun Heo9f2115f2015-09-08 15:01:10 -07006037 mm = get_task_mm(p);
6038 if (!mm)
6039 return 0;
6040 /* We move charges only when we move a owner of the mm */
6041 if (mm->owner == p) {
6042 VM_BUG_ON(mc.from);
6043 VM_BUG_ON(mc.to);
6044 VM_BUG_ON(mc.precharge);
6045 VM_BUG_ON(mc.moved_charge);
6046 VM_BUG_ON(mc.moved_swap);
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006047
Tejun Heo9f2115f2015-09-08 15:01:10 -07006048 spin_lock(&mc.lock);
Tejun Heo264a0ae2016-04-21 19:09:02 -04006049 mc.mm = mm;
Tejun Heo9f2115f2015-09-08 15:01:10 -07006050 mc.from = from;
6051 mc.to = memcg;
6052 mc.flags = move_flags;
6053 spin_unlock(&mc.lock);
6054 /* We set mc.moving_task later */
6055
6056 ret = mem_cgroup_precharge_mc(mm);
6057 if (ret)
6058 mem_cgroup_clear_mc();
Tejun Heo264a0ae2016-04-21 19:09:02 -04006059 } else {
6060 mmput(mm);
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006061 }
6062 return ret;
6063}
6064
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006065static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006066{
Johannes Weiner4e2f2452014-12-10 15:44:08 -08006067 if (mc.to)
6068 mem_cgroup_clear_mc();
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006069}
6070
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006071static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6072 unsigned long addr, unsigned long end,
6073 struct mm_walk *walk)
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006074{
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006075 int ret = 0;
Naoya Horiguchi26bcd642015-02-11 15:27:57 -08006076 struct vm_area_struct *vma = walk->vma;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006077 pte_t *pte;
6078 spinlock_t *ptl;
Naoya Horiguchi12724852012-03-21 16:34:28 -07006079 enum mc_target_type target_type;
6080 union mc_target target;
6081 struct page *page;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006082
Kirill A. Shutemovb6ec57f2016-01-21 16:40:25 -08006083 ptl = pmd_trans_huge_lock(pmd, vma);
6084 if (ptl) {
Hugh Dickins62ade862012-05-18 11:28:34 -07006085 if (mc.precharge < HPAGE_PMD_NR) {
Kirill A. Shutemovbf929152013-11-14 14:30:54 -08006086 spin_unlock(ptl);
Naoya Horiguchi12724852012-03-21 16:34:28 -07006087 return 0;
6088 }
6089 target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6090 if (target_type == MC_TARGET_PAGE) {
6091 page = target.page;
6092 if (!isolate_lru_page(page)) {
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08006093 if (!mem_cgroup_move_account(page, true,
Johannes Weiner1306a852014-12-10 15:44:52 -08006094 mc.from, mc.to)) {
Naoya Horiguchi12724852012-03-21 16:34:28 -07006095 mc.precharge -= HPAGE_PMD_NR;
6096 mc.moved_charge += HPAGE_PMD_NR;
6097 }
6098 putback_lru_page(page);
6099 }
6100 put_page(page);
Jérôme Glissec733a822017-09-08 16:11:54 -07006101 } else if (target_type == MC_TARGET_DEVICE) {
6102 page = target.page;
6103 if (!mem_cgroup_move_account(page, true,
6104 mc.from, mc.to)) {
6105 mc.precharge -= HPAGE_PMD_NR;
6106 mc.moved_charge += HPAGE_PMD_NR;
6107 }
6108 put_page(page);
Naoya Horiguchi12724852012-03-21 16:34:28 -07006109 }
Kirill A. Shutemovbf929152013-11-14 14:30:54 -08006110 spin_unlock(ptl);
Andrea Arcangeli1a5a9902012-03-21 16:33:42 -07006111 return 0;
Naoya Horiguchi12724852012-03-21 16:34:28 -07006112 }
6113
Andrea Arcangeli45f83ce2012-03-28 14:42:40 -07006114 if (pmd_trans_unstable(pmd))
6115 return 0;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006116retry:
6117 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6118 for (; addr != end; addr += PAGE_SIZE) {
6119 pte_t ptent = *(pte++);
Jérôme Glissec733a822017-09-08 16:11:54 -07006120 bool device = false;
Daisuke Nishimura02491442010-03-10 15:22:17 -08006121 swp_entry_t ent;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006122
6123 if (!mc.precharge)
6124 break;
6125
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07006126 switch (get_mctgt_type(vma, addr, ptent, &target)) {
Jérôme Glissec733a822017-09-08 16:11:54 -07006127 case MC_TARGET_DEVICE:
6128 device = true;
Joe Perchese4a9bc52020-04-06 20:08:39 -07006129 fallthrough;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006130 case MC_TARGET_PAGE:
6131 page = target.page;
Kirill A. Shutemov53f92632016-01-15 16:53:42 -08006132 /*
6133 * We can have a part of the split pmd here. Moving it
6134 * can be done but it would be too convoluted so simply
6135 * ignore such a partial THP and keep it in original
6136 * memcg. There should be somebody mapping the head.
6137 */
6138 if (PageTransCompound(page))
6139 goto put;
Jérôme Glissec733a822017-09-08 16:11:54 -07006140 if (!device && isolate_lru_page(page))
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006141 goto put;
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -08006142 if (!mem_cgroup_move_account(page, false,
6143 mc.from, mc.to)) {
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006144 mc.precharge--;
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08006145 /* we uncharge from mc.from later. */
6146 mc.moved_charge++;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006147 }
Jérôme Glissec733a822017-09-08 16:11:54 -07006148 if (!device)
6149 putback_lru_page(page);
Naoya Horiguchi8d32ff82012-03-21 16:34:27 -07006150put: /* get_mctgt_type() gets the page */
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006151 put_page(page);
6152 break;
Daisuke Nishimura02491442010-03-10 15:22:17 -08006153 case MC_TARGET_SWAP:
6154 ent = target.ent;
Hugh Dickinse91cbb42012-05-29 15:06:51 -07006155 if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
Daisuke Nishimura02491442010-03-10 15:22:17 -08006156 mc.precharge--;
Hugh Dickins8d22a932020-07-23 21:15:24 -07006157 mem_cgroup_id_get_many(mc.to, 1);
6158 /* we fixup other refcnts and charges later. */
Daisuke Nishimura483c30b2010-03-10 15:22:18 -08006159 mc.moved_swap++;
6160 }
Daisuke Nishimura02491442010-03-10 15:22:17 -08006161 break;
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006162 default:
6163 break;
6164 }
6165 }
6166 pte_unmap_unlock(pte - 1, ptl);
6167 cond_resched();
6168
6169 if (addr != end) {
6170 /*
6171 * We have consumed all precharges we got in can_attach().
6172 * We try charge one by one, but don't do any additional
6173 * charges to mc.to if we have failed in charge once in attach()
6174 * phase.
6175 */
Daisuke Nishimura854ffa82010-03-10 15:22:15 -08006176 ret = mem_cgroup_do_precharge(1);
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006177 if (!ret)
6178 goto retry;
6179 }
6180
6181 return ret;
6182}
6183
Christoph Hellwig7b86ac32019-08-28 16:19:54 +02006184static const struct mm_walk_ops charge_walk_ops = {
6185 .pmd_entry = mem_cgroup_move_charge_pte_range,
6186};
6187
Tejun Heo264a0ae2016-04-21 19:09:02 -04006188static void mem_cgroup_move_charge(void)
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006189{
Daisuke Nishimura4ffef5f2010-03-10 15:22:14 -08006190 lru_add_drain_all();
Johannes Weiner312722c2014-12-10 15:44:25 -08006191 /*
Johannes Weiner81f8c3a2016-03-15 14:57:04 -07006192 * Signal lock_page_memcg() to take the memcg's move_lock
6193 * while we're moving its pages to another memcg. Then wait
6194 * for already started RCU-only updates to finish.
Johannes Weiner312722c2014-12-10 15:44:25 -08006195 */
6196 atomic_inc(&mc.from->moving_account);
6197 synchronize_rcu();
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08006198retry:
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07006199 if (unlikely(!mmap_read_trylock(mc.mm))) {
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08006200 /*
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07006201 * Someone who are holding the mmap_lock might be waiting in
Daisuke Nishimuradfe076b2011-01-13 15:47:41 -08006202 * waitq. So we cancel all extra charges, wake up all waiters,
6203 * and retry. Because we cancel precharges, we might not be able
6204 * to move enough charges, but moving charge is a best-effort
6205 * feature anyway, so it wouldn't be a big problem.
6206 */
6207 __mem_cgroup_clear_mc();
6208 cond_resched();
6209 goto retry;
6210 }
Naoya Horiguchi26bcd642015-02-11 15:27:57 -08006211 /*
6212 * When we have consumed all precharges and failed in doing
6213 * additional charge, the page walk just aborts.
6214 */
Christoph Hellwig7b86ac32019-08-28 16:19:54 +02006215 walk_page_range(mc.mm, 0, mc.mm->highest_vm_end, &charge_walk_ops,
6216 NULL);
James Morse0247f3f2016-10-07 17:00:12 -07006217
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07006218 mmap_read_unlock(mc.mm);
Johannes Weiner312722c2014-12-10 15:44:25 -08006219 atomic_dec(&mc.from->moving_account);
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006220}
6221
Tejun Heo264a0ae2016-04-21 19:09:02 -04006222static void mem_cgroup_move_task(void)
Balbir Singh67e465a2008-02-07 00:13:54 -08006223{
Tejun Heo264a0ae2016-04-21 19:09:02 -04006224 if (mc.to) {
6225 mem_cgroup_move_charge();
KOSAKI Motohiroa4336582011-06-15 15:08:13 -07006226 mem_cgroup_clear_mc();
Tejun Heo264a0ae2016-04-21 19:09:02 -04006227 }
Balbir Singh67e465a2008-02-07 00:13:54 -08006228}
Daisuke Nishimura5cfb80a2010-03-23 13:35:11 -07006229#else /* !CONFIG_MMU */
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006230static int mem_cgroup_can_attach(struct cgroup_taskset *tset)
Daisuke Nishimura5cfb80a2010-03-23 13:35:11 -07006231{
6232 return 0;
6233}
Tejun Heo1f7dd3e52015-12-03 10:18:21 -05006234static void mem_cgroup_cancel_attach(struct cgroup_taskset *tset)
Daisuke Nishimura5cfb80a2010-03-23 13:35:11 -07006235{
6236}
Tejun Heo264a0ae2016-04-21 19:09:02 -04006237static void mem_cgroup_move_task(void)
Daisuke Nishimura5cfb80a2010-03-23 13:35:11 -07006238{
6239}
6240#endif
Balbir Singh67e465a2008-02-07 00:13:54 -08006241
Tejun Heof00baae2013-04-15 13:41:15 -07006242/*
6243 * Cgroup retains root cgroups across [un]mount cycles making it necessary
Tejun Heoaa6ec292014-07-09 10:08:08 -04006244 * to verify whether we're attached to the default hierarchy on each mount
6245 * attempt.
Tejun Heof00baae2013-04-15 13:41:15 -07006246 */
Tejun Heoeb954192013-08-08 20:11:23 -04006247static void mem_cgroup_bind(struct cgroup_subsys_state *root_css)
Tejun Heof00baae2013-04-15 13:41:15 -07006248{
6249 /*
Tejun Heoaa6ec292014-07-09 10:08:08 -04006250 * use_hierarchy is forced on the default hierarchy. cgroup core
Tejun Heof00baae2013-04-15 13:41:15 -07006251 * guarantees that @root doesn't have any children, so turning it
6252 * on for the root memcg is enough.
6253 */
Tejun Heo9e10a132015-09-18 11:56:28 -04006254 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Vladimir Davydov7feee5902015-03-12 16:26:19 -07006255 root_mem_cgroup->use_hierarchy = true;
6256 else
6257 root_mem_cgroup->use_hierarchy = false;
Tejun Heof00baae2013-04-15 13:41:15 -07006258}
6259
Chris Down677dc972019-03-05 15:45:55 -08006260static int seq_puts_memcg_tunable(struct seq_file *m, unsigned long value)
6261{
6262 if (value == PAGE_COUNTER_MAX)
6263 seq_puts(m, "max\n");
6264 else
6265 seq_printf(m, "%llu\n", (u64)value * PAGE_SIZE);
6266
6267 return 0;
6268}
6269
Johannes Weiner241994ed2015-02-11 15:26:06 -08006270static u64 memory_current_read(struct cgroup_subsys_state *css,
6271 struct cftype *cft)
6272{
Johannes Weinerf5fc3c5d2015-11-05 18:50:23 -08006273 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
6274
6275 return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006276}
6277
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006278static int memory_min_show(struct seq_file *m, void *v)
6279{
Chris Down677dc972019-03-05 15:45:55 -08006280 return seq_puts_memcg_tunable(m,
6281 READ_ONCE(mem_cgroup_from_seq(m)->memory.min));
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006282}
6283
6284static ssize_t memory_min_write(struct kernfs_open_file *of,
6285 char *buf, size_t nbytes, loff_t off)
6286{
6287 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6288 unsigned long min;
6289 int err;
6290
6291 buf = strstrip(buf);
6292 err = page_counter_memparse(buf, "max", &min);
6293 if (err)
6294 return err;
6295
6296 page_counter_set_min(&memcg->memory, min);
6297
6298 return nbytes;
6299}
6300
Johannes Weiner241994ed2015-02-11 15:26:06 -08006301static int memory_low_show(struct seq_file *m, void *v)
6302{
Chris Down677dc972019-03-05 15:45:55 -08006303 return seq_puts_memcg_tunable(m,
6304 READ_ONCE(mem_cgroup_from_seq(m)->memory.low));
Johannes Weiner241994ed2015-02-11 15:26:06 -08006305}
6306
6307static ssize_t memory_low_write(struct kernfs_open_file *of,
6308 char *buf, size_t nbytes, loff_t off)
6309{
6310 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6311 unsigned long low;
6312 int err;
6313
6314 buf = strstrip(buf);
Johannes Weinerd2973692015-02-27 15:52:04 -08006315 err = page_counter_memparse(buf, "max", &low);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006316 if (err)
6317 return err;
6318
Roman Gushchin23067152018-06-07 17:06:22 -07006319 page_counter_set_low(&memcg->memory, low);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006320
6321 return nbytes;
6322}
6323
6324static int memory_high_show(struct seq_file *m, void *v)
6325{
Jakub Kicinskid1663a92020-06-01 21:49:49 -07006326 return seq_puts_memcg_tunable(m,
6327 READ_ONCE(mem_cgroup_from_seq(m)->memory.high));
Johannes Weiner241994ed2015-02-11 15:26:06 -08006328}
6329
6330static ssize_t memory_high_write(struct kernfs_open_file *of,
6331 char *buf, size_t nbytes, loff_t off)
6332{
6333 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
Johannes Weiner8c8c3832019-11-30 17:50:09 -08006334 unsigned int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
6335 bool drained = false;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006336 unsigned long high;
6337 int err;
6338
6339 buf = strstrip(buf);
Johannes Weinerd2973692015-02-27 15:52:04 -08006340 err = page_counter_memparse(buf, "max", &high);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006341 if (err)
6342 return err;
6343
Jakub Kicinskid1663a92020-06-01 21:49:49 -07006344 page_counter_set_high(&memcg->memory, high);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006345
Johannes Weiner8c8c3832019-11-30 17:50:09 -08006346 for (;;) {
6347 unsigned long nr_pages = page_counter_read(&memcg->memory);
6348 unsigned long reclaimed;
Johannes Weiner588083b2016-03-17 14:20:25 -07006349
Johannes Weiner8c8c3832019-11-30 17:50:09 -08006350 if (nr_pages <= high)
6351 break;
6352
6353 if (signal_pending(current))
6354 break;
6355
6356 if (!drained) {
6357 drain_all_stock(memcg);
6358 drained = true;
6359 continue;
6360 }
6361
6362 reclaimed = try_to_free_mem_cgroup_pages(memcg, nr_pages - high,
6363 GFP_KERNEL, true);
6364
6365 if (!reclaimed && !nr_retries--)
6366 break;
6367 }
6368
Johannes Weiner241994ed2015-02-11 15:26:06 -08006369 return nbytes;
6370}
6371
6372static int memory_max_show(struct seq_file *m, void *v)
6373{
Chris Down677dc972019-03-05 15:45:55 -08006374 return seq_puts_memcg_tunable(m,
6375 READ_ONCE(mem_cgroup_from_seq(m)->memory.max));
Johannes Weiner241994ed2015-02-11 15:26:06 -08006376}
6377
6378static ssize_t memory_max_write(struct kernfs_open_file *of,
6379 char *buf, size_t nbytes, loff_t off)
6380{
6381 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
Johannes Weinerb6e6edc2016-03-17 14:20:28 -07006382 unsigned int nr_reclaims = MEM_CGROUP_RECLAIM_RETRIES;
6383 bool drained = false;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006384 unsigned long max;
6385 int err;
6386
6387 buf = strstrip(buf);
Johannes Weinerd2973692015-02-27 15:52:04 -08006388 err = page_counter_memparse(buf, "max", &max);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006389 if (err)
6390 return err;
6391
Roman Gushchinbbec2e12018-06-07 17:06:18 -07006392 xchg(&memcg->memory.max, max);
Johannes Weinerb6e6edc2016-03-17 14:20:28 -07006393
6394 for (;;) {
6395 unsigned long nr_pages = page_counter_read(&memcg->memory);
6396
6397 if (nr_pages <= max)
6398 break;
6399
Johannes Weiner7249c9f2019-11-30 17:50:06 -08006400 if (signal_pending(current))
Johannes Weinerb6e6edc2016-03-17 14:20:28 -07006401 break;
Johannes Weinerb6e6edc2016-03-17 14:20:28 -07006402
6403 if (!drained) {
6404 drain_all_stock(memcg);
6405 drained = true;
6406 continue;
6407 }
6408
6409 if (nr_reclaims) {
6410 if (!try_to_free_mem_cgroup_pages(memcg, nr_pages - max,
6411 GFP_KERNEL, true))
6412 nr_reclaims--;
6413 continue;
6414 }
6415
Johannes Weinere27be242018-04-10 16:29:45 -07006416 memcg_memory_event(memcg, MEMCG_OOM);
Johannes Weinerb6e6edc2016-03-17 14:20:28 -07006417 if (!mem_cgroup_out_of_memory(memcg, GFP_KERNEL, 0))
6418 break;
6419 }
Johannes Weiner241994ed2015-02-11 15:26:06 -08006420
Tejun Heo2529bb32015-05-22 18:23:34 -04006421 memcg_wb_domain_size_changed(memcg);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006422 return nbytes;
6423}
6424
Shakeel Butt1e577f92019-07-11 20:55:55 -07006425static void __memory_events_show(struct seq_file *m, atomic_long_t *events)
6426{
6427 seq_printf(m, "low %lu\n", atomic_long_read(&events[MEMCG_LOW]));
6428 seq_printf(m, "high %lu\n", atomic_long_read(&events[MEMCG_HIGH]));
6429 seq_printf(m, "max %lu\n", atomic_long_read(&events[MEMCG_MAX]));
6430 seq_printf(m, "oom %lu\n", atomic_long_read(&events[MEMCG_OOM]));
6431 seq_printf(m, "oom_kill %lu\n",
6432 atomic_long_read(&events[MEMCG_OOM_KILL]));
6433}
6434
Johannes Weiner241994ed2015-02-11 15:26:06 -08006435static int memory_events_show(struct seq_file *m, void *v)
6436{
Chris Downaa9694b2019-03-05 15:45:52 -08006437 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006438
Shakeel Butt1e577f92019-07-11 20:55:55 -07006439 __memory_events_show(m, memcg->memory_events);
6440 return 0;
6441}
Johannes Weiner241994ed2015-02-11 15:26:06 -08006442
Shakeel Butt1e577f92019-07-11 20:55:55 -07006443static int memory_events_local_show(struct seq_file *m, void *v)
6444{
6445 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
6446
6447 __memory_events_show(m, memcg->memory_events_local);
Johannes Weiner241994ed2015-02-11 15:26:06 -08006448 return 0;
6449}
6450
Johannes Weiner587d9f72016-01-20 15:03:19 -08006451static int memory_stat_show(struct seq_file *m, void *v)
6452{
Chris Downaa9694b2019-03-05 15:45:52 -08006453 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
Johannes Weinerc8713d02019-07-11 20:55:59 -07006454 char *buf;
Johannes Weiner587d9f72016-01-20 15:03:19 -08006455
Johannes Weinerc8713d02019-07-11 20:55:59 -07006456 buf = memory_stat_format(memcg);
6457 if (!buf)
6458 return -ENOMEM;
6459 seq_puts(m, buf);
6460 kfree(buf);
Johannes Weiner587d9f72016-01-20 15:03:19 -08006461 return 0;
6462}
6463
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07006464static int memory_oom_group_show(struct seq_file *m, void *v)
6465{
Chris Downaa9694b2019-03-05 15:45:52 -08006466 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07006467
6468 seq_printf(m, "%d\n", memcg->oom_group);
6469
6470 return 0;
6471}
6472
6473static ssize_t memory_oom_group_write(struct kernfs_open_file *of,
6474 char *buf, size_t nbytes, loff_t off)
6475{
6476 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
6477 int ret, oom_group;
6478
6479 buf = strstrip(buf);
6480 if (!buf)
6481 return -EINVAL;
6482
6483 ret = kstrtoint(buf, 0, &oom_group);
6484 if (ret)
6485 return ret;
6486
6487 if (oom_group != 0 && oom_group != 1)
6488 return -EINVAL;
6489
6490 memcg->oom_group = oom_group;
6491
6492 return nbytes;
6493}
6494
Johannes Weiner241994ed2015-02-11 15:26:06 -08006495static struct cftype memory_files[] = {
6496 {
6497 .name = "current",
Johannes Weinerf5fc3c5d2015-11-05 18:50:23 -08006498 .flags = CFTYPE_NOT_ON_ROOT,
Johannes Weiner241994ed2015-02-11 15:26:06 -08006499 .read_u64 = memory_current_read,
6500 },
6501 {
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006502 .name = "min",
6503 .flags = CFTYPE_NOT_ON_ROOT,
6504 .seq_show = memory_min_show,
6505 .write = memory_min_write,
6506 },
6507 {
Johannes Weiner241994ed2015-02-11 15:26:06 -08006508 .name = "low",
6509 .flags = CFTYPE_NOT_ON_ROOT,
6510 .seq_show = memory_low_show,
6511 .write = memory_low_write,
6512 },
6513 {
6514 .name = "high",
6515 .flags = CFTYPE_NOT_ON_ROOT,
6516 .seq_show = memory_high_show,
6517 .write = memory_high_write,
6518 },
6519 {
6520 .name = "max",
6521 .flags = CFTYPE_NOT_ON_ROOT,
6522 .seq_show = memory_max_show,
6523 .write = memory_max_write,
6524 },
6525 {
6526 .name = "events",
6527 .flags = CFTYPE_NOT_ON_ROOT,
Tejun Heo472912a2015-09-18 18:01:59 -04006528 .file_offset = offsetof(struct mem_cgroup, events_file),
Johannes Weiner241994ed2015-02-11 15:26:06 -08006529 .seq_show = memory_events_show,
6530 },
Johannes Weiner587d9f72016-01-20 15:03:19 -08006531 {
Shakeel Butt1e577f92019-07-11 20:55:55 -07006532 .name = "events.local",
6533 .flags = CFTYPE_NOT_ON_ROOT,
6534 .file_offset = offsetof(struct mem_cgroup, events_local_file),
6535 .seq_show = memory_events_local_show,
6536 },
6537 {
Johannes Weiner587d9f72016-01-20 15:03:19 -08006538 .name = "stat",
Johannes Weiner587d9f72016-01-20 15:03:19 -08006539 .seq_show = memory_stat_show,
6540 },
Roman Gushchin3d8b38e2018-08-21 21:53:54 -07006541 {
6542 .name = "oom.group",
6543 .flags = CFTYPE_NOT_ON_ROOT | CFTYPE_NS_DELEGATABLE,
6544 .seq_show = memory_oom_group_show,
6545 .write = memory_oom_group_write,
6546 },
Johannes Weiner241994ed2015-02-11 15:26:06 -08006547 { } /* terminate */
6548};
6549
Tejun Heo073219e2014-02-08 10:36:58 -05006550struct cgroup_subsys memory_cgrp_subsys = {
Tejun Heo92fb9742012-11-19 08:13:38 -08006551 .css_alloc = mem_cgroup_css_alloc,
Glauber Costad142e3e2013-02-22 16:34:52 -08006552 .css_online = mem_cgroup_css_online,
Tejun Heo92fb9742012-11-19 08:13:38 -08006553 .css_offline = mem_cgroup_css_offline,
Vladimir Davydov6df38682015-12-29 14:54:10 -08006554 .css_released = mem_cgroup_css_released,
Tejun Heo92fb9742012-11-19 08:13:38 -08006555 .css_free = mem_cgroup_css_free,
Tejun Heo1ced9532014-07-08 18:02:57 -04006556 .css_reset = mem_cgroup_css_reset,
Daisuke Nishimura7dc74be2010-03-10 15:22:13 -08006557 .can_attach = mem_cgroup_can_attach,
6558 .cancel_attach = mem_cgroup_cancel_attach,
Tejun Heo264a0ae2016-04-21 19:09:02 -04006559 .post_attach = mem_cgroup_move_task,
Tejun Heof00baae2013-04-15 13:41:15 -07006560 .bind = mem_cgroup_bind,
Johannes Weiner241994ed2015-02-11 15:26:06 -08006561 .dfl_cftypes = memory_files,
6562 .legacy_cftypes = mem_cgroup_legacy_files,
KAMEZAWA Hiroyuki6d12e2d2008-02-07 00:14:31 -08006563 .early_init = 0,
Balbir Singh8cdea7c2008-02-07 00:13:50 -08006564};
KAMEZAWA Hiroyukic0777192009-01-07 18:07:57 -08006565
Johannes Weinerbc50bcc2020-04-01 21:07:03 -07006566/*
6567 * This function calculates an individual cgroup's effective
6568 * protection which is derived from its own memory.min/low, its
6569 * parent's and siblings' settings, as well as the actual memory
6570 * distribution in the tree.
6571 *
6572 * The following rules apply to the effective protection values:
6573 *
6574 * 1. At the first level of reclaim, effective protection is equal to
6575 * the declared protection in memory.min and memory.low.
6576 *
6577 * 2. To enable safe delegation of the protection configuration, at
6578 * subsequent levels the effective protection is capped to the
6579 * parent's effective protection.
6580 *
6581 * 3. To make complex and dynamic subtrees easier to configure, the
6582 * user is allowed to overcommit the declared protection at a given
6583 * level. If that is the case, the parent's effective protection is
6584 * distributed to the children in proportion to how much protection
6585 * they have declared and how much of it they are utilizing.
6586 *
6587 * This makes distribution proportional, but also work-conserving:
6588 * if one cgroup claims much more protection than it uses memory,
6589 * the unused remainder is available to its siblings.
6590 *
6591 * 4. Conversely, when the declared protection is undercommitted at a
6592 * given level, the distribution of the larger parental protection
6593 * budget is NOT proportional. A cgroup's protection from a sibling
6594 * is capped to its own memory.min/low setting.
6595 *
Johannes Weiner8a931f82020-04-01 21:07:07 -07006596 * 5. However, to allow protecting recursive subtrees from each other
6597 * without having to declare each individual cgroup's fixed share
6598 * of the ancestor's claim to protection, any unutilized -
6599 * "floating" - protection from up the tree is distributed in
6600 * proportion to each cgroup's *usage*. This makes the protection
6601 * neutral wrt sibling cgroups and lets them compete freely over
6602 * the shared parental protection budget, but it protects the
6603 * subtree as a whole from neighboring subtrees.
6604 *
6605 * Note that 4. and 5. are not in conflict: 4. is about protecting
6606 * against immediate siblings whereas 5. is about protecting against
6607 * neighboring subtrees.
Johannes Weinerbc50bcc2020-04-01 21:07:03 -07006608 */
6609static unsigned long effective_protection(unsigned long usage,
Johannes Weiner8a931f82020-04-01 21:07:07 -07006610 unsigned long parent_usage,
Johannes Weinerbc50bcc2020-04-01 21:07:03 -07006611 unsigned long setting,
6612 unsigned long parent_effective,
6613 unsigned long siblings_protected)
6614{
6615 unsigned long protected;
Johannes Weiner8a931f82020-04-01 21:07:07 -07006616 unsigned long ep;
Johannes Weinerbc50bcc2020-04-01 21:07:03 -07006617
6618 protected = min(usage, setting);
6619 /*
6620 * If all cgroups at this level combined claim and use more
6621 * protection then what the parent affords them, distribute
6622 * shares in proportion to utilization.
6623 *
6624 * We are using actual utilization rather than the statically
6625 * claimed protection in order to be work-conserving: claimed
6626 * but unused protection is available to siblings that would
6627 * otherwise get a smaller chunk than what they claimed.
6628 */
6629 if (siblings_protected > parent_effective)
6630 return protected * parent_effective / siblings_protected;
6631
6632 /*
6633 * Ok, utilized protection of all children is within what the
6634 * parent affords them, so we know whatever this child claims
6635 * and utilizes is effectively protected.
6636 *
6637 * If there is unprotected usage beyond this value, reclaim
6638 * will apply pressure in proportion to that amount.
6639 *
6640 * If there is unutilized protection, the cgroup will be fully
6641 * shielded from reclaim, but we do return a smaller value for
6642 * protection than what the group could enjoy in theory. This
6643 * is okay. With the overcommit distribution above, effective
6644 * protection is always dependent on how memory is actually
6645 * consumed among the siblings anyway.
6646 */
Johannes Weiner8a931f82020-04-01 21:07:07 -07006647 ep = protected;
6648
6649 /*
6650 * If the children aren't claiming (all of) the protection
6651 * afforded to them by the parent, distribute the remainder in
6652 * proportion to the (unprotected) memory of each cgroup. That
6653 * way, cgroups that aren't explicitly prioritized wrt each
6654 * other compete freely over the allowance, but they are
6655 * collectively protected from neighboring trees.
6656 *
6657 * We're using unprotected memory for the weight so that if
6658 * some cgroups DO claim explicit protection, we don't protect
6659 * the same bytes twice.
Johannes Weinercd324ed2020-06-25 20:30:16 -07006660 *
6661 * Check both usage and parent_usage against the respective
6662 * protected values. One should imply the other, but they
6663 * aren't read atomically - make sure the division is sane.
Johannes Weiner8a931f82020-04-01 21:07:07 -07006664 */
6665 if (!(cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT))
6666 return ep;
Johannes Weinercd324ed2020-06-25 20:30:16 -07006667 if (parent_effective > siblings_protected &&
6668 parent_usage > siblings_protected &&
6669 usage > protected) {
Johannes Weiner8a931f82020-04-01 21:07:07 -07006670 unsigned long unclaimed;
6671
6672 unclaimed = parent_effective - siblings_protected;
6673 unclaimed *= usage - protected;
6674 unclaimed /= parent_usage - siblings_protected;
6675
6676 ep += unclaimed;
6677 }
6678
6679 return ep;
Johannes Weinerbc50bcc2020-04-01 21:07:03 -07006680}
6681
Johannes Weiner241994ed2015-02-11 15:26:06 -08006682/**
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006683 * mem_cgroup_protected - check if memory consumption is in the normal range
Sean Christopherson34c81052017-07-10 15:48:05 -07006684 * @root: the top ancestor of the sub-tree being checked
Johannes Weiner241994ed2015-02-11 15:26:06 -08006685 * @memcg: the memory cgroup to check
6686 *
Roman Gushchin23067152018-06-07 17:06:22 -07006687 * WARNING: This function is not stateless! It can only be used as part
6688 * of a top-down tree iteration, not for isolated queries.
Sean Christopherson34c81052017-07-10 15:48:05 -07006689 *
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006690 * Returns one of the following:
6691 * MEMCG_PROT_NONE: cgroup memory is not protected
6692 * MEMCG_PROT_LOW: cgroup memory is protected as long there is
6693 * an unprotected supply of reclaimable memory from other cgroups.
6694 * MEMCG_PROT_MIN: cgroup memory is protected
Johannes Weiner241994ed2015-02-11 15:26:06 -08006695 */
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006696enum mem_cgroup_protection mem_cgroup_protected(struct mem_cgroup *root,
6697 struct mem_cgroup *memcg)
Johannes Weiner241994ed2015-02-11 15:26:06 -08006698{
Johannes Weiner8a931f82020-04-01 21:07:07 -07006699 unsigned long usage, parent_usage;
Roman Gushchin23067152018-06-07 17:06:22 -07006700 struct mem_cgroup *parent;
6701
Johannes Weiner241994ed2015-02-11 15:26:06 -08006702 if (mem_cgroup_disabled())
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006703 return MEMCG_PROT_NONE;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006704
Sean Christopherson34c81052017-07-10 15:48:05 -07006705 if (!root)
6706 root = root_mem_cgroup;
6707 if (memcg == root)
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006708 return MEMCG_PROT_NONE;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006709
Roman Gushchin23067152018-06-07 17:06:22 -07006710 usage = page_counter_read(&memcg->memory);
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006711 if (!usage)
6712 return MEMCG_PROT_NONE;
Sean Christopherson34c81052017-07-10 15:48:05 -07006713
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006714 parent = parent_mem_cgroup(memcg);
Roman Gushchindf2a4192018-06-14 15:26:17 -07006715 /* No parent means a non-hierarchical mode on v1 memcg */
6716 if (!parent)
6717 return MEMCG_PROT_NONE;
6718
Johannes Weinerbc50bcc2020-04-01 21:07:03 -07006719 if (parent == root) {
Chris Downc3d53202020-04-01 21:07:27 -07006720 memcg->memory.emin = READ_ONCE(memcg->memory.min);
Chris Down03960e32020-06-25 20:30:22 -07006721 memcg->memory.elow = READ_ONCE(memcg->memory.low);
Johannes Weinerbc50bcc2020-04-01 21:07:03 -07006722 goto out;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006723 }
6724
Johannes Weiner8a931f82020-04-01 21:07:07 -07006725 parent_usage = page_counter_read(&parent->memory);
6726
Chris Downb3a78222020-04-01 21:07:33 -07006727 WRITE_ONCE(memcg->memory.emin, effective_protection(usage, parent_usage,
Chris Downc3d53202020-04-01 21:07:27 -07006728 READ_ONCE(memcg->memory.min),
6729 READ_ONCE(parent->memory.emin),
Chris Downb3a78222020-04-01 21:07:33 -07006730 atomic_long_read(&parent->memory.children_min_usage)));
Roman Gushchin23067152018-06-07 17:06:22 -07006731
Chris Downb3a78222020-04-01 21:07:33 -07006732 WRITE_ONCE(memcg->memory.elow, effective_protection(usage, parent_usage,
Chris Down03960e32020-06-25 20:30:22 -07006733 READ_ONCE(memcg->memory.low),
6734 READ_ONCE(parent->memory.elow),
Chris Downb3a78222020-04-01 21:07:33 -07006735 atomic_long_read(&parent->memory.children_low_usage)));
Roman Gushchin23067152018-06-07 17:06:22 -07006736
Johannes Weinerbc50bcc2020-04-01 21:07:03 -07006737out:
6738 if (usage <= memcg->memory.emin)
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006739 return MEMCG_PROT_MIN;
Johannes Weinerbc50bcc2020-04-01 21:07:03 -07006740 else if (usage <= memcg->memory.elow)
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006741 return MEMCG_PROT_LOW;
6742 else
6743 return MEMCG_PROT_NONE;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006744}
6745
Johannes Weiner00501b52014-08-08 14:19:20 -07006746/**
Johannes Weinerf0e45fb2020-06-03 16:02:07 -07006747 * mem_cgroup_charge - charge a newly allocated page to a cgroup
Johannes Weiner00501b52014-08-08 14:19:20 -07006748 * @page: page to charge
6749 * @mm: mm context of the victim
6750 * @gfp_mask: reclaim mode
Johannes Weiner00501b52014-08-08 14:19:20 -07006751 *
6752 * Try to charge @page to the memcg that @mm belongs to, reclaiming
6753 * pages according to @gfp_mask if necessary.
6754 *
Johannes Weinerf0e45fb2020-06-03 16:02:07 -07006755 * Returns 0 on success. Otherwise, an error code is returned.
Johannes Weiner00501b52014-08-08 14:19:20 -07006756 */
Johannes Weinerd9eb1ea2020-06-03 16:02:24 -07006757int mem_cgroup_charge(struct page *page, struct mm_struct *mm, gfp_t gfp_mask)
Johannes Weiner00501b52014-08-08 14:19:20 -07006758{
Johannes Weiner3fba69a2020-06-03 16:01:31 -07006759 unsigned int nr_pages = hpage_nr_pages(page);
Johannes Weiner00501b52014-08-08 14:19:20 -07006760 struct mem_cgroup *memcg = NULL;
Johannes Weiner00501b52014-08-08 14:19:20 -07006761 int ret = 0;
6762
6763 if (mem_cgroup_disabled())
6764 goto out;
6765
6766 if (PageSwapCache(page)) {
Johannes Weiner2d1c4982020-06-03 16:02:14 -07006767 swp_entry_t ent = { .val = page_private(page), };
6768 unsigned short id;
6769
Johannes Weiner00501b52014-08-08 14:19:20 -07006770 /*
6771 * Every swap fault against a single page tries to charge the
6772 * page, bail as early as possible. shmem_unuse() encounters
Johannes Weinereccb52e2020-06-03 16:02:11 -07006773 * already charged pages, too. page->mem_cgroup is protected
6774 * by the page lock, which serializes swap cache removal, which
Johannes Weiner00501b52014-08-08 14:19:20 -07006775 * in turn serializes uncharging.
6776 */
Vladimir Davydove993d902015-09-09 15:35:35 -07006777 VM_BUG_ON_PAGE(!PageLocked(page), page);
Huang Yingabe28952017-09-06 16:22:41 -07006778 if (compound_head(page)->mem_cgroup)
Johannes Weiner00501b52014-08-08 14:19:20 -07006779 goto out;
Vladimir Davydove993d902015-09-09 15:35:35 -07006780
Johannes Weiner2d1c4982020-06-03 16:02:14 -07006781 id = lookup_swap_cgroup_id(ent);
6782 rcu_read_lock();
6783 memcg = mem_cgroup_from_id(id);
6784 if (memcg && !css_tryget_online(&memcg->css))
6785 memcg = NULL;
6786 rcu_read_unlock();
Johannes Weiner00501b52014-08-08 14:19:20 -07006787 }
6788
Johannes Weiner00501b52014-08-08 14:19:20 -07006789 if (!memcg)
6790 memcg = get_mem_cgroup_from_mm(mm);
6791
6792 ret = try_charge(memcg, gfp_mask, nr_pages);
Johannes Weinerf0e45fb2020-06-03 16:02:07 -07006793 if (ret)
6794 goto out_put;
Johannes Weiner00501b52014-08-08 14:19:20 -07006795
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07006796 css_get(&memcg->css);
Johannes Weinerd9eb1ea2020-06-03 16:02:24 -07006797 commit_charge(page, memcg);
Johannes Weiner6abb5a82014-08-08 14:19:33 -07006798
Johannes Weiner6abb5a82014-08-08 14:19:33 -07006799 local_irq_disable();
Johannes Weiner3fba69a2020-06-03 16:01:31 -07006800 mem_cgroup_charge_statistics(memcg, page, nr_pages);
Johannes Weiner6abb5a82014-08-08 14:19:33 -07006801 memcg_check_events(memcg, page);
6802 local_irq_enable();
Johannes Weiner00501b52014-08-08 14:19:20 -07006803
Johannes Weiner2d1c4982020-06-03 16:02:14 -07006804 if (PageSwapCache(page)) {
Johannes Weiner00501b52014-08-08 14:19:20 -07006805 swp_entry_t entry = { .val = page_private(page) };
6806 /*
6807 * The swap entry might not get freed for a long time,
6808 * let's not wait for it. The page already received a
6809 * memory+swap charge, drop the swap entry duplicate.
6810 */
Huang Ying38d8b4e2017-07-06 15:37:18 -07006811 mem_cgroup_uncharge_swap(entry, nr_pages);
Johannes Weiner00501b52014-08-08 14:19:20 -07006812 }
Johannes Weiner00501b52014-08-08 14:19:20 -07006813
Johannes Weinerf0e45fb2020-06-03 16:02:07 -07006814out_put:
6815 css_put(&memcg->css);
6816out:
6817 return ret;
Johannes Weiner3fea5a42020-06-03 16:01:41 -07006818}
6819
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006820struct uncharge_gather {
6821 struct mem_cgroup *memcg;
Johannes Weiner9f762db2020-06-03 16:01:44 -07006822 unsigned long nr_pages;
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006823 unsigned long pgpgout;
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006824 unsigned long nr_kmem;
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006825 struct page *dummy_page;
6826};
6827
6828static inline void uncharge_gather_clear(struct uncharge_gather *ug)
Johannes Weiner747db952014-08-08 14:19:24 -07006829{
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006830 memset(ug, 0, sizeof(*ug));
6831}
6832
6833static void uncharge_batch(const struct uncharge_gather *ug)
6834{
Johannes Weiner747db952014-08-08 14:19:24 -07006835 unsigned long flags;
6836
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006837 if (!mem_cgroup_is_root(ug->memcg)) {
Johannes Weiner9f762db2020-06-03 16:01:44 -07006838 page_counter_uncharge(&ug->memcg->memory, ug->nr_pages);
Johannes Weiner7941d212016-01-14 15:21:23 -08006839 if (do_memsw_account())
Johannes Weiner9f762db2020-06-03 16:01:44 -07006840 page_counter_uncharge(&ug->memcg->memsw, ug->nr_pages);
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006841 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && ug->nr_kmem)
6842 page_counter_uncharge(&ug->memcg->kmem, ug->nr_kmem);
6843 memcg_oom_recover(ug->memcg);
Johannes Weinerce00a962014-09-05 08:43:57 -04006844 }
Johannes Weiner747db952014-08-08 14:19:24 -07006845
6846 local_irq_save(flags);
Johannes Weinerc9019e92018-01-31 16:16:37 -08006847 __count_memcg_events(ug->memcg, PGPGOUT, ug->pgpgout);
Johannes Weiner9f762db2020-06-03 16:01:44 -07006848 __this_cpu_add(ug->memcg->vmstats_percpu->nr_page_events, ug->nr_pages);
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006849 memcg_check_events(ug->memcg, ug->dummy_page);
Johannes Weiner747db952014-08-08 14:19:24 -07006850 local_irq_restore(flags);
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006851}
6852
6853static void uncharge_page(struct page *page, struct uncharge_gather *ug)
6854{
Johannes Weiner9f762db2020-06-03 16:01:44 -07006855 unsigned long nr_pages;
6856
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006857 VM_BUG_ON_PAGE(PageLRU(page), page);
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006858
6859 if (!page->mem_cgroup)
6860 return;
6861
6862 /*
6863 * Nobody should be changing or seriously looking at
6864 * page->mem_cgroup at this point, we have fully
6865 * exclusive access to the page.
6866 */
6867
6868 if (ug->memcg != page->mem_cgroup) {
6869 if (ug->memcg) {
6870 uncharge_batch(ug);
6871 uncharge_gather_clear(ug);
6872 }
6873 ug->memcg = page->mem_cgroup;
6874 }
6875
Johannes Weiner9f762db2020-06-03 16:01:44 -07006876 nr_pages = compound_nr(page);
6877 ug->nr_pages += nr_pages;
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006878
Johannes Weiner9f762db2020-06-03 16:01:44 -07006879 if (!PageKmemcg(page)) {
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006880 ug->pgpgout++;
6881 } else {
Johannes Weiner9f762db2020-06-03 16:01:44 -07006882 ug->nr_kmem += nr_pages;
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006883 __ClearPageKmemcg(page);
6884 }
6885
6886 ug->dummy_page = page;
6887 page->mem_cgroup = NULL;
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07006888 css_put(&ug->memcg->css);
Johannes Weiner747db952014-08-08 14:19:24 -07006889}
6890
6891static void uncharge_list(struct list_head *page_list)
6892{
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006893 struct uncharge_gather ug;
Johannes Weiner747db952014-08-08 14:19:24 -07006894 struct list_head *next;
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006895
6896 uncharge_gather_clear(&ug);
Johannes Weiner747db952014-08-08 14:19:24 -07006897
Johannes Weiner8b592652016-03-17 14:20:31 -07006898 /*
6899 * Note that the list can be a single page->lru; hence the
6900 * do-while loop instead of a simple list_for_each_entry().
6901 */
Johannes Weiner747db952014-08-08 14:19:24 -07006902 next = page_list->next;
6903 do {
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006904 struct page *page;
6905
Johannes Weiner747db952014-08-08 14:19:24 -07006906 page = list_entry(next, struct page, lru);
6907 next = page->lru.next;
6908
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006909 uncharge_page(page, &ug);
Johannes Weiner747db952014-08-08 14:19:24 -07006910 } while (next != page_list);
6911
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006912 if (ug.memcg)
6913 uncharge_batch(&ug);
Johannes Weiner747db952014-08-08 14:19:24 -07006914}
6915
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006916/**
6917 * mem_cgroup_uncharge - uncharge a page
6918 * @page: page to uncharge
6919 *
Johannes Weinerf0e45fb2020-06-03 16:02:07 -07006920 * Uncharge a page previously charged with mem_cgroup_charge().
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006921 */
6922void mem_cgroup_uncharge(struct page *page)
6923{
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006924 struct uncharge_gather ug;
6925
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006926 if (mem_cgroup_disabled())
6927 return;
6928
Johannes Weiner747db952014-08-08 14:19:24 -07006929 /* Don't touch page->lru of any random page, pre-check: */
Johannes Weiner1306a852014-12-10 15:44:52 -08006930 if (!page->mem_cgroup)
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006931 return;
6932
Jérôme Glissea9d5ade2017-09-08 16:11:50 -07006933 uncharge_gather_clear(&ug);
6934 uncharge_page(page, &ug);
6935 uncharge_batch(&ug);
Johannes Weiner747db952014-08-08 14:19:24 -07006936}
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006937
Johannes Weiner747db952014-08-08 14:19:24 -07006938/**
6939 * mem_cgroup_uncharge_list - uncharge a list of page
6940 * @page_list: list of pages to uncharge
6941 *
6942 * Uncharge a list of pages previously charged with
Johannes Weinerf0e45fb2020-06-03 16:02:07 -07006943 * mem_cgroup_charge().
Johannes Weiner747db952014-08-08 14:19:24 -07006944 */
6945void mem_cgroup_uncharge_list(struct list_head *page_list)
6946{
6947 if (mem_cgroup_disabled())
6948 return;
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006949
Johannes Weiner747db952014-08-08 14:19:24 -07006950 if (!list_empty(page_list))
6951 uncharge_list(page_list);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006952}
6953
6954/**
Johannes Weiner6a93ca82016-03-15 14:57:19 -07006955 * mem_cgroup_migrate - charge a page's replacement
6956 * @oldpage: currently circulating page
6957 * @newpage: replacement page
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006958 *
Johannes Weiner6a93ca82016-03-15 14:57:19 -07006959 * Charge @newpage as a replacement page for @oldpage. @oldpage will
6960 * be uncharged upon free.
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006961 *
6962 * Both pages must be locked, @newpage->mapping must be set up.
6963 */
Johannes Weiner6a93ca82016-03-15 14:57:19 -07006964void mem_cgroup_migrate(struct page *oldpage, struct page *newpage)
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006965{
Johannes Weiner29833312014-12-10 15:44:02 -08006966 struct mem_cgroup *memcg;
Johannes Weiner44b7a8d2016-01-20 15:03:16 -08006967 unsigned int nr_pages;
Tejun Heod93c4132016-06-24 14:49:54 -07006968 unsigned long flags;
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006969
6970 VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
6971 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006972 VM_BUG_ON_PAGE(PageAnon(oldpage) != PageAnon(newpage), newpage);
Johannes Weiner6abb5a82014-08-08 14:19:33 -07006973 VM_BUG_ON_PAGE(PageTransHuge(oldpage) != PageTransHuge(newpage),
6974 newpage);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006975
6976 if (mem_cgroup_disabled())
6977 return;
6978
6979 /* Page cache replacement: new page already charged? */
Johannes Weiner1306a852014-12-10 15:44:52 -08006980 if (newpage->mem_cgroup)
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006981 return;
6982
Hugh Dickins45637ba2015-11-05 18:49:40 -08006983 /* Swapcache readahead pages can get replaced before being charged */
Johannes Weiner1306a852014-12-10 15:44:52 -08006984 memcg = oldpage->mem_cgroup;
Johannes Weiner29833312014-12-10 15:44:02 -08006985 if (!memcg)
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006986 return;
6987
Johannes Weiner44b7a8d2016-01-20 15:03:16 -08006988 /* Force-charge the new page. The old one will be freed soon */
Kaitao Cheng928552702020-01-30 22:13:42 -08006989 nr_pages = hpage_nr_pages(newpage);
Johannes Weiner44b7a8d2016-01-20 15:03:16 -08006990
6991 page_counter_charge(&memcg->memory, nr_pages);
6992 if (do_memsw_account())
6993 page_counter_charge(&memcg->memsw, nr_pages);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07006994
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07006995 css_get(&memcg->css);
Johannes Weinerd9eb1ea2020-06-03 16:02:24 -07006996 commit_charge(newpage, memcg);
Johannes Weiner44b7a8d2016-01-20 15:03:16 -08006997
Tejun Heod93c4132016-06-24 14:49:54 -07006998 local_irq_save(flags);
Johannes Weiner3fba69a2020-06-03 16:01:31 -07006999 mem_cgroup_charge_statistics(memcg, newpage, nr_pages);
Johannes Weiner44b7a8d2016-01-20 15:03:16 -08007000 memcg_check_events(memcg, newpage);
Tejun Heod93c4132016-06-24 14:49:54 -07007001 local_irq_restore(flags);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07007002}
7003
Johannes Weineref129472016-01-14 15:21:34 -08007004DEFINE_STATIC_KEY_FALSE(memcg_sockets_enabled_key);
Johannes Weiner11092082016-01-14 15:21:26 -08007005EXPORT_SYMBOL(memcg_sockets_enabled_key);
7006
Johannes Weiner2d758072016-10-07 17:00:58 -07007007void mem_cgroup_sk_alloc(struct sock *sk)
Johannes Weiner11092082016-01-14 15:21:26 -08007008{
7009 struct mem_cgroup *memcg;
7010
Johannes Weiner2d758072016-10-07 17:00:58 -07007011 if (!mem_cgroup_sockets_enabled)
7012 return;
7013
Shakeel Butte876ecc2020-03-09 22:16:05 -07007014 /* Do not associate the sock with unrelated interrupted task's memcg. */
7015 if (in_interrupt())
7016 return;
7017
Johannes Weiner11092082016-01-14 15:21:26 -08007018 rcu_read_lock();
7019 memcg = mem_cgroup_from_task(current);
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007020 if (memcg == root_mem_cgroup)
7021 goto out;
Johannes Weiner0db15292016-01-20 15:02:50 -08007022 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys) && !memcg->tcpmem_active)
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007023 goto out;
Shakeel Butt8965aa22020-04-01 21:07:10 -07007024 if (css_tryget(&memcg->css))
Johannes Weiner11092082016-01-14 15:21:26 -08007025 sk->sk_memcg = memcg;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007026out:
Johannes Weiner11092082016-01-14 15:21:26 -08007027 rcu_read_unlock();
7028}
Johannes Weiner11092082016-01-14 15:21:26 -08007029
Johannes Weiner2d758072016-10-07 17:00:58 -07007030void mem_cgroup_sk_free(struct sock *sk)
Johannes Weiner11092082016-01-14 15:21:26 -08007031{
Johannes Weiner2d758072016-10-07 17:00:58 -07007032 if (sk->sk_memcg)
7033 css_put(&sk->sk_memcg->css);
Johannes Weiner11092082016-01-14 15:21:26 -08007034}
7035
7036/**
7037 * mem_cgroup_charge_skmem - charge socket memory
7038 * @memcg: memcg to charge
7039 * @nr_pages: number of pages to charge
7040 *
7041 * Charges @nr_pages to @memcg. Returns %true if the charge fit within
7042 * @memcg's configured limit, %false if the charge had to be forced.
7043 */
7044bool mem_cgroup_charge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7045{
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007046 gfp_t gfp_mask = GFP_KERNEL;
Johannes Weiner11092082016-01-14 15:21:26 -08007047
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007048 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
Johannes Weiner0db15292016-01-20 15:02:50 -08007049 struct page_counter *fail;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007050
Johannes Weiner0db15292016-01-20 15:02:50 -08007051 if (page_counter_try_charge(&memcg->tcpmem, nr_pages, &fail)) {
7052 memcg->tcpmem_pressure = 0;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007053 return true;
7054 }
Johannes Weiner0db15292016-01-20 15:02:50 -08007055 page_counter_charge(&memcg->tcpmem, nr_pages);
7056 memcg->tcpmem_pressure = 1;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007057 return false;
Johannes Weiner11092082016-01-14 15:21:26 -08007058 }
Johannes Weinerd886f4e2016-01-20 15:02:47 -08007059
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007060 /* Don't block in the packet receive path */
7061 if (in_softirq())
7062 gfp_mask = GFP_NOWAIT;
7063
Johannes Weinerc9019e92018-01-31 16:16:37 -08007064 mod_memcg_state(memcg, MEMCG_SOCK, nr_pages);
Johannes Weinerb2807f02016-01-20 15:03:22 -08007065
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007066 if (try_charge(memcg, gfp_mask, nr_pages) == 0)
7067 return true;
7068
7069 try_charge(memcg, gfp_mask|__GFP_NOFAIL, nr_pages);
Johannes Weiner11092082016-01-14 15:21:26 -08007070 return false;
7071}
7072
7073/**
7074 * mem_cgroup_uncharge_skmem - uncharge socket memory
Mike Rapoportb7701a52018-02-06 15:42:13 -08007075 * @memcg: memcg to uncharge
7076 * @nr_pages: number of pages to uncharge
Johannes Weiner11092082016-01-14 15:21:26 -08007077 */
7078void mem_cgroup_uncharge_skmem(struct mem_cgroup *memcg, unsigned int nr_pages)
7079{
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007080 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys)) {
Johannes Weiner0db15292016-01-20 15:02:50 -08007081 page_counter_uncharge(&memcg->tcpmem, nr_pages);
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007082 return;
7083 }
Johannes Weinerd886f4e2016-01-20 15:02:47 -08007084
Johannes Weinerc9019e92018-01-31 16:16:37 -08007085 mod_memcg_state(memcg, MEMCG_SOCK, -nr_pages);
Johannes Weinerb2807f02016-01-20 15:03:22 -08007086
Roman Gushchin475d0482017-09-08 16:13:09 -07007087 refill_stock(memcg, nr_pages);
Johannes Weiner11092082016-01-14 15:21:26 -08007088}
7089
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007090static int __init cgroup_memory(char *s)
7091{
7092 char *token;
7093
7094 while ((token = strsep(&s, ",")) != NULL) {
7095 if (!*token)
7096 continue;
7097 if (!strcmp(token, "nosocket"))
7098 cgroup_memory_nosocket = true;
Vladimir Davydov04823c82016-01-20 15:02:38 -08007099 if (!strcmp(token, "nokmem"))
7100 cgroup_memory_nokmem = true;
Johannes Weinerf7e1cb62016-01-14 15:21:29 -08007101 }
7102 return 0;
7103}
7104__setup("cgroup.memory=", cgroup_memory);
Johannes Weiner11092082016-01-14 15:21:26 -08007105
Michal Hocko2d110852013-02-22 16:34:43 -08007106/*
Michal Hocko10813122013-02-22 16:35:41 -08007107 * subsys_initcall() for memory controller.
7108 *
Sebastian Andrzej Siewior308167f2016-11-03 15:49:59 +01007109 * Some parts like memcg_hotplug_cpu_dead() have to be initialized from this
7110 * context because of lock dependencies (cgroup_lock -> cpu hotplug) but
7111 * basically everything that doesn't depend on a specific mem_cgroup structure
7112 * should be initialized from here.
Michal Hocko2d110852013-02-22 16:34:43 -08007113 */
7114static int __init mem_cgroup_init(void)
7115{
Johannes Weiner95a045f2015-02-11 15:26:33 -08007116 int cpu, node;
7117
Kirill Tkhai84c07d12018-08-17 15:47:25 -07007118#ifdef CONFIG_MEMCG_KMEM
Vladimir Davydov13583c32016-12-12 16:41:29 -08007119 /*
7120 * Kmem cache creation is mostly done with the slab_mutex held,
Tejun Heo17cc4df2017-02-22 15:41:36 -08007121 * so use a workqueue with limited concurrency to avoid stalling
7122 * all worker threads in case lots of cgroups are created and
7123 * destroyed simultaneously.
Vladimir Davydov13583c32016-12-12 16:41:29 -08007124 */
Tejun Heo17cc4df2017-02-22 15:41:36 -08007125 memcg_kmem_cache_wq = alloc_workqueue("memcg_kmem_cache", 0, 1);
7126 BUG_ON(!memcg_kmem_cache_wq);
Vladimir Davydov13583c32016-12-12 16:41:29 -08007127#endif
7128
Sebastian Andrzej Siewior308167f2016-11-03 15:49:59 +01007129 cpuhp_setup_state_nocalls(CPUHP_MM_MEMCQ_DEAD, "mm/memctrl:dead", NULL,
7130 memcg_hotplug_cpu_dead);
Johannes Weiner95a045f2015-02-11 15:26:33 -08007131
7132 for_each_possible_cpu(cpu)
7133 INIT_WORK(&per_cpu_ptr(&memcg_stock, cpu)->work,
7134 drain_local_stock);
7135
7136 for_each_node(node) {
7137 struct mem_cgroup_tree_per_node *rtpn;
Johannes Weiner95a045f2015-02-11 15:26:33 -08007138
7139 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL,
7140 node_online(node) ? node : NUMA_NO_NODE);
7141
Mel Gormanef8f2322016-07-28 15:46:05 -07007142 rtpn->rb_root = RB_ROOT;
Davidlohr Buesofa90b2f2017-09-08 16:15:21 -07007143 rtpn->rb_rightmost = NULL;
Mel Gormanef8f2322016-07-28 15:46:05 -07007144 spin_lock_init(&rtpn->lock);
Johannes Weiner95a045f2015-02-11 15:26:33 -08007145 soft_limit_tree.rb_tree_per_node[node] = rtpn;
7146 }
7147
Michal Hocko2d110852013-02-22 16:34:43 -08007148 return 0;
7149}
7150subsys_initcall(mem_cgroup_init);
Johannes Weiner21afa382015-02-11 15:26:36 -08007151
7152#ifdef CONFIG_MEMCG_SWAP
Arnd Bergmann358c07f2016-08-25 15:17:08 -07007153static struct mem_cgroup *mem_cgroup_id_get_online(struct mem_cgroup *memcg)
7154{
Kirill Tkhai1c2d4792018-10-26 15:09:28 -07007155 while (!refcount_inc_not_zero(&memcg->id.ref)) {
Arnd Bergmann358c07f2016-08-25 15:17:08 -07007156 /*
7157 * The root cgroup cannot be destroyed, so it's refcount must
7158 * always be >= 1.
7159 */
7160 if (WARN_ON_ONCE(memcg == root_mem_cgroup)) {
7161 VM_BUG_ON(1);
7162 break;
7163 }
7164 memcg = parent_mem_cgroup(memcg);
7165 if (!memcg)
7166 memcg = root_mem_cgroup;
7167 }
7168 return memcg;
7169}
7170
Johannes Weiner21afa382015-02-11 15:26:36 -08007171/**
7172 * mem_cgroup_swapout - transfer a memsw charge to swap
7173 * @page: page whose memsw charge to transfer
7174 * @entry: swap entry to move the charge to
7175 *
7176 * Transfer the memsw charge of @page to @entry.
7177 */
7178void mem_cgroup_swapout(struct page *page, swp_entry_t entry)
7179{
Vladimir Davydov1f47b612016-08-11 15:33:00 -07007180 struct mem_cgroup *memcg, *swap_memcg;
Huang Yingd6810d72017-09-06 16:22:45 -07007181 unsigned int nr_entries;
Johannes Weiner21afa382015-02-11 15:26:36 -08007182 unsigned short oldid;
7183
7184 VM_BUG_ON_PAGE(PageLRU(page), page);
7185 VM_BUG_ON_PAGE(page_count(page), page);
7186
Johannes Weiner2d1c4982020-06-03 16:02:14 -07007187 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Johannes Weiner21afa382015-02-11 15:26:36 -08007188 return;
7189
7190 memcg = page->mem_cgroup;
7191
7192 /* Readahead page, never charged */
7193 if (!memcg)
7194 return;
7195
Vladimir Davydov1f47b612016-08-11 15:33:00 -07007196 /*
7197 * In case the memcg owning these pages has been offlined and doesn't
7198 * have an ID allocated to it anymore, charge the closest online
7199 * ancestor for the swap instead and transfer the memory+swap charge.
7200 */
7201 swap_memcg = mem_cgroup_id_get_online(memcg);
Huang Yingd6810d72017-09-06 16:22:45 -07007202 nr_entries = hpage_nr_pages(page);
7203 /* Get references for the tail pages, too */
7204 if (nr_entries > 1)
7205 mem_cgroup_id_get_many(swap_memcg, nr_entries - 1);
7206 oldid = swap_cgroup_record(entry, mem_cgroup_id(swap_memcg),
7207 nr_entries);
Johannes Weiner21afa382015-02-11 15:26:36 -08007208 VM_BUG_ON_PAGE(oldid, page);
Johannes Weinerc9019e92018-01-31 16:16:37 -08007209 mod_memcg_state(swap_memcg, MEMCG_SWAP, nr_entries);
Johannes Weiner21afa382015-02-11 15:26:36 -08007210
7211 page->mem_cgroup = NULL;
7212
7213 if (!mem_cgroup_is_root(memcg))
Huang Yingd6810d72017-09-06 16:22:45 -07007214 page_counter_uncharge(&memcg->memory, nr_entries);
Johannes Weiner21afa382015-02-11 15:26:36 -08007215
Johannes Weiner2d1c4982020-06-03 16:02:14 -07007216 if (!cgroup_memory_noswap && memcg != swap_memcg) {
Vladimir Davydov1f47b612016-08-11 15:33:00 -07007217 if (!mem_cgroup_is_root(swap_memcg))
Huang Yingd6810d72017-09-06 16:22:45 -07007218 page_counter_charge(&swap_memcg->memsw, nr_entries);
7219 page_counter_uncharge(&memcg->memsw, nr_entries);
Vladimir Davydov1f47b612016-08-11 15:33:00 -07007220 }
7221
Sebastian Andrzej Siewiorce9ce662015-09-04 15:47:50 -07007222 /*
7223 * Interrupts should be disabled here because the caller holds the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07007224 * i_pages lock which is taken with interrupts-off. It is
Sebastian Andrzej Siewiorce9ce662015-09-04 15:47:50 -07007225 * important here to have the interrupts disabled because it is the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07007226 * only synchronisation we have for updating the per-CPU variables.
Sebastian Andrzej Siewiorce9ce662015-09-04 15:47:50 -07007227 */
7228 VM_BUG_ON(!irqs_disabled());
Johannes Weiner3fba69a2020-06-03 16:01:31 -07007229 mem_cgroup_charge_statistics(memcg, page, -nr_entries);
Johannes Weiner21afa382015-02-11 15:26:36 -08007230 memcg_check_events(memcg, page);
Johannes Weiner73f576c2016-07-20 15:44:57 -07007231
Johannes Weiner1a3e1f42020-08-06 23:20:45 -07007232 css_put(&memcg->css);
Johannes Weiner21afa382015-02-11 15:26:36 -08007233}
7234
Huang Ying38d8b4e2017-07-06 15:37:18 -07007235/**
7236 * mem_cgroup_try_charge_swap - try charging swap space for a page
Vladimir Davydov37e84352016-01-20 15:02:56 -08007237 * @page: page being added to swap
7238 * @entry: swap entry to charge
7239 *
Huang Ying38d8b4e2017-07-06 15:37:18 -07007240 * Try to charge @page's memcg for the swap space at @entry.
Vladimir Davydov37e84352016-01-20 15:02:56 -08007241 *
7242 * Returns 0 on success, -ENOMEM on failure.
7243 */
7244int mem_cgroup_try_charge_swap(struct page *page, swp_entry_t entry)
7245{
Huang Ying38d8b4e2017-07-06 15:37:18 -07007246 unsigned int nr_pages = hpage_nr_pages(page);
Vladimir Davydov37e84352016-01-20 15:02:56 -08007247 struct page_counter *counter;
Huang Ying38d8b4e2017-07-06 15:37:18 -07007248 struct mem_cgroup *memcg;
Vladimir Davydov37e84352016-01-20 15:02:56 -08007249 unsigned short oldid;
7250
Johannes Weiner2d1c4982020-06-03 16:02:14 -07007251 if (!cgroup_subsys_on_dfl(memory_cgrp_subsys))
Vladimir Davydov37e84352016-01-20 15:02:56 -08007252 return 0;
7253
7254 memcg = page->mem_cgroup;
7255
7256 /* Readahead page, never charged */
7257 if (!memcg)
7258 return 0;
7259
Tejun Heof3a53a32018-06-07 17:05:35 -07007260 if (!entry.val) {
7261 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
Tejun Heobb98f2c2018-06-07 17:05:31 -07007262 return 0;
Tejun Heof3a53a32018-06-07 17:05:35 -07007263 }
Tejun Heobb98f2c2018-06-07 17:05:31 -07007264
Vladimir Davydov1f47b612016-08-11 15:33:00 -07007265 memcg = mem_cgroup_id_get_online(memcg);
Vladimir Davydov37e84352016-01-20 15:02:56 -08007266
Johannes Weiner2d1c4982020-06-03 16:02:14 -07007267 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg) &&
Huang Ying38d8b4e2017-07-06 15:37:18 -07007268 !page_counter_try_charge(&memcg->swap, nr_pages, &counter)) {
Tejun Heof3a53a32018-06-07 17:05:35 -07007269 memcg_memory_event(memcg, MEMCG_SWAP_MAX);
7270 memcg_memory_event(memcg, MEMCG_SWAP_FAIL);
Vladimir Davydov1f47b612016-08-11 15:33:00 -07007271 mem_cgroup_id_put(memcg);
7272 return -ENOMEM;
7273 }
7274
Huang Ying38d8b4e2017-07-06 15:37:18 -07007275 /* Get references for the tail pages, too */
7276 if (nr_pages > 1)
7277 mem_cgroup_id_get_many(memcg, nr_pages - 1);
7278 oldid = swap_cgroup_record(entry, mem_cgroup_id(memcg), nr_pages);
Vladimir Davydov37e84352016-01-20 15:02:56 -08007279 VM_BUG_ON_PAGE(oldid, page);
Johannes Weinerc9019e92018-01-31 16:16:37 -08007280 mod_memcg_state(memcg, MEMCG_SWAP, nr_pages);
Vladimir Davydov37e84352016-01-20 15:02:56 -08007281
Vladimir Davydov37e84352016-01-20 15:02:56 -08007282 return 0;
7283}
7284
Johannes Weiner21afa382015-02-11 15:26:36 -08007285/**
Huang Ying38d8b4e2017-07-06 15:37:18 -07007286 * mem_cgroup_uncharge_swap - uncharge swap space
Johannes Weiner21afa382015-02-11 15:26:36 -08007287 * @entry: swap entry to uncharge
Huang Ying38d8b4e2017-07-06 15:37:18 -07007288 * @nr_pages: the amount of swap space to uncharge
Johannes Weiner21afa382015-02-11 15:26:36 -08007289 */
Huang Ying38d8b4e2017-07-06 15:37:18 -07007290void mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
Johannes Weiner21afa382015-02-11 15:26:36 -08007291{
7292 struct mem_cgroup *memcg;
7293 unsigned short id;
7294
Huang Ying38d8b4e2017-07-06 15:37:18 -07007295 id = swap_cgroup_record(entry, 0, nr_pages);
Johannes Weiner21afa382015-02-11 15:26:36 -08007296 rcu_read_lock();
Vladimir Davydovadbe4272015-04-15 16:13:00 -07007297 memcg = mem_cgroup_from_id(id);
Johannes Weiner21afa382015-02-11 15:26:36 -08007298 if (memcg) {
Johannes Weiner2d1c4982020-06-03 16:02:14 -07007299 if (!cgroup_memory_noswap && !mem_cgroup_is_root(memcg)) {
Vladimir Davydov37e84352016-01-20 15:02:56 -08007300 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Huang Ying38d8b4e2017-07-06 15:37:18 -07007301 page_counter_uncharge(&memcg->swap, nr_pages);
Vladimir Davydov37e84352016-01-20 15:02:56 -08007302 else
Huang Ying38d8b4e2017-07-06 15:37:18 -07007303 page_counter_uncharge(&memcg->memsw, nr_pages);
Vladimir Davydov37e84352016-01-20 15:02:56 -08007304 }
Johannes Weinerc9019e92018-01-31 16:16:37 -08007305 mod_memcg_state(memcg, MEMCG_SWAP, -nr_pages);
Huang Ying38d8b4e2017-07-06 15:37:18 -07007306 mem_cgroup_id_put_many(memcg, nr_pages);
Johannes Weiner21afa382015-02-11 15:26:36 -08007307 }
7308 rcu_read_unlock();
7309}
7310
Vladimir Davydovd8b38432016-01-20 15:03:07 -08007311long mem_cgroup_get_nr_swap_pages(struct mem_cgroup *memcg)
7312{
7313 long nr_swap_pages = get_nr_swap_pages();
7314
Johannes Weinereccb52e2020-06-03 16:02:11 -07007315 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
Vladimir Davydovd8b38432016-01-20 15:03:07 -08007316 return nr_swap_pages;
7317 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg))
7318 nr_swap_pages = min_t(long, nr_swap_pages,
Roman Gushchinbbec2e12018-06-07 17:06:18 -07007319 READ_ONCE(memcg->swap.max) -
Vladimir Davydovd8b38432016-01-20 15:03:07 -08007320 page_counter_read(&memcg->swap));
7321 return nr_swap_pages;
7322}
7323
Vladimir Davydov5ccc5ab2016-01-20 15:03:10 -08007324bool mem_cgroup_swap_full(struct page *page)
7325{
7326 struct mem_cgroup *memcg;
7327
7328 VM_BUG_ON_PAGE(!PageLocked(page), page);
7329
7330 if (vm_swap_full())
7331 return true;
Johannes Weinereccb52e2020-06-03 16:02:11 -07007332 if (cgroup_memory_noswap || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
Vladimir Davydov5ccc5ab2016-01-20 15:03:10 -08007333 return false;
7334
7335 memcg = page->mem_cgroup;
7336 if (!memcg)
7337 return false;
7338
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07007339 for (; memcg != root_mem_cgroup; memcg = parent_mem_cgroup(memcg)) {
7340 unsigned long usage = page_counter_read(&memcg->swap);
7341
7342 if (usage * 2 >= READ_ONCE(memcg->swap.high) ||
7343 usage * 2 >= READ_ONCE(memcg->swap.max))
Vladimir Davydov5ccc5ab2016-01-20 15:03:10 -08007344 return true;
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07007345 }
Vladimir Davydov5ccc5ab2016-01-20 15:03:10 -08007346
7347 return false;
7348}
7349
Johannes Weinereccb52e2020-06-03 16:02:11 -07007350static int __init setup_swap_account(char *s)
Johannes Weiner21afa382015-02-11 15:26:36 -08007351{
7352 if (!strcmp(s, "1"))
Johannes Weinereccb52e2020-06-03 16:02:11 -07007353 cgroup_memory_noswap = 0;
Johannes Weiner21afa382015-02-11 15:26:36 -08007354 else if (!strcmp(s, "0"))
Johannes Weinereccb52e2020-06-03 16:02:11 -07007355 cgroup_memory_noswap = 1;
Johannes Weiner21afa382015-02-11 15:26:36 -08007356 return 1;
7357}
Johannes Weinereccb52e2020-06-03 16:02:11 -07007358__setup("swapaccount=", setup_swap_account);
Johannes Weiner21afa382015-02-11 15:26:36 -08007359
Vladimir Davydov37e84352016-01-20 15:02:56 -08007360static u64 swap_current_read(struct cgroup_subsys_state *css,
7361 struct cftype *cft)
7362{
7363 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
7364
7365 return (u64)page_counter_read(&memcg->swap) * PAGE_SIZE;
7366}
7367
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07007368static int swap_high_show(struct seq_file *m, void *v)
7369{
7370 return seq_puts_memcg_tunable(m,
7371 READ_ONCE(mem_cgroup_from_seq(m)->swap.high));
7372}
7373
7374static ssize_t swap_high_write(struct kernfs_open_file *of,
7375 char *buf, size_t nbytes, loff_t off)
7376{
7377 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7378 unsigned long high;
7379 int err;
7380
7381 buf = strstrip(buf);
7382 err = page_counter_memparse(buf, "max", &high);
7383 if (err)
7384 return err;
7385
7386 page_counter_set_high(&memcg->swap, high);
7387
7388 return nbytes;
7389}
7390
Vladimir Davydov37e84352016-01-20 15:02:56 -08007391static int swap_max_show(struct seq_file *m, void *v)
7392{
Chris Down677dc972019-03-05 15:45:55 -08007393 return seq_puts_memcg_tunable(m,
7394 READ_ONCE(mem_cgroup_from_seq(m)->swap.max));
Vladimir Davydov37e84352016-01-20 15:02:56 -08007395}
7396
7397static ssize_t swap_max_write(struct kernfs_open_file *of,
7398 char *buf, size_t nbytes, loff_t off)
7399{
7400 struct mem_cgroup *memcg = mem_cgroup_from_css(of_css(of));
7401 unsigned long max;
7402 int err;
7403
7404 buf = strstrip(buf);
7405 err = page_counter_memparse(buf, "max", &max);
7406 if (err)
7407 return err;
7408
Tejun Heobe091022018-06-07 17:09:21 -07007409 xchg(&memcg->swap.max, max);
Vladimir Davydov37e84352016-01-20 15:02:56 -08007410
7411 return nbytes;
7412}
7413
Tejun Heof3a53a32018-06-07 17:05:35 -07007414static int swap_events_show(struct seq_file *m, void *v)
7415{
Chris Downaa9694b2019-03-05 15:45:52 -08007416 struct mem_cgroup *memcg = mem_cgroup_from_seq(m);
Tejun Heof3a53a32018-06-07 17:05:35 -07007417
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07007418 seq_printf(m, "high %lu\n",
7419 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_HIGH]));
Tejun Heof3a53a32018-06-07 17:05:35 -07007420 seq_printf(m, "max %lu\n",
7421 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_MAX]));
7422 seq_printf(m, "fail %lu\n",
7423 atomic_long_read(&memcg->memory_events[MEMCG_SWAP_FAIL]));
7424
7425 return 0;
7426}
7427
Vladimir Davydov37e84352016-01-20 15:02:56 -08007428static struct cftype swap_files[] = {
7429 {
7430 .name = "swap.current",
7431 .flags = CFTYPE_NOT_ON_ROOT,
7432 .read_u64 = swap_current_read,
7433 },
7434 {
Jakub Kicinski4b82ab42020-06-01 21:49:52 -07007435 .name = "swap.high",
7436 .flags = CFTYPE_NOT_ON_ROOT,
7437 .seq_show = swap_high_show,
7438 .write = swap_high_write,
7439 },
7440 {
Vladimir Davydov37e84352016-01-20 15:02:56 -08007441 .name = "swap.max",
7442 .flags = CFTYPE_NOT_ON_ROOT,
7443 .seq_show = swap_max_show,
7444 .write = swap_max_write,
7445 },
Tejun Heof3a53a32018-06-07 17:05:35 -07007446 {
7447 .name = "swap.events",
7448 .flags = CFTYPE_NOT_ON_ROOT,
7449 .file_offset = offsetof(struct mem_cgroup, swap_events_file),
7450 .seq_show = swap_events_show,
7451 },
Vladimir Davydov37e84352016-01-20 15:02:56 -08007452 { } /* terminate */
7453};
7454
Johannes Weinereccb52e2020-06-03 16:02:11 -07007455static struct cftype memsw_files[] = {
Johannes Weiner21afa382015-02-11 15:26:36 -08007456 {
7457 .name = "memsw.usage_in_bytes",
7458 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
7459 .read_u64 = mem_cgroup_read_u64,
7460 },
7461 {
7462 .name = "memsw.max_usage_in_bytes",
7463 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
7464 .write = mem_cgroup_reset,
7465 .read_u64 = mem_cgroup_read_u64,
7466 },
7467 {
7468 .name = "memsw.limit_in_bytes",
7469 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
7470 .write = mem_cgroup_write,
7471 .read_u64 = mem_cgroup_read_u64,
7472 },
7473 {
7474 .name = "memsw.failcnt",
7475 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
7476 .write = mem_cgroup_reset,
7477 .read_u64 = mem_cgroup_read_u64,
7478 },
7479 { }, /* terminate */
7480};
7481
Bhupesh Sharma82ff1652020-07-23 21:15:21 -07007482/*
7483 * If mem_cgroup_swap_init() is implemented as a subsys_initcall()
7484 * instead of a core_initcall(), this could mean cgroup_memory_noswap still
7485 * remains set to false even when memcg is disabled via "cgroup_disable=memory"
7486 * boot parameter. This may result in premature OOPS inside
7487 * mem_cgroup_get_nr_swap_pages() function in corner cases.
7488 */
Johannes Weiner21afa382015-02-11 15:26:36 -08007489static int __init mem_cgroup_swap_init(void)
7490{
Johannes Weiner2d1c4982020-06-03 16:02:14 -07007491 /* No memory control -> no swap control */
7492 if (mem_cgroup_disabled())
7493 cgroup_memory_noswap = true;
7494
7495 if (cgroup_memory_noswap)
Johannes Weinereccb52e2020-06-03 16:02:11 -07007496 return 0;
7497
7498 WARN_ON(cgroup_add_dfl_cftypes(&memory_cgrp_subsys, swap_files));
7499 WARN_ON(cgroup_add_legacy_cftypes(&memory_cgrp_subsys, memsw_files));
7500
Johannes Weiner21afa382015-02-11 15:26:36 -08007501 return 0;
7502}
Bhupesh Sharma82ff1652020-07-23 21:15:21 -07007503core_initcall(mem_cgroup_swap_init);
Johannes Weiner21afa382015-02-11 15:26:36 -08007504
7505#endif /* CONFIG_MEMCG_SWAP */