Commit 96d36604 authored by Paul E. McKenney's avatar Paul E. McKenney
Browse files

ratelimit: Avoid atomic decrement under lock if already rate-limited

Currently, if the lock is acquired, the code unconditionally does
an atomic decrement on ->rs_n_left, even if that atomic operation is
guaranteed to return a limit-rate verdict.  A limit-rate verdict will
in fact be the common case when something is spewing into a rate limit.
This unconditional atomic operation incurs needless overhead and also
raises the spectre of counter wrap.

Therefore, do the atomic decrement only if there is some chance that
rates won't be limited.

Link: https://lore.kernel.org/all/fbe93a52-365e-47fe-93a4-44a44547d601@paulmck-laptop/
Link: https://lore.kernel.org/all/20250423115409.3425-1-spasswolf@web.de/


Signed-off-by: default avatarPaul E. McKenney <paulmck@kernel.org>
Reviewed-by: default avatarPetr Mladek <pmladek@suse.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Kuniyuki Iwashima <kuniyu@amazon.com>
Cc: Mateusz Guzik <mjguzik@gmail.com>
Cc: Steven Rostedt <rostedt@goodmis.org>
Cc: John Ogness <john.ogness@linutronix.de>
Cc: Sergey Senozhatsky <senozhatsky@chromium.org>
parent 123a1d97
Loading
Loading
Loading
Loading
+8 −5
Original line number Diff line number Diff line
@@ -103,15 +103,18 @@ int ___ratelimit(struct ratelimit_state *rs, const char *func)
		}
	}
	if (burst) {
		int n_left;
		int n_left = atomic_read(&rs->rs_n_left);

		/* The burst might have been taken by a parallel call. */

		if (n_left > 0) {
			n_left = atomic_dec_return(&rs->rs_n_left);
			if (n_left >= 0) {
				ret = 1;
				goto unlock_ret;
			}
		}
	}

	ratelimit_state_inc_miss(rs);
	ret = 0;