Skip to contentSkip to conversation

sched: Fix: Handle target_cpu offlining in active_load_balance_cpu_stop

RFC PATCH In review Mathieu Desnoyers 2 participants 12 messages Apr 19, 2023 – Apr 20, 2023

Subsystems (3)
lore
Share & tools
lore
#0 lore raw

RFC PATCH v9 1/2 sched: Fix: Handle target_cpu offlining in active_load_balance_cpu_stop

Handle scenario where the target cpu is going offline concurrently with execution of active_load_balance_cpu_stop, which can cause __sched_core_flip to flip rq->core_enabled without rq lock held, which can trigger lockdep_assert_rq_held() warnings.

This scenario possibly has other unwanted effects such as migrating tasks to offline cpus, which may prevent their execution for a long time until the cpu is brought back online.

---
 kernel/sched/fair.c | 34 ++++++++++++++++++++++++++++++++--
 1 file changed, 32 insertions(+), 2 deletions(-)
kernel/sched/fair.c +32 -2
index 5f6587d94c1d..1c837ba41704 100644
@@ -8744,6 +8744,27 @@ static void attach_one_task(struct rq *rq, struct task_struct *p)
 	rq_unlock(rq, &rf);
 }
 
+/*
+ * try_attach_one_task() -- attaches the task returned from detach_one_task() to
+ * its new rq if the rq is online. Returns false if the rq is not online.
+ */
+static bool try_attach_one_task(struct rq *rq, struct task_struct *p)
+{
+	struct rq_flags rf;
+	bool result = true;
+
+	rq_lock(rq, &rf);
+	if (!rq->online) {
+		result = false;
+		goto unlock;
+	}
+	update_rq_clock(rq);
+	attach_task(rq, p);
+unlock:
+	rq_unlock(rq, &rf);
+	return result;
+}
+
 /*
  * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
  * new rq.
@@ -11048,8 +11069,17 @@ static int active_load_balance_cpu_stop(void *data)
 	busiest_rq->active_balance = 0;
 	rq_unlock(busiest_rq, &rf);
 
-	if (p)
-		attach_one_task(target_rq, p);
+	if (p) {
+		if (!try_attach_one_task(target_rq, p)) {
+			/*
+			 * target_rq was offlined concurrently. There is no
+			 * guarantee that the busiest cpu is still online at
+			 * this point. Fallback on using the CPU on which the
+			 * stopper thread is running as target.
+			 */
+			attach_one_task(this_rq(), p);
+		}
+	}
 
 	local_irq_enable();
 
Signature · 1 line
2.25.1
#1 lore raw

RFC PATCH v9 2/2 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_to() (with destination runqueue lock held) in activate_task() for migrating tasks. If the destination cpu's mm_cid is unset, and if the source runqueue is not actively using its mm_cid, then the source cpu's mm_cid is moved to the destination cpu on migration.

Introduce a task-work executed periodically, similarly to NUMA work, which delays reclaim of cid values when they are unused for a period of time.

Keep track of the allocation time for each per-cpu cid, and let the task work clear them when they are observed to be older than SCHED_MM_CID_PERIOD_NS and unused. This task work also clears all mm_cids which are greater or equal to the Hamming weight of the mm cidmask to keep concurrency ids compact.

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-rc7 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 v8:
- In order to take care of infrequently scheduled tasks, bump the time snapshot associated with old cids if an active task using the mm is observed on their associated rq.
- Eliminate this_cpu_ptr() overhead on fast-paths by using __this_cpu_read() and __this_cpu_write().
- Eliminate duplicated this_cpu_ptr() by handing the resulting pointer as argument to the callees in sched_mm_cid_migrate_to and sched_mm_cid_remote_clear.

Changes since v7:
- Call sched_mm_cid_migrate_to() for try-to-wake-up migrations as well,
- Remove next_scan bogus variable which shadows actual initialized variable. Fixed issue reported by kernel test robot,
- Clear the src_cid in sched_mm_cid_migrate_to() in situations where the dst_cid is already set to prevent over-allocation of cids in frequent migration scenarios when atomic_read(&mm->mm_users) < t->nr_cpus_allowed.
- Rebase on v6.3-rc7.

Changes since v6:
- Reintroduce migrate-to hook to hand-off cid from source to destination runqueue. This ensures that a single-threaded process always observes mm_cid==0 when migrating across CPUs.
- Ensure compactness of mm_cid in task-work by clearing mm_cid per-cpu entries that are above the Hamming weight of the mm cidmask.

Changes since v5:
- Introduce task-work and delay-based reclaim.

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 |  82 +++++-
 include/linux/sched.h    |   3 +
 include/linux/sched/mm.h |   5 +
 kernel/fork.c            |   9 +-
 kernel/sched/core.c      | 524 +++++++++++++++++++++++++++++++++++++--
 kernel/sched/sched.h     | 235 +++++++++++++++---
 6 files changed, 803 insertions(+), 55 deletions(-)
include/linux/mm_types.h +74 -8
index a57e6ae78e65..5eab61156f0e 100644
@@ -550,6 +550,13 @@ struct vm_area_struct {
 	struct vm_userfaultfd_ctx vm_userfaultfd_ctx;
 } __randomize_layout;
 
+#ifdef CONFIG_SCHED_MM_CID
+struct mm_cid {
+	u64 time;
+	int cid;
+};
+#endif
+
 struct kioctx_table;
 struct mm_struct {
 	struct {
@@ -600,15 +607,19 @@ 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;
+		struct mm_cid __percpu *pcpu_cid;
+		/*
+		 * @mm_cid_next_scan: Next mm_cid scan (in jiffies).
+		 *
+		 * When the next mm_cid scan is due (in jiffies).
+		 */
+		unsigned long mm_cid_next_scan;
 #endif
 #ifdef CONFIG_MMU
 		atomic_long_t pgtables_bytes;	/* size of all page tables */
@@ -873,6 +884,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 +928,40 @@ 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) {
+		struct mm_cid *pcpu_cid = per_cpu_ptr(mm->pcpu_cid, i);
+
+		pcpu_cid->cid = MM_CID_UNSET;
+		pcpu_cid->time = 0;
+	}
 	cpumask_clear(mm_cidmask(mm));
 }
 
