Skip to contentSkip to conversation

sched: Fix performance regression introduced by mm_cid

RFC PATCH Superseded Mathieu Desnoyers 3 participants 7 messages Apr 13, 2023 – Apr 14, 2023

Subsystems (3)

v5 of 10 Superseded Latest is v10 →

lore
Share & tools
lore
#0 lore raw

RFC PATCH v5 1/1 sched: Fix performance regression introduced by mm_cid

Introduce per-mm/cpu current concurrency id (mm_cid) to fix a PostgreSQL sysbench regression reported by Aaron Lu.

Keep track of the currently allocated mm_cid for each mm/cpu rather than freeing them immediately on context switch. This eliminates most atomic operations when context switching back and forth between threads belonging to different memory spaces in multi-threaded scenarios (many processes, each with many threads). The per-mm/per-cpu mm_cid values are serialized by their respective runqueue locks.

Thread migration is handled by introducing invocation to sched_mm_cid_migrate_from() in set_task_cpu() and to sched_mm_cid_migrate_to() (with destination runqueue lock held) in activate_task() for migrating tasks. set_task_cpu() is invoked with and without source rq lock held: the wakeup path does not hold the source rq lock.

sched_mm_cid_migrate_from() clears the mm_cid from the task's mm per-cpu index corresponding to the source runqueue if it matches the last mm_cid observed by the migrated task. This last mm_cid value is returned as a hint to conditionally clear the mm's per-cpu mm_cid on the destination cpu.

Then, in sched_mm_cid_migrate_to(), if the last mm_cid is smaller than the mm's destination cpu current mm_cid, clear the mm's destination cpu current mm_cid. If the migrated task's mm is in use on the destination cpu, the reclaim of the mm_cid will be done lazily on the next destination cpu context switch, else it is performed immediately.

The source cpu's mm_cid is _not_ simply moved to the destination cpu on migration, because passing ownership of the mm_cid value to the destination cpu while an actively running tasks also has its own mm_cid value (in case of lazy reclaim on next context switch) would over-allocate mm_cid values beyond the number of possible cpus.

Because we want to ensure the mm_cid converges towards the smaller values as migrations happen, the prior optimization that was done when context switching between threads belonging to the same mm is removed, because it could delay the lazy release of the destination runqueue mm_cid after it has been replaced by a migration. Removing this prior optimization is not an issue performance-wise because the introduced per-mm/per-cpu mm_cid tracking also covers this more specific case.

This patch is based on v6.3-rc6 with this patch applied:

("mm: Fix memory leak on mm_init error handling")

https://lore.kernel.org/lkml/[email protected]/

Fixes af7f588d8f73 ("sched: Introduce per-memory-map concurrency ID")
Cc Aaron Lu <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Olivier Dion <[email protected]>

---
Changes since v4:
- Retry on filled mm_cid mask,
- Disable interrupts during ownership of cid in migrate-from without rq lock,
- Implement lock-free cid-get, using spinlock only to guarantee forward progress when contention is detected.
- Use try_cmpxchg where appropriate.

Changes since v3:
- Rebase on v6.3-rc6,
- Move switch_mm_cid() from prepare_task_switch() to context_switch() after the switch_to() barrier,
- Adding missing barriers at the beginning of switch_mm_cid(),
- Document the lock-free migrate-from algorithm.
- Add memory barriers in sched_mm_cid_exit_signals(), sched_mm_cid_before_execve(), and sched_mm_cid_after_execve() to order t->mm_cid_active store, per-mm/cpu cid load wrt migrate-from per-mm-cid cid cmpxchg, t->mm_cid_active load.

---
 include/linux/mm_types.h |  65 ++++++-
 include/linux/sched.h    |   1 +
 include/linux/sched/mm.h |   5 +
 kernel/fork.c            |   8 +-
 kernel/sched/core.c      | 382 +++++++++++++++++++++++++++++++++++++--
 kernel/sched/sched.h     | 205 ++++++++++++++++++---
 6 files changed, 610 insertions(+), 56 deletions(-)
