Skip to contentSkip to conversation

fsnotify: Avoid data race between fsnotify_recalc_mask() and fsnotify_object_watched()

PATCH Superseded Jan Kara 1 participant 2 messages Jul 15, 2024

Subsystems (2)

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore

Jan Kara

author maintainer
#0 lore raw

PATCH 1/1 fsnotify: Avoid data race between fsnotify_recalc_mask() and fsnotify_object_watched()

When __fsnotify_recalc_mask() recomputes the mask on the watched object, the compiler can "optimize" the code to perform partial updates to the mask (including zeroing it at the beginning). Thus places checking the object mask without conn->lock such as fsnotify_object_watched() could see invalid states of the mask. Make sure the mask update is performed by one memory store using WRITE_ONCE().

---
 fs/notify/mark.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

I plan to merge this fix through my tree.

fs/notify/mark.c +5 -1
index c3eefa70633c..74a8a8ed42ff 100644
@@ -245,7 +245,11 @@ static void *__fsnotify_recalc_mask(struct fsnotify_mark_connector *conn)
 		    !(mark->flags & FSNOTIFY_MARK_FLAG_NO_IREF))
 			want_iref = true;
 	}
-	*fsnotify_conn_mask_p(conn) = new_mask;
+	/*
+	 * We use WRITE_ONCE() to prevent silly compiler optimizations from
+	 * confusing readers not holding conn->lock with partial updates.
+	 */
+	WRITE_ONCE(*fsnotify_conn_mask_p(conn), new_mask);
 
 	return fsnotify_update_iref(conn, want_iref);
 }
Signature · 1 line
2.35.3
author maintainer
#1 lore raw
Quoted 11 lines · Jan Kara

When __fsnotify_recalc_mask() recomputes the mask on the watched object, the compiler can "optimize" the code to perform partial updates to the mask (including zeroing it at the beginning). Thus places checking the object mask without conn->lock such as fsnotify_object_watched() could see invalid states of the mask. Make sure the mask update is performed by one memory store using WRITE_ONCE().

Apparently my brain is still in vacation mode and although this will probably be good enough to stop the data race from happening, it will not be probably good enough for KCSAN as WRITE_ONCE() should better be paired with READ_ONCE(). I'll send v2.

Honza

Quoted 26 lines
---
 fs/notify/mark.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

I plan to merge this fix through my tree.

fs/notify/mark.c +5 -1
index c3eefa70633c..74a8a8ed42ff 100644
@@ -245,7 +245,11 @@ static void *__fsnotify_recalc_mask(struct fsnotify_mark_connector *conn)
 		    !(mark->flags & FSNOTIFY_MARK_FLAG_NO_IREF))
 			want_iref = true;
 	}
-	*fsnotify_conn_mask_p(conn) = new_mask;
+	/*
+	 * We use WRITE_ONCE() to prevent silly compiler optimizations from
+	 * confusing readers not holding conn->lock with partial updates.
+	 */
+	WRITE_ONCE(*fsnotify_conn_mask_p(conn), new_mask);
 
 	return fsnotify_update_iref(conn, want_iref);
 }
Signature · 1 line
2.35.3
Signature · 2 lines
Jan Kara <[email protected]>
SUSE Labs, CR