+static inline int mm_alloc_cid(struct mm_struct *mm)
+{
+	mm->pcpu_cid = alloc_percpu(struct mm_cid);
+	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 +3 -0
index 63d242164b1a..41c24f406fcf 100644
@@ -1313,7 +1313,10 @@ 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				migrate_from_cpu;
 	int				mm_cid_active;	/* Whether cid bitmap is active */
+	struct callback_head		cid_work;
 #endif
 
 	struct tlbflush_unmap_batch	tlb_ubc;
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 +8 -1
index ea332319dffe..ff198be38a11 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,7 +1058,9 @@ 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;
+	tsk->migrate_from_cpu = -1;
 #endif
 	return tsk;
 
@@ -1162,18 +1165,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 +507 -17

595 lines not on this page · raw message

kernel/sched/sched.h +206 -29

267 lines not on this page · raw message

Signature · 1 line
2.25.1
#2 lore raw

Re: [RFC PATCH v9 2/2] sched: Fix performance regression introduced by mm_cid

Quoted 2 lines · Mathieu Desnoyers

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

mm_cid_get() dropped to 5.x% after I disable CONFIG_DEBUG_PREEMPT, using __this_cpu_X() doesn't help, I suppose that is because __this_cpu_X() still needs to fetch mm->pcpu_cid.

Annotate mm_cid_get():

       │     static inline int mm_cid_get(struct mm_struct *mm)
       │     {
  0.05 │       push   %rbp
  0.02 │       mov    %rsp,%rbp
       │       push   %r15
       │       push   %r14
       │       push   %r13
       │       push   %r12
       │       push   %rbx
  0.02 │       sub    $0x10,%rsp
       │     struct mm_cid __percpu *pcpu_cid = mm->pcpu_cid;
 71.30 │       mov    0x60(%rdi),%r12
       │     struct cpumask *cpumask;
       │     int cid;
       │
       │     lockdep_assert_rq_held(rq);
       │     cpumask = mm_cidmask(mm);
       │     cid = __this_cpu_read(pcpu_cid->cid);
 28.44 │       mov    %gs:0x8(%r12),%edx
       │     if (mm_cid_is_valid(cid)) {

sched_mm_cid_migrate_to() is 4.x% and its annotation :

       │     dst_pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu_of(dst_rq));
       │       mov     -0x30(%rbp),%rax
 54.53 │       mov     0x60(%r13),%rbx
 19.61 │       movslq  0xaf0(%rax),%r15

The reason why accessing mm->pcpu_cid is so costly is still a myth to me...

BTW, I used below diff to mitigate the incorrect rq lock issue I described in my reply to v8:

kernel/sched/core.c +1 -1
index c6e2dd8f4ee3..f16418731866 100644
@@ -11662,7 +11662,7 @@ void sched_mm_cid_migrate_to(struct rq *dst_rq, struct task_struct *t)
 		return;
 	}
 	/* Move src_cid to dst cpu. */
-	mm_cid_snapshot_time(mm);
+	mm_cid_snapshot_time(mm, cpu_of(dst_rq));
 	WRITE_ONCE(dst_pcpu_cid->cid, src_cid);
 }
 
kernel/sched/sched.h +7 -6
index d1d470441422..8b6a0c8ed3d1 100644
@@ -3348,12 +3348,13 @@ static inline int __mm_cid_try_get(struct mm_struct *mm)
  * Save a snapshot of the current runqueue time of this cpu
  * with the per-cpu cid value, allowing to estimate how recently it was used.
  */
-static inline void mm_cid_snapshot_time(struct mm_struct *mm)
+static inline void mm_cid_snapshot_time(struct mm_struct *mm, int cpu)
 {
-	struct rq *rq = this_rq();
+	struct mm_cid *pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu);
+	struct rq *rq = cpu_rq(cpu);
 
 	lockdep_assert_rq_held(rq);
-	__this_cpu_write(mm->pcpu_cid->time, rq->clock);
+	WRITE_ONCE(pcpu_cid->time, rq->clock);
 }
 
 static inline int __mm_cid_get(struct mm_struct *mm)
@@ -3404,7 +3405,7 @@ static inline int __mm_cid_get(struct mm_struct *mm)
 unlock:
 	raw_spin_unlock(&cid_lock);
 end:
-	mm_cid_snapshot_time(mm);
+	mm_cid_snapshot_time(mm, raw_smp_processor_id());
 	return cid;
 }
 
