linux/mm/memcontrol.c
<<
>>
Prefs
   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 * Kernel Memory Controller
  14 * Copyright (C) 2012 Parallels Inc. and Google Inc.
  15 * Authors: Glauber Costa and Suleiman Souhlal
  16 *
  17 * This program is free software; you can redistribute it and/or modify
  18 * it under the terms of the GNU General Public License as published by
  19 * the Free Software Foundation; either version 2 of the License, or
  20 * (at your option) any later version.
  21 *
  22 * This program is distributed in the hope that it will be useful,
  23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  25 * GNU General Public License for more details.
  26 */
  27
  28#include <linux/page_counter.h>
  29#include <linux/memcontrol.h>
  30#include <linux/cgroup.h>
  31#include <linux/mm.h>
  32#include <linux/hugetlb.h>
  33#include <linux/pagemap.h>
  34#include <linux/smp.h>
  35#include <linux/page-flags.h>
  36#include <linux/backing-dev.h>
  37#include <linux/bit_spinlock.h>
  38#include <linux/rcupdate.h>
  39#include <linux/limits.h>
  40#include <linux/export.h>
  41#include <linux/mutex.h>
  42#include <linux/rbtree.h>
  43#include <linux/slab.h>
  44#include <linux/swap.h>
  45#include <linux/swapops.h>
  46#include <linux/spinlock.h>
  47#include <linux/eventfd.h>
  48#include <linux/sort.h>
  49#include <linux/fs.h>
  50#include <linux/seq_file.h>
  51#include <linux/vmalloc.h>
  52#include <linux/vmpressure.h>
  53#include <linux/mm_inline.h>
  54#include <linux/page_cgroup.h>
  55#include <linux/cpu.h>
  56#include <linux/oom.h>
  57#include "internal.h"
  58#include <net/sock.h>
  59#include <net/ip.h>
  60#include <net/tcp_memcontrol.h>
  61#include "slab.h"
  62
  63#include <asm/uaccess.h>
  64
  65#include <trace/events/vmscan.h>
  66
  67struct cgroup_subsys mem_cgroup_subsys __read_mostly;
  68EXPORT_SYMBOL(mem_cgroup_subsys);
  69
  70#define MEM_CGROUP_RECLAIM_RETRIES      5
  71static struct mem_cgroup *root_mem_cgroup __read_mostly;
  72
  73/* Kernel memory accounting disabled? */
  74static bool cgroup_memory_nokmem;
  75
  76#ifdef CONFIG_MEMCG_SWAP
  77/* Turned on only when memory cgroup is enabled && really_do_swap_account = 1 */
  78int do_swap_account __read_mostly;
  79
  80/* for remember boot option*/
  81#ifdef CONFIG_MEMCG_SWAP_ENABLED
  82static int really_do_swap_account __initdata = 1;
  83#else
  84static int really_do_swap_account __initdata = 0;
  85#endif
  86
  87#else
  88#define do_swap_account         0
  89#endif
  90
  91
  92/*
  93 * Statistics for memory cgroup.
  94 */
  95enum mem_cgroup_stat_index {
  96        /*
  97         * For MEM_CONTAINER_TYPE_ALL, usage = pagecache + rss.
  98         */
  99        MEM_CGROUP_STAT_CACHE,          /* # of pages charged as cache */
 100        MEM_CGROUP_STAT_RSS,            /* # of pages charged as anon rss */
 101        MEM_CGROUP_STAT_RSS_HUGE,       /* # of pages charged as anon huge */
 102        MEM_CGROUP_STAT_FILE_MAPPED,    /* # of pages charged as file rss */
 103        MEM_CGROUP_STAT_SWAP,           /* # of pages, swapped out */
 104        MEM_CGROUP_STAT_NSTATS,
 105};
 106
 107static const char * const mem_cgroup_stat_names[] = {
 108        "cache",
 109        "rss",
 110        "rss_huge",
 111        "mapped_file",
 112        "swap",
 113};
 114
 115enum mem_cgroup_events_index {
 116        MEM_CGROUP_EVENTS_PGPGIN,       /* # of pages paged in */
 117        MEM_CGROUP_EVENTS_PGPGOUT,      /* # of pages paged out */
 118        MEM_CGROUP_EVENTS_PGFAULT,      /* # of page-faults */
 119        MEM_CGROUP_EVENTS_PGMAJFAULT,   /* # of major page-faults */
 120        MEM_CGROUP_EVENTS_NSTATS,
 121};
 122
 123static const char * const mem_cgroup_events_names[] = {
 124        "pgpgin",
 125        "pgpgout",
 126        "pgfault",
 127        "pgmajfault",
 128};
 129
 130static const char * const mem_cgroup_lru_names[] = {
 131        "inactive_anon",
 132        "active_anon",
 133        "inactive_file",
 134        "active_file",
 135        "unevictable",
 136};
 137
 138/*
 139 * Per memcg event counter is incremented at every pagein/pageout. With THP,
 140 * it will be incremated by the number of pages. This counter is used for
 141 * for trigger some periodic events. This is straightforward and better
 142 * than using jiffies etc. to handle periodic memcg event.
 143 */
 144enum mem_cgroup_events_target {
 145        MEM_CGROUP_TARGET_THRESH,
 146        MEM_CGROUP_TARGET_SOFTLIMIT,
 147        MEM_CGROUP_TARGET_NUMAINFO,
 148        MEM_CGROUP_NTARGETS,
 149};
 150#define THRESHOLDS_EVENTS_TARGET 128
 151#define SOFTLIMIT_EVENTS_TARGET 1024
 152#define NUMAINFO_EVENTS_TARGET  1024
 153
 154#define MEM_CGROUP_ID_MAX       USHRT_MAX
 155
 156static void mem_cgroup_id_put(struct mem_cgroup *memcg);
 157static unsigned short mem_cgroup_id(struct mem_cgroup *memcg);
 158
 159struct mem_cgroup_stat_cpu {
 160        long count[MEM_CGROUP_STAT_NSTATS];
 161        unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
 162        unsigned long nr_page_events;
 163        unsigned long targets[MEM_CGROUP_NTARGETS];
 164};
 165
 166struct mem_cgroup_reclaim_iter {
 167        /*
 168         * last scanned hierarchy member. Valid only if last_dead_count
 169         * matches memcg->dead_count of the hierarchy root group.
 170         */
 171        struct mem_cgroup *last_visited;
 172        unsigned long last_dead_count;
 173
 174        /* scan generation, increased every round-trip */
 175        unsigned int generation;
 176};
 177
 178/*
 179 * per-zone information in memory controller.
 180 */
 181struct mem_cgroup_per_zone {
 182        struct lruvec           lruvec;
 183        unsigned long           lru_size[NR_LRU_LISTS];
 184
 185        struct mem_cgroup_reclaim_iter reclaim_iter[DEF_PRIORITY + 1];
 186
 187        struct rb_node          tree_node;      /* RB tree node */
 188        unsigned long           usage_in_excess;/* Set to the value by which */
 189                                                /* the soft limit is exceeded*/
 190        bool                    on_tree;
 191        struct mem_cgroup       *memcg;         /* Back pointer, we cannot */
 192                                                /* use container_of        */
 193};
 194
 195struct mem_cgroup_per_node {
 196        struct mem_cgroup_per_zone zoneinfo[MAX_NR_ZONES];
 197};
 198
 199struct mem_cgroup_lru_info {
 200        struct mem_cgroup_per_node *nodeinfo[0];
 201};
 202
 203/*
 204 * Cgroups above their limits are maintained in a RB-Tree, independent of
 205 * their hierarchy representation
 206 */
 207
 208struct mem_cgroup_tree_per_zone {
 209        struct rb_root rb_root;
 210        spinlock_t lock;
 211};
 212
 213struct mem_cgroup_tree_per_node {
 214        struct mem_cgroup_tree_per_zone rb_tree_per_zone[MAX_NR_ZONES];
 215};
 216
 217struct mem_cgroup_tree {
 218        struct mem_cgroup_tree_per_node *rb_tree_per_node[MAX_NUMNODES];
 219};
 220
 221static struct mem_cgroup_tree soft_limit_tree __read_mostly;
 222
 223struct mem_cgroup_threshold {
 224        struct eventfd_ctx *eventfd;
 225        unsigned long threshold;
 226};
 227
 228/* For threshold */
 229struct mem_cgroup_threshold_ary {
 230        /* An array index points to threshold just below or equal to usage. */
 231        int current_threshold;
 232        /* Size of entries[] */
 233        unsigned int size;
 234        /* Array of thresholds */
 235        struct mem_cgroup_threshold entries[0];
 236};
 237
 238struct mem_cgroup_thresholds {
 239        /* Primary thresholds array */
 240        struct mem_cgroup_threshold_ary *primary;
 241        /*
 242         * Spare threshold array.
 243         * This is needed to make mem_cgroup_unregister_event() "never fail".
 244         * It must be able to store at least primary->size - 1 entries.
 245         */
 246        struct mem_cgroup_threshold_ary *spare;
 247};
 248
 249/* for OOM */
 250struct mem_cgroup_eventfd_list {
 251        struct list_head list;
 252        struct eventfd_ctx *eventfd;
 253};
 254
 255static void mem_cgroup_threshold(struct mem_cgroup *memcg);
 256static void mem_cgroup_oom_notify(struct mem_cgroup *memcg);
 257
 258/*
 259 * The memory controller data structure. The memory controller controls both
 260 * page cache and RSS per cgroup. We would eventually like to provide
 261 * statistics based on the statistics developed by Rik Van Riel for clock-pro,
 262 * to help the administrator determine what knobs to tune.
 263 *
 264 * TODO: Add a water mark for the memory controller. Reclaim will begin when
 265 * we hit the water mark. May be even add a low water mark, such that
 266 * no reclaim occurs from a cgroup at it's low water mark, this is
 267 * a feature that will be implemented much later in the future.
 268 */
 269struct mem_cgroup {
 270        struct cgroup_subsys_state css;
 271
 272        /* Private memcg ID. Used to ID objects that outlive the cgroup */
 273        unsigned short id;
 274
 275        /*
 276         * the counter to account for memory usage
 277         */
 278        struct page_counter memory;
 279
 280        unsigned long soft_limit;
 281
 282        /* vmpressure notifications */
 283        struct vmpressure vmpressure;
 284
 285        union {
 286                /*
 287                 * the counter to account for mem+swap usage.
 288                 */
 289                struct page_counter memsw;
 290                /*
 291                 * rcu_freeing is used only when freeing struct mem_cgroup,
 292                 * so put it into a union to avoid wasting more memory.
 293                 * It must be disjoint from the css field.  It could be
 294                 * in a union with the res field, but res plays a much
 295                 * larger part in mem_cgroup life than memsw, and might
 296                 * be of interest, even at time of free, when debugging.
 297                 * So share rcu_head with the less interesting memsw.
 298                 */
 299                struct rcu_head rcu_freeing;
 300                /*
 301                 * We also need some space for a worker in deferred freeing.
 302                 * By the time we call it, rcu_freeing is no longer in use.
 303                 */
 304                struct work_struct work_freeing;
 305        };
 306        /*
 307         * the counter to account for kernel memory usage.
 308         */
 309        struct page_counter kmem;
 310        /*
 311         * Should the accounting and control be hierarchical, per subtree?
 312         */
 313        bool use_hierarchy;
 314        unsigned long kmem_account_flags; /* See KMEM_ACCOUNTED_*, below */
 315
 316        bool            oom_lock;
 317        atomic_t        under_oom;
 318        atomic_t        oom_wakeups;
 319
 320        atomic_t        refcnt;
 321
 322        int     swappiness;
 323        /* OOM-Killer disable */
 324        int             oom_kill_disable;
 325
 326        /* set when res.limit == memsw.limit */
 327        bool            memsw_is_minimum;
 328
 329        /* protect arrays of thresholds */
 330        struct mutex thresholds_lock;
 331
 332        /* thresholds for memory usage. RCU-protected */
 333        struct mem_cgroup_thresholds thresholds;
 334
 335        /* thresholds for mem+swap usage. RCU-protected */
 336        struct mem_cgroup_thresholds memsw_thresholds;
 337
 338        /* For oom notifier event fd */
 339        struct list_head oom_notify;
 340
 341        /*
 342         * Should we move charges of a task when a task is moved into this
 343         * mem_cgroup ? And what type of charges should we move ?
 344         */
 345        unsigned long   move_charge_at_immigrate;
 346        /*
 347         * set > 0 if pages under this cgroup are moving to other cgroup.
 348         */
 349        atomic_t        moving_account;
 350        /* taken only while moving_account > 0 */
 351        spinlock_t      move_lock;
 352        /*
 353         * percpu counter.
 354         */
 355        struct mem_cgroup_stat_cpu __percpu *stat;
 356        /*
 357         * used when a cpu is offlined or other synchronizations
 358         * See mem_cgroup_read_stat().
 359         */
 360        struct mem_cgroup_stat_cpu nocpu_base;
 361        spinlock_t pcp_counter_lock;
 362
 363        atomic_t        dead_count;
 364#if defined(CONFIG_MEMCG_KMEM) && defined(CONFIG_INET)
 365        struct tcp_memcontrol tcp_mem;
 366#endif
 367#if defined(CONFIG_MEMCG_KMEM)
 368        /* analogous to slab_common's slab_caches list, but per-memcg;
 369         * protected by memcg_slab_mutex */
 370        struct list_head memcg_slab_caches;
 371        RH_KABI_DEPRECATE(struct mutex, slab_caches_mutex)
 372        /* Index in the kmem_cache->memcg_params->memcg_caches array */
 373        int kmemcg_id;
 374#endif
 375
 376        int last_scanned_node;
 377#if MAX_NUMNODES > 1
 378        nodemask_t      scan_nodes;
 379        atomic_t        numainfo_events;
 380        atomic_t        numainfo_updating;
 381#endif
 382
 383        /*
 384         * Per cgroup active and inactive list, similar to the
 385         * per zone LRU lists.
 386         *
 387         * WARNING: This has to be the last element of the struct. Don't
 388         * add new fields after this point.
 389         */
 390        struct mem_cgroup_lru_info info;
 391};
 392
 393static size_t memcg_size(void)
 394{
 395        return sizeof(struct mem_cgroup) +
 396                nr_node_ids * sizeof(struct mem_cgroup_per_node *);
 397}
 398
 399/* internal only representation about the status of kmem accounting. */
 400enum {
 401        KMEM_ACCOUNTED_ACTIVE, /* accounted by this cgroup itself */
 402        KMEM_ACCOUNTED_DEAD, /* dead memcg with pending kmem charges */
 403};
 404
 405#ifdef CONFIG_MEMCG_KMEM
 406static inline void memcg_kmem_set_active(struct mem_cgroup *memcg)
 407{
 408        set_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
 409}
 410
 411static bool memcg_kmem_is_active(struct mem_cgroup *memcg)
 412{
 413        return test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags);
 414}
 415
 416static void memcg_kmem_mark_dead(struct mem_cgroup *memcg)
 417{
 418        if (test_bit(KMEM_ACCOUNTED_ACTIVE, &memcg->kmem_account_flags))
 419                set_bit(KMEM_ACCOUNTED_DEAD, &memcg->kmem_account_flags);
 420}
 421
 422static bool memcg_kmem_test_and_clear_dead(struct mem_cgroup *memcg)
 423{
 424        return test_and_clear_bit(KMEM_ACCOUNTED_DEAD,
 425                                  &memcg->kmem_account_flags);
 426}
 427#endif
 428
 429/* Stuffs for move charges at task migration. */
 430/*
 431 * Types of charges to be moved. "move_charge_at_immitgrate" and
 432 * "immigrate_flags" are treated as a left-shifted bitmap of these types.
 433 */
 434enum move_type {
 435        MOVE_CHARGE_TYPE_ANON,  /* private anonymous page and swap of it */
 436        MOVE_CHARGE_TYPE_FILE,  /* file page(including tmpfs) and swap of it */
 437        NR_MOVE_TYPE,
 438};
 439
 440/* "mc" and its members are protected by cgroup_mutex */
 441static struct move_charge_struct {
 442        spinlock_t        lock; /* for from, to */
 443        struct mem_cgroup *from;
 444        struct mem_cgroup *to;
 445        unsigned long immigrate_flags;
 446        unsigned long precharge;
 447        unsigned long moved_charge;
 448        unsigned long moved_swap;
 449        struct task_struct *moving_task;        /* a task moving charges */
 450        wait_queue_head_t waitq;                /* a waitq for other context */
 451} mc = {
 452        .lock = __SPIN_LOCK_UNLOCKED(mc.lock),
 453        .waitq = __WAIT_QUEUE_HEAD_INITIALIZER(mc.waitq),
 454};
 455
 456static bool move_anon(void)
 457{
 458        return test_bit(MOVE_CHARGE_TYPE_ANON, &mc.immigrate_flags);
 459}
 460
 461static bool move_file(void)
 462{
 463        return test_bit(MOVE_CHARGE_TYPE_FILE, &mc.immigrate_flags);
 464}
 465
 466/*
 467 * Maximum loops in mem_cgroup_hierarchical_reclaim(), used for soft
 468 * limit reclaim to prevent infinite loops, if they ever occur.
 469 */
 470#define MEM_CGROUP_MAX_RECLAIM_LOOPS            100
 471#define MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS 2
 472
 473enum charge_type {
 474        MEM_CGROUP_CHARGE_TYPE_CACHE = 0,
 475        MEM_CGROUP_CHARGE_TYPE_ANON,
 476        MEM_CGROUP_CHARGE_TYPE_SWAPOUT, /* for accounting swapcache */
 477        MEM_CGROUP_CHARGE_TYPE_DROP,    /* a page was unused swap cache */
 478        NR_CHARGE_TYPE,
 479};
 480
 481/* for encoding cft->private value on file */
 482enum res_type {
 483        _MEM,
 484        _MEMSWAP,
 485        _OOM_TYPE,
 486        _KMEM,
 487};
 488
 489#define MEMFILE_PRIVATE(x, val) ((x) << 16 | (val))
 490#define MEMFILE_TYPE(val)       ((val) >> 16 & 0xffff)
 491#define MEMFILE_ATTR(val)       ((val) & 0xffff)
 492/* Used for OOM nofiier */
 493#define OOM_CONTROL             (0)
 494
 495/*
 496 * Reclaim flags for mem_cgroup_hierarchical_reclaim
 497 */
 498#define MEM_CGROUP_RECLAIM_NOSWAP_BIT   0x0
 499#define MEM_CGROUP_RECLAIM_NOSWAP       (1 << MEM_CGROUP_RECLAIM_NOSWAP_BIT)
 500#define MEM_CGROUP_RECLAIM_SHRINK_BIT   0x1
 501#define MEM_CGROUP_RECLAIM_SHRINK       (1 << MEM_CGROUP_RECLAIM_SHRINK_BIT)
 502
 503/*
 504 * The memcg_create_mutex will be held whenever a new cgroup is created.
 505 * As a consequence, any change that needs to protect against new child cgroups
 506 * appearing has to hold it as well.
 507 */
 508static DEFINE_MUTEX(memcg_create_mutex);
 509
 510static void mem_cgroup_get(struct mem_cgroup *memcg);
 511static void mem_cgroup_put(struct mem_cgroup *memcg);
 512
 513static inline
 514struct mem_cgroup *mem_cgroup_from_css(struct cgroup_subsys_state *s)
 515{
 516        return container_of(s, struct mem_cgroup, css);
 517}
 518
 519/* Some nice accessors for the vmpressure. */
 520struct vmpressure *memcg_to_vmpressure(struct mem_cgroup *memcg)
 521{
 522        if (!memcg)
 523                memcg = root_mem_cgroup;
 524        return &memcg->vmpressure;
 525}
 526
 527struct cgroup_subsys_state *vmpressure_to_css(struct vmpressure *vmpr)
 528{
 529        return &container_of(vmpr, struct mem_cgroup, vmpressure)->css;
 530}
 531
 532struct vmpressure *css_to_vmpressure(struct cgroup_subsys_state *css)
 533{
 534        return &mem_cgroup_from_css(css)->vmpressure;
 535}
 536
 537static inline bool mem_cgroup_is_root(struct mem_cgroup *memcg)
 538{
 539        return (memcg == root_mem_cgroup);
 540}
 541
 542/* Writing them here to avoid exposing memcg's inner layout */
 543#if defined(CONFIG_INET) && defined(CONFIG_MEMCG_KMEM)
 544
 545void sock_update_memcg(struct sock *sk)
 546{
 547        if (mem_cgroup_sockets_enabled) {
 548                struct mem_cgroup *memcg;
 549                struct cg_proto *cg_proto;
 550
 551                BUG_ON(!sk->sk_prot->proto_cgroup);
 552
 553                /* Socket cloning can throw us here with sk_cgrp already
 554                 * filled. It won't however, necessarily happen from
 555                 * process context. So the test for root memcg given
 556                 * the current task's memcg won't help us in this case.
 557                 *
 558                 * Respecting the original socket's memcg is a better
 559                 * decision in this case.
 560                 */
 561                if (sk->sk_cgrp) {
 562                        BUG_ON(mem_cgroup_is_root(sk->sk_cgrp->memcg));
 563                        mem_cgroup_get(sk->sk_cgrp->memcg);
 564                        return;
 565                }
 566
 567                rcu_read_lock();
 568                memcg = mem_cgroup_from_task(current);
 569                cg_proto = sk->sk_prot->proto_cgroup(memcg);
 570                if (!mem_cgroup_is_root(memcg) && memcg_proto_active(cg_proto)) {
 571                        mem_cgroup_get(memcg);
 572                        sk->sk_cgrp = cg_proto;
 573                }
 574                rcu_read_unlock();
 575        }
 576}
 577EXPORT_SYMBOL(sock_update_memcg);
 578
 579void sock_release_memcg(struct sock *sk)
 580{
 581        if (mem_cgroup_sockets_enabled && sk->sk_cgrp) {
 582                struct mem_cgroup *memcg;
 583                WARN_ON(!sk->sk_cgrp->memcg);
 584                memcg = sk->sk_cgrp->memcg;
 585                mem_cgroup_put(memcg);
 586        }
 587}
 588
 589struct cg_proto *tcp_proto_cgroup(struct mem_cgroup *memcg)
 590{
 591        if (!memcg || mem_cgroup_is_root(memcg))
 592                return NULL;
 593
 594        return &memcg->tcp_mem.cg_proto;
 595}
 596EXPORT_SYMBOL(tcp_proto_cgroup);
 597
 598static void disarm_sock_keys(struct mem_cgroup *memcg)
 599{
 600        if (!memcg_proto_activated(&memcg->tcp_mem.cg_proto))
 601                return;
 602        static_key_slow_dec(&memcg_socket_limit_enabled);
 603}
 604#else
 605static void disarm_sock_keys(struct mem_cgroup *memcg)
 606{
 607}
 608#endif
 609
 610#ifdef CONFIG_MEMCG_KMEM
 611/*
 612 * This will be the memcg's index in each cache's ->memcg_params->memcg_caches.
 613 * There are two main reasons for not using the css_id for this:
 614 *  1) this works better in sparse environments, where we have a lot of memcgs,
 615 *     but only a few kmem-limited. Or also, if we have, for instance, 200
 616 *     memcgs, and none but the 200th is kmem-limited, we'd have to have a
 617 *     200 entry array for that.
 618 *
 619 *  2) In order not to violate the cgroup API, we would like to do all memory
 620 *     allocation in ->create(). At that point, we haven't yet allocated the
 621 *     css_id. Having a separate index prevents us from messing with the cgroup
 622 *     core for this
 623 *
 624 * The current size of the caches array is stored in
 625 * memcg_limited_groups_array_size.  It will double each time we have to
 626 * increase it.
 627 */
 628static DEFINE_IDA(kmem_limited_groups);
 629int memcg_limited_groups_array_size;
 630
 631/*
 632 * MIN_SIZE is different than 1, because we would like to avoid going through
 633 * the alloc/free process all the time. In a small machine, 4 kmem-limited
 634 * cgroups is a reasonable guess. In the future, it could be a parameter or
 635 * tunable, but that is strictly not necessary.
 636 *
 637 * MAX_SIZE should be as large as the number of css_ids. Ideally, we could get
 638 * this constant directly from cgroup, but it is understandable that this is
 639 * better kept as an internal representation in cgroup.c. In any case, the
 640 * css_id space is not getting any smaller, and we don't have to necessarily
 641 * increase ours as well if it increases.
 642 */
 643#define MEMCG_CACHES_MIN_SIZE 4
 644#define MEMCG_CACHES_MAX_SIZE 65535
 645
 646/*
 647 * A lot of the calls to the cache allocation functions are expected to be
 648 * inlined by the compiler. Since the calls to memcg_kmem_get_cache are
 649 * conditional to this static branch, we'll have to allow modules that does
 650 * kmem_cache_alloc and the such to see this symbol as well
 651 */
 652struct static_key memcg_kmem_enabled_key;
 653EXPORT_SYMBOL(memcg_kmem_enabled_key);
 654
 655static void disarm_kmem_keys(struct mem_cgroup *memcg)
 656{
 657        if (memcg_kmem_is_active(memcg)) {
 658                static_key_slow_dec(&memcg_kmem_enabled_key);
 659                if (memcg->kmemcg_id >= 0)
 660                        ida_simple_remove(&kmem_limited_groups, memcg->kmemcg_id);
 661        }
 662        /*
 663         * This check can't live in kmem destruction function,
 664         * since the charges will outlive the cgroup
 665         */
 666        WARN_ON(page_counter_read(&memcg->kmem));
 667}
 668#else
 669static void disarm_kmem_keys(struct mem_cgroup *memcg)
 670{
 671}
 672#endif /* CONFIG_MEMCG_KMEM */
 673
 674static void disarm_static_keys(struct mem_cgroup *memcg)
 675{
 676        disarm_sock_keys(memcg);
 677        disarm_kmem_keys(memcg);
 678}
 679
 680static void drain_all_stock_async(struct mem_cgroup *memcg);
 681
 682static struct mem_cgroup_per_zone *
 683mem_cgroup_zoneinfo(struct mem_cgroup *memcg, int nid, int zid)
 684{
 685        VM_BUG_ON((unsigned)nid >= nr_node_ids);
 686        return &memcg->info.nodeinfo[nid]->zoneinfo[zid];
 687}
 688
 689struct cgroup_subsys_state *mem_cgroup_css(struct mem_cgroup *memcg)
 690{
 691        return &memcg->css;
 692}
 693
 694static struct mem_cgroup_per_zone *
 695page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page)
 696{
 697        int nid = page_to_nid(page);
 698        int zid = page_zonenum(page);
 699
 700        return mem_cgroup_zoneinfo(memcg, nid, zid);
 701}
 702
 703static struct mem_cgroup_tree_per_zone *
 704soft_limit_tree_node_zone(int nid, int zid)
 705{
 706        return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
 707}
 708
 709static struct mem_cgroup_tree_per_zone *
 710soft_limit_tree_from_page(struct page *page)
 711{
 712        int nid = page_to_nid(page);
 713        int zid = page_zonenum(page);
 714
 715        return &soft_limit_tree.rb_tree_per_node[nid]->rb_tree_per_zone[zid];
 716}
 717
 718static void
 719__mem_cgroup_insert_exceeded(struct mem_cgroup *memcg,
 720                                struct mem_cgroup_per_zone *mz,
 721                                struct mem_cgroup_tree_per_zone *mctz,
 722                                unsigned long new_usage_in_excess)
 723{
 724        struct rb_node **p = &mctz->rb_root.rb_node;
 725        struct rb_node *parent = NULL;
 726        struct mem_cgroup_per_zone *mz_node;
 727
 728        if (mz->on_tree)
 729                return;
 730
 731        mz->usage_in_excess = new_usage_in_excess;
 732        if (!mz->usage_in_excess)
 733                return;
 734        while (*p) {
 735                parent = *p;
 736                mz_node = rb_entry(parent, struct mem_cgroup_per_zone,
 737                                        tree_node);
 738                if (mz->usage_in_excess < mz_node->usage_in_excess)
 739                        p = &(*p)->rb_left;
 740                /*
 741                 * We can't avoid mem cgroups that are over their soft
 742                 * limit by the same amount
 743                 */
 744                else if (mz->usage_in_excess >= mz_node->usage_in_excess)
 745                        p = &(*p)->rb_right;
 746        }
 747        rb_link_node(&mz->tree_node, parent, p);
 748        rb_insert_color(&mz->tree_node, &mctz->rb_root);
 749        mz->on_tree = true;
 750}
 751
 752static void
 753__mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
 754                                struct mem_cgroup_per_zone *mz,
 755                                struct mem_cgroup_tree_per_zone *mctz)
 756{
 757        if (!mz->on_tree)
 758                return;
 759        rb_erase(&mz->tree_node, &mctz->rb_root);
 760        mz->on_tree = false;
 761}
 762
 763static void
 764mem_cgroup_remove_exceeded(struct mem_cgroup *memcg,
 765                                struct mem_cgroup_per_zone *mz,
 766                                struct mem_cgroup_tree_per_zone *mctz)
 767{
 768        spin_lock(&mctz->lock);
 769        __mem_cgroup_remove_exceeded(memcg, mz, mctz);
 770        spin_unlock(&mctz->lock);
 771}
 772
 773static unsigned long soft_limit_excess(struct mem_cgroup *memcg)
 774{
 775        unsigned long nr_pages = page_counter_read(&memcg->memory);
 776        unsigned long soft_limit = ACCESS_ONCE(memcg->soft_limit);
 777        unsigned long excess = 0;
 778
 779        if (nr_pages > soft_limit)
 780                excess = nr_pages - soft_limit;
 781
 782        return excess;
 783}
 784
 785static void mem_cgroup_update_tree(struct mem_cgroup *memcg, struct page *page)
 786{
 787        unsigned long excess;
 788        struct mem_cgroup_per_zone *mz;
 789        struct mem_cgroup_tree_per_zone *mctz;
 790        int nid = page_to_nid(page);
 791        int zid = page_zonenum(page);
 792        mctz = soft_limit_tree_from_page(page);
 793
 794        /*
 795         * Necessary to update all ancestors when hierarchy is used.
 796         * because their event counter is not touched.
 797         */
 798        for (; memcg; memcg = parent_mem_cgroup(memcg)) {
 799                mz = mem_cgroup_zoneinfo(memcg, nid, zid);
 800                excess = soft_limit_excess(memcg);
 801                /*
 802                 * We have to update the tree if mz is on RB-tree or
 803                 * mem is over its softlimit.
 804                 */
 805                if (excess || mz->on_tree) {
 806                        spin_lock(&mctz->lock);
 807                        /* if on-tree, remove it */
 808                        if (mz->on_tree)
 809                                __mem_cgroup_remove_exceeded(memcg, mz, mctz);
 810                        /*
 811                         * Insert again. mz->usage_in_excess will be updated.
 812                         * If excess is 0, no tree ops.
 813                         */
 814                        __mem_cgroup_insert_exceeded(memcg, mz, mctz, excess);
 815                        spin_unlock(&mctz->lock);
 816                }
 817        }
 818}
 819
 820static void mem_cgroup_remove_from_trees(struct mem_cgroup *memcg)
 821{
 822        int node, zone;
 823        struct mem_cgroup_per_zone *mz;
 824        struct mem_cgroup_tree_per_zone *mctz;
 825
 826        for_each_node(node) {
 827                for (zone = 0; zone < MAX_NR_ZONES; zone++) {
 828                        mz = mem_cgroup_zoneinfo(memcg, node, zone);
 829                        mctz = soft_limit_tree_node_zone(node, zone);
 830                        mem_cgroup_remove_exceeded(memcg, mz, mctz);
 831                }
 832        }
 833}
 834
 835static struct mem_cgroup_per_zone *
 836__mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
 837{
 838        struct rb_node *rightmost = NULL;
 839        struct mem_cgroup_per_zone *mz;
 840
 841retry:
 842        mz = NULL;
 843        rightmost = rb_last(&mctz->rb_root);
 844        if (!rightmost)
 845                goto done;              /* Nothing to reclaim from */
 846
 847        mz = rb_entry(rightmost, struct mem_cgroup_per_zone, tree_node);
 848        /*
 849         * Remove the node now but someone else can add it back,
 850         * we will to add it back at the end of reclaim to its correct
 851         * position in the tree.
 852         */
 853        __mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
 854        if (!soft_limit_excess(mz->memcg) ||
 855                !css_tryget(&mz->memcg->css))
 856                goto retry;
 857done:
 858        return mz;
 859}
 860
 861static struct mem_cgroup_per_zone *
 862mem_cgroup_largest_soft_limit_node(struct mem_cgroup_tree_per_zone *mctz)
 863{
 864        struct mem_cgroup_per_zone *mz;
 865
 866        spin_lock(&mctz->lock);
 867        mz = __mem_cgroup_largest_soft_limit_node(mctz);
 868        spin_unlock(&mctz->lock);
 869        return mz;
 870}
 871
 872/*
 873 * Implementation Note: reading percpu statistics for memcg.
 874 *
 875 * Both of vmstat[] and percpu_counter has threshold and do periodic
 876 * synchronization to implement "quick" read. There are trade-off between
 877 * reading cost and precision of value. Then, we may have a chance to implement
 878 * a periodic synchronizion of counter in memcg's counter.
 879 *
 880 * But this _read() function is used for user interface now. The user accounts
 881 * memory usage by memory cgroup and he _always_ requires exact value because
 882 * he accounts memory. Even if we provide quick-and-fuzzy read, we always
 883 * have to visit all online cpus and make sum. So, for now, unnecessary
 884 * synchronization is not implemented. (just implemented for cpu hotplug)
 885 *
 886 * If there are kernel internal actions which can make use of some not-exact
 887 * value, and reading all cpu value can be performance bottleneck in some
 888 * common workload, threashold and synchonization as vmstat[] should be
 889 * implemented.
 890 */
 891static long mem_cgroup_read_stat(struct mem_cgroup *memcg,
 892                                 enum mem_cgroup_stat_index idx)
 893{
 894        long val = 0;
 895        int cpu;
 896
 897        get_online_cpus();
 898        for_each_online_cpu(cpu)
 899                val += per_cpu(memcg->stat->count[idx], cpu);
 900#ifdef CONFIG_HOTPLUG_CPU
 901        spin_lock(&memcg->pcp_counter_lock);
 902        val += memcg->nocpu_base.count[idx];
 903        spin_unlock(&memcg->pcp_counter_lock);
 904#endif
 905        put_online_cpus();
 906        return val;
 907}
 908
 909static void mem_cgroup_swap_statistics(struct mem_cgroup *memcg,
 910                                         bool charge)
 911{
 912        int val = (charge) ? 1 : -1;
 913        this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_SWAP], val);
 914}
 915
 916static unsigned long mem_cgroup_read_events(struct mem_cgroup *memcg,
 917                                            enum mem_cgroup_events_index idx)
 918{
 919        unsigned long val = 0;
 920        int cpu;
 921
 922        for_each_online_cpu(cpu)
 923                val += per_cpu(memcg->stat->events[idx], cpu);
 924#ifdef CONFIG_HOTPLUG_CPU
 925        spin_lock(&memcg->pcp_counter_lock);
 926        val += memcg->nocpu_base.events[idx];
 927        spin_unlock(&memcg->pcp_counter_lock);
 928#endif
 929        return val;
 930}
 931
 932/*
 933 * A more cacheline efficient way to accumulate all the percpu statistics
 934 * counts and events in the percpu stat->count and stat->events arrays into
 935 * the given stats and events arrays.
 936 */
 937static void mem_cgroup_sum_all_stat_events(struct mem_cgroup *memcg,
 938                                           unsigned long *stats,
 939                                           unsigned long *events)
 940{
 941        int i;
 942        int cpu;
 943
 944        get_online_cpus();
 945        for_each_online_cpu(cpu) {
 946                unsigned long *pcpu_stats = per_cpu(memcg->stat->count, cpu);
 947                unsigned long *pcpu_events = per_cpu(memcg->stat->events, cpu);
 948
 949                for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++)
 950                        stats[i] += pcpu_stats[i];
 951
 952                for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
 953                        events[i] = pcpu_events[i];
 954        }
 955
 956#ifdef CONFIG_HOTPLUG_CPU
 957        spin_lock(&memcg->pcp_counter_lock);
 958
 959        for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++)
 960                stats[i] += memcg->nocpu_base.count[i];
 961
 962        for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
 963                events[i] = memcg->nocpu_base.events[i];
 964
 965        spin_unlock(&memcg->pcp_counter_lock);
 966#endif
 967        put_online_cpus();
 968        return;
 969}
 970
 971static void mem_cgroup_charge_statistics(struct mem_cgroup *memcg,
 972                                         struct page *page,
 973                                         bool anon, int nr_pages)
 974{
 975        preempt_disable();
 976
 977        /*
 978         * Here, RSS means 'mapped anon' and anon's SwapCache. Shmem/tmpfs is
 979         * counted as CACHE even if it's on ANON LRU.
 980         */
 981        if (anon)
 982                __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS],
 983                                nr_pages);
 984        else
 985                __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_CACHE],
 986                                nr_pages);
 987
 988        if (PageTransHuge(page))
 989                __this_cpu_add(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
 990                                nr_pages);
 991
 992        /* pagein of a big page is an event. So, ignore page size */
 993        if (nr_pages > 0)
 994                __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGIN]);
 995        else {
 996                __this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGPGOUT]);
 997                nr_pages = -nr_pages; /* for event */
 998        }
 999
