memcontrol.c 169 KB
Newer Older
1 2 3 4 5
/* memcontrol.c - Memory Controller
 *
 * Copyright IBM Corporation, 2007
 * Author Balbir Singh <balbir@linux.vnet.ibm.com>
 *
6 7 8
 * Copyright 2007 OpenVZ SWsoft Inc
 * Author: Pavel Emelianov <xemul@openvz.org>
 *
9 10 11 12
 * Memory thresholds
 * Copyright (C) 2009 Nokia Corporation
 * Author: Kirill A. Shutemov
 *
13 14 15 16
 * Kernel Memory Controller
 * Copyright (C) 2012 Parallels Inc. and Google Inc.
 * Authors: Glauber Costa and Suleiman Souhlal
 *
17 18 19 20 21 22
 * Native page reclaim
 * Charge lifetime sanitation
 * Lockless page tracking & accounting
 * Unified hierarchy configuration model
 * Copyright (C) 2015 Red Hat, Inc., Johannes Weiner
 *
23 24 25 26 27 28 29 30 31 32 33
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

34
#include <linux/page_counter.h>
35 36
#include <linux/memcontrol.h>
#include <linux/cgroup.h>
37
#include <linux/mm.h>
38
#include <linux/sched/mm.h>
39
#include <linux/shmem_fs.h>
40
#include <linux/hugetlb.h>
41
#include <linux/pagemap.h>
42
#include <linux/smp.h>
43
#include <linux/page-flags.h>
44
#include <linux/backing-dev.h>
45 46
#include <linux/bit_spinlock.h>
#include <linux/rcupdate.h>
47
#include <linux/limits.h>
48
#include <linux/export.h>
49
#include <linux/mutex.h>
50
#include <linux/rbtree.h>
51
#include <linux/slab.h>
52
#include <linux/swap.h>
53
#include <linux/swapops.h>
54
#include <linux/spinlock.h>
55
#include <linux/eventfd.h>
56
#include <linux/poll.h>
57
#include <linux/sort.h>
58
#include <linux/fs.h>
59
#include <linux/seq_file.h>
60
#include <linux/vmpressure.h>
61
#include <linux/mm_inline.h>
62
#include <linux/swap_cgroup.h>
63
#include <linux/cpu.h>
64
#include <linux/oom.h>
65
#include <linux/lockdep.h>
66
#include <linux/file.h>
67
#include <linux/tracehook.h>
68
#include "internal.h"
69
#include <net/sock.h>
70
#include <net/ip.h>
71
#include "slab.h"
72

73
#include <linux/uaccess.h>
74

75 76
#include <trace/events/vmscan.h>

77 78
struct cgroup_subsys memory_cgrp_subsys __read_mostly;
EXPORT_SYMBOL(memory_cgrp_subsys);
79

80 81
struct mem_cgroup *root_mem_cgroup __read_mostly;

82
#define MEM_CGROUP_RECLAIM_RETRIES	5
83

84 85 86
/* Socket memory accounting disabled? */
static bool cgroup_memory_nosocket;

87 88 89
/* Kernel memory accounting disabled? */
static bool cgroup_memory_nokmem;

90
/* Whether the swap controller is active */
91
#ifdef CONFIG_MEMCG_SWAP
92 93
int do_swap_account __read_mostly;
#else
94
#define do_swap_account		0
95 96
#endif

97 98 99 100 101 102
/* Whether legacy memory+swap accounting is active */
static bool do_memsw_account(void)
{
	return !cgroup_subsys_on_dfl(memory_cgrp_subsys) && do_swap_account;
}

103
static const char *const mem_cgroup_lru_names[] = {
104 105 106 107 108 109 110
	"inactive_anon",
	"active_anon",
	"inactive_file",
	"active_file",
	"unevictable",
};

111 112 113
#define THRESHOLDS_EVENTS_TARGET 128
#define SOFTLIMIT_EVENTS_TARGET 1024
#define NUMAINFO_EVENTS_TARGET	1024
114

115 116 117 118 119
/*
 * Cgroups above their limits are maintained in a RB-Tree, independent of
 * their hierarchy representation
 */

120
struct mem_cgroup_tree_per_node {
121
	struct rb_root rb_root;
122
	struct rb_node *rb_rightmost;
123 124 125 126 127 128 129 130 131
	spinlock_t lock;
};

struct mem_cgroup_tree {
	struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
};

static struct mem_cgroup_tree soft_limit_tree __read_mostly;

KAMEZAWA Hiroyuki's avatar
KAMEZAWA Hiroyuki committed
132 133 134 135 136
/* for OOM */
struct mem_cgroup_eventfd_list {
	struct list_head list;
	struct eventfd_ctx *eventfd;
};
137

138 139 140
/*
 * cgroup_event represents events which userspace want to receive.
 */
141
struct mem_cgroup_event {
142
	/*
143
	 * memcg which the event belongs to.
144
	 */
145
	struct mem_cgroup *memcg;
146 147 148 149 150 151 152 153
	/*
	 * eventfd to signal userspace about the event.
	 */
	struct eventfd_ctx *eventfd;
	/*
	 * Each of these stored in a list by the cgroup.
	 */
	struct list_head list;
154 155 156 157 158
	/*
	 * register_event() callback will be used to add new userspace
	 * waiter for changes related to this event.  Use eventfd_signal()
	 * on eventfd to send notification to userspace.
	 */
159
	int (*register_event)(struct mem_cgroup *memcg,
160
			      struct eventfd_ctx *eventfd, const char *args);
161 162 163 164 165
	/*
	 * unregister_event() callback will be called when userspace closes
	 * the eventfd or on cgroup removing.  This callback must be set,
	 * if you want provide notification functionality.
	 */
166
	void (*unregister_event)(struct mem_cgroup *memcg,
167
				 struct eventfd_ctx *eventfd);
168 169 170 171 172 173
	/*
	 * All fields below needed to unregister event when
	 * userspace closes eventfd.
	 */
	poll_table pt;
	wait_queue_head_t *wqh;
174
	wait_queue_entry_t wait;
175 176 177
	struct work_struct remove;
};

