Skip to contentSkip to conversation

buffer: Use try_cmpxchg in discard_buffer

PATCH Applied Uros Bizjak 1 participant 1 message Jul 14, 2022 VFS

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 buffer: Use try_cmpxchg in discard_buffer

Use try_cmpxchg instead of cmpxchg (*ptr, old, new) == old in discard_buffer. x86 CMPXCHG instruction returns success in ZF flag, so this change saves a compare after cmpxchg (and related move instruction in front of cmpxchg).

Also, try_cmpxchg implicitly assigns old *ptr value to "old" when cmpxchg fails, enabling further code simplifications.

Note that the value from *ptr should be read using READ_ONCE to prevent the compiler from merging, refetching or reordering the read.

No functional change intended.

Cc Alexander Viro <[email protected]>
---
 fs/buffer.c | 14 +++++---------
 1 file changed, 5 insertions(+), 9 deletions(-)
fs/buffer.c +5 -9
index 898c7f301b1b..23e1f0dcdbc4 100644
@@ -1464,19 +1464,15 @@ EXPORT_SYMBOL(set_bh_page);
 
 static void discard_buffer(struct buffer_head * bh)
 {
-	unsigned long b_state, b_state_old;
+	unsigned long b_state;
 
 	lock_buffer(bh);
 	clear_buffer_dirty(bh);
 	bh->b_bdev = NULL;
-	b_state = bh->b_state;
-	for (;;) {
-		b_state_old = cmpxchg(&bh->b_state, b_state,
-				      (b_state & ~BUFFER_FLAGS_DISCARD));
-		if (b_state_old == b_state)
-			break;
-		b_state = b_state_old;
-	}
+	b_state = READ_ONCE(bh->b_state);
+	do {
+	} while (!try_cmpxchg(&bh->b_state, &b_state,
+			      b_state & ~BUFFER_FLAGS_DISCARD));
 	unlock_buffer(bh);
 }
 
Signature · 1 line
2.35.3