[PATCH v1] mm/readahead: Optimize nr_to_read boundary check

Xiaole He posted 1 patch 2 months, 1 week ago
mm/readahead.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
[PATCH v1] mm/readahead: Optimize nr_to_read boundary check
Posted by Xiaole He 2 months, 1 week ago
The current boundary check for nr_to_read in do_page_cache_ra can lead
to a redundant self-assignment when the desired read length precisely
matches the remaining pages to the end of the file.

Currently, the code is:

if (nr_to_read > end_index - index)
    nr_to_read = end_index - index + 1;

If nr_to_read is, for instance, 3, and end_index - index + 1 is also 3
(meaning 3 pages remain), the condition 3 > 2 evaluates to true, leading
 to nr_to_read being assigned 3 again. While compilers might optimize
this trivial self-assignment, it introduces unnecessary logical overhead
 and reduces code clarity.

This patch refines the condition to be more explicit and avoid this
redundant assignment:

if (nr_to_read > end_index - index + 1)
    nr_to_read = end_index - index + 1;

This ensures the assignment only occurs when nr_to_read genuinely
exceeds the available pages, improving code precision and slightly
enhancing readability without altering the core functionality.

Signed-off-by: Xiaole He <hexiaole1994@126.com>
---
 mm/readahead.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/mm/readahead.c b/mm/readahead.c
index 20d36d6b055e..bbcfbebe7569 100644
--- a/mm/readahead.c
+++ b/mm/readahead.c
@@ -321,7 +321,7 @@ static void do_page_cache_ra(struct readahead_control *ractl,
 	if (index > end_index)
 		return;
 	/* Don't read past the page containing the last byte of the file */
-	if (nr_to_read > end_index - index)
+	if (nr_to_read > end_index - index + 1)
 		nr_to_read = end_index - index + 1;
 
 	page_cache_ra_unbounded(ractl, nr_to_read, lookahead_size);
-- 
2.43.0
Re: [PATCH v1] mm/readahead: Optimize nr_to_read boundary check
Posted by Matthew Wilcox 2 months, 1 week ago
On Fri, Jul 25, 2025 at 11:28:34PM +0800, Xiaole He wrote:
> If nr_to_read is, for instance, 3, and end_index - index + 1 is also 3
> (meaning 3 pages remain), the condition 3 > 2 evaluates to true, leading
>  to nr_to_read being assigned 3 again. While compilers might optimize
> this trivial self-assignment, it introduces unnecessary logical overhead
>  and reduces code clarity.

But it makes the initial comparison more complex (by one operation) and
I bet you can't measure the difference anyway.  I'm not inclined to
tweak this.