178 179
static void mem_cgroup_threshold(struct mem_cgroup *memcg);
static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
180

181 182
/* Stuffs for move charges at task migration. */
/*
183
 * Types of charges to be moved.
184
 */
185 186 187
#define MOVE_ANON	0x1U
#define MOVE_FILE	0x2U
#define MOVE_MASK	(MOVE_ANON | MOVE_FILE)
188

189 190
/* "mc" and its members are protected by cgroup_mutex */
static struct move_charge_struct {
191
	spinlock_t	  lock; /* for from, to */
192
	struct mm_struct  *mm;
193 194
	struct mem_cgroup *from;
	struct mem_cgroup *to;
195
	unsigned long flags;
196
	unsigned long precharge;
197
	unsigned long moved_charge;
198
	unsigned long moved_swap;
199 200 201
	struct task_struct *moving_task;	/* a task moving charges */
	wait_queue_head_t waitq;		/* a waitq for other context */
} mc = {
202
	.lock = __SPIN_LOCK_UNLOCKED(mc.lock),
203 204
	.waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
};
205

206 207 208 209
/*
 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
 * limit reclaim to prevent infinite loops, if they ever occur.
 */
210
#define	MEM_CGROUP_MAX_RECLAIM_LOOPS		100
211
#define	MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS	2
212

213 214
enum charge_type {
	MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
215
	MEM_CGROUP_CHARGE_TYPE_ANON,
216
	MEM_CGROUP_CHARGE_TYPE_SWAPOUT,	/* for accounting swapcache */
217
	MEM_CGROUP_CHARGE_TYPE_DROP,	/* a page was unused swap cache */
218 219 220
	NR_CHARGE_TYPE,
};

221
/* for encoding cft->private value on file */
222 223 224 225
enum res_type {
	_MEM,
	_MEMSWAP,
	_OOM_TYPE,
226
	_KMEM,
227
	_TCP,
228 229
};

230 231
#define MEMFILE_PRIVATE(x, val)	((x) << 16 | (val))
#define MEMFILE_TYPE(val)	((val) >> 16 & 0xffff)
232
#define MEMFILE_ATTR(val)	((val) & 0xffff)
KAMEZAWA Hiroyuki's avatar
KAMEZAWA Hiroyuki committed
233 234
/* Used for OOM nofiier */
#define OOM_CONTROL		(0)
235

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
/*
 * Iteration constructs for visiting all cgroups (under a tree).  If
 * loops are exited prematurely (break), mem_cgroup_iter_break() must
 * be used for reference counting.
 */
#define for_each_mem_cgroup_tree(iter, root)		\
	for (iter = mem_cgroup_iter(root, NULL, NULL);	\
	     iter != NULL;				\
	     iter = mem_cgroup_iter(root, iter, NULL))

#define for_each_mem_cgroup(iter)			\
	for (iter = mem_cgroup_iter(NULL, NULL, NULL);	\
	     iter != NULL;				\
	     iter = mem_cgroup_iter(NULL, iter, NULL))

251 252 253 254 255 256 257 258 259 260 261 262 263
/* Some nice accessors for the vmpressure. */
struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
{
	if (!memcg)
		memcg = root_mem_cgroup;
	return &memcg->vmpressure;
}

struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
{
	return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
}

264
#ifdef CONFIG_MEMCG_KMEM
265
/*
266
 * This will be the memcg's index in each cache's ->memcg_params.memcg_caches.
Li Zefan's avatar
Li Zefan committed
267 268 269 270 271
 * The main reason for not using cgroup id for this:
 *  this works better in sparse environments, where we have a lot of memcgs,
 *  but only a few kmem-limited. Or also, if we have, for instance, 200
 *  memcgs, and none but the 200th is kmem-limited, we'd have to have a
 *  200 entry array for that.
272
 *
273 274
 * The current size of the caches array is stored in memcg_nr_cache_ids. It
 * will double each time we have to increase it.
275
 */
276 277
static DEFINE_IDA(memcg_cache_ida);
int memcg_nr_cache_ids;
278

279 280 281 282 283 284 285 286 287 288 289 290 291
/* Protects memcg_nr_cache_ids */
static DECLARE_RWSEM(memcg_cache_ids_sem);

void memcg_get_cache_ids(void)
{
	down_read(&memcg_cache_ids_sem);
}

void memcg_put_cache_ids(void)
{
	up_read(&memcg_cache_ids_sem);
}

292 293 294 295 296 297
/*
 * MIN_SIZE is different than 1, because we would like to avoid going through
 * the alloc/free process all the time. In a small machine, 4 kmem-limited
 * cgroups is a reasonable guess. In the future, it could be a parameter or
 * tunable, but that is strictly not necessary.
 *
Li Zefan's avatar
Li Zefan committed
298
 * MAX_SIZE should be as large as the number of cgrp_ids. Ideally, we could get
299 300
 * this constant directly from cgroup, but it is understandable that this is
 * better kept as an internal representation in cgroup.c. In any case, the
Li Zefan's avatar
Li Zefan committed
301
 * cgrp_id space is not getting any smaller, and we don't have to necessarily
302 303 304
 * increase ours as well if it increases.
 */
