linux/include/linux/cgroup-defs.h
<<
>>
Prefs
   1/* SPDX-License-Identifier: GPL-2.0 */
   2/*
   3 * linux/cgroup-defs.h - basic definitions for cgroup
   4 *
   5 * This file provides basic type and interface.  Include this file directly
   6 * only if necessary to avoid cyclic dependencies.
   7 */
   8#ifndef _LINUX_CGROUP_DEFS_H
   9#define _LINUX_CGROUP_DEFS_H
  10
  11#include <linux/limits.h>
  12#include <linux/list.h>
  13#include <linux/idr.h>
  14#include <linux/wait.h>
  15#include <linux/mutex.h>
  16#include <linux/rcupdate.h>
  17#include <linux/refcount.h>
  18#include <linux/percpu-refcount.h>
  19#include <linux/percpu-rwsem.h>
  20#include <linux/workqueue.h>
  21#include <linux/bpf-cgroup.h>
  22
  23#ifdef CONFIG_CGROUPS
  24
  25struct cgroup;
  26struct cgroup_root;
  27struct cgroup_subsys;
  28struct cgroup_taskset;
  29struct kernfs_node;
  30struct kernfs_ops;
  31struct kernfs_open_file;
  32struct seq_file;
  33
  34#define MAX_CGROUP_TYPE_NAMELEN 32
  35#define MAX_CGROUP_ROOT_NAMELEN 64
  36#define MAX_CFTYPE_NAME         64
  37
  38/* define the enumeration of all cgroup subsystems */
  39#define SUBSYS(_x) _x ## _cgrp_id,
  40enum cgroup_subsys_id {
  41#include <linux/cgroup_subsys.h>
  42        CGROUP_SUBSYS_COUNT,
  43};
  44#undef SUBSYS
  45
  46/* bits in struct cgroup_subsys_state flags field */
  47enum {
  48        CSS_NO_REF      = (1 << 0), /* no reference counting for this css */
  49        CSS_ONLINE      = (1 << 1), /* between ->css_online() and ->css_offline() */
  50        CSS_RELEASED    = (1 << 2), /* refcnt reached zero, released */
  51        CSS_VISIBLE     = (1 << 3), /* css is visible to userland */
  52        CSS_DYING       = (1 << 4), /* css is dying */
  53};
  54
  55/* bits in struct cgroup flags field */
  56enum {
  57        /* Control Group requires release notifications to userspace */
  58        CGRP_NOTIFY_ON_RELEASE,
  59        /*
  60         * Clone the parent's configuration when creating a new child
  61         * cpuset cgroup.  For historical reasons, this option can be
  62         * specified at mount time and thus is implemented here.
  63         */
  64        CGRP_CPUSET_CLONE_CHILDREN,
  65};
  66
  67/* cgroup_root->flags */
  68enum {
  69        CGRP_ROOT_NOPREFIX      = (1 << 1), /* mounted subsystems have no named prefix */
  70        CGRP_ROOT_XATTR         = (1 << 2), /* supports extended attributes */
  71
  72        /*
  73         * Consider namespaces as delegation boundaries.  If this flag is
  74         * set, controller specific interface files in a namespace root
  75         * aren't writeable from inside the namespace.
  76         */
  77        CGRP_ROOT_NS_DELEGATE   = (1 << 3),
  78
  79        /*
  80         * Enable cpuset controller in v1 cgroup to use v2 behavior.
  81         */
  82        CGRP_ROOT_CPUSET_V2_MODE = (1 << 4),
  83};
  84
  85/* cftype->flags */
  86enum {
  87        CFTYPE_ONLY_ON_ROOT     = (1 << 0),     /* only create on root cgrp */
  88        CFTYPE_NOT_ON_ROOT      = (1 << 1),     /* don't create on root cgrp */
  89        CFTYPE_NS_DELEGATABLE   = (1 << 2),     /* writeable beyond delegation boundaries */
  90
  91        CFTYPE_NO_PREFIX        = (1 << 3),     /* (DON'T USE FOR NEW FILES) no subsys prefix */
  92        CFTYPE_WORLD_WRITABLE   = (1 << 4),     /* (DON'T USE FOR NEW FILES) S_IWUGO */
  93
  94        /* internal flags, do not use outside cgroup core proper */
  95        __CFTYPE_ONLY_ON_DFL    = (1 << 16),    /* only on default hierarchy */
  96        __CFTYPE_NOT_ON_DFL     = (1 << 17),    /* not on default hierarchy */
  97};
  98
  99/*
 100 * cgroup_file is the handle for a file instance created in a cgroup which
 101 * is used, for example, to generate file changed notifications.  This can
 102 * be obtained by setting cftype->file_offset.
 103 */
 104struct cgroup_file {
 105        /* do not access any fields from outside cgroup core */
 106        struct kernfs_node *kn;
 107};
 108
 109/*
 110 * Per-subsystem/per-cgroup state maintained by the system.  This is the
 111 * fundamental structural building block that controllers deal with.
 112 *
 113 * Fields marked with "PI:" are public and immutable and may be accessed
 114 * directly without synchronization.
 115 */
 116struct cgroup_subsys_state {
 117        /* PI: the cgroup that this css is attached to */
 118        struct cgroup *cgroup;
 119
 120        /* PI: the cgroup subsystem that this css is attached to */
 121        struct cgroup_subsys *ss;
 122
 123        /* reference count - access via css_[try]get() and css_put() */
 124        struct percpu_ref refcnt;
 125
 126        /* siblings list anchored at the parent's ->children */
 127        struct list_head sibling;
 128        struct list_head children;
 129
 130        /*
 131         * PI: Subsys-unique ID.  0 is unused and root is always 1.  The
 132         * matching css can be looked up using css_from_id().
 133         */
 134        int id;
 135
 136        unsigned int flags;
 137
 138        /*
 139         * Monotonically increasing unique serial number which defines a
 140         * uniform order among all csses.  It's guaranteed that all
 141         * ->children lists are in the ascending order of ->serial_nr and
 142         * used to allow interrupting and resuming iterations.
 143         */
 144        u64 serial_nr;
 145
 146        /*
 147         * Incremented by online self and children.  Used to guarantee that
 148         * parents are not offlined before their children.
 149         */
 150        atomic_t online_cnt;
 151
 152        /* percpu_ref killing and RCU release */
 153        struct rcu_head rcu_head;
 154        struct work_struct destroy_work;
 155
 156        /*
 157         * PI: the parent css.  Placed here for cache proximity to following
 158         * fields of the containing structure.
 159         */
 160        struct cgroup_subsys_state *parent;
 161};
 162
 163/*
 164 * A css_set is a structure holding pointers to a set of
 165 * cgroup_subsys_state objects. This saves space in the task struct
 166 * object and speeds up fork()/exit(), since a single inc/dec and a
 167 * list_add()/del() can bump the reference count on the entire cgroup
 168 * set for a task.
 169 */
 170struct css_set {
 171        /*
 172         * Set of subsystem states, one for each subsystem. This array is
 173         * immutable after creation apart from the init_css_set during
 174         * subsystem registration (at boot time).
 175         */
 176        struct cgroup_subsys_state *subsys[CGROUP_SUBSYS_COUNT];
 177
 178        /* reference count */
 179        refcount_t refcount;
 180
 181        /*
 182         * For a domain cgroup, the following points to self.  If threaded,
 183         * to the matching cset of the nearest domain ancestor.  The
 184         * dom_cset provides access to the domain cgroup and its csses to
 185         * which domain level resource consumptions should be charged.
 186         */
 187        struct css_set *dom_cset;
 188
 189        /* the default cgroup associated with this css_set */
 190        struct cgroup *dfl_cgrp;
 191
 192        /* internal task count, protected by css_set_lock */
 193        int nr_tasks;
 194
 195        /*
 196         * Lists running through all tasks using this cgroup group.
 197         * mg_tasks lists tasks which belong to this cset but are in the
 198         * process of being migrated out or in.  Protected by
 199         * css_set_rwsem, but, during migration, once tasks are moved to
 200         * mg_tasks, it can be read safely while holding cgroup_mutex.
 201         */
 202        struct list_head tasks;
 203        struct list_head mg_tasks;
 204
 205        /* all css_task_iters currently walking this cset */
 206        struct list_head task_iters;
 207
 208        /*
 209         * On the default hierarhcy, ->subsys[ssid] may point to a css
 210         * attached to an ancestor instead of the cgroup this css_set is
 211         * associated with.  The following node is anchored at
 212         * ->subsys[ssid]->cgroup->e_csets[ssid] and provides a way to
 213         * iterate through all css's attached to a given cgroup.
 214         */
 215        struct list_head e_cset_node[CGROUP_SUBSYS_COUNT];
 216
 217        /* all threaded csets whose ->dom_cset points to this cset */
 218        struct list_head threaded_csets;
 219        struct list_head threaded_csets_node;
 220
 221        /*
 222         * List running through all cgroup groups in the same hash
 223         * slot. Protected by css_set_lock
 224         */
 225        struct hlist_node hlist;
 226
 227        /*
 228         * List of cgrp_cset_links pointing at cgroups referenced from this
 229         * css_set.  Protected by css_set_lock.
 230         */
 231        struct list_head cgrp_links;
 232
 233        /*
 234         * List of csets participating in the on-going migration either as
 235         * source or destination.  Protected by cgroup_mutex.
 236         */
 237        struct list_head mg_preload_node;
 238        struct list_head mg_node;
 239
 240        /*
 241         * If this cset is acting as the source of migration the following
 242         * two fields are set.  mg_src_cgrp and mg_dst_cgrp are
 243         * respectively the source and destination cgroups of the on-going
 244         * migration.  mg_dst_cset is the destination cset the target tasks
 245         * on this cset should be migrated to.  Protected by cgroup_mutex.
 246         */
 247        struct cgroup *mg_src_cgrp;
 248        struct cgroup *mg_dst_cgrp;
 249        struct css_set *mg_dst_cset;
 250
 251        /* dead and being drained, ignore for migration */
 252        bool dead;
 253
 254        /* For RCU-protected deletion */
 255        struct rcu_head rcu_head;
 256};
 257
 258struct cgroup {
 259        /* self css with NULL ->ss, points back to this cgroup */
 260        struct cgroup_subsys_state self;
 261
 262        unsigned long flags;            /* "unsigned long" so bitops work */
 263
 264        /*
 265         * idr allocated in-hierarchy ID.
 266         *
 267         * ID 0 is not used, the ID of the root cgroup is always 1, and a
 268         * new cgroup will be assigned with a smallest available ID.
 269         *
 270         * Allocating/Removing ID must be protected by cgroup_mutex.
 271         */
 272        int id;
 273
 274        /*
 275         * The depth this cgroup is at.  The root is at depth zero and each
 276         * step down the hierarchy increments the level.  This along with
 277         * ancestor_ids[] can determine whether a given cgroup is a
 278         * descendant of another without traversing the hierarchy.
 279         */
 280        int level;
 281
 282        /* Maximum allowed descent tree depth */
 283        int max_depth;
 284
 285        /*
 286         * Keep track of total numbers of visible and dying descent cgroups.
 287         * Dying cgroups are cgroups which were deleted by a user,
 288         * but are still existing because someone else is holding a reference.
 289         * max_descendants is a maximum allowed number of descent cgroups.
 290         */
 291        int nr_descendants;
 292        int nr_dying_descendants;
 293        int max_descendants;
 294
 295        /*
 296         * Each non-empty css_set associated with this cgroup contributes
 297         * one to nr_populated_csets.  The counter is zero iff this cgroup
 298         * doesn't have any tasks.
 299         *
 300         * All children which have non-zero nr_populated_csets and/or
 301         * nr_populated_children of their own contribute one to either
 302         * nr_populated_domain_children or nr_populated_threaded_children
 303         * depending on their type.  Each counter is zero iff all cgroups
 304         * of the type in the subtree proper don't have any tasks.
 305         */
 306        int nr_populated_csets;
 307        int nr_populated_domain_children;
 308        int nr_populated_threaded_children;
 309
 310        int nr_threaded_children;       /* # of live threaded child cgroups */
 311
 312        struct kernfs_node *kn;         /* cgroup kernfs entry */
 313        struct cgroup_file procs_file;  /* handle for "cgroup.procs" */
 314        struct cgroup_file events_file; /* handle for "cgroup.events" */
 315
 316        /*
 317         * The bitmask of subsystems enabled on the child cgroups.
 318         * ->subtree_control is the one configured through
 319         * "cgroup.subtree_control" while ->child_ss_mask is the effective
 320         * one which may have more subsystems enabled.  Controller knobs
 321         * are made available iff it's enabled in ->subtree_control.
 322         */
 323        u16 subtree_control;
 324        u16 subtree_ss_mask;
 325        u16 old_subtree_control;
 326        u16 old_subtree_ss_mask;
 327
 328        /* Private pointers for each registered subsystem */
 329        struct cgroup_subsys_state __rcu *subsys[CGROUP_SUBSYS_COUNT];
 330
 331        struct cgroup_root *root;
 332
 333        /*
 334         * List of cgrp_cset_links pointing at css_sets with tasks in this
 335         * cgroup.  Protected by css_set_lock.
 336         */
 337        struct list_head cset_links;
 338
 339        /*
 340         * On the default hierarchy, a css_set for a cgroup with some
 341         * susbsys disabled will point to css's which are associated with
 342         * the closest ancestor which has the subsys enabled.  The
 343         * following lists all css_sets which point to this cgroup's css
 344         * for the given subsystem.
 345         */
 346        struct list_head e_csets[CGROUP_SUBSYS_COUNT];
 347
 348        /*
 349         * If !threaded, self.  If threaded, it points to the nearest
 350         * domain ancestor.  Inside a threaded subtree, cgroups are exempt
 351         * from process granularity and no-internal-task constraint.
 352         * Domain level resource consumptions which aren't tied to a
 353         * specific task are charged to the dom_cgrp.
 354         */
 355        struct cgroup *dom_cgrp;
 356
 357        /*
 358         * list of pidlists, up to two for each namespace (one for procs, one
 359         * for tasks); created on demand.
 360         */
 361        struct list_head pidlists;
 362        struct mutex pidlist_mutex;
 363
 364        /* used to wait for offlining of csses */
 365        wait_queue_head_t offline_waitq;
 366
 367        /* used to schedule release agent */
 368        struct work_struct release_agent_work;
 369
 370        /* used to store eBPF programs */
 371        struct cgroup_bpf bpf;
 372
 373        /* ids of the ancestors at each level including self */
 374        int ancestor_ids[];
 375};
 376
 377/*
 378 * A cgroup_root represents the root of a cgroup hierarchy, and may be
 379 * associated with a kernfs_root to form an active hierarchy.  This is
 380 * internal to cgroup core.  Don't access directly from controllers.
 381 */
 382struct cgroup_root {
 383        struct kernfs_root *kf_root;
 384
 385        /* The bitmask of subsystems attached to this hierarchy */
 386        unsigned int subsys_mask;
 387
 388        /* Unique id for this hierarchy. */
 389        int hierarchy_id;
 390
 391        /* The root cgroup.  Root is destroyed on its release. */
 392        struct cgroup cgrp;
 393
 394        /* for cgrp->ancestor_ids[0] */
 395        int cgrp_ancestor_id_storage;
 396
 397        /* Number of cgroups in the hierarchy, used only for /proc/cgroups */
 398        atomic_t nr_cgrps;
 399
 400        /* A list running through the active hierarchies */
 401        struct list_head root_list;
 402
 403        /* Hierarchy-specific flags */
 404        unsigned int flags;
 405
 406        /* IDs for cgroups in this hierarchy */
 407        struct idr cgroup_idr;
 408
 409        /* The path to use for release notifications. */
 410        char release_agent_path[PATH_MAX];
 411
 412        /* The name for this hierarchy - may be empty */
 413        char name[MAX_CGROUP_ROOT_NAMELEN];
 414};
 415
 416/*
 417 * struct cftype: handler definitions for cgroup control files
 418 *
 419 * When reading/writing to a file:
 420 *      - the cgroup to use is file->f_path.dentry->d_parent->d_fsdata
 421 *      - the 'cftype' of the file is file->f_path.dentry->d_fsdata
 422 */
 423struct cftype {
 424        /*
 425         * By convention, the name should begin with the name of the
 426         * subsystem, followed by a period.  Zero length string indicates
 427         * end of cftype array.
 428         */
 429        char name[MAX_CFTYPE_NAME];
 430        unsigned long private;
 431
 432        /*
 433         * The maximum length of string, excluding trailing nul, that can
 434         * be passed to write.  If < PAGE_SIZE-1, PAGE_SIZE-1 is assumed.
 435         */
 436        size_t max_write_len;
 437
 438        /* CFTYPE_* flags */
 439        unsigned int flags;
 440
 441        /*
 442         * If non-zero, should contain the offset from the start of css to
 443         * a struct cgroup_file field.  cgroup will record the handle of
 444         * the created file into it.  The recorded handle can be used as
 445         * long as the containing css remains accessible.
 446         */
 447        unsigned int file_offset;
 448
 449        /*
 450         * Fields used for internal bookkeeping.  Initialized automatically
 451         * during registration.
 452         */
 453        struct cgroup_subsys *ss;       /* NULL for cgroup core files */
 454        struct list_head node;          /* anchored at ss->cfts */
 455        struct kernfs_ops *kf_ops;
 456
 457        int (*open)(struct kernfs_open_file *of);
 458        void (*release)(struct kernfs_open_file *of);
 459
 460        /*
 461         * read_u64() is a shortcut for the common case of returning a
 462         * single integer. Use it in place of read()
 463         */
 464        u64 (*read_u64)(struct cgroup_subsys_state *css, struct cftype *cft);
 465        /*
 466         * read_s64() is a signed version of read_u64()
 467         */
 468        s64 (*read_s64)(struct cgroup_subsys_state *css, struct cftype *cft);
 469
 470        /* generic seq_file read interface */
 471        int (*seq_show)(struct seq_file *sf, void *v);
 472
 473        /* optional ops, implement all or none */
 474        void *(*seq_start)(struct seq_file *sf, loff_t *ppos);
 475        void *(*seq_next)(struct seq_file *sf, void *v, loff_t *ppos);
 476        void (*seq_stop)(struct seq_file *sf, void *v);
 477
 478        /*
 479         * write_u64() is a shortcut for the common case of accepting
 480         * a single integer (as parsed by simple_strtoull) from
 481         * userspace. Use in place of write(); return 0 or error.
 482         */
 483        int (*write_u64)(struct cgroup_subsys_state *css, struct cftype *cft,
 484                         u64 val);
 485        /*
 486         * write_s64() is a signed version of write_u64()
 487         */
 488        int (*write_s64)(struct cgroup_subsys_state *css, struct cftype *cft,
 489                         s64 val);
 490
 491        /*
 492         * write() is the generic write callback which maps directly to
 493         * kernfs write operation and overrides all other operations.
 494         * Maximum write size is determined by ->max_write_len.  Use
 495         * of_css/cft() to access the associated css and cft.
 496         */
 497        ssize_t (*write)(struct kernfs_open_file *of,
 498                         char *buf, size_t nbytes, loff_t off);
 499
 500#ifdef CONFIG_DEBUG_LOCK_ALLOC
 501        struct lock_class_key   lockdep_key;
 502#endif
 503};
 504
 505/*
 506 * Control Group subsystem type.
 507 * See Documentation/cgroups/cgroups.txt for details
 508 */
 509struct cgroup_subsys {
 510        struct cgroup_subsys_state *(*css_alloc)(struct cgroup_subsys_state *parent_css);
 511        int (*css_online)(struct cgroup_subsys_state *css);
 512        void (*css_offline)(struct cgroup_subsys_state *css);
 513        void (*css_released)(struct cgroup_subsys_state *css);
 514        void (*css_free)(struct cgroup_subsys_state *css);
 515        void (*css_reset)(struct cgroup_subsys_state *css);
 516
 517        int (*can_attach)(struct cgroup_taskset *tset);
 518        void (*cancel_attach)(struct cgroup_taskset *tset);
 519        void (*attach)(struct cgroup_taskset *tset);
 520        void (*post_attach)(void);
 521        int (*can_fork)(struct task_struct *task);
 522        void (*cancel_fork)(struct task_struct *task);
 523        void (*fork)(struct task_struct *task);
 524        void (*exit)(struct task_struct *task);
 525        void (*free)(struct task_struct *task);
 526        void (*bind)(struct cgroup_subsys_state *root_css);
 527
 528        bool early_init:1;
 529
 530        /*
 531         * If %true, the controller, on the default hierarchy, doesn't show
 532         * up in "cgroup.controllers" or "cgroup.subtree_control", is
 533         * implicitly enabled on all cgroups on the default hierarchy, and
 534         * bypasses the "no internal process" constraint.  This is for
 535         * utility type controllers which is transparent to userland.
 536         *
 537         * An implicit controller can be stolen from the default hierarchy
 538         * anytime and thus must be okay with offline csses from previous
 539         * hierarchies coexisting with csses for the current one.
 540         */
 541        bool implicit_on_dfl:1;
 542
 543        /*
 544         * If %true, the controller, supports threaded mode on the default
 545         * hierarchy.  In a threaded subtree, both process granularity and
 546         * no-internal-process constraint are ignored and a threaded
 547         * controllers should be able to handle that.
 548         *
 549         * Note that as an implicit controller is automatically enabled on
 550         * all cgroups on the default hierarchy, it should also be
 551         * threaded.  implicit && !threaded is not supported.
 552         */
 553        bool threaded:1;
 554
 555        /*
 556         * If %false, this subsystem is properly hierarchical -
 557         * configuration, resource accounting and restriction on a parent
 558         * cgroup cover those of its children.  If %true, hierarchy support
 559         * is broken in some ways - some subsystems ignore hierarchy
 560         * completely while others are only implemented half-way.
 561         *
 562         * It's now disallowed to create nested cgroups if the subsystem is
 563         * broken and cgroup core will emit a warning message on such
 564         * cases.  Eventually, all subsystems will be made properly
 565         * hierarchical and this will go away.
 566         */
 567        bool broken_hierarchy:1;
 568        bool warned_broken_hierarchy:1;
 569
 570        /* the following two fields are initialized automtically during boot */
 571        int id;
 572        const char *name;
 573
 574        /* optional, initialized automatically during boot if not set */
 575        const char *legacy_name;
 576
 577        /* link to parent, protected by cgroup_lock() */
 578        struct cgroup_root *root;
 579
 580        /* idr for css->id */
 581        struct idr css_idr;
 582
 583        /*
 584         * List of cftypes.  Each entry is the first entry of an array
 585         * terminated by zero length name.
 586         */
 587        struct list_head cfts;
 588
 589        /*
 590         * Base cftypes which are automatically registered.  The two can
 591         * point to the same array.
 592         */
 593        struct cftype *dfl_cftypes;     /* for the default hierarchy */
 594        struct cftype *legacy_cftypes;  /* for the legacy hierarchies */
 595
 596        /*
 597         * A subsystem may depend on other subsystems.  When such subsystem
 598         * is enabled on a cgroup, the depended-upon subsystems are enabled
 599         * together if available.  Subsystems enabled due to dependency are
 600         * not visible to userland until explicitly enabled.  The following
 601         * specifies the mask of subsystems that this one depends on.
 602         */
 603        unsigned int depends_on;
 604};
 605
 606extern struct percpu_rw_semaphore cgroup_threadgroup_rwsem;
 607
 608/**
 609 * cgroup_threadgroup_change_begin - threadgroup exclusion for cgroups
 610 * @tsk: target task
 611 *
 612 * Allows cgroup operations to synchronize against threadgroup changes
 613 * using a percpu_rw_semaphore.
 614 */
 615static inline void cgroup_threadgroup_change_begin(struct task_struct *tsk)
 616{
 617        percpu_down_read(&cgroup_threadgroup_rwsem);
 618}
 619
 620/**
 621 * cgroup_threadgroup_change_end - threadgroup exclusion for cgroups
 622 * @tsk: target task
 623 *
 624 * Counterpart of cgroup_threadcgroup_change_begin().
 625 */
 626static inline void cgroup_threadgroup_change_end(struct task_struct *tsk)
 627{
 628        percpu_up_read(&cgroup_threadgroup_rwsem);
 629}
 630
 631#else   /* CONFIG_CGROUPS */
 632
 633#define CGROUP_SUBSYS_COUNT 0
 634
 635static inline void cgroup_threadgroup_change_begin(struct task_struct *tsk)
 636{
 637        might_sleep();
 638}
 639
 640static inline void cgroup_threadgroup_change_end(struct task_struct *tsk) {}
 641
 642#endif  /* CONFIG_CGROUPS */
 643
 644#ifdef CONFIG_SOCK_CGROUP_DATA
 645
 646/*
 647 * sock_cgroup_data is embedded at sock->sk_cgrp_data and contains
 648 * per-socket cgroup information except for memcg association.
 649 *
 650 * On legacy hierarchies, net_prio and net_cls controllers directly set
 651 * attributes on each sock which can then be tested by the network layer.
 652 * On the default hierarchy, each sock is associated with the cgroup it was
 653 * created in and the networking layer can match the cgroup directly.
 654 *
 655 * To avoid carrying all three cgroup related fields separately in sock,
 656 * sock_cgroup_data overloads (prioidx, classid) and the cgroup pointer.
 657 * On boot, sock_cgroup_data records the cgroup that the sock was created
 658 * in so that cgroup2 matches can be made; however, once either net_prio or
 659 * net_cls starts being used, the area is overriden to carry prioidx and/or
 660 * classid.  The two modes are distinguished by whether the lowest bit is
 661 * set.  Clear bit indicates cgroup pointer while set bit prioidx and
 662 * classid.
 663 *
 664 * While userland may start using net_prio or net_cls at any time, once
 665 * either is used, cgroup2 matching no longer works.  There is no reason to
 666 * mix the two and this is in line with how legacy and v2 compatibility is
 667 * handled.  On mode switch, cgroup references which are already being
 668 * pointed to by socks may be leaked.  While this can be remedied by adding
 669 * synchronization around sock_cgroup_data, given that the number of leaked
 670 * cgroups is bound and highly unlikely to be high, this seems to be the
 671 * better trade-off.
 672 */
 673struct sock_cgroup_data {
 674        union {
 675#ifdef __LITTLE_ENDIAN
 676                struct {
 677                        u8      is_data;
 678                        u8      padding;
 679                        u16     prioidx;
 680                        u32     classid;
 681                } __packed;
 682#else
 683                struct {
 684                        u32     classid;
 685                        u16     prioidx;
 686                        u8      padding;
 687                        u8      is_data;
 688                } __packed;
 689#endif
 690                u64             val;
 691        };
 692};
 693
 694/*
 695 * There's a theoretical window where the following accessors race with
 696 * updaters and return part of the previous pointer as the prioidx or
 697 * classid.  Such races are short-lived and the result isn't critical.
 698 */
 699static inline u16 sock_cgroup_prioidx(struct sock_cgroup_data *skcd)
 700{
 701        /* fallback to 1 which is always the ID of the root cgroup */
 702        return (skcd->is_data & 1) ? skcd->prioidx : 1;
 703}
 704
 705static inline u32 sock_cgroup_classid(struct sock_cgroup_data *skcd)
 706{
 707        /* fallback to 0 which is the unconfigured default classid */
 708        return (skcd->is_data & 1) ? skcd->classid : 0;
 709}
 710
 711/*
 712 * If invoked concurrently, the updaters may clobber each other.  The
 713 * caller is responsible for synchronization.
 714 */
 715static inline void sock_cgroup_set_prioidx(struct sock_cgroup_data *skcd,
 716                                           u16 prioidx)
 717{
 718        struct sock_cgroup_data skcd_buf = {{ .val = READ_ONCE(skcd->val) }};
 719
 720        if (sock_cgroup_prioidx(&skcd_buf) == prioidx)
 721                return;
 722
 723        if (!(skcd_buf.is_data & 1)) {
 724                skcd_buf.val = 0;
 725                skcd_buf.is_data = 1;
 726        }
 727
 728        skcd_buf.prioidx = prioidx;
 729        WRITE_ONCE(skcd->val, skcd_buf.val);    /* see sock_cgroup_ptr() */
 730}
 731
 732static inline void sock_cgroup_set_classid(struct sock_cgroup_data *skcd,
 733                                           u32 classid)
 734{
 735        struct sock_cgroup_data skcd_buf = {{ .val = READ_ONCE(skcd->val) }};
 736
 737        if (sock_cgroup_classid(&skcd_buf) == classid)
 738                return;
 739
 740        if (!(skcd_buf.is_data & 1)) {
 741                skcd_buf.val = 0;
 742                skcd_buf.is_data = 1;
 743        }
 744
 745        skcd_buf.classid = classid;
 746        WRITE_ONCE(skcd->val, skcd_buf.val);    /* see sock_cgroup_ptr() */
 747}
 748
 749#else   /* CONFIG_SOCK_CGROUP_DATA */
 750
 751struct sock_cgroup_data {
 752};
 753
 754#endif  /* CONFIG_SOCK_CGROUP_DATA */
 755
 756#endif  /* _LINUX_CGROUP_DEFS_H */
 757