include/linux/mm_types.h +57 -8
index a57e6ae78e65..1dbfe0bbbb1c 100644
@@ -600,15 +600,13 @@ struct mm_struct {
 		atomic_t mm_count;
 #ifdef CONFIG_SCHED_MM_CID
 		/**
-		 * @cid_lock: Protect cid bitmap updates vs lookups.
+		 * @pcpu_cid: Per-cpu current cid.
 		 *
-		 * Prevent situations where updates to the cid bitmap happen
-		 * concurrently with lookups. Those can lead to situations
-		 * where a lookup cannot find a free bit simply because it was
-		 * unlucky enough to load, non-atomically, bitmap words as they
-		 * were being concurrently updated by the updaters.
+		 * Keep track of the currently allocated mm_cid for each cpu.
+		 * The per-cpu mm_cid values are serialized by their respective
+		 * runqueue locks.
 		 */
-		raw_spinlock_t cid_lock;
+		int __percpu *pcpu_cid;
 #endif
 #ifdef CONFIG_MMU
 		atomic_long_t pgtables_bytes;	/* size of all page tables */
@@ -873,6 +871,37 @@ static inline void vma_iter_init(struct vma_iterator *vmi,
 }
 
 #ifdef CONFIG_SCHED_MM_CID
+
+enum mm_cid_state {
+	MM_CID_UNSET = -1U,		/* Unset state has lazy_put flag set. */
+	MM_CID_LAZY_PUT = (1U << 31),
+};
+
+static inline bool mm_cid_is_unset(int cid)
+{
+	return cid == MM_CID_UNSET;
+}
+
+static inline bool mm_cid_is_lazy_put(int cid)
+{
+	return !mm_cid_is_unset(cid) && (cid & MM_CID_LAZY_PUT);
+}
+
+static inline bool mm_cid_is_valid(int cid)
+{
+	return !(cid & MM_CID_LAZY_PUT);
+}
+
+static inline int mm_cid_set_lazy_put(int cid)
+{
+	return cid | MM_CID_LAZY_PUT;
+}
+
+static inline int mm_cid_clear_lazy_put(int cid)
+{
+	return cid & ~MM_CID_LAZY_PUT;
+}
+
 /* Accessor for struct mm_struct's cidmask. */
 static inline cpumask_t *mm_cidmask(struct mm_struct *mm)
 {
@@ -886,16 +915,36 @@ static inline cpumask_t *mm_cidmask(struct mm_struct *mm)
 
 static inline void mm_init_cid(struct mm_struct *mm)
 {
-	raw_spin_lock_init(&mm->cid_lock);
+	int i;
+
+	for_each_possible_cpu(i)
+		*per_cpu_ptr(mm->pcpu_cid, i) = MM_CID_UNSET;
 	cpumask_clear(mm_cidmask(mm));
 }
 
+static inline int mm_alloc_cid(struct mm_struct *mm)
+{
+	mm->pcpu_cid = alloc_percpu(int);
+	if (!mm->pcpu_cid)
+		return -ENOMEM;
+	mm_init_cid(mm);
+	return 0;
+}
+
+static inline void mm_destroy_cid(struct mm_struct *mm)
+{
+	free_percpu(mm->pcpu_cid);
+	mm->pcpu_cid = NULL;
+}
+
 static inline unsigned int mm_cid_size(void)
 {
 	return cpumask_size();
 }
 #else /* CONFIG_SCHED_MM_CID */
 static inline void mm_init_cid(struct mm_struct *mm) { }
+static inline int mm_alloc_cid(struct mm_struct *mm) { return 0; }
+static inline void mm_destroy_cid(struct mm_struct *mm) { }
 static inline unsigned int mm_cid_size(void)
 {
 	return 0;
include/linux/sched.h +1 -0
index 63d242164b1a..48d48b2c73a5 100644
@@ -1313,6 +1313,7 @@ struct task_struct {
 
 #ifdef CONFIG_SCHED_MM_CID
 	int				mm_cid;		/* Current cid in mm */
+	int				last_mm_cid;	/* Most recent cid in mm */
 	int				mm_cid_active;	/* Whether cid bitmap is active */
 #endif
 
include/linux/sched/mm.h +5 -0
index 2a243616f222..f20fc0600fcc 100644
@@ -37,6 +37,11 @@ static inline void mmgrab(struct mm_struct *mm)
 	atomic_inc(&mm->mm_count);
 }
 
+static inline void smp_mb__after_mmgrab(void)
+{
+	smp_mb__after_atomic();
+}
+
 extern void __mmdrop(struct mm_struct *mm);
 
 static inline void mmdrop(struct mm_struct *mm)
kernel/fork.c +7 -1
index ea332319dffe..3832bea713c4 100644
@@ -793,6 +793,7 @@ void __mmdrop(struct mm_struct *mm)
 	check_mm(mm);
 	put_user_ns(mm->user_ns);
 	mm_pasid_drop(mm);
+	mm_destroy_cid(mm);
 
 	for (i = 0; i < NR_MM_COUNTERS; i++)
 		percpu_counter_destroy(&mm->rss_stat[i]);
@@ -1057,6 +1058,7 @@ static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
 
 #ifdef CONFIG_SCHED_MM_CID
 	tsk->mm_cid = -1;
+	tsk->last_mm_cid = -1;
 	tsk->mm_cid_active = 0;
 #endif
 	return tsk;
@@ -1162,18 +1164,22 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
 	if (init_new_context(p, mm))
 		goto fail_nocontext;
 
+	if (mm_alloc_cid(mm))
+		goto fail_cid;
+
 	for (i = 0; i < NR_MM_COUNTERS; i++)
 		if (percpu_counter_init(&mm->rss_stat[i], 0, GFP_KERNEL_ACCOUNT))
 			goto fail_pcpu;
 
 	mm->user_ns = get_user_ns(user_ns);
 	lru_gen_init_mm(mm);
-	mm_init_cid(mm);
 	return mm;
 
 fail_pcpu:
 	while (i > 0)
 		percpu_counter_destroy(&mm->rss_stat[--i]);
+	mm_destroy_cid(mm);
+fail_cid:
 	destroy_context(mm);
 fail_nocontext:
 	mm_free_pgd(mm);
kernel/sched/core.c +365 -17

447 lines not on this page · raw message

kernel/sched/sched.h +175 -30

236 lines not on this page · raw message

Signature · 1 line
2.25.1
#1 lore raw
Quoted 2 lines · Mathieu Desnoyers

Introduce per-mm/cpu current concurrency id (mm_cid) to fix a PostgreSQL sysbench regression reported by Aaron Lu.

Initial test using postgres_sysbench showed the lock contention is gone :-) Will check how it affects hackbench tomorrow.

#2 lore raw
Quoted 6 lines · Aaron Lu
Quoted 2 lines · Mathieu Desnoyers

Introduce per-mm/cpu current concurrency id (mm_cid) to fix a PostgreSQL sysbench regression reported by Aaron Lu.

Initial test using postgres_sysbench showed the lock contention is gone :-) Will check how it affects hackbench tomorrow.

That's good news! Not unexpected though.

One thing to look closely at is whether it's just that the qspinlocks are gone from the profiles but replaced by time spent in __mm_cid_get() due to cache-line bouncing of find-first-zero/test-and-set on the per-mm cid bitmap.

But if both are really gone from the profiles, then it's really good news.

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
#3 lore raw
Quoted 7 lines · Mathieu Desnoyers
Quoted 5 lines · Aaron Lu
Quoted 2 lines · Mathieu Desnoyers

Introduce per-mm/cpu current concurrency id (mm_cid) to fix a PostgreSQL sysbench regression reported by Aaron Lu.

Initial test using postgres_sysbench showed the lock contention is gone :-) Will check how it affects hackbench tomorrow.