#define MEMCG_CACHES_MIN_SIZE 4
Li Zefan's avatar
Li Zefan committed
305
#define MEMCG_CACHES_MAX_SIZE MEM_CGROUP_ID_MAX
306

307 308 309 310 311 312
/*
 * A lot of the calls to the cache allocation functions are expected to be
 * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
 * conditional to this static branch, we'll have to allow modules that does
 * kmem_cache_alloc and the such to see this symbol as well
 */
313
DEFINE_STATIC_KEY_FALSE(memcg_kmem_enabled_key);
314
EXPORT_SYMBOL(memcg_kmem_enabled_key);
315

316 317
struct workqueue_struct *memcg_kmem_cache_wq;

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
static int memcg_shrinker_map_size;
static DEFINE_MUTEX(memcg_shrinker_map_mutex);

static void memcg_free_shrinker_map_rcu(struct rcu_head *head)
{
	kvfree(container_of(head, struct memcg_shrinker_map, rcu));
}

static int memcg_expand_one_shrinker_map(struct mem_cgroup *memcg,
					 int size, int old_size)
{
	struct memcg_shrinker_map *new, *old;
	int nid;

	lockdep_assert_held(&memcg_shrinker_map_mutex);

	for_each_node(nid) {
		old = rcu_dereference_protected(
			mem_cgroup_nodeinfo(memcg, nid)->shrinker_map, true);
		/* Not yet online memcg */
		if (!old)
			return 0;

		new = kvmalloc(sizeof(*new) + size, GFP_KERNEL);
		if (!new)
			return -ENOMEM;

		/* Set all old bits, clear all new bits */
		memset(new->map, (int)0xff, old_size);
		memset((void *)new->map + old_size, 0, size - old_size);

		rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, new);
		call_rcu(&old->rcu, memcg_free_shrinker_map_rcu);
	}

	return 0;
}

static void memcg_free_shrinker_maps(struct mem_cgroup *memcg)
{
	struct mem_cgroup_per_node *pn;
	struct memcg_shrinker_map *map;
	int nid;

	if (mem_cgroup_is_root(memcg))
		return;

	for_each_node(nid) {
		pn = mem_cgroup_nodeinfo(memcg, nid);
		map = rcu_dereference_protected(pn->shrinker_map, true);
		if (map)
			kvfree(map);
		rcu_assign_pointer(pn->shrinker_map, NULL);
	}
}

static int memcg_alloc_shrinker_maps(struct mem_cgroup *memcg)
{
	struct memcg_shrinker_map *map;
	int nid, size, ret = 0;

	if (mem_cgroup_is_root(memcg))
		return 0;

	mutex_lock(&memcg_shrinker_map_mutex);
	size = memcg_shrinker_map_size;
	for_each_node(nid) {
		map = kvzalloc(sizeof(*map) + size, GFP_KERNEL);
		if (!map) {
			memcg_free_shrinker_maps(memcg);
			ret = -ENOMEM;
			break;
		}
		rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_map, map);
	}
	mutex_unlock(&memcg_shrinker_map_mutex);

	return ret;
}

int memcg_expand_shrinker_maps(int new_id)
{
	int size, old_size, ret = 0;
	struct mem_cgroup *memcg;

	size = DIV_ROUND_UP(new_id + 1, BITS_PER_LONG) * sizeof(unsigned long);
	old_size = memcg_shrinker_map_size;
	if (size <= old_size)
		return 0;

	mutex_lock(&memcg_shrinker_map_mutex);
	if (!root_mem_cgroup)
		goto unlock;

	for_each_mem_cgroup(memcg) {
		if (mem_cgroup_is_root(memcg))
			continue;
		ret = memcg_expand_one_shrinker_map(memcg, size, old_size);
		if (ret)
			goto unlock;
	}
unlock:
	if (!ret)
		memcg_shrinker_map_size = size;
	mutex_unlock(&memcg_shrinker_map_mutex);
	return ret;
}
425 426 427 428 429 430 431 432

void memcg_set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
{
	if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
		struct memcg_shrinker_map *map;

		rcu_read_lock();
		map = rcu_dereference(memcg->nodeinfo[nid]->shrinker_map);
433 434
		/* Pairs with smp mb in shrink_slab() */
		smp_mb__before_atomic();
435 436 437 438 439
		set_bit(shrinker_id, map->map);
		rcu_read_unlock();
	}
}

440 441 442 443 444 445
#else /* CONFIG_MEMCG_KMEM */
static int memcg_alloc_shrinker_maps(struct mem_cgroup *memcg)
{
	return 0;
}
static void memcg_free_shrinker_maps(struct mem_cgroup *memcg) { }
446
#endif /* CONFIG_MEMCG_KMEM */
447

448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
/**
 * mem_cgroup_css_from_page - css of the memcg associated with a page
 * @page: page of interest
 *
 * If memcg is bound to the default hierarchy, css of the memcg associated
 * with @page is returned.  The returned css remains associated with @page
 * until it is released.
 *
 * If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
 * is returned.
 */
struct cgroup_subsys_state *mem_cgroup_css_from_page(struct page *page)
{
	struct mem_cgroup *memcg;

	memcg = page->mem_cgroup;

465
	if (!memcg || !cgroup_subsys_on_dfl(memory_cgrp_subsys))
466 467 468 469 470
		memcg = root_mem_cgroup;

	return &memcg->css;
}

471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
/**
 * page_cgroup_ino - return inode number of the memcg a page is charged to
 * @page: the page
 *
 * Look up the closest online ancestor of the memory cgroup @page is charged to
 * and return its inode number or 0 if @page is not charged to any cgroup. It
 * is safe to call this function without holding a reference to @page.
 *
 * Note, this function is inherently racy, because there is nothing to prevent
 * the cgroup inode from getting torn down and potentially reallocated a moment
 * after page_cgroup_ino() returns, so it only should be used by callers that
 * do not care (such as procfs interfaces).
 */