@@ -3419,7 +3420,7 @@ static inline int mm_cid_get(struct mm_struct *mm)
 	cpumask = mm_cidmask(mm);
 	cid = __this_cpu_read(pcpu_cid->cid);
 	if (mm_cid_is_valid(cid)) {
-		mm_cid_snapshot_time(mm);
+		mm_cid_snapshot_time(mm, raw_smp_processor_id());
 		return cid;
 	}
 	if (mm_cid_is_lazy_put(cid)) {
@@ -3467,7 +3468,7 @@ static inline void switch_mm_cid(struct task_struct *prev,
 		 */
 	}
 	if (prev->mm_cid_active) {
-		mm_cid_snapshot_time(prev->mm);
+		mm_cid_snapshot_time(prev->mm, raw_smp_processor_id());
 		mm_cid_put_lazy(prev);
 		prev->mm_cid = -1;
 	}
#3 lore raw

Re: [RFC PATCH v9 2/2] sched: Fix performance regression introduced by mm_cid

Quoted 34 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.

mm_cid_get() dropped to 5.x% after I disable CONFIG_DEBUG_PREEMPT, using __this_cpu_X() doesn't help, I suppose that is because __this_cpu_X() still needs to fetch mm->pcpu_cid.

Annotate mm_cid_get():

        │     static inline int mm_cid_get(struct mm_struct *mm)
        │     {
   0.05 │       push   %rbp
   0.02 │       mov    %rsp,%rbp
        │       push   %r15
        │       push   %r14
        │       push   %r13
        │       push   %r12
        │       push   %rbx
   0.02 │       sub    $0x10,%rsp
        │     struct mm_cid __percpu *pcpu_cid = mm->pcpu_cid;
  71.30 │       mov    0x60(%rdi),%r12
        │     struct cpumask *cpumask;
        │     int cid;
        │
        │     lockdep_assert_rq_held(rq);
        │     cpumask = mm_cidmask(mm);
        │     cid = __this_cpu_read(pcpu_cid->cid);
  28.44 │       mov    %gs:0x8(%r12),%edx
        │     if (mm_cid_is_valid(cid)) {

sched_mm_cid_migrate_to() is 4.x% and its annotation :

Quoted 7 lines
        │     dst_pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu_of(dst_rq));
        │       mov     -0x30(%rbp),%rax
  54.53 │       mov     0x60(%r13),%rbx
  19.61 │       movslq  0xaf0(%rax),%r15

The reason why accessing mm->pcpu_cid is so costly is still a myth to me...

Then we clearly have another member of mm_struct on the same cache line as pcpu_cid which is bouncing all over the place and causing false-sharing. Any idea which field(s) are causing this ?

Quoted 3 lines

BTW, I used below diff to mitigate the incorrect rq lock issue I described in my reply to v8:

Yes, I'll do something similar in my next version, thanks ! I'll also drop my patch 1/2 from my patchset because clearly I was looking in the wrong place.

Thanks,

Mathieu

Quoted 62 lines
kernel/sched/core.c +1 -1
index c6e2dd8f4ee3..f16418731866 100644
@@ -11662,7 +11662,7 @@ void sched_mm_cid_migrate_to(struct rq *dst_rq, struct task_struct *t)
  		return;
  	}
  	/* Move src_cid to dst cpu. */
-	mm_cid_snapshot_time(mm);
+	mm_cid_snapshot_time(mm, cpu_of(dst_rq));
  	WRITE_ONCE(dst_pcpu_cid->cid, src_cid);
  }
 
kernel/sched/sched.h +7 -6
index d1d470441422..8b6a0c8ed3d1 100644
@@ -3348,12 +3348,13 @@ static inline int __mm_cid_try_get(struct mm_struct *mm)
   * Save a snapshot of the current runqueue time of this cpu
   * with the per-cpu cid value, allowing to estimate how recently it was used.
   */
-static inline void mm_cid_snapshot_time(struct mm_struct *mm)
+static inline void mm_cid_snapshot_time(struct mm_struct *mm, int cpu)
  {
-	struct rq *rq = this_rq();
+	struct mm_cid *pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu);
+	struct rq *rq = cpu_rq(cpu);
 
  	lockdep_assert_rq_held(rq);
-	__this_cpu_write(mm->pcpu_cid->time, rq->clock);
+	WRITE_ONCE(pcpu_cid->time, rq->clock);
  }
 
  static inline int __mm_cid_get(struct mm_struct *mm)
@@ -3404,7 +3405,7 @@ static inline int __mm_cid_get(struct mm_struct *mm)
  unlock:
  	raw_spin_unlock(&cid_lock);
  end:
-	mm_cid_snapshot_time(mm);
+	mm_cid_snapshot_time(mm, raw_smp_processor_id());
  	return cid;
  }
 
