Skip to contentSkip to conversation

cgroups: add pids subsystem

PATCH Superseded Aleksa Sarai 2 participants 7 messages Apr 1, 2015

Subsystems (4)

v7 of 14 Superseded Latest is v14 →

lore
Share & tools
lore
#0 lore raw

v7 cover cgroups: add pids subsystem

This is a futher revised version of the pids v6 patchset[1]. The main changes include:

* Actually separate the subsystem callback bitmasks for use with for_each_subsys_which(needs_*_callback, ...). Also switch from the usage of explicit ss_mask checking with for_each_subsys() with for_each_subsys_which().

* Pass an opaque cgroup_fork_state structure between the cgroup_{can,cancel,post}_fork hooks which stores the current task_struct's css_set. The refcount bumping and dropping is handled within cgroup_cfs_{get,put}() respectively. This is done so that the internal implementation of cgroup_fork_state is not exposed to copy_process(), while also allowing the caller to decide when they want to snapshot the current css_set.

* Fix a bug where migrating a task between cgroup hierachies would not decrement pids.counter in the source hierarchy. This would cause limits to be enforced prematurely due to residual charges on the pid counter. This is done by adding a detach() callback that alerts a subsystem to a task detaching from it.

[1]: https://lkml.org/lkml/2015/3/14/2

Aleksa Sarai (4):
cgroups: use bitmask to filter for_each_subsys
cgroups: replace explicit ss_mask checking with for_each_subsys_which
cgroups: allow a cgroup subsystem to reject a fork
cgroups: implement the PIDs subsystem

 include/linux/cgroup.h        |  42 +++++-
 include/linux/cgroup_subsys.h |   4 +
 init/Kconfig                  |  16 +++
 kernel/Makefile               |   1 +
 kernel/cgroup.c               | 244 ++++++++++++++++++++++++++-------
 kernel/cgroup_pids.c          | 310 ++++++++++++++++++++++++++++++++++++++++++
 kernel/fork.c                 |  38 +++++-
 7 files changed, 596 insertions(+), 59 deletions(-)
 create mode 100644 kernel/cgroup_pids.c
Signature · 1 line
2.3.4
#1 lore raw

PATCH v7 1/4 cgroups: use bitmask to filter for_each_subsys

Add a new macro for_each_subsys_which that allows all enabled cgroup subsystems to be filtered by a bitmask, such that mask & (1 << ssid) determines if the subsystem is to be processed in the loop body (where ssid is the unique id of the subsystem).

---
 kernel/cgroup.c | 43 ++++++++++++++++++++++++++-----------------
 1 file changed, 26 insertions(+), 17 deletions(-)
kernel/cgroup.c +26 -17
index 29a7b2c..1d69a085 100644
@@ -175,12 +175,14 @@ static DEFINE_IDR(cgroup_hierarchy_idr);
  */
 static u64 css_serial_nr_next = 1;
 
-/* This flag indicates whether tasks in the fork and exit paths should
+/*
+ * These bitmask flags indicate whether tasks in the fork and exit paths should
  * check for fork/exit handlers to call. This avoids us having to do
  * extra work in the fork/exit path if none of the subsystems need to
  * be called.
  */
-static int need_forkexit_callback __read_mostly;
+static int need_fork_callback __read_mostly;
+static int need_exit_callback __read_mostly;
 
 static struct cftype cgroup_dfl_base_files[];
 static struct cftype cgroup_legacy_base_files[];