ino_t page_cgroup_ino(struct page *page)
{
	struct mem_cgroup *memcg;
	unsigned long ino = 0;

	rcu_read_lock();
	memcg = READ_ONCE(page->mem_cgroup);
	while (memcg && !(memcg->css.flags & CSS_ONLINE))
		memcg = parent_mem_cgroup(memcg);
	if (memcg)
		ino = cgroup_ino(memcg->css.cgroup);
	rcu_read_unlock();
	return ino;
}

499 500
static struct mem_cgroup_per_node *
mem_cgroup_page_nodeinfo(struct mem_cgroup *memcg, struct page *page)
501
{
502
	int nid = page_to_nid(page);
503

504
	return memcg->nodeinfo[nid];
505 506
}

507 508
static struct mem_cgroup_tree_per_node *
soft_limit_tree_node(int nid)
509
{
510
	return soft_limit_tree.rb_tree_per_node[nid];
511 512
}

513
static struct mem_cgroup_tree_per_node *
514 515 516 517
soft_limit_tree_from_page(struct page *page)
{
	int nid = page_to_nid(page);

518
	return soft_limit_tree.rb_tree_per_node[nid];
519 520
}

521 522
static void __mem_cgroup_insert_exceeded(struct mem_cgroup_per_node *mz,
					 struct mem_cgroup_tree_per_node *mctz,
523
					 unsigned long new_usage_in_excess)
524 525 526
{
	struct rb_node **p = &mctz->rb_root.rb_node;
	struct rb_node *parent = NULL;
527
	struct mem_cgroup_per_node *mz_node;
528
	bool rightmost = true;
529 530 531 532 533 534 535 536 537

	if (mz->on_tree)
		return;

	mz->usage_in_excess = new_usage_in_excess;
	if (!mz->usage_in_excess)
		return;
	while (*p) {
		parent = *p;
538
		mz_node = rb_entry(parent, struct mem_cgroup_per_node,
539
					tree_node);
540
		if (mz->usage_in_excess < mz_node->usage_in_excess) {
541
			p = &(*p)->rb_left;
542 543 544
			rightmost = false;
		}

545 546 547 548 549 550 551
		/*
		 * We can't avoid mem cgroups that are over their soft
		 * limit by the same amount
		 */
		else if (mz->usage_in_excess >= mz_node->usage_in_excess)
			p = &(*p)->rb_right;
	}
552 553 554 555

	if (rightmost)
		mctz->rb_rightmost = &mz->tree_node;

556 557 558 559 560
	rb_link_node(&mz->tree_node, parent, p);
	rb_insert_color(&mz->tree_node, &mctz->rb_root);
	mz->on_tree = true;
}

561 562
static void __mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
					 struct mem_cgroup_tree_per_node *mctz)
563 564 565
{
	if (!mz->on_tree)
		return;
566 567 568 569

	if (&mz->tree_node == mctz->rb_rightmost)
		mctz->rb_rightmost = rb_prev(&mz->tree_node);

570 571 572 573
	rb_erase(&mz->tree_node, &mctz->rb_root);
	mz->on_tree = false;
}

574 575
static void mem_cgroup_remove_exceeded(struct mem_cgroup_per_node *mz,
				       struct mem_cgroup_tree_per_node *mctz)
576
{
577 578 579
	unsigned long flags;

	spin_lock_irqsave(&mctz->lock, flags);
580
	__mem_cgroup_remove_exceeded(mz, mctz);
581
	spin_unlock_irqrestore(&mctz->lock, flags);
582 583
}

584 585 586
static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
{
	unsigned long nr_pages = page_counter_read(&memcg->memory);
587
	unsigned long soft_limit = READ_ONCE(memcg->soft_limit);
588 589 590 591 592 593 594
	unsigned long excess = 0;

	if (nr_pages > soft_limit)
		excess = nr_pages - soft_limit;

	return excess;
}
595 596 597

static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
{
598
	unsigned long excess;
599 600
	struct mem_cgroup_per_node *mz;
	struct mem_cgroup_tree_per_node *mctz;
601

602
	mctz = soft_limit_tree_from_page(page);
603 604
	if (!mctz)
		return;
605 606 607 608 609
	/*
	 * Necessary to update all ancestors when hierarchy is used.
	 * because their event counter is not touched.
	 */
	for (; memcg; memcg = parent_mem_cgroup(memcg)) {
610
		mz = mem_cgroup_page_nodeinfo(memcg, page);
611
		excess = soft_limit_excess(memcg);
612 613 614 615 616
		/*
		 * We have to update the tree if mz is on RB-tree or
		 * mem is over its softlimit.
		 */
		if (excess || mz->on_tree) {
617 618 619
			unsigned long flags;

			spin_lock_irqsave(&mctz->lock, flags);
620 621
			/* if on-tree, remove it */
			if (mz->on_tree)
622
				__mem_cgroup_remove_exceeded(mz, mctz);
623 624 625 626
			/*
			 * Insert again. mz->usage_in_excess will be updated.
			 * If excess is 0, no tree ops.
			 */
627
			__mem_cgroup_insert_exceeded(mz, mctz, excess);
628
			spin_unlock_irqrestore(&mctz->lock, flags);
629 630 631 632 633 634
		}
	}
}

