[RFC PATCH 2/2] seqlock: introduce need_seqretry_xxx()

From: Oleg Nesterov
Date: Tue Oct 24 2023 - 08:10:35 EST


Not for inclusion, just for discussion...

Modulo naming, do you think the new need_seqretry_xxx() makes sense?

Simpler to use and less error prone. thread_group_cputime() is changed
as an example.
---
include/linux/seqlock.h | 10 ++++++++++
kernel/sched/cputime.c | 9 +++------
2 files changed, 13 insertions(+), 6 deletions(-)

diff --git a/include/linux/seqlock.h b/include/linux/seqlock.h
index d0050c889f26..9b3bc4ce3332 100644
--- a/include/linux/seqlock.h
+++ b/include/linux/seqlock.h
@@ -1165,6 +1165,16 @@ static inline int need_seqretry(seqlock_t *lock, int seq)
return !(seq & 1) && read_seqretry(lock, seq);
}

+static inline int need_seqretry_xxx(seqlock_t *lock, int *seq)
+{
+ int ret = !(*seq & 1) && read_seqretry(lock, *seq);
+
+ if (ret)
+ ++*seq; /* make this counter odd */
+
+ return ret;
+}
+
/**
* done_seqretry() - end seqlock_t "locking or lockless" reader section
* @lock: Pointer to seqlock_t
diff --git a/kernel/sched/cputime.c b/kernel/sched/cputime.c
index af7952f12e6c..45704a84baec 100644
--- a/kernel/sched/cputime.c
+++ b/kernel/sched/cputime.c
@@ -314,7 +314,7 @@ void thread_group_cputime(struct task_struct *tsk, struct task_cputime *times)
struct signal_struct *sig = tsk->signal;
u64 utime, stime;
struct task_struct *t;
- unsigned int seq, nextseq;
+ unsigned int seq;
unsigned long flags;

/*
@@ -330,9 +330,8 @@ void thread_group_cputime(struct task_struct *tsk, struct task_cputime *times)

rcu_read_lock();
/* Attempt a lockless read on the first round. */
- nextseq = 0;
+ seq = 0;
do {
- seq = nextseq;
flags = read_seqbegin_or_lock_irqsave(&sig->stats_lock, &seq);
times->utime = sig->utime;
times->stime = sig->stime;
@@ -344,9 +343,7 @@ void thread_group_cputime(struct task_struct *tsk, struct task_cputime *times)
times->stime += stime;
times->sum_exec_runtime += read_sum_exec_runtime(t);
}
- /* If lockless access failed, take the lock. */
- nextseq = 1;
- } while (need_seqretry(&sig->stats_lock, seq));
+ } while (need_seqretry_xxx(&sig->stats_lock, &seq));
done_seqretry_irqrestore(&sig->stats_lock, seq, flags);
rcu_read_unlock();
}
--
2.25.1.362.g51ebf55