Quoted 6 lines

That's good news! Not unexpected though.

One thing to look closely at is whether it's just that the qspinlocks are gone from the profiles but replaced by time spent in __mm_cid_get() due to cache-line bouncing of find-first-zero/test-and-set on the per-mm cid bitmap.

Found the below two appeared in profile when using cid as keyword, full profile attached for your reference.

# Children      Self  Shared Object    Symbol
     0.97%     0.62%  [kernel.vmlinux] [k] sched_mm_cid_migrate_from
     0.48%     0.47%  [kernel.vmlinux] [k] mm_cid_get

Thanks,
Aaron

#4 lore raw
In reply to Aaron Lu
Quoted 6 lines · Aaron Lu
Quoted 2 lines · Mathieu Desnoyers

Introduce per-mm/cpu current concurrency id (mm_cid) to fix a PostgreSQL sysbench regression reported by Aaron Lu.

Initial test using postgres_sysbench showed the lock contention is gone :-) Will check how it affects hackbench tomorrow.

For hackbench on SPR, there is also almost no lock contention from scheduler path. For cid related function, there are:

# Children      Self  Shared Object       Symbol
     7.10%     7.09%  [kernel.vmlinux]    [k] mm_cid_get
     3.62%     3.53%  [kernel.vmlinux]    [k] sched_mm_cid_migrate_from