@@ -3419,7 +3420,7 @@ static inline int mm_cid_get(struct mm_struct *mm)
  	cpumask = mm_cidmask(mm);
  	cid = __this_cpu_read(pcpu_cid->cid);
  	if (mm_cid_is_valid(cid)) {
-		mm_cid_snapshot_time(mm);
+		mm_cid_snapshot_time(mm, raw_smp_processor_id());
  		return cid;
  	}
  	if (mm_cid_is_lazy_put(cid)) {
@@ -3467,7 +3468,7 @@ static inline void switch_mm_cid(struct task_struct *prev,
  		 */
  	}
  	if (prev->mm_cid_active) {
-		mm_cid_snapshot_time(prev->mm);
+		mm_cid_snapshot_time(prev->mm, raw_smp_processor_id());
  		mm_cid_put_lazy(prev);
  		prev->mm_cid = -1;
  	}
Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
#4 lore raw

Re: [RFC PATCH v9 2/2] sched: Fix performance regression introduced by mm_cid

Quoted 40 lines · Mathieu Desnoyers
Quoted 39 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.

mm_cid_get() dropped to 5.x% after I disable CONFIG_DEBUG_PREEMPT, using __this_cpu_X() doesn't help, I suppose that is because __this_cpu_X() still needs to fetch mm->pcpu_cid.

Annotate mm_cid_get():

        │     static inline int mm_cid_get(struct mm_struct *mm)
        │     {
   0.05 │       push   %rbp
   0.02 │       mov    %rsp,%rbp
        │       push   %r15
        │       push   %r14
        │       push   %r13
        │       push   %r12
        │       push   %rbx
   0.02 │       sub    $0x10,%rsp
        │     struct mm_cid __percpu *pcpu_cid = mm->pcpu_cid;
  71.30 │       mov    0x60(%rdi),%r12
        │     struct cpumask *cpumask;
        │     int cid;
        │
        │     lockdep_assert_rq_held(rq);
        │     cpumask = mm_cidmask(mm);
        │     cid = __this_cpu_read(pcpu_cid->cid);
  28.44 │       mov    %gs:0x8(%r12),%edx
        │     if (mm_cid_is_valid(cid)) {

sched_mm_cid_migrate_to() is 4.x% and its annotation :

        │     dst_pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu_of(dst_rq));
        │       mov     -0x30(%rbp),%rax
  54.53 │       mov     0x60(%r13),%rbx
  19.61 │       movslq  0xaf0(%rax),%r15
Quoted 6 lines
Quoted 2 lines

The reason why accessing mm->pcpu_cid is so costly is still a myth to me...

Then we clearly have another member of mm_struct on the same cache line as pcpu_cid which is bouncing all over the place and causing false-sharing. Any idea which field(s) are causing this ?

That's my first reaction too but as I said in an earlier reply:
https://lore.kernel.org/lkml/20230419080606.GA4247@ziqianlu-desk2/
I've tried to place pcpu_cid into a dedicate cacheline with no other fields sharing a cacheline with it in mm_struct but it didn't help...

Thanks,
Aaron

#5 lore raw

Re: [RFC PATCH v9 2/2] sched: Fix performance regression introduced by mm_cid

Quoted 44 lines · Aaron Lu
Quoted 43 lines · Mathieu Desnoyers
Quoted 41 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.

mm_cid_get() dropped to 5.x% after I disable CONFIG_DEBUG_PREEMPT, using __this_cpu_X() doesn't help, I suppose that is because __this_cpu_X() still needs to fetch mm->pcpu_cid.

Annotate mm_cid_get():

         │     static inline int mm_cid_get(struct mm_struct *mm)
         │     {
    0.05 │       push   %rbp
    0.02 │       mov    %rsp,%rbp
         │       push   %r15
         │       push   %r14
         │       push   %r13
         │       push   %r12
         │       push   %rbx
    0.02 │       sub    $0x10,%rsp
         │     struct mm_cid __percpu *pcpu_cid = mm->pcpu_cid;
   71.30 │       mov    0x60(%rdi),%r12
         │     struct cpumask *cpumask;
         │     int cid;
         │
         │     lockdep_assert_rq_held(rq);
         │     cpumask = mm_cidmask(mm);
         │     cid = __this_cpu_read(pcpu_cid->cid);
   28.44 │       mov    %gs:0x8(%r12),%edx
         │     if (mm_cid_is_valid(cid)) {

sched_mm_cid_migrate_to() is 4.x% and its annotation :

         │     dst_pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu_of(dst_rq));
         │       mov     -0x30(%rbp),%rax
   54.53 │       mov     0x60(%r13),%rbx
   19.61 │       movslq  0xaf0(%rax),%r15

The reason why accessing mm->pcpu_cid is so costly is still a myth to me...

Quoted 8 lines
Quoted 3 lines

Then we clearly have another member of mm_struct on the same cache line as pcpu_cid which is bouncing all over the place and causing false-sharing. Any idea which field(s) are causing this ?

That's my first reaction too but as I said in an earlier reply:
https://lore.kernel.org/lkml/20230419080606.GA4247@ziqianlu-desk2/
I've tried to place pcpu_cid into a dedicate cacheline with no other fields sharing a cacheline with it in mm_struct but it didn't help...

I see two possible culprits there:

1) The mm_struct pcpu_cid field is suffering from false-sharing. I would be interested to look at your attempt to move it to a separate cache line to try to figure out what is going on.

2) (Maybe?) The task_struct mm field is suffering from false-sharing and stalling the next instruction which needs to use its value to fetch the mm->pcpu_cid field. We could try moving the task_struct mm field into its own cache line to see if it helps.

Thanks,

Mathieu

Quoted 3 lines

Thanks,
Aaron

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
#6 lore raw

Re: [RFC PATCH v9 2/2] sched: Fix performance regression introduced by mm_cid

Quoted 54 lines · Mathieu Desnoyers
Quoted 44 lines · Aaron Lu
Quoted 43 lines · Mathieu Desnoyers
Quoted 41 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.

mm_cid_get() dropped to 5.x% after I disable CONFIG_DEBUG_PREEMPT, using __this_cpu_X() doesn't help, I suppose that is because __this_cpu_X() still needs to fetch mm->pcpu_cid.

Annotate mm_cid_get():

         │     static inline int mm_cid_get(struct mm_struct *mm)
         │     {
    0.05 │       push   %rbp
    0.02 │       mov    %rsp,%rbp
         │       push   %r15
         │       push   %r14
         │       push   %r13
         │       push   %r12
         │       push   %rbx
    0.02 │       sub    $0x10,%rsp
         │     struct mm_cid __percpu *pcpu_cid = mm->pcpu_cid;
   71.30 │       mov    0x60(%rdi),%r12
         │     struct cpumask *cpumask;
         │     int cid;
         │
         │     lockdep_assert_rq_held(rq);
         │     cpumask = mm_cidmask(mm);
         │     cid = __this_cpu_read(pcpu_cid->cid);
   28.44 │       mov    %gs:0x8(%r12),%edx
         │     if (mm_cid_is_valid(cid)) {

sched_mm_cid_migrate_to() is 4.x% and its annotation :

         │     dst_pcpu_cid = per_cpu_ptr(mm->pcpu_cid, cpu_of(dst_rq));
         │       mov     -0x30(%rbp),%rax
   54.53 │       mov     0x60(%r13),%rbx
   19.61 │       movslq  0xaf0(%rax),%r15

The reason why accessing mm->pcpu_cid is so costly is still a myth to me...

Quoted 8 lines
Quoted 3 lines

Then we clearly have another member of mm_struct on the same cache line as pcpu_cid which is bouncing all over the place and causing false-sharing. Any idea which field(s) are causing this ?

That's my first reaction too but as I said in an earlier reply:
https://lore.kernel.org/lkml/20230419080606.GA4247@ziqianlu-desk2/
I've tried to place pcpu_cid into a dedicate cacheline with no other fields sharing a cacheline with it in mm_struct but it didn't help...

Quoted 5 lines

I see two possible culprits there:

1) The mm_struct pcpu_cid field is suffering from false-sharing. I would be interested to look at your attempt to move it to a separate cache line to try to figure out what is going on.

Brain damaged...my mistake, I only made sure its following fields not share the same cacheline but forgot to exclude its preceding fields and turned out it's one(some?) of the preceeding fields that caused false sharing. When I did:

include/linux/mm_types.h +1 -0
index 5eab61156f0e..a6f9d815991c 100644
@@ -606,6 +606,7 @@ struct mm_struct {
                 */
                atomic_t mm_count;
 #ifdef CONFIG_SCHED_MM_CID
+               CACHELINE_PADDING(_pad1_);
                /**
                 * @pcpu_cid: Per-cpu current cid.
                 *

mm_cid_get() dropped to 0.0x% when running hackbench :-)

sched_mm_cid_migrate_to() is about 4% with most cycles spent on accessing mm->mm_users:

       │     dst_cid = READ_ONCE(dst_pcpu_cid->cid);
  0.03 │       mov     0x8(%r12),%r15d
       │     if (!mm_cid_is_unset(dst_cid) &&
  0.07 │       cmp     $0xffffffff,%r15d
       │     ↓ je      87
       │     arch_atomic_read():
       │     {
       │     /*
       │     * Note for KASAN: we deliberately don't use READ_ONCE_NOCHECK() here,
       │     * it's non-inlined function that increases binary size and stack usage.
       │     */
       │     return __READ_ONCE((v)->counter);
 76.13 │       mov     0x54(%r13),%eax
       │     sched_mm_cid_migrate_to():
       │       cmp     %eax,0x410(%rdx)
 21.71 │     ↓ jle     1d8
       │     atomic_read(&mm->mm_users) >= t->nr_cpus_allowed)

With this info, it should be mm_users that caused false sharing for pcpu_cid previously. Looks like mm_users is bouncing.

Thanks,
Aaron

#7 lore raw

Re: [RFC PATCH v9 2/2] sched: Fix performance regression introduced by mm_cid

On 2023-04-20 09:35, Aaron Lu wrote:
[...]

Quoted 33 lines
Quoted 10 lines
Quoted 9 lines
Quoted 4 lines

Then we clearly have another member of mm_struct on the same cache line as pcpu_cid which is bouncing all over the place and causing false-sharing. Any idea which field(s) are causing this ?

That's my first reaction too but as I said in an earlier reply:
https://lore.kernel.org/lkml/20230419080606.GA4247@ziqianlu-desk2/
I've tried to place pcpu_cid into a dedicate cacheline with no other fields sharing a cacheline with it in mm_struct but it didn't help...

Quoted 5 lines

I see two possible culprits there:

1) The mm_struct pcpu_cid field is suffering from false-sharing. I would be interested to look at your attempt to move it to a separate cache line to try to figure out what is going on.

Brain damaged...my mistake, I only made sure its following fields not share the same cacheline but forgot to exclude its preceding fields and turned out it's one(some?) of the preceeding fields that caused false sharing. When I did:

include/linux/mm_types.h +1 -0
index 5eab61156f0e..a6f9d815991c 100644
@@ -606,6 +606,7 @@ struct mm_struct {
                  */
                 atomic_t mm_count;
  #ifdef CONFIG_SCHED_MM_CID
+               CACHELINE_PADDING(_pad1_);
                 /**
                  * @pcpu_cid: Per-cpu current cid.
                  *
Quoted 1 line

mm_cid_get() dropped to 0.0x% when running hackbench :-)

Now we are talking! :)

Quoted 22 lines

sched_mm_cid_migrate_to() is about 4% with most cycles spent on accessing mm->mm_users:

        │     dst_cid = READ_ONCE(dst_pcpu_cid->cid);
   0.03 │       mov     0x8(%r12),%r15d
        │     if (!mm_cid_is_unset(dst_cid) &&
   0.07 │       cmp     $0xffffffff,%r15d
        │     ↓ je      87
        │     arch_atomic_read():
        │     {
        │     /*
        │     * Note for KASAN: we deliberately don't use READ_ONCE_NOCHECK() here,
        │     * it's non-inlined function that increases binary size and stack usage.
        │     */
        │     return __READ_ONCE((v)->counter);
  76.13 │       mov     0x54(%r13),%eax
        │     sched_mm_cid_migrate_to():
        │       cmp     %eax,0x410(%rdx)
  21.71 │     ↓ jle     1d8
        │     atomic_read(&mm->mm_users) >= t->nr_cpus_allowed)
Quoted 2 lines

With this info, it should be mm_users that caused false sharing for pcpu_cid previously. Looks like mm_users is bouncing.

I suspect that the culprit here is mm_count rather than mm_users. mm_users just happens to share the same cache line as mm_count.

mm_count is incremented/decremented with mmgrab()/mmdrop() during context switch.

This is likely causing other issues, for instance, the
membarrier_state field is AFAIR read-mostly, used for membarrier_mm_sync_core_before_usermode() to issue core sync before every return to usermode if needed.

Other things like mm_struct pgd pointer appear to be likely read-mostly variables.

I suspect it's mm_count which should be moved to its own cache line to eliminate false-sharing with all the other read-mostly fields of mm_struct.

Thoughts ?

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
#8 lore raw

Re: [RFC PATCH v9 2/2] sched: Fix performance regression introduced by mm_cid

Quoted 75 lines · Mathieu Desnoyers

On 2023-04-20 09:35, Aaron Lu wrote:
[...]

Quoted 33 lines
Quoted 10 lines
Quoted 9 lines
Quoted 4 lines

Then we clearly have another member of mm_struct on the same cache line as pcpu_cid which is bouncing all over the place and causing false-sharing. Any idea which field(s) are causing this ?

That's my first reaction too but as I said in an earlier reply:
https://lore.kernel.org/lkml/20230419080606.GA4247@ziqianlu-desk2/
I've tried to place pcpu_cid into a dedicate cacheline with no other fields sharing a cacheline with it in mm_struct but it didn't help...

Quoted 5 lines

I see two possible culprits there:

1) The mm_struct pcpu_cid field is suffering from false-sharing. I would be interested to look at your attempt to move it to a separate cache line to try to figure out what is going on.