@@ -409,6 +411,19 @@ static int notify_on_release(const struct cgroup *cgrp)
 	for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT &&		\
 	     (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
 
+/**
+ * for_each_subsys_which - filter for_each_subsys with a bitmask
+ * @ss_mask: the bitmask
+ * @ss: the iteration cursor
+ * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
+ *
+ * The block will only run for cases where the ssid-th bit (1 << ssid) of
+ * mask is set to 1.
+ */
+#define for_each_subsys_which(ss_mask, ss, ssid) \
+	for_each_subsys((ss), (ssid)) \
+		if ((ss_mask) & (1 << (ssid)))
+
 /* iterate across the hierarchies */
 #define for_each_root(root)						\
 	list_for_each_entry((root), &cgroup_roots, root_list)
@@ -4932,7 +4947,8 @@ static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
 	 * init_css_set is in the subsystem's root cgroup. */
 	init_css_set.subsys[ss->id] = css;
 
-	need_forkexit_callback |= ss->fork || ss->exit;
+	need_fork_callback |= (bool) ss->fork << ss->id;
+	need_exit_callback |= (bool) ss->exit << ss->id;
 
 	/* At system boot, before all subsystems have been
 	 * registered, no tasks have been forked, so we don't
@@ -5239,11 +5255,8 @@ void cgroup_post_fork(struct task_struct *child)
 	 * css_set; otherwise, @child might change state between ->fork()
 	 * and addition to css_set.
 	 */
-	if (need_forkexit_callback) {
-		for_each_subsys(ss, i)
-			if (ss->fork)
-				ss->fork(child);
-	}
+	for_each_subsys_which(need_fork_callback, ss, i)
+		ss->fork(child);
 }
 
 /**
@@ -5287,16 +5300,12 @@ void cgroup_exit(struct task_struct *tsk)
 	cset = task_css_set(tsk);
 	RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
 
-	if (need_forkexit_callback) {
-		/* see cgroup_post_fork() for details */
-		for_each_subsys(ss, i) {
-			if (ss->exit) {
-				struct cgroup_subsys_state *old_css = cset->subsys[i];
-				struct cgroup_subsys_state *css = task_css(tsk, i);
+	/* see cgroup_post_fork() for details */
+	for_each_subsys_which(need_exit_callback, ss, i) {
+		struct cgroup_subsys_state *old_css = cset->subsys[i];
+		struct cgroup_subsys_state *css = task_css(tsk, i);
 
-				ss->exit(css, old_css, tsk);
-			}
-		}
+		ss->exit(css, old_css, tsk);
 	}
 
 	if (put_cset)
Signature · 1 line
2.3.4
#2 lore raw

PATCH v7 2/4 cgroups: replace explicit ss_mask checking with for_each_subsys_which

In reply to Aleksa Sarai

Replace the explicit checking against ss_masks inside a for_each_subsys block with for_each_subsys_which(ss_mask, ...), to take advantage of the more readable macro.

---
 kernel/cgroup.c | 42 ++++++++++++++----------------------------
 1 file changed, 14 insertions(+), 28 deletions(-)
kernel/cgroup.c +14 -28
index 1d69a085..abd491f 100644
@@ -1099,9 +1099,8 @@ static unsigned int cgroup_calc_child_subsys_mask(struct cgroup *cgrp,
 	while (true) {
 		unsigned int new_ss_mask = cur_ss_mask;
 
-		for_each_subsys(ss, ssid)
-			if (cur_ss_mask & (1 << ssid))
-				new_ss_mask |= ss->depends_on;
+		for_each_subsys_which(cur_ss_mask, ss, ssid)
+			new_ss_mask |= ss->depends_on;
 
 		/*
 		 * Mask out subsystems which aren't available.  This can
@@ -1238,10 +1237,7 @@ static int rebind_subsystems(struct cgroup_root *dst_root, unsigned int ss_mask)
 
 	lockdep_assert_held(&cgroup_mutex);
 
-	for_each_subsys(ss, ssid) {
-		if (!(ss_mask & (1 << ssid)))
-			continue;
-
+	for_each_subsys_which(ss_mask, ss, ssid) {
 		/* if @ss has non-root csses attached to it, can't move */
 		if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)))
 			return -EBUSY;
@@ -1278,18 +1274,14 @@ static int rebind_subsystems(struct cgroup_root *dst_root, unsigned int ss_mask)
 	 * Nothing can fail from this point on.  Remove files for the
 	 * removed subsystems and rebind each subsystem.
 	 */