1000        __this_cpu_add(memcg->stat->nr_page_events, nr_pages);
1001
1002        preempt_enable();
1003}
1004
1005unsigned long
1006mem_cgroup_get_lru_size(struct lruvec *lruvec, enum lru_list lru)
1007{
1008        struct mem_cgroup_per_zone *mz;
1009
1010        mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
1011        return mz->lru_size[lru];
1012}
1013
1014static unsigned long
1015mem_cgroup_zone_nr_lru_pages(struct mem_cgroup *memcg, int nid, int zid,
1016                        unsigned int lru_mask)
1017{
1018        struct mem_cgroup_per_zone *mz;
1019        enum lru_list lru;
1020        unsigned long ret = 0;
1021
1022        mz = mem_cgroup_zoneinfo(memcg, nid, zid);
1023
1024        for_each_lru(lru) {
1025                if (BIT(lru) & lru_mask)
1026                        ret += mz->lru_size[lru];
1027        }
1028        return ret;
1029}
1030
1031static unsigned long
1032mem_cgroup_node_nr_lru_pages(struct mem_cgroup *memcg,
1033                        int nid, unsigned int lru_mask)
1034{
1035        u64 total = 0;
1036        int zid;
1037
1038        for (zid = 0; zid < MAX_NR_ZONES; zid++)
1039                total += mem_cgroup_zone_nr_lru_pages(memcg,
1040                                                nid, zid, lru_mask);
1041
1042        return total;
1043}
1044
1045static unsigned long mem_cgroup_nr_lru_pages(struct mem_cgroup *memcg,
1046                        unsigned int lru_mask)
1047{
1048        int nid;
1049        u64 total = 0;
1050
1051        for_each_node_state(nid, N_MEMORY)
1052                total += mem_cgroup_node_nr_lru_pages(memcg, nid, lru_mask);
1053        return total;
1054}
1055
1056static bool mem_cgroup_event_ratelimit(struct mem_cgroup *memcg,
1057                                       enum mem_cgroup_events_target target)
1058{
1059        unsigned long val, next;
1060
1061        val = __this_cpu_read(memcg->stat->nr_page_events);
1062        next = __this_cpu_read(memcg->stat->targets[target]);
1063        /* from time_after() in jiffies.h */
1064        if ((long)next - (long)val < 0) {
1065                switch (target) {
1066                case MEM_CGROUP_TARGET_THRESH:
1067                        next = val + THRESHOLDS_EVENTS_TARGET;
1068                        break;
1069                case MEM_CGROUP_TARGET_SOFTLIMIT:
1070                        next = val + SOFTLIMIT_EVENTS_TARGET;
1071                        break;
1072                case MEM_CGROUP_TARGET_NUMAINFO:
1073                        next = val + NUMAINFO_EVENTS_TARGET;
1074                        break;
1075                default:
1076                        break;
1077                }
1078                __this_cpu_write(memcg->stat->targets[target], next);
1079                return true;
1080        }
1081        return false;
1082}
1083
1084/*
1085 * Check events in order.
1086 *
1087 */
1088static void memcg_check_events(struct mem_cgroup *memcg, struct page *page)
1089{
1090        preempt_disable();
1091        /* threshold event is triggered in finer grain than soft limit */
1092        if (unlikely(mem_cgroup_event_ratelimit(memcg,
1093                                                MEM_CGROUP_TARGET_THRESH))) {
1094                bool do_softlimit;
1095                bool do_numainfo __maybe_unused;
1096
1097                do_softlimit = mem_cgroup_event_ratelimit(memcg,
1098                                                MEM_CGROUP_TARGET_SOFTLIMIT);
1099#if MAX_NUMNODES > 1
1100                do_numainfo = mem_cgroup_event_ratelimit(memcg,
1101                                                MEM_CGROUP_TARGET_NUMAINFO);
1102#endif
1103                preempt_enable();
1104
1105                mem_cgroup_threshold(memcg);
1106                if (unlikely(do_softlimit))
1107                        mem_cgroup_update_tree(memcg, page);
1108#if MAX_NUMNODES > 1
1109                if (unlikely(do_numainfo))
1110                        atomic_inc(&memcg->numainfo_events);
1111#endif
1112        } else
1113                preempt_enable();
1114}
1115
1116struct mem_cgroup *mem_cgroup_from_cont(struct cgroup *cont)
1117{
1118        return mem_cgroup_from_css(
1119                cgroup_subsys_state(cont, mem_cgroup_subsys_id));
1120}
1121
1122struct mem_cgroup *mem_cgroup_from_task(struct task_struct *p)
1123{
1124        /*
1125         * mm_update_next_owner() may clear mm->owner to NULL
1126         * if it races with swapoff, page migration, etc.
1127         * So this can be called with p == NULL.
1128         */
1129        if (unlikely(!p))
1130                return NULL;
1131
1132        return mem_cgroup_from_css(task_subsys_state(p, mem_cgroup_subsys_id));
1133}
1134
1135struct mem_cgroup *try_get_mem_cgroup_from_mm(struct mm_struct *mm)
1136{
1137        struct mem_cgroup *memcg = NULL;
1138
1139        if (!mm)
1140                return NULL;
1141        /*
1142         * Because we have no locks, mm->owner's may be being moved to other
1143         * cgroup. We use css_tryget() here even if this looks
1144         * pessimistic (rather than adding locks here).
1145         */
1146        rcu_read_lock();
1147        do {
1148                memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1149                if (unlikely(!memcg))
1150                        break;
1151        } while (!css_tryget(&memcg->css));
1152        rcu_read_unlock();
1153        return memcg;
1154}
1155
1156/*
1157 * Returns a next (in a pre-order walk) alive memcg (with elevated css
1158 * ref. count) or NULL if the whole root's subtree has been visited.
1159 *
1160 * helper function to be used by mem_cgroup_iter
1161 */
1162static struct mem_cgroup *__mem_cgroup_iter_next(struct mem_cgroup *root,
1163                struct mem_cgroup *last_visited)
1164{
1165        struct cgroup *prev_cgroup, *next_cgroup;
1166
1167        /*
1168         * Root is not visited by cgroup iterators so it needs an
1169         * explicit visit.
1170         */
1171        if (!last_visited)
1172                return root;
1173
1174        prev_cgroup = (last_visited == root) ? NULL
1175                : last_visited->css.cgroup;
1176skip_node:
1177        next_cgroup = cgroup_next_descendant_pre(
1178                        prev_cgroup, root->css.cgroup);
1179
1180        /*
1181         * Even if we found a group we have to make sure it is
1182         * alive. css && !memcg means that the groups should be
1183         * skipped and we should continue the tree walk.
1184         * last_visited css is safe to use because it is
1185         * protected by css_get and the tree walk is rcu safe.
1186         */
1187        if (next_cgroup) {
1188                struct mem_cgroup *mem = mem_cgroup_from_cont(
1189                                next_cgroup);
1190                if (css_tryget(&mem->css))
1191                        return mem;
1192                else {
1193                        prev_cgroup = next_cgroup;
1194                        goto skip_node;
1195                }
1196        }
1197
1198        return NULL;
1199}
1200
1201static void mem_cgroup_iter_invalidate(struct mem_cgroup *root)
1202{
1203        /*
1204         * When a group in the hierarchy below root is destroyed, the
1205         * hierarchy iterator can no longer be trusted since it might
1206         * have pointed to the destroyed group.  Invalidate it.
1207         */
1208        atomic_inc(&root->dead_count);
1209}
1210
1211static struct mem_cgroup *
1212mem_cgroup_iter_load(struct mem_cgroup_reclaim_iter *iter,
1213                     struct mem_cgroup *root,
1214                     int *sequence)
1215{
1216        struct mem_cgroup *position = NULL;
1217        /*
1218         * A cgroup destruction happens in two stages: offlining and
1219         * release.  They are separated by a RCU grace period.
1220         *
1221         * If the iterator is valid, we may still race with an
1222         * offlining.  The RCU lock ensures the object won't be
1223         * released, tryget will fail if we lost the race.
1224         */
1225        *sequence = atomic_read(&root->dead_count);
1226        if (iter->last_dead_count == *sequence) {
1227                smp_rmb();
1228                position = iter->last_visited;
1229
1230                /*
1231                 * We cannot take a reference to root because we might race
1232                 * with root removal and returning NULL would end up in
1233                 * an endless loop on the iterator user level when root
1234                 * would be returned all the time.
1235                */
1236                if (position && position != root &&
1237                                !css_tryget(&position->css))
1238
1239                        position = NULL;
1240        }
1241        return position;
1242}
1243
1244static void mem_cgroup_iter_update(struct mem_cgroup_reclaim_iter *iter,
1245                                   struct mem_cgroup *last_visited,
1246                                   struct mem_cgroup *new_position,
1247                                   struct mem_cgroup *root,
1248                                   int sequence)
1249{
1250        /* root reference counting symmetric to mem_cgroup_iter_load */
1251        if (last_visited && last_visited != root)
1252                css_put(&last_visited->css);
1253        /*
1254         * We store the sequence count from the time @last_visited was
1255         * loaded successfully instead of rereading it here so that we
1256         * don't lose destruction events in between.  We could have
1257         * raced with the destruction of @new_position after all.
1258         */
1259        iter->last_visited = new_position;
1260        smp_wmb();
1261        iter->last_dead_count = sequence;
1262}
1263
1264/**
1265 * mem_cgroup_iter - iterate over memory cgroup hierarchy
1266 * @root: hierarchy root
1267 * @prev: previously returned memcg, NULL on first invocation
1268 * @reclaim: cookie for shared reclaim walks, NULL for full walks
1269 *
1270 * Returns references to children of the hierarchy below @root, or
1271 * @root itself, or %NULL after a full round-trip.
1272 *
1273 * Caller must pass the return value in @prev on subsequent
1274 * invocations for reference counting, or use mem_cgroup_iter_break()
1275 * to cancel a hierarchy walk before the round-trip is complete.
1276 *
1277 * Reclaimers can specify a zone and a priority level in @reclaim to
1278 * divide up the memcgs in the hierarchy among all concurrent
1279 * reclaimers operating on the same zone and priority.
1280 */
1281struct mem_cgroup *mem_cgroup_iter(struct mem_cgroup *root,
1282                                   struct mem_cgroup *prev,
1283                                   struct mem_cgroup_reclaim_cookie *reclaim)
1284{
1285        struct mem_cgroup *memcg = NULL;
1286        struct mem_cgroup *last_visited = NULL;
1287
1288        if (mem_cgroup_disabled())
1289                return NULL;
1290
1291        if (!root)
1292                root = root_mem_cgroup;
1293
1294        if (prev && !reclaim)
1295                last_visited = prev;
1296
1297        if (!root->use_hierarchy && root != root_mem_cgroup) {
1298                if (prev)
1299                        goto out_css_put;
1300                return root;
1301        }
1302
1303        rcu_read_lock();
1304        while (!memcg) {
1305                struct mem_cgroup_reclaim_iter *uninitialized_var(iter);
1306                int uninitialized_var(seq);
1307
1308                if (reclaim) {
1309                        int nid = zone_to_nid(reclaim->zone);
1310                        int zid = zone_idx(reclaim->zone);
1311                        struct mem_cgroup_per_zone *mz;
1312
1313                        mz = mem_cgroup_zoneinfo(root, nid, zid);
1314                        iter = &mz->reclaim_iter[reclaim->priority];
1315                        if (prev && reclaim->generation != iter->generation) {
1316                                iter->last_visited = NULL;
1317                                goto out_unlock;
1318                        }
1319
1320                        last_visited = mem_cgroup_iter_load(iter, root, &seq);
1321                }
1322
1323                memcg = __mem_cgroup_iter_next(root, last_visited);
1324
1325                if (reclaim) {
1326                        mem_cgroup_iter_update(iter, last_visited, memcg, root,
1327                                        seq);
1328
1329                        if (!memcg)
1330                                iter->generation++;
1331                        else if (!prev && memcg)
1332                                reclaim->generation = iter->generation;
1333                }
1334
1335                if (prev && !memcg)
1336                        goto out_unlock;
1337        }
1338out_unlock:
1339        rcu_read_unlock();
1340out_css_put:
1341        if (prev && prev != root)
1342                css_put(&prev->css);
1343
1344        return memcg;
1345}
1346
1347/**
1348 * mem_cgroup_iter_break - abort a hierarchy walk prematurely
1349 * @root: hierarchy root
1350 * @prev: last visited hierarchy member as returned by mem_cgroup_iter()
1351 */
1352void mem_cgroup_iter_break(struct mem_cgroup *root,
1353                           struct mem_cgroup *prev)
1354{
1355        if (!root)
1356                root = root_mem_cgroup;
1357        if (prev && prev != root)
1358                css_put(&prev->css);
1359}
1360
1361/*
1362 * Iteration constructs for visiting all cgroups (under a tree).  If
1363 * loops are exited prematurely (break), mem_cgroup_iter_break() must
1364 * be used for reference counting.
1365 */
1366#define for_each_mem_cgroup_tree(iter, root)            \
1367        for (iter = mem_cgroup_iter(root, NULL, NULL);  \
1368             iter != NULL;                              \
1369             iter = mem_cgroup_iter(root, iter, NULL))
1370
1371#define for_each_mem_cgroup(iter)                       \
1372        for (iter = mem_cgroup_iter(NULL, NULL, NULL);  \
1373             iter != NULL;                              \
1374             iter = mem_cgroup_iter(NULL, iter, NULL))
1375
1376void __mem_cgroup_count_vm_event(struct mm_struct *mm, enum vm_event_item idx)
1377{
1378        struct mem_cgroup *memcg;
1379
1380        rcu_read_lock();
1381        memcg = mem_cgroup_from_task(rcu_dereference(mm->owner));
1382        if (unlikely(!memcg))
1383                goto out;
1384
1385        switch (idx) {
1386        case PGFAULT:
1387                this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGFAULT]);
1388                break;
1389        case PGMAJFAULT:
1390                this_cpu_inc(memcg->stat->events[MEM_CGROUP_EVENTS_PGMAJFAULT]);
1391                break;
1392        default:
1393                BUG();
1394        }
1395out:
1396        rcu_read_unlock();
1397}
1398EXPORT_SYMBOL(__mem_cgroup_count_vm_event);
1399
1400/**
1401 * mem_cgroup_zone_lruvec - get the lru list vector for a zone and memcg
1402 * @zone: zone of the wanted lruvec
1403 * @memcg: memcg of the wanted lruvec
1404 *
1405 * Returns the lru list vector holding pages for the given @zone and
1406 * @mem.  This can be the global zone lruvec, if the memory controller
1407 * is disabled.
1408 */
1409struct lruvec *mem_cgroup_zone_lruvec(struct zone *zone,
1410                                      struct mem_cgroup *memcg)
1411{
1412        struct mem_cgroup_per_zone *mz;
1413        struct lruvec *lruvec;
1414
1415        if (mem_cgroup_disabled()) {
1416                lruvec = &zone->lruvec;
1417                goto out;
1418        }
1419
1420        mz = mem_cgroup_zoneinfo(memcg, zone_to_nid(zone), zone_idx(zone));
1421        lruvec = &mz->lruvec;
1422out:
1423        /*
1424         * Since a node can be onlined after the mem_cgroup was created,
1425         * we have to be prepared to initialize lruvec->zone here;
1426         * and if offlined then reonlined, we need to reinitialize it.
1427         */
1428        if (unlikely(lruvec->zone != zone))
1429                lruvec->zone = zone;
1430        return lruvec;
1431}
1432
1433/*
1434 * Following LRU functions are allowed to be used without PCG_LOCK.
1435 * Operations are called by routine of global LRU independently from memcg.
1436 * What we have to take care of here is validness of pc->mem_cgroup.
1437 *
1438 * Changes to pc->mem_cgroup happens when
1439 * 1. charge
1440 * 2. moving account
1441 * In typical case, "charge" is done before add-to-lru. Exception is SwapCache.
1442 * It is added to LRU before charge.
1443 * If PCG_USED bit is not set, page_cgroup is not added to this private LRU.
1444 * When moving account, the page is not on LRU. It's isolated.
1445 */
1446
1447/**
1448 * mem_cgroup_page_lruvec - return lruvec for adding an lru page
1449 * @page: the page
1450 * @zone: zone of the page
1451 */
1452struct lruvec *mem_cgroup_page_lruvec(struct page *page, struct zone *zone)
1453{
1454        struct mem_cgroup_per_zone *mz;
1455        struct mem_cgroup *memcg;
1456        struct page_cgroup *pc;
1457        struct lruvec *lruvec;
1458
1459        if (mem_cgroup_disabled()) {
1460                lruvec = &zone->lruvec;
1461                goto out;
1462        }
1463
1464        pc = lookup_page_cgroup(page);
1465        memcg = pc->mem_cgroup;
1466
1467        /*
1468         * Surreptitiously switch any uncharged offlist page to root:
1469         * an uncharged page off lru does nothing to secure
1470         * its former mem_cgroup from sudden removal.
1471         *
1472         * Our caller holds lru_lock, and PageCgroupUsed is updated
1473         * under page_cgroup lock: between them, they make all uses
1474         * of pc->mem_cgroup safe.
1475         */
1476        if (!PageLRU(page) && !PageCgroupUsed(pc) && memcg != root_mem_cgroup)
1477                pc->mem_cgroup = memcg = root_mem_cgroup;
1478
1479        mz = page_cgroup_zoneinfo(memcg, page);
1480        lruvec = &mz->lruvec;
1481out:
1482        /*
1483         * Since a node can be onlined after the mem_cgroup was created,
1484         * we have to be prepared to initialize lruvec->zone here;
1485         * and if offlined then reonlined, we need to reinitialize it.
1486         */
1487        if (unlikely(lruvec->zone != zone))
1488                lruvec->zone = zone;
1489        return lruvec;
1490}
1491
1492/**
1493 * mem_cgroup_update_lru_size - account for adding or removing an lru page
1494 * @lruvec: mem_cgroup per zone lru vector
1495 * @lru: index of lru list the page is sitting on
1496 * @nr_pages: positive when adding or negative when removing
1497 *
1498 * This function must be called when a page is added to or removed from an
1499 * lru list.
1500 */
1501void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru,
1502                                int nr_pages)
1503{
1504        struct mem_cgroup_per_zone *mz;
1505        unsigned long *lru_size;
1506
1507        if (mem_cgroup_disabled())
1508                return;
1509
1510        mz = container_of(lruvec, struct mem_cgroup_per_zone, lruvec);
1511        lru_size = mz->lru_size + lru;
1512        *lru_size += nr_pages;
1513        VM_BUG_ON((long)(*lru_size) < 0);
1514}
1515
1516/*
1517 * Checks whether given mem is same or in the root_mem_cgroup's
1518 * hierarchy subtree
1519 */
1520bool __mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1521                                  struct mem_cgroup *memcg)
1522{
1523        if (root_memcg == memcg)
1524                return true;
1525        if (!root_memcg->use_hierarchy || !memcg)
1526                return false;
1527        return cgroup_is_descendant(memcg->css.cgroup, root_memcg->css.cgroup);
1528}
1529
1530static bool mem_cgroup_same_or_subtree(const struct mem_cgroup *root_memcg,
1531                                       struct mem_cgroup *memcg)
1532{
1533        bool ret;
1534
1535        rcu_read_lock();
1536        ret = __mem_cgroup_same_or_subtree(root_memcg, memcg);
1537        rcu_read_unlock();
1538        return ret;
1539}
1540
1541int task_in_mem_cgroup(struct task_struct *task, const struct mem_cgroup *memcg)
1542{
1543        int ret;
1544        struct mem_cgroup *curr = NULL;
1545        struct task_struct *p;
1546
1547        p = find_lock_task_mm(task);
1548        if (p) {
1549                curr = try_get_mem_cgroup_from_mm(p->mm);
1550                task_unlock(p);
1551        } else {
1552                /*
1553                 * All threads may have already detached their mm's, but the oom
1554                 * killer still needs to detect if they have already been oom
1555                 * killed to prevent needlessly killing additional tasks.
1556                 */
1557                task_lock(task);
1558                curr = mem_cgroup_from_task(task);
1559                if (curr)
1560                        css_get(&curr->css);
1561                task_unlock(task);
1562        }
1563        if (!curr)
1564                return 0;
1565        /*
1566         * We should check use_hierarchy of "memcg" not "curr". Because checking
1567         * use_hierarchy of "curr" here make this function true if hierarchy is
1568         * enabled in "curr" and "curr" is a child of "memcg" in *cgroup*
1569         * hierarchy(even if use_hierarchy is disabled in "memcg").
1570         */
1571        ret = mem_cgroup_same_or_subtree(memcg, curr);
1572        css_put(&curr->css);
1573        return ret;
1574}
1575
1576int mem_cgroup_inactive_anon_is_low(struct lruvec *lruvec)
1577{
1578        unsigned long inactive_ratio;
1579        unsigned long inactive;
1580        unsigned long active;
1581        unsigned long gb;
1582
1583        inactive = mem_cgroup_get_lru_size(lruvec, LRU_INACTIVE_ANON);
1584        active = mem_cgroup_get_lru_size(lruvec, LRU_ACTIVE_ANON);
1585
1586        gb = (inactive + active) >> (30 - PAGE_SHIFT);
1587        if (gb)
1588                inactive_ratio = int_sqrt(10 * gb);
1589        else
1590                inactive_ratio = 1;
1591
1592        return inactive * inactive_ratio < active;
1593}
1594
1595#define mem_cgroup_from_counter(counter, member)        \
1596        container_of(counter, struct mem_cgroup, member)
1597
1598/**
1599 * mem_cgroup_margin - calculate chargeable space of a memory cgroup
1600 * @memcg: the memory cgroup
1601 *
1602 * Returns the maximum amount of memory @mem can be charged with, in
1603 * pages.
1604 */
1605static unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
1606{
1607        unsigned long margin = 0;
1608        unsigned long count;
1609        unsigned long limit;
1610
1611        count = page_counter_read(&memcg->memory);
1612        limit = ACCESS_ONCE(memcg->memory.limit);
1613        if (count < limit)
1614                margin = limit - count;
1615
1616        if (do_swap_account) {
1617                count = page_counter_read(&memcg->memsw);
1618                limit = ACCESS_ONCE(memcg->memsw.limit);
1619                if (count <= limit)
1620                        margin = min(margin, limit - count);
1621        }
1622
1623        return margin;
1624}
1625
1626int mem_cgroup_swappiness(struct mem_cgroup *memcg)
1627{
1628        struct cgroup *cgrp = memcg->css.cgroup;
1629
1630        /* root ? */
1631        if (cgrp->parent == NULL)
1632                return vm_swappiness;
1633
1634        return memcg->swappiness;
1635}
1636
1637/*
1638 * memcg->moving_account is used for checking possibility that some thread is
1639 * calling move_account(). When a thread on CPU-A starts moving pages under
1640 * a memcg, other threads should check memcg->moving_account under
1641 * rcu_read_lock(), like this:
1642 *
1643 *         CPU-A                                    CPU-B
1644 *                                              rcu_read_lock()
1645 *         memcg->moving_account+1              if (memcg->mocing_account)
1646 *                                                   take heavy locks.
1647 *         synchronize_rcu()                    update something.
1648 *                                              rcu_read_unlock()
1649 *         start move here.
1650 */
1651
1652/* for quick checking without looking up memcg */
1653atomic_t memcg_moving __read_mostly;
1654
1655static void mem_cgroup_start_move(struct mem_cgroup *memcg)
1656{
1657        atomic_inc(&memcg_moving);
1658        atomic_inc(&memcg->moving_account);
1659        synchronize_rcu();
1660}
1661
1662static void mem_cgroup_end_move(struct mem_cgroup *memcg)
1663{
1664        /*
1665         * Now, mem_cgroup_clear_mc() may call this function with NULL.
1666         * We check NULL in callee rather than caller.
1667         */
1668        if (memcg) {
1669                atomic_dec(&memcg_moving);
1670                atomic_dec(&memcg->moving_account);
1671        }
1672}
1673
1674/*
1675 * 2 routines for checking "mem" is under move_account() or not.
1676 *
1677 * mem_cgroup_stolen() -  checking whether a cgroup is mc.from or not. This
1678 *                        is used for avoiding races in accounting.  If true,
1679 *                        pc->mem_cgroup may be overwritten.
1680 *
1681 * mem_cgroup_under_move() - checking a cgroup is mc.from or mc.to or
1682 *                        under hierarchy of moving cgroups. This is for
1683 *                        waiting at hith-memory prressure caused by "move".
1684 */
1685
1686static bool mem_cgroup_stolen(struct mem_cgroup *memcg)
1687{
1688        VM_BUG_ON(!rcu_read_lock_held());
1689        return atomic_read(&memcg->moving_account) > 0;
1690}
1691
1692static bool mem_cgroup_under_move(struct mem_cgroup *memcg)
1693{
1694        struct mem_cgroup *from;
1695        struct mem_cgroup *to;
1696        bool ret = false;
1697        /*
1698         * Unlike task_move routines, we access mc.to, mc.from not under
1699         * mutual exclusion by cgroup_mutex. Here, we take spinlock instead.
1700         */
1701        spin_lock(&mc.lock);
1702        from = mc.from;
1703        to = mc.to;
1704        if (!from)
1705                goto unlock;
1706
1707        ret = mem_cgroup_same_or_subtree(memcg, from)
1708                || mem_cgroup_same_or_subtree(memcg, to);
1709unlock:
1710        spin_unlock(&mc.lock);
1711        return ret;
1712}
1713
1714static bool mem_cgroup_wait_acct_move(struct mem_cgroup *memcg)
1715{
1716        if (mc.moving_task && current != mc.moving_task) {
1717                if (mem_cgroup_under_move(memcg)) {
1718                        DEFINE_WAIT(wait);
1719                        prepare_to_wait(&mc.waitq, &wait, TASK_INTERRUPTIBLE);
1720                        /* moving charge context might have finished. */
1721                        if (mc.moving_task)
1722                                schedule();
1723                        finish_wait(&mc.waitq, &wait);
1724                        return true;
1725                }
1726        }
1727        return false;
1728}
1729
1730/*
1731 * Take this lock when
1732 * - a code tries to modify page's memcg while it's USED.
1733 * - a code tries to modify page state accounting in a memcg.
1734 * see mem_cgroup_stolen(), too.
1735 */
1736static void move_lock_mem_cgroup(struct mem_cgroup *memcg,
1737                                  unsigned long *flags)
1738{
1739        spin_lock_irqsave(&memcg->move_lock, *flags);
1740}
1741
1742static void move_unlock_mem_cgroup(struct mem_cgroup *memcg,
1743                                unsigned long *flags)
1744{
1745        spin_unlock_irqrestore(&memcg->move_lock, *flags);
1746}
1747
1748#define K(x) ((x) << (PAGE_SHIFT-10))
1749/**
1750 * mem_cgroup_print_oom_info: Print OOM information relevant to memory controller.
1751 * @memcg: The memory cgroup that went over limit
1752 * @p: Task that is going to be killed
1753 *
1754 * NOTE: @memcg and @p's mem_cgroup can be different when hierarchy is
1755 * enabled
1756 */
1757void mem_cgroup_print_oom_info(struct mem_cgroup *memcg, struct task_struct *p)
1758{
1759        struct cgroup *task_cgrp;
1760        struct cgroup *mem_cgrp;
1761        /*
1762         * Need a buffer in BSS, can't rely on allocations. The code relies
1763         * on the assumption that OOM is serialized for memory controller.
1764         * If this assumption is broken, revisit this code.
1765         */
1766        static char memcg_name[PATH_MAX];
1767        int ret;
1768        struct mem_cgroup *iter;
1769        unsigned int i;
1770
1771        if (!p)
1772                return;
1773
1774        rcu_read_lock();
1775
1776        mem_cgrp = memcg->css.cgroup;
1777        task_cgrp = task_cgroup(p, mem_cgroup_subsys_id);
1778
1779        ret = cgroup_path(task_cgrp, memcg_name, PATH_MAX);
1780        if (ret < 0) {
1781                /*
1782                 * Unfortunately, we are unable to convert to a useful name
1783                 * But we'll still print out the usage information
1784                 */
1785                rcu_read_unlock();
1786                goto done;
1787        }
1788        rcu_read_unlock();
1789
1790        pr_info("Task in %s killed", memcg_name);
1791
1792        rcu_read_lock();
1793        ret = cgroup_path(mem_cgrp, memcg_name, PATH_MAX);
1794        if (ret < 0) {
1795                rcu_read_unlock();
1796                goto done;
1797        }
1798        rcu_read_unlock();
1799
1800        /*
1801         * Continues from above, so we don't need an KERN_ level
1802         */
1803        pr_cont(" as a result of limit of %s\n", memcg_name);
1804done:
1805
1806        pr_info("memory: usage %llukB, limit %llukB, failcnt %lu\n",
1807                K((u64)page_counter_read(&memcg->memory)),
1808                K((u64)memcg->memory.limit), memcg->memory.failcnt);
1809        pr_info("memory+swap: usage %llukB, limit %llukB, failcnt %lu\n",
1810                K((u64)page_counter_read(&memcg->memsw)),
1811                K((u64)memcg->memsw.limit), memcg->memsw.failcnt);
1812        pr_info("kmem: usage %llukB, limit %llukB, failcnt %lu\n",
1813                K((u64)page_counter_read(&memcg->kmem)),
1814                K((u64)memcg->kmem.limit), memcg->kmem.failcnt);
1815
1816        for_each_mem_cgroup_tree(iter, memcg) {
1817                pr_info("Memory cgroup stats");
1818
1819                rcu_read_lock();
1820                ret = cgroup_path(iter->css.cgroup, memcg_name, PATH_MAX);
1821                if (!ret)
1822                        pr_cont(" for %s", memcg_name);
1823                rcu_read_unlock();
1824                pr_cont(":");
1825
1826                for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
1827                        if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
1828                                continue;
1829                        pr_cont(" %s:%ldKB", mem_cgroup_stat_names[i],
1830                                K(mem_cgroup_read_stat(iter, i)));
1831                }
1832
1833                for (i = 0; i < NR_LRU_LISTS; i++)
1834                        pr_cont(" %s:%luKB", mem_cgroup_lru_names[i],
1835                                K(mem_cgroup_nr_lru_pages(iter, BIT(i))));
1836
1837                pr_cont("\n");
1838        }
1839}
1840
1841/*
1842 * This function returns the number of memcg under hierarchy tree. Returns
1843 * 1(self count) if no children.
1844 */
1845static int mem_cgroup_count_children(struct mem_cgroup *memcg)
1846{
1847        int num = 0;
1848        struct mem_cgroup *iter;
1849
1850        for_each_mem_cgroup_tree(iter, memcg)
1851                num++;
1852        return num;
1853}
1854
1855/*
1856 * Return the memory (and swap, if configured) limit for a memcg.
1857 */
1858static unsigned long mem_cgroup_get_limit(struct mem_cgroup *memcg)
1859{
1860        unsigned long limit;
1861
1862        limit = memcg->memory.limit;
1863        if (mem_cgroup_swappiness(memcg)) {
1864                unsigned long memsw_limit;
1865
1866                memsw_limit = memcg->memsw.limit;
1867                limit = min(limit + total_swap_pages, memsw_limit);
1868        }
1869        return limit;
1870}
1871
1872static void mem_cgroup_out_of_memory(struct mem_cgroup *memcg, gfp_t gfp_mask,
1873                                     int order)
1874{
1875        struct mem_cgroup *iter;
1876        unsigned long chosen_points = 0;
1877        unsigned long totalpages;
1878        unsigned int points = 0;
1879        struct task_struct *chosen = NULL;
1880
1881        /*
1882         * If current has a pending SIGKILL or is exiting, then automatically
1883         * select it.  The goal is to allow it to allocate so that it may
1884         * quickly exit and free its memory.
1885         */
1886        if (fatal_signal_pending(current) || task_will_free_mem(current)) {
1887                set_thread_flag(TIF_MEMDIE);
1888                return;
1889        }
1890
1891        check_panic_on_oom(CONSTRAINT_MEMCG, gfp_mask, order, NULL);
1892        totalpages = mem_cgroup_get_limit(memcg) ? : 1;
1893        for_each_mem_cgroup_tree(iter, memcg) {
1894                struct cgroup *cgroup = iter->css.cgroup;
1895                struct cgroup_iter it;
1896                struct task_struct *task;
1897
1898                cgroup_iter_start(cgroup, &it);
1899                while ((task = cgroup_iter_next(cgroup, &it))) {
1900                        switch (oom_scan_process_thread(task, totalpages, NULL,
1901                                                        false)) {
1902                        case OOM_SCAN_SELECT:
1903                                if (chosen)
1904                                        put_task_struct(chosen);
1905                                chosen = task;
1906                                chosen_points = ULONG_MAX;
1907                                get_task_struct(chosen);
1908                                /* fall through */
1909                        case OOM_SCAN_CONTINUE:
1910                                continue;
1911                        case OOM_SCAN_ABORT:
1912                                cgroup_iter_end(cgroup, &it);
1913                                mem_cgroup_iter_break(memcg, iter);
1914                                if (chosen)
1915                                        put_task_struct(chosen);
1916                                return;
1917                        case OOM_SCAN_OK:
1918                                break;
1919                        };
1920                        points = oom_badness(task, memcg, NULL, totalpages);
1921                        if (points > chosen_points) {
1922                                if (chosen)
1923                                        put_task_struct(chosen);
1924                                chosen = task;
1925                                chosen_points = points;
1926                                get_task_struct(chosen);
1927                        }
1928                }
1929                cgroup_iter_end(cgroup, &it);
1930        }
1931
1932        if (!chosen)
1933                return;
1934        points = chosen_points * 1000 / totalpages;
1935        oom_kill_process(chosen, gfp_mask, order, points, totalpages, memcg,
1936                         NULL, "Memory cgroup out of memory");
1937}
1938
1939static unsigned long mem_cgroup_reclaim(struct mem_cgroup *memcg,
1940                                        gfp_t gfp_mask,
1941                                        unsigned long flags)
1942{
1943        unsigned long total = 0;
1944        bool noswap = false;
1945        int loop;
1946
1947        if (flags & MEM_CGROUP_RECLAIM_NOSWAP)
1948                noswap = true;
1949        if (!(flags & MEM_CGROUP_RECLAIM_SHRINK) && memcg->memsw_is_minimum)
1950                noswap = true;
1951
1952        for (loop = 0; loop < MEM_CGROUP_MAX_RECLAIM_LOOPS; loop++) {
1953                if (loop)
1954                        drain_all_stock_async(memcg);
1955                total += try_to_free_mem_cgroup_pages(memcg, gfp_mask, noswap);
1956                /*
1957                 * Allow limit shrinkers, which are triggered directly
1958                 * by userspace, to catch signals and stop reclaim
1959                 * after minimal progress, regardless of the margin.
1960                 */
1961                if (total && (flags & MEM_CGROUP_RECLAIM_SHRINK))
1962                        break;
1963                if (mem_cgroup_margin(memcg))
1964                        break;
1965                /*
1966                 * If nothing was reclaimed after two attempts, there
1967                 * may be no reclaimable pages in this hierarchy.
1968                 */
1969                if (loop && !total)
1970                        break;
1971        }
1972        return total;
1973}
1974
1975/**
1976 * test_mem_cgroup_node_reclaimable
1977 * @memcg: the target memcg
1978 * @nid: the node ID to be checked.
1979 * @noswap : specify true here if the user wants flle only information.
1980 *
1981 * This function returns whether the specified memcg contains any
1982 * reclaimable pages on a node. Returns true if there are any reclaimable
1983 * pages in the node.
1984 */
1985static bool test_mem_cgroup_node_reclaimable(struct mem_cgroup *memcg,
1986                int nid, bool noswap)
1987{
1988        if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_FILE))
1989                return true;
1990        if (noswap || !total_swap_pages)
1991                return false;
1992        if (mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL_ANON))
1993                return true;
1994        return false;
1995
1996}
1997#if MAX_NUMNODES > 1
1998
1999/*
2000 * Always updating the nodemask is not very good - even if we have an empty
2001 * list or the wrong list here, we can start from some node and traverse all
2002 * nodes based on the zonelist. So update the list loosely once per 10 secs.
2003 *
2004 */
2005static void mem_cgroup_may_update_nodemask(struct mem_cgroup *memcg)
2006{
2007        int nid;
2008        /*
2009         * numainfo_events > 0 means there was at least NUMAINFO_EVENTS_TARGET
2010         * pagein/pageout changes since the last update.
2011         */
2012        if (!atomic_read(&memcg->numainfo_events))
2013                return;
2014        if (atomic_inc_return(&memcg->numainfo_updating) > 1)
2015                return;
2016
2017        /* make a nodemask where this memcg uses memory from */
2018        memcg->scan_nodes = node_states[N_MEMORY];
2019
2020        for_each_node_mask(nid, node_states[N_MEMORY]) {
2021
2022                if (!test_mem_cgroup_node_reclaimable(memcg, nid, false))
2023                        node_clear(nid, memcg->scan_nodes);
2024        }
2025
2026        atomic_set(&memcg->numainfo_events, 0);
2027        atomic_set(&memcg->numainfo_updating, 0);
2028}
2029
2030/*
2031 * Selecting a node where we start reclaim from. Because what we need is just
2032 * reducing usage counter, start from anywhere is O,K. Considering
2033 * memory reclaim from current node, there are pros. and cons.
2034 *
2035 * Freeing memory from current node means freeing memory from a node which
2036 * we'll use or we've used. So, it may make LRU bad. And if several threads
2037 * hit limits, it will see a contention on a node. But freeing from remote
2038 * node means more costs for memory reclaim because of memory latency.
2039 *
2040 * Now, we use round-robin. Better algorithm is welcomed.
2041 */
2042int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
2043{
2044        int node;
2045
2046        mem_cgroup_may_update_nodemask(memcg);
2047        node = memcg->last_scanned_node;
2048
2049        node = next_node(node, memcg->scan_nodes);
2050        if (node == MAX_NUMNODES)
2051                node = first_node(memcg->scan_nodes);
2052        /*
2053         * We call this when we hit limit, not when pages are added to LRU.
2054         * No LRU may hold pages because all pages are UNEVICTABLE or
2055         * memcg is too small and all pages are not on LRU. In that case,
2056         * we use curret node.
2057         */
2058        if (unlikely(node == MAX_NUMNODES))
2059                node = numa_node_id();
2060
2061        memcg->last_scanned_node = node;
2062        return node;
2063}
2064
2065/*
2066 * Check all nodes whether it contains reclaimable pages or not.
2067 * For quick scan, we make use of scan_nodes. This will allow us to skip
2068 * unused nodes. But scan_nodes is lazily updated and may not cotain
2069 * enough new information. We need to do double check.
2070 */
2071static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
2072{
2073        int nid;
2074
2075        /*
2076         * quick check...making use of scan_node.
2077         * We can skip unused nodes.
2078         */
2079        if (!nodes_empty(memcg->scan_nodes)) {
2080                for (nid = first_node(memcg->scan_nodes);
2081                     nid < MAX_NUMNODES;
2082                     nid = next_node(nid, memcg->scan_nodes)) {
2083
2084                        if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
2085                                return true;
2086                }
2087        }
2088        /*
2089         * Check rest of nodes.
2090         */
2091        for_each_node_state(nid, N_MEMORY) {
2092                if (node_isset(nid, memcg->scan_nodes))
2093                        continue;
2094                if (test_mem_cgroup_node_reclaimable(memcg, nid, noswap))
2095                        return true;
2096        }
2097        return false;
2098}
2099
2100#else
2101int mem_cgroup_select_victim_node(struct mem_cgroup *memcg)
2102{
2103        return 0;
2104}
2105
2106static bool mem_cgroup_reclaimable(struct mem_cgroup *memcg, bool noswap)
2107{
2108        return test_mem_cgroup_node_reclaimable(memcg, 0, noswap);
2109}
2110#endif
2111
2112static int mem_cgroup_soft_reclaim(struct mem_cgroup *root_memcg,
2113                                   struct zone *zone,
2114                                   gfp_t gfp_mask,
2115                                   unsigned long *total_scanned)
2116{
2117        struct mem_cgroup *victim = NULL;
2118        int total = 0;
2119        int loop = 0;
2120        unsigned long excess;
2121        unsigned long nr_scanned;
2122        struct mem_cgroup_reclaim_cookie reclaim = {
2123                .zone = zone,
2124                .priority = 0,
2125        };
2126
2127        excess = soft_limit_excess(root_memcg);
2128
2129        while (1) {
2130                victim = mem_cgroup_iter(root_memcg, victim, &reclaim);
2131                if (!victim) {
2132                        loop++;
2133                        if (loop >= 2) {
2134                                /*
2135                                 * If we have not been able to reclaim
2136                                 * anything, it might because there are
2137                                 * no reclaimable pages under this hierarchy
2138                                 */
2139                                if (!total)
2140                                        break;
2141                                /*
2142                                 * We want to do more targeted reclaim.
2143                                 * excess >> 2 is not to excessive so as to
2144                                 * reclaim too much, nor too less that we keep
2145                                 * coming back to reclaim from this cgroup
2146                                 */
2147                                if (total >= (excess >> 2) ||
2148                                        (loop > MEM_CGROUP_MAX_RECLAIM_LOOPS))
2149                                        break;
2150                        }
2151                        continue;
2152                }
2153                if (!mem_cgroup_reclaimable(victim, false))
2154                        continue;
2155                total += mem_cgroup_shrink_node_zone(victim, gfp_mask, false,
2156                                                     zone, &nr_scanned);
2157                *total_scanned += nr_scanned;
2158                if (!soft_limit_excess(root_memcg))
2159                        break;
2160        }
2161        mem_cgroup_iter_break(root_memcg, victim);
2162        return total;
2163}
2164
2165static DEFINE_SPINLOCK(memcg_oom_lock);
2166
2167/*
2168 * Check OOM-Killer is already running under our hierarchy.
2169 * If someone is running, return false.
2170 */
2171static bool mem_cgroup_oom_trylock(struct mem_cgroup *memcg)
2172{
2173        struct mem_cgroup *iter, *failed = NULL;
2174
2175        spin_lock(&memcg_oom_lock);
2176
2177        for_each_mem_cgroup_tree(iter, memcg) {
2178                if (iter->oom_lock) {
2179                        /*
2180                         * this subtree of our hierarchy is already locked
2181                         * so we cannot give a lock.
2182                         */
2183                        failed = iter;
2184                        mem_cgroup_iter_break(memcg, iter);
2185                        break;
2186                } else
2187                        iter->oom_lock = true;
2188        }
2189
2190        if (failed) {
2191                /*
2192                 * OK, we failed to lock the whole subtree so we have
2193                 * to clean up what we set up to the failing subtree
2194                 */
2195                for_each_mem_cgroup_tree(iter, memcg) {
2196                        if (iter == failed) {
2197                                mem_cgroup_iter_break(memcg, iter);
2198                                break;
2199                        }
2200                        iter->oom_lock = false;
2201                }
2202        }
2203
2204        spin_unlock(&memcg_oom_lock);
2205
2206        return !failed;
2207}
2208
2209static void mem_cgroup_oom_unlock(struct mem_cgroup *memcg)
2210{
2211        struct mem_cgroup *iter;
2212
2213        spin_lock(&memcg_oom_lock);
2214        for_each_mem_cgroup_tree(iter, memcg)
2215                iter->oom_lock = false;
2216        spin_unlock(&memcg_oom_lock);
2217}
2218
2219static void mem_cgroup_mark_under_oom(struct mem_cgroup *memcg)
2220{
2221        struct mem_cgroup *iter;
2222
2223        for_each_mem_cgroup_tree(iter, memcg)
2224                atomic_inc(&iter->under_oom);
2225}
2226
2227static void mem_cgroup_unmark_under_oom(struct mem_cgroup *memcg)
2228{
2229        struct mem_cgroup *iter;
2230
2231        /*
2232         * When a new child is created while the hierarchy is under oom,
2233         * mem_cgroup_oom_lock() may not be called. We have to use
2234         * atomic_add_unless() here.
2235         */
2236        for_each_mem_cgroup_tree(iter, memcg)
2237                atomic_add_unless(&iter->under_oom, -1, 0);
2238}
2239
2240static DECLARE_WAIT_QUEUE_HEAD(memcg_oom_waitq);
2241
2242struct oom_wait_info {
2243        struct mem_cgroup *memcg;
2244        wait_queue_t    wait;
2245};
2246
2247static int memcg_oom_wake_function(wait_queue_t *wait,
2248        unsigned mode, int sync, void *arg)
2249{
2250        struct mem_cgroup *wake_memcg = (struct mem_cgroup *)arg;
2251        struct mem_cgroup *oom_wait_memcg;
2252        struct oom_wait_info *oom_wait_info;
2253
2254        oom_wait_info = container_of(wait, struct oom_wait_info, wait);
2255        oom_wait_memcg = oom_wait_info->memcg;
2256
2257        /*
2258         * Both of oom_wait_info->memcg and wake_memcg are stable under us.
2259         * Then we can use css_is_ancestor without taking care of RCU.
2260         */
2261        if (!mem_cgroup_same_or_subtree(oom_wait_memcg, wake_memcg)
2262                && !mem_cgroup_same_or_subtree(wake_memcg, oom_wait_memcg))
2263                return 0;
2264        return autoremove_wake_function(wait, mode, sync, arg);
2265}
2266
2267static void memcg_wakeup_oom(struct mem_cgroup *memcg)
2268{
2269        atomic_inc(&memcg->oom_wakeups);
2270        /* for filtering, pass "memcg" as argument. */
2271        __wake_up(&memcg_oom_waitq, TASK_NORMAL, 0, memcg);
2272}
2273
2274static void memcg_oom_recover(struct mem_cgroup *memcg)
2275{
2276        if (memcg && atomic_read(&memcg->under_oom))
2277                memcg_wakeup_oom(memcg);
2278}
2279
2280static void mem_cgroup_oom(struct mem_cgroup *memcg, gfp_t mask, int order)
2281{
2282        if (!current->memcg_oom.may_oom)
2283                return;
2284        /*
2285         * We are in the middle of the charge context here, so we
2286         * don't want to block when potentially sitting on a callstack
2287         * that holds all kinds of filesystem and mm locks.
2288         *
2289         * Also, the caller may handle a failed allocation gracefully
2290         * (like optional page cache readahead) and so an OOM killer
2291         * invocation might not even be necessary.
2292         *
2293         * That's why we don't do anything here except remember the
2294         * OOM context and then deal with it at the end of the page
2295         * fault when the stack is unwound, the locks are released,
2296         * and when we know whether the fault was overall successful.
2297         */
2298        css_get(&memcg->css);
2299        current->memcg_oom.memcg = memcg;
2300        current->memcg_oom.gfp_mask = mask;
2301        current->memcg_oom.order = order;
2302}
2303
2304/**
2305 * mem_cgroup_oom_synchronize - complete memcg OOM handling
2306 * @handle: actually kill/wait or just clean up the OOM state
2307 *
2308 * This has to be called at the end of a page fault if the memcg OOM
2309 * handler was enabled.
2310 *
2311 * Memcg supports userspace OOM handling where failed allocations must
2312 * sleep on a waitqueue until the userspace task resolves the
2313 * situation.  Sleeping directly in the charge context with all kinds
2314 * of locks held is not a good idea, instead we remember an OOM state
2315 * in the task and mem_cgroup_oom_synchronize() has to be called at
2316 * the end of the page fault to complete the OOM handling.
2317 *
2318 * Returns %true if an ongoing memcg OOM situation was detected and
2319 * completed, %false otherwise.
2320 */
2321bool mem_cgroup_oom_synchronize(bool handle)
2322{
2323        struct mem_cgroup *memcg = current->memcg_oom.memcg;
2324        struct oom_wait_info owait;
2325        bool locked;
2326
2327        /* OOM is global, do not handle */
2328        if (!memcg)
2329                return false;
2330
2331        if (!handle)
2332                goto cleanup;
2333
2334        owait.memcg = memcg;
2335        owait.wait.flags = 0;
2336        owait.wait.func = memcg_oom_wake_function;
2337        owait.wait.private = current;
2338        INIT_LIST_HEAD(&owait.wait.task_list);
2339
2340        prepare_to_wait(&memcg_oom_waitq, &owait.wait, TASK_KILLABLE);
2341        mem_cgroup_mark_under_oom(memcg);
2342
2343        locked = mem_cgroup_oom_trylock(memcg);
2344
2345        if (locked)
2346                mem_cgroup_oom_notify(memcg);
2347
2348        if (locked && !memcg->oom_kill_disable) {
2349                mem_cgroup_unmark_under_oom(memcg);
2350                finish_wait(&memcg_oom_waitq, &owait.wait);
2351                mem_cgroup_out_of_memory(memcg, current->memcg_oom.gfp_mask,
2352                                         current->memcg_oom.order);
2353        } else {
2354                schedule();
2355                mem_cgroup_unmark_under_oom(memcg);
2356                finish_wait(&memcg_oom_waitq, &owait.wait);
2357        }
2358
2359        if (locked) {
2360                mem_cgroup_oom_unlock(memcg);
2361                /*
2362                 * There is no guarantee that an OOM-lock contender
2363                 * sees the wakeups triggered by the OOM kill
2364                 * uncharges.  Wake any sleepers explicitely.
2365                 */
2366                memcg_oom_recover(memcg);
2367        }
2368cleanup:
2369        current->memcg_oom.memcg = NULL;
2370        css_put(&memcg->css);
2371        return true;
2372}
2373
2374/*
2375 * Currently used to update mapped file statistics, but the routine can be
2376 * generalized to update other statistics as well.
2377 *
2378 * Notes: Race condition
2379 *
2380 * We usually use page_cgroup_lock() for accessing page_cgroup member but
2381 * it tends to be costly. But considering some conditions, we doesn't need
2382 * to do so _always_.
2383 *
2384 * Considering "charge", lock_page_cgroup() is not required because all
2385 * file-stat operations happen after a page is attached to radix-tree. There
2386 * are no race with "charge".
2387 *
2388 * Considering "uncharge", we know that memcg doesn't clear pc->mem_cgroup
2389 * at "uncharge" intentionally. So, we always see valid pc->mem_cgroup even
2390 * if there are race with "uncharge". Statistics itself is properly handled
2391 * by flags.
2392 *
2393 * Considering "move", this is an only case we see a race. To make the race
2394 * small, we check mm->moving_account and detect there are possibility of race
2395 * If there is, we take a lock.
2396 */
2397
2398void __mem_cgroup_begin_update_page_stat(struct page *page,
2399                                bool *locked, unsigned long *flags)
2400{
2401        struct mem_cgroup *memcg;
2402        struct page_cgroup *pc;
2403
2404        pc = lookup_page_cgroup(page);
2405again:
2406        memcg = pc->mem_cgroup;
2407        if (unlikely(!memcg || !PageCgroupUsed(pc)))
2408                return;
2409        /*
2410         * If this memory cgroup is not under account moving, we don't
2411         * need to take move_lock_mem_cgroup(). Because we already hold
2412         * rcu_read_lock(), any calls to move_account will be delayed until
2413         * rcu_read_unlock() if mem_cgroup_stolen() == true.
2414         */
2415        if (!mem_cgroup_stolen(memcg))
2416                return;
2417
2418        move_lock_mem_cgroup(memcg, flags);
2419        if (memcg != pc->mem_cgroup || !PageCgroupUsed(pc)) {
2420                move_unlock_mem_cgroup(memcg, flags);
2421                goto again;
2422        }
2423        *locked = true;
2424}
2425
2426void __mem_cgroup_end_update_page_stat(struct page *page, unsigned long *flags)
2427{
2428        struct page_cgroup *pc = lookup_page_cgroup(page);
2429
2430        /*
2431         * It's guaranteed that pc->mem_cgroup never changes while
2432         * lock is held because a routine modifies pc->mem_cgroup
2433         * should take move_lock_mem_cgroup().
2434         */
2435        move_unlock_mem_cgroup(pc->mem_cgroup, flags);
2436}
2437
2438void mem_cgroup_update_page_stat(struct page *page,
2439                                 enum mem_cgroup_page_stat_item idx, int val)
2440{
2441        struct mem_cgroup *memcg;
2442        struct page_cgroup *pc = lookup_page_cgroup(page);
2443        unsigned long uninitialized_var(flags);
2444
2445        if (mem_cgroup_disabled())
2446                return;
2447
2448        memcg = pc->mem_cgroup;
2449        if (unlikely(!memcg || !PageCgroupUsed(pc)))
2450                return;
2451
2452        switch (idx) {
2453        case MEMCG_NR_FILE_MAPPED:
2454                idx = MEM_CGROUP_STAT_FILE_MAPPED;
2455                break;
2456        default:
2457                BUG();
2458        }
2459
2460        this_cpu_add(memcg->stat->count[idx], val);
2461}
2462
2463/*
2464 * size of first charge trial. "32" comes from vmscan.c's magic value.
2465 * TODO: maybe necessary to use big numbers in big irons.
2466 */
2467#define CHARGE_BATCH    32U
2468struct memcg_stock_pcp {
2469        struct mem_cgroup *cached; /* this never be root cgroup */
2470        unsigned int nr_pages;
2471        struct work_struct work;
2472        unsigned long flags;
2473#define FLUSHING_CACHED_CHARGE  0
2474};
2475static DEFINE_PER_CPU(struct memcg_stock_pcp, memcg_stock);
2476static DEFINE_MUTEX(percpu_charge_mutex);
2477
2478/**
2479 * consume_stock: Try to consume stocked charge on this cpu.
2480 * @memcg: memcg to consume from.
2481 * @nr_pages: how many pages to charge.
2482 *
2483 * The charges will only happen if @memcg matches the current cpu's memcg
2484 * stock, and at least @nr_pages are available in that stock.  Failure to
2485 * service an allocation will refill the stock.
2486 *
2487 * returns true if successful, false otherwise.
2488 */
2489static bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2490{
2491        struct memcg_stock_pcp *stock;
2492        bool ret = false;
2493
2494        if (nr_pages > CHARGE_BATCH)
2495                return ret;
2496
2497        stock = &get_cpu_var(memcg_stock);
2498        if (memcg == stock->cached && stock->nr_pages >= nr_pages) {
2499                stock->nr_pages -= nr_pages;
2500                ret = true;
2501        }
2502        put_cpu_var(memcg_stock);
2503        return ret;
2504}
2505
2506/*
2507 * Returns stocks cached in percpu and reset cached information.
2508 */
2509static void drain_stock(struct memcg_stock_pcp *stock)
2510{
2511        struct mem_cgroup *old = stock->cached;
2512
2513        if (stock->nr_pages) {
2514                page_counter_uncharge(&old->memory, stock->nr_pages);
2515                if (do_swap_account)
2516                        page_counter_uncharge(&old->memsw, stock->nr_pages);
2517                stock->nr_pages = 0;
2518        }
2519        stock->cached = NULL;
2520}
2521
2522/*
2523 * This must be called under preempt disabled or must be called by
2524 * a thread which is pinned to local cpu.
2525 */
2526static void drain_local_stock(struct work_struct *dummy)
2527{
2528        struct memcg_stock_pcp *stock = this_cpu_ptr(&memcg_stock);
2529        drain_stock(stock);
2530        clear_bit(FLUSHING_CACHED_CHARGE, &stock->flags);
2531}
2532
2533static void __init memcg_stock_init(void)
2534{
2535        int cpu;
2536
2537        for_each_possible_cpu(cpu) {
2538                struct memcg_stock_pcp *stock =
2539                                        &per_cpu(memcg_stock, cpu);
2540                INIT_WORK(&stock->work, drain_local_stock);
2541        }
2542}
2543
2544/*
2545 * Cache charges(val) to local per_cpu area.
2546 * This will be consumed by consume_stock() function, later.
2547 */
2548static void refill_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
2549{
2550        struct memcg_stock_pcp *stock = &get_cpu_var(memcg_stock);
2551
2552        if (stock->cached != memcg) { /* reset if necessary */
2553                drain_stock(stock);
2554                stock->cached = memcg;
2555        }
2556        stock->nr_pages += nr_pages;
2557        put_cpu_var(memcg_stock);
2558}
2559
2560/*
2561 * Drains all per-CPU charge caches for given root_memcg resp. subtree
2562 * of the hierarchy under it. sync flag says whether we should block
2563 * until the work is done.
2564 */
2565static void drain_all_stock(struct mem_cgroup *root_memcg, bool sync)
2566{
2567        int cpu, curcpu;
2568
2569        /* Notify other cpus that system-wide "drain" is running */
2570        get_online_cpus();
2571        curcpu = get_cpu();
2572        for_each_online_cpu(cpu) {
2573                struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2574                struct mem_cgroup *memcg;
2575
2576                memcg = stock->cached;
2577                if (!memcg || !stock->nr_pages)
2578                        continue;
2579                if (!mem_cgroup_same_or_subtree(root_memcg, memcg))
2580                        continue;
2581                if (!test_and_set_bit(FLUSHING_CACHED_CHARGE, &stock->flags)) {
2582                        if (cpu == curcpu)
2583                                drain_local_stock(&stock->work);
2584                        else
2585                                schedule_work_on(cpu, &stock->work);
2586                }
2587        }
2588        put_cpu();
2589
2590        if (!sync)
2591                goto out;
2592
2593        for_each_online_cpu(cpu) {
2594                struct memcg_stock_pcp *stock = &per_cpu(memcg_stock, cpu);
2595                if (test_bit(FLUSHING_CACHED_CHARGE, &stock->flags))
2596                        flush_work(&stock->work);
2597        }
2598out:
2599        put_online_cpus();
2600}
2601
2602/*
2603 * Tries to drain stocked charges in other cpus. This function is asynchronous
2604 * and just put a work per cpu for draining localy on each cpu. Caller can
2605 * expects some charges will be back later but cannot wait for it.
2606 */
2607static void drain_all_stock_async(struct mem_cgroup *root_memcg)
2608{
2609        /*
2610         * If someone calls draining, avoid adding more kworker runs.
2611         */
2612        if (!mutex_trylock(&percpu_charge_mutex))
2613                return;
2614        drain_all_stock(root_memcg, false);
2615        mutex_unlock(&percpu_charge_mutex);
2616}
2617
2618/* This is a synchronous drain interface. */
2619static void drain_all_stock_sync(struct mem_cgroup *root_memcg)
2620{
2621        /* called when force_empty is called */
2622        mutex_lock(&percpu_charge_mutex);
2623        drain_all_stock(root_memcg, true);
2624        mutex_unlock(&percpu_charge_mutex);
2625}
2626
2627/*
2628 * This function drains percpu counter value from DEAD cpu and
2629 * move it to local cpu. Note that this function can be preempted.
2630 */
2631static void mem_cgroup_drain_pcp_counter(struct mem_cgroup *memcg, int cpu)
2632{
2633        int i;
2634
2635        spin_lock(&memcg->pcp_counter_lock);
2636        for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
2637                long x = per_cpu(memcg->stat->count[i], cpu);
2638
2639                per_cpu(memcg->stat->count[i], cpu) = 0;
2640                memcg->nocpu_base.count[i] += x;
2641        }
2642        for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++) {
2643                unsigned long x = per_cpu(memcg->stat->events[i], cpu);
2644
2645                per_cpu(memcg->stat->events[i], cpu) = 0;
2646                memcg->nocpu_base.events[i] += x;
2647        }
2648        spin_unlock(&memcg->pcp_counter_lock);
2649}
2650
2651static int memcg_cpu_hotplug_callback(struct notifier_block *nb,
2652                                        unsigned long action,
2653                                        void *hcpu)
2654{
2655        int cpu = (unsigned long)hcpu;
2656        struct memcg_stock_pcp *stock;
2657        struct mem_cgroup *iter;
2658
2659        if (action == CPU_ONLINE)
2660                return NOTIFY_OK;
2661
2662        if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
2663                return NOTIFY_OK;
2664
2665        for_each_mem_cgroup(iter)
2666                mem_cgroup_drain_pcp_counter(iter, cpu);
2667
2668        stock = &per_cpu(memcg_stock, cpu);
2669        drain_stock(stock);
2670        return NOTIFY_OK;
2671}
2672
2673
2674/* See __mem_cgroup_try_charge() for details */
2675enum {
2676        CHARGE_OK,              /* success */
2677        CHARGE_RETRY,           /* need to retry but retry is not bad */
2678        CHARGE_NOMEM,           /* we can't do more. return -ENOMEM */
2679        CHARGE_WOULDBLOCK,      /* GFP_WAIT wasn't set and no enough res. */
2680};
2681
2682static int mem_cgroup_do_charge(struct mem_cgroup *memcg, gfp_t gfp_mask,
2683                                unsigned int nr_pages, unsigned int min_pages,
2684                                bool invoke_oom)
2685{
2686        struct mem_cgroup *mem_over_limit;
2687        struct page_counter *counter;
2688        unsigned long flags = 0;
2689        int ret = -ENOMEM;
2690
2691        if (likely(page_counter_try_charge(&memcg->memory, nr_pages,
2692                                           &counter))) {
2693                if (!do_swap_account)
2694                        return CHARGE_OK;
2695                if (likely(page_counter_try_charge(&memcg->memsw, nr_pages,
2696                                                   &counter)))
2697                        return CHARGE_OK;
2698
2699                page_counter_uncharge(&memcg->memory, nr_pages);
2700                mem_over_limit = mem_cgroup_from_counter(counter, memsw);
2701                flags |= MEM_CGROUP_RECLAIM_NOSWAP;
2702        } else
2703                mem_over_limit = mem_cgroup_from_counter(counter, memory);
2704        /*
2705         * Never reclaim on behalf of optional batching, retry with a
2706         * single page instead.
2707         */
2708        if (nr_pages > min_pages)
2709                return CHARGE_RETRY;
2710
2711        if (!(gfp_mask & __GFP_WAIT))
2712                return CHARGE_WOULDBLOCK;
2713
2714        if (gfp_mask & __GFP_NORETRY)
2715                return CHARGE_NOMEM;
2716
2717        ret = mem_cgroup_reclaim(mem_over_limit, gfp_mask, flags);
2718        if (mem_cgroup_margin(mem_over_limit) >= nr_pages)
2719                return CHARGE_RETRY;
2720        /*
2721         * Even though the limit is exceeded at this point, reclaim
2722         * may have been able to free some pages.  Retry the charge
2723         * before killing the task.
2724         *
2725         * Only for regular pages, though: huge pages are rather
2726         * unlikely to succeed so close to the limit, and we fall back
2727         * to regular pages anyway in case of failure.
2728         */
2729        if (nr_pages <= (1 << PAGE_ALLOC_COSTLY_ORDER) && ret)
2730                return CHARGE_RETRY;
2731
2732        /*
2733         * At task move, charge accounts can be doubly counted. So, it's
2734         * better to wait until the end of task_move if something is going on.
2735         */
2736        if (mem_cgroup_wait_acct_move(mem_over_limit))
2737                return CHARGE_RETRY;
2738
2739        if (invoke_oom)
2740                mem_cgroup_oom(mem_over_limit, gfp_mask,
2741                               get_order(nr_pages * PAGE_SIZE));
2742
2743        return CHARGE_NOMEM;
2744}
2745
2746/*
2747 * __mem_cgroup_try_charge() does
2748 * 1. detect memcg to be charged against from passed *mm and *ptr,
2749 * 2. update page_counter
2750 * 3. call memory reclaim if necessary.
2751 *
2752 * In some special case, if the task is fatal, fatal_signal_pending() or
2753 * has TIF_MEMDIE, this function returns -EINTR while writing root_mem_cgroup
2754 * to *ptr. There are two reasons for this. 1: fatal threads should quit as soon
2755 * as possible without any hazards. 2: all pages should have a valid
2756 * pc->mem_cgroup. If mm is NULL and the caller doesn't pass a valid memcg
2757 * pointer, that is treated as a charge to root_mem_cgroup.
2758 *
2759 * So __mem_cgroup_try_charge() will return
2760 *  0       ...  on success, filling *ptr with a valid memcg pointer.
2761 *  -ENOMEM ...  charge failure because of resource limits.
2762 *  -EINTR  ...  if thread is fatal. *ptr is filled with root_mem_cgroup.
2763 *
2764 * Unlike the exported interface, an "oom" parameter is added. if oom==true,
2765 * the oom-killer can be invoked.
2766 */
2767static int __mem_cgroup_try_charge(struct mm_struct *mm,
2768                                   gfp_t gfp_mask,
2769                                   unsigned int nr_pages,
2770                                   struct mem_cgroup **ptr,
2771                                   bool oom)
2772{
2773        unsigned int batch = max(CHARGE_BATCH, nr_pages);
2774        int nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;
2775        struct mem_cgroup *memcg = NULL;
2776        int ret;
2777
2778        /*
2779         * Unlike gloval-vm's OOM-kill, we're not in memory shortage
2780         * in system level. So, allow to go ahead dying process in addition to
2781         * MEMDIE process.
2782         */
2783        if (unlikely(test_thread_flag(TIF_MEMDIE)
2784                     || fatal_signal_pending(current)))
2785                goto bypass;
2786
2787        /*
2788         * Prevent unbounded recursion when reclaim operations need to
2789         * allocate memory. This might exceed the limits temporarily,
2790         * but we prefer facilitating memory reclaim and getting back
2791         * under the limit over triggering OOM kills in these cases.
2792         */
2793        if (unlikely(current->flags & PF_MEMALLOC))
2794                goto bypass;
2795
2796        if (unlikely(task_in_memcg_oom(current)))
2797                goto nomem;
2798
2799        if (gfp_mask & __GFP_NOFAIL)
2800                oom = false;
2801
2802        /*
2803         * We always charge the cgroup the mm_struct belongs to.
2804         * The mm_struct's mem_cgroup changes on task migration if the
2805         * thread group leader migrates. It's possible that mm is not
2806         * set, if so charge the root memcg (happens for pagecache usage).
2807         */
2808        if (!*ptr && !mm)
2809                *ptr = root_mem_cgroup;
2810again:
2811        if (*ptr) { /* css should be a valid one */
2812                memcg = *ptr;
2813                if (mem_cgroup_is_root(memcg))
2814                        goto done;
2815                if (consume_stock(memcg, nr_pages))
2816                        goto done;
2817                css_get(&memcg->css);
2818        } else {
2819                struct task_struct *p;
2820
2821                rcu_read_lock();
2822                p = rcu_dereference(mm->owner);
2823                /*
2824                 * Because we don't have task_lock(), "p" can exit.
2825                 * In that case, "memcg" can point to root or p can be NULL with
2826                 * race with swapoff. Then, we have small risk of mis-accouning.
2827                 * But such kind of mis-account by race always happens because
2828                 * we don't have cgroup_mutex(). It's overkill and we allo that
2829                 * small race, here.
2830                 * (*) swapoff at el will charge against mm-struct not against
2831                 * task-struct. So, mm->owner can be NULL.
2832                 */
2833                memcg = mem_cgroup_from_task(p);
2834                if (!memcg)
2835                        memcg = root_mem_cgroup;
2836                if (mem_cgroup_is_root(memcg)) {
2837                        rcu_read_unlock();
2838                        goto done;
2839                }
2840                if (consume_stock(memcg, nr_pages)) {
2841                        /*
2842                         * It seems dagerous to access memcg without css_get().
2843                         * But considering how consume_stok works, it's not
2844                         * necessary. If consume_stock success, some charges
2845                         * from this memcg are cached on this cpu. So, we
2846                         * don't need to call css_get()/css_tryget() before
2847                         * calling consume_stock().
2848                         */
2849                        rcu_read_unlock();
2850                        goto done;
2851                }
2852                /* after here, we may be blocked. we need to get refcnt */
2853                if (!css_tryget(&memcg->css)) {
2854                        rcu_read_unlock();
2855                        goto again;
2856                }
2857                rcu_read_unlock();
2858        }
2859
2860        do {
2861                bool invoke_oom = oom && !nr_oom_retries;
2862
2863                /* If killed, bypass charge */
2864                if (fatal_signal_pending(current)) {
2865                        css_put(&memcg->css);
2866                        goto bypass;
2867                }
2868
2869                ret = mem_cgroup_do_charge(memcg, gfp_mask, batch,
2870                                           nr_pages, invoke_oom);
2871                switch (ret) {
2872                case CHARGE_OK:
2873                        break;
2874                case CHARGE_RETRY: /* not in OOM situation but retry */
2875                        batch = nr_pages;
2876                        css_put(&memcg->css);
2877                        memcg = NULL;
2878                        goto again;
2879                case CHARGE_WOULDBLOCK: /* !__GFP_WAIT */
2880                        css_put(&memcg->css);
2881                        goto nomem;
2882                case CHARGE_NOMEM: /* OOM routine works */
2883                        if (!oom || invoke_oom) {
2884                                css_put(&memcg->css);
2885                                goto nomem;
2886                        }
2887                        nr_oom_retries--;
2888                        break;
2889                }
2890        } while (ret != CHARGE_OK);
2891
2892        if (batch > nr_pages)
2893                refill_stock(memcg, batch - nr_pages);
2894        css_put(&memcg->css);
2895done:
2896        *ptr = memcg;
2897        return 0;
2898nomem:
2899        if (!(gfp_mask & __GFP_NOFAIL)) {
2900                *ptr = NULL;
2901                return -ENOMEM;
2902        }
2903bypass:
2904        *ptr = root_mem_cgroup;
2905        return -EINTR;
2906}
2907
2908/*
2909 * Somemtimes we have to undo a charge we got by try_charge().
2910 * This function is for that and do uncharge, put css's refcnt.
2911 * gotten by try_charge().
2912 */
2913static void __mem_cgroup_cancel_charge(struct mem_cgroup *memcg,
2914                                       unsigned int nr_pages)
2915{
2916        if (!mem_cgroup_is_root(memcg)) {
2917                page_counter_uncharge(&memcg->memory, nr_pages);
2918                if (do_swap_account)
2919                        page_counter_uncharge(&memcg->memsw, nr_pages);
2920        }
2921}
2922
2923struct mem_cgroup *mem_cgroup_from_id(unsigned short id);
2924/*
2925 * A helper function to get mem_cgroup from ID. must be called under
2926 * rcu_read_lock().  The caller is responsible for calling css_tryget if
2927 * the mem_cgroup is used for charging. (dropping refcnt from swap can be
2928 * called against removed memcg.)
2929 */
2930static struct mem_cgroup *mem_cgroup_lookup(unsigned short id)
2931{
2932        /* ID 0 is unused ID */
2933        if (!id)
2934                return NULL;
2935        return mem_cgroup_from_id(id);
2936}
2937
2938struct mem_cgroup *try_get_mem_cgroup_from_page(struct page *page)
2939{
2940        struct mem_cgroup *memcg = NULL;
2941        struct page_cgroup *pc;
2942        unsigned short id;
2943        swp_entry_t ent;
2944
2945        VM_BUG_ON_PAGE(!PageLocked(page), page);
2946
2947        pc = lookup_page_cgroup(page);
2948        lock_page_cgroup(pc);
2949        if (PageCgroupUsed(pc)) {
2950                memcg = pc->mem_cgroup;
2951                if (memcg && !css_tryget(&memcg->css))
2952                        memcg = NULL;
2953        } else if (PageSwapCache(page)) {
2954                ent.val = page_private(page);
2955                id = lookup_swap_cgroup_id(ent);
2956                rcu_read_lock();
2957                memcg = mem_cgroup_lookup(id);
2958                if (memcg && !css_tryget(&memcg->css))
2959                        memcg = NULL;
2960                rcu_read_unlock();
2961        }
2962        unlock_page_cgroup(pc);
2963        return memcg;
2964}
2965
2966static void __mem_cgroup_commit_charge(struct mem_cgroup *memcg,
2967                                       struct page *page,
2968                                       unsigned int nr_pages,
2969                                       enum charge_type ctype,
2970                                       bool lrucare)
2971{
2972        struct page_cgroup *pc = lookup_page_cgroup(page);
2973        struct zone *uninitialized_var(zone);
2974        struct lruvec *lruvec;
2975        bool was_on_lru = false;
2976        bool anon;
2977
2978        lock_page_cgroup(pc);
2979        VM_BUG_ON_PAGE(PageCgroupUsed(pc), page);
2980        /*
2981         * we don't need page_cgroup_lock about tail pages, becase they are not
2982         * accessed by any other context at this point.
2983         */
2984
2985        /*
2986         * In some cases, SwapCache and FUSE(splice_buf->radixtree), the page
2987         * may already be on some other mem_cgroup's LRU.  Take care of it.
2988         */
2989        if (lrucare) {
2990                zone = page_zone(page);
2991                spin_lock_irq(&zone->lru_lock);
2992                if (PageLRU(page)) {
2993                        lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
2994                        ClearPageLRU(page);
2995                        del_page_from_lru_list(page, lruvec, page_lru(page));
2996                        was_on_lru = true;
2997                }
2998        }
2999
3000        pc->mem_cgroup = memcg;
3001        /*
3002         * We access a page_cgroup asynchronously without lock_page_cgroup().
3003         * Especially when a page_cgroup is taken from a page, pc->mem_cgroup
3004         * is accessed after testing USED bit. To make pc->mem_cgroup visible
3005         * before USED bit, we need memory barrier here.
3006         * See mem_cgroup_add_lru_list(), etc.
3007         */
3008        smp_wmb();
3009        SetPageCgroupUsed(pc);
3010
3011        if (lrucare) {
3012                if (was_on_lru) {
3013                        lruvec = mem_cgroup_zone_lruvec(zone, pc->mem_cgroup);
3014                        VM_BUG_ON_PAGE(PageLRU(page), page);
3015                        SetPageLRU(page);
3016                        add_page_to_lru_list(page, lruvec, page_lru(page));
3017                }
3018                spin_unlock_irq(&zone->lru_lock);
3019        }
3020
3021        if (ctype == MEM_CGROUP_CHARGE_TYPE_ANON)
3022                anon = true;
3023        else
3024                anon = false;
3025
3026        mem_cgroup_charge_statistics(memcg, page, anon, nr_pages);
3027        unlock_page_cgroup(pc);
3028
3029        /*
3030         * "charge_statistics" updated event counter. Then, check it.
3031         * Insert ancestor (and ancestor's ancestors), to softlimit RB-tree.
3032         * if they exceeds softlimit.
3033         */
3034        memcg_check_events(memcg, page);
3035}
3036
3037#ifdef CONFIG_MEMCG_KMEM
3038/*
3039 * The memcg_slab_mutex is held whenever a per memcg kmem cache is created or
3040 * destroyed. It protects memcg_caches arrays and memcg_slab_caches lists.
3041 */
3042static DEFINE_MUTEX(memcg_slab_mutex);
3043
3044static inline bool memcg_can_account_kmem(struct mem_cgroup *memcg)
3045{
3046        return !cgroup_memory_nokmem && !mem_cgroup_disabled() &&
3047                !mem_cgroup_is_root(memcg) &&
3048                memcg_kmem_is_active(memcg);
3049}
3050
3051/*
3052 * This is a bit cumbersome, but it is rarely used and avoids a backpointer
3053 * in the memcg_cache_params struct.
3054 */
3055static struct kmem_cache *memcg_params_to_cache(struct memcg_cache_params *p)
3056{
3057        struct kmem_cache *cachep;
3058
3059        VM_BUG_ON(p->is_root_cache);
3060        cachep = p->root_cache;
3061        return cache_from_memcg_idx(cachep, memcg_cache_id(p->memcg));
3062}
3063
3064#ifdef CONFIG_SLABINFO
3065static int mem_cgroup_slabinfo_read(struct cgroup *cont, struct cftype *cft,
3066                                        struct seq_file *m)
3067{
3068        struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
3069        struct memcg_cache_params *params;
3070
3071        if (!memcg_can_account_kmem(memcg))
3072                return -EIO;
3073
3074        print_slabinfo_header(m);
3075
3076        mutex_lock(&memcg_slab_mutex);
3077        list_for_each_entry(params, &memcg->memcg_slab_caches, list)
3078                cache_show(memcg_params_to_cache(params), m);
3079        mutex_unlock(&memcg_slab_mutex);
3080
3081        return 0;
3082}
3083#endif
3084
3085int memcg_charge_kmem(struct mem_cgroup *memcg, gfp_t gfp,
3086                             unsigned long nr_pages)
3087{
3088        struct page_counter *counter;
3089        struct mem_cgroup *_memcg;
3090        int ret = 0;
3091        bool may_oom;
3092
3093        if (!page_counter_try_charge(&memcg->kmem, nr_pages, &counter))
3094                return -ENOMEM;
3095
3096        /*
3097         * Conditions under which we can wait for the oom_killer. Those are
3098         * the same conditions tested by the core page allocator
3099         */
3100        may_oom = (gfp & __GFP_FS) && !(gfp & __GFP_NORETRY);
3101
3102        _memcg = memcg;
3103        ret = __mem_cgroup_try_charge(NULL, gfp, nr_pages, &_memcg, may_oom);
3104
3105        if (ret == -EINTR)  {
3106                /*
3107                 * __mem_cgroup_try_charge() chosed to bypass to root due to
3108                 * OOM kill or fatal signal.  Since our only options are to
3109                 * either fail the allocation or charge it to this cgroup, do
3110                 * it as a temporary condition. But we can't fail. From a
3111                 * kmem/slab perspective, the cache has already been selected,
3112                 * by mem_cgroup_kmem_get_cache(), so it is too late to change
3113                 * our minds.
3114                 *
3115                 * This condition will only trigger if the task entered
3116                 * memcg_charge_kmem in a sane state, but was OOM-killed during
3117                 * __mem_cgroup_try_charge() above. Tasks that were already
3118                 * dying when the allocation triggers should have been already
3119                 * directed to the root cgroup in memcontrol.h
3120                 */
3121                page_counter_charge(&memcg->memory, nr_pages);
3122                if (do_swap_account)
3123                        page_counter_charge(&memcg->memsw, nr_pages);
3124                ret = 0;
3125        } else if (ret)
3126                page_counter_uncharge(&memcg->kmem, nr_pages);
3127
3128        return ret;
3129}
3130
3131void memcg_uncharge_kmem(struct mem_cgroup *memcg,
3132                                unsigned long nr_pages)
3133{
3134        page_counter_uncharge(&memcg->memory, nr_pages);
3135        if (do_swap_account)
3136                page_counter_uncharge(&memcg->memsw, nr_pages);
3137
3138        /* Not down to 0 */
3139        if (page_counter_uncharge(&memcg->kmem, nr_pages))
3140                return;
3141
3142        if (memcg_kmem_test_and_clear_dead(memcg))
3143                mem_cgroup_put(memcg);
3144}
3145
3146/*
3147 * helper for acessing a memcg's index. It will be used as an index in the
3148 * child cache array in kmem_cache, and also to derive its name. This function
3149 * will return -1 when this is not a kmem-limited memcg.
3150 */
3151int memcg_cache_id(struct mem_cgroup *memcg)
3152{
3153        return memcg ? memcg->kmemcg_id : -1;
3154}
3155
3156/*
3157 * This ends up being protected by the set_limit mutex, during normal
3158 * operation, because that is its main call site.
3159 *
3160 * But when we create a new cache, we can call this as well if its parent
3161 * is kmem-limited. That will have to hold set_limit_mutex as well.
3162 */
3163static int memcg_update_cache_sizes(struct mem_cgroup *memcg)
3164{
3165        int num, ret;
3166
3167        num = ida_simple_get(&kmem_limited_groups,
3168                                0, MEMCG_CACHES_MAX_SIZE, GFP_KERNEL);
3169        if (num < 0)
3170                return num;
3171
3172        mutex_lock(&memcg_slab_mutex);
3173        ret = memcg_update_all_caches(num+1);
3174        mutex_unlock(&memcg_slab_mutex);
3175        if (ret) {
3176                ida_simple_remove(&kmem_limited_groups, num);
3177                return ret;
3178        }
3179
3180        memcg->kmemcg_id = num;
3181        INIT_LIST_HEAD(&memcg->memcg_slab_caches);
3182        return 0;
3183}
3184
3185static size_t memcg_caches_array_size(int num_groups)
3186{
3187        ssize_t size;
3188        if (num_groups <= 0)
3189                return 0;
3190
3191        size = 2 * num_groups;
3192        if (size < MEMCG_CACHES_MIN_SIZE)
3193                size = MEMCG_CACHES_MIN_SIZE;
3194        else if (size > MEMCG_CACHES_MAX_SIZE)
3195                size = MEMCG_CACHES_MAX_SIZE;
3196
3197        return size;
3198}
3199
3200/*
3201 * We should update the current array size iff all caches updates succeed. This
3202 * can only be done from the slab side. The slab mutex needs to be held when
3203 * calling this.
3204 */
3205void memcg_update_array_size(int num)
3206{
3207        if (num > memcg_limited_groups_array_size)
3208                memcg_limited_groups_array_size = memcg_caches_array_size(num);
3209}
3210
3211int memcg_update_cache_size(struct kmem_cache *s, int num_groups)
3212{
3213        struct memcg_cache_params *cur_params = s->memcg_params;
3214
3215        VM_BUG_ON(s->memcg_params && !s->memcg_params->is_root_cache);
3216        /*
3217         * Need to do this if we are increasing the size or there are
3218         * kmem_caches with null memcg_params otherwise we will dereference
3219         * in  __memcg_kmem_get_cache()
3220         */
3221        if (num_groups > memcg_limited_groups_array_size || !cur_params) {
3222                int i;
3223                struct memcg_cache_params *new_params;
3224                ssize_t size = memcg_caches_array_size(num_groups);
3225
3226                size *= sizeof(void *);
3227                size += sizeof(struct memcg_cache_params);
3228
3229                new_params = kzalloc(size, GFP_KERNEL);
3230                if (!new_params)
3231                        return -ENOMEM;
3232
3233                new_params->is_root_cache = true;
3234
3235                /* if there was no kmem_cache->memcg_params, first time so we are done */
3236                if (!cur_params)
3237                        goto out;
3238
3239                /*
3240                 * There is the chance it will be bigger than
3241                 * memcg_limited_groups_array_size, if we failed an allocation
3242                 * in a cache, in which case all caches updated before it, will
3243                 * have a bigger array.
3244                 *
3245                 * But if that is the case, the data after
3246                 * memcg_limited_groups_array_size is certainly unused
3247                 */
3248                for (i = 0; i < memcg_limited_groups_array_size; i++) {
3249                        if (!cur_params->memcg_caches[i])
3250                                continue;
3251                        new_params->memcg_caches[i] =
3252                                                cur_params->memcg_caches[i];
3253                }
3254
3255                /*
3256                 * Ideally, we would wait until all caches succeed, and only
3257                 * then free the old one. But this is not worth the extra
3258                 * pointer per-cache we'd have to have for this.
3259                 *
3260                 * It is not a big deal if some caches are left with a size
3261                 * bigger than the others. And all updates will reset this
3262                 * anyway.
3263                 */
3264out:
3265                rcu_assign_pointer(s->memcg_params, new_params);
3266                if (cur_params)
3267                        kfree_rcu(cur_params, rcu_head);
3268        }
3269        return 0;
3270}
3271
3272char *memcg_create_cache_name(struct mem_cgroup *memcg,
3273                              struct kmem_cache *root_cache)
3274{
3275        const char *name;
3276
3277        /*
3278         * We need a mutex here to protect the shared buffer. Since this is
3279         * expected to be called only on cache creation, we can employ the
3280         * slab_mutex for that purpose.
3281         */
3282        lockdep_assert_held(&slab_mutex);
3283
3284        rcu_read_lock();
3285        name = cgroup_name(memcg->css.cgroup);
3286        rcu_read_unlock();
3287        return kasprintf(GFP_KERNEL, "%s(%d:%s)", root_cache->name,
3288                         memcg_cache_id(memcg), name);
3289}
3290
3291int memcg_alloc_cache_params(struct mem_cgroup *memcg, struct kmem_cache *s,
3292                             struct kmem_cache *root_cache)
3293{
3294        size_t size = sizeof(struct memcg_cache_params);
3295
3296        if (!memcg_kmem_enabled())
3297                return 0;
3298
3299        if (!memcg)
3300                size += memcg_limited_groups_array_size * sizeof(void *);
3301
3302        s->memcg_params = kzalloc(size, GFP_KERNEL);
3303        if (!s->memcg_params)
3304                return -ENOMEM;
3305
3306        if (memcg) {
3307                s->memcg_params->memcg = memcg;
3308                s->memcg_params->root_cache = root_cache;
3309        } else
3310                s->memcg_params->is_root_cache = true;
3311
3312        return 0;
3313}
3314
3315void memcg_free_cache_params(struct kmem_cache *s)
3316{
3317        kfree(s->memcg_params);
3318}
3319
3320static void memcg_kmem_create_cache(struct mem_cgroup *memcg,
3321                                   struct kmem_cache *root_cache)
3322{
3323        struct kmem_cache *cachep;
3324        int id;
3325
3326        lockdep_assert_held(&memcg_slab_mutex);
3327
3328        id = memcg_cache_id(memcg);
3329
3330        /*
3331         * Since per-memcg caches are created asynchronously on first
3332         * allocation (see memcg_kmem_get_cache()), several threads can try to
3333         * create the same cache, but only one of them may succeed.
3334         */
3335        if (cache_from_memcg_idx(root_cache, id))
3336                return;
3337
3338        cachep = kmem_cache_create_memcg(memcg, root_cache);
3339        /*
3340         * If we could not create a memcg cache, do not complain, because
3341         * that's not critical at all as we can always proceed with the root
3342         * cache.
3343         */
3344        if (!cachep)
3345                return;
3346
3347        list_add(&cachep->memcg_params->list, &memcg->memcg_slab_caches);
3348
3349        /*
3350         * Since readers won't lock (see cache_from_memcg_idx()), we need a
3351         * barrier here to ensure nobody will see the kmem_cache partially
3352         * initialized.
3353         */
3354        smp_wmb();
3355
3356        BUG_ON(root_cache->memcg_params->memcg_caches[id]);
3357        root_cache->memcg_params->memcg_caches[id] = cachep;
3358
3359        mem_cgroup_get(memcg);
3360}
3361
3362static void memcg_kmem_destroy_cache(struct kmem_cache *cachep)
3363{
3364        struct kmem_cache *root_cache;
3365        struct mem_cgroup *memcg;
3366        int id;
3367
3368        lockdep_assert_held(&memcg_slab_mutex);
3369
3370        BUG_ON(is_root_cache(cachep));
3371
3372        root_cache = cachep->memcg_params->root_cache;
3373        memcg = cachep->memcg_params->memcg;
3374        id  = memcg_cache_id(memcg);
3375
3376        BUG_ON(root_cache->memcg_params->memcg_caches[id] != cachep);
3377        root_cache->memcg_params->memcg_caches[id] = NULL;
3378
3379        list_del(&cachep->memcg_params->list);
3380
3381        kmem_cache_destroy(cachep);
3382
3383        mem_cgroup_put(memcg);
3384}
3385
3386/*
3387 * During the creation a new cache, we need to disable our accounting mechanism
3388 * altogether. This is true even if we are not creating, but rather just
3389 * enqueing new caches to be created.
3390 *
3391 * This is because that process will trigger allocations; some visible, like
3392 * explicit kmallocs to auxiliary data structures, name strings and internal
3393 * cache structures; some well concealed, like INIT_WORK() that can allocate
3394 * objects during debug.
3395 *
3396 * If any allocation happens during memcg_kmem_get_cache, we will recurse back
3397 * to it. This may not be a bounded recursion: since the first cache creation
3398 * failed to complete (waiting on the allocation), we'll just try to create the
3399 * cache again, failing at the same point.
3400 *
3401 * memcg_kmem_get_cache is prepared to abort after seeing a positive count of
3402 * memcg_kmem_skip_account. So we enclose anything that might allocate memory
3403 * inside the following two functions.
3404 */
3405static inline void memcg_stop_kmem_account(void)
3406{
3407        VM_BUG_ON(!current->mm);
3408        current->memcg_kmem_skip_account++;
3409}
3410
3411static inline void memcg_resume_kmem_account(void)
3412{
3413        VM_BUG_ON(!current->mm);
3414        current->memcg_kmem_skip_account--;
3415}
3416
3417static DEFINE_MUTEX(memcg_limit_mutex);
3418
3419int __kmem_cache_destroy_memcg_children(struct kmem_cache *s)
3420{
3421        struct kmem_cache *c;
3422        int i, failed = 0;
3423
3424        mutex_lock(&memcg_slab_mutex);
3425        for_each_memcg_cache_index(i) {
3426                c = cache_from_memcg_idx(s, i);
3427                if (!c)
3428                        continue;
3429
3430                memcg_kmem_destroy_cache(c);
3431
3432                if (cache_from_memcg_idx(s, i))
3433                        failed++;
3434        }
3435        mutex_unlock(&memcg_slab_mutex);
3436        return failed;
3437}
3438
3439static void mem_cgroup_destroy_all_caches(struct mem_cgroup *memcg)
3440{
3441        struct kmem_cache *cachep;
3442        struct memcg_cache_params *params, *tmp;
3443
3444        if (!memcg_kmem_is_active(memcg))
3445                return;
3446
3447        mutex_lock(&memcg_slab_mutex);
3448        list_for_each_entry_safe(params, tmp, &memcg->memcg_slab_caches, list) {
3449                cachep = memcg_params_to_cache(params);
3450                __kmemcg_cache_deactivate(cachep);
3451                if (atomic_read(&cachep->memcg_params->nr_pages) == 0)
3452                        memcg_kmem_destroy_cache(cachep);
3453        }
3454        mutex_unlock(&memcg_slab_mutex);
3455}
3456
3457struct create_work {
3458        struct mem_cgroup *memcg;
3459        struct kmem_cache *cachep;
3460        struct work_struct work;
3461};
3462
3463static void memcg_create_cache_work_func(struct work_struct *w)
3464{
3465        struct create_work *cw = container_of(w, struct create_work, work);
3466        struct mem_cgroup *memcg = cw->memcg;
3467        struct kmem_cache *cachep = cw->cachep;
3468
3469        mutex_lock(&memcg_slab_mutex);
3470        memcg_kmem_create_cache(memcg, cachep);
3471        mutex_unlock(&memcg_slab_mutex);
3472
3473        css_put(&memcg->css);
3474        kfree(cw);
3475}
3476
3477/*
3478 * Enqueue the creation of a per-memcg kmem_cache.
3479 */
3480static void __memcg_create_cache_enqueue(struct mem_cgroup *memcg,
3481                                         struct kmem_cache *cachep)
3482{
3483        struct create_work *cw;
3484
3485        cw = kmalloc(sizeof(struct create_work), GFP_NOWAIT);
3486        if (cw == NULL) {
3487                css_put(&memcg->css);
3488                return;
3489        }
3490
3491        cw->memcg = memcg;
3492        cw->cachep = cachep;
3493
3494        INIT_WORK(&cw->work, memcg_create_cache_work_func);
3495        schedule_work(&cw->work);
3496}
3497
3498static void memcg_create_cache_enqueue(struct mem_cgroup *memcg,
3499                                       struct kmem_cache *cachep)
3500{
3501        /*
3502         * We need to stop accounting when we kmalloc, because if the
3503         * corresponding kmalloc cache is not yet created, the first allocation
3504         * in __memcg_create_cache_enqueue will recurse.
3505         *
3506         * However, it is better to enclose the whole function. Depending on
3507         * the debugging options enabled, INIT_WORK(), for instance, can
3508         * trigger an allocation. This too, will make us recurse. Because at
3509         * this point we can't allow ourselves back into memcg_kmem_get_cache,
3510         * the safest choice is to do it like this, wrapping the whole function.
3511         */
3512        memcg_stop_kmem_account();
3513        __memcg_create_cache_enqueue(memcg, cachep);
3514        memcg_resume_kmem_account();
3515}
3516/*
3517 * Return the kmem_cache we're supposed to use for a slab allocation.
3518 * We try to use the current memcg's version of the cache.
3519 *
3520 * If the cache does not exist yet, if we are the first user of it,
3521 * we either create it immediately, if possible, or create it asynchronously
3522 * in a workqueue.
3523 * In the latter case, we will let the current allocation go through with
3524 * the original cache.
3525 *
3526 * Can't be called in interrupt context or from kernel threads.
3527 * This function needs to be called with rcu_read_lock() held.
3528 */
3529struct kmem_cache *__memcg_kmem_get_cache(struct kmem_cache *cachep,
3530                                          gfp_t gfp)
3531{
3532        struct mem_cgroup *memcg;
3533        struct kmem_cache *memcg_cachep;
3534
3535        VM_BUG_ON(!cachep->memcg_params);
3536        VM_BUG_ON(!cachep->memcg_params->is_root_cache);
3537
3538        if (cachep->flags & SLAB_ACCOUNT)
3539                gfp |= __GFP_ACCOUNT;
3540
3541        if (!(gfp & __GFP_ACCOUNT))
3542                return cachep;
3543
3544        if (!current->mm || current->memcg_kmem_skip_account)
3545                return cachep;
3546
3547        rcu_read_lock();
3548        memcg = mem_cgroup_from_task(rcu_dereference(current->mm->owner));
3549
3550        if (!memcg_can_account_kmem(memcg))
3551                goto out;
3552
3553        memcg_cachep = cache_from_memcg_idx(cachep, memcg_cache_id(memcg));
3554        if (likely(memcg_cachep)) {
3555                cachep = memcg_cachep;
3556                goto out;
3557        }
3558
3559        /* The corresponding put will be done in the workqueue. */
3560        if (!css_tryget(&memcg->css))
3561                goto out;
3562        rcu_read_unlock();
3563
3564        /*
3565         * If we are in a safe context (can wait, and not in interrupt
3566         * context), we could be be predictable and return right away.
3567         * This would guarantee that the allocation being performed
3568         * already belongs in the new cache.
3569         *
3570         * However, there are some clashes that can arrive from locking.
3571         * For instance, because we acquire the slab_mutex while doing
3572         * kmem_cache_dup, this means no further allocation could happen
3573         * with the slab_mutex held.
3574         *
3575         * Also, because cache creation issue get_online_cpus(), this
3576         * creates a lock chain: memcg_slab_mutex -> cpu_hotplug_mutex,
3577         * that ends up reversed during cpu hotplug. (cpuset allocates
3578         * a bunch of GFP_KERNEL memory during cpuup). Due to all that,
3579         * better to defer everything.
3580         */
3581        memcg_create_cache_enqueue(memcg, cachep);
3582        return cachep;
3583out:
3584        rcu_read_unlock();
3585        return cachep;
3586}
3587EXPORT_SYMBOL(__memcg_kmem_get_cache);
3588
3589/*
3590 * We need to verify if the allocation against current->mm->owner's memcg is
3591 * possible for the given order. But the page is not allocated yet, so we'll
3592 * need a further commit step to do the final arrangements.
3593 *
3594 * It is possible for the task to switch cgroups in this mean time, so at
3595 * commit time, we can't rely on task conversion any longer.  We'll then use
3596 * the handle argument to return to the caller which cgroup we should commit
3597 * against. We could also return the memcg directly and avoid the pointer
3598 * passing, but a boolean return value gives better semantics considering
3599 * the compiled-out case as well.
3600 *
3601 * Returning true means the allocation is possible.
3602 */
3603bool
3604__memcg_kmem_newpage_charge(gfp_t gfp, struct mem_cgroup **_memcg, int order)
3605{
3606        struct mem_cgroup *memcg;
3607        int ret;
3608
3609        *_memcg = NULL;
3610
3611        /*
3612         * Disabling accounting is only relevant for some specific memcg
3613         * internal allocations. Therefore we would initially not have such
3614         * check here, since direct calls to the page allocator that are marked
3615         * with GFP_KMEMCG only happen outside memcg core. We are mostly
3616         * concerned with cache allocations, and by having this test at
3617         * memcg_kmem_get_cache, we are already able to relay the allocation to
3618         * the root cache and bypass the memcg cache altogether.
3619         *
3620         * There is one exception, though: the SLUB allocator does not create
3621         * large order caches, but rather service large kmallocs directly from
3622         * the page allocator. Therefore, the following sequence when backed by
3623         * the SLUB allocator:
3624         *
3625         *      memcg_stop_kmem_account();
3626         *      kmalloc(<large_number>)
3627         *      memcg_resume_kmem_account();
3628         *
3629         * would effectively ignore the fact that we should skip accounting,
3630         * since it will drive us directly to this function without passing
3631         * through the cache selector memcg_kmem_get_cache. Such large
3632         * allocations are extremely rare but can happen, for instance, for the
3633         * cache arrays. We bring this test here.
3634         */
3635        if (!current->mm || current->memcg_kmem_skip_account)
3636                return true;
3637
3638        memcg = try_get_mem_cgroup_from_mm(current->mm);
3639
3640        /*
3641         * very rare case described in mem_cgroup_from_task. Unfortunately there
3642         * isn't much we can do without complicating this too much, and it would
3643         * be gfp-dependent anyway. Just let it go
3644         */
3645        if (unlikely(!memcg))
3646                return true;
3647
3648        if (!memcg_can_account_kmem(memcg)) {
3649                css_put(&memcg->css);
3650                return true;
3651        }
3652
3653        ret = memcg_charge_kmem(memcg, gfp, 1 << order);
3654        if (!ret)
3655                *_memcg = memcg;
3656
3657        css_put(&memcg->css);
3658        return (ret == 0);
3659}
3660
3661void __memcg_kmem_commit_charge(struct page *page, struct mem_cgroup *memcg,
3662                              int order)
3663{
3664        struct page_cgroup *pc;
3665
3666        VM_BUG_ON(mem_cgroup_is_root(memcg));
3667
3668        /* The page allocation failed. Revert */
3669        if (!page) {
3670                memcg_uncharge_kmem(memcg, 1 << order);
3671                return;
3672        }
3673
3674        pc = lookup_page_cgroup(page);
3675        lock_page_cgroup(pc);
3676        pc->mem_cgroup = memcg;
3677        SetPageCgroupUsed(pc);
3678        unlock_page_cgroup(pc);
3679}
3680
3681void __memcg_kmem_uncharge_pages(struct page *page, int order)
3682{
3683        struct mem_cgroup *memcg = NULL;
3684        struct page_cgroup *pc;
3685
3686
3687        pc = lookup_page_cgroup(page);
3688        /*
3689         * Fast unlocked return. Theoretically might have changed, have to
3690         * check again after locking.
3691         */
3692        if (!PageCgroupUsed(pc))
3693                return;
3694
3695        lock_page_cgroup(pc);
3696        if (PageCgroupUsed(pc)) {
3697                memcg = pc->mem_cgroup;
3698                ClearPageCgroupUsed(pc);
3699        }
3700        unlock_page_cgroup(pc);
3701
3702        /*
3703         * We trust that only if there is a memcg associated with the page, it
3704         * is a valid allocation
3705         */
3706        if (!memcg)
3707                return;
3708
3709        VM_BUG_ON_PAGE(mem_cgroup_is_root(memcg), page);
3710        memcg_uncharge_kmem(memcg, 1 << order);
3711}
3712#else
3713static inline void mem_cgroup_destroy_all_caches(struct mem_cgroup *memcg)
3714{
3715}
3716#endif /* CONFIG_MEMCG_KMEM */
3717
3718#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3719
3720#define PCGF_NOCOPY_AT_SPLIT (1 << PCG_LOCK | 1 << PCG_MIGRATION)
3721/*
3722 * Because tail pages are not marked as "used", set it. We're under
3723 * zone->lru_lock, 'splitting on pmd' and compound_lock.
3724 * charge/uncharge will be never happen and move_account() is done under
3725 * compound_lock(), so we don't have to take care of races.
3726 */
3727void mem_cgroup_split_huge_fixup(struct page *head)
3728{
3729        struct page_cgroup *head_pc = lookup_page_cgroup(head);
3730        struct page_cgroup *pc;
3731        struct mem_cgroup *memcg;
3732        int i;
3733
3734        if (mem_cgroup_disabled())
3735                return;
3736
3737        memcg = head_pc->mem_cgroup;
3738        for (i = 1; i < HPAGE_PMD_NR; i++) {
3739                pc = head_pc + i;
3740                pc->mem_cgroup = memcg;
3741                smp_wmb();/* see __commit_charge() */
3742                pc->flags = head_pc->flags & ~PCGF_NOCOPY_AT_SPLIT;
3743        }
3744        __this_cpu_sub(memcg->stat->count[MEM_CGROUP_STAT_RSS_HUGE],
3745                       HPAGE_PMD_NR);
3746}
3747#endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3748
3749/**
3750 * mem_cgroup_move_account - move account of the page
3751 * @page: the page
3752 * @nr_pages: number of regular pages (>1 for huge pages)
3753 * @pc: page_cgroup of the page.
3754 * @from: mem_cgroup which the page is moved from.
3755 * @to: mem_cgroup which the page is moved to. @from != @to.
3756 *
3757 * The caller must confirm following.
3758 * - page is not on LRU (isolate_page() is useful.)
3759 * - compound_lock is held when nr_pages > 1
3760 *
3761 * This function doesn't do "charge" to new cgroup and doesn't do "uncharge"
3762 * from old cgroup.
3763 */
3764static int mem_cgroup_move_account(struct page *page,
3765                                   unsigned int nr_pages,
3766                                   struct page_cgroup *pc,
3767                                   struct mem_cgroup *from,
3768                                   struct mem_cgroup *to)
3769{
3770        unsigned long flags;
3771        int ret;
3772        bool anon = PageAnon(page);
3773
3774        VM_BUG_ON(from == to);
3775        VM_BUG_ON_PAGE(PageLRU(page), page);
3776        /*
3777         * The page is isolated from LRU. So, collapse function
3778         * will not handle this page. But page splitting can happen.
3779         * Do this check under compound_page_lock(). The caller should
3780         * hold it.
3781         */
3782        ret = -EBUSY;
3783        if (nr_pages > 1 && !PageTransHuge(page))
3784                goto out;
3785
3786        lock_page_cgroup(pc);
3787
3788        ret = -EINVAL;
3789        if (!PageCgroupUsed(pc) || pc->mem_cgroup != from)
3790                goto unlock;
3791
3792        move_lock_mem_cgroup(from, &flags);
3793
3794        if (!anon && page_mapped(page)) {
3795                /* Update mapped_file data for mem_cgroup */
3796                preempt_disable();
3797                __this_cpu_dec(from->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
3798                __this_cpu_inc(to->stat->count[MEM_CGROUP_STAT_FILE_MAPPED]);
3799                preempt_enable();
3800        }
3801        mem_cgroup_charge_statistics(from, page, anon, -nr_pages);
3802
3803        /* caller should have done css_get */
3804        pc->mem_cgroup = to;
3805        mem_cgroup_charge_statistics(to, page, anon, nr_pages);
3806        move_unlock_mem_cgroup(from, &flags);
3807        ret = 0;
3808unlock:
3809        unlock_page_cgroup(pc);
3810        /*
3811         * check events
3812         */
3813        memcg_check_events(to, page);
3814        memcg_check_events(from, page);
3815out:
3816        return ret;
3817}
3818
3819/**
3820 * mem_cgroup_move_parent - moves page to the parent group
3821 * @page: the page to move
3822 * @pc: page_cgroup of the page
3823 * @child: page's cgroup
3824 *
3825 * move charges to its parent or the root cgroup if the group has no
3826 * parent (aka use_hierarchy==0).
3827 * Although this might fail (get_page_unless_zero, isolate_lru_page or
3828 * mem_cgroup_move_account fails) the failure is always temporary and
3829 * it signals a race with a page removal/uncharge or migration. In the
3830 * first case the page is on the way out and it will vanish from the LRU
3831 * on the next attempt and the call should be retried later.
3832 * Isolation from the LRU fails only if page has been isolated from
3833 * the LRU since we looked at it and that usually means either global
3834 * reclaim or migration going on. The page will either get back to the
3835 * LRU or vanish.
3836 * Finaly mem_cgroup_move_account fails only if the page got uncharged
3837 * (!PageCgroupUsed) or moved to a different group. The page will
3838 * disappear in the next attempt.
3839 */
3840static int mem_cgroup_move_parent(struct page *page,
3841                                  struct page_cgroup *pc,
3842                                  struct mem_cgroup *child)
3843{
3844        struct mem_cgroup *parent;
3845        unsigned int nr_pages;
3846        unsigned long uninitialized_var(flags);
3847        int ret;
3848
3849        VM_BUG_ON(mem_cgroup_is_root(child));
3850
3851        ret = -EBUSY;
3852        if (!get_page_unless_zero(page))
3853                goto out;
3854        if (isolate_lru_page(page))
3855                goto put;
3856
3857        nr_pages = hpage_nr_pages(page);
3858
3859        parent = parent_mem_cgroup(child);
3860        /*
3861         * If no parent, move charges to root cgroup.
3862         */
3863        if (!parent)
3864                parent = root_mem_cgroup;
3865
3866        if (nr_pages > 1) {
3867                VM_BUG_ON_PAGE(!PageTransHuge(page), page);
3868                flags = compound_lock_irqsave(page);
3869        }
3870
3871        ret = mem_cgroup_move_account(page, nr_pages,
3872                                pc, child, parent);
3873        if (!ret) {
3874                /* Take charge off the local counters */
3875                page_counter_cancel(&child->memory, nr_pages);
3876                if (do_swap_account)
3877                        page_counter_cancel(&child->memsw, nr_pages);
3878        }
3879
3880        if (nr_pages > 1)
3881                compound_unlock_irqrestore(page, flags);
3882        putback_lru_page(page);
3883put:
3884        put_page(page);
3885out:
3886        return ret;
3887}
3888
3889/*
3890 * Charge the memory controller for page usage.
3891 * Return
3892 * 0 if the charge was successful
3893 * < 0 if the cgroup is over its limit
3894 */
3895static int mem_cgroup_charge_common(struct page *page, struct mm_struct *mm,
3896                                gfp_t gfp_mask, enum charge_type ctype)
3897{
3898        struct mem_cgroup *memcg = NULL;
3899        unsigned int nr_pages = 1;
3900        bool oom = true;
3901        int ret;
3902
3903        if (PageTransHuge(page)) {
3904                nr_pages <<= compound_order(page);
3905                VM_BUG_ON_PAGE(!PageTransHuge(page), page);
3906                /*
3907                 * Never OOM-kill a process for a huge page.  The
3908                 * fault handler will fall back to regular pages.
3909                 */
3910                oom = false;
3911        }
3912
3913        ret = __mem_cgroup_try_charge(mm, gfp_mask, nr_pages, &memcg, oom);
3914        if (ret == -ENOMEM)
3915                return ret;
3916        __mem_cgroup_commit_charge(memcg, page, nr_pages, ctype, false);
3917        return 0;
3918}
3919
3920int mem_cgroup_newpage_charge(struct page *page,
3921                              struct mm_struct *mm, gfp_t gfp_mask)
3922{
3923        if (mem_cgroup_disabled())
3924                return 0;
3925        VM_BUG_ON_PAGE(page_mapped(page), page);
3926        VM_BUG_ON_PAGE(page->mapping && !PageAnon(page), page);
3927        VM_BUG_ON(!mm);
3928        return mem_cgroup_charge_common(page, mm, gfp_mask,
3929                                        MEM_CGROUP_CHARGE_TYPE_ANON);
3930}
3931
3932/*
3933 * While swap-in, try_charge -> commit or cancel, the page is locked.
3934 * And when try_charge() successfully returns, one refcnt to memcg without
3935 * struct page_cgroup is acquired. This refcnt will be consumed by
3936 * "commit()" or removed by "cancel()"
3937 */
3938static int __mem_cgroup_try_charge_swapin(struct mm_struct *mm,
3939                                          struct page *page,
3940                                          gfp_t mask,
3941                                          struct mem_cgroup **memcgp)
3942{
3943        struct mem_cgroup *memcg;
3944        struct page_cgroup *pc;
3945        int ret;
3946
3947        pc = lookup_page_cgroup(page);
3948        /*
3949         * Every swap fault against a single page tries to charge the
3950         * page, bail as early as possible.  shmem_unuse() encounters
3951         * already charged pages, too.  The USED bit is protected by
3952         * the page lock, which serializes swap cache removal, which
3953         * in turn serializes uncharging.
3954         */
3955        if (PageCgroupUsed(pc))
3956                return 0;
3957        if (!do_swap_account)
3958                goto charge_cur_mm;
3959        memcg = try_get_mem_cgroup_from_page(page);
3960        if (!memcg)
3961                goto charge_cur_mm;
3962        *memcgp = memcg;
3963        ret = __mem_cgroup_try_charge(NULL, mask, 1, memcgp, true);
3964        css_put(&memcg->css);
3965        if (ret == -EINTR)
3966                ret = 0;
3967        return ret;
3968charge_cur_mm:
3969        ret = __mem_cgroup_try_charge(mm, mask, 1, memcgp, true);
3970        if (ret == -EINTR)
3971                ret = 0;
3972        return ret;
3973}
3974
3975int mem_cgroup_try_charge_swapin(struct mm_struct *mm, struct page *page,
3976                                 gfp_t gfp_mask, struct mem_cgroup **memcgp)
3977{
3978        *memcgp = NULL;
3979        if (mem_cgroup_disabled())
3980                return 0;
3981        /*
3982         * A racing thread's fault, or swapoff, may have already
3983         * updated the pte, and even removed page from swap cache: in
3984         * those cases unuse_pte()'s pte_same() test will fail; but
3985         * there's also a KSM case which does need to charge the page.
3986         */
3987        if (!PageSwapCache(page)) {
3988                int ret;
3989
3990                ret = __mem_cgroup_try_charge(mm, gfp_mask, 1, memcgp, true);
3991                if (ret == -EINTR)
3992                        ret = 0;
3993                return ret;
3994        }
3995        return __mem_cgroup_try_charge_swapin(mm, page, gfp_mask, memcgp);
3996}
3997
3998void mem_cgroup_cancel_charge_swapin(struct mem_cgroup *memcg)
3999{
4000        if (mem_cgroup_disabled())
4001                return;
4002        if (!memcg)
4003                return;
4004        __mem_cgroup_cancel_charge(memcg, 1);
4005}
4006
4007static void
4008__mem_cgroup_commit_charge_swapin(struct page *page, struct mem_cgroup *memcg,
4009                                        enum charge_type ctype)
4010{
4011        if (mem_cgroup_disabled())
4012                return;
4013        if (!memcg)
4014                return;
4015
4016        __mem_cgroup_commit_charge(memcg, page, 1, ctype, true);
4017        /*
4018         * Now swap is on-memory. This means this page may be
4019         * counted both as mem and swap....double count.
4020         * Fix it by uncharging from memsw. Basically, this SwapCache is stable
4021         * under lock_page(). But in do_swap_page()::memory.c, reuse_swap_page()
4022         * may call delete_from_swap_cache() before reach here.
4023         */
4024        if (do_swap_account && PageSwapCache(page)) {
4025                swp_entry_t ent = {.val = page_private(page)};
4026                mem_cgroup_uncharge_swap(ent);
4027        }
4028}
4029
4030void mem_cgroup_commit_charge_swapin(struct page *page,
4031                                     struct mem_cgroup *memcg)
4032{
4033        __mem_cgroup_commit_charge_swapin(page, memcg,
4034                                          MEM_CGROUP_CHARGE_TYPE_ANON);
4035}
4036
4037int mem_cgroup_cache_charge(struct page *page, struct mm_struct *mm,
4038                                gfp_t gfp_mask)
4039{
4040        struct mem_cgroup *memcg = NULL;
4041        enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
4042        int ret;
4043
4044        if (mem_cgroup_disabled())
4045                return 0;
4046        if (PageCompound(page))
4047                return 0;
4048
4049        if (!PageSwapCache(page))
4050                ret = mem_cgroup_charge_common(page, mm, gfp_mask, type);
4051        else { /* page is swapcache/shmem */
4052                ret = __mem_cgroup_try_charge_swapin(mm, page,
4053                                                     gfp_mask, &memcg);
4054                if (!ret)
4055                        __mem_cgroup_commit_charge_swapin(page, memcg, type);
4056        }
4057        return ret;
4058}
4059
4060static void mem_cgroup_do_uncharge(struct mem_cgroup *memcg,
4061                                   unsigned int nr_pages,
4062                                   const enum charge_type ctype)
4063{
4064        struct memcg_batch_info *batch = NULL;
4065        bool uncharge_memsw = true;
4066
4067        /* If swapout, usage of swap doesn't decrease */
4068        if (!do_swap_account || ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT)
4069                uncharge_memsw = false;
4070
4071        batch = &current->memcg_batch;
4072        /*
4073         * In usual, we do css_get() when we remember memcg pointer.
4074         * But in this case, we keep res->usage until end of a series of
4075         * uncharges. Then, it's ok to ignore memcg's refcnt.
4076         */
4077        if (!batch->memcg)
4078                batch->memcg = memcg;
4079        /*
4080         * do_batch > 0 when unmapping pages or inode invalidate/truncate.
4081         * In those cases, all pages freed continuously can be expected to be in
4082         * the same cgroup and we have chance to coalesce uncharges.
4083         * But we do uncharge one by one if this is killed by OOM(TIF_MEMDIE)
4084         * because we want to do uncharge as soon as possible.
4085         */
4086
4087        if (!batch->do_batch || test_thread_flag(TIF_MEMDIE))
4088                goto direct_uncharge;
4089
4090        if (nr_pages > 1)
4091                goto direct_uncharge;
4092
4093        /*
4094         * In typical case, batch->memcg == mem. This means we can
4095         * merge a series of uncharges to an uncharge of page_counter.
4096         * If not, we uncharge page_counter ony by one.
4097         */
4098        if (batch->memcg != memcg)
4099                goto direct_uncharge;
4100        /* remember freed charge and uncharge it later */
4101        batch->nr_pages++;
4102        if (uncharge_memsw)
4103                batch->memsw_nr_pages++;
4104        return;
4105direct_uncharge:
4106        page_counter_uncharge(&memcg->memory, nr_pages);
4107        if (uncharge_memsw)
4108                page_counter_uncharge(&memcg->memsw, nr_pages);
4109        if (unlikely(batch->memcg != memcg))
4110                memcg_oom_recover(memcg);
4111}
4112
4113/*
4114 * uncharge if !page_mapped(page)
4115 */
4116static struct mem_cgroup *
4117__mem_cgroup_uncharge_common(struct page *page, enum charge_type ctype,
4118                             bool end_migration)
4119{
4120        struct mem_cgroup *memcg = NULL;
4121        unsigned int nr_pages = 1;
4122        struct page_cgroup *pc;
4123        bool anon;
4124
4125        if (mem_cgroup_disabled())
4126                return NULL;
4127
4128        if (PageTransHuge(page)) {
4129                nr_pages <<= compound_order(page);
4130                VM_BUG_ON_PAGE(!PageTransHuge(page), page);
4131        }
4132        /*
4133         * Check if our page_cgroup is valid
4134         */
4135        pc = lookup_page_cgroup(page);
4136        if (unlikely(!PageCgroupUsed(pc)))
4137                return NULL;
4138
4139        lock_page_cgroup(pc);
4140
4141        memcg = pc->mem_cgroup;
4142
4143        if (!PageCgroupUsed(pc))
4144                goto unlock_out;
4145
4146        anon = PageAnon(page);
4147
4148        switch (ctype) {
4149        case MEM_CGROUP_CHARGE_TYPE_ANON:
4150                /*
4151                 * Generally PageAnon tells if it's the anon statistics to be
4152                 * updated; but sometimes e.g. mem_cgroup_uncharge_page() is
4153                 * used before page reached the stage of being marked PageAnon.
4154                 */
4155                anon = true;
4156                /* fallthrough */
4157        case MEM_CGROUP_CHARGE_TYPE_DROP:
4158                /* See mem_cgroup_prepare_migration() */
4159                if (page_mapped(page))
4160                        goto unlock_out;
4161                /*
4162                 * Pages under migration may not be uncharged.  But
4163                 * end_migration() /must/ be the one uncharging the
4164                 * unused post-migration page and so it has to call
4165                 * here with the migration bit still set.  See the
4166                 * page_counter handling below.
4167                 */
4168                if (!end_migration && PageCgroupMigration(pc))
4169                        goto unlock_out;
4170                break;
4171        case MEM_CGROUP_CHARGE_TYPE_SWAPOUT:
4172                if (!PageAnon(page)) {  /* Shared memory */
4173                        if (page->mapping && !page_is_file_cache(page))
4174                                goto unlock_out;
4175                } else if (page_mapped(page)) /* Anon */
4176                                goto unlock_out;
4177                break;
4178        default:
4179                break;
4180        }
4181
4182        mem_cgroup_charge_statistics(memcg, page, anon, -nr_pages);
4183
4184        ClearPageCgroupUsed(pc);
4185        /*
4186         * pc->mem_cgroup is not cleared here. It will be accessed when it's
4187         * freed from LRU. This is safe because uncharged page is expected not
4188         * to be reused (freed soon). Exception is SwapCache, it's handled by
4189         * special functions.
4190         */
4191
4192        unlock_page_cgroup(pc);
4193        /*
4194         * even after unlock, we have memcg->memory.usage here and this memcg
4195         * will never be freed.
4196         */
4197        memcg_check_events(memcg, page);
4198        if (do_swap_account && ctype == MEM_CGROUP_CHARGE_TYPE_SWAPOUT) {
4199                mem_cgroup_swap_statistics(memcg, true);
4200                mem_cgroup_get(memcg);
4201        }
4202        /*
4203         * Migration does not charge the page_counter for the
4204         * replacement page, so leave it alone when phasing out the
4205         * page that is unused after the migration.
4206         */
4207        if (!end_migration && !mem_cgroup_is_root(memcg))
4208                mem_cgroup_do_uncharge(memcg, nr_pages, ctype);
4209
4210        return memcg;
4211
4212unlock_out:
4213        unlock_page_cgroup(pc);
4214        return NULL;
4215}
4216
4217void mem_cgroup_uncharge_page(struct page *page)
4218{
4219        /* early check. */
4220        if (page_mapped(page))
4221                return;
4222        VM_BUG_ON_PAGE(page->mapping && !PageAnon(page), page);
4223        /*
4224         * If the page is in swap cache, uncharge should be deferred
4225         * to the swap path, which also properly accounts swap usage
4226         * and handles memcg lifetime.
4227         *
4228         * Note that this check is not stable and reclaim may add the
4229         * page to swap cache at any time after this.  However, if the
4230         * page is not in swap cache by the time page->mapcount hits
4231         * 0, there won't be any page table references to the swap
4232         * slot, and reclaim will free it and not actually write the
4233         * page to disk.
4234         */
4235        if (PageSwapCache(page))
4236                return;
4237        __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_ANON, false);
4238}
4239
4240void mem_cgroup_uncharge_cache_page(struct page *page)
4241{
4242        VM_BUG_ON_PAGE(page_mapped(page), page);
4243        VM_BUG_ON_PAGE(page->mapping, page);
4244        __mem_cgroup_uncharge_common(page, MEM_CGROUP_CHARGE_TYPE_CACHE, false);
4245}
4246
4247/*
4248 * Batch_start/batch_end is called in unmap_page_range/invlidate/trucate.
4249 * In that cases, pages are freed continuously and we can expect pages
4250 * are in the same memcg. All these calls itself limits the number of
4251 * pages freed at once, then uncharge_start/end() is called properly.
4252 * This may be called prural(2) times in a context,
4253 */
4254
4255void mem_cgroup_uncharge_start(void)
4256{
4257        current->memcg_batch.do_batch++;
4258        /* We can do nest. */
4259        if (current->memcg_batch.do_batch == 1) {
4260                current->memcg_batch.memcg = NULL;
4261                current->memcg_batch.nr_pages = 0;
4262                current->memcg_batch.memsw_nr_pages = 0;
4263        }
4264}
4265
4266void mem_cgroup_uncharge_end(void)
4267{
4268        struct memcg_batch_info *batch = &current->memcg_batch;
4269
4270        if (!batch->do_batch)
4271                return;
4272
4273        batch->do_batch--;
4274        if (batch->do_batch) /* If stacked, do nothing. */
4275                return;
4276
4277        if (!batch->memcg)
4278                return;
4279        /*
4280         * This "batch->memcg" is valid without any css_get/put etc...
4281         * bacause we hide charges behind us.
4282         */
4283        if (batch->nr_pages)
4284                page_counter_uncharge(&batch->memcg->memory, batch->nr_pages);
4285        if (batch->memsw_nr_pages)
4286                page_counter_uncharge(&batch->memcg->memsw, batch->memsw_nr_pages);
4287        memcg_oom_recover(batch->memcg);
4288        /* forget this pointer (for sanity check) */
4289        batch->memcg = NULL;
4290}
4291
4292#ifdef CONFIG_SWAP
4293/*
4294 * called after __delete_from_swap_cache() and drop "page" account.
4295 * memcg information is recorded to swap_cgroup of "ent"
4296 */
4297void
4298mem_cgroup_uncharge_swapcache(struct page *page, swp_entry_t ent, bool swapout)
4299{
4300        struct mem_cgroup *memcg;
4301        int ctype = MEM_CGROUP_CHARGE_TYPE_SWAPOUT;
4302
4303        if (!swapout) /* this was a swap cache but the swap is unused ! */
4304                ctype = MEM_CGROUP_CHARGE_TYPE_DROP;
4305
4306        memcg = __mem_cgroup_uncharge_common(page, ctype, false);
4307
4308        /*
4309         * record memcg information,  if swapout && memcg != NULL,
4310         * mem_cgroup_get() was called in uncharge().
4311         */
4312        if (do_swap_account && swapout && memcg)
4313                swap_cgroup_record(ent, mem_cgroup_id(memcg));
4314}
4315#endif
4316
4317#ifdef CONFIG_MEMCG_SWAP
4318/*
4319 * called from swap_entry_free(). remove record in swap_cgroup and
4320 * uncharge "memsw" account.
4321 */
4322void mem_cgroup_uncharge_swap(swp_entry_t ent)
4323{
4324        struct mem_cgroup *memcg;
4325        unsigned short id;
4326
4327        if (!do_swap_account)
4328                return;
4329
4330        id = swap_cgroup_record(ent, 0);
4331        rcu_read_lock();
4332        memcg = mem_cgroup_lookup(id);
4333        if (memcg) {
4334                /*
4335                 * We uncharge this because swap is freed.
4336                 * This memcg can be obsolete one. We avoid calling css_tryget
4337                 */
4338                if (!mem_cgroup_is_root(memcg))
4339                        page_counter_uncharge(&memcg->memsw, 1);
4340                mem_cgroup_swap_statistics(memcg, false);
4341                mem_cgroup_put(memcg);
4342        }
4343        rcu_read_unlock();
4344}
4345
4346/**
4347 * mem_cgroup_move_swap_account - move swap charge and swap_cgroup's record.
4348 * @entry: swap entry to be moved
4349 * @from:  mem_cgroup which the entry is moved from
4350 * @to:  mem_cgroup which the entry is moved to
4351 *
4352 * It succeeds only when the swap_cgroup's record for this entry is the same
4353 * as the mem_cgroup's id of @from.
4354 *
4355 * Returns 0 on success, -EINVAL on failure.
4356 *
4357 * The caller must have charged to @to, IOW, called page_counter_charge() about
4358 * both res and memsw, and called css_get().
4359 */
4360static int mem_cgroup_move_swap_account(swp_entry_t entry,
4361                                struct mem_cgroup *from, struct mem_cgroup *to)
4362{
4363        unsigned short old_id, new_id;
4364
4365        old_id = mem_cgroup_id(from);
4366        new_id = mem_cgroup_id(to);
4367
4368        if (swap_cgroup_cmpxchg(entry, old_id, new_id) == old_id) {
4369                mem_cgroup_swap_statistics(from, false);
4370                mem_cgroup_swap_statistics(to, true);
4371                /*
4372                 * This function is only called from task migration context now.
4373                 * It postpones page_counter and refcount handling till the end
4374                 * of task migration(mem_cgroup_clear_mc()) for performance
4375                 * improvement. But we cannot postpone mem_cgroup_get(to)
4376                 * because if the process that has been moved to @to does
4377                 * swap-in, the refcount of @to might be decreased to 0.
4378                 */
4379                mem_cgroup_get(to);
4380                return 0;
4381        }
4382        return -EINVAL;
4383}
4384#else
4385static inline int mem_cgroup_move_swap_account(swp_entry_t entry,
4386                                struct mem_cgroup *from, struct mem_cgroup *to)
4387{
4388        return -EINVAL;
4389}
4390#endif
4391
4392/*
4393 * Before starting migration, account PAGE_SIZE to mem_cgroup that the old
4394 * page belongs to.
4395 */
4396void mem_cgroup_prepare_migration(struct page *page, struct page *newpage,
4397                                  struct mem_cgroup **memcgp)
4398{
4399        struct mem_cgroup *memcg = NULL;
4400        unsigned int nr_pages = 1;
4401        struct page_cgroup *pc;
4402        enum charge_type ctype;
4403
4404        *memcgp = NULL;
4405
4406        if (mem_cgroup_disabled())
4407                return;
4408
4409        if (PageTransHuge(page))
4410                nr_pages <<= compound_order(page);
4411
4412        pc = lookup_page_cgroup(page);
4413        lock_page_cgroup(pc);
4414        if (PageCgroupUsed(pc)) {
4415                memcg = pc->mem_cgroup;
4416                css_get(&memcg->css);
4417                /*
4418                 * At migrating an anonymous page, its mapcount goes down
4419                 * to 0 and uncharge() will be called. But, even if it's fully
4420                 * unmapped, migration may fail and this page has to be
4421                 * charged again. We set MIGRATION flag here and delay uncharge
4422                 * until end_migration() is called
4423                 *
4424                 * Corner Case Thinking
4425                 * A)
4426                 * When the old page was mapped as Anon and it's unmap-and-freed
4427                 * while migration was ongoing.
4428                 * If unmap finds the old page, uncharge() of it will be delayed
4429                 * until end_migration(). If unmap finds a new page, it's
4430                 * uncharged when it make mapcount to be 1->0. If unmap code
4431                 * finds swap_migration_entry, the new page will not be mapped
4432                 * and end_migration() will find it(mapcount==0).
4433                 *
4434                 * B)
4435                 * When the old page was mapped but migraion fails, the kernel
4436                 * remaps it. A charge for it is kept by MIGRATION flag even
4437                 * if mapcount goes down to 0. We can do remap successfully
4438                 * without charging it again.
4439                 *
4440                 * C)
4441                 * The "old" page is under lock_page() until the end of
4442                 * migration, so, the old page itself will not be swapped-out.
4443                 * If the new page is swapped out before end_migraton, our
4444                 * hook to usual swap-out path will catch the event.
4445                 */
4446                if (PageAnon(page))
4447                        SetPageCgroupMigration(pc);
4448        }
4449        unlock_page_cgroup(pc);
4450        /*
4451         * If the page is not charged at this point,
4452         * we return here.
4453         */
4454        if (!memcg)
4455                return;
4456
4457        *memcgp = memcg;
4458        /*
4459         * We charge new page before it's used/mapped. So, even if unlock_page()
4460         * is called before end_migration, we can catch all events on this new
4461         * page. In the case new page is migrated but not remapped, new page's
4462         * mapcount will be finally 0 and we call uncharge in end_migration().
4463         */
4464        if (PageAnon(page))
4465                ctype = MEM_CGROUP_CHARGE_TYPE_ANON;
4466        else
4467                ctype = MEM_CGROUP_CHARGE_TYPE_CACHE;
4468        /*
4469         * The page is committed to the memcg, but it's not actually
4470         * charged to the page_counter since we plan on replacing the
4471         * old one and only one page is going to be left afterwards.
4472         */
4473        __mem_cgroup_commit_charge(memcg, newpage, nr_pages, ctype, false);
4474}
4475
4476/* remove redundant charge if migration failed*/
4477void mem_cgroup_end_migration(struct mem_cgroup *memcg,
4478        struct page *oldpage, struct page *newpage, bool migration_ok)
4479{
4480        struct page *used, *unused;
4481        struct page_cgroup *pc;
4482        bool anon;
4483
4484        if (!memcg)
4485                return;
4486
4487        if (!migration_ok) {
4488                used = oldpage;
4489                unused = newpage;
4490        } else {
4491                used = newpage;
4492                unused = oldpage;
4493        }
4494        anon = PageAnon(used);
4495        __mem_cgroup_uncharge_common(unused,
4496                                     anon ? MEM_CGROUP_CHARGE_TYPE_ANON
4497                                     : MEM_CGROUP_CHARGE_TYPE_CACHE,
4498                                     true);
4499        css_put(&memcg->css);
4500        /*
4501         * We disallowed uncharge of pages under migration because mapcount
4502         * of the page goes down to zero, temporarly.
4503         * Clear the flag and check the page should be charged.
4504         */
4505        pc = lookup_page_cgroup(oldpage);
4506        lock_page_cgroup(pc);
4507        ClearPageCgroupMigration(pc);
4508        unlock_page_cgroup(pc);
4509
4510        /*
4511         * If a page is a file cache, radix-tree replacement is very atomic
4512         * and we can skip this check. When it was an Anon page, its mapcount
4513         * goes down to 0. But because we added MIGRATION flage, it's not
4514         * uncharged yet. There are several case but page->mapcount check
4515         * and USED bit check in mem_cgroup_uncharge_page() will do enough
4516         * check. (see prepare_charge() also)
4517         */
4518        if (anon)
4519                mem_cgroup_uncharge_page(used);
4520}
4521
4522/*
4523 * At replace page cache, newpage is not under any memcg but it's on
4524 * LRU. So, this function doesn't touch page_counter but handles LRU
4525 * in correct way. Both pages are locked so we cannot race with uncharge.
4526 */
4527void mem_cgroup_replace_page_cache(struct page *oldpage,
4528                                  struct page *newpage)
4529{
4530        struct mem_cgroup *memcg = NULL;
4531        struct page_cgroup *pc;
4532        enum charge_type type = MEM_CGROUP_CHARGE_TYPE_CACHE;
4533
4534        if (mem_cgroup_disabled())
4535                return;
4536
4537        pc = lookup_page_cgroup(oldpage);
4538        /* fix accounting on old pages */
4539        lock_page_cgroup(pc);
4540        if (PageCgroupUsed(pc)) {
4541                memcg = pc->mem_cgroup;
4542                mem_cgroup_charge_statistics(memcg, oldpage, false, -1);
4543                ClearPageCgroupUsed(pc);
4544        }
4545        unlock_page_cgroup(pc);
4546
4547        /*
4548         * When called from shmem_replace_page(), in some cases the
4549         * oldpage has already been charged, and in some cases not.
4550         */
4551        if (!memcg)
4552                return;
4553        /*
4554         * Even if newpage->mapping was NULL before starting replacement,
4555         * the newpage may be on LRU(or pagevec for LRU) already. We lock
4556         * LRU while we overwrite pc->mem_cgroup.
4557         */
4558        __mem_cgroup_commit_charge(memcg, newpage, 1, type, true);
4559}
4560
4561#ifdef CONFIG_DEBUG_VM
4562static struct page_cgroup *lookup_page_cgroup_used(struct page *page)
4563{
4564        struct page_cgroup *pc;
4565
4566        pc = lookup_page_cgroup(page);
4567        /*
4568         * Can be NULL while feeding pages into the page allocator for
4569         * the first time, i.e. during boot or memory hotplug;
4570         * or when mem_cgroup_disabled().
4571         */
4572        if (likely(pc) && PageCgroupUsed(pc))
4573                return pc;
4574        return NULL;
4575}
4576
4577bool mem_cgroup_bad_page_check(struct page *page)
4578{
4579        if (mem_cgroup_disabled())
4580                return false;
4581
4582        return lookup_page_cgroup_used(page) != NULL;
4583}
4584
4585void mem_cgroup_print_bad_page(struct page *page)
4586{
4587        struct page_cgroup *pc;
4588
4589        pc = lookup_page_cgroup_used(page);
4590        if (pc) {
4591                pr_alert("pc:%p pc->flags:%lx pc->mem_cgroup:%p\n",
4592                         pc, pc->flags, pc->mem_cgroup);
4593        }
4594}
4595#endif
4596
4597static int mem_cgroup_resize_limit(struct mem_cgroup *memcg,
4598                                   unsigned long limit)
4599{
4600        unsigned long curusage;
4601        unsigned long oldusage;
4602        unsigned long memswlimit;
4603        bool enlarge = false;
4604        int retry_count;
4605        int ret;
4606
4607        /*
4608         * For keeping hierarchical_reclaim simple, how long we should retry
4609         * is depends on callers. We set our retry-count to be function
4610         * of # of children which we should visit in this loop.
4611         */
4612        retry_count = MEM_CGROUP_RECLAIM_RETRIES *
4613                      mem_cgroup_count_children(memcg);
4614
4615        oldusage = page_counter_read(&memcg->memory);
4616
4617        do {
4618                if (signal_pending(current)) {
4619                        ret = -EINTR;
4620                        break;
4621                }
4622                mutex_lock(&memcg_limit_mutex);
4623                memswlimit = memcg->memsw.limit;
4624                if (limit > memswlimit) {
4625                        mutex_unlock(&memcg_limit_mutex);
4626                        ret = -EINVAL;
4627                        break;
4628                }
4629
4630                if (limit > memcg->memory.limit)
4631                        enlarge = true;
4632
4633                ret = page_counter_limit(&memcg->memory, limit);
4634                if (!ret) {
4635                        if (memswlimit == limit)
4636                                memcg->memsw_is_minimum = true;
4637                        else
4638                                memcg->memsw_is_minimum = false;
4639                }
4640                mutex_unlock(&memcg_limit_mutex);
4641
4642                if (!ret)
4643                        break;
4644
4645                mem_cgroup_reclaim(memcg, GFP_KERNEL,
4646                                   MEM_CGROUP_RECLAIM_SHRINK);
4647                curusage = page_counter_read(&memcg->memory);
4648                /* Usage is reduced ? */
4649                if (curusage >= oldusage)
4650                        retry_count--;
4651                else
4652                        oldusage = curusage;
4653        } while (retry_count);
4654
4655        if (!ret && enlarge)
4656                memcg_oom_recover(memcg);
4657
4658        return ret;
4659}
4660
4661static int mem_cgroup_resize_memsw_limit(struct mem_cgroup *memcg,
4662                                         unsigned long limit)
4663{
4664        unsigned long curusage;
4665        unsigned long oldusage;
4666        unsigned long memlimit, memswlimit;
4667        bool enlarge = false;
4668        int retry_count;
4669        int ret;
4670
4671        /* see mem_cgroup_resize_res_limit */
4672        retry_count = MEM_CGROUP_RECLAIM_RETRIES *
4673                      mem_cgroup_count_children(memcg);
4674
4675        oldusage = page_counter_read(&memcg->memsw);
4676
4677        do {
4678                if (signal_pending(current)) {
4679                        ret = -EINTR;
4680                        break;
4681                }
4682                mutex_lock(&memcg_limit_mutex);
4683                memlimit = memcg->memory.limit;
4684                if (limit < memlimit) {
4685                        mutex_unlock(&memcg_limit_mutex);
4686                        ret = -EINVAL;
4687                        break;
4688                }
4689                memswlimit = memcg->memsw.limit;
4690                if (limit > memswlimit)
4691                        enlarge = true;
4692                ret = page_counter_limit(&memcg->memsw, limit);
4693                if (!ret) {
4694                        if (memlimit == limit)
4695                                memcg->memsw_is_minimum = true;
4696                        else
4697                                memcg->memsw_is_minimum = false;
4698                }
4699                mutex_unlock(&memcg_limit_mutex);
4700
4701                if (!ret)
4702                        break;
4703
4704                mem_cgroup_reclaim(memcg, GFP_KERNEL,
4705                                   MEM_CGROUP_RECLAIM_NOSWAP |
4706                                   MEM_CGROUP_RECLAIM_SHRINK);
4707                curusage = page_counter_read(&memcg->memsw);
4708                /* Usage is reduced ? */
4709                if (curusage >= oldusage)
4710                        retry_count--;
4711                else
4712                        oldusage = curusage;
4713        } while (retry_count);
4714
4715        if (!ret && enlarge)
4716                memcg_oom_recover(memcg);
4717        return ret;
4718}
4719
4720unsigned long mem_cgroup_soft_limit_reclaim(struct zone *zone, int order,
4721                                            gfp_t gfp_mask,
4722                                            unsigned long *total_scanned)
4723{
4724        unsigned long nr_reclaimed = 0;
4725        struct mem_cgroup_per_zone *mz, *next_mz = NULL;
4726        unsigned long reclaimed;
4727        int loop = 0;
4728        struct mem_cgroup_tree_per_zone *mctz;
4729        unsigned long excess;
4730        unsigned long nr_scanned;
4731
4732        if (order > 0)
4733                return 0;
4734
4735        mctz = soft_limit_tree_node_zone(zone_to_nid(zone), zone_idx(zone));
4736        /*
4737         * This loop can run a while, specially if mem_cgroup's continuously
4738         * keep exceeding their soft limit and putting the system under
4739         * pressure
4740         */
4741        do {
4742                if (next_mz)
4743                        mz = next_mz;
4744                else
4745                        mz = mem_cgroup_largest_soft_limit_node(mctz);
4746                if (!mz)
4747                        break;
4748
4749                nr_scanned = 0;
4750                reclaimed = mem_cgroup_soft_reclaim(mz->memcg, zone,
4751                                                    gfp_mask, &nr_scanned);
4752                nr_reclaimed += reclaimed;
4753                *total_scanned += nr_scanned;
4754                spin_lock(&mctz->lock);
4755
4756                /*
4757                 * If we failed to reclaim anything from this memory cgroup
4758                 * it is time to move on to the next cgroup
4759                 */
4760                next_mz = NULL;
4761                if (!reclaimed) {
4762                        do {
4763                                /*
4764                                 * Loop until we find yet another one.
4765                                 *
4766                                 * By the time we get the soft_limit lock
4767                                 * again, someone might have aded the
4768                                 * group back on the RB tree. Iterate to
4769                                 * make sure we get a different mem.
4770                                 * mem_cgroup_largest_soft_limit_node returns
4771                                 * NULL if no other cgroup is present on
4772                                 * the tree
4773                                 */
4774                                next_mz =
4775                                __mem_cgroup_largest_soft_limit_node(mctz);
4776                                if (next_mz == mz)
4777                                        css_put(&next_mz->memcg->css);
4778                                else /* next_mz == NULL or other memcg */
4779                                        break;
4780                        } while (1);
4781                }
4782                __mem_cgroup_remove_exceeded(mz->memcg, mz, mctz);
4783                excess = soft_limit_excess(mz->memcg);
4784                /*
4785                 * One school of thought says that we should not add
4786                 * back the node to the tree if reclaim returns 0.
4787                 * But our reclaim could return 0, simply because due
4788                 * to priority we are exposing a smaller subset of
4789                 * memory to reclaim from. Consider this as a longer
4790                 * term TODO.
4791                 */
4792                /* If excess == 0, no tree ops */
4793                __mem_cgroup_insert_exceeded(mz->memcg, mz, mctz, excess);
4794                spin_unlock(&mctz->lock);
4795                css_put(&mz->memcg->css);
4796                loop++;
4797                /*
4798                 * Could not reclaim anything and there are no more
4799                 * mem cgroups to try or we seem to be looping without
4800                 * reclaiming anything.
4801                 */
4802                if (!nr_reclaimed &&
4803                        (next_mz == NULL ||
4804                        loop > MEM_CGROUP_MAX_SOFT_LIMIT_RECLAIM_LOOPS))
4805                        break;
4806        } while (!nr_reclaimed);
4807        if (next_mz)
4808                css_put(&next_mz->memcg->css);
4809        return nr_reclaimed;
4810}
4811
4812/**
4813 * mem_cgroup_force_empty_list - clears LRU of a group
4814 * @memcg: group to clear
4815 * @node: NUMA node
4816 * @zid: zone id
4817 * @lru: lru to to clear
4818 *
4819 * Traverse a specified page_cgroup list and try to drop them all.  This doesn't
4820 * reclaim the pages page themselves - pages are moved to the parent (or root)
4821 * group.
4822 */
4823static void mem_cgroup_force_empty_list(struct mem_cgroup *memcg,
4824                                int node, int zid, enum lru_list lru)
4825{
4826        struct lruvec *lruvec;
4827        unsigned long flags;
4828        struct list_head *list;
4829        struct page *busy;
4830        struct zone *zone;
4831
4832        zone = &NODE_DATA(node)->node_zones[zid];
4833        lruvec = mem_cgroup_zone_lruvec(zone, memcg);
4834        list = &lruvec->lists[lru];
4835
4836        busy = NULL;
4837        do {
4838                struct page_cgroup *pc;
4839                struct page *page;
4840
4841                cond_resched();
4842                spin_lock_irqsave(&zone->lru_lock, flags);
4843                if (list_empty(list)) {
4844                        spin_unlock_irqrestore(&zone->lru_lock, flags);
4845                        break;
4846                }
4847                page = list_entry(list->prev, struct page, lru);
4848                if (busy == page) {
4849                        list_move(&page->lru, list);
4850                        busy = NULL;
4851                        spin_unlock_irqrestore(&zone->lru_lock, flags);
4852                        continue;
4853                }
4854                spin_unlock_irqrestore(&zone->lru_lock, flags);
4855
4856                pc = lookup_page_cgroup(page);
4857
4858                if (mem_cgroup_move_parent(page, pc, memcg)) {
4859                        /* found lock contention or "pc" is obsolete. */
4860                        busy = page;
4861                } else
4862                        busy = NULL;
4863        } while (!list_empty(list));
4864}
4865
4866/*
4867 * make mem_cgroup's charge to be 0 if there is no task by moving
4868 * all the charges and pages to the parent.
4869 * This enables deleting this mem_cgroup.
4870 *
4871 * Caller is responsible for holding css reference on the memcg.
4872 */
4873static void mem_cgroup_reparent_charges(struct mem_cgroup *memcg)
4874{
4875        int node, zid;
4876
4877        do {
4878                /* This is for making all *used* pages to be on LRU. */
4879                lru_add_drain_all();
4880                drain_all_stock_sync(memcg);
4881                mem_cgroup_start_move(memcg);
4882                for_each_node_state(node, N_MEMORY) {
4883                        for (zid = 0; zid < MAX_NR_ZONES; zid++) {
4884                                enum lru_list lru;
4885                                for_each_lru(lru) {
4886                                        mem_cgroup_force_empty_list(memcg,
4887                                                        node, zid, lru);
4888                                }
4889                        }
4890                }
4891                mem_cgroup_end_move(memcg);
4892                memcg_oom_recover(memcg);
4893                cond_resched();
4894
4895                /*
4896                 * Kernel memory may not necessarily be trackable to a specific
4897                 * process. So they are not migrated, and therefore we can't
4898                 * expect their value to drop to 0 here.
4899                 * Having res filled up with kmem only is enough.
4900                 *
4901                 * This is a safety check because mem_cgroup_force_empty_list
4902                 * could have raced with mem_cgroup_replace_page_cache callers
4903                 * so the lru seemed empty but the page could have been added
4904                 * right after the check. RES_USAGE should be safe as we always
4905                 * charge before adding to the LRU.
4906                 */
4907        } while (page_counter_read(&memcg->memory) -
4908                 page_counter_read(&memcg->kmem) > 0);
4909}
4910
4911/*
4912 * This mainly exists for tests during the setting of set of use_hierarchy.
4913 * Since this is the very setting we are changing, the current hierarchy value
4914 * is meaningless
4915 */
4916static inline bool __memcg_has_children(struct mem_cgroup *memcg)
4917{
4918        struct cgroup *pos;
4919
4920        /* bounce at first found */
4921        cgroup_for_each_child(pos, memcg->css.cgroup)
4922                return true;
4923        return false;
4924}
4925
4926/*
4927 * Must be called with memcg_create_mutex held, unless the cgroup is guaranteed
4928 * to be already dead (as in mem_cgroup_force_empty, for instance).  This is
4929 * from mem_cgroup_count_children(), in the sense that we don't really care how
4930 * many children we have; we only need to know if we have any.  It also counts
4931 * any memcg without hierarchy as infertile.
4932 */
4933static inline bool memcg_has_children(struct mem_cgroup *memcg)
4934{
4935        return memcg->use_hierarchy && __memcg_has_children(memcg);
4936}
4937
4938/*
4939 * Reclaims as many pages from the given memcg as possible and moves
4940 * the rest to the parent.
4941 *
4942 * Caller is responsible for holding css reference for memcg.
4943 */
4944static int mem_cgroup_force_empty(struct mem_cgroup *memcg)
4945{
4946        int nr_retries = MEM_CGROUP_RECLAIM_RETRIES;
4947        struct cgroup *cgrp = memcg->css.cgroup;
4948
4949        /* returns EBUSY if there is a task or if we come here twice. */
4950        if (cgroup_task_count(cgrp) || !list_empty(&cgrp->children))
4951                return -EBUSY;
4952
4953        /* we call try-to-free pages for make this cgroup empty */
4954        lru_add_drain_all();
4955        /* try to free all pages in this cgroup */
4956        while (nr_retries && page_counter_read(&memcg->memory)) {
4957                int progress;
4958
4959                if (signal_pending(current))
4960                        return -EINTR;
4961
4962                progress = try_to_free_mem_cgroup_pages(memcg, GFP_KERNEL,
4963                                                false);
4964                if (!progress) {
4965                        nr_retries--;
4966                        /* maybe some writeback is necessary */
4967                        congestion_wait(BLK_RW_ASYNC, HZ/10);
4968                }
4969
4970        }
4971        lru_add_drain();
4972        mem_cgroup_reparent_charges(memcg);
4973
4974        return 0;
4975}
4976
4977static int mem_cgroup_force_empty_write(struct cgroup *cont, unsigned int event)
4978{
4979        struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
4980        int ret;
4981
4982        if (mem_cgroup_is_root(memcg))
4983                return -EINVAL;
4984        css_get(&memcg->css);
4985        ret = mem_cgroup_force_empty(memcg);
4986        css_put(&memcg->css);
4987
4988        return ret;
4989}
4990
4991
4992static u64 mem_cgroup_hierarchy_read(struct cgroup *cont, struct cftype *cft)
4993{
4994        return mem_cgroup_from_cont(cont)->use_hierarchy;
4995}
4996
4997static int mem_cgroup_hierarchy_write(struct cgroup *cont, struct cftype *cft,
4998                                        u64 val)
4999{
5000        int retval = 0;
5001        struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5002        struct cgroup *parent = cont->parent;
5003        struct mem_cgroup *parent_memcg = NULL;
5004
5005        if (parent)
5006                parent_memcg = mem_cgroup_from_cont(parent);
5007
5008        mutex_lock(&memcg_create_mutex);
5009
5010        if (memcg->use_hierarchy == val)
5011                goto out;
5012
5013        /*
5014         * If parent's use_hierarchy is set, we can't make any modifications
5015         * in the child subtrees. If it is unset, then the change can
5016         * occur, provided the current cgroup has no children.
5017         *
5018         * For the root cgroup, parent_mem is NULL, we allow value to be
5019         * set if there are no children.
5020         */
5021        if ((!parent_memcg || !parent_memcg->use_hierarchy) &&
5022                                (val == 1 || val == 0)) {
5023                if (!__memcg_has_children(memcg))
5024                        memcg->use_hierarchy = val;
5025                else
5026                        retval = -EBUSY;
5027        } else
5028                retval = -EINVAL;
5029
5030out:
5031        mutex_unlock(&memcg_create_mutex);
5032
5033        return retval;
5034}
5035
5036
5037static unsigned long tree_stat(struct mem_cgroup *memcg,
5038                               enum mem_cgroup_stat_index idx)
5039{
5040        struct mem_cgroup *iter;
5041        long val = 0;
5042
5043        /* Per-cpu values can be negative, use a signed accumulator */
5044        for_each_mem_cgroup_tree(iter, memcg)
5045                val += mem_cgroup_read_stat(iter, idx);
5046
5047        if (val < 0) /* race ? */
5048                val = 0;
5049        return val;
5050}
5051
5052static inline unsigned long mem_cgroup_usage(struct mem_cgroup *memcg, bool swap)
5053{
5054        unsigned long val;
5055
5056        if (mem_cgroup_is_root(memcg)) {
5057                val = tree_stat(memcg, MEM_CGROUP_STAT_CACHE);
5058                val += tree_stat(memcg, MEM_CGROUP_STAT_RSS);
5059                if (swap)
5060                        val += tree_stat(memcg, MEM_CGROUP_STAT_SWAP);
5061        } else {
5062                if (!swap)
5063                        val = page_counter_read(&memcg->memory);
5064                else
5065                        val = page_counter_read(&memcg->memsw);
5066        }
5067        return val;
5068}
5069
5070struct accumulated_stats {
5071        unsigned long stat[MEM_CGROUP_STAT_NSTATS];
5072        unsigned long events[MEM_CGROUP_EVENTS_NSTATS];
5073        unsigned long lru_pages[NR_LRU_LISTS];
5074};
5075
5076static void accumulate_memcg_tree(struct mem_cgroup *memcg,
5077                                  struct accumulated_stats *acc)
5078{
5079        struct mem_cgroup *mi;
5080        int i;
5081
5082        for_each_mem_cgroup_tree(mi, memcg) {
5083                mem_cgroup_sum_all_stat_events(mi, acc->stat, acc->events);
5084
5085                for (i = 0; i < NR_LRU_LISTS; i++)
5086                        acc->lru_pages[i] += mem_cgroup_nr_lru_pages(mi, BIT(i));
5087
5088                cond_resched();
5089        }
5090}
5091
5092enum {
5093        RES_USAGE,
5094        RES_LIMIT,
5095        RES_MAX_USAGE,
5096        RES_FAILCNT,
5097        RES_SOFT_LIMIT,
5098};
5099
5100static ssize_t mem_cgroup_read(struct cgroup *cont, struct cftype *cft,
5101                               struct file *file, char __user *buf,
5102                               size_t nbytes, loff_t *ppos)
5103{
5104        struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5105        char str[64];
5106        u64 val;
5107        int len;
5108        struct page_counter *counter;
5109
5110        switch (MEMFILE_TYPE(cft->private)) {
5111        case _MEM:
5112                counter = &memcg->memory;
5113                break;
5114        case _MEMSWAP:
5115                counter = &memcg->memsw;
5116                break;
5117        case _KMEM:
5118                counter = &memcg->kmem;
5119                break;
5120        default:
5121                BUG();
5122        }
5123
5124        switch (MEMFILE_ATTR(cft->private)) {
5125        case RES_USAGE:
5126                if (counter == &memcg->memory)
5127                        val = (u64)mem_cgroup_usage(memcg, false) * PAGE_SIZE;
5128                else if (counter == &memcg->memsw)
5129                        val = (u64)mem_cgroup_usage(memcg, true) * PAGE_SIZE;
5130                else
5131                        val = (u64)page_counter_read(counter) * PAGE_SIZE;
5132                break;
5133        case RES_LIMIT:
5134                val = (u64)counter->limit * PAGE_SIZE;
5135                break;
5136        case RES_MAX_USAGE:
5137                val = (u64)counter->watermark * PAGE_SIZE;
5138                break;
5139        case RES_FAILCNT:
5140                val = (u64)counter->failcnt;
5141                break;
5142        case RES_SOFT_LIMIT:
5143                val = (u64)memcg->soft_limit * PAGE_SIZE;
5144                break;
5145        default:
5146                BUG();
5147        }
5148
5149        len = scnprintf(str, sizeof(str), "%llu\n", (unsigned long long)val);
5150        return simple_read_from_buffer(buf, nbytes, ppos, str, len);
5151}
5152
5153static int memcg_update_kmem_limit(struct cgroup *cont, unsigned long limit)
5154{
5155        int ret = -EINVAL;
5156#ifdef CONFIG_MEMCG_KMEM
5157        struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5158
5159        /*
5160         * When cgroup_memory_nokmem is set, kmem limit update is silently
5161         * ignored to not break existing applications that write to
5162         * kmem.limit_in_bytes.
5163         */
5164        if (cgroup_memory_nokmem)
5165                return 0;
5166
5167        /*
5168         * For simplicity, we won't allow this to be disabled.  It also can't
5169         * be changed if the cgroup has children already, or if tasks had
5170         * already joined.
5171         *
5172         * If tasks join before we set the limit, a person looking at
5173         * kmem.usage_in_bytes will have no way to determine when it took
5174         * place, which makes the value quite meaningless.
5175         *
5176         * After it first became limited, changes in the value of the limit are
5177         * of course permitted.
5178         */
5179        mutex_lock(&memcg_create_mutex);
5180        mutex_lock(&memcg_limit_mutex);
5181        if (!memcg->kmem_account_flags && limit != PAGE_COUNTER_MAX) {
5182                if (cgroup_task_count(cont) || memcg_has_children(memcg)) {
5183                        ret = -EBUSY;
5184                        goto out;
5185                }
5186                ret = page_counter_limit(&memcg->kmem, limit);
5187                VM_BUG_ON(ret);
5188
5189                ret = memcg_update_cache_sizes(memcg);
5190                if (ret) {
5191                        page_counter_limit(&memcg->kmem, PAGE_COUNTER_MAX);
5192                        goto out;
5193                }
5194                static_key_slow_inc(&memcg_kmem_enabled_key);
5195                /*
5196                 * setting the active bit after the inc will guarantee no one
5197                 * starts accounting before all call sites are patched
5198                 */
5199                memcg_kmem_set_active(memcg);
5200
5201                /*
5202                 * kmem charges can outlive the cgroup. In the case of slab
5203                 * pages, for instance, a page contain objects from various
5204                 * processes, so it is unfeasible to migrate them away. We
5205                 * need to reference count the memcg because of that.
5206                 */
5207                mem_cgroup_get(memcg);
5208        } else
5209                ret = page_counter_limit(&memcg->kmem, limit);
5210out:
5211        mutex_unlock(&memcg_limit_mutex);
5212        mutex_unlock(&memcg_create_mutex);
5213#endif
5214        return ret;
5215}
5216
5217#ifdef CONFIG_MEMCG_KMEM
5218static int memcg_propagate_kmem(struct mem_cgroup *memcg)
5219{
5220        int ret = 0;
5221        struct mem_cgroup *parent = parent_mem_cgroup(memcg);
5222
5223        if (!parent || cgroup_memory_nokmem)
5224                goto out;
5225
5226        memcg->kmem_account_flags = parent->kmem_account_flags;
5227        /*
5228         * When that happen, we need to disable the static branch only on those
5229         * memcgs that enabled it. To achieve this, we would be forced to
5230         * complicate the code by keeping track of which memcgs were the ones
5231         * that actually enabled limits, and which ones got it from its
5232         * parents.
5233         *
5234         * It is a lot simpler just to do static_key_slow_inc() on every child
5235         * that is accounted.
5236         */
5237        if (!memcg_kmem_is_active(memcg))
5238                goto out;
5239
5240        /*
5241         * destroy(), called if we fail, will issue static_key_slow_inc() and
5242         * mem_cgroup_put() if kmem is enabled. We have to either call them
5243         * unconditionally, or clear the KMEM_ACTIVE flag. I personally find
5244         * this more consistent, since it always leads to the same destroy path
5245         */
5246        mem_cgroup_get(memcg);
5247        static_key_slow_inc(&memcg_kmem_enabled_key);
5248
5249        mutex_lock(&memcg_limit_mutex);
5250        memcg_stop_kmem_account();
5251        ret = memcg_update_cache_sizes(memcg);
5252        memcg_resume_kmem_account();
5253        mutex_unlock(&memcg_limit_mutex);
5254out:
5255        return ret;
5256}
5257#endif /* CONFIG_MEMCG_KMEM */
5258
5259/*
5260 * The user of this function is...
5261 * RES_LIMIT.
5262 */
5263static int mem_cgroup_write(struct cgroup *cont, struct cftype *cft,
5264                            const char *buffer)
5265{
5266        struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5267        unsigned long nr_pages;
5268        int ret;
5269
5270        ret = page_counter_memparse(buffer, &nr_pages);
5271        if (ret)
5272                return ret;
5273
5274        switch (MEMFILE_ATTR(cft->private)) {
5275        case RES_LIMIT:
5276                if (mem_cgroup_is_root(memcg)) { /* Can't set limit on root */
5277                        ret = -EINVAL;
5278                        break;
5279                }
5280                switch (MEMFILE_TYPE(cft->private)) {
5281                case _MEM:
5282                        ret = mem_cgroup_resize_limit(memcg, nr_pages);
5283                        break;
5284                case _MEMSWAP:
5285                        ret = mem_cgroup_resize_memsw_limit(memcg, nr_pages);
5286                        break;
5287                case _KMEM:
5288                        ret = memcg_update_kmem_limit(cont, nr_pages);
5289                        break;
5290                }
5291                break;
5292        case RES_SOFT_LIMIT:
5293                memcg->soft_limit = nr_pages;
5294                ret = 0;
5295                break;
5296        }
5297        return ret;
5298}
5299
5300static int mem_cgroup_reset(struct cgroup *cont, unsigned int event)
5301{
5302        struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5303        struct page_counter *counter;
5304
5305        switch (MEMFILE_TYPE(event)) {
5306        case _MEM:
5307                counter = &memcg->memory;
5308                break;
5309        case _MEMSWAP:
5310                counter = &memcg->memsw;
5311                break;
5312        case _KMEM:
5313                counter = &memcg->kmem;
5314                break;
5315        default:
5316                BUG();
5317        }
5318
5319        switch (MEMFILE_ATTR(event)) {
5320        case RES_MAX_USAGE:
5321                page_counter_reset_watermark(counter);
5322                break;
5323        case RES_FAILCNT:
5324                counter->failcnt = 0;
5325                break;
5326        default:
5327                BUG();
5328        }
5329
5330        return 0;
5331}
5332
5333static u64 mem_cgroup_move_charge_read(struct cgroup *cgrp,
5334                                        struct cftype *cft)
5335{
5336        return mem_cgroup_from_cont(cgrp)->move_charge_at_immigrate;
5337}
5338
5339#ifdef CONFIG_MMU
5340static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
5341                                        struct cftype *cft, u64 val)
5342{
5343        struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5344
5345        if (val >= (1 << NR_MOVE_TYPE))
5346                return -EINVAL;
5347
5348        /*
5349         * No kind of locking is needed in here, because ->can_attach() will
5350         * check this value once in the beginning of the process, and then carry
5351         * on with stale data. This means that changes to this value will only
5352         * affect task migrations starting after the change.
5353         */
5354        memcg->move_charge_at_immigrate = val;
5355        return 0;
5356}
5357#else
5358static int mem_cgroup_move_charge_write(struct cgroup *cgrp,
5359                                        struct cftype *cft, u64 val)
5360{
5361        return -ENOSYS;
5362}
5363#endif
5364
5365#ifdef CONFIG_NUMA
5366static int memcg_numa_stat_show(struct cgroup *cont, struct cftype *cft,
5367                                      struct seq_file *m)
5368{
5369        int nid;
5370        unsigned long total_nr, file_nr, anon_nr, unevictable_nr;
5371        unsigned long node_nr;
5372        struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5373
5374        total_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL);
5375        seq_printf(m, "total=%lu", total_nr);
5376        for_each_node_state(nid, N_MEMORY) {
5377                node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid, LRU_ALL);
5378                seq_printf(m, " N%d=%lu", nid, node_nr);
5379        }
5380        seq_putc(m, '\n');
5381
5382        file_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_FILE);
5383        seq_printf(m, "file=%lu", file_nr);
5384        for_each_node_state(nid, N_MEMORY) {
5385                node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5386                                LRU_ALL_FILE);
5387                seq_printf(m, " N%d=%lu", nid, node_nr);
5388        }
5389        seq_putc(m, '\n');
5390
5391        anon_nr = mem_cgroup_nr_lru_pages(memcg, LRU_ALL_ANON);
5392        seq_printf(m, "anon=%lu", anon_nr);
5393        for_each_node_state(nid, N_MEMORY) {
5394                node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5395                                LRU_ALL_ANON);
5396                seq_printf(m, " N%d=%lu", nid, node_nr);
5397        }
5398        seq_putc(m, '\n');
5399
5400        unevictable_nr = mem_cgroup_nr_lru_pages(memcg, BIT(LRU_UNEVICTABLE));
5401        seq_printf(m, "unevictable=%lu", unevictable_nr);
5402        for_each_node_state(nid, N_MEMORY) {
5403                node_nr = mem_cgroup_node_nr_lru_pages(memcg, nid,
5404                                BIT(LRU_UNEVICTABLE));
5405                seq_printf(m, " N%d=%lu", nid, node_nr);
5406        }
5407        seq_putc(m, '\n');
5408        return 0;
5409}
5410#endif /* CONFIG_NUMA */
5411
5412static inline void mem_cgroup_lru_names_not_uptodate(void)
5413{
5414        BUILD_BUG_ON(ARRAY_SIZE(mem_cgroup_lru_names) != NR_LRU_LISTS);
5415}
5416
5417static int memcg_stat_show(struct cgroup *cont, struct cftype *cft,
5418                                 struct seq_file *m)
5419{
5420        struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
5421        unsigned long memory, memsw;
5422        struct mem_cgroup *mi;
5423        unsigned int i;
5424        struct accumulated_stats acc;
5425
5426        for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
5427                if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
5428                        continue;
5429                seq_printf(m, "%s %ld\n", mem_cgroup_stat_names[i],
5430                           mem_cgroup_read_stat(memcg, i) * PAGE_SIZE);
5431        }
5432
5433        for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
5434                seq_printf(m, "%s %lu\n", mem_cgroup_events_names[i],
5435                           mem_cgroup_read_events(memcg, i));
5436
5437        for (i = 0; i < NR_LRU_LISTS; i++)
5438                seq_printf(m, "%s %lu\n", mem_cgroup_lru_names[i],
5439                           mem_cgroup_nr_lru_pages(memcg, BIT(i)) * PAGE_SIZE);
5440
5441        /* Hierarchical information */
5442        memory = memsw = PAGE_COUNTER_MAX;
5443        for (mi = memcg; mi; mi = parent_mem_cgroup(mi)) {
5444                memory = min(memory, mi->memory.limit);
5445                memsw = min(memsw, mi->memsw.limit);
5446        }
5447        seq_printf(m, "hierarchical_memory_limit %llu\n",
5448                   (u64)memory * PAGE_SIZE);
5449        if (do_swap_account)
5450                seq_printf(m, "hierarchical_memsw_limit %llu\n",
5451                           (u64)memsw * PAGE_SIZE);
5452
5453        memset(&acc, 0, sizeof(acc));
5454        accumulate_memcg_tree(memcg, &acc);
5455
5456        for (i = 0; i < MEM_CGROUP_STAT_NSTATS; i++) {
5457                if (i == MEM_CGROUP_STAT_SWAP && !do_swap_account)
5458                        continue;
5459                seq_printf(m, "total_%s %lld\n", mem_cgroup_stat_names[i],
5460                           (u64)acc.stat[i] * PAGE_SIZE);
5461        }
5462
5463        for (i = 0; i < MEM_CGROUP_EVENTS_NSTATS; i++)
5464                seq_printf(m, "total_%s %llu\n", mem_cgroup_events_names[i],
5465                           (u64)acc.events[i]);
5466
5467        for (i = 0; i < NR_LRU_LISTS; i++)
5468                seq_printf(m, "total_%s %llu\n", mem_cgroup_lru_names[i],
5469                           (u64)acc.lru_pages[i] * PAGE_SIZE);
5470
5471#ifdef CONFIG_DEBUG_VM
5472        {
5473                int nid, zid;
5474                struct mem_cgroup_per_zone *mz;
5475                struct zone_reclaim_stat *rstat;
5476                unsigned long recent_rotated[2] = {0, 0};
5477                unsigned long recent_scanned[2] = {0, 0};
5478
5479                for_each_online_node(nid)
5480                        for (zid = 0; zid < MAX_NR_ZONES; zid++) {
5481                                mz = mem_cgroup_zoneinfo(memcg, nid, zid);
5482                                rstat = &mz->lruvec.reclaim_stat;
5483
5484                                recent_rotated[0] += rstat->recent_rotated[0];
5485                                recent_rotated[1] += rstat->recent_rotated[1];
5486                                recent_scanned[0] += rstat->recent_scanned[0];
5487                                recent_scanned[1] += rstat->recent_scanned[1];
5488                        }
5489                seq_printf(m, "recent_rotated_anon %lu\n", recent_rotated[0]);
5490                seq_printf(m, "recent_rotated_file %lu\n", recent_rotated[1]);
5491                seq_printf(m, "recent_scanned_anon %lu\n", recent_scanned[0]);
5492                seq_printf(m, "recent_scanned_file %lu\n", recent_scanned[1]);
5493        }
5494#endif
5495
5496        return 0;
5497}
5498
5499static u64 mem_cgroup_swappiness_read(struct cgroup *cgrp, struct cftype *cft)
5500{
5501        struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5502
5503        return mem_cgroup_swappiness(memcg);
5504}
5505
5506static int mem_cgroup_swappiness_write(struct cgroup *cgrp, struct cftype *cft,
5507                                       u64 val)
5508{
5509        struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5510
5511        if (val > 100)
5512                return -EINVAL;
5513
5514        if (cgrp->parent)
5515                memcg->swappiness = val;
5516        else
5517                vm_swappiness = val;
5518
5519        return 0;
5520}
5521
5522static void __mem_cgroup_threshold(struct mem_cgroup *memcg, bool swap)
5523{
5524        struct mem_cgroup_threshold_ary *t;
5525        unsigned long usage;
5526        int i;
5527
5528        rcu_read_lock();
5529        if (!swap)
5530                t = rcu_dereference(memcg->thresholds.primary);
5531        else
5532                t = rcu_dereference(memcg->memsw_thresholds.primary);
5533
5534        if (!t)
5535                goto unlock;
5536
5537        usage = mem_cgroup_usage(memcg, swap);
5538
5539        /*
5540         * current_threshold points to threshold just below or equal to usage.
5541         * If it's not true, a threshold was crossed after last
5542         * call of __mem_cgroup_threshold().
5543         */
5544        i = t->current_threshold;
5545
5546        /*
5547         * Iterate backward over array of thresholds starting from
5548         * current_threshold and check if a threshold is crossed.
5549         * If none of thresholds below usage is crossed, we read
5550         * only one element of the array here.
5551         */
5552        for (; i >= 0 && unlikely(t->entries[i].threshold > usage); i--)
5553                eventfd_signal(t->entries[i].eventfd, 1);
5554
5555        /* i = current_threshold + 1 */
5556        i++;
5557
5558        /*
5559         * Iterate forward over array of thresholds starting from
5560         * current_threshold+1 and check if a threshold is crossed.
5561         * If none of thresholds above usage is crossed, we read
5562         * only one element of the array here.
5563         */
5564        for (; i < t->size && unlikely(t->entries[i].threshold <= usage); i++)
5565                eventfd_signal(t->entries[i].eventfd, 1);
5566
5567        /* Update current_threshold */
5568        t->current_threshold = i - 1;
5569unlock:
5570        rcu_read_unlock();
5571}
5572
5573static void mem_cgroup_threshold(struct mem_cgroup *memcg)
5574{
5575        while (memcg) {
5576                __mem_cgroup_threshold(memcg, false);
5577                if (do_swap_account)
5578                        __mem_cgroup_threshold(memcg, true);
5579
5580                memcg = parent_mem_cgroup(memcg);
5581        }
5582}
5583
5584static int compare_thresholds(const void *a, const void *b)
5585{
5586        const struct mem_cgroup_threshold *_a = a;
5587        const struct mem_cgroup_threshold *_b = b;
5588
5589        if (_a->threshold > _b->threshold)
5590                return 1;
5591
5592        if (_a->threshold < _b->threshold)
5593                return -1;
5594
5595        return 0;
5596}
5597
5598static int mem_cgroup_oom_notify_cb(struct mem_cgroup *memcg)
5599{
5600        struct mem_cgroup_eventfd_list *ev;
5601
5602        spin_lock(&memcg_oom_lock);
5603
5604        list_for_each_entry(ev, &memcg->oom_notify, list)
5605                eventfd_signal(ev->eventfd, 1);
5606
5607        spin_unlock(&memcg_oom_lock);
5608        return 0;
5609}
5610
5611static void mem_cgroup_oom_notify(struct mem_cgroup *memcg)
5612{
5613        struct mem_cgroup *iter;
5614
5615        for_each_mem_cgroup_tree(iter, memcg)
5616                mem_cgroup_oom_notify_cb(iter);
5617}
5618
5619static int mem_cgroup_usage_register_event(struct cgroup *cgrp,
5620        struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
5621{
5622        struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5623        struct mem_cgroup_thresholds *thresholds;
5624        struct mem_cgroup_threshold_ary *new;
5625        enum res_type type = MEMFILE_TYPE(cft->private);
5626        unsigned long threshold;
5627        unsigned long usage;
5628        int i, size, ret;
5629
5630        ret = page_counter_memparse(args, &threshold);
5631        if (ret)
5632                return ret;
5633
5634        mutex_lock(&memcg->thresholds_lock);
5635
5636        if (type == _MEM)
5637                thresholds = &memcg->thresholds;
5638        else if (type == _MEMSWAP)
5639                thresholds = &memcg->memsw_thresholds;
5640        else
5641                BUG();
5642
5643        usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
5644
5645        /* Check if a threshold crossed before adding a new one */
5646        if (thresholds->primary)
5647                __mem_cgroup_threshold(memcg, type == _MEMSWAP);
5648
5649        size = thresholds->primary ? thresholds->primary->size + 1 : 1;
5650
5651        /* Allocate memory for new array of thresholds */
5652        new = kmalloc(sizeof(*new) + size * sizeof(struct mem_cgroup_threshold),
5653                        GFP_KERNEL);
5654        if (!new) {
5655                ret = -ENOMEM;
5656                goto unlock;
5657        }
5658        new->size = size;
5659
5660        /* Copy thresholds (if any) to new array */
5661        if (thresholds->primary) {
5662                memcpy(new->entries, thresholds->primary->entries, (size - 1) *
5663                                sizeof(struct mem_cgroup_threshold));
5664        }
5665
5666        /* Add new threshold */
5667        new->entries[size - 1].eventfd = eventfd;
5668        new->entries[size - 1].threshold = threshold;
5669
5670        /* Sort thresholds. Registering of new threshold isn't time-critical */
5671        sort(new->entries, size, sizeof(struct mem_cgroup_threshold),
5672                        compare_thresholds, NULL);
5673
5674        /* Find current threshold */
5675        new->current_threshold = -1;
5676        for (i = 0; i < size; i++) {
5677                if (new->entries[i].threshold <= usage) {
5678                        /*
5679                         * new->current_threshold will not be used until
5680                         * rcu_assign_pointer(), so it's safe to increment
5681                         * it here.
5682                         */
5683                        ++new->current_threshold;
5684                } else
5685                        break;
5686        }
5687
5688        /* Free old spare buffer and save old primary buffer as spare */
5689        kfree(thresholds->spare);
5690        thresholds->spare = thresholds->primary;
5691
5692        rcu_assign_pointer(thresholds->primary, new);
5693
5694        /* To be sure that nobody uses thresholds */
5695        synchronize_rcu();
5696
5697unlock:
5698        mutex_unlock(&memcg->thresholds_lock);
5699
5700        return ret;
5701}
5702
5703static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
5704        struct cftype *cft, struct eventfd_ctx *eventfd)
5705{
5706        struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5707        struct mem_cgroup_thresholds *thresholds;
5708        struct mem_cgroup_threshold_ary *new;
5709        enum res_type type = MEMFILE_TYPE(cft->private);
5710        unsigned long usage;
5711        int i, j, size, entries;
5712
5713        mutex_lock(&memcg->thresholds_lock);
5714        if (type == _MEM)
5715                thresholds = &memcg->thresholds;
5716        else if (type == _MEMSWAP)
5717                thresholds = &memcg->memsw_thresholds;
5718        else
5719                BUG();
5720
5721        if (!thresholds->primary)
5722                goto unlock;
5723
5724        usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
5725
5726        /* Check if a threshold crossed before removing */
5727        __mem_cgroup_threshold(memcg, type == _MEMSWAP);
5728
5729        /* Calculate new number of threshold */
5730        size = entries = 0;
5731        for (i = 0; i < thresholds->primary->size; i++) {
5732                if (thresholds->primary->entries[i].eventfd != eventfd)
5733                        size++;
5734                else
5735                        entries++;
5736        }
5737
5738        new = thresholds->spare;
5739
5740        /* If no items related to eventfd have been cleared, nothing to do */
5741        if (!entries)
5742                goto unlock;
5743
5744        /* Set thresholds array to NULL if we don't have thresholds */
5745        if (!size) {
5746                kfree(new);
5747                new = NULL;
5748                goto swap_buffers;
5749        }
5750
5751        new->size = size;
5752
5753        /* Copy thresholds and find current threshold */
5754        new->current_threshold = -1;
5755        for (i = 0, j = 0; i < thresholds->primary->size; i++) {
5756                if (thresholds->primary->entries[i].eventfd == eventfd)
5757                        continue;
5758
5759                new->entries[j] = thresholds->primary->entries[i];
5760                if (new->entries[j].threshold <= usage) {
5761                        /*
5762                         * new->current_threshold will not be used
5763                         * until rcu_assign_pointer(), so it's safe to increment
5764                         * it here.
5765                         */
5766                        ++new->current_threshold;
5767                }
5768                j++;
5769        }
5770
5771swap_buffers:
5772        /* Swap primary and spare array */
5773        thresholds->spare = thresholds->primary;
5774
5775        rcu_assign_pointer(thresholds->primary, new);
5776
5777        /* To be sure that nobody uses thresholds */
5778        synchronize_rcu();
5779
5780        /* If all events are unregistered, free the spare array */
5781        if (!new) {
5782                kfree(thresholds->spare);
5783                thresholds->spare = NULL;
5784        }
5785unlock:
5786        mutex_unlock(&memcg->thresholds_lock);
5787}
5788
5789static int mem_cgroup_oom_register_event(struct cgroup *cgrp,
5790        struct cftype *cft, struct eventfd_ctx *eventfd, const char *args)
5791{
5792        struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5793        struct mem_cgroup_eventfd_list *event;
5794        enum res_type type = MEMFILE_TYPE(cft->private);
5795
5796        BUG_ON(type != _OOM_TYPE);
5797        event = kmalloc(sizeof(*event), GFP_KERNEL);
5798        if (!event)
5799                return -ENOMEM;
5800
5801        spin_lock(&memcg_oom_lock);
5802
5803        event->eventfd = eventfd;
5804        list_add(&event->list, &memcg->oom_notify);
5805
5806        /* already in OOM ? */
5807        if (atomic_read(&memcg->under_oom))
5808                eventfd_signal(eventfd, 1);
5809        spin_unlock(&memcg_oom_lock);
5810
5811        return 0;
5812}
5813
5814static void mem_cgroup_oom_unregister_event(struct cgroup *cgrp,
5815        struct cftype *cft, struct eventfd_ctx *eventfd)
5816{
5817        struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5818        struct mem_cgroup_eventfd_list *ev, *tmp;
5819        enum res_type type = MEMFILE_TYPE(cft->private);
5820
5821        BUG_ON(type != _OOM_TYPE);
5822
5823        spin_lock(&memcg_oom_lock);
5824
5825        list_for_each_entry_safe(ev, tmp, &memcg->oom_notify, list) {
5826                if (ev->eventfd == eventfd) {
5827                        list_del(&ev->list);
5828                        kfree(ev);
5829                }
5830        }
5831
5832        spin_unlock(&memcg_oom_lock);
5833}
5834
5835static int mem_cgroup_oom_control_read(struct cgroup *cgrp,
5836        struct cftype *cft,  struct cgroup_map_cb *cb)
5837{
5838        struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5839
5840        cb->fill(cb, "oom_kill_disable", memcg->oom_kill_disable);
5841
5842        if (atomic_read(&memcg->under_oom))
5843                cb->fill(cb, "under_oom", 1);
5844        else
5845                cb->fill(cb, "under_oom", 0);
5846        return 0;
5847}
5848
5849static int mem_cgroup_oom_control_write(struct cgroup *cgrp,
5850        struct cftype *cft, u64 val)
5851{
5852        struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
5853
5854        /* cannot set to root cgroup and only 0 and 1 are allowed */
5855        if (!cgrp->parent || !((val == 0) || (val == 1)))
5856                return -EINVAL;
5857
5858        memcg->oom_kill_disable = val;
5859        if (!val)
5860                memcg_oom_recover(memcg);
5861
5862        return 0;
5863}
5864
5865#ifdef CONFIG_MEMCG_KMEM
5866static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5867{
5868        int ret;
5869
5870        memcg->kmemcg_id = -1;
5871        ret = memcg_propagate_kmem(memcg);
5872        if (ret)
5873                return ret;
5874
5875        return mem_cgroup_sockets_init(memcg, ss);
5876}
5877
5878static void kmem_cgroup_destroy(struct mem_cgroup *memcg)
5879{
5880        mem_cgroup_sockets_destroy(memcg);
5881
5882        memcg_kmem_mark_dead(memcg);
5883
5884        if (page_counter_read(&memcg->kmem))
5885                return;
5886
5887        /*
5888         * Charges already down to 0, undo mem_cgroup_get() done in the charge
5889         * path here, being careful not to race with memcg_uncharge_kmem: it is
5890         * possible that the charges went down to 0 between mark_dead and the
5891         * page_counter read, so in that case, we don't need the put
5892         */
5893        if (memcg_kmem_test_and_clear_dead(memcg))
5894                mem_cgroup_put(memcg);
5895}
5896#else
5897static int memcg_init_kmem(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
5898{
5899        return 0;
5900}
5901
5902static void kmem_cgroup_destroy(struct mem_cgroup *memcg)
5903{
5904}
5905#endif
5906
5907static struct cftype mem_cgroup_files[] = {
5908        {
5909                .name = "usage_in_bytes",
5910                .private = MEMFILE_PRIVATE(_MEM, RES_USAGE),
5911                .read = mem_cgroup_read,
5912                .register_event = mem_cgroup_usage_register_event,
5913                .unregister_event = mem_cgroup_usage_unregister_event,
5914        },
5915        {
5916                .name = "max_usage_in_bytes",
5917                .private = MEMFILE_PRIVATE(_MEM, RES_MAX_USAGE),
5918                .trigger = mem_cgroup_reset,
5919                .read = mem_cgroup_read,
5920        },
5921        {
5922                .name = "limit_in_bytes",
5923                .private = MEMFILE_PRIVATE(_MEM, RES_LIMIT),
5924                .write_string = mem_cgroup_write,
5925                .read = mem_cgroup_read,
5926        },
5927        {
5928                .name = "soft_limit_in_bytes",
5929                .private = MEMFILE_PRIVATE(_MEM, RES_SOFT_LIMIT),
5930                .write_string = mem_cgroup_write,
5931                .read = mem_cgroup_read,
5932        },
5933        {
5934                .name = "failcnt",
5935                .private = MEMFILE_PRIVATE(_MEM, RES_FAILCNT),
5936                .trigger = mem_cgroup_reset,
5937                .read = mem_cgroup_read,
5938        },
5939        {
5940                .name = "stat",
5941                .read_seq_string = memcg_stat_show,
5942        },
5943        {
5944                .name = "force_empty",
5945                .trigger = mem_cgroup_force_empty_write,
5946        },
5947        {
5948                .name = "use_hierarchy",
5949                .flags = CFTYPE_INSANE,
5950                .write_u64 = mem_cgroup_hierarchy_write,
5951                .read_u64 = mem_cgroup_hierarchy_read,
5952        },
5953        {
5954                .name = "swappiness",
5955                .read_u64 = mem_cgroup_swappiness_read,
5956                .write_u64 = mem_cgroup_swappiness_write,
5957        },
5958        {
5959                .name = "move_charge_at_immigrate",
5960                .read_u64 = mem_cgroup_move_charge_read,
5961                .write_u64 = mem_cgroup_move_charge_write,
5962        },
5963        {
5964                .name = "oom_control",
5965                .read_map = mem_cgroup_oom_control_read,
5966                .write_u64 = mem_cgroup_oom_control_write,
5967                .register_event = mem_cgroup_oom_register_event,
5968                .unregister_event = mem_cgroup_oom_unregister_event,
5969                .private = MEMFILE_PRIVATE(_OOM_TYPE, OOM_CONTROL),
5970        },
5971        {
5972                .name = "pressure_level",
5973                .register_event = vmpressure_register_event,
5974                .unregister_event = vmpressure_unregister_event,
5975        },
5976#ifdef CONFIG_NUMA
5977        {
5978                .name = "numa_stat",
5979                .read_seq_string = memcg_numa_stat_show,
5980        },
5981#endif
5982#ifdef CONFIG_MEMCG_KMEM
5983        {
5984                .name = "kmem.limit_in_bytes",
5985                .private = MEMFILE_PRIVATE(_KMEM, RES_LIMIT),
5986                .write_string = mem_cgroup_write,
5987                .read = mem_cgroup_read,
5988        },
5989        {
5990                .name = "kmem.usage_in_bytes",
5991                .private = MEMFILE_PRIVATE(_KMEM, RES_USAGE),
5992                .read = mem_cgroup_read,
5993        },
5994        {
5995                .name = "kmem.failcnt",
5996                .private = MEMFILE_PRIVATE(_KMEM, RES_FAILCNT),
5997                .trigger = mem_cgroup_reset,
5998                .read = mem_cgroup_read,
5999        },
6000        {
6001                .name = "kmem.max_usage_in_bytes",
6002                .private = MEMFILE_PRIVATE(_KMEM, RES_MAX_USAGE),
6003                .trigger = mem_cgroup_reset,
6004                .read = mem_cgroup_read,
6005        },
6006#ifdef CONFIG_SLABINFO
6007        {
6008                .name = "kmem.slabinfo",
6009                .read_seq_string = mem_cgroup_slabinfo_read,
6010        },
6011#endif
6012#endif
6013        { },    /* terminate */
6014};
6015
6016#ifdef CONFIG_MEMCG_SWAP
6017static struct cftype memsw_cgroup_files[] = {
6018        {
6019                .name = "memsw.usage_in_bytes",
6020                .private = MEMFILE_PRIVATE(_MEMSWAP, RES_USAGE),
6021                .read = mem_cgroup_read,
6022                .register_event = mem_cgroup_usage_register_event,
6023                .unregister_event = mem_cgroup_usage_unregister_event,
6024        },
6025        {
6026                .name = "memsw.max_usage_in_bytes",
6027                .private = MEMFILE_PRIVATE(_MEMSWAP, RES_MAX_USAGE),
6028                .trigger = mem_cgroup_reset,
6029                .read = mem_cgroup_read,
6030        },
6031        {
6032                .name = "memsw.limit_in_bytes",
6033                .private = MEMFILE_PRIVATE(_MEMSWAP, RES_LIMIT),
6034                .write_string = mem_cgroup_write,
6035                .read = mem_cgroup_read,
6036        },
6037        {
6038                .name = "memsw.failcnt",
6039                .private = MEMFILE_PRIVATE(_MEMSWAP, RES_FAILCNT),
6040                .trigger = mem_cgroup_reset,
6041                .read = mem_cgroup_read,
6042        },
6043        { },    /* terminate */
6044};
6045#endif
6046
6047/*
6048 * Private memory cgroup IDR
6049 *
6050 * Swap-out records and page cache shadow entries need to store memcg
6051 * references in constrained space, so we maintain an ID space that is
6052 * limited to 16 bit (MEM_CGROUP_ID_MAX), limiting the total number of
6053 * memory-controlled cgroups to 64k.
6054 *
6055 * However, there usually are many references to the oflline CSS after
6056 * the cgroup has been destroyed, such as page cache or reclaimable
6057 * slab objects, that don't need to hang on to the ID. We want to keep
6058 * those dead CSS from occupying IDs, or we might quickly exhaust the
6059 * relatively small ID space and prevent the creation of new cgroups
6060 * even when there are much fewer than 64k cgroups - possibly none.
6061 *
6062 * Maintain a private 16-bit ID space for memcg, and allow the ID to
6063 * be freed and recycled when it's no longer needed, which is usually
6064 * when the CSS is offlined.
6065 *
6066 * The only exception to that are records of swapped out tmpfs/shmem
6067 * pages that need to be attributed to live ancestors on swapin. But
6068 * those references are manageable from userspace.
6069 */
6070
6071static DEFINE_IDR(mem_cgroup_idr);
6072
6073static DEFINE_MUTEX(mem_cgroup_idr_lock);
6074
6075static unsigned short mem_cgroup_id(struct mem_cgroup *memcg)
6076{
6077        return memcg->id;
6078}
6079
6080static void mem_cgroup_id_put(struct mem_cgroup *memcg)
6081{
6082        mutex_lock(&mem_cgroup_idr_lock);
6083        idr_remove(&mem_cgroup_idr, memcg->id);
6084        mutex_unlock(&mem_cgroup_idr_lock);
6085        memcg->id = 0;
6086        synchronize_rcu();
6087}
6088
6089/**
6090 * mem_cgroup_from_id - look up a memcg from a memcg id
6091 * @id: the memcg id to look up
6092 *
6093 * Caller must hold rcu_read_lock().
6094 */
6095struct mem_cgroup *mem_cgroup_from_id(unsigned short id)
6096{
6097        WARN_ON_ONCE(!rcu_read_lock_held());
6098        return idr_find(&mem_cgroup_idr, id);
6099}
6100
6101static int alloc_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
6102{
6103        struct mem_cgroup_per_node *pn;
6104        struct mem_cgroup_per_zone *mz;
6105        int zone, tmp = node;
6106        /*
6107         * This routine is called against possible nodes.
6108         * But it's BUG to call kmalloc() against offline node.
6109         *
6110         * TODO: this routine can waste much memory for nodes which will
6111         *       never be onlined. It's better to use memory hotplug callback
6112         *       function.
6113         */
6114        if (!node_state(node, N_NORMAL_MEMORY))
6115                tmp = -1;
6116        pn = kzalloc_node(sizeof(*pn), GFP_KERNEL, tmp);
6117        if (!pn)
6118                return 1;
6119
6120        for (zone = 0; zone < MAX_NR_ZONES; zone++) {
6121                mz = &pn->zoneinfo[zone];
6122                lruvec_init(&mz->lruvec);
6123                mz->usage_in_excess = 0;
6124                mz->on_tree = false;
6125                mz->memcg = memcg;
6126        }
6127        memcg->info.nodeinfo[node] = pn;
6128        return 0;
6129}
6130
6131static void free_mem_cgroup_per_zone_info(struct mem_cgroup *memcg, int node)
6132{
6133        kfree(memcg->info.nodeinfo[node]);
6134}
6135
6136static struct mem_cgroup *mem_cgroup_alloc(void)
6137{
6138        struct mem_cgroup *memcg;
6139        size_t size = memcg_size();
6140        int id;
6141
6142        /* Can be very big if nr_node_ids is very big */
6143        if (size < PAGE_SIZE)
6144                memcg = kzalloc(size, GFP_KERNEL);
6145        else
6146                memcg = vzalloc(size);
6147
6148        if (!memcg)
6149                return NULL;
6150
6151        mutex_lock(&mem_cgroup_idr_lock);
6152        id = idr_alloc(&mem_cgroup_idr, NULL,
6153                       1, MEM_CGROUP_ID_MAX,
6154                       GFP_KERNEL);
6155        mutex_unlock(&mem_cgroup_idr_lock);
6156        if (id < 0)
6157                goto fail;
6158
6159        memcg->id = id;
6160
6161        memcg->stat = alloc_percpu(struct mem_cgroup_stat_cpu);
6162        if (!memcg->stat)
6163                goto out_free;
6164        spin_lock_init(&memcg->pcp_counter_lock);
6165        mutex_lock(&mem_cgroup_idr_lock);
6166        idr_replace(&mem_cgroup_idr, memcg, memcg->id);
6167        mutex_unlock(&mem_cgroup_idr_lock);
6168        synchronize_rcu();
6169        return memcg;
6170
6171out_free:
6172        if (memcg->id > 0) {
6173                mutex_lock(&mem_cgroup_idr_lock);
6174                idr_remove(&mem_cgroup_idr, memcg->id);
6175                mutex_unlock(&mem_cgroup_idr_lock);
6176                synchronize_rcu();
6177        }
6178fail:
6179        if (size < PAGE_SIZE)
6180                kfree(memcg);
6181        else
6182                vfree(memcg);
6183        return NULL;
6184}
6185
6186/*
6187 * At destroying mem_cgroup, references from swap_cgroup can remain.
6188 * (scanning all at force_empty is too costly...)
6189 *
6190 * Instead of clearing all references at force_empty, we remember
6191 * the number of reference from swap_cgroup and free mem_cgroup when
6192 * it goes down to 0.
6193 *
6194 * Removal of cgroup itself succeeds regardless of refs from swap.
6195 */
6196
6197static void __mem_cgroup_free(struct mem_cgroup *memcg)
6198{
6199        int node;
6200        size_t size = memcg_size();
6201
6202        mem_cgroup_remove_from_trees(memcg);
6203
6204        mem_cgroup_id_put(memcg);
6205
6206        for_each_node(node)
6207                free_mem_cgroup_per_zone_info(memcg, node);
6208
6209        free_percpu(memcg->stat);
6210
6211        /*
6212         * We need to make sure that (at least for now), the jump label
6213         * destruction code runs outside of the cgroup lock. This is because
6214         * get_online_cpus(), which is called from the static_branch update,
6215         * can't be called inside the cgroup_lock. cpusets are the ones
6216         * enforcing this dependency, so if they ever change, we might as well.
6217         *
6218         * schedule_work() will guarantee this happens. Be careful if you need
6219         * to move this code around, and make sure it is outside
6220         * the cgroup_lock.
6221         */
6222        disarm_static_keys(memcg);
6223        if (size < PAGE_SIZE)
6224                kfree(memcg);
6225        else
6226                vfree(memcg);
6227}
6228
6229
6230/*
6231 * Helpers for freeing a kmalloc()ed/vzalloc()ed mem_cgroup by RCU,
6232 * but in process context.  The work_freeing structure is overlaid
6233 * on the rcu_freeing structure, which itself is overlaid on memsw.
6234 */
6235static void free_work(struct work_struct *work)
6236{
6237        struct mem_cgroup *memcg;
6238
6239        memcg = container_of(work, struct mem_cgroup, work_freeing);
6240        __mem_cgroup_free(memcg);
6241}
6242
6243static void free_rcu(struct rcu_head *rcu_head)
6244{
6245        struct mem_cgroup *memcg;
6246
6247        memcg = container_of(rcu_head, struct mem_cgroup, rcu_freeing);
6248        INIT_WORK(&memcg->work_freeing, free_work);
6249        schedule_work(&memcg->work_freeing);
6250}
6251
6252static void mem_cgroup_get(struct mem_cgroup *memcg)
6253{
6254        atomic_inc(&memcg->refcnt);
6255}
6256
6257static void __mem_cgroup_put(struct mem_cgroup *memcg, int count)
6258{
6259        if (atomic_sub_and_test(count, &memcg->refcnt)) {
6260                struct mem_cgroup *parent = parent_mem_cgroup(memcg);
6261                call_rcu(&memcg->rcu_freeing, free_rcu);
6262                if (parent)
6263                        mem_cgroup_put(parent);
6264        }
6265}
6266
6267static void mem_cgroup_put(struct mem_cgroup *memcg)
6268{
6269        __mem_cgroup_put(memcg, 1);
6270}
6271
6272/*
6273 * Returns the parent mem_cgroup in memcgroup hierarchy with hierarchy enabled.
6274 */
6275struct mem_cgroup *parent_mem_cgroup(struct mem_cgroup *memcg)
6276{
6277        if (!memcg->memory.parent)
6278                return NULL;
6279        return mem_cgroup_from_counter(memcg->memory.parent, memory);
6280}
6281EXPORT_SYMBOL(parent_mem_cgroup);
6282
6283static void __init mem_cgroup_soft_limit_tree_init(void)
6284{
6285        struct mem_cgroup_tree_per_node *rtpn;
6286        struct mem_cgroup_tree_per_zone *rtpz;
6287        int tmp, node, zone;
6288
6289        for_each_node(node) {
6290                tmp = node;
6291                if (!node_state(node, N_NORMAL_MEMORY))
6292                        tmp = -1;
6293                rtpn = kzalloc_node(sizeof(*rtpn), GFP_KERNEL, tmp);
6294                BUG_ON(!rtpn);
6295
6296                soft_limit_tree.rb_tree_per_node[node] = rtpn;
6297
6298                for (zone = 0; zone < MAX_NR_ZONES; zone++) {
6299                        rtpz = &rtpn->rb_tree_per_zone[zone];
6300                        rtpz->rb_root = RB_ROOT;
6301                        spin_lock_init(&rtpz->lock);
6302                }
6303        }
6304}
6305
6306static struct cgroup_subsys_state * __ref
6307mem_cgroup_css_alloc(struct cgroup *cont)
6308{
6309        struct mem_cgroup *memcg;
6310        long error = -ENOMEM;
6311        int node;
6312
6313        memcg = mem_cgroup_alloc();
6314        if (!memcg)
6315                return ERR_PTR(error);
6316
6317        for_each_node(node)
6318                if (alloc_mem_cgroup_per_zone_info(memcg, node))
6319                        goto free_out;
6320
6321        /* root ? */
6322        if (cont->parent == NULL) {
6323                root_mem_cgroup = memcg;
6324                page_counter_init(&memcg->memory, NULL);
6325                memcg->soft_limit = PAGE_COUNTER_MAX;
6326                page_counter_init(&memcg->memsw, NULL);
6327                page_counter_init(&memcg->kmem, NULL);
6328        }
6329
6330        memcg->last_scanned_node = MAX_NUMNODES;
6331        INIT_LIST_HEAD(&memcg->oom_notify);
6332        atomic_set(&memcg->refcnt, 1);
6333        memcg->move_charge_at_immigrate = 0;
6334        mutex_init(&memcg->thresholds_lock);
6335        spin_lock_init(&memcg->move_lock);
6336        vmpressure_init(&memcg->vmpressure);
6337
6338        return &memcg->css;
6339
6340free_out:
6341        __mem_cgroup_free(memcg);
6342        return ERR_PTR(error);
6343}
6344
6345static int
6346mem_cgroup_css_online(struct cgroup *cont)
6347{
6348        struct mem_cgroup *memcg, *parent;
6349        int error = 0;
6350
6351        if (!cont->parent)
6352                return 0;
6353
6354        mutex_lock(&memcg_create_mutex);
6355        memcg = mem_cgroup_from_cont(cont);
6356        parent = mem_cgroup_from_cont(cont->parent);
6357
6358        memcg->use_hierarchy = parent->use_hierarchy;
6359        memcg->oom_kill_disable = parent->oom_kill_disable;
6360        memcg->swappiness = mem_cgroup_swappiness(parent);
6361
6362        if (parent->use_hierarchy) {
6363                page_counter_init(&memcg->memory, &parent->memory);
6364                memcg->soft_limit = PAGE_COUNTER_MAX;
6365                page_counter_init(&memcg->memsw, &parent->memsw);
6366                page_counter_init(&memcg->kmem, &parent->kmem);
6367
6368                /*
6369                 * We increment refcnt of the parent to ensure that we can
6370                 * safely access it on page_counter_charge/uncharge.
6371                 * This refcnt will be decremented when freeing this
6372                 * mem_cgroup(see mem_cgroup_put).
6373                 */
6374                mem_cgroup_get(parent);
6375        } else {
6376                page_counter_init(&memcg->memory, NULL);
6377                memcg->soft_limit = PAGE_COUNTER_MAX;
6378                page_counter_init(&memcg->memsw, NULL);
6379                page_counter_init(&memcg->kmem, NULL);
6380                /*
6381                 * Deeper hierachy with use_hierarchy == false doesn't make
6382                 * much sense so let cgroup subsystem know about this
6383                 * unfortunate state in our controller.
6384                 */
6385                if (parent != root_mem_cgroup)
6386                        mem_cgroup_subsys.broken_hierarchy = true;
6387        }
6388
6389        error = memcg_init_kmem(memcg, &mem_cgroup_subsys);
6390        mutex_unlock(&memcg_create_mutex);
6391        return error;
6392}
6393
6394/*
6395 * Announce all parents that a group from their hierarchy is gone.
6396 */
6397static void mem_cgroup_invalidate_reclaim_iterators(struct mem_cgroup *memcg)
6398{
6399        struct mem_cgroup *parent = memcg;
6400
6401        while ((parent = parent_mem_cgroup(parent)))
6402                mem_cgroup_iter_invalidate(parent);
6403
6404        /*
6405         * if the root memcg is not hierarchical we have to check it
6406         * explicitely.
6407         */
6408        if (!root_mem_cgroup->use_hierarchy)
6409                mem_cgroup_iter_invalidate(root_mem_cgroup);
6410}
6411
6412static void mem_cgroup_css_offline(struct cgroup *cont)
6413{
6414        struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
6415        struct cgroup *iter;
6416
6417        mem_cgroup_invalidate_reclaim_iterators(memcg);
6418
6419        /*
6420         * This requires that offlining is serialized.  Right now that is
6421         * guaranteed because css_killed_work_fn() holds the cgroup_mutex.
6422         */
6423        rcu_read_lock();
6424        cgroup_for_each_descendant_post(iter, cont) {
6425                rcu_read_unlock();
6426                mem_cgroup_reparent_charges(mem_cgroup_from_cont(iter));
6427                rcu_read_lock();
6428        }
6429        rcu_read_unlock();
6430        mem_cgroup_reparent_charges(memcg);
6431
6432        mem_cgroup_destroy_all_caches(memcg);
6433        vmpressure_cleanup(&memcg->vmpressure);
6434}
6435
6436static void mem_cgroup_css_free(struct cgroup *cont)
6437{
6438        struct mem_cgroup *memcg = mem_cgroup_from_cont(cont);
6439
6440        kmem_cgroup_destroy(memcg);
6441
6442        mem_cgroup_put(memcg);
6443}
6444
6445#ifdef CONFIG_MMU
6446/* Handlers for move charge at task migration. */
6447#define PRECHARGE_COUNT_AT_ONCE 256
6448static int mem_cgroup_do_precharge(unsigned long count)
6449{
6450        int ret = 0;
6451        int batch_count = PRECHARGE_COUNT_AT_ONCE;
6452        struct mem_cgroup *memcg = mc.to;
6453
6454        if (mem_cgroup_is_root(memcg)) {
6455                mc.precharge += count;
6456                /* we don't need css_get for root */
6457                return ret;
6458        }
6459        /* try to charge at once */
6460        if (count > 1) {
6461                struct page_counter *dummy;
6462                /*
6463                 * "memcg" cannot be under rmdir() because we've already checked
6464                 * by cgroup_lock_live_cgroup() that it is not removed and we
6465                 * are still under the same cgroup_mutex. So we can postpone
6466                 * css_get().
6467                 */
6468                if (!page_counter_try_charge(&memcg->memory, count, &dummy))
6469                        goto one_by_one;
6470                if (do_swap_account &&
6471                    !page_counter_try_charge(&memcg->memsw, count, &dummy)) {
6472                        page_counter_uncharge(&memcg->memory, count);
6473                        goto one_by_one;
6474                }
6475                mc.precharge += count;
6476                return ret;
6477        }
6478one_by_one:
6479        /* fall back to one by one charge */
6480        while (count--) {
6481                if (signal_pending(current)) {
6482                        ret = -EINTR;
6483                        break;
6484                }
6485                if (!batch_count--) {
6486                        batch_count = PRECHARGE_COUNT_AT_ONCE;
6487                        cond_resched();
6488                }
6489                ret = __mem_cgroup_try_charge(NULL,
6490                                        GFP_KERNEL, 1, &memcg, false);
6491                if (ret)
6492                        /* mem_cgroup_clear_mc() will do uncharge later */
6493                        return ret;
6494                mc.precharge++;
6495        }
6496        return ret;
6497}
6498
6499/**
6500 * get_mctgt_type - get target type of moving charge
6501 * @vma: the vma the pte to be checked belongs
6502 * @addr: the address corresponding to the pte to be checked
6503 * @ptent: the pte to be checked
6504 * @target: the pointer the target page or swap ent will be stored(can be NULL)
6505 *
6506 * Returns
6507 *   0(MC_TARGET_NONE): if the pte is not a target for move charge.
6508 *   1(MC_TARGET_PAGE): if the page corresponding to this pte is a target for
6509 *     move charge. if @target is not NULL, the page is stored in target->page
6510 *     with extra refcnt got(Callers should handle it).
6511 *   2(MC_TARGET_SWAP): if the swap entry corresponding to this pte is a
6512 *     target for charge migration. if @target is not NULL, the entry is stored
6513 *     in target->ent.
6514 *
6515 * Called with pte lock held.
6516 */
6517union mc_target {
6518        struct page     *page;
6519        swp_entry_t     ent;
6520};
6521
6522enum mc_target_type {
6523        MC_TARGET_NONE = 0,
6524        MC_TARGET_PAGE,
6525        MC_TARGET_SWAP,
6526};
6527
6528static struct page *mc_handle_present_pte(struct vm_area_struct *vma,
6529                                                unsigned long addr, pte_t ptent)
6530{
6531        struct page *page = vm_normal_page(vma, addr, ptent);
6532
6533        if (!page || !page_mapped(page))
6534                return NULL;
6535        if (PageAnon(page)) {
6536                /* we don't move shared anon */
6537                if (!move_anon())
6538                        return NULL;
6539        } else if (!move_file())
6540                /* we ignore mapcount for file pages */
6541                return NULL;
6542        if (!get_page_unless_zero(page))
6543                return NULL;
6544
6545        return page;
6546}
6547
6548#ifdef CONFIG_SWAP
6549static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
6550                        unsigned long addr, pte_t ptent, swp_entry_t *entry)
6551{
6552        struct page *page = NULL;
6553        swp_entry_t ent = pte_to_swp_entry(ptent);
6554
6555        if (!move_anon() || non_swap_entry(ent))
6556                return NULL;
6557        /*
6558         * Because lookup_swap_cache() updates some statistics counter,
6559         * we call find_get_page() with swapper_space directly.
6560         */
6561        page = find_get_page(swap_address_space(ent), ent.val);
6562        if (do_swap_account)
6563                entry->val = ent.val;
6564
6565        return page;
6566}
6567#else
6568static struct page *mc_handle_swap_pte(struct vm_area_struct *vma,
6569                        unsigned long addr, pte_t ptent, swp_entry_t *entry)
6570{
6571        return NULL;
6572}
6573#endif
6574
6575static struct page *mc_handle_file_pte(struct vm_area_struct *vma,
6576                        unsigned long addr, pte_t ptent, swp_entry_t *entry)
6577{
6578        struct page *page = NULL;
6579        struct address_space *mapping;
6580        pgoff_t pgoff;
6581
6582        if (!vma->vm_file) /* anonymous vma */
6583                return NULL;
6584        if (!move_file())
6585                return NULL;
6586
6587        mapping = vma->vm_file->f_mapping;
6588        if (pte_none(ptent))
6589                pgoff = linear_page_index(vma, addr);
6590        else /* pte_file(ptent) is true */
6591                pgoff = pte_to_pgoff(ptent);
6592
6593        /* page is moved even if it's not RSS of this task(page-faulted). */
6594#ifdef CONFIG_SWAP
6595        /* shmem/tmpfs may report page out on swap: account for that too. */
6596        if (shmem_mapping(mapping)) {
6597                page = __find_get_page(mapping, pgoff);
6598                if (radix_tree_exceptional_entry(page)) {
6599                        swp_entry_t swp = radix_to_swp_entry(page);
6600                        if (do_swap_account)
6601                                *entry = swp;
6602                        page = find_get_page(swap_address_space(swp), swp.val);
6603                }
6604        } else
6605                page = find_get_page(mapping, pgoff);
6606#else
6607        page = find_get_page(mapping, pgoff);
6608#endif
6609        return page;
6610}
6611
6612static enum mc_target_type get_mctgt_type(struct vm_area_struct *vma,
6613                unsigned long addr, pte_t ptent, union mc_target *target)
6614{
6615        struct page *page = NULL;
6616        struct page_cgroup *pc;
6617        enum mc_target_type ret = MC_TARGET_NONE;
6618        swp_entry_t ent = { .val = 0 };
6619
6620        if (pte_present(ptent))
6621                page = mc_handle_present_pte(vma, addr, ptent);
6622        else if (is_swap_pte(ptent))
6623                page = mc_handle_swap_pte(vma, addr, ptent, &ent);
6624        else if (pte_none(ptent) || pte_file(ptent))
6625                page = mc_handle_file_pte(vma, addr, ptent, &ent);
6626
6627        if (!page && !ent.val)
6628                return ret;
6629        if (page) {
6630                pc = lookup_page_cgroup(page);
6631                /*
6632                 * Do only loose check w/o page_cgroup lock.
6633                 * mem_cgroup_move_account() checks the pc is valid or not under
6634                 * the lock.
6635                 */
6636                if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
6637                        ret = MC_TARGET_PAGE;
6638                        if (target)
6639                                target->page = page;
6640                }
6641                if (!ret || !target)
6642                        put_page(page);
6643        }
6644        /* There is a swap entry and a page doesn't exist or isn't charged */
6645        if (ent.val && !ret &&
6646                        mem_cgroup_id(mc.from) == lookup_swap_cgroup_id(ent)) {
6647                ret = MC_TARGET_SWAP;
6648                if (target)
6649                        target->ent = ent;
6650        }
6651        return ret;
6652}
6653
6654#ifdef CONFIG_TRANSPARENT_HUGEPAGE
6655/*
6656 * We don't consider swapping or file mapped pages because THP does not
6657 * support them for now.
6658 * Caller should make sure that pmd_trans_huge(pmd) is true.
6659 */
6660static enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6661                unsigned long addr, pmd_t pmd, union mc_target *target)
6662{
6663        struct page *page = NULL;
6664        struct page_cgroup *pc;
6665        enum mc_target_type ret = MC_TARGET_NONE;
6666
6667        page = pmd_page(pmd);
6668        VM_BUG_ON_PAGE(!page || !PageHead(page), page);
6669        if (!move_anon())
6670                return ret;
6671        pc = lookup_page_cgroup(page);
6672        if (PageCgroupUsed(pc) && pc->mem_cgroup == mc.from) {
6673                ret = MC_TARGET_PAGE;
6674                if (target) {
6675                        get_page(page);
6676                        target->page = page;
6677                }
6678        }
6679        return ret;
6680}
6681#else
6682static inline enum mc_target_type get_mctgt_type_thp(struct vm_area_struct *vma,
6683                unsigned long addr, pmd_t pmd, union mc_target *target)
6684{
6685        return MC_TARGET_NONE;
6686}
6687#endif
6688
6689static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
6690                                        unsigned long addr, unsigned long end,
6691                                        struct mm_walk *walk)
6692{
6693        struct vm_area_struct *vma = walk->private;
6694        pte_t *pte;
6695        spinlock_t *ptl;
6696
6697        if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
6698                if (get_mctgt_type_thp(vma, addr, *pmd, NULL) == MC_TARGET_PAGE)
6699                        mc.precharge += HPAGE_PMD_NR;
6700                spin_unlock(ptl);
6701                return 0;
6702        }
6703
6704        if (pmd_trans_unstable(pmd))
6705                return 0;
6706        pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6707        for (; addr != end; pte++, addr += PAGE_SIZE)
6708                if (get_mctgt_type(vma, addr, *pte, NULL))
6709                        mc.precharge++; /* increment precharge temporarily */
6710        pte_unmap_unlock(pte - 1, ptl);
6711        cond_resched();
6712
6713        return 0;
6714}
6715
6716static unsigned long mem_cgroup_count_precharge(struct mm_struct *mm)
6717{
6718        unsigned long precharge;
6719        struct vm_area_struct *vma;
6720
6721        down_read(&mm->mmap_sem);
6722        for (vma = mm->mmap; vma; vma = vma->vm_next) {
6723                struct mm_walk mem_cgroup_count_precharge_walk = {
6724                        .pmd_entry = mem_cgroup_count_precharge_pte_range,
6725                        .mm = mm,
6726                        .private = vma,
6727                };
6728                if (is_vm_hugetlb_page(vma))
6729                        continue;
6730                walk_page_range(vma->vm_start, vma->vm_end,
6731                                        &mem_cgroup_count_precharge_walk);
6732        }
6733        up_read(&mm->mmap_sem);
6734
6735        precharge = mc.precharge;
6736        mc.precharge = 0;
6737
6738        return precharge;
6739}
6740
6741static int mem_cgroup_precharge_mc(struct mm_struct *mm)
6742{
6743        unsigned long precharge = mem_cgroup_count_precharge(mm);
6744
6745        VM_BUG_ON(mc.moving_task);
6746        mc.moving_task = current;
6747        return mem_cgroup_do_precharge(precharge);
6748}
6749
6750/* cancels all extra charges on mc.from and mc.to, and wakes up all waiters. */
6751static void __mem_cgroup_clear_mc(void)
6752{
6753        struct mem_cgroup *from = mc.from;
6754        struct mem_cgroup *to = mc.to;
6755
6756        /* we must uncharge all the leftover precharges from mc.to */
6757        if (mc.precharge) {
6758                __mem_cgroup_cancel_charge(mc.to, mc.precharge);
6759                mc.precharge = 0;
6760        }
6761        /*
6762         * we didn't uncharge from mc.from at mem_cgroup_move_account(), so
6763         * we must uncharge here.
6764         */
6765        if (mc.moved_charge) {
6766                __mem_cgroup_cancel_charge(mc.from, mc.moved_charge);
6767                mc.moved_charge = 0;
6768        }
6769        /* we must fixup refcnts and charges */
6770        if (mc.moved_swap) {
6771                /* uncharge swap account from the old cgroup */
6772                if (!mem_cgroup_is_root(mc.from))
6773                        page_counter_uncharge(&mc.from->memsw, mc.moved_swap);
6774
6775                if (!mem_cgroup_is_root(mc.to)) {
6776                        /*
6777                         * we charged both to->memory and to->memsw, so we
6778                         * should uncharge to->memory.
6779                         */
6780                        page_counter_uncharge(&mc.to->memory, mc.moved_swap);
6781                }
6782                __mem_cgroup_put(mc.from, mc.moved_swap);
6783
6784                /* we've already done mem_cgroup_get(mc.to) */
6785                mc.moved_swap = 0;
6786        }
6787        memcg_oom_recover(from);
6788        memcg_oom_recover(to);
6789        wake_up_all(&mc.waitq);
6790}
6791
6792static void mem_cgroup_clear_mc(void)
6793{
6794        struct mem_cgroup *from = mc.from;
6795
6796        /*
6797         * we must clear moving_task before waking up waiters at the end of
6798         * task migration.
6799         */
6800        mc.moving_task = NULL;
6801        __mem_cgroup_clear_mc();
6802        spin_lock(&mc.lock);
6803        mc.from = NULL;
6804        mc.to = NULL;
6805        spin_unlock(&mc.lock);
6806        mem_cgroup_end_move(from);
6807}
6808
6809static int mem_cgroup_can_attach(struct cgroup *cgroup,
6810                                 struct cgroup_taskset *tset)
6811{
6812        struct task_struct *p = cgroup_taskset_first(tset);
6813        int ret = 0;
6814        struct mem_cgroup *memcg = mem_cgroup_from_cont(cgroup);
6815        unsigned long move_charge_at_immigrate;
6816
6817        /*
6818         * We are now commited to this value whatever it is. Changes in this
6819         * tunable will only affect upcoming migrations, not the current one.
6820         * So we need to save it, and keep it going.
6821         */
6822        move_charge_at_immigrate  = memcg->move_charge_at_immigrate;
6823        if (move_charge_at_immigrate) {
6824                struct mm_struct *mm;
6825                struct mem_cgroup *from = mem_cgroup_from_task(p);
6826
6827                VM_BUG_ON(from == memcg);
6828
6829                mm = get_task_mm(p);
6830                if (!mm)
6831                        return 0;
6832                /* We move charges only when we move a owner of the mm */
6833                if (mm->owner == p) {
6834                        VM_BUG_ON(mc.from);
6835                        VM_BUG_ON(mc.to);
6836                        VM_BUG_ON(mc.precharge);
6837                        VM_BUG_ON(mc.moved_charge);
6838                        VM_BUG_ON(mc.moved_swap);
6839                        mem_cgroup_start_move(from);
6840                        spin_lock(&mc.lock);
6841                        mc.from = from;
6842                        mc.to = memcg;
6843                        mc.immigrate_flags = move_charge_at_immigrate;
6844                        spin_unlock(&mc.lock);
6845                        /* We set mc.moving_task later */
6846
6847                        ret = mem_cgroup_precharge_mc(mm);
6848                        if (ret)
6849                                mem_cgroup_clear_mc();
6850                }
6851                mmput(mm);
6852        }
6853        return ret;
6854}
6855
6856static void mem_cgroup_cancel_attach(struct cgroup *cgroup,
6857                                     struct cgroup_taskset *tset)
6858{
6859        mem_cgroup_clear_mc();
6860}
6861
6862static int mem_cgroup_move_charge_pte_range(pmd_t *pmd,
6863                                unsigned long addr, unsigned long end,
6864                                struct mm_walk *walk)
6865{
6866        int ret = 0;
6867        struct vm_area_struct *vma = walk->private;
6868        pte_t *pte;
6869        spinlock_t *ptl;
6870        enum mc_target_type target_type;
6871        union mc_target target;
6872        struct page *page;
6873        struct page_cgroup *pc;
6874
6875        /*
6876         * We don't take compound_lock() here but no race with splitting thp
6877         * happens because:
6878         *  - if pmd_trans_huge_lock() returns 1, the relevant thp is not
6879         *    under splitting, which means there's no concurrent thp split,
6880         *  - if another thread runs into split_huge_page() just after we
6881         *    entered this if-block, the thread must wait for page table lock
6882         *    to be unlocked in __split_huge_page_splitting(), where the main
6883         *    part of thp split is not executed yet.
6884         */
6885        if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) {
6886                if (mc.precharge < HPAGE_PMD_NR) {
6887                        spin_unlock(ptl);
6888                        return 0;
6889                }
6890                target_type = get_mctgt_type_thp(vma, addr, *pmd, &target);
6891                if (target_type == MC_TARGET_PAGE) {
6892                        page = target.page;
6893                        if (!isolate_lru_page(page)) {
6894                                pc = lookup_page_cgroup(page);
6895                                if (!mem_cgroup_move_account(page, HPAGE_PMD_NR,
6896                                                        pc, mc.from, mc.to)) {
6897                                        mc.precharge -= HPAGE_PMD_NR;
6898                                        mc.moved_charge += HPAGE_PMD_NR;
6899                                }
6900                                putback_lru_page(page);
6901                        }
6902                        put_page(page);
6903                }
6904                spin_unlock(ptl);
6905                return 0;
6906        }
6907
6908        if (pmd_trans_unstable(pmd))
6909                return 0;
6910retry:
6911        pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
6912        for (; addr != end; addr += PAGE_SIZE) {
6913                pte_t ptent = *(pte++);
6914                swp_entry_t ent;
6915
6916                if (!mc.precharge)
6917                        break;
6918
6919                switch (get_mctgt_type(vma, addr, ptent, &target)) {
6920                case MC_TARGET_PAGE:
6921                        page = target.page;
6922                        if (isolate_lru_page(page))
6923                                goto put;
6924                        pc = lookup_page_cgroup(page);
6925                        if (!mem_cgroup_move_account(page, 1, pc,
6926                                                     mc.from, mc.to)) {
6927                                mc.precharge--;
6928                                /* we uncharge from mc.from later. */
6929                                mc.moved_charge++;
6930                        }
6931                        putback_lru_page(page);
6932put:                    /* get_mctgt_type() gets the page */
6933                        put_page(page);
6934                        break;
6935                case MC_TARGET_SWAP:
6936                        ent = target.ent;
6937                        if (!mem_cgroup_move_swap_account(ent, mc.from, mc.to)) {
6938                                mc.precharge--;
6939                                /* we fixup refcnts and charges later. */
6940                                mc.moved_swap++;
6941                        }
6942                        break;
6943                default:
6944                        break;
6945                }
6946        }
6947        pte_unmap_unlock(pte - 1, ptl);
6948        cond_resched();
6949
6950        if (addr != end) {
6951                /*
6952                 * We have consumed all precharges we got in can_attach().
6953                 * We try charge one by one, but don't do any additional
6954                 * charges to mc.to if we have failed in charge once in attach()
6955                 * phase.
6956                 */
6957                ret = mem_cgroup_do_precharge(1);
6958                if (!ret)
6959                        goto retry;
6960        }
6961
6962        return ret;
6963}
6964
6965static void mem_cgroup_move_charge(struct mm_struct *mm)
6966{
6967        struct vm_area_struct *vma;
6968
6969        lru_add_drain_all();
6970retry:
6971        if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
6972                /*
6973                 * Someone who are holding the mmap_sem might be waiting in
6974                 * waitq. So we cancel all extra charges, wake up all waiters,
6975                 * and retry. Because we cancel precharges, we might not be able
6976                 * to move enough charges, but moving charge is a best-effort
6977                 * feature anyway, so it wouldn't be a big problem.
6978                 */
6979                __mem_cgroup_clear_mc();
6980                cond_resched();
6981                goto retry;
6982        }
6983        for (vma = mm->mmap; vma; vma = vma->vm_next) {
6984                int ret;
6985                struct mm_walk mem_cgroup_move_charge_walk = {
6986                        .pmd_entry = mem_cgroup_move_charge_pte_range,
6987                        .mm = mm,
6988                        .private = vma,
6989                };
6990                if (is_vm_hugetlb_page(vma))
6991                        continue;
6992                ret = walk_page_range(vma->vm_start, vma->vm_end,
6993                                                &mem_cgroup_move_charge_walk);
6994                if (ret)
6995                        /*
6996                         * means we have consumed all precharges and failed in
6997                         * doing additional charge. Just abandon here.
6998                         */
6999                        break;
7000        }
7001        up_read(&mm->mmap_sem);
7002}
7003
7004static void mem_cgroup_move_task(struct cgroup *cont,
7005                                 struct cgroup_taskset *tset)
7006{
7007        struct task_struct *p = cgroup_taskset_first(tset);
7008        struct mm_struct *mm = get_task_mm(p);
7009
7010        if (mm) {
7011                if (mc.to)
7012                        mem_cgroup_move_charge(mm);
7013                mmput(mm);
7014        }
7015        if (mc.to)
7016                mem_cgroup_clear_mc();
7017}
7018#else   /* !CONFIG_MMU */
7019static int mem_cgroup_can_attach(struct cgroup *cgroup,
7020                                 struct cgroup_taskset *tset)
7021{
7022        return 0;
7023}
7024static void mem_cgroup_cancel_attach(struct cgroup *cgroup,
7025                                     struct cgroup_taskset *tset)
7026{
7027}
7028static void mem_cgroup_move_task(struct cgroup *cont,
7029                                 struct cgroup_taskset *tset)
7030{
7031}
7032#endif
7033
7034/*
7035 * Cgroup retains root cgroups across [un]mount cycles making it necessary
7036 * to verify sane_behavior flag on each mount attempt.
7037 */
7038static void mem_cgroup_bind(struct cgroup *root)
7039{
7040        /*
7041         * use_hierarchy is forced with sane_behavior.  cgroup core
7042         * guarantees that @root doesn't have any children, so turning it
7043         * on for the root memcg is enough.
7044         */
7045        if (cgroup_sane_behavior(root))
7046                mem_cgroup_from_cont(root)->use_hierarchy = true;
7047}
7048
7049struct cgroup_subsys mem_cgroup_subsys = {
7050        .name = "memory",
7051        .subsys_id = mem_cgroup_subsys_id,
7052        .css_alloc = mem_cgroup_css_alloc,
7053        .css_online = mem_cgroup_css_online,
7054        .css_offline = mem_cgroup_css_offline,
7055        .css_free = mem_cgroup_css_free,
7056        .can_attach = mem_cgroup_can_attach,
7057        .cancel_attach = mem_cgroup_cancel_attach,
7058        .attach = mem_cgroup_move_task,
7059        .bind = mem_cgroup_bind,
7060        .base_cftypes = mem_cgroup_files,
7061        .early_init = 0,
7062};
7063
7064#ifdef CONFIG_MEMCG_SWAP
7065static int __init enable_swap_account(char *s)
7066{
7067        /* consider enabled if no parameter or 1 is given */
7068        if (!strcmp(s, "1"))
7069                really_do_swap_account = 1;
7070        else if (!strcmp(s, "0"))
7071                really_do_swap_account = 0;
7072        return 1;
7073}
7074__setup("swapaccount=", enable_swap_account);
7075
7076static void __init memsw_file_init(void)
7077{
7078        WARN_ON(cgroup_add_cftypes(&mem_cgroup_subsys, memsw_cgroup_files));
7079}
7080
7081static void __init enable_swap_cgroup(void)
7082{
7083        if (!mem_cgroup_disabled() && really_do_swap_account) {
7084                do_swap_account = 1;
7085                memsw_file_init();
7086        }
7087}
7088
7089#else
7090static void __init enable_swap_cgroup(void)
7091{
7092}
7093#endif
7094
7095static int __init cgroup_memory(char *s)
7096{
7097        char *token;
7098
7099        while ((token = strsep(&s, ",")) != NULL) {
7100                if (!*token)
7101                        continue;
7102                if (!strcmp(token, "nokmem"))
7103                        cgroup_memory_nokmem = true;
7104        }
7105        return 0;
7106}
7107__setup("cgroup.memory=", cgroup_memory);
7108
7109/*
7110 * subsys_initcall() for memory controller.
7111 *
7112 * Some parts like hotcpu_notifier() have to be initialized from this context
7113 * because of lock dependencies (cgroup_lock -> cpu hotplug) but basically
7114 * everything that doesn't depend on a specific mem_cgroup structure should
7115 * be initialized from here.
7116 */
7117static int __init mem_cgroup_init(void)
7118{
7119        hotcpu_notifier(memcg_cpu_hotplug_callback, 0);
7120        enable_swap_cgroup();
7121        mem_cgroup_soft_limit_tree_init();
7122        memcg_stock_init();
7123        return 0;
7124}
7125subsys_initcall(mem_cgroup_init);
7126