Brain damaged...my mistake, I only made sure its following fields not share the same cacheline but forgot to exclude its preceding fields and turned out it's one(some?) of the preceeding fields that caused false sharing. When I did:

include/linux/mm_types.h +1 -0
index 5eab61156f0e..a6f9d815991c 100644
@@ -606,6 +606,7 @@ struct mm_struct {
                  */
                 atomic_t mm_count;
  #ifdef CONFIG_SCHED_MM_CID
+               CACHELINE_PADDING(_pad1_);
                 /**
                  * @pcpu_cid: Per-cpu current cid.
                  *
Quoted 1 line

mm_cid_get() dropped to 0.0x% when running hackbench :-)

Now we are talking! :)

Quoted 22 lines

sched_mm_cid_migrate_to() is about 4% with most cycles spent on accessing mm->mm_users:

        │     dst_cid = READ_ONCE(dst_pcpu_cid->cid);
   0.03 │       mov     0x8(%r12),%r15d
        │     if (!mm_cid_is_unset(dst_cid) &&
   0.07 │       cmp     $0xffffffff,%r15d
        │     ↓ je      87
        │     arch_atomic_read():
        │     {
        │     /*
        │     * Note for KASAN: we deliberately don't use READ_ONCE_NOCHECK() here,
        │     * it's non-inlined function that increases binary size and stack usage.
        │     */
        │     return __READ_ONCE((v)->counter);
  76.13 │       mov     0x54(%r13),%eax
        │     sched_mm_cid_migrate_to():
        │       cmp     %eax,0x410(%rdx)
  21.71 │     ↓ jle     1d8
        │     atomic_read(&mm->mm_users) >= t->nr_cpus_allowed)
