Re: [PATCH] locking/rtmutex: Do the trylock-slowpath with DEBUG_RT_MUTEXES enabled.

From: Thomas Gleixner
Date: Fri Apr 21 2023 - 13:59:06 EST


On Tue, Mar 28 2023 at 18:54, Sebastian Andrzej Siewior wrote:
> On 2023-03-22 17:27:21 [+0100], To Thomas Gleixner wrote:
>> > Aside of that for CONFIG_DEBUG_RT_MUTEXES=y builds it flushes on every
>> > lock operation whether the lock is contended or not.
>>
>> For mutex & ww_mutex operations. rwsem is not affected by
>> CONFIG_DEBUG_RT_MUTEXES. As for mutex it could be mitigated by invoking
>> try_to_take_rt_mutex() before blk_flush_plug().

> I haven't observed anything in the ww-mutex path so we can ignore it or
> do something similar to this.

Yay for consistency !

I fixed it up to the below.

Thanks,

tglx
---

--- a/kernel/locking/rtmutex.c
+++ b/kernel/locking/rtmutex.c
@@ -219,6 +219,11 @@ static __always_inline bool rt_mutex_cmp
return try_cmpxchg_acquire(&lock->owner, &old, new);
}

+static __always_inline bool rt_mutex_try_acquire(struct rt_mutex_base *lock)
+{
+ return rt_mutex_cmpxchg_acquire(lock, old, new);
+}
+
static __always_inline bool rt_mutex_cmpxchg_release(struct rt_mutex_base *lock,
struct task_struct *old,
struct task_struct *new)
@@ -298,6 +303,20 @@ static __always_inline bool rt_mutex_cmp

}

+static __always_inline bool rt_mutex_try_acquire(struct rt_mutex_base *lock)
+{
+ /*
+ * With debug enabled rt_mutex_cmpxchg trylock() will always fail,
+ * which will unconditionally invoke blk_flush_plug() in the slow
+ * path of __rt_mutex_lock() and __ww_rt_mutex_lock() even in the
+ * non-contended case.
+ *
+ * Avoid that by using rt_mutex_slow_trylock() which is fully covered
+ * by the debug code and can acquire a non-contended rtmutex.
+ */
+ return rt_mutex_slowtrylock(lock);
+}
+
static __always_inline bool rt_mutex_cmpxchg_release(struct rt_mutex_base *lock,
struct task_struct *old,
struct task_struct *new)
@@ -1698,9 +1717,8 @@ static int __sched rt_mutex_slowlock(str
static __always_inline int __rt_mutex_lock(struct rt_mutex_base *lock,
unsigned int state)
{
- if (likely(rt_mutex_cmpxchg_acquire(lock, NULL, current)))
+ if (likely(rt_mutex_try_acquire(lock)))
return 0;
-
/*
* The task is about to sleep. Flush plugged IO as that might
* take locks and corrupt tsk::pi_blocked_on.
--- a/kernel/locking/ww_rt_mutex.c
+++ b/kernel/locking/ww_rt_mutex.c
@@ -62,7 +62,7 @@ static int __sched
}
mutex_acquire_nest(&rtm->dep_map, 0, 0, nest_lock, ip);

- if (likely(rt_mutex_cmpxchg_acquire(&rtm->rtmutex, NULL, current))) {
+ if (likely(rt_mutex_try_acquire(&rtm->rtmutex, NULL, current))) {
if (ww_ctx)
ww_mutex_set_context_fastpath(lock, ww_ctx);
return 0;