[PATCH v4 03/11] futex: Allow automatic allocation of process wide futex hash.

Sebastian Andrzej Siewior posted 11 patches 1 year ago
There is a newer version of this series
[PATCH v4 03/11] futex: Allow automatic allocation of process wide futex hash.
Posted by Sebastian Andrzej Siewior 1 year ago
Allocate a default futex hash if a task forks its first thread.

Signed-off-by: Sebastian Andrzej Siewior <bigeasy@linutronix.de>
---
 kernel/fork.c | 26 ++++++++++++++++++++++++++
 1 file changed, 26 insertions(+)

diff --git a/kernel/fork.c b/kernel/fork.c
index cda8886f3a1d7..6267d600af991 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -2130,6 +2130,17 @@ static void rv_task_fork(struct task_struct *p)
 #define rv_task_fork(p) do {} while (0)
 #endif
 
+static bool need_futex_hash_allocate_default(u64 clone_flags)
+{
+	if ((clone_flags & (CLONE_THREAD | CLONE_VM)) != (CLONE_THREAD | CLONE_VM))
+		return false;
+	if (!thread_group_empty(current))
+		return false;
+	if (current->mm->futex_hash_bucket)
+		return false;
+	return true;
+}
+
 /*
  * This creates a new process as a copy of the old one,
  * but does not actually start it yet.
@@ -2507,6 +2518,21 @@ __latent_entropy struct task_struct *copy_process(
 	if (retval)
 		goto bad_fork_cancel_cgroup;
 
+	/*
+	 * Allocate a default futex hash for the user process once the first
+	 * thread spawns.
+	 */
+	if (need_futex_hash_allocate_default(clone_flags)) {
+		retval = futex_hash_allocate_default();
+		if (retval)
+			goto bad_fork_core_free;
+		/*
+		 * If we fail beyond this point we don't free the allocated
+		 * futex hash map. We assume that another thread will created
+		 * and makes use of it The hash map will be freed once the main
+		 * thread terminates.
+		 */
+	}
 	/*
 	 * From this point on we must avoid any synchronous user-space
 	 * communication until we take the tasklist-lock. In particular, we do
-- 
2.45.2
Re: [PATCH v4 03/11] futex: Allow automatic allocation of process wide futex hash.
Posted by Thomas Gleixner 1 year ago
On Tue, Dec 03 2024 at 17:42, Sebastian Andrzej Siewior wrote:
> +static bool need_futex_hash_allocate_default(u64 clone_flags)
> +{
> +	if ((clone_flags & (CLONE_THREAD | CLONE_VM)) != (CLONE_THREAD | CLONE_VM))
> +		return false;
> +	if (!thread_group_empty(current))
> +		return false;
> +	if (current->mm->futex_hash_bucket)
> +		return false;

If you add an accessor like:

        if (mm_get_futex_hash_bucket(current->mm))

then you can either #ifdef the futex muck in mm_struct or make it

struct mm_futex_hash_bucket {
#ifdef CONFIG_FUTEX
	unsigned int			futex_hash_mask;
	struct futex_hash_bucket	*futex_hash_bucket;
#endif
};

and avoid the #ifdeffery in mm_struct itself because the empty struct
occupies zero space.

The accessor and the other helpers allow the the compiler to optimize
all of it out for CONFIG_FUTEX=n.

Thanks,

        tglx