7.4 Early Initialization of Control Groups
Control Groups (universally abbreviated as cgroups) represent a fundamental subsystem within the Linux kernel architecture, designed to enforce fine-grained resource management, isolation, and telemetry. Leveraging cgroups, system administrators can explicitly configure resource allocation ceilings (such as maximum CPU core execution time boundaries, physical RAM constraints, or block I/O parameters) and assign granular processing priority vectors across different collections of processes.
The underlying engineering strategy of cgroup resource tracking relies on partitioning system resources into specific, functional hierarchies. These top-level resource blocks can be further broken down into secondary sub-groups, resulting in a multi-dimensional tree structure. This abstract data tree maps directly to the operational directory structure of the cgroup virtual filesystem (cgroupfs) exposed to user space. An administrator can dynamically throttle the runtime behavior of an application thread by binding its process context to a specific branch within this cgroup hierarchy, forcing the process to execute within the resource parameters assigned to that node. A process can be simultaneously attached to multiple independent cgroup paths to capture and constrain different system resources. The following schematic illustrates the structural mechanics and thread-binding relationships mapping a cgroup tree layout implemented under the legacy v1 cgroup specification:
Figure 7-2 cgroup v1 Hierarchy Mapping and Process Bindings
The overall cgroup ecosystem is structurally defined by three core abstractions: the Control Group (cgroup), the Control Group Filesystem (cgroupfs), and the Resource Subsystem (subsystem). The underlying kernel modules leverage the structural metadata tables exposed by both the cgroup nodes and the virtual filesystem layer to coordinate low-level scheduling and resource enforcement loops. The design rules and structural characteristics governing contemporary cgroup frameworks are detailed below, using the modern cgroup v2 architecture standard as a reference model.
The Control Group (cgroup) and Virtual Filesystem
A control group defines a logical aggregation or set of running processes or execution threads constrained by an identical collection of resource thresholds and scheduling variables specified within a matching cgroupfs interface node. Internally, the kernel organizes cgroups as a hierarchical tree topology that mirrors the physical directory layout of the unified cgroup filesystem. System administrators can dynamically reshape or scale this tracking tree from user space simply by executing standard directory creation (mkdir), deletion (rmdir), or re-naming (mv) instructions under the mount point located at /sys/fs/cgroup.
Each discrete cgroup can host a collection of processes, an aggregation of standalone execution threads, or encapsulate multiple nested downstream child cgroups. The legacy cgroup v1 specification permitted resource budgeting to be granulated down to the individual thread level, meaning a single thread could be decoupled from its parent process and mapped to run inside an entirely separate cgroup. While this flexibility provided powerful, low-level tuning hooks, the architectural side effects and tracking overhead severely degraded system determinism.
To resolve these complexities, the unified cgroup v2 standard implements the strict "no internal processes" rule. Under this specification, a cgroup node is strictly prohibited from housing a mixture of both child cgroups and active process contexts; a node must either act exclusively as an internal container that routes down to secondary child cgroups, or function strictly as an end-node containing processes exclusively. Consequently, all standard user-space processes are forced to reside exclusively within the leaf nodes of the cgroup hierarchy.
Threaded Subtrees and Domain Classifications
While the structural constraints introduced by cgroup v2 significantly reduced kernel management complexity, they completely eliminated the capability to granularly budget resources down to individual threads in certain deployments. To restore this capability without compromising architectural stability, contemporary Linux kernels introduce the concept of Threaded Subtrees. A threaded subtree represents an isolated branch within the main cgroup tree where individual nodes are explicitly permitted to contain child cgroups, thread pointers, or a combination of both.
The root origin of a threaded subtree is defined as the closest ancestral node that complies with the standard process-only container layout, known as the Threaded Domain Root. Under this multi-domain architecture model, cgroup v2 classifies nodes into specific operational categories: nodes containing standard child cgroups or complete process clusters are categorized into the Domain Class, the structural root node anchoring a threaded branch is designated as a Threaded Domain Class, and all secondary downstream sub-nodes nested along that threaded branch are managed under the Threaded Cgroup Class.
Resource Subsystems (Resource Managers)
A subsystem—frequently referenced as a Resource Controller—is an internal, low-level Linux kernel module engineered to intercept and alter the operational behavior of tasks. For instance, a controller can throttle the maximum CPU execution time slices allocated to a cgroup, fence off the volume of physical page frames a group can pin in RAM, profile the runtime CPU cycles consumed across a collection of tasks, or execute global freezer hooks to freeze and resume process execution threads.
These resource managers leverage cgroup categorization loops to process groups of tasks collectively using specialized scheduling algorithms. Typically, each distinct system resource maps back to an independent hardware controller module. Under the legacy v1 specification, each resource controller maintained its own completely independent tree topology, forcing users to track and navigate separate filesystem trees to schedule individual resources and assign ceilings for a process.
The cgroup v2 architecture design resolves this fragmentation by enforcing a Unified Hierarchy, binding all resource controllers to a single, consolidated tree structure. This design allows administrators to coordinate all resource scheduling, budgeting, and performance tracking vectors globally through a single centralized cgroup filesystem interface.
The Ubuntu Linux distribution defines 18 distinct subsystems, mapping to 18 individual resource managers. Several of the most frequently deployed subsystems are detailed below:
-
blkio: Sets resource limits and throttling thresholds for block device access (such as disk I/O operations).
-
cpu: Regulates CPU time-slice distribution and processing bandwidth allocation using the kernel scheduler.
-
cpuacct: Automatically aggregates telemetry data to generate comprehensive CPU resource utilization reports for tasks within a control group.
-
cpuset: Isolates specific CPU cores and memory nodes (NUMA affinity mapping) to assign them exclusively to designated tasks.
-
devices: Restricts or permits access permissions to physical character and block device nodes.
-
freezer: Pauses (suspends) or resumes the runtime execution sequence of tasks enclosed within a control group.
-
memory: Enforces strict physical RAM and swap space usage ceilings for targeted tasks while automatically generating detailed memory tracking reports.
-
net_cls: Tags network data packets with a specific class identifier (classid), allowing egress network traffic shapers to trace data back to its origin control group.
-
net_prio: Dynamically assigns priority coefficients to network interfaces on a per-cgroup basis.
-
ns: The namespace subsystem, designed to route resource scheduling over isolated operational environments; different namespaces can implement entirely separate scheduling policies.
The cgroupfs interface functions as a Linux pseudo-filesystem, serving as the primary kernel boundary layer exposed to user space. System administrators can mount this virtual directory structure to any designated location within the filesystem tree. Under the legacy cgroup v1 standard, each individual resource controller maintained an independent pseudo-filesystem instance, permitting users to mount different resource managers to entirely separate directory endpoints. Conversely, the cgroup v2 architecture mandates that all integrated resource controllers share a single, unified pseudo-filesystem instance. In modern Linux distributions, the initialization manager systemd automatically mounts this consolidated filesystem to the absolute path /sys/fs/cgroup during the early boot phase; throughout all subsequent analyses, this filesystem is assumed to reside at /sys/fs/cgroup.
Every subdirectory nested beneath this root cgroup directory maps directly to a specific structural node within the control group tree topology. In frameworks deploying cgroup v1 mechanics, each distinct resource manager exposes a corresponding parent subdirectory inside the mount root. In architectures tracking the cgroup v2 standard, subdirectories do not necessarily correspond to a single standalone resource; instead, each container directory exposes two vital control nodes: cgroup.controllers and cgroup.subtree_control. By updating these control files, administrators toggle resource constraints over the sub-tree.
However, within current kernel implementations, because a subset of legacy resource controllers has not yet been fully refactored to support the v2 specification, the subdirectories nested under /sys/fs/cgroup often remain mapped to individual resource managers to guarantee backward compatibility with v1 layouts. Utilizing this virtual filesystem layer, administrators can create or destroy structural nodes along the cgroup tree, establish process-specific resource limits and execution priorities, extract precise resource tracking statistics, and maintain absolute control over task behaviors.
An administrator can instantiate a new child cgroup node along the hierarchy simply by executing standard directory creation steps to form a new subdirectory inside any active cgroup path; similarly, removing a directory deletes the corresponding control node from the execution tree. Each localized cgroup directory hosts an array of core control files, resource configuration descriptors, and diagnostic data files. Diagnostic data files are strictly read-only nodes dynamically populated by the kernel to provide administrators with clear telemetry tracking system resource behavior. Conversely, core control files and resource configuration descriptors are formatted as read-write files generated by the system.
When an administrator creates or modifies these files, the kernel utilizes them to schedule and manage the resources regulated by that specific resource controller. The files dedicated to resource constraint optimization restrict or enhance the behavior of the active processes mapped to the corresponding nested subdirectories.
Every localized cgroup subdirectory can host both core control files and resource configuration files. Core control files regulate the fundamental architecture of the control group hierarchy itself; they are designated with a cgroup prefix name string, and their trailing extension tags define their functional file type. Several of the most infrastructure-critical control files include cgroup.procs, cgroup.type, cgroup.threads, and cgroup.subtree_control.
The cgroup.procs file registers the absolute Process IDs (PIDs) of all processes assigned to the cgroup node matching that subdirectory. Reading this file outputs a clear list tracking all currently associated processes, while writing a specific process PID into it immediately rebinds and relocates that process into the control group context of the current directory. This file can be interrogated or modified via standard shell commands as shown below:
-
Create a new child cgroup named cg1:
# mkdir /sys/fs/cgroup/cpu/cg1 -
Attach the current shell process to the cg1 control group:
# echo \$\$ > /sys/fs/cgroup/cpu/cg1/cgroup.procs -
Display all processes currently contained within the control group:
# cat /sys/fs/cgroup/cpu/cg1/cgroup.procs
The cgroup.type file specifies the runtime domain classification of the control group matching that subdirectory. The registered type can resolve to a standard resource domain (domain), a threaded domain root (threaded domain), a nested threaded control group (threaded), or an unvalidated domain (invalid domain). The first three configurations represent the production domain classifications detailed in the preceding cgroup v2 conceptual overview.
Conversely, the invalid domain flag functions as a transient tracking type deployed dynamically when setting up a threaded subtree hierarchy; it signals that the control group rests in an unvalidated, temporary state. An invalid control group is strictly prohibited from housing process contexts or running resource budget constraints; it must be converted into a validated production type before it can accept active tasks. The inclusion of this invalid state ensures the kernel layout can support subsequent architectural expansions of the threaded cgroup model.
The classification parameters tracking a control group's type can be audited or changed via the following operations:
-
Configure the cg1 control group to act as a threaded control group:
# echo threaded > /sys/fs/cgroup/cpu/cg1/cgroup.type -
Configure the cg1 control group to act as a standard resource domain:
# echo domain > /sys/fs/cgroup/cpu/cg1/cgroup.type -
Configure the cg1 control group to act as a threaded domain root:
# echo "threaded domain" > /sys/fs/cgroup/cpu/cg1/cgroup.type
The cgroup.threads file logs the specific Thread IDs (TIDs) of all individual execution threads contained within that control group. Attaching an individual thread to a designated cgroup is handled by writing its unique TID into the target cgroup.threads node, and removing a TID from this list unbinds and expels the thread from the group.
The cgroup.controllers file is configured as a read-only metadata node that catalogs all available resource controllers currently active for that specific cgroup. To remain valid, these controllers must be explicitly derived from and enabled by the parent ancestral cgroup node.
The cgroup.subtree_control file logs the specific resource controllers that are actively enabled for the children of that control group. The controllers configured inside this file must strictly be a subset of the entries exposed within cgroup.controllers; a control group can only activate a resource controller if it is explicitly whitelisted inside its cgroup.controllers metadata node. The following commands show the method for dynamically enabling or disabling resource controllers utilizing the cgroup.subtree_control node interface:
-
Create a new child control group named mycgroup:
# mkdir /sys/fs/cgroup/mycgroup -
Enable the pids, cpu, and memory resource controllers for the nested subtree:
$ echo '+pids + cpu +memory' > /sys/fs/cgroup/mycgroup/cgroup.subtree_control
- Disable the pids controller within the mycgroup subtree:
$ echo '-pids' > /sys/fs/cgroup/mycgroup/cgroup.subtree_control
Beyond the primary core control files introduced above, each control group directory hosts an array of secondary tracking nodes, including cgroup.events, cgroup.max.descendants, cgroup.max.depth, cgroup.stat, cgroup.freeze, cgroup.kill, cgroup.pressure, and irq.pressure. Interested developers can consult the corresponding system documentation or Linux cgroup manuals for granular bitwise definitions of these blocks.
Resource Control Interface Files
Except for the absolute root cgroup container directory, every nested subdirectory exposes an array of dedicated resource control interface files. The naming standard for these interface nodes generally follows the explicit syntax format resource.parameter.
For instance, the cpu resource controller tasked with managing CPU clock-cycle and processing bandwidth distribution provides nine control nodes, including cpu.stat, cpu.weight.nice, cpu.max, cpu.max.burst, cpu.pressure, and cpu.idle. Concurrently, the memory resource management infrastructure maps out twenty-one control interface files, including memory.current, memory.min, memory.low, memory.high, memory.max, memory.reclaim, and memory.oom.group.
A subset of these nodes functions strictly as read-only diagnostic counters to aggregate memory execution metrics, whereas the majority serve as read-write variables to establish the definitive memory limits for the control group. Generally, each distinct file regulates a single structural parameter. For example:
# echo "2M" > /sys/fs/cgroup/mycgroup/memory.min
This statement establishes a strict minimum memory guarantee threshold of 2 MB for the mycgroup control group. As long as the memory footprint consumed by this group drops below the 2 MB boundary, the kernel's memory management tracking engine is completely barred from reclaiming or purging its pages under any physical memory pressure state.
Varying the target resource manager shifts the applicable parameter options, and the total count of interface files changes strictly based on the subsystem's architectural complexity; full listings are available within the upstream cgroup manual.
Core Cgroup Data Structures
The internal kernel code implementing the cgroup resource budgeting infrastructure relies on a decoupled network of data structures, predominantly encompassing struct cgroup, struct cgroup_root, struct cgroup_subsys, and struct cgroup_subsys_state.
-
struct cgroup: Describes the hierarchical node architecture of the control group tree topology. Every active directory path across the cgroup hierarchy maps to an individual cgroup structure instance inside the kernel, guaranteeing that all processes and execution threads linked to that node share identical resource ceilings and configuration variables. This structure is defined within the core header file git/include/linux/cgroup-defs.h. Its primary fields track the localized state of individual child subsystems, the absolute root pointer of the host tree, the relative depth or tier of the node along the hierarchy, the maximum depth limits of the subtree, the precise counter parameters tracking child nodes by category, and the active bitmask filters regulating enabled or disabled controllers. It also encapsulates an array of pointers routing to the individual controller states, the linked virtual filesystem virtual tracking nodes, and a master linked list connecting all associated subsystem states.
-
struct cgroup_root: Represents the absolute root container of a cgroup hierarchy tree. Declared within git/include/linux/cgroup-defs.h, it bridges the cgroup tree to the virtual filesystem infrastructure by embedding the .kf_root field, which points to the unified struct kernfs_root directory node. It also implements the .subsys_mask bitmask tracking globally enabled or disabled controllers, embeds the primitive struct cgroup structure (.cgrp) allocated to anchor the root block itself, and maintains a collection of tracking lists to manage the root mappings of various resource controllers (retained to ensure compatibility with legacy cgroup v1 environments).
-
struct cgroup_subsys: Defines the operational behavior and callback hooks of a specific resource controller subsystem. Maintained within git/include/linux/cgroup-defs.h, it exposes an array of low-level scheduling and resource enforcement function pointers, references the primary hierarchy tree root via the .root field, stores the descriptive system key string (.name), and sets the .implicit_on_dfl boolean flag to indicate whether the subsystem initializes by default. It also implements the .threaded flag bit to verify thread-level cgroup capability and tracks resource-specific virtual configuration nodes via the .cfts metadata arrays and the default .dfl_cfts property collections.
-
struct cgroup_subsys_state: Captures and maintains the runtime execution state of a specific controller module associated with an individual cgroup. These subsystem state blocks form a parallel tree hierarchy that mirrors the layout of the primary control group tree. Each state tree node references a matching node on the cgroup hierarchy, serving as the definitive database used by resource managers to tune scheduling parameters. The structure primarily contains a direct pointer referencing its parent control group, a pointer tracking its target resource controller subsystem, and standard layout fields to anchor the node within the hierarchy (including indicators routing to its parent node, list fields tracking sister nodes, and links mapping its immediate child branches).
Early Cgroup Initialization (cgroup_init_early)
The primary objective of the early initialization function cgroup_init_early() is to construct the default global cgroup root node (cgrp_dfl_root), initialize its master root list tracking parameters, and hook the early startup process into the cgroup framework. It accomplishes this task by writing the absolute physical address of the static initialization tracking set init_css_set straight into the .cgroups tracking pointer field inside the primary bootstrap task descriptor init_task.
The core initial tracking matrix is defined by the static init_css_set structure, which initializes with the following layout:
struct css_set init_css_set = {
.refcount = REFCOUNT_INIT(1),
.dom_cset = &init_css_set,
.tasks = LIST_HEAD_INIT(init_css_set.tasks),
.mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
.dying_tasks = LIST_HEAD_INIT(init_css_set.dying_tasks),
.task_iters = LIST_HEAD_INIT(init_css_set.task_iters),
.threaded_csets = LIST_HEAD_INIT(init_css_set.threaded_csets),
.cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
.mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
.mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
.dfl_cgrp = &cgrp_dfl_root.cgrp,
};
Its architectural function is to configure and initialize the master list heads for tracking tasks across distinct execution boundaries, ensuring that tasks running through different behavioral cycles are isolated into separate linked lists.
The struct css_set structure acts as a centralized data repository required during the resource budgeting process, aggregating the state arrays of individual subsystems, referencing its associated control group nodes, and anchoring the various task linked lists. If a target node is classified as a standard resource domain or a threaded domain root, this structure also logs a comprehensive listing of all active nodes utilizing that specific domain. Furthermore, to seamlessly execute task migration routines—such as moving a running process or execution thread from one control group to an alternative branch—the structure caches the metadata and routing metrics tracking both the source and destination nodes during the migration cycle.
The primary design objective of implementing the css_set abstraction is not to manage the resources themselves, but rather to optimize system performance by drastically reducing the memory storage footprint of the task_struct arrays, which accelerates the execution speed of process cloning and termination routines (fork() and exit()). When a running task initiates a fork or exit routine, the kernel simply increments or decrements the reference counter field (.refcount) inside the corresponding css_set structure, followed by a fast list node insertion or deletion. This avoids the overhead of allocating or deep-copying massive blocks of duplicated data structures. Every active task in the Linux kernel accesses its associated subsystem states and node parameters indirectly by indexing through its own assigned css_set reference pointer.
Beyond establishing the default baseline control group root node, the cgroup_init_early() function performs early validation loops across the available resource subsystems, assigning unique names and unique identification indexes to every controller supported by the compiled kernel. If a specific subsystem registers a dependency requiring early lifecycle bring-up (indicated by the presence of an active .early_init flag bit inside its struct cgroup_subsys definition), the routine calls the controller's specialized early initializer to provision the subsystem.
The technical workflow executing this early subsystem initialization focuses primarily on setting the initial field states inside the target resource controller structure (struct cgroup_subsys). This sequence zeroes out the localized subsystem status identifiers, initializes the tracking list heads for the control group configuration files, and binds the subsystem's absolute root pointer field straight to the default global cgroup root node. It then generates a valid initial subsystem state descriptor layout (struct cgroup_subsys_state), configures its tracking identifier flags to 1, and registers this newly established state block directly into the centralized subsystem state array pool.
The interlocking network linking struct css_set, struct cgroup_subsys_state, and struct cgroup completely resolves the architectural challenge of tracking which running tasks belong to which control groups and defining the exact subsystem constraints bounding their execution.
-
struct cgroup: Represents an active, structural cgroup directory node inside the kernel. It coordinates and organizes various resource controllers (such as CPU bandwidth managers and memory fences) into a deterministic, hierarchical tree topology.
-
struct cgroup_subsys_state (css): Functions as the core status carrier. It encapsulates the precise resource limitations and scheduling configurations enforced by a concrete subsystem over an individual cgroup node; every valid cgroup node maintains a collection of these css pointers.
-
struct css_set: Serves as the high-speed operational bridge connecting the running process (task_struct) to its cgroup nodes. Because a single process context can be simultaneously bounded by multiple separate cgroups across disparate resource hierarchies, mapping individual processes directly to multiple separate cgroups would degrade kernel performance. The kernel resolves this by routing each process to point straight to a single consolidated css_set pointer. If two independent processes share an identical combination of cgroup bindings across all active resource controllers, they share a single, unified css_set instance in memory.
The multi-dimensional interface relationship linking these data structures is mapped out in the schematic diagram below, where the css_set exposes a continuous array of cgroup_subsys_state pointers, each routing to an individual state descriptor, which subsequently utilizes its internal .cgroup tracking pointer to map back to the parent cgroup container node:
Figure 7-3 Architectural Relationships Linking Core Data Structures in the Cgroup Subsystem