static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
{
635 636 637
	struct mem_cgroup_tree_per_node *mctz;
	struct mem_cgroup_per_node *mz;
	int nid;
638

639
	for_each_node(nid) {
640 641
		mz = mem_cgroup_nodeinfo(memcg, nid);
		mctz = soft_limit_tree_node(nid);
642 643
		if (mctz)
			mem_cgroup_remove_exceeded(mz, mctz);
644 645 646
	}
}

647 648
static struct mem_cgroup_per_node *
__mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
649
{
650
	struct mem_cgroup_per_node *mz;
651 652 653

retry:
	mz = NULL;
654
	if (!mctz->rb_rightmost)
655 656
		goto done;		/* Nothing to reclaim from */

657 658
	mz = rb_entry(mctz->rb_rightmost,
		      struct mem_cgroup_per_node, tree_node);
659 660 661 662 663
	/*
	 * Remove the node now but someone else can add it back,
	 * we will to add it back at the end of reclaim to its correct
	 * position in the tree.
	 */
664
	__mem_cgroup_remove_exceeded(mz, mctz);
665
	if (!soft_limit_excess(mz->memcg) ||
666
	    !css_tryget_online(&mz->memcg->css))
667 668 669 670 671
		goto retry;
done:
	return mz;
}

672 673
static struct mem_cgroup_per_node *
mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_node *mctz)
674
{
675
	struct mem_cgroup_per_node *mz;
676

677
	spin_lock_irq(&mctz->lock);
678
	mz = __mem_cgroup_largest_soft_limit_node(mctz);
679
	spin_unlock_irq(&mctz->lock);
680 681 682
	return mz;
}

683
static unsigned long memcg_sum_events(struct mem_cgroup *memcg,
684
				      int event)
685
{
686
	return atomic_long_read(&memcg->events[event]);
687 688
}

689
static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
690
					 struct page *page,
691
					 bool compound, int nr_pages)
692
{
693 694 695 696
	/*
	 * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
	 * counted as CACHE even if it's on ANON LRU.
	 */
697
	if (PageAnon(page))
698
		__mod_memcg_state(memcg, MEMCG_RSS, nr_pages);
699
	else {
700
		__mod_memcg_state(memcg, MEMCG_CACHE, nr_pages);
701
		if (PageSwapBacked(page))
702
			__mod_memcg_state(memcg, NR_SHMEM, nr_pages);
703
	}
704

705 706
	if (compound) {
		VM_BUG_ON_PAGE(!PageTransHuge(page), page);
707
		__mod_memcg_state(memcg, MEMCG_RSS_HUGE, nr_pages);
708
	}
709

710 711
	/* pagein of a big page is an event. So, ignore page size */
	if (nr_pages > 0)
712
		__count_memcg_events(memcg, PGPGIN, 1);
713
	else {
714
		__count_memcg_events(memcg, PGPGOUT, 1);
715 716
		nr_pages = -nr_pages; /* for event */
	}
717

718
	__this_cpu_add(memcg->stat_cpu->nr_page_events, nr_pages);
719 720
}

721 722
unsigned long mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
					   int nid, unsigned int lru_mask)
723
{
724
	struct lruvec *lruvec = mem_cgroup_lruvec(NODE_DATA(nid), memcg);
725
	unsigned long nr = 0;
726
	enum lru_list lru;
727

728
	VM_BUG_ON((unsigned)nid >= nr_node_ids);
729

730 731 732
	for_each_lru(lru) {
		if (!(BIT(lru) & lru_mask))
			continue;
733
		nr += mem_cgroup_get_lru_size(lruvec, lru);
734 735
	}
	return nr;
736
}
737

738
static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
739
			unsigned int lru_mask)
740
{
741
	unsigned long nr = 0;
742
	int nid;
743

744
	for_each_node_state(nid, N_MEMORY)
745 746
		nr += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
	return nr;
747 748
}

749 750
static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
				       enum mem_cgroup_events_target target)
751 752 753
{
	unsigned long val, next;

754 755
	val = __this_cpu_read(memcg->stat_cpu->nr_page_events);
	next = __this_cpu_read(memcg->stat_cpu->targets[target]);
756
	/* from time_after() in jiffies.h */
757
	if ((long)(next - val) < 0) {
758 759 760 761
		switch (target) {
		case MEM_CGROUP_TARGET_THRESH:
			next = val + THRESHOLDS_EVENTS_TARGET;
			break;
762 763 764
		case MEM_CGROUP_TARGET_SOFTLIMIT:
			next = val + SOFTLIMIT_EVENTS_TARGET;
			break;
765 766 767 768 769 770
		case MEM_CGROUP_TARGET_NUMAINFO:
			next = val + NUMAINFO_EVENTS_TARGET;
			break;
		default:
			break;
		}
771
		__this_cpu_write(memcg->stat_cpu->targets[target], next);
772
		return true;
773
	}
774
	return false;
775 776 777 778 779 780
}

/*
 * Check events in order.
 *
 */
781
static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
782 783
{
	/* threshold event is triggered in finer grain than soft limit */
784 785
	if (unlikely(mem_cgroup_event_ratelimit(memcg,
						MEM_CGROUP_TARGET_THRESH))) {
786
		bool do_softlimit;
787
		bool do_numainfo __maybe_unused;
788

789 790
		do_softlimit = mem_cgroup_event_ratelimit(memcg,
						MEM_CGROUP_TARGET_SOFTLIMIT);
791 792 793 794
#if MAX_NUMNODES > 1
		do_numainfo = mem_cgroup_event_ratelimit(memcg,
						MEM_CGROUP_TARGET_NUMAINFO);
#endif
795
		mem_cgroup_threshold(memcg);
796 797
		if (unlikely(do_softlimit))
			mem_cgroup_update_tree(memcg, page);
798
#if MAX_NUMNODES > 1
799
		if (unlikely(do_numainfo))
800
			atomic_inc(&memcg->numainfo_events);
801
#endif
802
	}
803 804
}

