1 /* memcontrol.c - Memory Controller 2 * 3 * Copyright IBM Corporation, 2007 4 * Author Balbir Singh <balbir@linux.vnet.ibm.com> 5 * 6 * Copyright 2007 OpenVZ SWsoft Inc 7 * Author: Pavel Emelianov <xemul@openvz.org> 8 * 9 * Memory thresholds 10 * Copyright (C) 2009 Nokia Corporation 11 * Author: Kirill A. Shutemov 12 * 13 * This program is free software; you can redistribute it and/or modify 14 * it under the terms of the GNU General Public License as published by 15 * the Free Software Foundation; either version 2 of the License, or 16 * (at your option) any later version. 17 * 18 * This program is distributed in the hope that it will be useful, 19 * but WITHOUT ANY WARRANTY; without even the implied warranty of 20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 21 * GNU General Public License for more details. 22 */ 23 24 #include <linux/res_counter.h> 25 #include <linux/memcontrol.h> 26 #include <linux/cgroup.h> 27 #include <linux/mm.h> 28 #include <linux/hugetlb.h> 29 #include <linux/pagemap.h> 30 #include <linux/smp.h> 31 #include <linux/page-flags.h> 32 #include <linux/backing-dev.h> 33 #include <linux/bit_spinlock.h> 34 #include <linux/rcupdate.h> 35 #include <linux/limits.h> 36 #include <linux/export.h> 37 #include <linux/mutex.h> 38 #include <linux/rbtree.h> 39 #include <linux/slab.h> 40 #include <linux/swap.h> 41 #include <linux/swapops.h> 42 #include <linux/spinlock.h> 43 #include <linux/eventfd.h> 44 #include <linux/sort.h> 45 #include <linux/fs.h> 46 #include <linux/seq_file.h> 47 #include <linux/vmalloc.h> 48 #include <linux/mm_inline.h> 49 #include <linux/page_cgroup.h> 50 #include <linux/cpu.h> 51 #include <linux/oom.h> 52 #include "internal.h" 53 #include <net/sock.h> 54 #include <net/tcp_memcontrol.h> 55 56 #include <asm/uaccess.h> 57 58 #include <trace/events/vmscan.h> 59 60 struct cgroup_subsys mem_cgroup_subsys __read_mostly; 61 #define MEM_CGROUP_RECLAIM_RETRIES 5 62 struct mem_cgroup *root_mem_cgroup __read_mostly; 63 64 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP 65 /* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */ 66 int do_swap_account __read_mostly; 67 68 /* for remember boot option*/ 69 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP_ENABLED 70 static int really_do_swap_account __initdata = 1; 71 #else 72 static int really_do_swap_account __initdata = 0; 73 #endif 74 75 #else 76 #define do_swap_account (0) 77 #endif 78 79 80 /* 81 * Statistics for memory cgroup. 82 */ 83 enum mem_cgroup_stat_index { 84 /* 85 * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss. 86 */ 87 MEM_CGROUP_STAT_CACHE, /* # of pages charged as cache */ 88 MEM_CGROUP_STAT_RSS, /* # of pages charged as anon rss */ 89 MEM_CGROUP_STAT_FILE_MAPPED, /* # of pages charged as file rss */ 90 MEM_CGROUP_STAT_SWAPOUT, /* # of pages, swapped out */ 91 MEM_CGROUP_STAT_DATA, /* end of data requires synchronization */ 92 MEM_CGROUP_ON_MOVE, /* someone is moving account between groups */ 93 MEM_CGROUP_STAT_NSTATS, 94 }; 95 96 enum mem_cgroup_events_index { 97 MEM_CGROUP_EVENTS_PGPGIN, /* # of pages paged in */ 98 MEM_CGROUP_EVENTS_PGPGOUT, /* # of pages paged out */ 99 MEM_CGROUP_EVENTS_COUNT, /* # of pages paged in/out */ 100 MEM_CGROUP_EVENTS_PGFAULT, /* # of page-faults */ 101 MEM_CGROUP_EVENTS_PGMAJFAULT, /* # of major page-faults */ 102 MEM_CGROUP_EVENTS_NSTATS, 103 }; 104 /* 105 * Per memcg event counter is incremented at every pagein/pageout. With THP, 106 * it will be incremated by the number of pages. This counter is used for 107 * for trigger some periodic events. This is straightforward and better 108 * than using jiffies etc. to handle periodic memcg event. 109 */ 110 enum mem_cgroup_events_target { 111 MEM_CGROUP_TARGET_THRESH, 112 MEM_CGROUP_TARGET_SOFTLIMIT, 113 MEM_CGROUP_TARGET_NUMAINFO, 114 MEM_CGROUP_NTARGETS, 115 }; 116 #define THRESHOLDS_EVENTS_TARGET (128) 117 #define SOFTLIMIT_EVENTS_TARGET (1024) 118 #define NUMAINFO_EVENTS_TARGET (1024) 119 120 struct mem_cgroup_stat_cpu { 121 long count[MEM_CGROUP_STAT_NSTATS]; 122 unsigned long events[MEM_CGROUP_EVENTS_NSTATS]; 123 unsigned long targets[MEM_CGROUP_NTARGETS]; 124 }; 125 126 /* 127 * per-zone information in memory controller. 128 */ 129 struct mem_cgroup_per_zone { 130 /* 131 * spin_lock to protect the per cgroup LRU 132 */ 133 struct list_head lists[NR_LRU_LISTS]; 134 unsigned long count[NR_LRU_LISTS]; 135 136 struct zone_reclaim_stat reclaim_stat; 137 struct rb_node tree_node; /* RB tree node */ 138 unsigned long long usage_in_excess;/* Set to the value by which */ 139 /* the soft limit is exceeded*/ 140 bool on_tree; 141 struct mem_cgroup *mem; /* Back pointer, we cannot */ 142 /* use container_of */ 143 }; 144 /* Macro for accessing counter */ 145 #define MEM_CGROUP_ZSTAT(mz, idx) ((mz)->count[(idx)]) 146 147 struct mem_cgroup_per_node { 148 struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES]; 149 }; 150 151 struct mem_cgroup_lru_info { 152 struct mem_cgroup_per_node *nodeinfo[MAX_NUMNODES]; 153 }; 154 155 /* 156 * Cgroups above their limits are maintained in a RB-Tree, independent of 157 * their hierarchy representation 158 */ 159 160 struct mem_cgroup_tree_per_zone { 161 struct rb_root rb_root; 162 spinlock_t lock; 163 }; 164 165 struct mem_cgroup_tree_per_node { 166 struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES]; 167 }; 168 169 struct mem_cgroup_tree { 170 struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES]; 171 }; 172 173 static struct mem_cgroup_tree soft_limit_tree __read_mostly; 174 175 struct mem_cgroup_threshold { 176 struct eventfd_ctx *eventfd; 177 u64 threshold; 178 }; 179 180 /* For threshold */ 181 struct mem_cgroup_threshold_ary { 182 /* An array index points to threshold just below usage. */ 183 int current_threshold; 184 /* Size of entries[] */ 185 unsigned int size; 186 /* Array of thresholds */ 187 struct mem_cgroup_threshold entries[0]; 188 }; 189 190 struct mem_cgroup_thresholds { 191 /* Primary thresholds array */ 192 struct mem_cgroup_threshold_ary *primary; 193 /* 194 * Spare threshold array. 195 * This is needed to make mem_cgroup_unregister_event() "never fail". 196 * It must be able to store at least primary->size - 1 entries. 197 */ 198 struct mem_cgroup_threshold_ary *spare; 199 }; 200 201 /* for OOM */ 202 struct mem_cgroup_eventfd_list { 203 struct list_head list; 204 struct eventfd_ctx *eventfd; 205 }; 206 207 static void mem_cgroup_threshold(struct mem_cgroup *memcg); 208 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg); 209 210 /* 211 * The memory controller data structure. The memory controller controls both 212 * page cache and RSS per cgroup. We would eventually like to provide 213 * statistics based on the statistics developed by Rik Van Riel for clock-pro, 214 * to help the administrator determine what knobs to tune. 215 * 216 * TODO: Add a water mark for the memory controller. Reclaim will begin when 217 * we hit the water mark. May be even add a low water mark, such that 218 * no reclaim occurs from a cgroup at it's low water mark, this is 219 * a feature that will be implemented much later in the future. 220 */ 221 struct mem_cgroup { 222 struct cgroup_subsys_state css; 223 /* 224 * the counter to account for memory usage 225 */ 226 struct res_counter res; 227 /* 228 * the counter to account for mem+swap usage. 229 */ 230 struct res_counter memsw; 231 /* 232 * the counter to account for kmem usage. 233 */ 234 struct res_counter kmem; 235 /* 236 * Per cgroup active and inactive list, similar to the 237 * per zone LRU lists. 238 */ 239 struct mem_cgroup_lru_info info; 240 /* 241 * While reclaiming in a hierarchy, we cache the last child we 242 * reclaimed from. 243 */ 244 int last_scanned_child; 245 int last_scanned_node; 246 #if MAX_NUMNODES > 1 247 nodemask_t scan_nodes; 248 atomic_t numainfo_events; 249 atomic_t numainfo_updating; 250 #endif 251 /* 252 * Should the accounting and control be hierarchical, per subtree? 253 */ 254 bool use_hierarchy; 255 256 bool oom_lock; 257 atomic_t under_oom; 258 259 atomic_t refcnt; 260 261 int swappiness; 262 /* OOM-Killer disable */ 263 int oom_kill_disable; 264 265 /* set when res.limit == memsw.limit */ 266 bool memsw_is_minimum; 267 268 /* protect arrays of thresholds */ 269 struct mutex thresholds_lock; 270 271 /* thresholds for memory usage. RCU-protected */ 272 struct mem_cgroup_thresholds thresholds; 273 274 /* thresholds for mem+swap usage. RCU-protected */ 275 struct mem_cgroup_thresholds memsw_thresholds; 276 277 /* For oom notifier event fd */ 278 struct list_head oom_notify; 279 280 /* 281 * Should we move charges of a task when a task is moved into this 282 * mem_cgroup ? And what type of charges should we move ? 283 */ 284 unsigned long move_charge_at_immigrate; 285 /* 286 * Should kernel memory limits be stabilished independently 287 * from user memory ? 288 */ 289 int kmem_independent_accounting; 290 /* 291 * percpu counter. 292 */ 293 struct mem_cgroup_stat_cpu *stat; 294 /* 295 * used when a cpu is offlined or other synchronizations 296 * See mem_cgroup_read_stat(). 297 */ 298 struct mem_cgroup_stat_cpu nocpu_base; 299 spinlock_t pcp_counter_lock; 300 301 #ifdef CONFIG_INET 302 struct tcp_memcontrol tcp_mem; 303 #endif 304 }; 305 306 /* Stuffs for move charges at task migration. */ 307 /* 308 * Types of charges to be moved. "move_charge_at_immitgrate" is treated as a 309 * left-shifted bitmap of these types. 310 */ 311 enum move_type { 312 MOVE_CHARGE_TYPE_ANON, /* private anonymous page and swap of it */ 313 MOVE_CHARGE_TYPE_FILE, /* file page(including tmpfs) and swap of it */ 314 NR_MOVE_TYPE, 315 }; 316 317 /* "mc" and its members are protected by cgroup_mutex */ 318 static struct move_charge_struct { 319 spinlock_t lock; /* for from, to */ 320 struct mem_cgroup *from; 321 struct mem_cgroup *to; 322 unsigned long precharge; 323 unsigned long moved_charge; 324 unsigned long moved_swap; 325 struct task_struct *moving_task; /* a task moving charges */ 326 wait_queue_head_t waitq; /* a waitq for other context */ 327 } mc = { 328 .lock = __SPIN_LOCK_UNLOCKED(mc.lock), 329 .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq), 330 }; 331 332 static bool move_anon(void) 333 { 334 return test_bit(MOVE_CHARGE_TYPE_ANON, 335 &mc.to->move_charge_at_immigrate); 336 } 337 338 static bool move_file(void) 339 { 340 return test_bit(MOVE_CHARGE_TYPE_FILE, 341 &mc.to->move_charge_at_immigrate); 342 } 343 344 /* 345 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft 346 * limit reclaim to prevent infinite loops, if they ever occur. 347 */ 348 #define MEM_CGROUP_MAX_RECLAIM_LOOPS (100) 349 #define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS (2) 350 351 enum charge_type { 352 MEM_CGROUP_CHARGE_TYPE_CACHE = 0, 353 MEM_CGROUP_CHARGE_TYPE_MAPPED, 354 MEM_CGROUP_CHARGE_TYPE_SHMEM, /* used by page migration of shmem */ 355 MEM_CGROUP_CHARGE_TYPE_FORCE, /* used by force_empty */ 356 MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */ 357 MEM_CGROUP_CHARGE_TYPE_DROP, /* a page was unused swap cache */ 358 NR_CHARGE_TYPE, 359 }; 360 361 /* for encoding cft->private value on file */ 362 363 enum mem_type { 364 _MEM = 0, 365 _MEMSWAP, 366 _OOM_TYPE, 367 _KMEM, 368 }; 369 370 #define MEMFILE_PRIVATE(x, val) (((x) << 16) | (val)) 371 #define MEMFILE_TYPE(val) (((val) >> 16) & 0xffff) 372 #define MEMFILE_ATTR(val) ((val) & 0xffff) 373 /* Used for OOM nofiier */ 374 #define OOM_CONTROL (0) 375 376 /* 377 * Reclaim flags for mem_cgroup_hierarchical_reclaim 378 */ 379 #define MEM_CGROUP_RECLAIM_NOSWAP_BIT 0x0 380 #define MEM_CGROUP_RECLAIM_NOSWAP (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT) 381 #define MEM_CGROUP_RECLAIM_SHRINK_BIT 0x1 382 #define MEM_CGROUP_RECLAIM_SHRINK (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT) 383 #define MEM_CGROUP_RECLAIM_SOFT_BIT 0x2 384 #define MEM_CGROUP_RECLAIM_SOFT (1 << MEM_CGROUP_RECLAIM_SOFT_BIT) 385 386 static void mem_cgroup_get(struct mem_cgroup *memcg); 387 static void mem_cgroup_put(struct mem_cgroup *memcg); 388 389 /* Writing them here to avoid exposing memcg's inner layout */ 390 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_KMEM 391 #ifdef CONFIG_INET 392 #include <net/sock.h> 393 #include <net/ip.h> 394 395 static bool mem_cgroup_is_root(struct mem_cgroup *memcg); 396 void sock_update_memcg(struct sock *sk) 397 { 398 /* A socket spends its whole life in the same cgroup */ 399 if (sk->sk_cgrp) { 400 WARN_ON(1); 401 return; 402 } 403 if (static_branch(&memcg_socket_limit_enabled)) { 404 struct mem_cgroup *memcg; 405 406 BUG_ON(!sk->sk_prot->proto_cgroup); 407 408 rcu_read_lock(); 409 memcg = mem_cgroup_from_task(current); 410 if (!mem_cgroup_is_root(memcg)) { 411 mem_cgroup_get(memcg); 412 sk->sk_cgrp = sk->sk_prot->proto_cgroup(memcg); 413 } 414 rcu_read_unlock(); 415 } 416 } 417 EXPORT_SYMBOL(sock_update_memcg); 418 419 void sock_release_memcg(struct sock *sk) 420 { 421 if (static_branch(&memcg_socket_limit_enabled) && sk->sk_cgrp) { 422 struct mem_cgroup *memcg; 423 WARN_ON(!sk->sk_cgrp->memcg); 424 memcg = sk->sk_cgrp->memcg; 425 mem_cgroup_put(memcg); 426 } 427 } 428 429 struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg) 430 { 431 if (!memcg || mem_cgroup_is_root(memcg)) 432 return NULL; 433 434 return &memcg->tcp_mem.cg_proto; 435 } 436 EXPORT_SYMBOL(tcp_proto_cgroup); 437 #endif /* CONFIG_INET */ 438 #endif /* CONFIG_CGROUP_MEM_RES_CTLR_KMEM */ 439 440 static void drain_all_stock_async(struct mem_cgroup *memcg); 441 442 static struct mem_cgroup_per_zone * 443 mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid) 444 { 445 return &memcg->info.nodeinfo[nid]->zoneinfo[zid]; 446 } 447 448 struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg) 449 { 450 return &memcg->css; 451 } 452 453 static struct mem_cgroup_per_zone * 454 page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page) 455 { 456 int nid = page_to_nid(page); 457 int zid = page_zonenum(page); 458 459 return mem_cgroup_zoneinfo(memcg, nid, zid); 460 } 461 462 static struct mem_cgroup_tree_per_zone * 463 soft_limit_tree_node_zone(int nid, int zid) 464 { 465 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid]; 466 } 467 468 static struct mem_cgroup_tree_per_zone * 469 soft_limit_tree_from_page(struct page *page) 470 { 471 int nid = page_to_nid(page); 472 int zid = page_zonenum(page); 473 474 return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid]; 475 } 476 477 static void 478 __mem_cgroup_insert_exceeded(struct mem_cgroup *memcg, 479 struct mem_cgroup_per_zone *mz, 480 struct mem_cgroup_tree_per_zone *mctz, 481 unsigned long long new_usage_in_excess) 482 { 483 struct rb_node **p = &mctz->rb_root.rb_node; 484 struct rb_node *parent = NULL; 485 struct mem_cgroup_per_zone *mz_node; 486 487 if (mz->on_tree) 488 return; 489 490 mz->usage_in_excess = new_usage_in_excess; 491 if (!mz->usage_in_excess) 492 return; 493 while (*p) { 494 parent = *p; 495 mz_node = rb_entry(parent, struct mem_cgroup_per_zone, 496 tree_node); 497 if (mz->usage_in_excess < mz_node->usage_in_excess) 498 p = &(*p)->rb_left; 499 /* 500 * We can't avoid mem cgroups that are over their soft 501 * limit by the same amount 502 */ 503 else if (mz->usage_in_excess >= mz_node->usage_in_excess) 504 p = &(*p)->rb_right; 505 } 506 rb_link_node(&mz->tree_node, parent, p); 507 rb_insert_color(&mz->tree_node, &mctz->rb_root); 508 mz->on_tree = true; 509 } 510 511 static void 512 __mem_cgroup_remove_exceeded(struct mem_cgroup *memcg, 513 struct mem_cgroup_per_zone *mz, 514 struct mem_cgroup_tree_per_zone *mctz) 515 { 516 if (!mz->on_tree) 517 return; 518 rb_erase(&mz->tree_node, &mctz->rb_root); 519 mz->on_tree = false; 520 } 521 522 static void 523 mem_cgroup_remove_exceeded(struct mem_cgroup *memcg, 524 struct mem_cgroup_per_zone *mz, 525 struct mem_cgroup_tree_per_zone *mctz) 526 { 527 spin_lock(&mctz->lock); 528 __mem_cgroup_remove_exceeded(memcg, mz, mctz); 529 spin_unlock(&mctz->lock); 530 } 531 532 533 static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page) 534 { 535 unsigned long long excess; 536 struct mem_cgroup_per_zone *mz; 537 struct mem_cgroup_tree_per_zone *mctz; 538 int nid = page_to_nid(page); 539 int zid = page_zonenum(page); 540 mctz = soft_limit_tree_from_page(page); 541 542 /* 543 * Necessary to update all ancestors when hierarchy is used. 544 * because their event counter is not touched. 545 */ 546 for (; memcg; memcg = parent_mem_cgroup(memcg)) { 547 mz = mem_cgroup_zoneinfo(memcg, nid, zid); 548 excess = res_counter_soft_limit_excess(&memcg->res); 549 /* 550 * We have to update the tree if mz is on RB-tree or 551 * mem is over its softlimit. 552 */ 553 if (excess || mz->on_tree) { 554 spin_lock(&mctz->lock); 555 /* if on-tree, remove it */ 556 if (mz->on_tree) 557 __mem_cgroup_remove_exceeded(memcg, mz, mctz); 558 /* 559 * Insert again. mz->usage_in_excess will be updated. 560 * If excess is 0, no tree ops. 561 */ 562 __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess); 563 spin_unlock(&mctz->lock); 564 } 565 } 566 } 567 568 static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg) 569 { 570 int node, zone; 571 struct mem_cgroup_per_zone *mz; 572 struct mem_cgroup_tree_per_zone *mctz; 573 574 for_each_node_state(node, N_POSSIBLE) { 575 for (zone = 0; zone < MAX_NR_ZONES; zone++) { 576 mz = mem_cgroup_zoneinfo(memcg, node, zone); 577 mctz = soft_limit_tree_node_zone(node, zone); 578 mem_cgroup_remove_exceeded(memcg, mz, mctz); 579 } 580 } 581 } 582 583 static struct mem_cgroup_per_zone * 584 __mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz) 585 { 586 struct rb_node *rightmost = NULL; 587 struct mem_cgroup_per_zone *mz; 588 589 retry: 590 mz = NULL; 591 rightmost = rb_last(&mctz->rb_root); 592 if (!rightmost) 593 goto done; /* Nothing to reclaim from */ 594 595 mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node); 596 /* 597 * Remove the node now but someone else can add it back, 598 * we will to add it back at the end of reclaim to its correct 599 * position in the tree. 600 */ 601 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz); 602 if (!res_counter_soft_limit_excess(&mz->mem->res) || 603 !css_tryget(&mz->mem->css)) 604 goto retry; 605 done: 606 return mz; 607 } 608 609 static struct mem_cgroup_per_zone * 610 mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz) 611 { 612 struct mem_cgroup_per_zone *mz; 613 614 spin_lock(&mctz->lock); 615 mz = __mem_cgroup_largest_soft_limit_node(mctz); 616 spin_unlock(&mctz->lock); 617 return mz; 618 } 619 620 /* 621 * Implementation Note: reading percpu statistics for memcg. 622 * 623 * Both of vmstat[] and percpu_counter has threshold and do periodic 624 * synchronization to implement "quick" read. There are trade-off between 625 * reading cost and precision of value. Then, we may have a chance to implement 626 * a periodic synchronizion of counter in memcg's counter. 627 * 628 * But this _read() function is used for user interface now. The user accounts 629 * memory usage by memory cgroup and he _always_ requires exact value because 630 * he accounts memory. Even if we provide quick-and-fuzzy read, we always 631 * have to visit all online cpus and make sum. So, for now, unnecessary 632 * synchronization is not implemented. (just implemented for cpu hotplug) 633 * 634 * If there are kernel internal actions which can make use of some not-exact 635 * value, and reading all cpu value can be performance bottleneck in some 636 * common workload, threashold and synchonization as vmstat[] should be 637 * implemented. 638 */ 639 static long mem_cgroup_read_stat(struct mem_cgroup *memcg, 640 enum mem_cgroup_stat_index idx) 641 { 642 long val = 0; 643 int cpu; 644 645 get_online_cpus(); 646 for_each_online_cpu(cpu) 647 val += per_cpu(memcg->stat->count[idx], cpu); 648 #ifdef CONFIG_HOTPLUG_CPU 649 spin_lock(&memcg->pcp_counter_lock); 650 val += memcg->nocpu_base.count[idx]; 651 spin_unlock(&memcg->pcp_counter_lock); 652 #endif 653 put_online_cpus(); 654 return val; 655 } 656 657 static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg, 658 bool charge) 659 { 660 int val = (charge) ? 1 : -1; 661 this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAPOUT], val); 662 } 663 664 void mem_cgroup_pgfault(struct mem_cgroup *memcg, int val) 665 { 666 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT], val); 667 } 668 669 void mem_cgroup_pgmajfault(struct mem_cgroup *memcg, int val) 670 { 671 this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT], val); 672 } 673 674 static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg, 675 enum mem_cgroup_events_index idx) 676 { 677 unsigned long val = 0; 678 int cpu; 679 680 for_each_online_cpu(cpu) 681 val += per_cpu(memcg->stat->events[idx], cpu); 682 #ifdef CONFIG_HOTPLUG_CPU 683 spin_lock(&memcg->pcp_counter_lock); 684 val += memcg->nocpu_base.events[idx]; 685 spin_unlock(&memcg->pcp_counter_lock); 686 #endif 687 return val; 688 } 689 690 static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg, 691 bool file, int nr_pages) 692 { 693 preempt_disable(); 694 695 if (file) 696 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE], 697 nr_pages); 698 else 699 __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS], 700 nr_pages); 701 702 /* pagein of a big page is an event. So, ignore page size */ 703 if (nr_pages > 0) 704 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]); 705 else { 706 __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]); 707 nr_pages = -nr_pages; /* for event */ 708 } 709 710 __this_cpu_add(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT], nr_pages); 711 712 preempt_enable(); 713 } 714 715 unsigned long 716 mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid, 717 unsigned int lru_mask) 718 { 719 struct mem_cgroup_per_zone *mz; 720 enum lru_list l; 721 unsigned long ret = 0; 722 723 mz = mem_cgroup_zoneinfo(memcg, nid, zid); 724 725 for_each_lru(l) { 726 if (BIT(l) & lru_mask) 727 ret += MEM_CGROUP_ZSTAT(mz, l); 728 } 729 return ret; 730 } 731 732 static unsigned long 733 mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg, 734 int nid, unsigned int lru_mask) 735 { 736 u64 total = 0; 737 int zid; 738 739 for (zid = 0; zid < MAX_NR_ZONES; zid++) 740 total += mem_cgroup_zone_nr_lru_pages(memcg, 741 nid, zid, lru_mask); 742 743 return total; 744 } 745 746 static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg, 747 unsigned int lru_mask) 748 { 749 int nid; 750 u64 total = 0; 751 752 for_each_node_state(nid, N_HIGH_MEMORY) 753 total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask); 754 return total; 755 } 756 757 static bool __memcg_event_check(struct mem_cgroup *memcg, int target) 758 { 759 unsigned long val, next; 760 761 val = __this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]); 762 next = __this_cpu_read(memcg->stat->targets[target]); 763 /* from time_after() in jiffies.h */ 764 return ((long)next - (long)val < 0); 765 } 766 767 static void __mem_cgroup_target_update(struct mem_cgroup *memcg, int target) 768 { 769 unsigned long val, next; 770 771 val = __this_cpu_read(memcg->stat->events[MEM_CGROUP_EVENTS_COUNT]); 772 773 switch (target) { 774 case MEM_CGROUP_TARGET_THRESH: 775 next = val + THRESHOLDS_EVENTS_TARGET; 776 break; 777 case MEM_CGROUP_TARGET_SOFTLIMIT: 778 next = val + SOFTLIMIT_EVENTS_TARGET; 779 break; 780 case MEM_CGROUP_TARGET_NUMAINFO: 781 next = val + NUMAINFO_EVENTS_TARGET; 782 break; 783 default: 784 return; 785 } 786 787 __this_cpu_write(memcg->stat->targets[target], next); 788 } 789 790 /* 791 * Check events in order. 792 * 793 */ 794 static void memcg_check_events(struct mem_cgroup *memcg, struct page *page) 795 { 796 preempt_disable(); 797 /* threshold event is triggered in finer grain than soft limit */ 798 if (unlikely(__memcg_event_check(memcg, MEM_CGROUP_TARGET_THRESH))) { 799 mem_cgroup_threshold(memcg); 800 __mem_cgroup_target_update(memcg, MEM_CGROUP_TARGET_THRESH); 801 if (unlikely(__memcg_event_check(memcg, 802 MEM_CGROUP_TARGET_SOFTLIMIT))) { 803 mem_cgroup_update_tree(memcg, page); 804 __mem_cgroup_target_update(memcg, 805 MEM_CGROUP_TARGET_SOFTLIMIT); 806 } 807 #if MAX_NUMNODES > 1 808 if (unlikely(__memcg_event_check(memcg, 809 MEM_CGROUP_TARGET_NUMAINFO))) { 810 atomic_inc(&memcg->numainfo_events); 811 __mem_cgroup_target_update(memcg, 812 MEM_CGROUP_TARGET_NUMAINFO); 813 } 814 #endif 815 } 816 preempt_enable(); 817 } 818 819 struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont) 820 { 821 return container_of(cgroup_subsys_state(cont, 822 mem_cgroup_subsys_id), struct mem_cgroup, 823 css); 824 } 825 826 struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p) 827 { 828 /* 829 * mm_update_next_owner() may clear mm->owner to NULL 830 * if it races with swapoff, page migration, etc. 831 * So this can be called with p == NULL. 832 */ 833 if (unlikely(!p)) 834 return NULL; 835 836 return container_of(task_subsys_state(p, mem_cgroup_subsys_id), 837 struct mem_cgroup, css); 838 } 839 840 struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm) 841 { 842 struct mem_cgroup *memcg = NULL; 843 844 if (!mm) 845 return NULL; 846 /* 847 * Because we have no locks, mm->owner's may be being moved to other 848 * cgroup. We use css_tryget() here even if this looks 849 * pessimistic (rather than adding locks here). 850 */ 851 rcu_read_lock(); 852 do { 853 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner)); 854 if (unlikely(!memcg)) 855 break; 856 } while (!css_tryget(&memcg->css)); 857 rcu_read_unlock(); 858 return memcg; 859 } 860 861 /* The caller has to guarantee "mem" exists before calling this */ 862 static struct mem_cgroup *mem_cgroup_start_loop(struct mem_cgroup *memcg) 863 { 864 struct cgroup_subsys_state *css; 865 int found; 866 867 if (!memcg) /* ROOT cgroup has the smallest ID */ 868 return root_mem_cgroup; /*css_put/get against root is ignored*/ 869 if (!memcg->use_hierarchy) { 870 if (css_tryget(&memcg->css)) 871 return memcg; 872 return NULL; 873 } 874 rcu_read_lock(); 875 /* 876 * searching a memory cgroup which has the smallest ID under given 877 * ROOT cgroup. (ID >= 1) 878 */ 879 css = css_get_next(&mem_cgroup_subsys, 1, &memcg->css, &found); 880 if (css && css_tryget(css)) 881 memcg = container_of(css, struct mem_cgroup, css); 882 else 883 memcg = NULL; 884 rcu_read_unlock(); 885 return memcg; 886 } 887 888 static struct mem_cgroup *mem_cgroup_get_next(struct mem_cgroup *iter, 889 struct mem_cgroup *root, 890 bool cond) 891 { 892 int nextid = css_id(&iter->css) + 1; 893 int found; 894 int hierarchy_used; 895 struct cgroup_subsys_state *css; 896 897 hierarchy_used = iter->use_hierarchy; 898 899 css_put(&iter->css); 900 /* If no ROOT, walk all, ignore hierarchy */ 901 if (!cond || (root && !hierarchy_used)) 902 return NULL; 903 904 if (!root) 905 root = root_mem_cgroup; 906 907 do { 908 iter = NULL; 909 rcu_read_lock(); 910 911 css = css_get_next(&mem_cgroup_subsys, nextid, 912 &root->css, &found); 913 if (css && css_tryget(css)) 914 iter = container_of(css, struct mem_cgroup, css); 915 rcu_read_unlock(); 916 /* If css is NULL, no more cgroups will be found */ 917 nextid = found + 1; 918 } while (css && !iter); 919 920 return iter; 921 } 922 /* 923 * for_eacn_mem_cgroup_tree() for visiting all cgroup under tree. Please 924 * be careful that "break" loop is not allowed. We have reference count. 925 * Instead of that modify "cond" to be false and "continue" to exit the loop. 926 */ 927 #define for_each_mem_cgroup_tree_cond(iter, root, cond) \ 928 for (iter = mem_cgroup_start_loop(root);\ 929 iter != NULL;\ 930 iter = mem_cgroup_get_next(iter, root, cond)) 931 932 #define for_each_mem_cgroup_tree(iter, root) \ 933 for_each_mem_cgroup_tree_cond(iter, root, true) 934 935 #define for_each_mem_cgroup_all(iter) \ 936 for_each_mem_cgroup_tree_cond(iter, NULL, true) 937 938 939 static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg) 940 { 941 return (memcg == root_mem_cgroup); 942 } 943 944 void mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx) 945 { 946 struct mem_cgroup *memcg; 947 948 if (!mm) 949 return; 950 951 rcu_read_lock(); 952 memcg = mem_cgroup_from_task(rcu_dereference(mm->owner)); 953 if (unlikely(!memcg)) 954 goto out; 955 956 switch (idx) { 957 case PGMAJFAULT: 958 mem_cgroup_pgmajfault(memcg, 1); 959 break; 960 case PGFAULT: 961 mem_cgroup_pgfault(memcg, 1); 962 break; 963 default: 964 BUG(); 965 } 966 out: 967 rcu_read_unlock(); 968 } 969 EXPORT_SYMBOL(mem_cgroup_count_vm_event); 970 971 /* 972 * Following LRU functions are allowed to be used without PCG_LOCK. 973 * Operations are called by routine of global LRU independently from memcg. 974 * What we have to take care of here is validness of pc->mem_cgroup. 975 * 976 * Changes to pc->mem_cgroup happens when 977 * 1. charge 978 * 2. moving account 979 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache. 980 * It is added to LRU before charge. 981 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU. 982 * When moving account, the page is not on LRU. It's isolated. 983 */ 984 985 void mem_cgroup_del_lru_list(struct page *page, enum lru_list lru) 986 { 987 struct page_cgroup *pc; 988 struct mem_cgroup_per_zone *mz; 989 990 if (mem_cgroup_disabled()) 991 return; 992 pc = lookup_page_cgroup(page); 993 /* can happen while we handle swapcache. */ 994 if (!TestClearPageCgroupAcctLRU(pc)) 995 return; 996 VM_BUG_ON(!pc->mem_cgroup); 997 /* 998 * We don't check PCG_USED bit. It's cleared when the "page" is finally 999 * removed from global LRU. 1000 */ 1001 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page); 1002 /* huge page split is done under lru_lock. so, we have no races. */ 1003 MEM_CGROUP_ZSTAT(mz, lru) -= 1 << compound_order(page); 1004 if (mem_cgroup_is_root(pc->mem_cgroup)) 1005 return; 1006 VM_BUG_ON(list_empty(&pc->lru)); 1007 list_del_init(&pc->lru); 1008 } 1009 1010 void mem_cgroup_del_lru(struct page *page) 1011 { 1012 mem_cgroup_del_lru_list(page, page_lru(page)); 1013 } 1014 1015 /* 1016 * Writeback is about to end against a page which has been marked for immediate 1017 * reclaim. If it still appears to be reclaimable, move it to the tail of the 1018 * inactive list. 1019 */ 1020 void mem_cgroup_rotate_reclaimable_page(struct page *page) 1021 { 1022 struct mem_cgroup_per_zone *mz; 1023 struct page_cgroup *pc; 1024 enum lru_list lru = page_lru(page); 1025 1026 if (mem_cgroup_disabled()) 1027 return; 1028 1029 pc = lookup_page_cgroup(page); 1030 /* unused or root page is not rotated. */ 1031 if (!PageCgroupUsed(pc)) 1032 return; 1033 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */ 1034 smp_rmb(); 1035 if (mem_cgroup_is_root(pc->mem_cgroup)) 1036 return; 1037 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page); 1038 list_move_tail(&pc->lru, &mz->lists[lru]); 1039 } 1040 1041 void mem_cgroup_rotate_lru_list(struct page *page, enum lru_list lru) 1042 { 1043 struct mem_cgroup_per_zone *mz; 1044 struct page_cgroup *pc; 1045 1046 if (mem_cgroup_disabled()) 1047 return; 1048 1049 pc = lookup_page_cgroup(page); 1050 /* unused or root page is not rotated. */ 1051 if (!PageCgroupUsed(pc)) 1052 return; 1053 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */ 1054 smp_rmb(); 1055 if (mem_cgroup_is_root(pc->mem_cgroup)) 1056 return; 1057 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page); 1058 list_move(&pc->lru, &mz->lists[lru]); 1059 } 1060 1061 void mem_cgroup_add_lru_list(struct page *page, enum lru_list lru) 1062 { 1063 struct page_cgroup *pc; 1064 struct mem_cgroup_per_zone *mz; 1065 1066 if (mem_cgroup_disabled()) 1067 return; 1068 pc = lookup_page_cgroup(page); 1069 VM_BUG_ON(PageCgroupAcctLRU(pc)); 1070 /* 1071 * putback: charge: 1072 * SetPageLRU SetPageCgroupUsed 1073 * smp_mb smp_mb 1074 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU 1075 * 1076 * Ensure that one of the two sides adds the page to the memcg 1077 * LRU during a race. 1078 */ 1079 smp_mb(); 1080 if (!PageCgroupUsed(pc)) 1081 return; 1082 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */ 1083 smp_rmb(); 1084 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page); 1085 /* huge page split is done under lru_lock. so, we have no races. */ 1086 MEM_CGROUP_ZSTAT(mz, lru) += 1 << compound_order(page); 1087 SetPageCgroupAcctLRU(pc); 1088 if (mem_cgroup_is_root(pc->mem_cgroup)) 1089 return; 1090 list_add(&pc->lru, &mz->lists[lru]); 1091 } 1092 1093 /* 1094 * At handling SwapCache and other FUSE stuff, pc->mem_cgroup may be changed 1095 * while it's linked to lru because the page may be reused after it's fully 1096 * uncharged. To handle that, unlink page_cgroup from LRU when charge it again. 1097 * It's done under lock_page and expected that zone->lru_lock isnever held. 1098 */ 1099 static void mem_cgroup_lru_del_before_commit(struct page *page) 1100 { 1101 unsigned long flags; 1102 struct zone *zone = page_zone(page); 1103 struct page_cgroup *pc = lookup_page_cgroup(page); 1104 1105 /* 1106 * Doing this check without taking ->lru_lock seems wrong but this 1107 * is safe. Because if page_cgroup's USED bit is unset, the page 1108 * will not be added to any memcg's LRU. If page_cgroup's USED bit is 1109 * set, the commit after this will fail, anyway. 1110 * This all charge/uncharge is done under some mutual execustion. 1111 * So, we don't need to taking care of changes in USED bit. 1112 */ 1113 if (likely(!PageLRU(page))) 1114 return; 1115 1116 spin_lock_irqsave(&zone->lru_lock, flags); 1117 /* 1118 * Forget old LRU when this page_cgroup is *not* used. This Used bit 1119 * is guarded by lock_page() because the page is SwapCache. 1120 */ 1121 if (!PageCgroupUsed(pc)) 1122 mem_cgroup_del_lru_list(page, page_lru(page)); 1123 spin_unlock_irqrestore(&zone->lru_lock, flags); 1124 } 1125 1126 static void mem_cgroup_lru_add_after_commit(struct page *page) 1127 { 1128 unsigned long flags; 1129 struct zone *zone = page_zone(page); 1130 struct page_cgroup *pc = lookup_page_cgroup(page); 1131 /* 1132 * putback: charge: 1133 * SetPageLRU SetPageCgroupUsed 1134 * smp_mb smp_mb 1135 * PageCgroupUsed && add to memcg LRU PageLRU && add to memcg LRU 1136 * 1137 * Ensure that one of the two sides adds the page to the memcg 1138 * LRU during a race. 1139 */ 1140 smp_mb(); 1141 /* taking care of that the page is added to LRU while we commit it */ 1142 if (likely(!PageLRU(page))) 1143 return; 1144 spin_lock_irqsave(&zone->lru_lock, flags); 1145 /* link when the page is linked to LRU but page_cgroup isn't */ 1146 if (PageLRU(page) && !PageCgroupAcctLRU(pc)) 1147 mem_cgroup_add_lru_list(page, page_lru(page)); 1148 spin_unlock_irqrestore(&zone->lru_lock, flags); 1149 } 1150 1151 1152 void mem_cgroup_move_lists(struct page *page, 1153 enum lru_list from, enum lru_list to) 1154 { 1155 if (mem_cgroup_disabled()) 1156 return; 1157 mem_cgroup_del_lru_list(page, from); 1158 mem_cgroup_add_lru_list(page, to); 1159 } 1160 1161 /* 1162 * Checks whether given mem is same or in the root_mem_cgroup's 1163 * hierarchy subtree 1164 */ 1165 static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg, 1166 struct mem_cgroup *memcg) 1167 { 1168 if (root_memcg != memcg) { 1169 return (root_memcg->use_hierarchy && 1170 css_is_ancestor(&memcg->css, &root_memcg->css)); 1171 } 1172 1173 return true; 1174 } 1175 1176 int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg) 1177 { 1178 int ret; 1179 struct mem_cgroup *curr = NULL; 1180 struct task_struct *p; 1181 1182 p = find_lock_task_mm(task); 1183 if (!p) 1184 return 0; 1185 curr = try_get_mem_cgroup_from_mm(p->mm); 1186 task_unlock(p); 1187 if (!curr) 1188 return 0; 1189 /* 1190 * We should check use_hierarchy of "memcg" not "curr". Because checking 1191 * use_hierarchy of "curr" here make this function true if hierarchy is 1192 * enabled in "curr" and "curr" is a child of "memcg" in *cgroup* 1193 * hierarchy(even if use_hierarchy is disabled in "memcg"). 1194 */ 1195 ret = mem_cgroup_same_or_subtree(memcg, curr); 1196 css_put(&curr->css); 1197 return ret; 1198 } 1199 1200 int mem_cgroup_inactive_anon_is_low(struct mem_cgroup *memcg, struct zone *zone) 1201 { 1202 unsigned long inactive_ratio; 1203 int nid = zone_to_nid(zone); 1204 int zid = zone_idx(zone); 1205 unsigned long inactive; 1206 unsigned long active; 1207 unsigned long gb; 1208 1209 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid, 1210 BIT(LRU_INACTIVE_ANON)); 1211 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid, 1212 BIT(LRU_ACTIVE_ANON)); 1213 1214 gb = (inactive + active) >> (30 - PAGE_SHIFT); 1215 if (gb) 1216 inactive_ratio = int_sqrt(10 * gb); 1217 else 1218 inactive_ratio = 1; 1219 1220 return inactive * inactive_ratio < active; 1221 } 1222 1223 int mem_cgroup_inactive_file_is_low(struct mem_cgroup *memcg, struct zone *zone) 1224 { 1225 unsigned long active; 1226 unsigned long inactive; 1227 int zid = zone_idx(zone); 1228 int nid = zone_to_nid(zone); 1229 1230 inactive = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid, 1231 BIT(LRU_INACTIVE_FILE)); 1232 active = mem_cgroup_zone_nr_lru_pages(memcg, nid, zid, 1233 BIT(LRU_ACTIVE_FILE)); 1234 1235 return (active > inactive); 1236 } 1237 1238 struct zone_reclaim_stat *mem_cgroup_get_reclaim_stat(struct mem_cgroup *memcg, 1239 struct zone *zone) 1240 { 1241 int nid = zone_to_nid(zone); 1242 int zid = zone_idx(zone); 1243 struct mem_cgroup_per_zone *mz = mem_cgroup_zoneinfo(memcg, nid, zid); 1244 1245 return &mz->reclaim_stat; 1246 } 1247 1248 struct zone_reclaim_stat * 1249 mem_cgroup_get_reclaim_stat_from_page(struct page *page) 1250 { 1251 struct page_cgroup *pc; 1252 struct mem_cgroup_per_zone *mz; 1253 1254 if (mem_cgroup_disabled()) 1255 return NULL; 1256 1257 pc = lookup_page_cgroup(page); 1258 if (!PageCgroupUsed(pc)) 1259 return NULL; 1260 /* Ensure pc->mem_cgroup is visible after reading PCG_USED. */ 1261 smp_rmb(); 1262 mz = page_cgroup_zoneinfo(pc->mem_cgroup, page); 1263 return &mz->reclaim_stat; 1264 } 1265 1266 unsigned long mem_cgroup_isolate_pages(unsigned long nr_to_scan, 1267 struct list_head *dst, 1268 unsigned long *scanned, int order, 1269 isolate_mode_t mode, 1270 struct zone *z, 1271 struct mem_cgroup *mem_cont, 1272 int active, int file) 1273 { 1274 unsigned long nr_taken = 0; 1275 struct page *page; 1276 unsigned long scan; 1277 LIST_HEAD(pc_list); 1278 struct list_head *src; 1279 struct page_cgroup *pc, *tmp; 1280 int nid = zone_to_nid(z); 1281 int zid = zone_idx(z); 1282 struct mem_cgroup_per_zone *mz; 1283 int lru = LRU_FILE * file + active; 1284 int ret; 1285 1286 BUG_ON(!mem_cont); 1287 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid); 1288 src = &mz->lists[lru]; 1289 1290 scan = 0; 1291 list_for_each_entry_safe_reverse(pc, tmp, src, lru) { 1292 if (scan >= nr_to_scan) 1293 break; 1294 1295 if (unlikely(!PageCgroupUsed(pc))) 1296 continue; 1297 1298 page = lookup_cgroup_page(pc); 1299 1300 if (unlikely(!PageLRU(page))) 1301 continue; 1302 1303 scan++; 1304 ret = __isolate_lru_page(page, mode, file); 1305 switch (ret) { 1306 case 0: 1307 list_move(&page->lru, dst); 1308 mem_cgroup_del_lru(page); 1309 nr_taken += hpage_nr_pages(page); 1310 break; 1311 case -EBUSY: 1312 /* we don't affect global LRU but rotate in our LRU */ 1313 mem_cgroup_rotate_lru_list(page, page_lru(page)); 1314 break; 1315 default: 1316 break; 1317 } 1318 } 1319 1320 *scanned = scan; 1321 1322 trace_mm_vmscan_memcg_isolate(0, nr_to_scan, scan, nr_taken, 1323 0, 0, 0, mode); 1324 1325 return nr_taken; 1326 } 1327 1328 #define mem_cgroup_from_res_counter(counter, member) \ 1329 container_of(counter, struct mem_cgroup, member) 1330 1331 /** 1332 * mem_cgroup_margin - calculate chargeable space of a memory cgroup 1333 * @mem: the memory cgroup 1334 * 1335 * Returns the maximum amount of memory @mem can be charged with, in 1336 * pages. 1337 */ 1338 static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg) 1339 { 1340 unsigned long long margin; 1341 1342 margin = res_counter_margin(&memcg->res); 1343 if (do_swap_account) 1344 margin = min(margin, res_counter_margin(&memcg->memsw)); 1345 return margin >> PAGE_SHIFT; 1346 } 1347 1348 int mem_cgroup_swappiness(struct mem_cgroup *memcg) 1349 { 1350 struct cgroup *cgrp = memcg->css.cgroup; 1351 1352 /* root ? */ 1353 if (cgrp->parent == NULL) 1354 return vm_swappiness; 1355 1356 return memcg->swappiness; 1357 } 1358 1359 static void mem_cgroup_start_move(struct mem_cgroup *memcg) 1360 { 1361 int cpu; 1362 1363 get_online_cpus(); 1364 spin_lock(&memcg->pcp_counter_lock); 1365 for_each_online_cpu(cpu) 1366 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) += 1; 1367 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] += 1; 1368 spin_unlock(&memcg->pcp_counter_lock); 1369 put_online_cpus(); 1370 1371 synchronize_rcu(); 1372 } 1373 1374 static void mem_cgroup_end_move(struct mem_cgroup *memcg) 1375 { 1376 int cpu; 1377 1378 if (!memcg) 1379 return; 1380 get_online_cpus(); 1381 spin_lock(&memcg->pcp_counter_lock); 1382 for_each_online_cpu(cpu) 1383 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) -= 1; 1384 memcg->nocpu_base.count[MEM_CGROUP_ON_MOVE] -= 1; 1385 spin_unlock(&memcg->pcp_counter_lock); 1386 put_online_cpus(); 1387 } 1388 /* 1389 * 2 routines for checking "mem" is under move_account() or not. 1390 * 1391 * mem_cgroup_stealed() - checking a cgroup is mc.from or not. This is used 1392 * for avoiding race in accounting. If true, 1393 * pc->mem_cgroup may be overwritten. 1394 * 1395 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or 1396 * under hierarchy of moving cgroups. This is for 1397 * waiting at hith-memory prressure caused by "move". 1398 */ 1399 1400 static bool mem_cgroup_stealed(struct mem_cgroup *memcg) 1401 { 1402 VM_BUG_ON(!rcu_read_lock_held()); 1403 return this_cpu_read(memcg->stat->count[MEM_CGROUP_ON_MOVE]) > 0; 1404 } 1405 1406 static bool mem_cgroup_under_move(struct mem_cgroup *memcg) 1407 { 1408 struct mem_cgroup *from; 1409 struct mem_cgroup *to; 1410 bool ret = false; 1411 /* 1412 * Unlike task_move routines, we access mc.to, mc.from not under 1413 * mutual exclusion by cgroup_mutex. Here, we take spinlock instead. 1414 */ 1415 spin_lock(&mc.lock); 1416 from = mc.from; 1417 to = mc.to; 1418 if (!from) 1419 goto unlock; 1420 1421 ret = mem_cgroup_same_or_subtree(memcg, from) 1422 || mem_cgroup_same_or_subtree(memcg, to); 1423 unlock: 1424 spin_unlock(&mc.lock); 1425 return ret; 1426 } 1427 1428 static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg) 1429 { 1430 if (mc.moving_task && current != mc.moving_task) { 1431 if (mem_cgroup_under_move(memcg)) { 1432 DEFINE_WAIT(wait); 1433 prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE); 1434 /* moving charge context might have finished. */ 1435 if (mc.moving_task) 1436 schedule(); 1437 finish_wait(&mc.waitq, &wait); 1438 return true; 1439 } 1440 } 1441 return false; 1442 } 1443 1444 /** 1445 * mem_cgroup_print_oom_info: Called from OOM with tasklist_lock held in read mode. 1446 * @memcg: The memory cgroup that went over limit 1447 * @p: Task that is going to be killed 1448 * 1449 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is 1450 * enabled 1451 */ 1452 void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p) 1453 { 1454 struct cgroup *task_cgrp; 1455 struct cgroup *mem_cgrp; 1456 /* 1457 * Need a buffer in BSS, can't rely on allocations. The code relies 1458 * on the assumption that OOM is serialized for memory controller. 1459 * If this assumption is broken, revisit this code. 1460 */ 1461 static char memcg_name[PATH_MAX]; 1462 int ret; 1463 1464 if (!memcg || !p) 1465 return; 1466 1467 1468 rcu_read_lock(); 1469 1470 mem_cgrp = memcg->css.cgroup; 1471 task_cgrp = task_cgroup(p, mem_cgroup_subsys_id); 1472 1473 ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX); 1474 if (ret < 0) { 1475 /* 1476 * Unfortunately, we are unable to convert to a useful name 1477 * But we'll still print out the usage information 1478 */ 1479 rcu_read_unlock(); 1480 goto done; 1481 } 1482 rcu_read_unlock(); 1483 1484 printk(KERN_INFO "Task in %s killed", memcg_name); 1485 1486 rcu_read_lock(); 1487 ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX); 1488 if (ret < 0) { 1489 rcu_read_unlock(); 1490 goto done; 1491 } 1492 rcu_read_unlock(); 1493 1494 /* 1495 * Continues from above, so we don't need an KERN_ level 1496 */ 1497 printk(KERN_CONT " as a result of limit of %s\n", memcg_name); 1498 done: 1499 1500 printk(KERN_INFO "memory: usage %llukB, limit %llukB, failcnt %llu\n", 1501 res_counter_read_u64(&memcg->res, RES_USAGE) >> 10, 1502 res_counter_read_u64(&memcg->res, RES_LIMIT) >> 10, 1503 res_counter_read_u64(&memcg->res, RES_FAILCNT)); 1504 printk(KERN_INFO "memory+swap: usage %llukB, limit %llukB, " 1505 "failcnt %llu\n", 1506 res_counter_read_u64(&memcg->memsw, RES_USAGE) >> 10, 1507 res_counter_read_u64(&memcg->memsw, RES_LIMIT) >> 10, 1508 res_counter_read_u64(&memcg->memsw, RES_FAILCNT)); 1509 } 1510 1511 /* 1512 * This function returns the number of memcg under hierarchy tree. Returns 1513 * 1(self count) if no children. 1514 */ 1515 static int mem_cgroup_count_children(struct mem_cgroup *memcg) 1516 { 1517 int num = 0; 1518 struct mem_cgroup *iter; 1519 1520 for_each_mem_cgroup_tree(iter, memcg) 1521 num++; 1522 return num; 1523 } 1524 1525 /* 1526 * Return the memory (and swap, if configured) limit for a memcg. 1527 */ 1528 u64 mem_cgroup_get_limit(struct mem_cgroup *memcg) 1529 { 1530 u64 limit; 1531 u64 memsw; 1532 1533 limit = res_counter_read_u64(&memcg->res, RES_LIMIT); 1534 limit += total_swap_pages << PAGE_SHIFT; 1535 1536 memsw = res_counter_read_u64(&memcg->memsw, RES_LIMIT); 1537 /* 1538 * If memsw is finite and limits the amount of swap space available 1539 * to this memcg, return that limit. 1540 */ 1541 return min(limit, memsw); 1542 } 1543 1544 /* 1545 * Visit the first child (need not be the first child as per the ordering 1546 * of the cgroup list, since we track last_scanned_child) of @mem and use 1547 * that to reclaim free pages from. 1548 */ 1549 static struct mem_cgroup * 1550 mem_cgroup_select_victim(struct mem_cgroup *root_memcg) 1551 { 1552 struct mem_cgroup *ret = NULL; 1553 struct cgroup_subsys_state *css; 1554 int nextid, found; 1555 1556 if (!root_memcg->use_hierarchy) { 1557 css_get(&root_memcg->css); 1558 ret = root_memcg; 1559 } 1560 1561 while (!ret) { 1562 rcu_read_lock(); 1563 nextid = root_memcg->last_scanned_child + 1; 1564 css = css_get_next(&mem_cgroup_subsys, nextid, &root_memcg->css, 1565 &found); 1566 if (css && css_tryget(css)) 1567 ret = container_of(css, struct mem_cgroup, css); 1568 1569 rcu_read_unlock(); 1570 /* Updates scanning parameter */ 1571 if (!css) { 1572 /* this means start scan from ID:1 */ 1573 root_memcg->last_scanned_child = 0; 1574 } else 1575 root_memcg->last_scanned_child = found; 1576 } 1577 1578 return ret; 1579 } 1580 1581 /** 1582 * test_mem_cgroup_node_reclaimable 1583 * @mem: the target memcg 1584 * @nid: the node ID to be checked. 1585 * @noswap : specify true here if the user wants flle only information. 1586 * 1587 * This function returns whether the specified memcg contains any 1588 * reclaimable pages on a node. Returns true if there are any reclaimable 1589 * pages in the node. 1590 */ 1591 static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg, 1592 int nid, bool noswap) 1593 { 1594 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE)) 1595 return true; 1596 if (noswap || !total_swap_pages) 1597 return false; 1598 if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON)) 1599 return true; 1600 return false; 1601 1602 } 1603 #if MAX_NUMNODES > 1 1604 1605 /* 1606 * Always updating the nodemask is not very good - even if we have an empty 1607 * list or the wrong list here, we can start from some node and traverse all 1608 * nodes based on the zonelist. So update the list loosely once per 10 secs. 1609 * 1610 */ 1611 static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg) 1612 { 1613 int nid; 1614 /* 1615 * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET 1616 * pagein/pageout changes since the last update. 1617 */ 1618 if (!atomic_read(&memcg->numainfo_events)) 1619 return; 1620 if (atomic_inc_return(&memcg->numainfo_updating) > 1) 1621 return; 1622 1623 /* make a nodemask where this memcg uses memory from */ 1624 memcg->scan_nodes = node_states[N_HIGH_MEMORY]; 1625 1626 for_each_node_mask(nid, node_states[N_HIGH_MEMORY]) { 1627 1628 if (!test_mem_cgroup_node_reclaimable(memcg, nid, false)) 1629 node_clear(nid, memcg->scan_nodes); 1630 } 1631 1632 atomic_set(&memcg->numainfo_events, 0); 1633 atomic_set(&memcg->numainfo_updating, 0); 1634 } 1635 1636 /* 1637 * Selecting a node where we start reclaim from. Because what we need is just 1638 * reducing usage counter, start from anywhere is O,K. Considering 1639 * memory reclaim from current node, there are pros. and cons. 1640 * 1641 * Freeing memory from current node means freeing memory from a node which 1642 * we'll use or we've used. So, it may make LRU bad. And if several threads 1643 * hit limits, it will see a contention on a node. But freeing from remote 1644 * node means more costs for memory reclaim because of memory latency. 1645 * 1646 * Now, we use round-robin. Better algorithm is welcomed. 1647 */ 1648 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg) 1649 { 1650 int node; 1651 1652 mem_cgroup_may_update_nodemask(memcg); 1653 node = memcg->last_scanned_node; 1654 1655 node = next_node(node, memcg->scan_nodes); 1656 if (node == MAX_NUMNODES) 1657 node = first_node(memcg->scan_nodes); 1658 /* 1659 * We call this when we hit limit, not when pages are added to LRU. 1660 * No LRU may hold pages because all pages are UNEVICTABLE or 1661 * memcg is too small and all pages are not on LRU. In that case, 1662 * we use curret node. 1663 */ 1664 if (unlikely(node == MAX_NUMNODES)) 1665 node = numa_node_id(); 1666 1667 memcg->last_scanned_node = node; 1668 return node; 1669 } 1670 1671 /* 1672 * Check all nodes whether it contains reclaimable pages or not. 1673 * For quick scan, we make use of scan_nodes. This will allow us to skip 1674 * unused nodes. But scan_nodes is lazily updated and may not cotain 1675 * enough new information. We need to do double check. 1676 */ 1677 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap) 1678 { 1679 int nid; 1680 1681 /* 1682 * quick check...making use of scan_node. 1683 * We can skip unused nodes. 1684 */ 1685 if (!nodes_empty(memcg->scan_nodes)) { 1686 for (nid = first_node(memcg->scan_nodes); 1687 nid < MAX_NUMNODES; 1688 nid = next_node(nid, memcg->scan_nodes)) { 1689 1690 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap)) 1691 return true; 1692 } 1693 } 1694 /* 1695 * Check rest of nodes. 1696 */ 1697 for_each_node_state(nid, N_HIGH_MEMORY) { 1698 if (node_isset(nid, memcg->scan_nodes)) 1699 continue; 1700 if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap)) 1701 return true; 1702 } 1703 return false; 1704 } 1705 1706 #else 1707 int mem_cgroup_select_victim_node(struct mem_cgroup *memcg) 1708 { 1709 return 0; 1710 } 1711 1712 bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap) 1713 { 1714 return test_mem_cgroup_node_reclaimable(memcg, 0, noswap); 1715 } 1716 #endif 1717 1718 /* 1719 * Scan the hierarchy if needed to reclaim memory. We remember the last child 1720 * we reclaimed from, so that we don't end up penalizing one child extensively 1721 * based on its position in the children list. 1722 * 1723 * root_memcg is the original ancestor that we've been reclaim from. 1724 * 1725 * We give up and return to the caller when we visit root_memcg twice. 1726 * (other groups can be removed while we're walking....) 1727 * 1728 * If shrink==true, for avoiding to free too much, this returns immedieately. 1729 */ 1730 static int mem_cgroup_hierarchical_reclaim(struct mem_cgroup *root_memcg, 1731 struct zone *zone, 1732 gfp_t gfp_mask, 1733 unsigned long reclaim_options, 1734 unsigned long *total_scanned) 1735 { 1736 struct mem_cgroup *victim; 1737 int ret, total = 0; 1738 int loop = 0; 1739 bool noswap = reclaim_options & MEM_CGROUP_RECLAIM_NOSWAP; 1740 bool shrink = reclaim_options & MEM_CGROUP_RECLAIM_SHRINK; 1741 bool check_soft = reclaim_options & MEM_CGROUP_RECLAIM_SOFT; 1742 unsigned long excess; 1743 unsigned long nr_scanned; 1744 1745 excess = res_counter_soft_limit_excess(&root_memcg->res) >> PAGE_SHIFT; 1746 1747 /* If memsw_is_minimum==1, swap-out is of-no-use. */ 1748 if (!check_soft && !shrink && root_memcg->memsw_is_minimum) 1749 noswap = true; 1750 1751 while (1) { 1752 victim = mem_cgroup_select_victim(root_memcg); 1753 if (victim == root_memcg) { 1754 loop++; 1755 /* 1756 * We are not draining per cpu cached charges during 1757 * soft limit reclaim because global reclaim doesn't 1758 * care about charges. It tries to free some memory and 1759 * charges will not give any. 1760 */ 1761 if (!check_soft && loop >= 1) 1762 drain_all_stock_async(root_memcg); 1763 if (loop >= 2) { 1764 /* 1765 * If we have not been able to reclaim 1766 * anything, it might because there are 1767 * no reclaimable pages under this hierarchy 1768 */ 1769 if (!check_soft || !total) { 1770 css_put(&victim->css); 1771 break; 1772 } 1773 /* 1774 * We want to do more targeted reclaim. 1775 * excess >> 2 is not to excessive so as to 1776 * reclaim too much, nor too less that we keep 1777 * coming back to reclaim from this cgroup 1778 */ 1779 if (total >= (excess >> 2) || 1780 (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS)) { 1781 css_put(&victim->css); 1782 break; 1783 } 1784 } 1785 } 1786 if (!mem_cgroup_reclaimable(victim, noswap)) { 1787 /* this cgroup's local usage == 0 */ 1788 css_put(&victim->css); 1789 continue; 1790 } 1791 /* we use swappiness of local cgroup */ 1792 if (check_soft) { 1793 ret = mem_cgroup_shrink_node_zone(victim, gfp_mask, 1794 noswap, zone, &nr_scanned); 1795 *total_scanned += nr_scanned; 1796 } else 1797 ret = try_to_free_mem_cgroup_pages(victim, gfp_mask, 1798 noswap); 1799 css_put(&victim->css); 1800 /* 1801 * At shrinking usage, we can't check we should stop here or 1802 * reclaim more. It's depends on callers. last_scanned_child 1803 * will work enough for keeping fairness under tree. 1804 */ 1805 if (shrink) 1806 return ret; 1807 total += ret; 1808 if (check_soft) { 1809 if (!res_counter_soft_limit_excess(&root_memcg->res)) 1810 return total; 1811 } else if (mem_cgroup_margin(root_memcg)) 1812 return total; 1813 } 1814 return total; 1815 } 1816 1817 /* 1818 * Check OOM-Killer is already running under our hierarchy. 1819 * If someone is running, return false. 1820 * Has to be called with memcg_oom_lock 1821 */ 1822 static bool mem_cgroup_oom_lock(struct mem_cgroup *memcg) 1823 { 1824 struct mem_cgroup *iter, *failed = NULL; 1825 bool cond = true; 1826 1827 for_each_mem_cgroup_tree_cond(iter, memcg, cond) { 1828 if (iter->oom_lock) { 1829 /* 1830 * this subtree of our hierarchy is already locked 1831 * so we cannot give a lock. 1832 */ 1833 failed = iter; 1834 cond = false; 1835 } else 1836 iter->oom_lock = true; 1837 } 1838 1839 if (!failed) 1840 return true; 1841 1842 /* 1843 * OK, we failed to lock the whole subtree so we have to clean up 1844 * what we set up to the failing subtree 1845 */ 1846 cond = true; 1847 for_each_mem_cgroup_tree_cond(iter, memcg, cond) { 1848 if (iter == failed) { 1849 cond = false; 1850 continue; 1851 } 1852 iter->oom_lock = false; 1853 } 1854 return false; 1855 } 1856 1857 /* 1858 * Has to be called with memcg_oom_lock 1859 */ 1860 static int mem_cgroup_oom_unlock(struct mem_cgroup *memcg) 1861 { 1862 struct mem_cgroup *iter; 1863 1864 for_each_mem_cgroup_tree(iter, memcg) 1865 iter->oom_lock = false; 1866 return 0; 1867 } 1868 1869 static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg) 1870 { 1871 struct mem_cgroup *iter; 1872 1873 for_each_mem_cgroup_tree(iter, memcg) 1874 atomic_inc(&iter->under_oom); 1875 } 1876 1877 static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg) 1878 { 1879 struct mem_cgroup *iter; 1880 1881 /* 1882 * When a new child is created while the hierarchy is under oom, 1883 * mem_cgroup_oom_lock() may not be called. We have to use 1884 * atomic_add_unless() here. 1885 */ 1886 for_each_mem_cgroup_tree(iter, memcg) 1887 atomic_add_unless(&iter->under_oom, -1, 0); 1888 } 1889 1890 static DEFINE_SPINLOCK(memcg_oom_lock); 1891 static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq); 1892 1893 struct oom_wait_info { 1894 struct mem_cgroup *mem; 1895 wait_queue_t wait; 1896 }; 1897 1898 static int memcg_oom_wake_function(wait_queue_t *wait, 1899 unsigned mode, int sync, void *arg) 1900 { 1901 struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg, 1902 *oom_wait_memcg; 1903 struct oom_wait_info *oom_wait_info; 1904 1905 oom_wait_info = container_of(wait, struct oom_wait_info, wait); 1906 oom_wait_memcg = oom_wait_info->mem; 1907 1908 /* 1909 * Both of oom_wait_info->mem and wake_mem are stable under us. 1910 * Then we can use css_is_ancestor without taking care of RCU. 1911 */ 1912 if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg) 1913 && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg)) 1914 return 0; 1915 return autoremove_wake_function(wait, mode, sync, arg); 1916 } 1917 1918 static void memcg_wakeup_oom(struct mem_cgroup *memcg) 1919 { 1920 /* for filtering, pass "memcg" as argument. */ 1921 __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg); 1922 } 1923 1924 static void memcg_oom_recover(struct mem_cgroup *memcg) 1925 { 1926 if (memcg && atomic_read(&memcg->under_oom)) 1927 memcg_wakeup_oom(memcg); 1928 } 1929 1930 /* 1931 * try to call OOM killer. returns false if we should exit memory-reclaim loop. 1932 */ 1933 bool mem_cgroup_handle_oom(struct mem_cgroup *memcg, gfp_t mask) 1934 { 1935 struct oom_wait_info owait; 1936 bool locked, need_to_kill; 1937 1938 owait.mem = memcg; 1939 owait.wait.flags = 0; 1940 owait.wait.func = memcg_oom_wake_function; 1941 owait.wait.private = current; 1942 INIT_LIST_HEAD(&owait.wait.task_list); 1943 need_to_kill = true; 1944 mem_cgroup_mark_under_oom(memcg); 1945 1946 /* At first, try to OOM lock hierarchy under memcg.*/ 1947 spin_lock(&memcg_oom_lock); 1948 locked = mem_cgroup_oom_lock(memcg); 1949 /* 1950 * Even if signal_pending(), we can't quit charge() loop without 1951 * accounting. So, UNINTERRUPTIBLE is appropriate. But SIGKILL 1952 * under OOM is always welcomed, use TASK_KILLABLE here. 1953 */ 1954 prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE); 1955 if (!locked || memcg->oom_kill_disable) 1956 need_to_kill = false; 1957 if (locked) 1958 mem_cgroup_oom_notify(memcg); 1959 spin_unlock(&memcg_oom_lock); 1960 1961 if (need_to_kill) { 1962 finish_wait(&memcg_oom_waitq, &owait.wait); 1963 mem_cgroup_out_of_memory(memcg, mask); 1964 } else { 1965 schedule(); 1966 finish_wait(&memcg_oom_waitq, &owait.wait); 1967 } 1968 spin_lock(&memcg_oom_lock); 1969 if (locked) 1970 mem_cgroup_oom_unlock(memcg); 1971 memcg_wakeup_oom(memcg); 1972 spin_unlock(&memcg_oom_lock); 1973 1974 mem_cgroup_unmark_under_oom(memcg); 1975 1976 if (test_thread_flag(TIF_MEMDIE) || fatal_signal_pending(current)) 1977 return false; 1978 /* Give chance to dying process */ 1979 schedule_timeout_uninterruptible(1); 1980 return true; 1981 } 1982 1983 /* 1984 * Currently used to update mapped file statistics, but the routine can be 1985 * generalized to update other statistics as well. 1986 * 1987 * Notes: Race condition 1988 * 1989 * We usually use page_cgroup_lock() for accessing page_cgroup member but 1990 * it tends to be costly. But considering some conditions, we doesn't need 1991 * to do so _always_. 1992 * 1993 * Considering "charge", lock_page_cgroup() is not required because all 1994 * file-stat operations happen after a page is attached to radix-tree. There 1995 * are no race with "charge". 1996 * 1997 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup 1998 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even 1999 * if there are race with "uncharge". Statistics itself is properly handled 2000 * by flags. 2001 * 2002 * Considering "move", this is an only case we see a race. To make the race 2003 * small, we check MEM_CGROUP_ON_MOVE percpu value and detect there are 2004 * possibility of race condition. If there is, we take a lock. 2005 */ 2006 2007 void mem_cgroup_update_page_stat(struct page *page, 2008 enum mem_cgroup_page_stat_item idx, int val) 2009 { 2010 struct mem_cgroup *memcg; 2011 struct page_cgroup *pc = lookup_page_cgroup(page); 2012 bool need_unlock = false; 2013 unsigned long uninitialized_var(flags); 2014 2015 if (unlikely(!pc)) 2016 return; 2017 2018 rcu_read_lock(); 2019 memcg = pc->mem_cgroup; 2020 if (unlikely(!memcg || !PageCgroupUsed(pc))) 2021 goto out; 2022 /* pc->mem_cgroup is unstable ? */ 2023 if (unlikely(mem_cgroup_stealed(memcg)) || PageTransHuge(page)) { 2024 /* take a lock against to access pc->mem_cgroup */ 2025 move_lock_page_cgroup(pc, &flags); 2026 need_unlock = true; 2027 memcg = pc->mem_cgroup; 2028 if (!memcg || !PageCgroupUsed(pc)) 2029 goto out; 2030 } 2031 2032 switch (idx) { 2033 case MEMCG_NR_FILE_MAPPED: 2034 if (val > 0) 2035 SetPageCgroupFileMapped(pc); 2036 else if (!page_mapped(page)) 2037 ClearPageCgroupFileMapped(pc); 2038 idx = MEM_CGROUP_STAT_FILE_MAPPED; 2039 break; 2040 default: 2041 BUG(); 2042 } 2043 2044 this_cpu_add(memcg->stat->count[idx], val); 2045 2046 out: 2047 if (unlikely(need_unlock)) 2048 move_unlock_page_cgroup(pc, &flags); 2049 rcu_read_unlock(); 2050 return; 2051 } 2052 EXPORT_SYMBOL(mem_cgroup_update_page_stat); 2053 2054 /* 2055 * size of first charge trial. "32" comes from vmscan.c's magic value. 2056 * TODO: maybe necessary to use big numbers in big irons. 2057 */ 2058 #define CHARGE_BATCH 32U 2059 struct memcg_stock_pcp { 2060 struct mem_cgroup *cached; /* this never be root cgroup */ 2061 unsigned int nr_pages; 2062 struct work_struct work; 2063 unsigned long flags; 2064 #define FLUSHING_CACHED_CHARGE (0) 2065 }; 2066 static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock); 2067 static DEFINE_MUTEX(percpu_charge_mutex); 2068 2069 /* 2070 * Try to consume stocked charge on this cpu. If success, one page is consumed 2071 * from local stock and true is returned. If the stock is 0 or charges from a 2072 * cgroup which is not current target, returns false. This stock will be 2073 * refilled. 2074 */ 2075 static bool consume_stock(struct mem_cgroup *memcg) 2076 { 2077 struct memcg_stock_pcp *stock; 2078 bool ret = true; 2079 2080 stock = &get_cpu_var(memcg_stock); 2081 if (memcg == stock->cached && stock->nr_pages) 2082 stock->nr_pages--; 2083 else /* need to call res_counter_charge */ 2084 ret = false; 2085 put_cpu_var(memcg_stock); 2086 return ret; 2087 } 2088 2089 /* 2090 * Returns stocks cached in percpu to res_counter and reset cached information. 2091 */ 2092 static void drain_stock(struct memcg_stock_pcp *stock) 2093 { 2094 struct mem_cgroup *old = stock->cached; 2095 2096 if (stock->nr_pages) { 2097 unsigned long bytes = stock->nr_pages * PAGE_SIZE; 2098 2099 res_counter_uncharge(&old->res, bytes); 2100 if (do_swap_account) 2101 res_counter_uncharge(&old->memsw, bytes); 2102 stock->nr_pages = 0; 2103 } 2104 stock->cached = NULL; 2105 } 2106 2107 /* 2108 * This must be called under preempt disabled or must be called by 2109 * a thread which is pinned to local cpu. 2110 */ 2111 static void drain_local_stock(struct work_struct *dummy) 2112 { 2113 struct memcg_stock_pcp *stock = &__get_cpu_var(memcg_stock); 2114 drain_stock(stock); 2115 clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags); 2116 } 2117 2118 /* 2119 * Cache charges(val) which is from res_counter, to local per_cpu area. 2120 * This will be consumed by consume_stock() function, later. 2121 */ 2122 static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages) 2123 { 2124 struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock); 2125 2126 if (stock->cached != memcg) { /* reset if necessary */ 2127 drain_stock(stock); 2128 stock->cached = memcg; 2129 } 2130 stock->nr_pages += nr_pages; 2131 put_cpu_var(memcg_stock); 2132 } 2133 2134 /* 2135 * Drains all per-CPU charge caches for given root_memcg resp. subtree 2136 * of the hierarchy under it. sync flag says whether we should block 2137 * until the work is done. 2138 */ 2139 static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync) 2140 { 2141 int cpu, curcpu; 2142 2143 /* Notify other cpus that system-wide "drain" is running */ 2144 get_online_cpus(); 2145 curcpu = get_cpu(); 2146 for_each_online_cpu(cpu) { 2147 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu); 2148 struct mem_cgroup *memcg; 2149 2150 memcg = stock->cached; 2151 if (!memcg || !stock->nr_pages) 2152 continue; 2153 if (!mem_cgroup_same_or_subtree(root_memcg, memcg)) 2154 continue; 2155 if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) { 2156 if (cpu == curcpu) 2157 drain_local_stock(&stock->work); 2158 else 2159 schedule_work_on(cpu, &stock->work); 2160 } 2161 } 2162 put_cpu(); 2163 2164 if (!sync) 2165 goto out; 2166 2167 for_each_online_cpu(cpu) { 2168 struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu); 2169 if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) 2170 flush_work(&stock->work); 2171 } 2172 out: 2173 put_online_cpus(); 2174 } 2175 2176 /* 2177 * Tries to drain stocked charges in other cpus. This function is asynchronous 2178 * and just put a work per cpu for draining localy on each cpu. Caller can 2179 * expects some charges will be back to res_counter later but cannot wait for 2180 * it. 2181 */ 2182 static void drain_all_stock_async(struct mem_cgroup *root_memcg) 2183 { 2184 /* 2185 * If someone calls draining, avoid adding more kworker runs. 2186 */ 2187 if (!mutex_trylock(&percpu_charge_mutex)) 2188 return; 2189 drain_all_stock(root_memcg, false); 2190 mutex_unlock(&percpu_charge_mutex); 2191 } 2192 2193 /* This is a synchronous drain interface. */ 2194 static void drain_all_stock_sync(struct mem_cgroup *root_memcg) 2195 { 2196 /* called when force_empty is called */ 2197 mutex_lock(&percpu_charge_mutex); 2198 drain_all_stock(root_memcg, true); 2199 mutex_unlock(&percpu_charge_mutex); 2200 } 2201 2202 /* 2203 * This function drains percpu counter value from DEAD cpu and 2204 * move it to local cpu. Note that this function can be preempted. 2205 */ 2206 static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu) 2207 { 2208 int i; 2209 2210 spin_lock(&memcg->pcp_counter_lock); 2211 for (i = 0; i < MEM_CGROUP_STAT_DATA; i++) { 2212 long x = per_cpu(memcg->stat->count[i], cpu); 2213 2214 per_cpu(memcg->stat->count[i], cpu) = 0; 2215 memcg->nocpu_base.count[i] += x; 2216 } 2217 for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) { 2218 unsigned long x = per_cpu(memcg->stat->events[i], cpu); 2219 2220 per_cpu(memcg->stat->events[i], cpu) = 0; 2221 memcg->nocpu_base.events[i] += x; 2222 } 2223 /* need to clear ON_MOVE value, works as a kind of lock. */ 2224 per_cpu(memcg->stat->count[MEM_CGROUP_ON_MOVE], cpu) = 0; 2225 spin_unlock(&memcg->pcp_counter_lock); 2226 } 2227 2228 static void synchronize_mem_cgroup_on_move(struct mem_cgroup *memcg, int cpu) 2229 { 2230 int idx = MEM_CGROUP_ON_MOVE; 2231 2232 spin_lock(&memcg->pcp_counter_lock); 2233 per_cpu(memcg->stat->count[idx], cpu) = memcg->nocpu_base.count[idx]; 2234 spin_unlock(&memcg->pcp_counter_lock); 2235 } 2236 2237 static int __cpuinit memcg_cpu_hotplug_callback(struct notifier_block *nb, 2238 unsigned long action, 2239 void *hcpu) 2240 { 2241 int cpu = (unsigned long)hcpu; 2242 struct memcg_stock_pcp *stock; 2243 struct mem_cgroup *iter; 2244 2245 if ((action == CPU_ONLINE)) { 2246 for_each_mem_cgroup_all(iter) 2247 synchronize_mem_cgroup_on_move(iter, cpu); 2248 return NOTIFY_OK; 2249 } 2250 2251 if ((action != CPU_DEAD) || action != CPU_DEAD_FROZEN) 2252 return NOTIFY_OK; 2253 2254 for_each_mem_cgroup_all(iter) 2255 mem_cgroup_drain_pcp_counter(iter, cpu); 2256 2257 stock = &per_cpu(memcg_stock, cpu); 2258 drain_stock(stock); 2259 return NOTIFY_OK; 2260 } 2261 2262 2263 /* See __mem_cgroup_try_charge() for details */ 2264 enum { 2265 CHARGE_OK, /* success */ 2266 CHARGE_RETRY, /* need to retry but retry is not bad */ 2267 CHARGE_NOMEM, /* we can't do more. return -ENOMEM */ 2268 CHARGE_WOULDBLOCK, /* GFP_WAIT wasn't set and no enough res. */ 2269 CHARGE_OOM_DIE, /* the current is killed because of OOM */ 2270 }; 2271 2272 static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask, 2273 unsigned int nr_pages, bool oom_check) 2274 { 2275 unsigned long csize = nr_pages * PAGE_SIZE; 2276 struct mem_cgroup *mem_over_limit; 2277 struct res_counter *fail_res; 2278 unsigned long flags = 0; 2279 int ret; 2280 2281 ret = res_counter_charge(&memcg->res, csize, &fail_res); 2282 2283 if (likely(!ret)) { 2284 if (!do_swap_account) 2285 return CHARGE_OK; 2286 ret = res_counter_charge(&memcg->memsw, csize, &fail_res); 2287 if (likely(!ret)) 2288 return CHARGE_OK; 2289 2290 res_counter_uncharge(&memcg->res, csize); 2291 mem_over_limit = mem_cgroup_from_res_counter(fail_res, memsw); 2292 flags |= MEM_CGROUP_RECLAIM_NOSWAP; 2293 } else 2294 mem_over_limit = mem_cgroup_from_res_counter(fail_res, res); 2295 /* 2296 * nr_pages can be either a huge page (HPAGE_PMD_NR), a batch 2297 * of regular pages (CHARGE_BATCH), or a single regular page (1). 2298 * 2299 * Never reclaim on behalf of optional batching, retry with a 2300 * single page instead. 2301 */ 2302 if (nr_pages == CHARGE_BATCH) 2303 return CHARGE_RETRY; 2304 2305 if (!(gfp_mask & __GFP_WAIT)) 2306 return CHARGE_WOULDBLOCK; 2307 2308 ret = mem_cgroup_hierarchical_reclaim(mem_over_limit, NULL, 2309 gfp_mask, flags, NULL); 2310 if (mem_cgroup_margin(mem_over_limit) >= nr_pages) 2311 return CHARGE_RETRY; 2312 /* 2313 * Even though the limit is exceeded at this point, reclaim 2314 * may have been able to free some pages. Retry the charge 2315 * before killing the task. 2316 * 2317 * Only for regular pages, though: huge pages are rather 2318 * unlikely to succeed so close to the limit, and we fall back 2319 * to regular pages anyway in case of failure. 2320 */ 2321 if (nr_pages == 1 && ret) 2322 return CHARGE_RETRY; 2323 2324 /* 2325 * At task move, charge accounts can be doubly counted. So, it's 2326 * better to wait until the end of task_move if something is going on. 2327 */ 2328 if (mem_cgroup_wait_acct_move(mem_over_limit)) 2329 return CHARGE_RETRY; 2330 2331 /* If we don't need to call oom-killer at el, return immediately */ 2332 if (!oom_check) 2333 return CHARGE_NOMEM; 2334 /* check OOM */ 2335 if (!mem_cgroup_handle_oom(mem_over_limit, gfp_mask)) 2336 return CHARGE_OOM_DIE; 2337 2338 return CHARGE_RETRY; 2339 } 2340 2341 /* 2342 * Unlike exported interface, "oom" parameter is added. if oom==true, 2343 * oom-killer can be invoked. 2344 */ 2345 static int __mem_cgroup_try_charge(struct mm_struct *mm, 2346 gfp_t gfp_mask, 2347 unsigned int nr_pages, 2348 struct mem_cgroup **ptr, 2349 bool oom) 2350 { 2351 unsigned int batch = max(CHARGE_BATCH, nr_pages); 2352 int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES; 2353 struct mem_cgroup *memcg = NULL; 2354 int ret; 2355 2356 /* 2357 * Unlike gloval-vm's OOM-kill, we're not in memory shortage 2358 * in system level. So, allow to go ahead dying process in addition to 2359 * MEMDIE process. 2360 */ 2361 if (unlikely(test_thread_flag(TIF_MEMDIE) 2362 || fatal_signal_pending(current))) 2363 goto bypass; 2364 2365 /* 2366 * We always charge the cgroup the mm_struct belongs to. 2367 * The mm_struct's mem_cgroup changes on task migration if the 2368 * thread group leader migrates. It's possible that mm is not 2369 * set, if so charge the init_mm (happens for pagecache usage). 2370 */ 2371 if (!*ptr && !mm) 2372 goto bypass; 2373 again: 2374 if (*ptr) { /* css should be a valid one */ 2375 memcg = *ptr; 2376 VM_BUG_ON(css_is_removed(&memcg->css)); 2377 if (mem_cgroup_is_root(memcg)) 2378 goto done; 2379 if (nr_pages == 1 && consume_stock(memcg)) 2380 goto done; 2381 css_get(&memcg->css); 2382 } else { 2383 struct task_struct *p; 2384 2385 rcu_read_lock(); 2386 p = rcu_dereference(mm->owner); 2387 /* 2388 * Because we don't have task_lock(), "p" can exit. 2389 * In that case, "memcg" can point to root or p can be NULL with 2390 * race with swapoff. Then, we have small risk of mis-accouning. 2391 * But such kind of mis-account by race always happens because 2392 * we don't have cgroup_mutex(). It's overkill and we allo that 2393 * small race, here. 2394 * (*) swapoff at el will charge against mm-struct not against 2395 * task-struct. So, mm->owner can be NULL. 2396 */ 2397 memcg = mem_cgroup_from_task(p); 2398 if (!memcg || mem_cgroup_is_root(memcg)) { 2399 rcu_read_unlock(); 2400 goto done; 2401 } 2402 if (nr_pages == 1 && consume_stock(memcg)) { 2403 /* 2404 * It seems dagerous to access memcg without css_get(). 2405 * But considering how consume_stok works, it's not 2406 * necessary. If consume_stock success, some charges 2407 * from this memcg are cached on this cpu. So, we 2408 * don't need to call css_get()/css_tryget() before 2409 * calling consume_stock(). 2410 */ 2411 rcu_read_unlock(); 2412 goto done; 2413 } 2414 /* after here, we may be blocked. we need to get refcnt */ 2415 if (!css_tryget(&memcg->css)) { 2416 rcu_read_unlock(); 2417 goto again; 2418 } 2419 rcu_read_unlock(); 2420 } 2421 2422 do { 2423 bool oom_check; 2424 2425 /* If killed, bypass charge */ 2426 if (fatal_signal_pending(current)) { 2427 css_put(&memcg->css); 2428 goto bypass; 2429 } 2430 2431 oom_check = false; 2432 if (oom && !nr_oom_retries) { 2433 oom_check = true; 2434 nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES; 2435 } 2436 2437 ret = mem_cgroup_do_charge(memcg, gfp_mask, batch, oom_check); 2438 switch (ret) { 2439 case CHARGE_OK: 2440 break; 2441 case CHARGE_RETRY: /* not in OOM situation but retry */ 2442 batch = nr_pages; 2443 css_put(&memcg->css); 2444 memcg = NULL; 2445 goto again; 2446 case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */ 2447 css_put(&memcg->css); 2448 goto nomem; 2449 case CHARGE_NOMEM: /* OOM routine works */ 2450 if (!oom) { 2451 css_put(&memcg->css); 2452 goto nomem; 2453 } 2454 /* If oom, we never return -ENOMEM */ 2455 nr_oom_retries--; 2456 break; 2457 case CHARGE_OOM_DIE: /* Killed by OOM Killer */ 2458 css_put(&memcg->css); 2459 goto bypass; 2460 } 2461 } while (ret != CHARGE_OK); 2462 2463 if (batch > nr_pages) 2464 refill_stock(memcg, batch - nr_pages); 2465 css_put(&memcg->css); 2466 done: 2467 *ptr = memcg; 2468 return 0; 2469 nomem: 2470 *ptr = NULL; 2471 return -ENOMEM; 2472 bypass: 2473 *ptr = NULL; 2474 return 0; 2475 } 2476 2477 /* 2478 * Somemtimes we have to undo a charge we got by try_charge(). 2479 * This function is for that and do uncharge, put css's refcnt. 2480 * gotten by try_charge(). 2481 */ 2482 static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg, 2483 unsigned int nr_pages) 2484 { 2485 if (!mem_cgroup_is_root(memcg)) { 2486 unsigned long bytes = nr_pages * PAGE_SIZE; 2487 2488 res_counter_uncharge(&memcg->res, bytes); 2489 if (do_swap_account) 2490 res_counter_uncharge(&memcg->memsw, bytes); 2491 } 2492 } 2493 2494 /* 2495 * A helper function to get mem_cgroup from ID. must be called under 2496 * rcu_read_lock(). The caller must check css_is_removed() or some if 2497 * it's concern. (dropping refcnt from swap can be called against removed 2498 * memcg.) 2499 */ 2500 static struct mem_cgroup *mem_cgroup_lookup(unsigned short id) 2501 { 2502 struct cgroup_subsys_state *css; 2503 2504 /* ID 0 is unused ID */ 2505 if (!id) 2506 return NULL; 2507 css = css_lookup(&mem_cgroup_subsys, id); 2508 if (!css) 2509 return NULL; 2510 return container_of(css, struct mem_cgroup, css); 2511 } 2512 2513 struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page) 2514 { 2515 struct mem_cgroup *memcg = NULL; 2516 struct page_cgroup *pc; 2517 unsigned short id; 2518 swp_entry_t ent; 2519 2520 VM_BUG_ON(!PageLocked(page)); 2521 2522 pc = lookup_page_cgroup(page); 2523 lock_page_cgroup(pc); 2524 if (PageCgroupUsed(pc)) { 2525 memcg = pc->mem_cgroup; 2526 if (memcg && !css_tryget(&memcg->css)) 2527 memcg = NULL; 2528 } else if (PageSwapCache(page)) { 2529 ent.val = page_private(page); 2530 id = lookup_swap_cgroup(ent); 2531 rcu_read_lock(); 2532 memcg = mem_cgroup_lookup(id); 2533 if (memcg && !css_tryget(&memcg->css)) 2534 memcg = NULL; 2535 rcu_read_unlock(); 2536 } 2537 unlock_page_cgroup(pc); 2538 return memcg; 2539 } 2540 2541 static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg, 2542 struct page *page, 2543 unsigned int nr_pages, 2544 struct page_cgroup *pc, 2545 enum charge_type ctype) 2546 { 2547 lock_page_cgroup(pc); 2548 if (unlikely(PageCgroupUsed(pc))) { 2549 unlock_page_cgroup(pc); 2550 __mem_cgroup_cancel_charge(memcg, nr_pages); 2551 return; 2552 } 2553 /* 2554 * we don't need page_cgroup_lock about tail pages, becase they are not 2555 * accessed by any other context at this point. 2556 */ 2557 pc->mem_cgroup = memcg; 2558 /* 2559 * We access a page_cgroup asynchronously without lock_page_cgroup(). 2560 * Especially when a page_cgroup is taken from a page, pc->mem_cgroup 2561 * is accessed after testing USED bit. To make pc->mem_cgroup visible 2562 * before USED bit, we need memory barrier here. 2563 * See mem_cgroup_add_lru_list(), etc. 2564 */ 2565 smp_wmb(); 2566 switch (ctype) { 2567 case MEM_CGROUP_CHARGE_TYPE_CACHE: 2568 case MEM_CGROUP_CHARGE_TYPE_SHMEM: 2569 SetPageCgroupCache(pc); 2570 SetPageCgroupUsed(pc); 2571 break; 2572 case MEM_CGROUP_CHARGE_TYPE_MAPPED: 2573 ClearPageCgroupCache(pc); 2574 SetPageCgroupUsed(pc); 2575 break; 2576 default: 2577 break; 2578 } 2579 2580 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), nr_pages); 2581 unlock_page_cgroup(pc); 2582 /* 2583 * "charge_statistics" updated event counter. Then, check it. 2584 * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree. 2585 * if they exceeds softlimit. 2586 */ 2587 memcg_check_events(memcg, page); 2588 } 2589 2590 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 2591 2592 #define PCGF_NOCOPY_AT_SPLIT ((1 << PCG_LOCK) | (1 << PCG_MOVE_LOCK) |\ 2593 (1 << PCG_ACCT_LRU) | (1 << PCG_MIGRATION)) 2594 /* 2595 * Because tail pages are not marked as "used", set it. We're under 2596 * zone->lru_lock, 'splitting on pmd' and compund_lock. 2597 */ 2598 void mem_cgroup_split_huge_fixup(struct page *head, struct page *tail) 2599 { 2600 struct page_cgroup *head_pc = lookup_page_cgroup(head); 2601 struct page_cgroup *tail_pc = lookup_page_cgroup(tail); 2602 unsigned long flags; 2603 2604 if (mem_cgroup_disabled()) 2605 return; 2606 /* 2607 * We have no races with charge/uncharge but will have races with 2608 * page state accounting. 2609 */ 2610 move_lock_page_cgroup(head_pc, &flags); 2611 2612 tail_pc->mem_cgroup = head_pc->mem_cgroup; 2613 smp_wmb(); /* see __commit_charge() */ 2614 if (PageCgroupAcctLRU(head_pc)) { 2615 enum lru_list lru; 2616 struct mem_cgroup_per_zone *mz; 2617 2618 /* 2619 * LRU flags cannot be copied because we need to add tail 2620 *.page to LRU by generic call and our hook will be called. 2621 * We hold lru_lock, then, reduce counter directly. 2622 */ 2623 lru = page_lru(head); 2624 mz = page_cgroup_zoneinfo(head_pc->mem_cgroup, head); 2625 MEM_CGROUP_ZSTAT(mz, lru) -= 1; 2626 } 2627 tail_pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT; 2628 move_unlock_page_cgroup(head_pc, &flags); 2629 } 2630 #endif 2631 2632 /** 2633 * mem_cgroup_move_account - move account of the page 2634 * @page: the page 2635 * @nr_pages: number of regular pages (>1 for huge pages) 2636 * @pc: page_cgroup of the page. 2637 * @from: mem_cgroup which the page is moved from. 2638 * @to: mem_cgroup which the page is moved to. @from != @to. 2639 * @uncharge: whether we should call uncharge and css_put against @from. 2640 * 2641 * The caller must confirm following. 2642 * - page is not on LRU (isolate_page() is useful.) 2643 * - compound_lock is held when nr_pages > 1 2644 * 2645 * This function doesn't do "charge" nor css_get to new cgroup. It should be 2646 * done by a caller(__mem_cgroup_try_charge would be useful). If @uncharge is 2647 * true, this function does "uncharge" from old cgroup, but it doesn't if 2648 * @uncharge is false, so a caller should do "uncharge". 2649 */ 2650 static int mem_cgroup_move_account(struct page *page, 2651 unsigned int nr_pages, 2652 struct page_cgroup *pc, 2653 struct mem_cgroup *from, 2654 struct mem_cgroup *to, 2655 bool uncharge) 2656 { 2657 unsigned long flags; 2658 int ret; 2659 2660 VM_BUG_ON(from == to); 2661 VM_BUG_ON(PageLRU(page)); 2662 /* 2663 * The page is isolated from LRU. So, collapse function 2664 * will not handle this page. But page splitting can happen. 2665 * Do this check under compound_page_lock(). The caller should 2666 * hold it. 2667 */ 2668 ret = -EBUSY; 2669 if (nr_pages > 1 && !PageTransHuge(page)) 2670 goto out; 2671 2672 lock_page_cgroup(pc); 2673 2674 ret = -EINVAL; 2675 if (!PageCgroupUsed(pc) || pc->mem_cgroup != from) 2676 goto unlock; 2677 2678 move_lock_page_cgroup(pc, &flags); 2679 2680 if (PageCgroupFileMapped(pc)) { 2681 /* Update mapped_file data for mem_cgroup */ 2682 preempt_disable(); 2683 __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]); 2684 __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]); 2685 preempt_enable(); 2686 } 2687 mem_cgroup_charge_statistics(from, PageCgroupCache(pc), -nr_pages); 2688 if (uncharge) 2689 /* This is not "cancel", but cancel_charge does all we need. */ 2690 __mem_cgroup_cancel_charge(from, nr_pages); 2691 2692 /* caller should have done css_get */ 2693 pc->mem_cgroup = to; 2694 mem_cgroup_charge_statistics(to, PageCgroupCache(pc), nr_pages); 2695 /* 2696 * We charges against "to" which may not have any tasks. Then, "to" 2697 * can be under rmdir(). But in current implementation, caller of 2698 * this function is just force_empty() and move charge, so it's 2699 * guaranteed that "to" is never removed. So, we don't check rmdir 2700 * status here. 2701 */ 2702 move_unlock_page_cgroup(pc, &flags); 2703 ret = 0; 2704 unlock: 2705 unlock_page_cgroup(pc); 2706 /* 2707 * check events 2708 */ 2709 memcg_check_events(to, page); 2710 memcg_check_events(from, page); 2711 out: 2712 return ret; 2713 } 2714 2715 /* 2716 * move charges to its parent. 2717 */ 2718 2719 static int mem_cgroup_move_parent(struct page *page, 2720 struct page_cgroup *pc, 2721 struct mem_cgroup *child, 2722 gfp_t gfp_mask) 2723 { 2724 struct cgroup *cg = child->css.cgroup; 2725 struct cgroup *pcg = cg->parent; 2726 struct mem_cgroup *parent; 2727 unsigned int nr_pages; 2728 unsigned long uninitialized_var(flags); 2729 int ret; 2730 2731 /* Is ROOT ? */ 2732 if (!pcg) 2733 return -EINVAL; 2734 2735 ret = -EBUSY; 2736 if (!get_page_unless_zero(page)) 2737 goto out; 2738 if (isolate_lru_page(page)) 2739 goto put; 2740 2741 nr_pages = hpage_nr_pages(page); 2742 2743 parent = mem_cgroup_from_cont(pcg); 2744 ret = __mem_cgroup_try_charge(NULL, gfp_mask, nr_pages, &parent, false); 2745 if (ret || !parent) 2746 goto put_back; 2747 2748 if (nr_pages > 1) 2749 flags = compound_lock_irqsave(page); 2750 2751 ret = mem_cgroup_move_account(page, nr_pages, pc, child, parent, true); 2752 if (ret) 2753 __mem_cgroup_cancel_charge(parent, nr_pages); 2754 2755 if (nr_pages > 1) 2756 compound_unlock_irqrestore(page, flags); 2757 put_back: 2758 putback_lru_page(page); 2759 put: 2760 put_page(page); 2761 out: 2762 return ret; 2763 } 2764 2765 /* 2766 * Charge the memory controller for page usage. 2767 * Return 2768 * 0 if the charge was successful 2769 * < 0 if the cgroup is over its limit 2770 */ 2771 static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm, 2772 gfp_t gfp_mask, enum charge_type ctype) 2773 { 2774 struct mem_cgroup *memcg = NULL; 2775 unsigned int nr_pages = 1; 2776 struct page_cgroup *pc; 2777 bool oom = true; 2778 int ret; 2779 2780 if (PageTransHuge(page)) { 2781 nr_pages <<= compound_order(page); 2782 VM_BUG_ON(!PageTransHuge(page)); 2783 /* 2784 * Never OOM-kill a process for a huge page. The 2785 * fault handler will fall back to regular pages. 2786 */ 2787 oom = false; 2788 } 2789 2790 pc = lookup_page_cgroup(page); 2791 BUG_ON(!pc); /* XXX: remove this and move pc lookup into commit */ 2792 2793 ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom); 2794 if (ret || !memcg) 2795 return ret; 2796 2797 __mem_cgroup_commit_charge(memcg, page, nr_pages, pc, ctype); 2798 return 0; 2799 } 2800 2801 int mem_cgroup_newpage_charge(struct page *page, 2802 struct mm_struct *mm, gfp_t gfp_mask) 2803 { 2804 if (mem_cgroup_disabled()) 2805 return 0; 2806 /* 2807 * If already mapped, we don't have to account. 2808 * If page cache, page->mapping has address_space. 2809 * But page->mapping may have out-of-use anon_vma pointer, 2810 * detecit it by PageAnon() check. newly-mapped-anon's page->mapping 2811 * is NULL. 2812 */ 2813 if (page_mapped(page) || (page->mapping && !PageAnon(page))) 2814 return 0; 2815 if (unlikely(!mm)) 2816 mm = &init_mm; 2817 return mem_cgroup_charge_common(page, mm, gfp_mask, 2818 MEM_CGROUP_CHARGE_TYPE_MAPPED); 2819 } 2820 2821 static void 2822 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr, 2823 enum charge_type ctype); 2824 2825 static void 2826 __mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *memcg, 2827 enum charge_type ctype) 2828 { 2829 struct page_cgroup *pc = lookup_page_cgroup(page); 2830 /* 2831 * In some case, SwapCache, FUSE(splice_buf->radixtree), the page 2832 * is already on LRU. It means the page may on some other page_cgroup's 2833 * LRU. Take care of it. 2834 */ 2835 mem_cgroup_lru_del_before_commit(page); 2836 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype); 2837 mem_cgroup_lru_add_after_commit(page); 2838 return; 2839 } 2840 2841 int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm, 2842 gfp_t gfp_mask) 2843 { 2844 struct mem_cgroup *memcg = NULL; 2845 int ret; 2846 2847 if (mem_cgroup_disabled()) 2848 return 0; 2849 if (PageCompound(page)) 2850 return 0; 2851 2852 if (unlikely(!mm)) 2853 mm = &init_mm; 2854 2855 if (page_is_file_cache(page)) { 2856 ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, &memcg, true); 2857 if (ret || !memcg) 2858 return ret; 2859 2860 /* 2861 * FUSE reuses pages without going through the final 2862 * put that would remove them from the LRU list, make 2863 * sure that they get relinked properly. 2864 */ 2865 __mem_cgroup_commit_charge_lrucare(page, memcg, 2866 MEM_CGROUP_CHARGE_TYPE_CACHE); 2867 return ret; 2868 } 2869 /* shmem */ 2870 if (PageSwapCache(page)) { 2871 ret = mem_cgroup_try_charge_swapin(mm, page, gfp_mask, &memcg); 2872 if (!ret) 2873 __mem_cgroup_commit_charge_swapin(page, memcg, 2874 MEM_CGROUP_CHARGE_TYPE_SHMEM); 2875 } else 2876 ret = mem_cgroup_charge_common(page, mm, gfp_mask, 2877 MEM_CGROUP_CHARGE_TYPE_SHMEM); 2878 2879 return ret; 2880 } 2881 2882 /* 2883 * While swap-in, try_charge -> commit or cancel, the page is locked. 2884 * And when try_charge() successfully returns, one refcnt to memcg without 2885 * struct page_cgroup is acquired. This refcnt will be consumed by 2886 * "commit()" or removed by "cancel()" 2887 */ 2888 int mem_cgroup_try_charge_swapin(struct mm_struct *mm, 2889 struct page *page, 2890 gfp_t mask, struct mem_cgroup **ptr) 2891 { 2892 struct mem_cgroup *memcg; 2893 int ret; 2894 2895 *ptr = NULL; 2896 2897 if (mem_cgroup_disabled()) 2898 return 0; 2899 2900 if (!do_swap_account) 2901 goto charge_cur_mm; 2902 /* 2903 * A racing thread's fault, or swapoff, may have already updated 2904 * the pte, and even removed page from swap cache: in those cases 2905 * do_swap_page()'s pte_same() test will fail; but there's also a 2906 * KSM case which does need to charge the page. 2907 */ 2908 if (!PageSwapCache(page)) 2909 goto charge_cur_mm; 2910 memcg = try_get_mem_cgroup_from_page(page); 2911 if (!memcg) 2912 goto charge_cur_mm; 2913 *ptr = memcg; 2914 ret = __mem_cgroup_try_charge(NULL, mask, 1, ptr, true); 2915 css_put(&memcg->css); 2916 return ret; 2917 charge_cur_mm: 2918 if (unlikely(!mm)) 2919 mm = &init_mm; 2920 return __mem_cgroup_try_charge(mm, mask, 1, ptr, true); 2921 } 2922 2923 static void 2924 __mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr, 2925 enum charge_type ctype) 2926 { 2927 if (mem_cgroup_disabled()) 2928 return; 2929 if (!ptr) 2930 return; 2931 cgroup_exclude_rmdir(&ptr->css); 2932 2933 __mem_cgroup_commit_charge_lrucare(page, ptr, ctype); 2934 /* 2935 * Now swap is on-memory. This means this page may be 2936 * counted both as mem and swap....double count. 2937 * Fix it by uncharging from memsw. Basically, this SwapCache is stable 2938 * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page() 2939 * may call delete_from_swap_cache() before reach here. 2940 */ 2941 if (do_swap_account && PageSwapCache(page)) { 2942 swp_entry_t ent = {.val = page_private(page)}; 2943 unsigned short id; 2944 struct mem_cgroup *memcg; 2945 2946 id = swap_cgroup_record(ent, 0); 2947 rcu_read_lock(); 2948 memcg = mem_cgroup_lookup(id); 2949 if (memcg) { 2950 /* 2951 * This recorded memcg can be obsolete one. So, avoid 2952 * calling css_tryget 2953 */ 2954 if (!mem_cgroup_is_root(memcg)) 2955 res_counter_uncharge(&memcg->memsw, PAGE_SIZE); 2956 mem_cgroup_swap_statistics(memcg, false); 2957 mem_cgroup_put(memcg); 2958 } 2959 rcu_read_unlock(); 2960 } 2961 /* 2962 * At swapin, we may charge account against cgroup which has no tasks. 2963 * So, rmdir()->pre_destroy() can be called while we do this charge. 2964 * In that case, we need to call pre_destroy() again. check it here. 2965 */ 2966 cgroup_release_and_wakeup_rmdir(&ptr->css); 2967 } 2968 2969 void mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *ptr) 2970 { 2971 __mem_cgroup_commit_charge_swapin(page, ptr, 2972 MEM_CGROUP_CHARGE_TYPE_MAPPED); 2973 } 2974 2975 void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg) 2976 { 2977 if (mem_cgroup_disabled()) 2978 return; 2979 if (!memcg) 2980 return; 2981 __mem_cgroup_cancel_charge(memcg, 1); 2982 } 2983 2984 static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg, 2985 unsigned int nr_pages, 2986 const enum charge_type ctype) 2987 { 2988 struct memcg_batch_info *batch = NULL; 2989 bool uncharge_memsw = true; 2990 2991 /* If swapout, usage of swap doesn't decrease */ 2992 if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) 2993 uncharge_memsw = false; 2994 2995 batch = ¤t->memcg_batch; 2996 /* 2997 * In usual, we do css_get() when we remember memcg pointer. 2998 * But in this case, we keep res->usage until end of a series of 2999 * uncharges. Then, it's ok to ignore memcg's refcnt. 3000 */ 3001 if (!batch->memcg) 3002 batch->memcg = memcg; 3003 /* 3004 * do_batch > 0 when unmapping pages or inode invalidate/truncate. 3005 * In those cases, all pages freed continuously can be expected to be in 3006 * the same cgroup and we have chance to coalesce uncharges. 3007 * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE) 3008 * because we want to do uncharge as soon as possible. 3009 */ 3010 3011 if (!batch->do_batch || test_thread_flag(TIF_MEMDIE)) 3012 goto direct_uncharge; 3013 3014 if (nr_pages > 1) 3015 goto direct_uncharge; 3016 3017 /* 3018 * In typical case, batch->memcg == mem. This means we can 3019 * merge a series of uncharges to an uncharge of res_counter. 3020 * If not, we uncharge res_counter ony by one. 3021 */ 3022 if (batch->memcg != memcg) 3023 goto direct_uncharge; 3024 /* remember freed charge and uncharge it later */ 3025 batch->nr_pages++; 3026 if (uncharge_memsw) 3027 batch->memsw_nr_pages++; 3028 return; 3029 direct_uncharge: 3030 res_counter_uncharge(&memcg->res, nr_pages * PAGE_SIZE); 3031 if (uncharge_memsw) 3032 res_counter_uncharge(&memcg->memsw, nr_pages * PAGE_SIZE); 3033 if (unlikely(batch->memcg != memcg)) 3034 memcg_oom_recover(memcg); 3035 return; 3036 } 3037 3038 /* 3039 * uncharge if !page_mapped(page) 3040 */ 3041 static struct mem_cgroup * 3042 __mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype) 3043 { 3044 struct mem_cgroup *memcg = NULL; 3045 unsigned int nr_pages = 1; 3046 struct page_cgroup *pc; 3047 3048 if (mem_cgroup_disabled()) 3049 return NULL; 3050 3051 if (PageSwapCache(page)) 3052 return NULL; 3053 3054 if (PageTransHuge(page)) { 3055 nr_pages <<= compound_order(page); 3056 VM_BUG_ON(!PageTransHuge(page)); 3057 } 3058 /* 3059 * Check if our page_cgroup is valid 3060 */ 3061 pc = lookup_page_cgroup(page); 3062 if (unlikely(!pc || !PageCgroupUsed(pc))) 3063 return NULL; 3064 3065 lock_page_cgroup(pc); 3066 3067 memcg = pc->mem_cgroup; 3068 3069 if (!PageCgroupUsed(pc)) 3070 goto unlock_out; 3071 3072 switch (ctype) { 3073 case MEM_CGROUP_CHARGE_TYPE_MAPPED: 3074 case MEM_CGROUP_CHARGE_TYPE_DROP: 3075 /* See mem_cgroup_prepare_migration() */ 3076 if (page_mapped(page) || PageCgroupMigration(pc)) 3077 goto unlock_out; 3078 break; 3079 case MEM_CGROUP_CHARGE_TYPE_SWAPOUT: 3080 if (!PageAnon(page)) { /* Shared memory */ 3081 if (page->mapping && !page_is_file_cache(page)) 3082 goto unlock_out; 3083 } else if (page_mapped(page)) /* Anon */ 3084 goto unlock_out; 3085 break; 3086 default: 3087 break; 3088 } 3089 3090 mem_cgroup_charge_statistics(memcg, PageCgroupCache(pc), -nr_pages); 3091 3092 ClearPageCgroupUsed(pc); 3093 /* 3094 * pc->mem_cgroup is not cleared here. It will be accessed when it's 3095 * freed from LRU. This is safe because uncharged page is expected not 3096 * to be reused (freed soon). Exception is SwapCache, it's handled by 3097 * special functions. 3098 */ 3099 3100 unlock_page_cgroup(pc); 3101 /* 3102 * even after unlock, we have memcg->res.usage here and this memcg 3103 * will never be freed. 3104 */ 3105 memcg_check_events(memcg, page); 3106 if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) { 3107 mem_cgroup_swap_statistics(memcg, true); 3108 mem_cgroup_get(memcg); 3109 } 3110 if (!mem_cgroup_is_root(memcg)) 3111 mem_cgroup_do_uncharge(memcg, nr_pages, ctype); 3112 3113 return memcg; 3114 3115 unlock_out: 3116 unlock_page_cgroup(pc); 3117 return NULL; 3118 } 3119 3120 void mem_cgroup_uncharge_page(struct page *page) 3121 { 3122 /* early check. */ 3123 if (page_mapped(page)) 3124 return; 3125 if (page->mapping && !PageAnon(page)) 3126 return; 3127 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_MAPPED); 3128 } 3129 3130 void mem_cgroup_uncharge_cache_page(struct page *page) 3131 { 3132 VM_BUG_ON(page_mapped(page)); 3133 VM_BUG_ON(page->mapping); 3134 __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE); 3135 } 3136 3137 /* 3138 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate. 3139 * In that cases, pages are freed continuously and we can expect pages 3140 * are in the same memcg. All these calls itself limits the number of 3141 * pages freed at once, then uncharge_start/end() is called properly. 3142 * This may be called prural(2) times in a context, 3143 */ 3144 3145 void mem_cgroup_uncharge_start(void) 3146 { 3147 current->memcg_batch.do_batch++; 3148 /* We can do nest. */ 3149 if (current->memcg_batch.do_batch == 1) { 3150 current->memcg_batch.memcg = NULL; 3151 current->memcg_batch.nr_pages = 0; 3152 current->memcg_batch.memsw_nr_pages = 0; 3153 } 3154 } 3155 3156 void mem_cgroup_uncharge_end(void) 3157 { 3158 struct memcg_batch_info *batch = ¤t->memcg_batch; 3159 3160 if (!batch->do_batch) 3161 return; 3162 3163 batch->do_batch--; 3164 if (batch->do_batch) /* If stacked, do nothing. */ 3165 return; 3166 3167 if (!batch->memcg) 3168 return; 3169 /* 3170 * This "batch->memcg" is valid without any css_get/put etc... 3171 * bacause we hide charges behind us. 3172 */ 3173 if (batch->nr_pages) 3174 res_counter_uncharge(&batch->memcg->res, 3175 batch->nr_pages * PAGE_SIZE); 3176 if (batch->memsw_nr_pages) 3177 res_counter_uncharge(&batch->memcg->memsw, 3178 batch->memsw_nr_pages * PAGE_SIZE); 3179 memcg_oom_recover(batch->memcg); 3180 /* forget this pointer (for sanity check) */ 3181 batch->memcg = NULL; 3182 } 3183 3184 #ifdef CONFIG_SWAP 3185 /* 3186 * called after __delete_from_swap_cache() and drop "page" account. 3187 * memcg information is recorded to swap_cgroup of "ent" 3188 */ 3189 void 3190 mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout) 3191 { 3192 struct mem_cgroup *memcg; 3193 int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT; 3194 3195 if (!swapout) /* this was a swap cache but the swap is unused ! */ 3196 ctype = MEM_CGROUP_CHARGE_TYPE_DROP; 3197 3198 memcg = __mem_cgroup_uncharge_common(page, ctype); 3199 3200 /* 3201 * record memcg information, if swapout && memcg != NULL, 3202 * mem_cgroup_get() was called in uncharge(). 3203 */ 3204 if (do_swap_account && swapout && memcg) 3205 swap_cgroup_record(ent, css_id(&memcg->css)); 3206 } 3207 #endif 3208 3209 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP 3210 /* 3211 * called from swap_entry_free(). remove record in swap_cgroup and 3212 * uncharge "memsw" account. 3213 */ 3214 void mem_cgroup_uncharge_swap(swp_entry_t ent) 3215 { 3216 struct mem_cgroup *memcg; 3217 unsigned short id; 3218 3219 if (!do_swap_account) 3220 return; 3221 3222 id = swap_cgroup_record(ent, 0); 3223 rcu_read_lock(); 3224 memcg = mem_cgroup_lookup(id); 3225 if (memcg) { 3226 /* 3227 * We uncharge this because swap is freed. 3228 * This memcg can be obsolete one. We avoid calling css_tryget 3229 */ 3230 if (!mem_cgroup_is_root(memcg)) 3231 res_counter_uncharge(&memcg->memsw, PAGE_SIZE); 3232 mem_cgroup_swap_statistics(memcg, false); 3233 mem_cgroup_put(memcg); 3234 } 3235 rcu_read_unlock(); 3236 } 3237 3238 /** 3239 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record. 3240 * @entry: swap entry to be moved 3241 * @from: mem_cgroup which the entry is moved from 3242 * @to: mem_cgroup which the entry is moved to 3243 * @need_fixup: whether we should fixup res_counters and refcounts. 3244 * 3245 * It succeeds only when the swap_cgroup's record for this entry is the same 3246 * as the mem_cgroup's id of @from. 3247 * 3248 * Returns 0 on success, -EINVAL on failure. 3249 * 3250 * The caller must have charged to @to, IOW, called res_counter_charge() about 3251 * both res and memsw, and called css_get(). 3252 */ 3253 static int mem_cgroup_move_swap_account(swp_entry_t entry, 3254 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup) 3255 { 3256 unsigned short old_id, new_id; 3257 3258 old_id = css_id(&from->css); 3259 new_id = css_id(&to->css); 3260 3261 if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) { 3262 mem_cgroup_swap_statistics(from, false); 3263 mem_cgroup_swap_statistics(to, true); 3264 /* 3265 * This function is only called from task migration context now. 3266 * It postpones res_counter and refcount handling till the end 3267 * of task migration(mem_cgroup_clear_mc()) for performance 3268 * improvement. But we cannot postpone mem_cgroup_get(to) 3269 * because if the process that has been moved to @to does 3270 * swap-in, the refcount of @to might be decreased to 0. 3271 */ 3272 mem_cgroup_get(to); 3273 if (need_fixup) { 3274 if (!mem_cgroup_is_root(from)) 3275 res_counter_uncharge(&from->memsw, PAGE_SIZE); 3276 mem_cgroup_put(from); 3277 /* 3278 * we charged both to->res and to->memsw, so we should 3279 * uncharge to->res. 3280 */ 3281 if (!mem_cgroup_is_root(to)) 3282 res_counter_uncharge(&to->res, PAGE_SIZE); 3283 } 3284 return 0; 3285 } 3286 return -EINVAL; 3287 } 3288 #else 3289 static inline int mem_cgroup_move_swap_account(swp_entry_t entry, 3290 struct mem_cgroup *from, struct mem_cgroup *to, bool need_fixup) 3291 { 3292 return -EINVAL; 3293 } 3294 #endif 3295 3296 /* 3297 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old 3298 * page belongs to. 3299 */ 3300 int mem_cgroup_prepare_migration(struct page *page, 3301 struct page *newpage, struct mem_cgroup **ptr, gfp_t gfp_mask) 3302 { 3303 struct mem_cgroup *memcg = NULL; 3304 struct page_cgroup *pc; 3305 enum charge_type ctype; 3306 int ret = 0; 3307 3308 *ptr = NULL; 3309 3310 VM_BUG_ON(PageTransHuge(page)); 3311 if (mem_cgroup_disabled()) 3312 return 0; 3313 3314 pc = lookup_page_cgroup(page); 3315 lock_page_cgroup(pc); 3316 if (PageCgroupUsed(pc)) { 3317 memcg = pc->mem_cgroup; 3318 css_get(&memcg->css); 3319 /* 3320 * At migrating an anonymous page, its mapcount goes down 3321 * to 0 and uncharge() will be called. But, even if it's fully 3322 * unmapped, migration may fail and this page has to be 3323 * charged again. We set MIGRATION flag here and delay uncharge 3324 * until end_migration() is called 3325 * 3326 * Corner Case Thinking 3327 * A) 3328 * When the old page was mapped as Anon and it's unmap-and-freed 3329 * while migration was ongoing. 3330 * If unmap finds the old page, uncharge() of it will be delayed 3331 * until end_migration(). If unmap finds a new page, it's 3332 * uncharged when it make mapcount to be 1->0. If unmap code 3333 * finds swap_migration_entry, the new page will not be mapped 3334 * and end_migration() will find it(mapcount==0). 3335 * 3336 * B) 3337 * When the old page was mapped but migraion fails, the kernel 3338 * remaps it. A charge for it is kept by MIGRATION flag even 3339 * if mapcount goes down to 0. We can do remap successfully 3340 * without charging it again. 3341 * 3342 * C) 3343 * The "old" page is under lock_page() until the end of 3344 * migration, so, the old page itself will not be swapped-out. 3345 * If the new page is swapped out before end_migraton, our 3346 * hook to usual swap-out path will catch the event. 3347 */ 3348 if (PageAnon(page)) 3349 SetPageCgroupMigration(pc); 3350 } 3351 unlock_page_cgroup(pc); 3352 /* 3353 * If the page is not charged at this point, 3354 * we return here. 3355 */ 3356 if (!memcg) 3357 return 0; 3358 3359 *ptr = memcg; 3360 ret = __mem_cgroup_try_charge(NULL, gfp_mask, 1, ptr, false); 3361 css_put(&memcg->css);/* drop extra refcnt */ 3362 if (ret || *ptr == NULL) { 3363 if (PageAnon(page)) { 3364 lock_page_cgroup(pc); 3365 ClearPageCgroupMigration(pc); 3366 unlock_page_cgroup(pc); 3367 /* 3368 * The old page may be fully unmapped while we kept it. 3369 */ 3370 mem_cgroup_uncharge_page(page); 3371 } 3372 return -ENOMEM; 3373 } 3374 /* 3375 * We charge new page before it's used/mapped. So, even if unlock_page() 3376 * is called before end_migration, we can catch all events on this new 3377 * page. In the case new page is migrated but not remapped, new page's 3378 * mapcount will be finally 0 and we call uncharge in end_migration(). 3379 */ 3380 pc = lookup_page_cgroup(newpage); 3381 if (PageAnon(page)) 3382 ctype = MEM_CGROUP_CHARGE_TYPE_MAPPED; 3383 else if (page_is_file_cache(page)) 3384 ctype = MEM_CGROUP_CHARGE_TYPE_CACHE; 3385 else 3386 ctype = MEM_CGROUP_CHARGE_TYPE_SHMEM; 3387 __mem_cgroup_commit_charge(memcg, page, 1, pc, ctype); 3388 return ret; 3389 } 3390 3391 /* remove redundant charge if migration failed*/ 3392 void mem_cgroup_end_migration(struct mem_cgroup *memcg, 3393 struct page *oldpage, struct page *newpage, bool migration_ok) 3394 { 3395 struct page *used, *unused; 3396 struct page_cgroup *pc; 3397 3398 if (!memcg) 3399 return; 3400 /* blocks rmdir() */ 3401 cgroup_exclude_rmdir(&memcg->css); 3402 if (!migration_ok) { 3403 used = oldpage; 3404 unused = newpage; 3405 } else { 3406 used = newpage; 3407 unused = oldpage; 3408 } 3409 /* 3410 * We disallowed uncharge of pages under migration because mapcount 3411 * of the page goes down to zero, temporarly. 3412 * Clear the flag and check the page should be charged. 3413 */ 3414 pc = lookup_page_cgroup(oldpage); 3415 lock_page_cgroup(pc); 3416 ClearPageCgroupMigration(pc); 3417 unlock_page_cgroup(pc); 3418 3419 __mem_cgroup_uncharge_common(unused, MEM_CGROUP_CHARGE_TYPE_FORCE); 3420 3421 /* 3422 * If a page is a file cache, radix-tree replacement is very atomic 3423 * and we can skip this check. When it was an Anon page, its mapcount 3424 * goes down to 0. But because we added MIGRATION flage, it's not 3425 * uncharged yet. There are several case but page->mapcount check 3426 * and USED bit check in mem_cgroup_uncharge_page() will do enough 3427 * check. (see prepare_charge() also) 3428 */ 3429 if (PageAnon(used)) 3430 mem_cgroup_uncharge_page(used); 3431 /* 3432 * At migration, we may charge account against cgroup which has no 3433 * tasks. 3434 * So, rmdir()->pre_destroy() can be called while we do this charge. 3435 * In that case, we need to call pre_destroy() again. check it here. 3436 */ 3437 cgroup_release_and_wakeup_rmdir(&memcg->css); 3438 } 3439 3440 #ifdef CONFIG_DEBUG_VM 3441 static struct page_cgroup *lookup_page_cgroup_used(struct page *page) 3442 { 3443 struct page_cgroup *pc; 3444 3445 pc = lookup_page_cgroup(page); 3446 if (likely(pc) && PageCgroupUsed(pc)) 3447 return pc; 3448 return NULL; 3449 } 3450 3451 bool mem_cgroup_bad_page_check(struct page *page) 3452 { 3453 if (mem_cgroup_disabled()) 3454 return false; 3455 3456 return lookup_page_cgroup_used(page) != NULL; 3457 } 3458 3459 void mem_cgroup_print_bad_page(struct page *page) 3460 { 3461 struct page_cgroup *pc; 3462 3463 pc = lookup_page_cgroup_used(page); 3464 if (pc) { 3465 int ret = -1; 3466 char *path; 3467 3468 printk(KERN_ALERT "pc:%p pc->flags:%lx pc->mem_cgroup:%p", 3469 pc, pc->flags, pc->mem_cgroup); 3470 3471 path = kmalloc(PATH_MAX, GFP_KERNEL); 3472 if (path) { 3473 rcu_read_lock(); 3474 ret = cgroup_path(pc->mem_cgroup->css.cgroup, 3475 path, PATH_MAX); 3476 rcu_read_unlock(); 3477 } 3478 3479 printk(KERN_CONT "(%s)\n", 3480 (ret < 0) ? "cannot get the path" : path); 3481 kfree(path); 3482 } 3483 } 3484 #endif 3485 3486 static DEFINE_MUTEX(set_limit_mutex); 3487 3488 static int mem_cgroup_resize_limit(struct mem_cgroup *memcg, 3489 unsigned long long val) 3490 { 3491 int retry_count; 3492 u64 memswlimit, memlimit; 3493 int ret = 0; 3494 int children = mem_cgroup_count_children(memcg); 3495 u64 curusage, oldusage; 3496 int enlarge; 3497 3498 /* 3499 * For keeping hierarchical_reclaim simple, how long we should retry 3500 * is depends on callers. We set our retry-count to be function 3501 * of # of children which we should visit in this loop. 3502 */ 3503 retry_count = MEM_CGROUP_RECLAIM_RETRIES * children; 3504 3505 oldusage = res_counter_read_u64(&memcg->res, RES_USAGE); 3506 3507 enlarge = 0; 3508 while (retry_count) { 3509 if (signal_pending(current)) { 3510 ret = -EINTR; 3511 break; 3512 } 3513 /* 3514 * Rather than hide all in some function, I do this in 3515 * open coded manner. You see what this really does. 3516 * We have to guarantee memcg->res.limit < memcg->memsw.limit. 3517 */ 3518 mutex_lock(&set_limit_mutex); 3519 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT); 3520 if (memswlimit < val) { 3521 ret = -EINVAL; 3522 mutex_unlock(&set_limit_mutex); 3523 break; 3524 } 3525 3526 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT); 3527 if (memlimit < val) 3528 enlarge = 1; 3529 3530 ret = res_counter_set_limit(&memcg->res, val); 3531 if (!ret) { 3532 if (memswlimit == val) 3533 memcg->memsw_is_minimum = true; 3534 else 3535 memcg->memsw_is_minimum = false; 3536 } 3537 mutex_unlock(&set_limit_mutex); 3538 3539 if (!ret) 3540 break; 3541 3542 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL, 3543 MEM_CGROUP_RECLAIM_SHRINK, 3544 NULL); 3545 curusage = res_counter_read_u64(&memcg->res, RES_USAGE); 3546 /* Usage is reduced ? */ 3547 if (curusage >= oldusage) 3548 retry_count--; 3549 else 3550 oldusage = curusage; 3551 } 3552 if (!ret && enlarge) 3553 memcg_oom_recover(memcg); 3554 3555 return ret; 3556 } 3557 3558 static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg, 3559 unsigned long long val) 3560 { 3561 int retry_count; 3562 u64 memlimit, memswlimit, oldusage, curusage; 3563 int children = mem_cgroup_count_children(memcg); 3564 int ret = -EBUSY; 3565 int enlarge = 0; 3566 3567 /* see mem_cgroup_resize_res_limit */ 3568 retry_count = children * MEM_CGROUP_RECLAIM_RETRIES; 3569 oldusage = res_counter_read_u64(&memcg->memsw, RES_USAGE); 3570 while (retry_count) { 3571 if (signal_pending(current)) { 3572 ret = -EINTR; 3573 break; 3574 } 3575 /* 3576 * Rather than hide all in some function, I do this in 3577 * open coded manner. You see what this really does. 3578 * We have to guarantee memcg->res.limit < memcg->memsw.limit. 3579 */ 3580 mutex_lock(&set_limit_mutex); 3581 memlimit = res_counter_read_u64(&memcg->res, RES_LIMIT); 3582 if (memlimit > val) { 3583 ret = -EINVAL; 3584 mutex_unlock(&set_limit_mutex); 3585 break; 3586 } 3587 memswlimit = res_counter_read_u64(&memcg->memsw, RES_LIMIT); 3588 if (memswlimit < val) 3589 enlarge = 1; 3590 ret = res_counter_set_limit(&memcg->memsw, val); 3591 if (!ret) { 3592 if (memlimit == val) 3593 memcg->memsw_is_minimum = true; 3594 else 3595 memcg->memsw_is_minimum = false; 3596 } 3597 mutex_unlock(&set_limit_mutex); 3598 3599 if (!ret) 3600 break; 3601 3602 mem_cgroup_hierarchical_reclaim(memcg, NULL, GFP_KERNEL, 3603 MEM_CGROUP_RECLAIM_NOSWAP | 3604 MEM_CGROUP_RECLAIM_SHRINK, 3605 NULL); 3606 curusage = res_counter_read_u64(&memcg->memsw, RES_USAGE); 3607 /* Usage is reduced ? */ 3608 if (curusage >= oldusage) 3609 retry_count--; 3610 else 3611 oldusage = curusage; 3612 } 3613 if (!ret && enlarge) 3614 memcg_oom_recover(memcg); 3615 return ret; 3616 } 3617 3618 unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order, 3619 gfp_t gfp_mask, 3620 unsigned long *total_scanned) 3621 { 3622 unsigned long nr_reclaimed = 0; 3623 struct mem_cgroup_per_zone *mz, *next_mz = NULL; 3624 unsigned long reclaimed; 3625 int loop = 0; 3626 struct mem_cgroup_tree_per_zone *mctz; 3627 unsigned long long excess; 3628 unsigned long nr_scanned; 3629 3630 if (order > 0) 3631 return 0; 3632 3633 mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone)); 3634 /* 3635 * This loop can run a while, specially if mem_cgroup's continuously 3636 * keep exceeding their soft limit and putting the system under 3637 * pressure 3638 */ 3639 do { 3640 if (next_mz) 3641 mz = next_mz; 3642 else 3643 mz = mem_cgroup_largest_soft_limit_node(mctz); 3644 if (!mz) 3645 break; 3646 3647 nr_scanned = 0; 3648 reclaimed = mem_cgroup_hierarchical_reclaim(mz->mem, zone, 3649 gfp_mask, 3650 MEM_CGROUP_RECLAIM_SOFT, 3651 &nr_scanned); 3652 nr_reclaimed += reclaimed; 3653 *total_scanned += nr_scanned; 3654 spin_lock(&mctz->lock); 3655 3656 /* 3657 * If we failed to reclaim anything from this memory cgroup 3658 * it is time to move on to the next cgroup 3659 */ 3660 next_mz = NULL; 3661 if (!reclaimed) { 3662 do { 3663 /* 3664 * Loop until we find yet another one. 3665 * 3666 * By the time we get the soft_limit lock 3667 * again, someone might have aded the 3668 * group back on the RB tree. Iterate to 3669 * make sure we get a different mem. 3670 * mem_cgroup_largest_soft_limit_node returns 3671 * NULL if no other cgroup is present on 3672 * the tree 3673 */ 3674 next_mz = 3675 __mem_cgroup_largest_soft_limit_node(mctz); 3676 if (next_mz == mz) 3677 css_put(&next_mz->mem->css); 3678 else /* next_mz == NULL or other memcg */ 3679 break; 3680 } while (1); 3681 } 3682 __mem_cgroup_remove_exceeded(mz->mem, mz, mctz); 3683 excess = res_counter_soft_limit_excess(&mz->mem->res); 3684 /* 3685 * One school of thought says that we should not add 3686 * back the node to the tree if reclaim returns 0. 3687 * But our reclaim could return 0, simply because due 3688 * to priority we are exposing a smaller subset of 3689 * memory to reclaim from. Consider this as a longer 3690 * term TODO. 3691 */ 3692 /* If excess == 0, no tree ops */ 3693 __mem_cgroup_insert_exceeded(mz->mem, mz, mctz, excess); 3694 spin_unlock(&mctz->lock); 3695 css_put(&mz->mem->css); 3696 loop++; 3697 /* 3698 * Could not reclaim anything and there are no more 3699 * mem cgroups to try or we seem to be looping without 3700 * reclaiming anything. 3701 */ 3702 if (!nr_reclaimed && 3703 (next_mz == NULL || 3704 loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS)) 3705 break; 3706 } while (!nr_reclaimed); 3707 if (next_mz) 3708 css_put(&next_mz->mem->css); 3709 return nr_reclaimed; 3710 } 3711 3712 /* 3713 * This routine traverse page_cgroup in given list and drop them all. 3714 * *And* this routine doesn't reclaim page itself, just removes page_cgroup. 3715 */ 3716 static int mem_cgroup_force_empty_list(struct mem_cgroup *memcg, 3717 int node, int zid, enum lru_list lru) 3718 { 3719 struct zone *zone; 3720 struct mem_cgroup_per_zone *mz; 3721 struct page_cgroup *pc, *busy; 3722 unsigned long flags, loop; 3723 struct list_head *list; 3724 int ret = 0; 3725 3726 zone = &NODE_DATA(node)->node_zones[zid]; 3727 mz = mem_cgroup_zoneinfo(memcg, node, zid); 3728 list = &mz->lists[lru]; 3729 3730 loop = MEM_CGROUP_ZSTAT(mz, lru); 3731 /* give some margin against EBUSY etc...*/ 3732 loop += 256; 3733 busy = NULL; 3734 while (loop--) { 3735 struct page *page; 3736 3737 ret = 0; 3738 spin_lock_irqsave(&zone->lru_lock, flags); 3739 if (list_empty(list)) { 3740 spin_unlock_irqrestore(&zone->lru_lock, flags); 3741 break; 3742 } 3743 pc = list_entry(list->prev, struct page_cgroup, lru); 3744 if (busy == pc) { 3745 list_move(&pc->lru, list); 3746 busy = NULL; 3747 spin_unlock_irqrestore(&zone->lru_lock, flags); 3748 continue; 3749 } 3750 spin_unlock_irqrestore(&zone->lru_lock, flags); 3751 3752 page = lookup_cgroup_page(pc); 3753 3754 ret = mem_cgroup_move_parent(page, pc, memcg, GFP_KERNEL); 3755 if (ret == -ENOMEM) 3756 break; 3757 3758 if (ret == -EBUSY || ret == -EINVAL) { 3759 /* found lock contention or "pc" is obsolete. */ 3760 busy = pc; 3761 cond_resched(); 3762 } else 3763 busy = NULL; 3764 } 3765 3766 if (!ret && !list_empty(list)) 3767 return -EBUSY; 3768 return ret; 3769 } 3770 3771 /* 3772 * make mem_cgroup's charge to be 0 if there is no task. 3773 * This enables deleting this mem_cgroup. 3774 */ 3775 static int mem_cgroup_force_empty(struct mem_cgroup *memcg, bool free_all) 3776 { 3777 int ret; 3778 int node, zid, shrink; 3779 int nr_retries = MEM_CGROUP_RECLAIM_RETRIES; 3780 struct cgroup *cgrp = memcg->css.cgroup; 3781 3782 css_get(&memcg->css); 3783 3784 shrink = 0; 3785 /* should free all ? */ 3786 if (free_all) 3787 goto try_to_free; 3788 move_account: 3789 do { 3790 ret = -EBUSY; 3791 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children)) 3792 goto out; 3793 ret = -EINTR; 3794 if (signal_pending(current)) 3795 goto out; 3796 /* This is for making all *used* pages to be on LRU. */ 3797 lru_add_drain_all(); 3798 drain_all_stock_sync(memcg); 3799 ret = 0; 3800 mem_cgroup_start_move(memcg); 3801 for_each_node_state(node, N_HIGH_MEMORY) { 3802 for (zid = 0; !ret && zid < MAX_NR_ZONES; zid++) { 3803 enum lru_list l; 3804 for_each_lru(l) { 3805 ret = mem_cgroup_force_empty_list(memcg, 3806 node, zid, l); 3807 if (ret) 3808 break; 3809 } 3810 } 3811 if (ret) 3812 break; 3813 } 3814 mem_cgroup_end_move(memcg); 3815 memcg_oom_recover(memcg); 3816 /* it seems parent cgroup doesn't have enough mem */ 3817 if (ret == -ENOMEM) 3818 goto try_to_free; 3819 cond_resched(); 3820 /* "ret" should also be checked to ensure all lists are empty. */ 3821 } while (memcg->res.usage > 0 || ret); 3822 out: 3823 css_put(&memcg->css); 3824 return ret; 3825 3826 try_to_free: 3827 /* returns EBUSY if there is a task or if we come here twice. */ 3828 if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children) || shrink) { 3829 ret = -EBUSY; 3830 goto out; 3831 } 3832 /* we call try-to-free pages for make this cgroup empty */ 3833 lru_add_drain_all(); 3834 /* try to free all pages in this cgroup */ 3835 shrink = 1; 3836 while (nr_retries && memcg->res.usage > 0) { 3837 int progress; 3838 3839 if (signal_pending(current)) { 3840 ret = -EINTR; 3841 goto out; 3842 } 3843 progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL, 3844 false); 3845 if (!progress) { 3846 nr_retries--; 3847 /* maybe some writeback is necessary */ 3848 congestion_wait(BLK_RW_ASYNC, HZ/10); 3849 } 3850 3851 } 3852 lru_add_drain(); 3853 /* try move_account...there may be some *locked* pages. */ 3854 goto move_account; 3855 } 3856 3857 int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event) 3858 { 3859 return mem_cgroup_force_empty(mem_cgroup_from_cont(cont), true); 3860 } 3861 3862 3863 static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft) 3864 { 3865 return mem_cgroup_from_cont(cont)->use_hierarchy; 3866 } 3867 3868 static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft, 3869 u64 val) 3870 { 3871 int retval = 0; 3872 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont); 3873 struct cgroup *parent = cont->parent; 3874 struct mem_cgroup *parent_memcg = NULL; 3875 3876 if (parent) 3877 parent_memcg = mem_cgroup_from_cont(parent); 3878 3879 cgroup_lock(); 3880 /* 3881 * If parent's use_hierarchy is set, we can't make any modifications 3882 * in the child subtrees. If it is unset, then the change can 3883 * occur, provided the current cgroup has no children. 3884 * 3885 * For the root cgroup, parent_mem is NULL, we allow value to be 3886 * set if there are no children. 3887 */ 3888 if ((!parent_memcg || !parent_memcg->use_hierarchy) && 3889 (val == 1 || val == 0)) { 3890 if (list_empty(&cont->children)) 3891 memcg->use_hierarchy = val; 3892 else 3893 retval = -EBUSY; 3894 } else 3895 retval = -EINVAL; 3896 cgroup_unlock(); 3897 3898 return retval; 3899 } 3900 3901 3902 static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg, 3903 enum mem_cgroup_stat_index idx) 3904 { 3905 struct mem_cgroup *iter; 3906 long val = 0; 3907 3908 /* Per-cpu values can be negative, use a signed accumulator */ 3909 for_each_mem_cgroup_tree(iter, memcg) 3910 val += mem_cgroup_read_stat(iter, idx); 3911 3912 if (val < 0) /* race ? */ 3913 val = 0; 3914 return val; 3915 } 3916 3917 static inline u64 mem_cgroup_usage(struct mem_cgroup *memcg, bool swap) 3918 { 3919 u64 val; 3920 3921 if (!mem_cgroup_is_root(memcg)) { 3922 val = 0; 3923 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_KMEM 3924 if (!memcg->kmem_independent_accounting) 3925 val = res_counter_read_u64(&memcg->kmem, RES_USAGE); 3926 #endif 3927 if (!swap) 3928 val += res_counter_read_u64(&memcg->res, RES_USAGE); 3929 else 3930 val += res_counter_read_u64(&memcg->memsw, RES_USAGE); 3931 3932 return val; 3933 } 3934 3935 val = mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_CACHE); 3936 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_RSS); 3937 3938 if (swap) 3939 val += mem_cgroup_recursive_stat(memcg, MEM_CGROUP_STAT_SWAPOUT); 3940 3941 return val << PAGE_SHIFT; 3942 } 3943 3944 static u64 mem_cgroup_read(struct cgroup *cont, struct cftype *cft) 3945 { 3946 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont); 3947 u64 val; 3948 int type, name; 3949 3950 type = MEMFILE_TYPE(cft->private); 3951 name = MEMFILE_ATTR(cft->private); 3952 switch (type) { 3953 case _MEM: 3954 if (name == RES_USAGE) 3955 val = mem_cgroup_usage(memcg, false); 3956 else 3957 val = res_counter_read_u64(&memcg->res, name); 3958 break; 3959 case _MEMSWAP: 3960 if (name == RES_USAGE) 3961 val = mem_cgroup_usage(memcg, true); 3962 else 3963 val = res_counter_read_u64(&memcg->memsw, name); 3964 break; 3965 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_KMEM 3966 case _KMEM: 3967 val = res_counter_read_u64(&memcg->kmem, name); 3968 break; 3969 #endif 3970 default: 3971 BUG(); 3972 break; 3973 } 3974 return val; 3975 } 3976 /* 3977 * The user of this function is... 3978 * RES_LIMIT. 3979 */ 3980 static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft, 3981 const char *buffer) 3982 { 3983 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont); 3984 int type, name; 3985 unsigned long long val; 3986 int ret; 3987 3988 type = MEMFILE_TYPE(cft->private); 3989 name = MEMFILE_ATTR(cft->private); 3990 switch (name) { 3991 case RES_LIMIT: 3992 if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */ 3993 ret = -EINVAL; 3994 break; 3995 } 3996 /* This function does all necessary parse...reuse it */ 3997 ret = res_counter_memparse_write_strategy(buffer, &val); 3998 if (ret) 3999 break; 4000 if (type == _MEM) 4001 ret = mem_cgroup_resize_limit(memcg, val); 4002 else 4003 ret = mem_cgroup_resize_memsw_limit(memcg, val); 4004 break; 4005 case RES_SOFT_LIMIT: 4006 ret = res_counter_memparse_write_strategy(buffer, &val); 4007 if (ret) 4008 break; 4009 /* 4010 * For memsw, soft limits are hard to implement in terms 4011 * of semantics, for now, we support soft limits for 4012 * control without swap 4013 */ 4014 if (type == _MEM) 4015 ret = res_counter_set_soft_limit(&memcg->res, val); 4016 else 4017 ret = -EINVAL; 4018 break; 4019 default: 4020 ret = -EINVAL; /* should be BUG() ? */ 4021 break; 4022 } 4023 return ret; 4024 } 4025 4026 static void memcg_get_hierarchical_limit(struct mem_cgroup *memcg, 4027 unsigned long long *mem_limit, unsigned long long *memsw_limit) 4028 { 4029 struct cgroup *cgroup; 4030 unsigned long long min_limit, min_memsw_limit, tmp; 4031 4032 min_limit = res_counter_read_u64(&memcg->res, RES_LIMIT); 4033 min_memsw_limit = res_counter_read_u64(&memcg->memsw, RES_LIMIT); 4034 cgroup = memcg->css.cgroup; 4035 if (!memcg->use_hierarchy) 4036 goto out; 4037 4038 while (cgroup->parent) { 4039 cgroup = cgroup->parent; 4040 memcg = mem_cgroup_from_cont(cgroup); 4041 if (!memcg->use_hierarchy) 4042 break; 4043 tmp = res_counter_read_u64(&memcg->res, RES_LIMIT); 4044 min_limit = min(min_limit, tmp); 4045 tmp = res_counter_read_u64(&memcg->memsw, RES_LIMIT); 4046 min_memsw_limit = min(min_memsw_limit, tmp); 4047 } 4048 out: 4049 *mem_limit = min_limit; 4050 *memsw_limit = min_memsw_limit; 4051 return; 4052 } 4053 4054 static int mem_cgroup_reset(struct cgroup *cont, unsigned int event) 4055 { 4056 struct mem_cgroup *memcg; 4057 int type, name; 4058 4059 memcg = mem_cgroup_from_cont(cont); 4060 type = MEMFILE_TYPE(event); 4061 name = MEMFILE_ATTR(event); 4062 switch (name) { 4063 case RES_MAX_USAGE: 4064 if (type == _MEM) 4065 res_counter_reset_max(&memcg->res); 4066 else 4067 res_counter_reset_max(&memcg->memsw); 4068 break; 4069 case RES_FAILCNT: 4070 if (type == _MEM) 4071 res_counter_reset_failcnt(&memcg->res); 4072 else 4073 res_counter_reset_failcnt(&memcg->memsw); 4074 break; 4075 } 4076 4077 return 0; 4078 } 4079 4080 static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp, 4081 struct cftype *cft) 4082 { 4083 return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate; 4084 } 4085 4086 #ifdef CONFIG_MMU 4087 static int mem_cgroup_move_charge_write(struct cgroup *cgrp, 4088 struct cftype *cft, u64 val) 4089 { 4090 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp); 4091 4092 if (val >= (1 << NR_MOVE_TYPE)) 4093 return -EINVAL; 4094 /* 4095 * We check this value several times in both in can_attach() and 4096 * attach(), so we need cgroup lock to prevent this value from being 4097 * inconsistent. 4098 */ 4099 cgroup_lock(); 4100 memcg->move_charge_at_immigrate = val; 4101 cgroup_unlock(); 4102 4103 return 0; 4104 } 4105 #else 4106 static int mem_cgroup_move_charge_write(struct cgroup *cgrp, 4107 struct cftype *cft, u64 val) 4108 { 4109 return -ENOSYS; 4110 } 4111 #endif 4112 4113 4114 /* For read statistics */ 4115 enum { 4116 MCS_CACHE, 4117 MCS_RSS, 4118 MCS_FILE_MAPPED, 4119 MCS_PGPGIN, 4120 MCS_PGPGOUT, 4121 MCS_SWAP, 4122 MCS_PGFAULT, 4123 MCS_PGMAJFAULT, 4124 MCS_INACTIVE_ANON, 4125 MCS_ACTIVE_ANON, 4126 MCS_INACTIVE_FILE, 4127 MCS_ACTIVE_FILE, 4128 MCS_UNEVICTABLE, 4129 NR_MCS_STAT, 4130 }; 4131 4132 struct mcs_total_stat { 4133 s64 stat[NR_MCS_STAT]; 4134 }; 4135 4136 struct { 4137 char *local_name; 4138 char *total_name; 4139 } memcg_stat_strings[NR_MCS_STAT] = { 4140 {"cache", "total_cache"}, 4141 {"rss", "total_rss"}, 4142 {"mapped_file", "total_mapped_file"}, 4143 {"pgpgin", "total_pgpgin"}, 4144 {"pgpgout", "total_pgpgout"}, 4145 {"swap", "total_swap"}, 4146 {"pgfault", "total_pgfault"}, 4147 {"pgmajfault", "total_pgmajfault"}, 4148 {"inactive_anon", "total_inactive_anon"}, 4149 {"active_anon", "total_active_anon"}, 4150 {"inactive_file", "total_inactive_file"}, 4151 {"active_file", "total_active_file"}, 4152 {"unevictable", "total_unevictable"} 4153 }; 4154 4155 4156 static void 4157 mem_cgroup_get_local_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s) 4158 { 4159 s64 val; 4160 4161 /* per cpu stat */ 4162 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_CACHE); 4163 s->stat[MCS_CACHE] += val * PAGE_SIZE; 4164 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_RSS); 4165 s->stat[MCS_RSS] += val * PAGE_SIZE; 4166 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_FILE_MAPPED); 4167 s->stat[MCS_FILE_MAPPED] += val * PAGE_SIZE; 4168 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGIN); 4169 s->stat[MCS_PGPGIN] += val; 4170 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGPGOUT); 4171 s->stat[MCS_PGPGOUT] += val; 4172 if (do_swap_account) { 4173 val = mem_cgroup_read_stat(memcg, MEM_CGROUP_STAT_SWAPOUT); 4174 s->stat[MCS_SWAP] += val * PAGE_SIZE; 4175 } 4176 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGFAULT); 4177 s->stat[MCS_PGFAULT] += val; 4178 val = mem_cgroup_read_events(memcg, MEM_CGROUP_EVENTS_PGMAJFAULT); 4179 s->stat[MCS_PGMAJFAULT] += val; 4180 4181 /* per zone stat */ 4182 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_ANON)); 4183 s->stat[MCS_INACTIVE_ANON] += val * PAGE_SIZE; 4184 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_ANON)); 4185 s->stat[MCS_ACTIVE_ANON] += val * PAGE_SIZE; 4186 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_INACTIVE_FILE)); 4187 s->stat[MCS_INACTIVE_FILE] += val * PAGE_SIZE; 4188 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_ACTIVE_FILE)); 4189 s->stat[MCS_ACTIVE_FILE] += val * PAGE_SIZE; 4190 val = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE)); 4191 s->stat[MCS_UNEVICTABLE] += val * PAGE_SIZE; 4192 } 4193 4194 static void 4195 mem_cgroup_get_total_stat(struct mem_cgroup *memcg, struct mcs_total_stat *s) 4196 { 4197 struct mem_cgroup *iter; 4198 4199 for_each_mem_cgroup_tree(iter, memcg) 4200 mem_cgroup_get_local_stat(iter, s); 4201 } 4202 4203 #ifdef CONFIG_NUMA 4204 static int mem_control_numa_stat_show(struct seq_file *m, void *arg) 4205 { 4206 int nid; 4207 unsigned long total_nr, file_nr, anon_nr, unevictable_nr; 4208 unsigned long node_nr; 4209 struct cgroup *cont = m->private; 4210 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont); 4211 4212 total_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL); 4213 seq_printf(m, "total=%lu", total_nr); 4214 for_each_node_state(nid, N_HIGH_MEMORY) { 4215 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, LRU_ALL); 4216 seq_printf(m, " N%d=%lu", nid, node_nr); 4217 } 4218 seq_putc(m, '\n'); 4219 4220 file_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_FILE); 4221 seq_printf(m, "file=%lu", file_nr); 4222 for_each_node_state(nid, N_HIGH_MEMORY) { 4223 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, 4224 LRU_ALL_FILE); 4225 seq_printf(m, " N%d=%lu", nid, node_nr); 4226 } 4227 seq_putc(m, '\n'); 4228 4229 anon_nr = mem_cgroup_nr_lru_pages(mem_cont, LRU_ALL_ANON); 4230 seq_printf(m, "anon=%lu", anon_nr); 4231 for_each_node_state(nid, N_HIGH_MEMORY) { 4232 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, 4233 LRU_ALL_ANON); 4234 seq_printf(m, " N%d=%lu", nid, node_nr); 4235 } 4236 seq_putc(m, '\n'); 4237 4238 unevictable_nr = mem_cgroup_nr_lru_pages(mem_cont, BIT(LRU_UNEVICTABLE)); 4239 seq_printf(m, "unevictable=%lu", unevictable_nr); 4240 for_each_node_state(nid, N_HIGH_MEMORY) { 4241 node_nr = mem_cgroup_node_nr_lru_pages(mem_cont, nid, 4242 BIT(LRU_UNEVICTABLE)); 4243 seq_printf(m, " N%d=%lu", nid, node_nr); 4244 } 4245 seq_putc(m, '\n'); 4246 return 0; 4247 } 4248 #endif /* CONFIG_NUMA */ 4249 4250 static int mem_control_stat_show(struct cgroup *cont, struct cftype *cft, 4251 struct cgroup_map_cb *cb) 4252 { 4253 struct mem_cgroup *mem_cont = mem_cgroup_from_cont(cont); 4254 struct mcs_total_stat mystat; 4255 int i; 4256 4257 memset(&mystat, 0, sizeof(mystat)); 4258 mem_cgroup_get_local_stat(mem_cont, &mystat); 4259 4260 4261 for (i = 0; i < NR_MCS_STAT; i++) { 4262 if (i == MCS_SWAP && !do_swap_account) 4263 continue; 4264 cb->fill(cb, memcg_stat_strings[i].local_name, mystat.stat[i]); 4265 } 4266 4267 /* Hierarchical information */ 4268 { 4269 unsigned long long limit, memsw_limit; 4270 memcg_get_hierarchical_limit(mem_cont, &limit, &memsw_limit); 4271 cb->fill(cb, "hierarchical_memory_limit", limit); 4272 if (do_swap_account) 4273 cb->fill(cb, "hierarchical_memsw_limit", memsw_limit); 4274 } 4275 4276 memset(&mystat, 0, sizeof(mystat)); 4277 mem_cgroup_get_total_stat(mem_cont, &mystat); 4278 for (i = 0; i < NR_MCS_STAT; i++) { 4279 if (i == MCS_SWAP && !do_swap_account) 4280 continue; 4281 cb->fill(cb, memcg_stat_strings[i].total_name, mystat.stat[i]); 4282 } 4283 4284 #ifdef CONFIG_DEBUG_VM 4285 { 4286 int nid, zid; 4287 struct mem_cgroup_per_zone *mz; 4288 unsigned long recent_rotated[2] = {0, 0}; 4289 unsigned long recent_scanned[2] = {0, 0}; 4290 4291 for_each_online_node(nid) 4292 for (zid = 0; zid < MAX_NR_ZONES; zid++) { 4293 mz = mem_cgroup_zoneinfo(mem_cont, nid, zid); 4294 4295 recent_rotated[0] += 4296 mz->reclaim_stat.recent_rotated[0]; 4297 recent_rotated[1] += 4298 mz->reclaim_stat.recent_rotated[1]; 4299 recent_scanned[0] += 4300 mz->reclaim_stat.recent_scanned[0]; 4301 recent_scanned[1] += 4302 mz->reclaim_stat.recent_scanned[1]; 4303 } 4304 cb->fill(cb, "recent_rotated_anon", recent_rotated[0]); 4305 cb->fill(cb, "recent_rotated_file", recent_rotated[1]); 4306 cb->fill(cb, "recent_scanned_anon", recent_scanned[0]); 4307 cb->fill(cb, "recent_scanned_file", recent_scanned[1]); 4308 } 4309 #endif 4310 4311 return 0; 4312 } 4313 4314 static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft) 4315 { 4316 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp); 4317 4318 return mem_cgroup_swappiness(memcg); 4319 } 4320 4321 static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft, 4322 u64 val) 4323 { 4324 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp); 4325 struct mem_cgroup *parent; 4326 4327 if (val > 100) 4328 return -EINVAL; 4329 4330 if (cgrp->parent == NULL) 4331 return -EINVAL; 4332 4333 parent = mem_cgroup_from_cont(cgrp->parent); 4334 4335 cgroup_lock(); 4336 4337 /* If under hierarchy, only empty-root can set this value */ 4338 if ((parent->use_hierarchy) || 4339 (memcg->use_hierarchy && !list_empty(&cgrp->children))) { 4340 cgroup_unlock(); 4341 return -EINVAL; 4342 } 4343 4344 memcg->swappiness = val; 4345 4346 cgroup_unlock(); 4347 4348 return 0; 4349 } 4350 4351 static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap) 4352 { 4353 struct mem_cgroup_threshold_ary *t; 4354 u64 usage; 4355 int i; 4356 4357 rcu_read_lock(); 4358 if (!swap) 4359 t = rcu_dereference(memcg->thresholds.primary); 4360 else 4361 t = rcu_dereference(memcg->memsw_thresholds.primary); 4362 4363 if (!t) 4364 goto unlock; 4365 4366 usage = mem_cgroup_usage(memcg, swap); 4367 4368 /* 4369 * current_threshold points to threshold just below usage. 4370 * If it's not true, a threshold was crossed after last 4371 * call of __mem_cgroup_threshold(). 4372 */ 4373 i = t->current_threshold; 4374 4375 /* 4376 * Iterate backward over array of thresholds starting from 4377 * current_threshold and check if a threshold is crossed. 4378 * If none of thresholds below usage is crossed, we read 4379 * only one element of the array here. 4380 */ 4381 for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--) 4382 eventfd_signal(t->entries[i].eventfd, 1); 4383 4384 /* i = current_threshold + 1 */ 4385 i++; 4386 4387 /* 4388 * Iterate forward over array of thresholds starting from 4389 * current_threshold+1 and check if a threshold is crossed. 4390 * If none of thresholds above usage is crossed, we read 4391 * only one element of the array here. 4392 */ 4393 for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++) 4394 eventfd_signal(t->entries[i].eventfd, 1); 4395 4396 /* Update current_threshold */ 4397 t->current_threshold = i - 1; 4398 unlock: 4399 rcu_read_unlock(); 4400 } 4401 4402 static void mem_cgroup_threshold(struct mem_cgroup *memcg) 4403 { 4404 while (memcg) { 4405 __mem_cgroup_threshold(memcg, false); 4406 if (do_swap_account) 4407 __mem_cgroup_threshold(memcg, true); 4408 4409 memcg = parent_mem_cgroup(memcg); 4410 } 4411 } 4412 4413 static int compare_thresholds(const void *a, const void *b) 4414 { 4415 const struct mem_cgroup_threshold *_a = a; 4416 const struct mem_cgroup_threshold *_b = b; 4417 4418 return _a->threshold - _b->threshold; 4419 } 4420 4421 static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg) 4422 { 4423 struct mem_cgroup_eventfd_list *ev; 4424 4425 list_for_each_entry(ev, &memcg->oom_notify, list) 4426 eventfd_signal(ev->eventfd, 1); 4427 return 0; 4428 } 4429 4430 static void mem_cgroup_oom_notify(struct mem_cgroup *memcg) 4431 { 4432 struct mem_cgroup *iter; 4433 4434 for_each_mem_cgroup_tree(iter, memcg) 4435 mem_cgroup_oom_notify_cb(iter); 4436 } 4437 4438 static int mem_cgroup_usage_register_event(struct cgroup *cgrp, 4439 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args) 4440 { 4441 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp); 4442 struct mem_cgroup_thresholds *thresholds; 4443 struct mem_cgroup_threshold_ary *new; 4444 int type = MEMFILE_TYPE(cft->private); 4445 u64 threshold, usage; 4446 int i, size, ret; 4447 4448 ret = res_counter_memparse_write_strategy(args, &threshold); 4449 if (ret) 4450 return ret; 4451 4452 mutex_lock(&memcg->thresholds_lock); 4453 4454 if (type == _MEM) 4455 thresholds = &memcg->thresholds; 4456 else if (type == _MEMSWAP) 4457 thresholds = &memcg->memsw_thresholds; 4458 else 4459 BUG(); 4460 4461 usage = mem_cgroup_usage(memcg, type == _MEMSWAP); 4462 4463 /* Check if a threshold crossed before adding a new one */ 4464 if (thresholds->primary) 4465 __mem_cgroup_threshold(memcg, type == _MEMSWAP); 4466 4467 size = thresholds->primary ? thresholds->primary->size + 1 : 1; 4468 4469 /* Allocate memory for new array of thresholds */ 4470 new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold), 4471 GFP_KERNEL); 4472 if (!new) { 4473 ret = -ENOMEM; 4474 goto unlock; 4475 } 4476 new->size = size; 4477 4478 /* Copy thresholds (if any) to new array */ 4479 if (thresholds->primary) { 4480 memcpy(new->entries, thresholds->primary->entries, (size - 1) * 4481 sizeof(struct mem_cgroup_threshold)); 4482 } 4483 4484 /* Add new threshold */ 4485 new->entries[size - 1].eventfd = eventfd; 4486 new->entries[size - 1].threshold = threshold; 4487 4488 /* Sort thresholds. Registering of new threshold isn't time-critical */ 4489 sort(new->entries, size, sizeof(struct mem_cgroup_threshold), 4490 compare_thresholds, NULL); 4491 4492 /* Find current threshold */ 4493 new->current_threshold = -1; 4494 for (i = 0; i < size; i++) { 4495 if (new->entries[i].threshold < usage) { 4496 /* 4497 * new->current_threshold will not be used until 4498 * rcu_assign_pointer(), so it's safe to increment 4499 * it here. 4500 */ 4501 ++new->current_threshold; 4502 } 4503 } 4504 4505 /* Free old spare buffer and save old primary buffer as spare */ 4506 kfree(thresholds->spare); 4507 thresholds->spare = thresholds->primary; 4508 4509 rcu_assign_pointer(thresholds->primary, new); 4510 4511 /* To be sure that nobody uses thresholds */ 4512 synchronize_rcu(); 4513 4514 unlock: 4515 mutex_unlock(&memcg->thresholds_lock); 4516 4517 return ret; 4518 } 4519 4520 static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp, 4521 struct cftype *cft, struct eventfd_ctx *eventfd) 4522 { 4523 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp); 4524 struct mem_cgroup_thresholds *thresholds; 4525 struct mem_cgroup_threshold_ary *new; 4526 int type = MEMFILE_TYPE(cft->private); 4527 u64 usage; 4528 int i, j, size; 4529 4530 mutex_lock(&memcg->thresholds_lock); 4531 if (type == _MEM) 4532 thresholds = &memcg->thresholds; 4533 else if (type == _MEMSWAP) 4534 thresholds = &memcg->memsw_thresholds; 4535 else 4536 BUG(); 4537 4538 /* 4539 * Something went wrong if we trying to unregister a threshold 4540 * if we don't have thresholds 4541 */ 4542 BUG_ON(!thresholds); 4543 4544 usage = mem_cgroup_usage(memcg, type == _MEMSWAP); 4545 4546 /* Check if a threshold crossed before removing */ 4547 __mem_cgroup_threshold(memcg, type == _MEMSWAP); 4548 4549 /* Calculate new number of threshold */ 4550 size = 0; 4551 for (i = 0; i < thresholds->primary->size; i++) { 4552 if (thresholds->primary->entries[i].eventfd != eventfd) 4553 size++; 4554 } 4555 4556 new = thresholds->spare; 4557 4558 /* Set thresholds array to NULL if we don't have thresholds */ 4559 if (!size) { 4560 kfree(new); 4561 new = NULL; 4562 goto swap_buffers; 4563 } 4564 4565 new->size = size; 4566 4567 /* Copy thresholds and find current threshold */ 4568 new->current_threshold = -1; 4569 for (i = 0, j = 0; i < thresholds->primary->size; i++) { 4570 if (thresholds->primary->entries[i].eventfd == eventfd) 4571 continue; 4572 4573 new->entries[j] = thresholds->primary->entries[i]; 4574 if (new->entries[j].threshold < usage) { 4575 /* 4576 * new->current_threshold will not be used 4577 * until rcu_assign_pointer(), so it's safe to increment 4578 * it here. 4579 */ 4580 ++new->current_threshold; 4581 } 4582 j++; 4583 } 4584 4585 swap_buffers: 4586 /* Swap primary and spare array */ 4587 thresholds->spare = thresholds->primary; 4588 rcu_assign_pointer(thresholds->primary, new); 4589 4590 /* To be sure that nobody uses thresholds */ 4591 synchronize_rcu(); 4592 4593 mutex_unlock(&memcg->thresholds_lock); 4594 } 4595 4596 static int mem_cgroup_oom_register_event(struct cgroup *cgrp, 4597 struct cftype *cft, struct eventfd_ctx *eventfd, const char *args) 4598 { 4599 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp); 4600 struct mem_cgroup_eventfd_list *event; 4601 int type = MEMFILE_TYPE(cft->private); 4602 4603 BUG_ON(type != _OOM_TYPE); 4604 event = kmalloc(sizeof(*event), GFP_KERNEL); 4605 if (!event) 4606 return -ENOMEM; 4607 4608 spin_lock(&memcg_oom_lock); 4609 4610 event->eventfd = eventfd; 4611 list_add(&event->list, &memcg->oom_notify); 4612 4613 /* already in OOM ? */ 4614 if (atomic_read(&memcg->under_oom)) 4615 eventfd_signal(eventfd, 1); 4616 spin_unlock(&memcg_oom_lock); 4617 4618 return 0; 4619 } 4620 4621 static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp, 4622 struct cftype *cft, struct eventfd_ctx *eventfd) 4623 { 4624 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp); 4625 struct mem_cgroup_eventfd_list *ev, *tmp; 4626 int type = MEMFILE_TYPE(cft->private); 4627 4628 BUG_ON(type != _OOM_TYPE); 4629 4630 spin_lock(&memcg_oom_lock); 4631 4632 list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) { 4633 if (ev->eventfd == eventfd) { 4634 list_del(&ev->list); 4635 kfree(ev); 4636 } 4637 } 4638 4639 spin_unlock(&memcg_oom_lock); 4640 } 4641 4642 static int mem_cgroup_oom_control_read(struct cgroup *cgrp, 4643 struct cftype *cft, struct cgroup_map_cb *cb) 4644 { 4645 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp); 4646 4647 cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable); 4648 4649 if (atomic_read(&memcg->under_oom)) 4650 cb->fill(cb, "under_oom", 1); 4651 else 4652 cb->fill(cb, "under_oom", 0); 4653 return 0; 4654 } 4655 4656 static int mem_cgroup_oom_control_write(struct cgroup *cgrp, 4657 struct cftype *cft, u64 val) 4658 { 4659 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp); 4660 struct mem_cgroup *parent; 4661 4662 /* cannot set to root cgroup and only 0 and 1 are allowed */ 4663 if (!cgrp->parent || !((val == 0) || (val == 1))) 4664 return -EINVAL; 4665 4666 parent = mem_cgroup_from_cont(cgrp->parent); 4667 4668 cgroup_lock(); 4669 /* oom-kill-disable is a flag for subhierarchy. */ 4670 if ((parent->use_hierarchy) || 4671 (memcg->use_hierarchy && !list_empty(&cgrp->children))) { 4672 cgroup_unlock(); 4673 return -EINVAL; 4674 } 4675 memcg->oom_kill_disable = val; 4676 if (!val) 4677 memcg_oom_recover(memcg); 4678 cgroup_unlock(); 4679 return 0; 4680 } 4681 4682 #ifdef CONFIG_NUMA 4683 static const struct file_operations mem_control_numa_stat_file_operations = { 4684 .read = seq_read, 4685 .llseek = seq_lseek, 4686 .release = single_release, 4687 }; 4688 4689 static int mem_control_numa_stat_open(struct inode *unused, struct file *file) 4690 { 4691 struct cgroup *cont = file->f_dentry->d_parent->d_fsdata; 4692 4693 file->f_op = &mem_control_numa_stat_file_operations; 4694 return single_open(file, mem_control_numa_stat_show, cont); 4695 } 4696 #endif /* CONFIG_NUMA */ 4697 4698 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_KMEM 4699 static u64 kmem_limit_independent_read(struct cgroup *cgroup, struct cftype *cft) 4700 { 4701 return mem_cgroup_from_cont(cgroup)->kmem_independent_accounting; 4702 } 4703 4704 static int kmem_limit_independent_write(struct cgroup *cgroup, struct cftype *cft, 4705 u64 val) 4706 { 4707 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup); 4708 struct mem_cgroup *parent = parent_mem_cgroup(memcg); 4709 4710 val = !!val; 4711 4712 /* 4713 * This follows the same hierarchy restrictions than 4714 * mem_cgroup_hierarchy_write() 4715 */ 4716 if (!parent || !parent->use_hierarchy) { 4717 if (list_empty(&cgroup->children)) 4718 memcg->kmem_independent_accounting = val; 4719 else 4720 return -EBUSY; 4721 } 4722 else 4723 return -EINVAL; 4724 4725 return 0; 4726 } 4727 static struct cftype kmem_cgroup_files[] = { 4728 { 4729 .name = "independent_kmem_limit", 4730 .read_u64 = kmem_limit_independent_read, 4731 .write_u64 = kmem_limit_independent_write, 4732 }, 4733 { 4734 .name = "kmem.usage_in_bytes", 4735 .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE), 4736 .read_u64 = mem_cgroup_read, 4737 }, 4738 { 4739 .name = "kmem.limit_in_bytes", 4740 .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT), 4741 .read_u64 = mem_cgroup_read, 4742 }, 4743 }; 4744 4745 static int register_kmem_files(struct cgroup *cont, struct cgroup_subsys *ss) 4746 { 4747 int ret = 0; 4748 4749 ret = cgroup_add_files(cont, ss, kmem_cgroup_files, 4750 ARRAY_SIZE(kmem_cgroup_files)); 4751 4752 /* 4753 * Part of this would be better living in a separate allocation 4754 * function, leaving us with just the cgroup tree population work. 4755 * We, however, depend on state such as network's proto_list that 4756 * is only initialized after cgroup creation. I found the less 4757 * cumbersome way to deal with it to defer it all to populate time 4758 */ 4759 if (!ret) 4760 ret = mem_cgroup_sockets_init(cont, ss); 4761 return ret; 4762 }; 4763 4764 static void kmem_cgroup_destroy(struct cgroup_subsys *ss, 4765 struct cgroup *cont) 4766 { 4767 mem_cgroup_sockets_destroy(cont, ss); 4768 } 4769 #else 4770 static int register_kmem_files(struct cgroup *cont, struct cgroup_subsys *ss) 4771 { 4772 return 0; 4773 } 4774 4775 static void kmem_cgroup_destroy(struct cgroup_subsys *ss, 4776 struct cgroup *cont) 4777 { 4778 } 4779 #endif 4780 4781 static struct cftype mem_cgroup_files[] = { 4782 { 4783 .name = "usage_in_bytes", 4784 .private = MEMFILE_PRIVATE(_MEM, RES_USAGE), 4785 .read_u64 = mem_cgroup_read, 4786 .register_event = mem_cgroup_usage_register_event, 4787 .unregister_event = mem_cgroup_usage_unregister_event, 4788 }, 4789 { 4790 .name = "max_usage_in_bytes", 4791 .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE), 4792 .trigger = mem_cgroup_reset, 4793 .read_u64 = mem_cgroup_read, 4794 }, 4795 { 4796 .name = "limit_in_bytes", 4797 .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT), 4798 .write_string = mem_cgroup_write, 4799 .read_u64 = mem_cgroup_read, 4800 }, 4801 { 4802 .name = "soft_limit_in_bytes", 4803 .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT), 4804 .write_string = mem_cgroup_write, 4805 .read_u64 = mem_cgroup_read, 4806 }, 4807 { 4808 .name = "failcnt", 4809 .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT), 4810 .trigger = mem_cgroup_reset, 4811 .read_u64 = mem_cgroup_read, 4812 }, 4813 { 4814 .name = "stat", 4815 .read_map = mem_control_stat_show, 4816 }, 4817 { 4818 .name = "force_empty", 4819 .trigger = mem_cgroup_force_empty_write, 4820 }, 4821 { 4822 .name = "use_hierarchy", 4823 .write_u64 = mem_cgroup_hierarchy_write, 4824 .read_u64 = mem_cgroup_hierarchy_read, 4825 }, 4826 { 4827 .name = "swappiness", 4828 .read_u64 = mem_cgroup_swappiness_read, 4829 .write_u64 = mem_cgroup_swappiness_write, 4830 }, 4831 { 4832 .name = "move_charge_at_immigrate", 4833 .read_u64 = mem_cgroup_move_charge_read, 4834 .write_u64 = mem_cgroup_move_charge_write, 4835 }, 4836 { 4837 .name = "oom_control", 4838 .read_map = mem_cgroup_oom_control_read, 4839 .write_u64 = mem_cgroup_oom_control_write, 4840 .register_event = mem_cgroup_oom_register_event, 4841 .unregister_event = mem_cgroup_oom_unregister_event, 4842 .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL), 4843 }, 4844 #ifdef CONFIG_NUMA 4845 { 4846 .name = "numa_stat", 4847 .open = mem_control_numa_stat_open, 4848 .mode = S_IRUGO, 4849 }, 4850 #endif 4851 }; 4852 4853 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP 4854 static struct cftype memsw_cgroup_files[] = { 4855 { 4856 .name = "memsw.usage_in_bytes", 4857 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE), 4858 .read_u64 = mem_cgroup_read, 4859 .register_event = mem_cgroup_usage_register_event, 4860 .unregister_event = mem_cgroup_usage_unregister_event, 4861 }, 4862 { 4863 .name = "memsw.max_usage_in_bytes", 4864 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE), 4865 .trigger = mem_cgroup_reset, 4866 .read_u64 = mem_cgroup_read, 4867 }, 4868 { 4869 .name = "memsw.limit_in_bytes", 4870 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT), 4871 .write_string = mem_cgroup_write, 4872 .read_u64 = mem_cgroup_read, 4873 }, 4874 { 4875 .name = "memsw.failcnt", 4876 .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT), 4877 .trigger = mem_cgroup_reset, 4878 .read_u64 = mem_cgroup_read, 4879 }, 4880 }; 4881 4882 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss) 4883 { 4884 if (!do_swap_account) 4885 return 0; 4886 return cgroup_add_files(cont, ss, memsw_cgroup_files, 4887 ARRAY_SIZE(memsw_cgroup_files)); 4888 }; 4889 #else 4890 static int register_memsw_files(struct cgroup *cont, struct cgroup_subsys *ss) 4891 { 4892 return 0; 4893 } 4894 #endif 4895 4896 static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node) 4897 { 4898 struct mem_cgroup_per_node *pn; 4899 struct mem_cgroup_per_zone *mz; 4900 enum lru_list l; 4901 int zone, tmp = node; 4902 /* 4903 * This routine is called against possible nodes. 4904 * But it's BUG to call kmalloc() against offline node. 4905 * 4906 * TODO: this routine can waste much memory for nodes which will 4907 * never be onlined. It's better to use memory hotplug callback 4908 * function. 4909 */ 4910 if (!node_state(node, N_NORMAL_MEMORY)) 4911 tmp = -1; 4912 pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp); 4913 if (!pn) 4914 return 1; 4915 4916 for (zone = 0; zone < MAX_NR_ZONES; zone++) { 4917 mz = &pn->zoneinfo[zone]; 4918 for_each_lru(l) 4919 INIT_LIST_HEAD(&mz->lists[l]); 4920 mz->usage_in_excess = 0; 4921 mz->on_tree = false; 4922 mz->mem = memcg; 4923 } 4924 memcg->info.nodeinfo[node] = pn; 4925 return 0; 4926 } 4927 4928 static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node) 4929 { 4930 kfree(memcg->info.nodeinfo[node]); 4931 } 4932 4933 static struct mem_cgroup *mem_cgroup_alloc(void) 4934 { 4935 struct mem_cgroup *mem; 4936 int size = sizeof(struct mem_cgroup); 4937 4938 /* Can be very big if MAX_NUMNODES is very big */ 4939 if (size < PAGE_SIZE) 4940 mem = kzalloc(size, GFP_KERNEL); 4941 else 4942 mem = vzalloc(size); 4943 4944 if (!mem) 4945 return NULL; 4946 4947 mem->stat = alloc_percpu(struct mem_cgroup_stat_cpu); 4948 if (!mem->stat) 4949 goto out_free; 4950 spin_lock_init(&mem->pcp_counter_lock); 4951 return mem; 4952 4953 out_free: 4954 if (size < PAGE_SIZE) 4955 kfree(mem); 4956 else 4957 vfree(mem); 4958 return NULL; 4959 } 4960 4961 /* 4962 * At destroying mem_cgroup, references from swap_cgroup can remain. 4963 * (scanning all at force_empty is too costly...) 4964 * 4965 * Instead of clearing all references at force_empty, we remember 4966 * the number of reference from swap_cgroup and free mem_cgroup when 4967 * it goes down to 0. 4968 * 4969 * Removal of cgroup itself succeeds regardless of refs from swap. 4970 */ 4971 4972 static void __mem_cgroup_free(struct mem_cgroup *memcg) 4973 { 4974 int node; 4975 4976 mem_cgroup_remove_from_trees(memcg); 4977 free_css_id(&mem_cgroup_subsys, &memcg->css); 4978 4979 for_each_node_state(node, N_POSSIBLE) 4980 free_mem_cgroup_per_zone_info(memcg, node); 4981 4982 free_percpu(memcg->stat); 4983 if (sizeof(struct mem_cgroup) < PAGE_SIZE) 4984 kfree(memcg); 4985 else 4986 vfree(memcg); 4987 } 4988 4989 static void mem_cgroup_get(struct mem_cgroup *memcg) 4990 { 4991 atomic_inc(&memcg->refcnt); 4992 } 4993 4994 static void __mem_cgroup_put(struct mem_cgroup *memcg, int count) 4995 { 4996 if (atomic_sub_and_test(count, &memcg->refcnt)) { 4997 struct mem_cgroup *parent = parent_mem_cgroup(memcg); 4998 __mem_cgroup_free(memcg); 4999 if (parent) 5000 mem_cgroup_put(parent); 5001 } 5002 } 5003 5004 static void mem_cgroup_put(struct mem_cgroup *memcg) 5005 { 5006 __mem_cgroup_put(memcg, 1); 5007 } 5008 5009 /* 5010 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled. 5011 */ 5012 struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg) 5013 { 5014 if (!memcg->res.parent) 5015 return NULL; 5016 return mem_cgroup_from_res_counter(memcg->res.parent, res); 5017 } 5018 EXPORT_SYMBOL(parent_mem_cgroup); 5019 5020 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP 5021 static void __init enable_swap_cgroup(void) 5022 { 5023 if (!mem_cgroup_disabled() && really_do_swap_account) 5024 do_swap_account = 1; 5025 } 5026 #else 5027 static void __init enable_swap_cgroup(void) 5028 { 5029 } 5030 #endif 5031 5032 static int mem_cgroup_soft_limit_tree_init(void) 5033 { 5034 struct mem_cgroup_tree_per_node *rtpn; 5035 struct mem_cgroup_tree_per_zone *rtpz; 5036 int tmp, node, zone; 5037 5038 for_each_node_state(node, N_POSSIBLE) { 5039 tmp = node; 5040 if (!node_state(node, N_NORMAL_MEMORY)) 5041 tmp = -1; 5042 rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp); 5043 if (!rtpn) 5044 return 1; 5045 5046 soft_limit_tree.rb_tree_per_node[node] = rtpn; 5047 5048 for (zone = 0; zone < MAX_NR_ZONES; zone++) { 5049 rtpz = &rtpn->rb_tree_per_zone[zone]; 5050 rtpz->rb_root = RB_ROOT; 5051 spin_lock_init(&rtpz->lock); 5052 } 5053 } 5054 return 0; 5055 } 5056 5057 static struct cgroup_subsys_state * __ref 5058 mem_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cont) 5059 { 5060 struct mem_cgroup *memcg, *parent; 5061 long error = -ENOMEM; 5062 int node; 5063 5064 memcg = mem_cgroup_alloc(); 5065 if (!memcg) 5066 return ERR_PTR(error); 5067 5068 for_each_node_state(node, N_POSSIBLE) 5069 if (alloc_mem_cgroup_per_zone_info(memcg, node)) 5070 goto free_out; 5071 5072 /* root ? */ 5073 if (cont->parent == NULL) { 5074 int cpu; 5075 enable_swap_cgroup(); 5076 parent = NULL; 5077 root_mem_cgroup = memcg; 5078 if (mem_cgroup_soft_limit_tree_init()) 5079 goto free_out; 5080 for_each_possible_cpu(cpu) { 5081 struct memcg_stock_pcp *stock = 5082 &per_cpu(memcg_stock, cpu); 5083 INIT_WORK(&stock->work, drain_local_stock); 5084 } 5085 hotcpu_notifier(memcg_cpu_hotplug_callback, 0); 5086 } else { 5087 parent = mem_cgroup_from_cont(cont->parent); 5088 memcg->use_hierarchy = parent->use_hierarchy; 5089 memcg->oom_kill_disable = parent->oom_kill_disable; 5090 } 5091 5092 if (parent && parent->use_hierarchy) { 5093 res_counter_init(&memcg->res, &parent->res); 5094 res_counter_init(&memcg->memsw, &parent->memsw); 5095 res_counter_init(&memcg->kmem, &parent->kmem); 5096 /* 5097 * We increment refcnt of the parent to ensure that we can 5098 * safely access it on res_counter_charge/uncharge. 5099 * This refcnt will be decremented when freeing this 5100 * mem_cgroup(see mem_cgroup_put). 5101 */ 5102 mem_cgroup_get(parent); 5103 } else { 5104 res_counter_init(&memcg->res, NULL); 5105 res_counter_init(&memcg->memsw, NULL); 5106 res_counter_init(&memcg->kmem, NULL); 5107 } 5108 memcg->last_scanned_child = 0; 5109 memcg->last_scanned_node = MAX_NUMNODES; 5110 INIT_LIST_HEAD(&memcg->oom_notify); 5111 5112 if (parent) 5113 memcg->swappiness = mem_cgroup_swappiness(parent); 5114 atomic_set(&memcg->refcnt, 1); 5115 memcg->move_charge_at_immigrate = 0; 5116 mutex_init(&memcg->thresholds_lock); 5117 return &memcg->css; 5118 free_out: 5119 __mem_cgroup_free(memcg); 5120 root_mem_cgroup = NULL; 5121 return ERR_PTR(error); 5122 } 5123 5124 static int mem_cgroup_pre_destroy(struct cgroup_subsys *ss, 5125 struct cgroup *cont) 5126 { 5127 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont); 5128 5129 return mem_cgroup_force_empty(memcg, false); 5130 } 5131 5132 static void mem_cgroup_destroy(struct cgroup_subsys *ss, 5133 struct cgroup *cont) 5134 { 5135 struct mem_cgroup *memcg = mem_cgroup_from_cont(cont); 5136 5137 kmem_cgroup_destroy(ss, cont); 5138 5139 mem_cgroup_put(memcg); 5140 } 5141 5142 static int mem_cgroup_populate(struct cgroup_subsys *ss, 5143 struct cgroup *cont) 5144 { 5145 int ret; 5146 5147 ret = cgroup_add_files(cont, ss, mem_cgroup_files, 5148 ARRAY_SIZE(mem_cgroup_files)); 5149 5150 if (!ret) 5151 ret = register_memsw_files(cont, ss); 5152 5153 if (!ret) 5154 ret = register_kmem_files(cont, ss); 5155 5156 return ret; 5157 } 5158 5159 #ifdef CONFIG_MMU 5160 /* Handlers for move charge at task migration. */ 5161 #define PRECHARGE_COUNT_AT_ONCE 256 5162 static int mem_cgroup_do_precharge(unsigned long count) 5163 { 5164 int ret = 0; 5165 int batch_count = PRECHARGE_COUNT_AT_ONCE; 5166 struct mem_cgroup *memcg = mc.to; 5167 5168 if (mem_cgroup_is_root(memcg)) { 5169 mc.precharge += count; 5170 /* we don't need css_get for root */ 5171 return ret; 5172 } 5173 /* try to charge at once */ 5174 if (count > 1) { 5175 struct res_counter *dummy; 5176 /* 5177 * "memcg" cannot be under rmdir() because we've already checked 5178 * by cgroup_lock_live_cgroup() that it is not removed and we 5179 * are still under the same cgroup_mutex. So we can postpone 5180 * css_get(). 5181 */ 5182 if (res_counter_charge(&memcg->res, PAGE_SIZE * count, &dummy)) 5183 goto one_by_one; 5184 if (do_swap_account && res_counter_charge(&memcg->memsw, 5185 PAGE_SIZE * count, &dummy)) { 5186 res_counter_uncharge(&memcg->res, PAGE_SIZE * count); 5187 goto one_by_one; 5188 } 5189 mc.precharge += count; 5190 return ret; 5191 } 5192 one_by_one: 5193 /* fall back to one by one charge */ 5194 while (count--) { 5195 if (signal_pending(current)) { 5196 ret = -EINTR; 5197 break; 5198 } 5199 if (!batch_count--) { 5200 batch_count = PRECHARGE_COUNT_AT_ONCE; 5201 cond_resched(); 5202 } 5203 ret = __mem_cgroup_try_charge(NULL, 5204 GFP_KERNEL, 1, &memcg, false); 5205 if (ret || !memcg) 5206 /* mem_cgroup_clear_mc() will do uncharge later */ 5207 return -ENOMEM; 5208 mc.precharge++; 5209 } 5210 return ret; 5211 } 5212 5213 /** 5214 * is_target_pte_for_mc - check a pte whether it is valid for move charge 5215 * @vma: the vma the pte to be checked belongs 5216 * @addr: the address corresponding to the pte to be checked 5217 * @ptent: the pte to be checked 5218 * @target: the pointer the target page or swap ent will be stored(can be NULL) 5219 * 5220 * Returns 5221 * 0(MC_TARGET_NONE): if the pte is not a target for move charge. 5222 * 1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for 5223 * move charge. if @target is not NULL, the page is stored in target->page 5224 * with extra refcnt got(Callers should handle it). 5225 * 2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a 5226 * target for charge migration. if @target is not NULL, the entry is stored 5227 * in target->ent. 5228 * 5229 * Called with pte lock held. 5230 */ 5231 union mc_target { 5232 struct page *page; 5233 swp_entry_t ent; 5234 }; 5235 5236 enum mc_target_type { 5237 MC_TARGET_NONE, /* not used */ 5238 MC_TARGET_PAGE, 5239 MC_TARGET_SWAP, 5240 }; 5241 5242 static struct page *mc_handle_present_pte(struct vm_area_struct *vma, 5243 unsigned long addr, pte_t ptent) 5244 { 5245 struct page *page = vm_normal_page(vma, addr, ptent); 5246 5247 if (!page || !page_mapped(page)) 5248 return NULL; 5249 if (PageAnon(page)) { 5250 /* we don't move shared anon */ 5251 if (!move_anon() || page_mapcount(page) > 2) 5252 return NULL; 5253 } else if (!move_file()) 5254 /* we ignore mapcount for file pages */ 5255 return NULL; 5256 if (!get_page_unless_zero(page)) 5257 return NULL; 5258 5259 return page; 5260 } 5261 5262 static struct page *mc_handle_swap_pte(struct vm_area_struct *vma, 5263 unsigned long addr, pte_t ptent, swp_entry_t *entry) 5264 { 5265 int usage_count; 5266 struct page *page = NULL; 5267 swp_entry_t ent = pte_to_swp_entry(ptent); 5268 5269 if (!move_anon() || non_swap_entry(ent)) 5270 return NULL; 5271 usage_count = mem_cgroup_count_swap_user(ent, &page); 5272 if (usage_count > 1) { /* we don't move shared anon */ 5273 if (page) 5274 put_page(page); 5275 return NULL; 5276 } 5277 if (do_swap_account) 5278 entry->val = ent.val; 5279 5280 return page; 5281 } 5282 5283 static struct page *mc_handle_file_pte(struct vm_area_struct *vma, 5284 unsigned long addr, pte_t ptent, swp_entry_t *entry) 5285 { 5286 struct page *page = NULL; 5287 struct inode *inode; 5288 struct address_space *mapping; 5289 pgoff_t pgoff; 5290 5291 if (!vma->vm_file) /* anonymous vma */ 5292 return NULL; 5293 if (!move_file()) 5294 return NULL; 5295 5296 inode = vma->vm_file->f_path.dentry->d_inode; 5297 mapping = vma->vm_file->f_mapping; 5298 if (pte_none(ptent)) 5299 pgoff = linear_page_index(vma, addr); 5300 else /* pte_file(ptent) is true */ 5301 pgoff = pte_to_pgoff(ptent); 5302 5303 /* page is moved even if it's not RSS of this task(page-faulted). */ 5304 page = find_get_page(mapping, pgoff); 5305 5306 #ifdef CONFIG_SWAP 5307 /* shmem/tmpfs may report page out on swap: account for that too. */ 5308 if (radix_tree_exceptional_entry(page)) { 5309 swp_entry_t swap = radix_to_swp_entry(page); 5310 if (do_swap_account) 5311 *entry = swap; 5312 page = find_get_page(&swapper_space, swap.val); 5313 } 5314 #endif 5315 return page; 5316 } 5317 5318 static int is_target_pte_for_mc(struct vm_area_struct *vma, 5319 unsigned long addr, pte_t ptent, union mc_target *target) 5320 { 5321 struct page *page = NULL; 5322 struct page_cgroup *pc; 5323 int ret = 0; 5324 swp_entry_t ent = { .val = 0 }; 5325 5326 if (pte_present(ptent)) 5327 page = mc_handle_present_pte(vma, addr, ptent); 5328 else if (is_swap_pte(ptent)) 5329 page = mc_handle_swap_pte(vma, addr, ptent, &ent); 5330 else if (pte_none(ptent) || pte_file(ptent)) 5331 page = mc_handle_file_pte(vma, addr, ptent, &ent); 5332 5333 if (!page && !ent.val) 5334 return 0; 5335 if (page) { 5336 pc = lookup_page_cgroup(page); 5337 /* 5338 * Do only loose check w/o page_cgroup lock. 5339 * mem_cgroup_move_account() checks the pc is valid or not under 5340 * the lock. 5341 */ 5342 if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) { 5343 ret = MC_TARGET_PAGE; 5344 if (target) 5345 target->page = page; 5346 } 5347 if (!ret || !target) 5348 put_page(page); 5349 } 5350 /* There is a swap entry and a page doesn't exist or isn't charged */ 5351 if (ent.val && !ret && 5352 css_id(&mc.from->css) == lookup_swap_cgroup(ent)) { 5353 ret = MC_TARGET_SWAP; 5354 if (target) 5355 target->ent = ent; 5356 } 5357 return ret; 5358 } 5359 5360 static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd, 5361 unsigned long addr, unsigned long end, 5362 struct mm_walk *walk) 5363 { 5364 struct vm_area_struct *vma = walk->private; 5365 pte_t *pte; 5366 spinlock_t *ptl; 5367 5368 split_huge_page_pmd(walk->mm, pmd); 5369 5370 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl); 5371 for (; addr != end; pte++, addr += PAGE_SIZE) 5372 if (is_target_pte_for_mc(vma, addr, *pte, NULL)) 5373 mc.precharge++; /* increment precharge temporarily */ 5374 pte_unmap_unlock(pte - 1, ptl); 5375 cond_resched(); 5376 5377 return 0; 5378 } 5379 5380 static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm) 5381 { 5382 unsigned long precharge; 5383 struct vm_area_struct *vma; 5384 5385 down_read(&mm->mmap_sem); 5386 for (vma = mm->mmap; vma; vma = vma->vm_next) { 5387 struct mm_walk mem_cgroup_count_precharge_walk = { 5388 .pmd_entry = mem_cgroup_count_precharge_pte_range, 5389 .mm = mm, 5390 .private = vma, 5391 }; 5392 if (is_vm_hugetlb_page(vma)) 5393 continue; 5394 walk_page_range(vma->vm_start, vma->vm_end, 5395 &mem_cgroup_count_precharge_walk); 5396 } 5397 up_read(&mm->mmap_sem); 5398 5399 precharge = mc.precharge; 5400 mc.precharge = 0; 5401 5402 return precharge; 5403 } 5404 5405 static int mem_cgroup_precharge_mc(struct mm_struct *mm) 5406 { 5407 unsigned long precharge = mem_cgroup_count_precharge(mm); 5408 5409 VM_BUG_ON(mc.moving_task); 5410 mc.moving_task = current; 5411 return mem_cgroup_do_precharge(precharge); 5412 } 5413 5414 /* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */ 5415 static void __mem_cgroup_clear_mc(void) 5416 { 5417 struct mem_cgroup *from = mc.from; 5418 struct mem_cgroup *to = mc.to; 5419 5420 /* we must uncharge all the leftover precharges from mc.to */ 5421 if (mc.precharge) { 5422 __mem_cgroup_cancel_charge(mc.to, mc.precharge); 5423 mc.precharge = 0; 5424 } 5425 /* 5426 * we didn't uncharge from mc.from at mem_cgroup_move_account(), so 5427 * we must uncharge here. 5428 */ 5429 if (mc.moved_charge) { 5430 __mem_cgroup_cancel_charge(mc.from, mc.moved_charge); 5431 mc.moved_charge = 0; 5432 } 5433 /* we must fixup refcnts and charges */ 5434 if (mc.moved_swap) { 5435 /* uncharge swap account from the old cgroup */ 5436 if (!mem_cgroup_is_root(mc.from)) 5437 res_counter_uncharge(&mc.from->memsw, 5438 PAGE_SIZE * mc.moved_swap); 5439 __mem_cgroup_put(mc.from, mc.moved_swap); 5440 5441 if (!mem_cgroup_is_root(mc.to)) { 5442 /* 5443 * we charged both to->res and to->memsw, so we should 5444 * uncharge to->res. 5445 */ 5446 res_counter_uncharge(&mc.to->res, 5447 PAGE_SIZE * mc.moved_swap); 5448 } 5449 /* we've already done mem_cgroup_get(mc.to) */ 5450 mc.moved_swap = 0; 5451 } 5452 memcg_oom_recover(from); 5453 memcg_oom_recover(to); 5454 wake_up_all(&mc.waitq); 5455 } 5456 5457 static void mem_cgroup_clear_mc(void) 5458 { 5459 struct mem_cgroup *from = mc.from; 5460 5461 /* 5462 * we must clear moving_task before waking up waiters at the end of 5463 * task migration. 5464 */ 5465 mc.moving_task = NULL; 5466 __mem_cgroup_clear_mc(); 5467 spin_lock(&mc.lock); 5468 mc.from = NULL; 5469 mc.to = NULL; 5470 spin_unlock(&mc.lock); 5471 mem_cgroup_end_move(from); 5472 } 5473 5474 static int mem_cgroup_can_attach(struct cgroup_subsys *ss, 5475 struct cgroup *cgroup, 5476 struct task_struct *p) 5477 { 5478 int ret = 0; 5479 struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup); 5480 5481 if (memcg->move_charge_at_immigrate) { 5482 struct mm_struct *mm; 5483 struct mem_cgroup *from = mem_cgroup_from_task(p); 5484 5485 VM_BUG_ON(from == memcg); 5486 5487 mm = get_task_mm(p); 5488 if (!mm) 5489 return 0; 5490 /* We move charges only when we move a owner of the mm */ 5491 if (mm->owner == p) { 5492 VM_BUG_ON(mc.from); 5493 VM_BUG_ON(mc.to); 5494 VM_BUG_ON(mc.precharge); 5495 VM_BUG_ON(mc.moved_charge); 5496 VM_BUG_ON(mc.moved_swap); 5497 mem_cgroup_start_move(from); 5498 spin_lock(&mc.lock); 5499 mc.from = from; 5500 mc.to = memcg; 5501 spin_unlock(&mc.lock); 5502 /* We set mc.moving_task later */ 5503 5504 ret = mem_cgroup_precharge_mc(mm); 5505 if (ret) 5506 mem_cgroup_clear_mc(); 5507 } 5508 mmput(mm); 5509 } 5510 return ret; 5511 } 5512 5513 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss, 5514 struct cgroup *cgroup, 5515 struct task_struct *p) 5516 { 5517 mem_cgroup_clear_mc(); 5518 } 5519 5520 static int mem_cgroup_move_charge_pte_range(pmd_t *pmd, 5521 unsigned long addr, unsigned long end, 5522 struct mm_walk *walk) 5523 { 5524 int ret = 0; 5525 struct vm_area_struct *vma = walk->private; 5526 pte_t *pte; 5527 spinlock_t *ptl; 5528 5529 split_huge_page_pmd(walk->mm, pmd); 5530 retry: 5531 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl); 5532 for (; addr != end; addr += PAGE_SIZE) { 5533 pte_t ptent = *(pte++); 5534 union mc_target target; 5535 int type; 5536 struct page *page; 5537 struct page_cgroup *pc; 5538 swp_entry_t ent; 5539 5540 if (!mc.precharge) 5541 break; 5542 5543 type = is_target_pte_for_mc(vma, addr, ptent, &target); 5544 switch (type) { 5545 case MC_TARGET_PAGE: 5546 page = target.page; 5547 if (isolate_lru_page(page)) 5548 goto put; 5549 pc = lookup_page_cgroup(page); 5550 if (!mem_cgroup_move_account(page, 1, pc, 5551 mc.from, mc.to, false)) { 5552 mc.precharge--; 5553 /* we uncharge from mc.from later. */ 5554 mc.moved_charge++; 5555 } 5556 putback_lru_page(page); 5557 put: /* is_target_pte_for_mc() gets the page */ 5558 put_page(page); 5559 break; 5560 case MC_TARGET_SWAP: 5561 ent = target.ent; 5562 if (!mem_cgroup_move_swap_account(ent, 5563 mc.from, mc.to, false)) { 5564 mc.precharge--; 5565 /* we fixup refcnts and charges later. */ 5566 mc.moved_swap++; 5567 } 5568 break; 5569 default: 5570 break; 5571 } 5572 } 5573 pte_unmap_unlock(pte - 1, ptl); 5574 cond_resched(); 5575 5576 if (addr != end) { 5577 /* 5578 * We have consumed all precharges we got in can_attach(). 5579 * We try charge one by one, but don't do any additional 5580 * charges to mc.to if we have failed in charge once in attach() 5581 * phase. 5582 */ 5583 ret = mem_cgroup_do_precharge(1); 5584 if (!ret) 5585 goto retry; 5586 } 5587 5588 return ret; 5589 } 5590 5591 static void mem_cgroup_move_charge(struct mm_struct *mm) 5592 { 5593 struct vm_area_struct *vma; 5594 5595 lru_add_drain_all(); 5596 retry: 5597 if (unlikely(!down_read_trylock(&mm->mmap_sem))) { 5598 /* 5599 * Someone who are holding the mmap_sem might be waiting in 5600 * waitq. So we cancel all extra charges, wake up all waiters, 5601 * and retry. Because we cancel precharges, we might not be able 5602 * to move enough charges, but moving charge is a best-effort 5603 * feature anyway, so it wouldn't be a big problem. 5604 */ 5605 __mem_cgroup_clear_mc(); 5606 cond_resched(); 5607 goto retry; 5608 } 5609 for (vma = mm->mmap; vma; vma = vma->vm_next) { 5610 int ret; 5611 struct mm_walk mem_cgroup_move_charge_walk = { 5612 .pmd_entry = mem_cgroup_move_charge_pte_range, 5613 .mm = mm, 5614 .private = vma, 5615 }; 5616 if (is_vm_hugetlb_page(vma)) 5617 continue; 5618 ret = walk_page_range(vma->vm_start, vma->vm_end, 5619 &mem_cgroup_move_charge_walk); 5620 if (ret) 5621 /* 5622 * means we have consumed all precharges and failed in 5623 * doing additional charge. Just abandon here. 5624 */ 5625 break; 5626 } 5627 up_read(&mm->mmap_sem); 5628 } 5629 5630 static void mem_cgroup_move_task(struct cgroup_subsys *ss, 5631 struct cgroup *cont, 5632 struct cgroup *old_cont, 5633 struct task_struct *p) 5634 { 5635 struct mm_struct *mm = get_task_mm(p); 5636 5637 if (mm) { 5638 if (mc.to) 5639 mem_cgroup_move_charge(mm); 5640 put_swap_token(mm); 5641 mmput(mm); 5642 } 5643 if (mc.to) 5644 mem_cgroup_clear_mc(); 5645 } 5646 #else /* !CONFIG_MMU */ 5647 static int mem_cgroup_can_attach(struct cgroup_subsys *ss, 5648 struct cgroup *cgroup, 5649 struct task_struct *p) 5650 { 5651 return 0; 5652 } 5653 static void mem_cgroup_cancel_attach(struct cgroup_subsys *ss, 5654 struct cgroup *cgroup, 5655 struct task_struct *p) 5656 { 5657 } 5658 static void mem_cgroup_move_task(struct cgroup_subsys *ss, 5659 struct cgroup *cont, 5660 struct cgroup *old_cont, 5661 struct task_struct *p) 5662 { 5663 } 5664 #endif 5665 5666 struct cgroup_subsys mem_cgroup_subsys = { 5667 .name = "memory", 5668 .subsys_id = mem_cgroup_subsys_id, 5669 .create = mem_cgroup_create, 5670 .pre_destroy = mem_cgroup_pre_destroy, 5671 .destroy = mem_cgroup_destroy, 5672 .populate = mem_cgroup_populate, 5673 .can_attach = mem_cgroup_can_attach, 5674 .cancel_attach = mem_cgroup_cancel_attach, 5675 .attach = mem_cgroup_move_task, 5676 .early_init = 0, 5677 .use_id = 1, 5678 }; 5679 5680 #ifdef CONFIG_CGROUP_MEM_RES_CTLR_SWAP 5681 static int __init enable_swap_account(char *s) 5682 { 5683 /* consider enabled if no parameter or 1 is given */ 5684 if (!strcmp(s, "1")) 5685 really_do_swap_account = 1; 5686 else if (!strcmp(s, "0")) 5687 really_do_swap_account = 0; 5688 return 1; 5689 } 5690 __setup("swapaccount=", enable_swap_account); 5691 5692 #endif 5693