Quoted 2 lines

With this info, it should be mm_users that caused false sharing for pcpu_cid previously. Looks like mm_users is bouncing.

I suspect that the culprit here is mm_count rather than mm_users. mm_users just happens to share the same cache line as mm_count.

mm_count is incremented/decremented with mmgrab()/mmdrop() during context switch.

This is likely causing other issues, for instance, the membarrier_state field is AFAIR read-mostly, used for membarrier_mm_sync_core_before_usermode() to issue core sync before every return to usermode if needed.

Quoted 8 lines

Other things like mm_struct pgd pointer appear to be likely read-mostly variables.

I suspect it's mm_count which should be moved to its own cache line to eliminate false-sharing with all the other read-mostly fields of mm_struct.

Thoughts ?

Makes sesne, I was wondering where the write side of mm_user is. Let me see how that goes by placing mm_count aside from other read mostly fields.

#9 lore raw

Re: [RFC PATCH v9 2/2] sched: Fix performance regression introduced by mm_cid

Quoted 79 lines · Aaron Lu
Quoted 78 lines · Mathieu Desnoyers

On 2023-04-20 09:35, Aaron Lu wrote:
[...]

Quoted 33 lines
Quoted 10 lines
Quoted 9 lines
Quoted 4 lines

Then we clearly have another member of mm_struct on the same cache line as pcpu_cid which is bouncing all over the place and causing false-sharing. Any idea which field(s) are causing this ?

That's my first reaction too but as I said in an earlier reply:
https://lore.kernel.org/lkml/20230419080606.GA4247@ziqianlu-desk2/
I've tried to place pcpu_cid into a dedicate cacheline with no other fields sharing a cacheline with it in mm_struct but it didn't help...

Quoted 5 lines

I see two possible culprits there:

1) The mm_struct pcpu_cid field is suffering from false-sharing. I would be interested to look at your attempt to move it to a separate cache line to try to figure out what is going on.

Brain damaged...my mistake, I only made sure its following fields not share the same cacheline but forgot to exclude its preceding fields and turned out it's one(some?) of the preceeding fields that caused false sharing. When I did:

include/linux/mm_types.h +1 -0
index 5eab61156f0e..a6f9d815991c 100644
@@ -606,6 +606,7 @@ struct mm_struct {
                  */
                 atomic_t mm_count;
  #ifdef CONFIG_SCHED_MM_CID
+               CACHELINE_PADDING(_pad1_);
                 /**
                  * @pcpu_cid: Per-cpu current cid.
                  *
Quoted 1 line

mm_cid_get() dropped to 0.0x% when running hackbench :-)

Now we are talking! :)

Quoted 22 lines

sched_mm_cid_migrate_to() is about 4% with most cycles spent on accessing mm->mm_users:

        │     dst_cid = READ_ONCE(dst_pcpu_cid->cid);
   0.03 │       mov     0x8(%r12),%r15d
        │     if (!mm_cid_is_unset(dst_cid) &&
   0.07 │       cmp     $0xffffffff,%r15d
        │     ↓ je      87
        │     arch_atomic_read():
        │     {
        │     /*
        │     * Note for KASAN: we deliberately don't use READ_ONCE_NOCHECK() here,
        │     * it's non-inlined function that increases binary size and stack usage.
        │     */
        │     return __READ_ONCE((v)->counter);
  76.13 │       mov     0x54(%r13),%eax
        │     sched_mm_cid_migrate_to():
        │       cmp     %eax,0x410(%rdx)
  21.71 │     ↓ jle     1d8
        │     atomic_read(&mm->mm_users) >= t->nr_cpus_allowed)