805
struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
806
{
807 808 809 810 811 812 813 814
	/*
	 * mm_update_next_owner() may clear mm->owner to NULL
	 * if it races with swapoff, page migration, etc.
	 * So this can be called with p == NULL.
	 */
	if (unlikely(!p))
		return NULL;

815
	return mem_cgroup_from_css(task_css(p, memory_cgrp_id));
816
}
817
EXPORT_SYMBOL(mem_cgroup_from_task);
818

819 820 821 822 823 824 825 826 827
/**
 * get_mem_cgroup_from_mm: Obtain a reference on given mm_struct's memcg.
 * @mm: mm from which memcg should be extracted. It can be NULL.
 *
 * Obtain a reference on mm->memcg and returns it if successful. Otherwise
 * root_mem_cgroup is returned. However if mem_cgroup is disabled, NULL is
 * returned.
 */
struct mem_cgroup *get_mem_cgroup_from_mm(struct mm_struct *mm)
828
{
829 830 831 832
	struct mem_cgroup *memcg;

	if (mem_cgroup_disabled())
		return NULL;
833

834 835
	rcu_read_lock();
	do {
836 837 838 839 840 841
		/*
		 * Page cache insertions can happen withou an
		 * actual mm context, e.g. during disk probing
		 * on boot, loopback IO, acct() writes etc.
		 */
		if (unlikely(!mm))
842
			memcg = root_mem_cgroup;
843 844 845 846 847
		else {
			memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
			if (unlikely(!memcg))
				memcg = root_mem_cgroup;
		}
848
	} while (!css_tryget_online(&memcg->css));
849
	rcu_read_unlock();
850
	return memcg;
851
}
852 853
EXPORT_SYMBOL(get_mem_cgroup_from_mm);

854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
/**
 * get_mem_cgroup_from_page: Obtain a reference on given page's memcg.
 * @page: page from which memcg should be extracted.
 *
 * Obtain a reference on page->memcg and returns it if successful. Otherwise
 * root_mem_cgroup is returned.
 */
struct mem_cgroup *get_mem_cgroup_from_page(struct page *page)
{
	struct mem_cgroup *memcg = page->mem_cgroup;

	if (mem_cgroup_disabled())
		return NULL;

	rcu_read_lock();
	if (!memcg || !css_tryget_online(&memcg->css))
		memcg = root_mem_cgroup;
	rcu_read_unlock();
	return memcg;
}
EXPORT_SYMBOL(get_mem_cgroup_from_page);

876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
/**
 * If current->active_memcg is non-NULL, do not fallback to current->mm->memcg.
 */
static __always_inline struct mem_cgroup *get_mem_cgroup_from_current(void)
{
	if (unlikely(current->active_memcg)) {
		struct mem_cgroup *memcg = root_mem_cgroup;

		rcu_read_lock();
		if (css_tryget_online(&current->active_memcg->css))
			memcg = current->active_memcg;
		rcu_read_unlock();
		return memcg;
	}
	return get_mem_cgroup_from_mm(current->mm);
}
892

893 894 895 896 897 898 899 900 901 902 903 904 905
/**
 * mem_cgroup_iter - iterate over memory cgroup hierarchy
 * @root: hierarchy root
 * @prev: previously returned memcg, NULL on first invocation
 * @reclaim: cookie for shared reclaim walks, NULL for full walks
 *
 * Returns references to children of the hierarchy below @root, or
 * @root itself, or %NULL after a full round-trip.
 *
 * Caller must pass the return value in @prev on subsequent
 * invocations for reference counting, or use mem_cgroup_iter_break()
 * to cancel a hierarchy walk before the round-trip is complete.
 *
906
 * Reclaimers can specify a node and a priority level in @reclaim to
907
 * divide up the memcgs in the hierarchy among all concurrent
908
 * reclaimers operating on the same node and priority.
909
 */
910
struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
911
				   struct mem_cgroup *prev,
912
				   struct mem_cgroup_reclaim_cookie *reclaim)
913
{
914
	struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
915
	struct cgroup_subsys_state *css = NULL;
916
	struct mem_cgroup *memcg = NULL;
917
	struct mem_cgroup *pos = NULL;
918

919 920
	if (mem_cgroup_disabled())
		return NULL;
921

922 923
	if (!root)
		root = root_mem_cgroup;
924

925
	if (prev && !reclaim)
926
		pos = prev;
927

928 929
	if (!root->use_hierarchy && root != root_mem_cgroup) {
		if (prev)
930
			goto out;
931
		return root;
932
	}
933

934
	rcu_read_lock();
935

936
	if (reclaim) {
937
		struct mem_cgroup_per_node *mz;
938

939
		mz = mem_cgroup_nodeinfo(root, reclaim->pgdat->node_id);
940 941 942 943 944
		iter = &mz->iter[reclaim->priority];

		if (prev && reclaim->generation != iter->generation)
			goto out_unlock;

945
		while (1) {
946
			pos = READ_ONCE(iter->position);
947 948
			if (!pos || css_tryget(&pos->css))
				break;
949
			/*
950 951 952 953 954 955
			 * css reference reached zero, so iter->position will
			 * be cleared by ->css_released. However, we should not
			 * rely on this happening soon, because ->css_released
			 * is called from a work queue, and by busy-waiting we
			 * might block it. So we clear iter->position right
			 * away.
956
			 */
957 958
			(void)cmpxchg(&iter->position, pos, NULL);
		}
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
	}

	if (pos)
		css = &pos->css;

	for (;;) {
		css = css_next_descendant_pre(css, &root->css);
		if (!css) {
			/*
			 * Reclaimers share the hierarchy walk, and a
			 * new one might jump in right at the end of
			 * the hierarchy - make sure they see at least
			 * one group and restart from the beginning.
			 */
			if (!prev)
				continue;
			break;
976
		}
977

978 979 980 981 982 983
		/*
		 * Verify the css and acquire a reference.  The root
		 * is provided by the caller, so we know it's alive
		 * and kicking, and don't take an extra reference.
		 */
		memcg = mem_cgroup_from_css(css);
984

985 986
		if (css == &root->css)
			break;
987

988 989
		if (css_tryget(css))
			break;
990

991
		memcg = NULL;
992
	}
993 994 995

	if (reclaim) {
		/*
996 997 998
		 * The position could have already been updated by a competing
		 * thread, so check that the value hasn't changed since we read
		 * it to avoid reclaiming from the same cgroup twice.
999
		 */
1000 1001
		(void)cmpxchg(&iter->position, pos, memcg);

1002 1003 1004 1005 1006 1007 1008
		if (pos)
			css_put(&pos->css);

		if (!memcg)
			iter->generation++;
		else if (!prev)
			reclaim->generation = iter->generation;
1009
	}
1010

1011 1012
out_unlock:
	rcu_read_unlock();
1013
out:
1014 1015 1016
	if (prev && prev != root)
		css_put(&prev->css);

1017
	return memcg;
1018
}
1019