-	for_each_subsys(ss, ssid)
-		if (ss_mask & (1 << ssid))
-			cgroup_clear_dir(&ss->root->cgrp, 1 << ssid);
+	for_each_subsys_which(ss_mask, ss, ssid)
+		cgroup_clear_dir(&ss->root->cgrp, 1 << ssid);
 
-	for_each_subsys(ss, ssid) {
+	for_each_subsys_which(ss_mask, ss, ssid) {
 		struct cgroup_root *src_root;
 		struct cgroup_subsys_state *css;
 		struct css_set *cset;
 
-		if (!(ss_mask & (1 << ssid)))
-			continue;
-
 		src_root = ss->root;
 		css = cgroup_css(&src_root->cgrp, ss);
 
@@ -2563,13 +2555,11 @@ static void cgroup_print_ss_mask(struct seq_file *seq, unsigned int ss_mask)
 	bool printed = false;
 	int ssid;
 
-	for_each_subsys(ss, ssid) {
-		if (ss_mask & (1 << ssid)) {
-			if (printed)
-				seq_putc(seq, ' ');
-			seq_printf(seq, "%s", ss->name);
-			printed = true;
-		}
+	for_each_subsys_which(ss_mask, ss, ssid) {
+		if (printed)
+			seq_putc(seq, ' ');
+		seq_printf(seq, "%s", ss->name);
+		printed = true;
 	}
 	if (printed)
 		seq_putc(seq, '\n');
@@ -2719,9 +2709,8 @@ static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
 	while ((tok = strsep(&buf, " "))) {
 		if (tok[0] == '\0')
 			continue;
-		for_each_subsys(ss, ssid) {
-			if (ss->disabled || strcmp(tok + 1, ss->name) ||
-			    ((1 << ss->id) & cgrp_dfl_root_inhibit_ss_mask))
+		for_each_subsys_which(~cgrp_dfl_root_inhibit_ss_mask, ss, ssid) {
+			if (ss->disabled || strcmp(tok + 1, ss->name))
 				continue;
 
 			if (*tok == '+') {
@@ -2808,10 +2797,7 @@ static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
 	 * still around.  In such cases, wait till it's gone using
 	 * offline_waitq.
 	 */
-	for_each_subsys(ss, ssid) {
-		if (!(css_enable & (1 << ssid)))
-			continue;
-
+	for_each_subsys_which(css_enable, ss, ssid) {
 		cgroup_for_each_live_child(child, cgrp) {
 			DEFINE_WAIT(wait);
 
Signature · 1 line
2.3.4
#3 lore raw

PATCH v7 3/4 cgroups: allow a cgroup subsystem to reject a fork

In reply to Aleksa Sarai

Add a new cgroup subsystem callback can_fork that conditionally states whether or not the fork is accepted or rejected by a cgroup policy.

In addition, add a cancel_fork callback so that if an error occurs later in the forking process, any state modified by can_fork can be reverted.

In order to ensure that the fork charged the right hierarchy, save the "current" css_set before doing ss->can_fork and compare it with the "current" css_set that gets committed to the task *proper* in post_fork. If they do not match, revert the can_fork's charging of the wrong hierarchy and forcefully reapply it to the right hierarchy using the reapply_fork callback. Since a changing "current" css_set in copy_process indicates an organisation operation took place, we can break the cgroup policy in this case.

In order for a subsystem to know that a task associated with a cgroup hierarchy is being migrated to another hierarchy, add a detach callback to the subsystem which is run after the migration has been confirmed but before the old_cset's refcount is dropped.

This is in preparation for implementing the pids cgroup subsystem.

---
 include/linux/cgroup.h |  42 ++++++++++++-
 kernel/cgroup.c        | 163 ++++++++++++++++++++++++++++++++++++++++++++++---
 kernel/fork.c          |  38 ++++++++++--
 3 files changed, 227 insertions(+), 16 deletions(-)
include/linux/cgroup.h +40 -2
index b9cb94c..278df0f 100644
@@ -25,14 +25,25 @@
 
 #ifdef CONFIG_CGROUPS
 
+struct cgroup_fork_state;
 struct cgroup_root;
 struct cgroup_subsys;
 struct cgroup;
 
+extern struct cgroup_fork_state *cgroup_cfs_alloc(void);
+extern void cgroup_cfs_free(struct cgroup_fork_state *cfs);
+extern void cgroup_cfs_get(struct cgroup_fork_state *cfs);
+extern void cgroup_cfs_put(struct cgroup_fork_state *cfs);
+
 extern int cgroup_init_early(void);
 extern int cgroup_init(void);
 extern void cgroup_fork(struct task_struct *p);
-extern void cgroup_post_fork(struct task_struct *p);
+extern int cgroup_can_fork(struct task_struct *p,
+			   struct cgroup_fork_state *cfs);
+extern void cgroup_cancel_fork(struct task_struct *p,
+			       struct cgroup_fork_state *cfs);
+extern void cgroup_post_fork(struct task_struct *p,
+			     struct cgroup_fork_state *old_cfs);
 extern void cgroup_exit(struct task_struct *p);
 extern int cgroupstats_build(struct cgroupstats *stats,
 				struct dentry *dentry);
@@ -649,6 +660,15 @@ struct cgroup_subsys {
 			      struct cgroup_taskset *tset);
 	void (*attach)(struct cgroup_subsys_state *css,
 		       struct cgroup_taskset *tset);
+	void (*detach)(struct cgroup_subsys_state *old_css,
+		       struct task_struct *task);
+	int (*can_fork)(struct cgroup_subsys_state *css,
+			struct task_struct *task);
+	void (*cancel_fork)(struct cgroup_subsys_state *css,
+			    struct task_struct *task);
+	void (*reapply_fork)(struct cgroup_subsys_state *css,
+			     struct cgroup_subsys_state *old_css,
+			     struct task_struct *task);
 	void (*fork)(struct task_struct *task);
 	void (*exit)(struct cgroup_subsys_state *css,
 		     struct cgroup_subsys_state *old_css,
@@ -943,12 +963,30 @@ struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
 
 #else /* !CONFIG_CGROUPS */
 
+struct cgroup_fork_state;
 struct cgroup_subsys_state;
 
+static inline struct cgroup_fork_state *cfs cgroup_cfs_alloc(void)
+{
+	return NULL;
+}
+static inline void cgroup_cfs_free(struct cgroup_fork_state *cfs) {}
+static inline void cgroup_cfs_get(struct cgroup_fork_state *cfs) {}
+static inline void cgroup_cfs_put(struct cgroup_fork_state *cfs) {}
+
 static inline int cgroup_init_early(void) { return 0; }
 static inline int cgroup_init(void) { return 0; }
 static inline void cgroup_fork(struct task_struct *p) {}
-static inline void cgroup_post_fork(struct task_struct *p) {}
+static inline int cgroup_can_fork(struct task_struct *p,
+				  struct cgroup_fork_state *cfs)
+{
+	return 0;
+}
+static inline void cgroup_cancel_fork(struct task_struct *p,
+				      struct cgroup_fork_state *cfs) {}
+static inline void cgroup_post_fork(struct task_struct *p,
+				    struct cgroup_fork_state *old_cfs) {}
+
 static inline void cgroup_exit(struct task_struct *p) {}
 
 static inline int cgroupstats_build(struct cgroupstats *stats,
kernel/cgroup.c +154 -9

238 lines not on this page · raw message

kernel/fork.c +33 -5
index cf65139..170ae32 100644
@@ -1196,6 +1196,7 @@ static struct task_struct *copy_process(unsigned long clone_flags,
 {
 	int retval;
 	struct task_struct *p;
+	struct cgroup_fork_state *cfs;
 
 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
 		return ERR_PTR(-EINVAL);
@@ -1322,12 +1323,17 @@ static struct task_struct *copy_process(unsigned long clone_flags,
 	if (clone_flags & CLONE_THREAD)
 		threadgroup_change_begin(current);
 	cgroup_fork(p);
+	cfs = cgroup_cfs_alloc();
+	if (IS_ERR(cfs)) {
+		retval = PTR_ERR(cfs);
+		goto bad_fork_cleanup_threadgroup_lock;
+	}
 #ifdef CONFIG_NUMA
 	p->mempolicy = mpol_dup(p->mempolicy);
 	if (IS_ERR(p->mempolicy)) {
 		retval = PTR_ERR(p->mempolicy);
 		p->mempolicy = NULL;
-		goto bad_fork_cleanup_threadgroup_lock;
+		goto bad_fork_cfs_free;
 	}
 #endif
 #ifdef CONFIG_CPUSETS
@@ -1468,6 +1474,21 @@ static struct task_struct *copy_process(unsigned long clone_flags,
 	INIT_LIST_HEAD(&p->thread_group);
 	p->task_works = NULL;
 
+
+	/*
+	 * Ensure that the cgroup subsystem policies allow the new process to be
+	 * forked. If this fork is happening in an organization operation, then
+	 * this will not charge the correct css_set. This is fixed during
+	 * cgroup_post_fork() (when the css_set has been updated) by undoing
+	 * this operation and forcefully charging the correct css_set.
+	 */
+	rcu_read_lock();
+	cgroup_cfs_get(cfs);
+	rcu_read_unlock();
+	retval = cgroup_can_fork(p, cfs);
+	if (retval)
+		goto bad_fork_put_cfs;
+
 	/*
 	 * Make it visible to the rest of the system, but dont wake it up yet.
 	 * Need tasklist lock for parent etc handling!
@@ -1504,7 +1525,7 @@ static struct task_struct *copy_process(unsigned long clone_flags,
 		spin_unlock(&current->sighand->siglock);
 		write_unlock_irq(&tasklist_lock);
 		retval = -ERESTARTNOINTR;
-		goto bad_fork_free_pid;
+		goto bad_fork_cancel_cgroup;
 	}
 
 	if (likely(p->pid)) {
@@ -1546,7 +1567,9 @@ static struct task_struct *copy_process(unsigned long clone_flags,
 	write_unlock_irq(&tasklist_lock);
 
 	proc_fork_connector(p);
-	cgroup_post_fork(p);
+	cgroup_post_fork(p, cfs);
+	cgroup_cfs_put(cfs);
+	cgroup_cfs_free(cfs);
 	if (clone_flags & CLONE_THREAD)
 		threadgroup_change_end(current);
 	perf_event_fork(p);
@@ -1556,7 +1579,10 @@ static struct task_struct *copy_process(unsigned long clone_flags,
 
 	return p;
 
-bad_fork_free_pid:
+bad_fork_cancel_cgroup:
+	cgroup_cancel_fork(p, cfs);
+bad_fork_put_cfs:
+	cgroup_cfs_put(cfs);
 	if (pid != &init_struct_pid)
 		free_pid(pid);
 bad_fork_cleanup_io:
@@ -1585,8 +1611,10 @@ bad_fork_cleanup_perf:
 bad_fork_cleanup_policy:
 #ifdef CONFIG_NUMA
 	mpol_put(p->mempolicy);
-bad_fork_cleanup_threadgroup_lock:
+bad_fork_cfs_free:
 #endif
+	cgroup_cfs_free(cfs);
+bad_fork_cleanup_threadgroup_lock:
 	if (clone_flags & CLONE_THREAD)
 		threadgroup_change_end(current);
 	delayacct_tsk_free(p);
Signature · 1 line
2.3.4
#4 lore raw

PATCH v7 4/4 cgroups: implement the PIDs subsystem

In reply to Aleksa Sarai

Adds a new single-purpose PIDs subsystem to limit the number of tasks that can be forked inside a cgroup. Essentially this is an implementation of RLIMIT_NPROC that applies to a cgroup rather than a process tree.

However, it should be noted that organisational operations (adding and removing tasks from a PIDs hierarchy) will *not* be prevented. Rather, the number of tasks in the hierarchy cannot exceed the limit through forking. This is due to the fact that, in the unified hierarchy, attach cannot fail (and it is not possible for a task to overcome its PIDs cgroup policy limit by attaching to a child cgroup).

PIDs are fundamentally a global resource, and it is possible to reach PID exhaustion inside a cgroup without hitting any reasonable kmemcg policy. Once you've hit PID exhaustion, you're only in a marginally better state than OOM. This subsystem allows PID exhaustion inside a cgroup to be prevented.

---
 include/linux/cgroup_subsys.h |   4 +
 init/Kconfig                  |  16 +++
 kernel/Makefile               |   1 +
 kernel/cgroup_pids.c          | 310 ++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 331 insertions(+)
 create mode 100644 kernel/cgroup_pids.c
include/linux/cgroup_subsys.h +4 -0
index e4a96fb..a198822 100644
@@ -47,6 +47,10 @@ SUBSYS(net_prio)
 SUBSYS(hugetlb)
 #endif
 
+#if IS_ENABLED(CONFIG_CGROUP_PIDS)
+SUBSYS(pids)
+#endif
+
 /*
  * The following subsystems are not supported on the default hierarchy.
  */
init/Kconfig +16 -0
index f5dbc6d..1f135b7 100644
@@ -952,6 +952,22 @@ config CGROUP_FREEZER
 	  Provides a way to freeze and unfreeze all tasks in a
 	  cgroup.
 
+config CGROUP_PIDS
+	bool "PIDs cgroup subsystem"
+	help
+	  Provides enforcement of process number limits in the scope of a
+	  cgroup. Any attempt to fork more processes than is allowed in the
+	  cgroup will fail. PIDs are fundamentally a global resource because it
+	  is fairly trivial to reach PID exhaustion before you reach even a
+	  conservative kmemcg limit. As a result, it is possible to grind a
+	  system to halt without being limited by other cgroup policies. The
+	  PIDs cgroup subsystem is designed to stop this from happening.
+
+	  It should be noted that organisational operations (such as attaching
+	  to a cgroup hierarchy will *not* be blocked by the PIDs subsystem),
+	  since the PIDs limit only affects a process's ability to fork, not to
+	  attach to a cgroup.
+
 config CGROUP_DEVICE
 	bool "Device controller for cgroups"
 	help
kernel/Makefile +1 -0
index 1408b33..e823592 100644
@@ -53,6 +53,7 @@ obj-$(CONFIG_BACKTRACE_SELF_TEST) += backtracetest.o
 obj-$(CONFIG_COMPAT) += compat.o
 obj-$(CONFIG_CGROUPS) += cgroup.o
 obj-$(CONFIG_CGROUP_FREEZER) += cgroup_freezer.o
+obj-$(CONFIG_CGROUP_PIDS) += cgroup_pids.o
 obj-$(CONFIG_CPUSETS) += cpuset.o
 obj-$(CONFIG_UTS_NS) += utsname.o
 obj-$(CONFIG_USER_NS) += user_namespace.o
kernel/cgroup_pids.c new file +310 -0

310 lines not on this page · raw message

Signature · 1 line
2.3.4
#5 lore raw
In reply to Aleksa Sarai

Hi Tejun,

I decided to send out this version of the patchset (that has the additional callback, and passes around an opaque "fork state" inside the copy_process() callback), because I personally prefer this version of the patchset (it's much cleaner and doesn't mess around with the fork() callback for no good reason). If you *really* want the other one, I can send it.

--
Aleksa Sarai (cyphar)
www.cyphar.com

maintainer
#6 lore raw
Quoted 7 lines · Aleksa Sarai

Hi Tejun,

I decided to send out this version of the patchset (that has the additional callback, and passes around an opaque "fork state" inside the copy_process() callback), because I personally prefer this version of the patchset (it's much cleaner and doesn't mess around with the fork() callback for no good reason). If you *really* want the other one, I can send it.

Yes, please.

Signature · 1 line
tejun