Quoted 2 lines

With this info, it should be mm_users that caused false sharing for pcpu_cid previously. Looks like mm_users is bouncing.

I suspect that the culprit here is mm_count rather than mm_users. mm_users just happens to share the same cache line as mm_count.

mm_count is incremented/decremented with mmgrab()/mmdrop() during context switch.

This is likely causing other issues, for instance, the membarrier_state field is AFAIR read-mostly, used for membarrier_mm_sync_core_before_usermode() to issue core sync before every return to usermode if needed.

Other things like mm_struct pgd pointer appear to be likely read-mostly variables.

Quoted 8 lines
Quoted 5 lines

I suspect it's mm_count which should be moved to its own cache line to eliminate false-sharing with all the other read-mostly fields of mm_struct.

Thoughts ?

Makes sesne, I was wondering where the write side of mm_user is. Let me see how that goes by placing mm_count aside from other read mostly fields.

With the following naive padding for mm_count:

include/linux/mm_types.h +2 -0
index 5eab61156f0e..866696e2d83e 100644
@@ -604,7 +604,9 @@ struct mm_struct {
                 * Use mmgrab()/mmdrop() to modify. When this drops to 0, the
                 * &struct mm_struct is freed.
                 */
+               CACHELINE_PADDING(_pad1_);
                atomic_t mm_count;
+               CACHELINE_PADDING(_pad2_);
 #ifdef CONFIG_SCHED_MM_CID
                /**
                 * @pcpu_cid: Per-cpu current cid.

mm_cid_get() is about 0.1% and sched_mm_cid_migrate_to() is about 0.2% for hackbench on SPR :-)

Thanks,
Aaron

#10 lore raw

Re: [RFC PATCH v9 2/2] sched: Fix performance regression introduced by mm_cid

Quoted 106 lines · Aaron Lu
Quoted 79 lines · Aaron Lu
Quoted 78 lines · Mathieu Desnoyers

On 2023-04-20 09:35, Aaron Lu wrote:
[...]

Quoted 33 lines
Quoted 10 lines
Quoted 9 lines
Quoted 4 lines

Then we clearly have another member of mm_struct on the same cache line as pcpu_cid which is bouncing all over the place and causing false-sharing. Any idea which field(s) are causing this ?

That's my first reaction too but as I said in an earlier reply:
https://lore.kernel.org/lkml/20230419080606.GA4247@ziqianlu-desk2/
I've tried to place pcpu_cid into a dedicate cacheline with no other fields sharing a cacheline with it in mm_struct but it didn't help...

Quoted 5 lines

I see two possible culprits there:

1) The mm_struct pcpu_cid field is suffering from false-sharing. I would be interested to look at your attempt to move it to a separate cache line to try to figure out what is going on.

Brain damaged...my mistake, I only made sure its following fields not share the same cacheline but forgot to exclude its preceding fields and turned out it's one(some?) of the preceeding fields that caused false sharing. When I did:

include/linux/mm_types.h +1 -0
index 5eab61156f0e..a6f9d815991c 100644
@@ -606,6 +606,7 @@ struct mm_struct {
                   */
                  atomic_t mm_count;
   #ifdef CONFIG_SCHED_MM_CID
+               CACHELINE_PADDING(_pad1_);
                  /**
                   * @pcpu_cid: Per-cpu current cid.
                   *
Quoted 1 line

mm_cid_get() dropped to 0.0x% when running hackbench :-)

Now we are talking! :)

Quoted 22 lines

sched_mm_cid_migrate_to() is about 4% with most cycles spent on accessing mm->mm_users:

         │     dst_cid = READ_ONCE(dst_pcpu_cid->cid);
    0.03 │       mov     0x8(%r12),%r15d
         │     if (!mm_cid_is_unset(dst_cid) &&
    0.07 │       cmp     $0xffffffff,%r15d
         │     ↓ je      87
         │     arch_atomic_read():
         │     {
         │     /*
         │     * Note for KASAN: we deliberately don't use READ_ONCE_NOCHECK() here,
         │     * it's non-inlined function that increases binary size and stack usage.
         │     */
         │     return __READ_ONCE((v)->counter);
   76.13 │       mov     0x54(%r13),%eax
         │     sched_mm_cid_migrate_to():
         │       cmp     %eax,0x410(%rdx)
   21.71 │     ↓ jle     1d8
         │     atomic_read(&mm->mm_users) >= t->nr_cpus_allowed)
Quoted 2 lines

With this info, it should be mm_users that caused false sharing for pcpu_cid previously. Looks like mm_users is bouncing.

I suspect that the culprit here is mm_count rather than mm_users. mm_users just happens to share the same cache line as mm_count.

mm_count is incremented/decremented with mmgrab()/mmdrop() during context switch.

This is likely causing other issues, for instance, the membarrier_state field is AFAIR read-mostly, used for membarrier_mm_sync_core_before_usermode() to issue core sync before every return to usermode if needed.

Other things like mm_struct pgd pointer appear to be likely read-mostly variables.

Quoted 8 lines
Quoted 5 lines

I suspect it's mm_count which should be moved to its own cache line to eliminate false-sharing with all the other read-mostly fields of mm_struct.

Thoughts ?

Makes sesne, I was wondering where the write side of mm_user is. Let me see how that goes by placing mm_count aside from other read mostly fields.

With the following naive padding for mm_count:

include/linux/mm_types.h +2 -0
index 5eab61156f0e..866696e2d83e 100644
@@ -604,7 +604,9 @@ struct mm_struct {
                  * Use mmgrab()/mmdrop() to modify. When this drops to 0, the
                  * &struct mm_struct is freed.
                  */
+               CACHELINE_PADDING(_pad1_);
                 atomic_t mm_count;
+               CACHELINE_PADDING(_pad2_);
  #ifdef CONFIG_SCHED_MM_CID
                 /**
                  * @pcpu_cid: Per-cpu current cid.
Quoted 2 lines

mm_cid_get() is about 0.1% and sched_mm_cid_migrate_to() is about 0.2% for hackbench on SPR :-)

Allright, then our work is done here. I'm popping the champagne.

I'm doing some more testing on v10 which includes a fix for the time-snapshot wrong runqueue, and I'll post it today.

Thanks a lot for your help ! :-)

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
#11 lore raw

Re: [RFC PATCH v9 2/2] sched: Fix performance regression introduced by mm_cid

In reply to Mathieu Desnoyers
Quoted 73 lines · Mathieu Desnoyers

On 2023-04-20 09:35, Aaron Lu wrote:
[...]

Quoted 33 lines
Quoted 10 lines
Quoted 9 lines
Quoted 4 lines

Then we clearly have another member of mm_struct on the same cache line as pcpu_cid which is bouncing all over the place and causing false-sharing. Any idea which field(s) are causing this ?

That's my first reaction too but as I said in an earlier reply:
https://lore.kernel.org/lkml/20230419080606.GA4247@ziqianlu-desk2/
I've tried to place pcpu_cid into a dedicate cacheline with no other fields sharing a cacheline with it in mm_struct but it didn't help...

Quoted 5 lines

I see two possible culprits there:

1) The mm_struct pcpu_cid field is suffering from false-sharing. I would be interested to look at your attempt to move it to a separate cache line to try to figure out what is going on.

Brain damaged...my mistake, I only made sure its following fields not share the same cacheline but forgot to exclude its preceding fields and turned out it's one(some?) of the preceeding fields that caused false sharing. When I did:

include/linux/mm_types.h +1 -0
index 5eab61156f0e..a6f9d815991c 100644
@@ -606,6 +606,7 @@ struct mm_struct {
                   */
                  atomic_t mm_count;
   #ifdef CONFIG_SCHED_MM_CID
+               CACHELINE_PADDING(_pad1_);
                  /**
                   * @pcpu_cid: Per-cpu current cid.
                   *
Quoted 1 line

mm_cid_get() dropped to 0.0x% when running hackbench :-)

Now we are talking! :)

Quoted 22 lines

sched_mm_cid_migrate_to() is about 4% with most cycles spent on accessing mm->mm_users:

        │     dst_cid = READ_ONCE(dst_pcpu_cid->cid);
   0.03 │       mov     0x8(%r12),%r15d
        │     if (!mm_cid_is_unset(dst_cid) &&
   0.07 │       cmp     $0xffffffff,%r15d
        │     ↓ je      87
        │     arch_atomic_read():
        │     {
        │     /*
        │     * Note for KASAN: we deliberately don't use READ_ONCE_NOCHECK() here,
        │     * it's non-inlined function that increases binary size and stack usage.
        │     */
        │     return __READ_ONCE((v)->counter);
  76.13 │       mov     0x54(%r13),%eax
        │     sched_mm_cid_migrate_to():
        │       cmp     %eax,0x410(%rdx)
  21.71 │     ↓ jle     1d8
        │     atomic_read(&mm->mm_users) >= t->nr_cpus_allowed)
Quoted 2 lines

With this info, it should be mm_users that caused false sharing for pcpu_cid previously. Looks like mm_users is bouncing.

I suspect that the culprit here is mm_count rather than mm_users. mm_users just happens to share the same cache line as mm_count.

mm_count is incremented/decremented with mmgrab()/mmdrop() during context switch.

This is likely causing other issues, for instance, the
membarrier_state field is AFAIR read-mostly, used for membarrier_mm_sync_core_before_usermode() to issue core sync before every return to usermode if needed.

Quoted 6 lines

Other things like mm_struct pgd pointer appear to be likely read-mostly variables.

I suspect it's mm_count which should be moved to its own cache line to eliminate false-sharing with all the other read-mostly fields of mm_struct.

I have prepared a patch which moves the mm_count field into its own cache line, but after a quick discussion with Peter Zijlstra, it appears that the work on lazy-tlb refcounting currently in

https://git.kernel.org/pub/scm/linux/kernel/git/peterz/queue.git/log/?h=x86/lazy

will take care of this by entirely removing the reference counting for lazy TLB.

So with this, I suspect we are as good as we can be in terms of near-zero footprint for the mm_cid feature, right ?

include/linux/mm_types.h +15 -8
index a57e6ae78e65..f740fa447df1 100644
@@ -553,6 +553,21 @@ struct vm_area_struct {
 struct kioctx_table;
 struct mm_struct {
 	struct {
+		/*
+		 * Fields which are often written to are placed in a separate
+		 * cache line.
+		 */
+		struct {
+			/**
+			 * @mm_count: The number of references to &struct mm_struct
+			 * (@mm_users count as 1).
+			 *
+			 * Use mmgrab()/mmdrop() to modify. When this drops to 0, the
+			 * &struct mm_struct is freed.
+			 */
+			atomic_t mm_count;
+		} ____cacheline_aligned_in_smp;
+
 		struct maple_tree mm_mt;
 #ifdef CONFIG_MMU
 		unsigned long (*get_unmapped_area) (struct file *filp,
@@ -590,14 +605,6 @@ struct mm_struct {
 		 */
 		atomic_t mm_users;
 
-		/**
-		 * @mm_count: The number of references to &struct mm_struct
-		 * (@mm_users count as 1).
-		 *
-		 * Use mmgrab()/mmdrop() to modify. When this drops to 0, the
-		 * &struct mm_struct is freed.
-		 */
-		atomic_t mm_count;
 #ifdef CONFIG_SCHED_MM_CID
 		/**
 		 * @cid_lock: Protect cid bitmap updates vs lookups.
Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com