1020 1021 1022 1023 1024 1025 1026
/**
 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
 * @root: hierarchy root
 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
 */
void mem_cgroup_iter_break(struct mem_cgroup *root,
			   struct mem_cgroup *prev)
1027 1028 1029 1030 1031 1032
{
	if (!root)
		root = root_mem_cgroup;
	if (prev && prev != root)
		css_put(&prev->css);
}
1033

1034 1035 1036 1037
static void invalidate_reclaim_iterators(struct mem_cgroup *dead_memcg)
{
	struct mem_cgroup *memcg = dead_memcg;
	struct mem_cgroup_reclaim_iter *iter;
1038 1039
	struct mem_cgroup_per_node *mz;
	int nid;
1040 1041
	int i;

1042
	for (; memcg; memcg = parent_mem_cgroup(memcg)) {
1043
		for_each_node(nid) {
1044 1045 1046 1047 1048
			mz = mem_cgroup_nodeinfo(memcg, nid);
			for (i = 0; i <= DEF_PRIORITY; i++) {
				iter = &mz->iter[i];
				cmpxchg(&iter->position,
					dead_memcg, NULL);
1049 1050 1051 1052 1053
			}
		}
	}
}

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
/**
 * mem_cgroup_scan_tasks - iterate over tasks of a memory cgroup hierarchy
 * @memcg: hierarchy root
 * @fn: function to call for each task
 * @arg: argument passed to @fn
 *
 * This function iterates over tasks attached to @memcg or to any of its
 * descendants and calls @fn for each task. If @fn returns a non-zero
 * value, the function breaks the iteration loop and returns the value.
 * Otherwise, it will iterate over all tasks and return 0.
 *
 * This function must not be called for the root memory cgroup.
 */
int mem_cgroup_scan_tasks(struct mem_cgroup *memcg,
			  int (*fn)(struct task_struct *, void *), void *arg)
{
	struct mem_cgroup *iter;
	int ret = 0;

	BUG_ON(memcg == root_mem_cgroup);

	for_each_mem_cgroup_tree(iter, memcg) {
		struct css_task_iter it;
		struct task_struct *task;

1079
		css_task_iter_start(&iter->css, 0, &it);
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
		while (!ret && (task = css_task_iter_next(&it)))
			ret = fn(task, arg);
		css_task_iter_end(&it);
		if (ret) {
			mem_cgroup_iter_break(memcg, iter);
			break;
		}
	}
	return ret;
}

1091
/**
1092
 * mem_cgroup_page_lruvec - return lruvec for isolating/putting an LRU page
1093
 * @page: the page
1094
 * @pgdat: pgdat of the page
1095 1096 1097 1098
 *
 * This function is only safe when following the LRU page isolation
 * and putback protocol: the LRU lock must be held, and the page must
 * either be PageLRU() or the caller must have isolated/allocated it.
1099
 */
1100
struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct pglist_data *pgdat)
1101
{
1102
	struct mem_cgroup_per_node *mz;
1103
	struct mem_cgroup *memcg;
1104
	struct lruvec *lruvec;
1105

1106
	if (mem_cgroup_disabled()) {
1107
		lruvec = &pgdat->lruvec;
1108 1109
		goto out;
	}
1110

1111
	memcg = page->mem_cgroup;
1112
	/*
1113
	 * Swapcache readahead pages are added to the LRU - and
1114
	 * possibly migrated - before they are charged.
1115
	 */
1116 1117
	if (!memcg)
		memcg = root_mem_cgroup;
1118

1119
	mz = mem_cgroup_page_nodeinfo(memcg, page);
1120 1121 1122 1123 1124 1125 1126
	lruvec = &mz->lruvec;
out:
	/*
	 * Since a node can be onlined after the mem_cgroup was created,
	 * we have to be prepared to initialize lruvec->zone here;
	 * and if offlined then reonlined, we need to reinitialize it.
	 */
1127 1128
	if (unlikely(lruvec->pgdat != pgdat))
		lruvec->pgdat = pgdat;
1129
	return lruvec;
1130
}
1131