Full profile attached for your reference.

maintainer
#5 lore raw
In reply to Mathieu Desnoyers
Quoted 37 lines · Mathieu Desnoyers
kernel/sched/sched.h +37 -0
+static inline void __mm_cid_put(struct mm_struct *mm, int cid)
+{
+	if (cid < 0)
+		return;
+	cpumask_clear_cpu(cid, mm_cidmask(mm));
+}
+
+/*
+ * The per-mm/cpu cid can have the MM_CID_LAZY_PUT flag set or transition to the
+ * MM_CID_UNSET state without holding the rq lock, but the rq lock needs to be
+ * held to transition to other states.
+ */
+static inline void mm_cid_put_lazy(struct task_struct *t)
+{
+	struct mm_struct *mm = t->mm;
+	int *pcpu_cid, cid;
+
+	lockdep_assert_rq_held(this_rq());
+	pcpu_cid = this_cpu_ptr(mm->pcpu_cid);
+	cid = READ_ONCE(*pcpu_cid);
+	if (!mm_cid_is_lazy_put(cid))
+		return;
+	if (!try_cmpxchg(pcpu_cid, &cid, MM_CID_UNSET))
+		return;
+	__mm_cid_put(mm, mm_cid_clear_lazy_put(cid));
+}
+
+static inline void mm_cid_put(struct task_struct *t)
+{
+	struct mm_struct *mm = t->mm;
+	int *pcpu_cid, cid, res;
+
+	lockdep_assert_rq_held(this_rq());
+	WARN_ON_ONCE(t->mm_cid < 0);
+	pcpu_cid = this_cpu_ptr(mm->pcpu_cid);
+	cid = READ_ONCE(*pcpu_cid);
+	for (;;) {

kernel/sched/sched.h static inline void update_current_exec_runtime(struct task_struct *curr, · line 3305

Quoted 10 lines
kernel/sched/sched.h +10 -0
+		if (mm_cid_is_unset(cid))
+			return;
+		WARN_ON_ONCE(mm_cid_clear_lazy_put(cid) != t->mm_cid);
+		/*
+		 * Attempt transition from valid or lazy-put to unset.
+		 */
+		res = cmpxchg(pcpu_cid, cid, MM_CID_UNSET);
+		if (res == cid)
+			break;
+		cid = res;
		if (try_cmpxchg(pcpu_cid, &cid, MM_CID_UNSET))
			break;
Quoted 11 lines
kernel/sched/sched.h +5 -0
+	}
 
 
 
+	__mm_cid_put(mm, mm_cid_clear_lazy_put(cid));
+}
+
+static inline int __mm_cid_try_get(struct mm_struct *mm)
 {
 	struct cpumask *cpumask;
 	int cid;

kernel/sched/sched.h static inline void update_current_exec_runtime(struct task_struct *curr, · line 3323

Quoted 10 lines
kernel/sched/sched.h +8 -0
 
 	cpumask = mm_cidmask(mm);
+	/*
+	 * Retry finding first zero bit if the mask is temporarily
+	 * filled. This only happens during concurrent migrate-from
+	 * which owns a cid without holding a rq lock.
+	 */
+	do {
+		cid = cpumask_first_zero(cpumask);
+	} while (cid >= nr_cpu_ids);

Urgh..

	for (;;) {
		cid = cpumask_first_zero(cpumask);
		if (cid < nr_cpu_ids)
			break;
		cpu_relax();
	}
Quoted 5 lines
kernel/sched/sched.h +5 -0
+	if (!cpumask_test_and_set_cpu(cid, cpumask))
+		return cid;
+	/*
+	 * If initial find-then-test-and-set fails due to concurrent updates,
+	 * attempt a brute-force test-and-set from 0 to nr_cpu_ids-1 to

kernel/sched/sched.h static inline void update_current_exec_runtime(struct task_struct *curr, · line 3338

Quoted 10 lines
kernel/sched/sched.h +10 -0
+	 * eliminate the race between find and test-and-set. This does not
+	 * strictly provide forward-progress guarantees, because we could
+	 * theoretically be racing against concurrent updates of the mask, but
+	 * it does have much better odds to succeed in contended cases than
+	 * the find-then-test-and-set approach.
+	 */
+	for (cid = 0; cid < nr_cpu_ids; cid++) {
+		if (!cpumask_test_and_set_cpu(cid, cpumask))
+			return cid;
+	}

Yikes, we have IRQs disabled and hold rq->lock, this is a very expensive proposition. Also, afaict all *should* just work without this on.

kernel/sched/sched.h static inline void update_current_exec_runtime(struct task_struct *curr, · line 3346

Quoted 8 lines
kernel/sched/sched.h +5 -0
+	return -1;
 }
 
+static inline int __mm_cid_get(struct mm_struct *mm)
 {
+	int cid;
+
+	if (!READ_ONCE(use_cid_lock)) {

This all hurts my brain, but shouldn't you be able to replace use_cid_lock with raw_spin_is_locked(&cid_lock) ?

Quoted 30 lines
kernel/sched/sched.h +30 -0
+		cid = __mm_cid_try_get(mm);
+		if (cid >= 0)
+			goto end;
+		raw_spin_lock(&cid_lock);
+	} else {
+		raw_spin_lock(&cid_lock);
+		cid = __mm_cid_try_get(mm);
+		if (cid >= 0)
+			goto unlock;
+	}
+
+	/*
+	 * cid concurrently allocated. Retry while forcing following
+	 * allocations to use the cid_lock to ensure forward progress.
+	 */
+	WRITE_ONCE(use_cid_lock, 1);
+	/*
+	 * Set use_cid_lock before allocation. Only care about program order
+	 * because this is for forward progress.
+	 */
+	barrier();
+	/*
+	 * Retry until it succeeds. It is guaranteed to eventually
+	 * succeed once all newcoming allocations observe the
+	 * use_cid_lock flag set.
+	 */
+	do {
+		cid = __mm_cid_try_get(mm);
+	} while (cid < 0);
+	/*

kernel/sched/sched.h static inline void update_current_exec_runtime(struct task_struct *curr, · line 3386

Quoted 10 lines
kernel/sched/sched.h +9 -0
+	 * Allocate before clearing use_cid_lock. Only care about
+	 * program order because this is for forward progress.
+	 */
+	barrier();
+	WRITE_ONCE(use_cid_lock, 0);
+unlock:
+	raw_spin_unlock(&cid_lock);
+end:
+	return cid;
 }

Anyway, I ran the thing and __schedule()'s dropped from around 11% to 5%

4.98% 0.04% swapper [kernel.vmlinux] [k] schedule_idle

       |
       --4.95%--schedule_idle
                |
                --4.94%--__schedule
                         |
                         |--2.36%--mm_cid_get
                         |
                         |--0.72%--finish_task_switch.isra.0
                         |          |
                         |           --0.61%--asm_sysvec_call_function_single
                         |                     |
                         |                      --0.51%--sysvec_call_function_single
                         |
                         --0.59%--switch_mm_irqs_off

So improved, but not as good as my glorious hack ;-)

Also, I see that even migrate_from is visible

5.26% 0.74% sched-messaging [kernel.vmlinux] [k] try_to_wake_up

       |
       |--4.52%--try_to_wake_up
       |          |
       |          |--1.49%--set_task_cpu
       |          |          |
       |          |           --1.18%--sched_mm_cid_migrate_from
       |          |
       |          |--1.24%--select_task_rq_fair
       |          |
       |          |--0.73%--ttwu_do_activate
       |          |          |
       |          |           --0.57%--enqueue_task_fair
       |          |
       |           --0.50%--ttwu_queue_wakelist
       |
       --0.74%--start_thread
#6 lore raw
Quoted 44 lines · Peter Zijlstra
Quoted 42 lines · Mathieu Desnoyers
kernel/sched/sched.h +42 -0
+static inline void __mm_cid_put(struct mm_struct *mm, int cid)
+{
+	if (cid < 0)
+		return;
+	cpumask_clear_cpu(cid, mm_cidmask(mm));
+}
+
+/*
+ * The per-mm/cpu cid can have the MM_CID_LAZY_PUT flag set or transition to the
+ * MM_CID_UNSET state without holding the rq lock, but the rq lock needs to be
+ * held to transition to other states.
+ */
+static inline void mm_cid_put_lazy(struct task_struct *t)
+{
+	struct mm_struct *mm = t->mm;
+	int *pcpu_cid, cid;
+
+	lockdep_assert_rq_held(this_rq());
+	pcpu_cid = this_cpu_ptr(mm->pcpu_cid);
+	cid = READ_ONCE(*pcpu_cid);
+	if (!mm_cid_is_lazy_put(cid))
+		return;
+	if (!try_cmpxchg(pcpu_cid, &cid, MM_CID_UNSET))
+		return;
+	__mm_cid_put(mm, mm_cid_clear_lazy_put(cid));
+}
+
+static inline void mm_cid_put(struct task_struct *t)
+{
+	struct mm_struct *mm = t->mm;
+	int *pcpu_cid, cid, res;
+
+	lockdep_assert_rq_held(this_rq());
+	WARN_ON_ONCE(t->mm_cid < 0);
+	pcpu_cid = this_cpu_ptr(mm->pcpu_cid);
+	cid = READ_ONCE(*pcpu_cid);
+	for (;;) {
+		if (mm_cid_is_unset(cid))
+			return;
+		WARN_ON_ONCE(mm_cid_clear_lazy_put(cid) != t->mm_cid);
+		/*
+		 * Attempt transition from valid or lazy-put to unset.
Quoted 8 lines

kernel/sched/sched.h static inline void update_current_exec_runtime(struct task_struct *curr, · line 3305

Quoted 5 lines
kernel/sched/sched.h +5 -0
+		 */
+		res = cmpxchg(pcpu_cid, cid, MM_CID_UNSET);
+		if (res == cid)
+			break;
+		cid = res;
		if (try_cmpxchg(pcpu_cid, &cid, MM_CID_UNSET))
			break;

I left this as a cmpxchg on purpose: it acts as a read for the next loop. Or is it better to move the "cid = READ_ONCE(*pcpu_cid);" at the beginning of the loop and use try_cmpxchg ?

Quoted 24 lines
Quoted 12 lines
kernel/sched/sched.h +5 -0
+	}
 
 
 
+	__mm_cid_put(mm, mm_cid_clear_lazy_put(cid));
+}
+
+static inline int __mm_cid_try_get(struct mm_struct *mm)
  {
  	struct cpumask *cpumask;
  	int cid;

kernel/sched/sched.h static inline void update_current_exec_runtime(struct task_struct *curr, · line 3323

Quoted 10 lines
kernel/sched/sched.h +8 -0
 
  	cpumask = mm_cidmask(mm);
+	/*
+	 * Retry finding first zero bit if the mask is temporarily
+	 * filled. This only happens during concurrent migrate-from
+	 * which owns a cid without holding a rq lock.
+	 */
+	do {
+		cid = cpumask_first_zero(cpumask);
+	} while (cid >= nr_cpu_ids);

Urgh..

Quoted 6 lines
	for (;;) {
		cid = cpumask_first_zero(cpumask);
		if (cid < nr_cpu_ids)
			break;
		cpu_relax();
	}

OK

Quoted 12 lines
Quoted 12 lines
kernel/sched/sched.h +10 -0
+	if (!cpumask_test_and_set_cpu(cid, cpumask))
+		return cid;
+	/*
+	 * If initial find-then-test-and-set fails due to concurrent updates,
+	 * attempt a brute-force test-and-set from 0 to nr_cpu_ids-1 to
+	 * eliminate the race between find and test-and-set. This does not
+	 * strictly provide forward-progress guarantees, because we could
+	 * theoretically be racing against concurrent updates of the mask, but
+	 * it does have much better odds to succeed in contended cases than
+	 * the find-then-test-and-set approach.
Quoted 8 lines

kernel/sched/sched.h static inline void update_current_exec_runtime(struct task_struct *curr, · line 3338

Quoted 5 lines
kernel/sched/sched.h +5 -0
+	 */
+	for (cid = 0; cid < nr_cpu_ids; cid++) {
+		if (!cpumask_test_and_set_cpu(cid, cpumask))
+			return cid;
+	}

Yikes, we have IRQs disabled and hold rq->lock, this is a very expensive proposition. Also, afaict all *should* just work without this on.

Yes, I'll remove this.

Quoted 4 lines
Quoted 4 lines
kernel/sched/sched.h +1 -0
+	return -1;
  }
Quoted 8 lines

kernel/sched/sched.h static inline void update_current_exec_runtime(struct task_struct *curr, · line 3346

Quoted 5 lines
kernel/sched/sched.h +4 -0
+static inline int __mm_cid_get(struct mm_struct *mm)
  {
+	int cid;
+
+	if (!READ_ONCE(use_cid_lock)) {

This all hurts my brain, but shouldn't you be able to replace use_cid_lock with raw_spin_is_locked(&cid_lock) ?

No, because we only want the thread which observed the find/test-and-set race to set the use_cid_lock bit. We don't want all other threads which end up using the lock because they see use_cid_lock set to also themselves cause other threads to use the lock. This could cause a scenario where we always keep using the lock and never revert back to lock-free in a very contended case.

Quoted 36 lines
Quoted 36 lines
kernel/sched/sched.h +35 -0
+		cid = __mm_cid_try_get(mm);
+		if (cid >= 0)
+			goto end;
+		raw_spin_lock(&cid_lock);
+	} else {
+		raw_spin_lock(&cid_lock);
+		cid = __mm_cid_try_get(mm);
+		if (cid >= 0)
+			goto unlock;
+	}
+
+	/*
+	 * cid concurrently allocated. Retry while forcing following
+	 * allocations to use the cid_lock to ensure forward progress.
+	 */
+	WRITE_ONCE(use_cid_lock, 1);
+	/*
+	 * Set use_cid_lock before allocation. Only care about program order
+	 * because this is for forward progress.
+	 */
+	barrier();
+	/*
+	 * Retry until it succeeds. It is guaranteed to eventually
+	 * succeed once all newcoming allocations observe the
+	 * use_cid_lock flag set.
+	 */
+	do {
+		cid = __mm_cid_try_get(mm);
+	} while (cid < 0);
+	/*
+	 * Allocate before clearing use_cid_lock. Only care about
+	 * program order because this is for forward progress.
+	 */
+	barrier();
+	WRITE_ONCE(use_cid_lock, 0);
Quoted 8 lines

kernel/sched/sched.h static inline void update_current_exec_runtime(struct task_struct *curr, · line 3386

Quoted 5 lines
kernel/sched/sched.h +4 -0
+unlock:
+	raw_spin_unlock(&cid_lock);
+end:
+	return cid;
  }

Anyway, I ran the thing and __schedule()'s dropped from around 11% to 5%

That's a good start!

Quoted 17 lines

4.98% 0.04% swapper [kernel.vmlinux] [k] schedule_idle

        |
        --4.95%--schedule_idle
                 |
                 --4.94%--__schedule
                          |
                          |--2.36%--mm_cid_get
                          |
                          |--0.72%--finish_task_switch.isra.0
                          |          |
                          |           --0.61%--asm_sysvec_call_function_single
                          |                     |
                          |                      --0.51%--sysvec_call_function_single
                          |
                          --0.59%--switch_mm_irqs_off
Quoted 1 line

So improved, but not as good as my glorious hack ;-)

Yeah, we still need to touch the bitmap and suffer from cache line bouncing.

Quoted 4 lines

Also, I see that even migrate_from is visible

5.26% 0.74% sched-messaging [kernel.vmlinux] [k] try_to_wake_up

Quoted 16 lines
        |
        |--4.52%--try_to_wake_up
        |          |
        |          |--1.49%--set_task_cpu
        |          |          |
        |          |           --1.18%--sched_mm_cid_migrate_from
        |          |
        |          |--1.24%--select_task_rq_fair
        |          |
        |          |--0.73%--ttwu_do_activate
        |          |          |
        |          |           --0.57%--enqueue_task_fair
        |          |
        |           --0.50%--ttwu_queue_wakelist
        |
        --0.74%--start_thread

One tradeoff we can consider is that we could afford to delay compaction of cids to much later. One way to achieve this would be to update a timestamp along with each per-mm/cpu cid value keeping track of its last use on context switch. Then we could implement a worker thread which would periodically iterate over all mm and figure out if it needs to compact things because per-mm/cpu cids were unused for too long.

Thoughts ?

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com