1132
/**
1133 1134 1135
 * mem_cgroup_update_lru_size - account for adding or removing an lru page
 * @lruvec: mem_cgroup per zone lru vector
 * @lru: index of lru list the page is sitting on
1136
 * @zid: zone id of the accounted pages
1137
 * @nr_pages: positive when adding or negative when removing
1138
 *
1139 1140 1141
 * This function must be called under lru_lock, just before a page is added
 * to or just after a page is removed from an lru list (that ordering being
 * so as to allow it to check that lru_size 0 is consistent with list_empty).
1142
 */
1143
void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1144
				int zid, int nr_pages)
1145
{
1146
	struct mem_cgroup_per_node *mz;
1147
	unsigned long *lru_size;
1148
	long size;
1149 1150 1151 1152

	if (mem_cgroup_disabled())
		return;

1153
	mz = container_of(lruvec, struct mem_cgroup_per_node, lruvec);
1154
	lru_size = &mz->lru_zone_size[zid][lru];
1155 1156 1157 1158 1159

	if (nr_pages < 0)
		*lru_size += nr_pages;

	size = *lru_size;
1160 1161 1162
	if (WARN_ONCE(size < 0,
		"%s(%p, %d, %d): lru_size %ld\n",
		__func__, lruvec, lru, nr_pages, size)) {
1163 1164 1165 1166 1167 1168
		VM_BUG_ON(1);
		*lru_size = 0;
	}

	if (nr_pages > 0)
		*lru_size += nr_pages;
1169
}
1170

1171
bool task_in_mem_cgroup(struct task_struct *task, struct mem_cgroup *memcg)
1172
{
1173
	struct mem_cgroup *task_memcg;
1174
	struct task_struct *p;
1175
	bool ret;
1176

1177
	p = find_lock_task_mm(task);
1178
	if (p) {
1179
		task_memcg = get_mem_cgroup_from_mm(p->mm);
1180 1181 1182 1183 1184 1185 1186
		task_unlock(p);
	} else {
		/*
		 * All threads may have already detached their mm's, but the oom
		 * killer still needs to detect if they have already been oom
		 * killed to prevent needlessly killing additional tasks.
		 */
1187
		rcu_read_lock();
1188 1189
		task_memcg = mem_cgroup_from_task(task);
		css_get(&task_memcg->css);
1190
		rcu_read_unlock();
1191
	}
1192 1193
	ret = mem_cgroup_is_descendant(task_memcg, memcg);
	css_put(&task_memcg->css);
1194 1195 1196
	return ret;
}

1197
/**
1198
 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
Wanpeng Li's avatar
Wanpeng Li committed
1199
 * @memcg: the memory cgroup
1200
 *
1201
 * Returns the maximum amount of memory @mem can be charged with, in
1202
 * pages.
1203
 */
1204
static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1205
{
1206 1207 1208
	unsigned long margin = 0;
	unsigned long count;
	unsigned long limit;
1209

1210
	count = page_counter_read(&memcg->memory);
1211
	limit = READ_ONCE(memcg->memory.max);
1212 1213 1214
	if (count < limit)
		margin = limit - count;

1215
	if (do_memsw_account()) {
1216
		count = page_counter_read(&memcg->memsw);
1217
		limit = READ_ONCE(memcg->memsw.max);
1218 1219
		if (count <= limit)
			margin = min(margin, limit - count);
1220 1221
		else
			margin = 0;
1222 1223 1224
	}

	return margin;
1225 1226
}

1227
/*
1228
 * A routine for checking "mem" is under move_account() or not.
1229
 *
1230 1231 1232
 * Checking a cgroup is mc.from or mc.to or under hierarchy of
 * moving cgroups. This is for waiting at high-memory pressure
 * caused by "move".
1233
 */
1234
static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1235
{
1236 1237
	struct mem_cgroup *from;
	struct mem_cgroup *to;
1238
	bool ret = false;
1239 1240 1241 1242 1243 1244 1245 1246 1247
	/*
	 * Unlike task_move routines, we access mc.to, mc.from not under
	 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
	 */
	spin_lock(&mc.lock);
	from = mc.from;
	to = mc.to;
	if (!from)
		goto unlock;
1248

1249 1250
	ret = mem_cgroup_is_descendant(from, memcg) ||
		mem_cgroup_is_descendant(to, memcg);
1251 1252
unlock:
	spin_unlock(&mc.lock);
1253 1254 1255
	return ret;
}

1256
static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1257 1258
{
	if (mc.moving_task && current != mc.moving_task) {
1259
		if (mem_cgroup_under_move(memcg)) {
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
			DEFINE_WAIT(wait);
			prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
			/* moving charge context might have finished. */
			if (mc.moving_task)
				schedule();
			finish_wait(&mc.waitq, &wait);
			return true;
		}
	}
	return false;
}

1272
static const unsigned int memcg1_stats[] = {
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
	MEMCG_CACHE,
	MEMCG_RSS,
	MEMCG_RSS_HUGE,
	NR_SHMEM,
	NR_FILE_MAPPED,
	NR_FILE_DIRTY,
	NR_WRITEBACK,
	MEMCG_SWAP,
};

static const char *const memcg1_stat_names[] = {
	"cache",
	"rss",
	"rss_huge",
	"shmem",
	"mapped_file",
	"dirty",
	"writeback",
	"swap",
};

1294
#define K(x) ((x) << (PAGE_SHIFT-10))
1295
/**
1296
 * mem_cgroup_print_oom_info: Print OOM information relevant to memory controller.
1297 1298 1299 1300 1301 1302 1303 1304
 * @memcg: The memory cgroup that went over limit
 * @p: Task that is going to be killed
 *
 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
 * enabled
 */
void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
{
1305 1306
	struct mem_cgroup *iter;
	unsigned int i;
1307 1308