Skip to contentSkip to conversation

fanotify: introduce response identifier

PATCH Superseded Ibrahim Jirdeh 2 participants 8 messages Jul 10, 2025

Subsystems (3)

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

v2 cover fanotify: introduce response identifier

These patches are in order to add an identifier other than fd which can be used to respond to fanotify permission events. This is useful for HSM use cases which are backed by a daemon to respond reliably
[1] and also for reporting pre-dir-content events without an event->fd [2]

The first few patches in the series are pulled in from Amir's work to add support for pre-dir-content events.

In terms of testing, there are some additional LTP test cases to go with these patches which exercise responding to events via response identifier
[3]

Changes v1 => v2:

Moved away from adding a unique event identifier, and instead overload event->fd to support a response identifier for now for FAN_REPORT_FID setting.

v1: https://lore.kernel.org/linux-fsdevel/[email protected]/

[1] https://lore.kernel.org/all/CAMp4zn8aXNPzq1i8KYmbRfwDBvO5Qefa4isSyS1bwYuvkuBsHg@mail.gmail.com/
[2] https://lore.kernel.org/linux-fsdevel/2dx3pbcnv5w75fxb2ghqtsk6gzl6cuxmd2rinzwbq7xxfjf5z7@3nqidi3mno46/
[3] https://github.com/ibrahim-jirdeh/ltp/commit/4cdb1ac3b22be7b332cc18ff193686f2be7ea69d

Amir Goldstein (2):
fanotify: add support for a variable length permission event
fanotify: allow pre-content events with fid info

Ibrahim Jirdeh (1):
fanotify: introduce event response identifier

 fs/notify/fanotify/fanotify.c       |  81 ++++++++---
 fs/notify/fanotify/fanotify.h       |  26 +++-
 fs/notify/fanotify/fanotify_user.c  | 201 +++++++++++++++++++---------
 include/linux/fanotify.h            |   3 +-
 include/linux/fsnotify_backend.h    |   2 +
 include/uapi/linux/fanotify.h       |  15 ++-
 tools/include/uapi/linux/fanotify.h |  15 ++-
 7 files changed, 249 insertions(+), 94 deletions(-)

--
2.47.1

#1 lore raw

PATCH v2 1/3 fanotify: add support for a variable length permission event

From: ibrahimjirdeh <[email protected]>

Summary:
From Amir Goldstein <[email protected]>

In preparation for pre-content events that report fid info + name, we need a new event type that is both variable length and can be put on a user response wait list.

Create an event type FANOTIFY_EVENT_TYPE_FID_NAME_PERM with is a combination of the variable length fanotify_name_event prefixed with a fix length fanotify_perm_event and they share the common fanotify_event memeber.

---
 fs/notify/fanotify/fanotify.c | 76 +++++++++++++++++++++++++++--------
 fs/notify/fanotify/fanotify.h | 19 ++++++---
 2 files changed, 74 insertions(+), 21 deletions(-)
fs/notify/fanotify/fanotify.c +60 -16
index 3083643b864b..34acb7c16e8b 100644
@@ -454,7 +454,13 @@ static int fanotify_encode_fh(struct fanotify_fh *fh, struct inode *inode,
 	dwords = fh_len >> 2;
 	type = exportfs_encode_fid(inode, buf, &dwords);
 	err = -EINVAL;
-	if (type <= 0 || type == FILEID_INVALID || fh_len != dwords << 2)
+	/*
+	 * Unlike file_handle, type and len of struct fanotify_fh are u8.
+	 * Traditionally, filesystem return handle_type < 0xff, but there
+	 * is no enforecement for that in vfs.
+	 */
+	BUILD_BUG_ON(MAX_HANDLE_SZ > 0xff || FILEID_INVALID > 0xff);
+	if (type <= 0 || type >= FILEID_INVALID || fh_len != dwords << 2)
 		goto out_err;
 
 	fh->type = type;
@@ -576,20 +582,13 @@ static struct fanotify_event *fanotify_alloc_mnt_event(u64 mnt_id, gfp_t gfp)
 	return &pevent->fae;
 }
 
-static struct fanotify_event *fanotify_alloc_perm_event(const void *data,
-							int data_type,
-							gfp_t gfp)
+static void fanotify_init_perm_event(struct fanotify_perm_event *pevent,
+				     const void *data, int data_type)
 {
 	const struct path *path = fsnotify_data_path(data, data_type);
 	const struct file_range *range =
 			    fsnotify_data_file_range(data, data_type);
-	struct fanotify_perm_event *pevent;
-
-	pevent = kmem_cache_alloc(fanotify_perm_event_cachep, gfp);
-	if (!pevent)
-		return NULL;
 
-	pevent->fae.type = FANOTIFY_EVENT_TYPE_PATH_PERM;
 	pevent->response = 0;
 	pevent->hdr.type = FAN_RESPONSE_INFO_NONE;
 	pevent->hdr.pad = 0;
@@ -600,6 +599,20 @@ static struct fanotify_event *fanotify_alloc_perm_event(const void *data,
 	pevent->ppos = range ? &range->pos : NULL;
 	pevent->count = range ? range->count : 0;
 	path_get(path);
+}
+
+static struct fanotify_event *fanotify_alloc_perm_event(const void *data,
+							int data_type,
+							gfp_t gfp)
+{
+	struct fanotify_perm_event *pevent;
+
+	pevent = kmem_cache_alloc(fanotify_perm_event_cachep, gfp);
+	if (!pevent)
+		return NULL;
+
+	pevent->fae.type = FANOTIFY_EVENT_TYPE_PATH_PERM;
+	fanotify_init_perm_event(pevent, data, data_type);
 
 	return &pevent->fae;
 }
@@ -630,11 +643,12 @@ static struct fanotify_event *fanotify_alloc_name_event(struct inode *dir,
 							struct inode *child,
 							struct dentry *moved,
 							unsigned int *hash,
-							gfp_t gfp)
+							gfp_t gfp, bool perm)
 {
 	struct fanotify_name_event *fne;
 	struct fanotify_info *info;
 	struct fanotify_fh *dfh, *ffh;
+	struct fanotify_perm_event *pevent;
 	struct inode *dir2 = moved ? d_inode(moved->d_parent) : NULL;
 	const struct qstr *name2 = moved ? &moved->d_name : NULL;
 	unsigned int dir_fh_len = fanotify_encode_fh_len(dir);
@@ -652,11 +666,26 @@ static struct fanotify_event *fanotify_alloc_name_event(struct inode *dir,
 		size += FANOTIFY_FH_HDR_LEN + dir2_fh_len;
 	if (child_fh_len)
 		size += FANOTIFY_FH_HDR_LEN + child_fh_len;
+	if (perm) {
+		BUILD_BUG_ON(offsetof(struct fanotify_perm_event, fae) +
+			     sizeof(struct fanotify_event) != sizeof(*pevent));
+		size += offsetof(struct fanotify_perm_event, fae);
+	}
 	fne = kmalloc(size, gfp);
 	if (!fne)
 		return NULL;
 
-	fne->fae.type = FANOTIFY_EVENT_TYPE_FID_NAME;
+	/*
+	 * fanotify_name_event follows fanotify_perm_event and they share the
+	 * fae member.
+	 */
+	if (perm) {
+		pevent = (void *)fne;
+		fne = FANOTIFY_NE(&pevent->fae);
+		fne->fae.type = FANOTIFY_EVENT_TYPE_FID_NAME_PERM;
+	} else {
+		fne->fae.type = FANOTIFY_EVENT_TYPE_FID_NAME;
+	}
 	fne->fsid = *fsid;
 	*hash ^= fanotify_hash_fsid(fsid);
 	info = &fne->info;
@@ -751,6 +780,7 @@ static struct fanotify_event *fanotify_alloc_event(
 	struct inode *dirid = fanotify_dfid_inode(mask, data, data_type, dir);
 	const struct path *path = fsnotify_data_path(data, data_type);
 	u64 mnt_id = fsnotify_data_mnt_id(data, data_type);
+	bool perm = fanotify_is_perm_event(mask);
 	struct mem_cgroup *old_memcg;
 	struct dentry *moved = NULL;
 	struct inode *child = NULL;
@@ -836,14 +866,18 @@ static struct fanotify_event *fanotify_alloc_event(
 	/* Whoever is interested in the event, pays for the allocation. */
 	old_memcg = set_active_memcg(group->memcg);
 
-	if (fanotify_is_perm_event(mask)) {
+	if (name_event && (file_name || moved || child || perm)) {
+		event = fanotify_alloc_name_event(dirid, fsid, file_name, child,
+						  moved, &hash, gfp, perm);
+		if (event && perm) {
+			fanotify_init_perm_event(FANOTIFY_PERM(event),
+						 data, data_type);
+		}
+	} else if (perm) {
 		event = fanotify_alloc_perm_event(data, data_type, gfp);
 	} else if (fanotify_is_error_event(mask)) {
 		event = fanotify_alloc_error_event(group, fsid, data,
 						   data_type, &hash);
-	} else if (name_event && (file_name || moved || child)) {
-		event = fanotify_alloc_name_event(dirid, fsid, file_name, child,
-						  moved, &hash, gfp);
 	} else if (fid_mode) {
 		event = fanotify_alloc_fid_event(id, fsid, &hash, gfp);
 	} else if (path) {
@@ -1031,6 +1065,13 @@ static void fanotify_free_perm_event(struct fanotify_event *event)
 	kmem_cache_free(fanotify_perm_event_cachep, FANOTIFY_PERM(event));
 }
 
+static void fanotify_free_name_perm_event(struct fanotify_event *event)
+{
+	path_put(fanotify_event_path(event));
+	/* Variable length perm event */
+	kfree(FANOTIFY_PERM(event));
+}
+
 static void fanotify_free_fid_event(struct fanotify_event *event)
 {
 	struct fanotify_fid_event *ffe = FANOTIFY_FE(event);
@@ -1078,6 +1119,9 @@ static void fanotify_free_event(struct fsnotify_group *group,
 	case FANOTIFY_EVENT_TYPE_FID_NAME:
 		fanotify_free_name_event(event);
 		break;
+	case FANOTIFY_EVENT_TYPE_FID_NAME_PERM:
+		fanotify_free_name_perm_event(event);
+		break;
 	case FANOTIFY_EVENT_TYPE_OVERFLOW:
 		kfree(event);
 		break;
fs/notify/fanotify/fanotify.h +14 -5
index b78308975082..f6d25fcf8692 100644
@@ -240,6 +240,7 @@ static inline void fanotify_info_copy_name2(struct fanotify_info *info,
 enum fanotify_event_type {
 	FANOTIFY_EVENT_TYPE_FID, /* fixed length */
 	FANOTIFY_EVENT_TYPE_FID_NAME, /* variable length */
+	FANOTIFY_EVENT_TYPE_FID_NAME_PERM, /* variable length perm event */
 	FANOTIFY_EVENT_TYPE_PATH,
 	FANOTIFY_EVENT_TYPE_PATH_PERM,
 	FANOTIFY_EVENT_TYPE_OVERFLOW, /* struct fanotify_event */
@@ -326,7 +327,8 @@ static inline __kernel_fsid_t *fanotify_event_fsid(struct fanotify_event *event)
 {
 	if (event->type == FANOTIFY_EVENT_TYPE_FID)
 		return &FANOTIFY_FE(event)->fsid;
-	else if (event->type == FANOTIFY_EVENT_TYPE_FID_NAME)
+	else if (event->type == FANOTIFY_EVENT_TYPE_FID_NAME ||
+		 event->type == FANOTIFY_EVENT_TYPE_FID_NAME_PERM)
 		return &FANOTIFY_NE(event)->fsid;
 	else if (event->type == FANOTIFY_EVENT_TYPE_FS_ERROR)
 		return &FANOTIFY_EE(event)->fsid;
@@ -339,7 +341,8 @@ static inline struct fanotify_fh *fanotify_event_object_fh(
 {
 	if (event->type == FANOTIFY_EVENT_TYPE_FID)
 		return &FANOTIFY_FE(event)->object_fh;
-	else if (event->type == FANOTIFY_EVENT_TYPE_FID_NAME)
+	else if (event->type == FANOTIFY_EVENT_TYPE_FID_NAME ||
+		 event->type == FANOTIFY_EVENT_TYPE_FID_NAME_PERM)
 		return fanotify_info_file_fh(&FANOTIFY_NE(event)->info);
 	else if (event->type == FANOTIFY_EVENT_TYPE_FS_ERROR)
 		return &FANOTIFY_EE(event)->object_fh;
@@ -350,7 +353,8 @@ static inline struct fanotify_fh *fanotify_event_object_fh(
 static inline struct fanotify_info *fanotify_event_info(
 						struct fanotify_event *event)
 {
-	if (event->type == FANOTIFY_EVENT_TYPE_FID_NAME)
+	if (event->type == FANOTIFY_EVENT_TYPE_FID_NAME ||
+	    event->type == FANOTIFY_EVENT_TYPE_FID_NAME_PERM)
 		return &FANOTIFY_NE(event)->info;
 	else
 		return NULL;
@@ -435,7 +439,6 @@ FANOTIFY_ME(struct fanotify_event *event)
  * user response.
  */
 struct fanotify_perm_event {
-	struct fanotify_event fae;
 	struct path path;
 	const loff_t *ppos;		/* optional file range info */
 	size_t count;
@@ -446,6 +449,11 @@ struct fanotify_perm_event {
 		struct fanotify_response_info_header hdr;
 		struct fanotify_response_info_audit_rule audit_rule;
 	};
+	/*
+	 * Overlaps with fanotify_name_event::fae when type is
+	 * FANOTIFY_EVENT_TYPE_FID_NAME_PERM - Keep at the end!
+	 */
+	struct fanotify_event fae;
 };
 
 static inline struct fanotify_perm_event *
@@ -487,7 +495,8 @@ static inline const struct path *fanotify_event_path(struct fanotify_event *even
 {
 	if (event->type == FANOTIFY_EVENT_TYPE_PATH)
 		return &FANOTIFY_PE(event)->path;
-	else if (event->type == FANOTIFY_EVENT_TYPE_PATH_PERM)
+	else if (event->type == FANOTIFY_EVENT_TYPE_PATH_PERM ||
+		 event->type == FANOTIFY_EVENT_TYPE_FID_NAME_PERM)
 		return &FANOTIFY_PERM(event)->path;
 	else
 		return NULL;
Signature · 1 line
2.47.1
#2 lore raw

PATCH v2 2/3 fanotify: allow pre-content events with fid info

In reply to Ibrahim Jirdeh

From: ibrahimjirdeh <[email protected]>

Summary:
From Amir Goldstein <[email protected]>

Until now, the high priority classes (FAN_CLASS_*CONTENT), which are required for permission and pre-content events, were not allowed to report events with fid info.

This is partly because the event->fd is used as a key for the the permission response and partly because we needed to chose between allocating a permission event of fid event struct.

Allow reporting fid info with pre-content class with some restrictions:
1. Only pre-content events are allowed with such groups
2. No event flags are allowed (i.e. FAN_EVENT_ON_CHILD)

The flag FAN_EVENT_ON_CHILD is anyway ignored on sb/mount marks and on an non-dir inode mark.

On a directory inode mark, FAN_PRE_ACCESS makes no sense without FAN_EVENT_ON_CHILD, so in this case, this flag is implied.

---
 fs/notify/fanotify/fanotify_user.c  | 70 ++++++++++++++++++++++-------
 include/linux/fsnotify_backend.h    |  1 +
 include/uapi/linux/fanotify.h       |  4 +-
 tools/include/uapi/linux/fanotify.h |  4 +-
 4 files changed, 62 insertions(+), 17 deletions(-)
fs/notify/fanotify/fanotify_user.c +55 -15
index b192ee068a7a..19d3f2d914fe 100644
@@ -353,7 +353,7 @@ static int process_access_response(struct fsnotify_group *group,
 		break;
 	case FAN_DENY:
 		/* Custom errno is supported only for pre-content groups */
-		if (errno && group->priority != FSNOTIFY_PRIO_PRE_CONTENT)
+		if (errno && group->priority < FSNOTIFY_PRIO_PRE_CONTENT)
 			return -EINVAL;
 
 		/*
@@ -1383,6 +1383,16 @@ static int fanotify_group_init_error_pool(struct fsnotify_group *group)
 					 sizeof(struct fanotify_error_event));
 }
 
+/* Check for forbidden events/flags combinations */
+static bool fanotify_mask_is_valid(__u64 mask)
+{
+	/* Pre-content events do not support event flags */
+	if (mask & FANOTIFY_PRE_CONTENT_EVENTS && mask & FAN_ONDIR)
+		return false;
+
+	return true;
+}
+
 static int fanotify_may_update_existing_mark(struct fsnotify_mark *fsn_mark,
 					     __u32 mask, unsigned int fan_flags)
 {
@@ -1411,9 +1421,9 @@ static int fanotify_may_update_existing_mark(struct fsnotify_mark *fsn_mark,
 	    fsn_mark->flags & FSNOTIFY_MARK_FLAG_IGNORED_SURV_MODIFY)
 		return -EEXIST;
 
-	/* For now pre-content events are not generated for directories */
+	/* Check for forbidden event combinations after update */
 	mask |= fsn_mark->mask;
-	if (mask & FANOTIFY_PRE_CONTENT_EVENTS && mask & FAN_ONDIR)
+	if (!fanotify_mask_is_valid(mask))
 		return -EEXIST;
 
 	return 0;
@@ -1564,7 +1574,13 @@ SYSCALL_DEFINE2(fanotify_init, unsigned int, flags, unsigned int, event_f_flags)
 		return -EINVAL;
 	}
 
-	if (fid_mode && class != FAN_CLASS_NOTIF)
+	/*
+	 * Async events support any fid report mode.
+	 * Permission events do not support any fid report mode.
+	 * Pre-content events support only FAN_REPORT_DFID_NAME_TARGET mode.
+	 */
+	if (fid_mode && class != FAN_CLASS_NOTIF &&
+	    (class | fid_mode) != FAN_CLASS_PRE_CONTENT_FID)
 		return -EINVAL;
 
 	/*
@@ -1633,7 +1649,12 @@ SYSCALL_DEFINE2(fanotify_init, unsigned int, flags, unsigned int, event_f_flags)
 		group->priority = FSNOTIFY_PRIO_CONTENT;
 		break;
 	case FAN_CLASS_PRE_CONTENT:
-		group->priority = FSNOTIFY_PRIO_PRE_CONTENT;
+		/*
+		 * FAN_CLASS_PRE_CONTENT_FID is exclusively for pre-content
+		 * events, so it gets a higher priority.
+		 */
+		group->priority = fid_mode ? FSNOTIFY_PRIO_PRE_CONTENT_FID :
+					     FSNOTIFY_PRIO_PRE_CONTENT;
 		break;
 	default:
 		fd = -EINVAL;
@@ -1750,6 +1771,9 @@ static int fanotify_events_supported(struct fsnotify_group *group,
 				 (mask & FAN_RENAME) ||
 				 (flags & FAN_MARK_IGNORE);
 
+	if (!fanotify_mask_is_valid(mask))
+		return -EINVAL;
+
 	/*
 	 * Filesystems need to opt-into pre-content evnets (a.k.a HSM)
 	 * and they are only supported on regular files and directories.
@@ -1911,13 +1935,27 @@ static int do_fanotify_mark(int fanotify_fd, unsigned int flags, __u64 mask,
 	/*
 	 * Permission events are not allowed for FAN_CLASS_NOTIF.
 	 * Pre-content permission events are not allowed for FAN_CLASS_CONTENT.
+	 * Only pre-content events are allowed for FAN_CLASS_PRE_CONTENT_FID.
 	 */
-	if (mask & FANOTIFY_PERM_EVENTS &&
-	    group->priority == FSNOTIFY_PRIO_NORMAL)
-		return -EINVAL;
-	else if (mask & FANOTIFY_PRE_CONTENT_EVENTS &&
-		 group->priority == FSNOTIFY_PRIO_CONTENT)
+	fid_mode = FAN_GROUP_FLAG(group, FANOTIFY_FID_BITS);
+	switch (group->priority) {
+	case FSNOTIFY_PRIO_NORMAL:
+		if (mask & FANOTIFY_PERM_EVENTS)
+			return -EINVAL;
+		break;
+	case FSNOTIFY_PRIO_CONTENT:
+		if (mask & FANOTIFY_PRE_CONTENT_EVENTS)
+			return -EINVAL;
+		break;
+	case FSNOTIFY_PRIO_PRE_CONTENT:
+		break;
+	case FSNOTIFY_PRIO_PRE_CONTENT_FID:
+		if (mask & ~FANOTIFY_PRE_CONTENT_EVENTS)
+			return -EINVAL;
+		break;
+	default:
 		return -EINVAL;
+	}
 
 	if (mask & FAN_FS_ERROR &&
 	    mark_type != FAN_MARK_FILESYSTEM)
@@ -1938,7 +1976,6 @@ static int do_fanotify_mark(int fanotify_fd, unsigned int flags, __u64 mask,
 	 * carry enough information (i.e. path) to be filtered by mount
 	 * point.
 	 */
-	fid_mode = FAN_GROUP_FLAG(group, FANOTIFY_FID_BITS);
 	if (mask & ~(FANOTIFY_FD_EVENTS|FANOTIFY_MOUNT_EVENTS|FANOTIFY_EVENT_FLAGS) &&
 	    (!fid_mode || mark_type == FAN_MARK_MOUNT))
 		return -EINVAL;
@@ -1951,10 +1988,6 @@ static int do_fanotify_mark(int fanotify_fd, unsigned int flags, __u64 mask,
 	if (mask & FAN_RENAME && !(fid_mode & FAN_REPORT_NAME))
 		return -EINVAL;
 
-	/* Pre-content events are not currently generated for directories. */
-	if (mask & FANOTIFY_PRE_CONTENT_EVENTS && mask & FAN_ONDIR)
-		return -EINVAL;
-
 	if (mark_cmd == FAN_MARK_FLUSH) {
 		fsnotify_clear_marks_by_group(group, obj_type);
 		return 0;
@@ -2041,6 +2074,13 @@ static int do_fanotify_mark(int fanotify_fd, unsigned int flags, __u64 mask,
 		if ((fid_mode & FAN_REPORT_DIR_FID) &&
 		    (flags & FAN_MARK_ADD) && !ignore)
 			mask |= FAN_EVENT_ON_CHILD;
+	} else if (fid_mode && (mask & FANOTIFY_PRE_CONTENT_EVENTS)) {
+		/*
+		 * Pre-content events on directory inode mask implies that
+		 * we are watching access to children.
+		 */
+		mask |= FAN_EVENT_ON_CHILD;
+		umask = FAN_EVENT_ON_CHILD;
 	}
 
 	/* create/update an inode mark */
include/linux/fsnotify_backend.h +1 -0
index d4034ddaf392..832d94d783d9 100644
@@ -201,6 +201,7 @@ enum fsnotify_group_prio {
 	FSNOTIFY_PRIO_NORMAL = 0,	/* normal notifiers, no permissions */
 	FSNOTIFY_PRIO_CONTENT,		/* fanotify permission events */
 	FSNOTIFY_PRIO_PRE_CONTENT,	/* fanotify pre-content events */
+	FSNOTIFY_PRIO_PRE_CONTENT_FID,	/* fanotify pre-content events with fid */
 	__FSNOTIFY_PRIO_NUM
 };
 
include/uapi/linux/fanotify.h +3 -1
index e710967c7c26..3201d8d6c51a 100644
@@ -73,7 +73,9 @@
 /* Convenience macro - FAN_REPORT_TARGET_FID requires all other FID flags */
 #define FAN_REPORT_DFID_NAME_TARGET (FAN_REPORT_DFID_NAME | \
 				     FAN_REPORT_FID | FAN_REPORT_TARGET_FID)
-
+/* Convenience macro - FAN_CLASS_PRE_CONTENT requires all or no FID flags */
+#define FAN_CLASS_PRE_CONTENT_FID   (FAN_CLASS_PRE_CONTENT | \
+	FAN_REPORT_DFID_NAME_TARGET)
 /* Deprecated - do not use this in programs and do not add new flags here! */
 #define FAN_ALL_INIT_FLAGS	(FAN_CLOEXEC | FAN_NONBLOCK | \
 				 FAN_ALL_CLASS_BITS | FAN_UNLIMITED_QUEUE |\
tools/include/uapi/linux/fanotify.h +3 -1
index e710967c7c26..3201d8d6c51a 100644
@@ -73,7 +73,9 @@
 /* Convenience macro - FAN_REPORT_TARGET_FID requires all other FID flags */
 #define FAN_REPORT_DFID_NAME_TARGET (FAN_REPORT_DFID_NAME | \
 				     FAN_REPORT_FID | FAN_REPORT_TARGET_FID)
-
+/* Convenience macro - FAN_CLASS_PRE_CONTENT requires all or no FID flags */
+#define FAN_CLASS_PRE_CONTENT_FID   (FAN_CLASS_PRE_CONTENT | \
+	FAN_REPORT_DFID_NAME_TARGET)
 /* Deprecated - do not use this in programs and do not add new flags here! */
 #define FAN_ALL_INIT_FLAGS	(FAN_CLOEXEC | FAN_NONBLOCK | \
 				 FAN_ALL_CLASS_BITS | FAN_UNLIMITED_QUEUE |\
Signature · 1 line
2.47.1
#3 lore raw

PATCH v2 3/3 fanotify: introduce event response identifier

In reply to Ibrahim Jirdeh

From: ibrahimjirdeh <[email protected]>

Summary:
This adds support for responding to events via response identifier. This prevents races if there are multiple processes backing the same fanotify group (eg. handover of fanotify group to new instance of a backing daemon). It is also useful for reporting pre-dir-content events without an event->fd:
https://lore.kernel.org/linux-fsdevel/2dx3pbcnv5w75fxb2ghqtsk6gzl6cuxmd2rinzwbq7xxfjf5z7@3nqidi3mno46/.

Rather than introducing a new event identifier field and extending fanotify_event_metadata, we have opted to overload event->fd and restrict this functionality to use-cases which are using file handle apis (FAN_REPORT_FID).

In terms of how response ids are allocated, we use an idr for allocation and restrict the id range to below -255 to ensure there is no overlap with existing fd-as-identifier usage. We can also leverage the added idr for more efficient lookup when handling response although that is not done in this patch.

---
 fs/notify/fanotify/fanotify.c       |   3 +
 fs/notify/fanotify/fanotify.h       |   5 +-
 fs/notify/fanotify/fanotify_user.c  | 129 ++++++++++++++++++----------
 include/linux/fanotify.h            |   3 +-
 include/linux/fsnotify_backend.h    |   1 +
 include/uapi/linux/fanotify.h       |  11 ++-
 tools/include/uapi/linux/fanotify.h |  11 ++-
 7 files changed, 110 insertions(+), 53 deletions(-)
fs/notify/fanotify/fanotify.c +3 -0
index 34acb7c16e8b..d9aebd359199 100644
@@ -1106,6 +1106,9 @@ static void fanotify_free_event(struct fsnotify_group *group,
 
 	event = FANOTIFY_E(fsn_event);
 	put_pid(event->pid);
+	if (fanotify_is_perm_event(event->mask) &&
+	    FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID))
+		idr_remove(&group->response_idr, -FANOTIFY_PERM(event)->id);
 	switch (event->type) {
 	case FANOTIFY_EVENT_TYPE_PATH:
 		fanotify_free_path_event(event);
fs/notify/fanotify/fanotify.h +4 -1
index f6d25fcf8692..8d62321237d6 100644
@@ -444,7 +444,10 @@ struct fanotify_perm_event {
 	size_t count;
 	u32 response;			/* userspace answer to the event */
 	unsigned short state;		/* state of the event */
-	int fd;		/* fd we passed to userspace for this event */
+	union {
+		__s32 fd;			/* fd we passed to userspace for this event */
+		__s32 id;			/* FAN_REPORT_RESPONSE_ID */
+	};
 	union {
 		struct fanotify_response_info_header hdr;
 		struct fanotify_response_info_audit_rule audit_rule;
fs/notify/fanotify/fanotify_user.c +82 -47

197 lines not on this page · raw message

include/linux/fanotify.h +2 -1
index 879cff5eccd4..4463fcfd16bb 100644
@@ -38,7 +38,8 @@
 					 FAN_REPORT_PIDFD | \
 					 FAN_REPORT_FD_ERROR | \
 					 FAN_UNLIMITED_QUEUE | \
-					 FAN_UNLIMITED_MARKS)
+					 FAN_UNLIMITED_MARKS | \
+					 FAN_REPORT_RESPONSE_ID)
 
 /*
  * fanotify_init() flags that are allowed for user without CAP_SYS_ADMIN.
include/linux/fsnotify_backend.h +1 -0
index 832d94d783d9..83c82331866b 100644
@@ -232,6 +232,7 @@ struct fsnotify_group {
 	unsigned int max_events;		/* maximum events allowed on the list */
 	enum fsnotify_group_prio priority;	/* priority for sending events */
 	bool shutdown;		/* group is being shut down, don't queue more events */
+	struct idr response_idr; /* used for response id allocation */
 
 #define FSNOTIFY_GROUP_USER	0x01 /* user allocated group */
 #define FSNOTIFY_GROUP_DUPS	0x02 /* allow multiple marks per object */
include/uapi/linux/fanotify.h +9 -2
index 3201d8d6c51a..04bbbfb5f7f3 100644
@@ -67,6 +67,7 @@
 #define FAN_REPORT_TARGET_FID	0x00001000	/* Report dirent target id  */
 #define FAN_REPORT_FD_ERROR	0x00002000	/* event->fd can report error */
 #define FAN_REPORT_MNT		0x00004000	/* Report mount events */
+#define FAN_REPORT_RESPONSE_ID		0x00008000 /* event->fd is a response id */
 
 /* Convenience macro - FAN_REPORT_NAME requires FAN_REPORT_DIR_FID */
 #define FAN_REPORT_DFID_NAME	(FAN_REPORT_DIR_FID | FAN_REPORT_NAME)
@@ -143,7 +144,10 @@ struct fanotify_event_metadata {
 	__u8 reserved;
 	__u16 metadata_len;
 	__aligned_u64 mask;
-	__s32 fd;
+	union {
+		__s32 fd;
+		__s32 id; /* FAN_REPORT_RESPONSE_ID */
+	};
 	__s32 pid;
 };
 
@@ -227,7 +231,10 @@ struct fanotify_event_info_mnt {
 #define FAN_RESPONSE_INFO_AUDIT_RULE	1
 
 struct fanotify_response {
-	__s32 fd;
+	union {
+		__s32 fd;
+		__s32 id; /* FAN_REPORT_RESPONSE_ID */
+	};
 	__u32 response;
 };
 
tools/include/uapi/linux/fanotify.h +9 -2
index 3201d8d6c51a..04bbbfb5f7f3 100644
@@ -67,6 +67,7 @@
 #define FAN_REPORT_TARGET_FID	0x00001000	/* Report dirent target id  */
 #define FAN_REPORT_FD_ERROR	0x00002000	/* event->fd can report error */
 #define FAN_REPORT_MNT		0x00004000	/* Report mount events */
+#define FAN_REPORT_RESPONSE_ID		0x00008000 /* event->fd is a response id */
 
 /* Convenience macro - FAN_REPORT_NAME requires FAN_REPORT_DIR_FID */
 #define FAN_REPORT_DFID_NAME	(FAN_REPORT_DIR_FID | FAN_REPORT_NAME)
@@ -143,7 +144,10 @@ struct fanotify_event_metadata {
 	__u8 reserved;
 	__u16 metadata_len;
 	__aligned_u64 mask;
-	__s32 fd;
+	union {
+		__s32 fd;
+		__s32 id; /* FAN_REPORT_RESPONSE_ID */
+	};
 	__s32 pid;
 };
 
@@ -227,7 +231,10 @@ struct fanotify_event_info_mnt {
 #define FAN_RESPONSE_INFO_AUDIT_RULE	1
 
 struct fanotify_response {
-	__s32 fd;
+	union {
+		__s32 fd;
+		__s32 id; /* FAN_REPORT_RESPONSE_ID */
+	};
 	__u32 response;
 };
 
Signature · 1 line
2.47.1
#4 lore raw

Re: [PATCH 3/3] [PATCH v2 3/3] fanotify: introduce event response identifier

Quoted 4 lines · Ibrahim Jirdeh

From: ibrahimjirdeh <[email protected]>

Summary:

Formatting issue.

Quoted 50 lines

This adds support for responding to events via response identifier. This prevents races if there are multiple processes backing the same fanotify group (eg. handover of fanotify group to new instance of a backing daemon). It is also useful for reporting pre-dir-content events without an event->fd:
https://lore.kernel.org/linux-fsdevel/2dx3pbcnv5w75fxb2ghqtsk6gzl6cuxmd2rinzwbq7xxfjf5z7@3nqidi3mno46/.

Rather than introducing a new event identifier field and extending fanotify_event_metadata, we have opted to overload event->fd and restrict this functionality to use-cases which are using file handle apis (FAN_REPORT_FID).

In terms of how response ids are allocated, we use an idr for allocation and restrict the id range to below -255 to ensure there is no overlap with existing fd-as-identifier usage. We can also leverage the added idr for more efficient lookup when handling response although that is not done in this patch.

---
 fs/notify/fanotify/fanotify.c       |   3 +
 fs/notify/fanotify/fanotify.h       |   5 +-
 fs/notify/fanotify/fanotify_user.c  | 129 ++++++++++++++++++----------
 include/linux/fanotify.h            |   3 +-
 include/linux/fsnotify_backend.h    |   1 +
 include/uapi/linux/fanotify.h       |  11 ++-
 tools/include/uapi/linux/fanotify.h |  11 ++-
 7 files changed, 110 insertions(+), 53 deletions(-)
fs/notify/fanotify/fanotify.c +3 -0
index 34acb7c16e8b..d9aebd359199 100644
@@ -1106,6 +1106,9 @@ static void fanotify_free_event(struct fsnotify_group *group,
 
        event = FANOTIFY_E(fsn_event);
        put_pid(event->pid);
+       if (fanotify_is_perm_event(event->mask) &&
+           FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID))
+               idr_remove(&group->response_idr, -FANOTIFY_PERM(event)->id);
        switch (event->type) {
        case FANOTIFY_EVENT_TYPE_PATH:
                fanotify_free_path_event(event);
fs/notify/fanotify/fanotify.h +0 -0
index f6d25fcf8692..8d62321237d6 100644

fs/notify/fanotify/fanotify.h struct fanotify_perm_event { · line 450

Quoted 8 lines
fs/notify/fanotify/fanotify.h +4 -1
@@ -444,7 +444,10 @@ struct fanotify_perm_event {
        size_t count;
        u32 response;                   /* userspace answer to the event */
        unsigned short state;           /* state of the event */
-       int fd;         /* fd we passed to userspace for this event */
+       union {
+               __s32 fd;                       /* fd we passed to userspace for this event */
+               __s32 id;                       /* FAN_REPORT_RESPONSE_ID */
+       };

That's an "int" and I don't think that we need a union in this internal context. int id; /* id we passed to userspace for this event */
is always correct, whether the id is also an fd or not.

Quoted 8 lines
fs/notify/fanotify/fanotify.h +0 -0
        union {
                struct fanotify_response_info_header hdr;
                struct fanotify_response_info_audit_rule audit_rule;
fs/notify/fanotify/fanotify_user.c +0 -0
index 19d3f2d914fe..b033f86e0db3 100644

fs/notify/fanotify/fanotify_user.c static int process_access_response(struct fsnotify_group *group, · line 335

Quoted 7 lines
fs/notify/fanotify/fanotify_user.c +3 -1
@@ -330,14 +330,16 @@ static int process_access_response(struct fsnotify_group *group,
                                   size_t info_len)
 {
        struct fanotify_perm_event *event;
-       int fd = response_struct->fd;
+       int id = FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID) ?
+                        response_struct->id :
+                        response_struct->fd;

Not needed. Can always use int id = response_struct->id; it is never used as an actual fd in this context. But this function would be a good place to add:

BUILD_BUG_ON(sizeof(response_struct->id) != sizeof(response_struct->fd)); BUILD_BUG_ON(offsetof(struct fanotity_response, id) != offsetof(struct fanotify_repose, fd));

to make sure that code can use either alternative safely.

Quoted 18 lines
fs/notify/fanotify/fanotify_user.c +3 -3
        u32 response = response_struct->response;
        int errno = fanotify_get_response_errno(response);
        int ret = info_len;
        struct fanotify_response_info_audit_rule friar;
 
-       pr_debug("%s: group=%p fd=%d response=%x errno=%d buf=%p size=%zu\n",
-                __func__, group, fd, response, errno, info, info_len);
+       pr_debug("%s: group=%p id=%d response=%x errno=%d buf=%p size=%zu\n",
+                __func__, group, id, response, errno, info, info_len);
        /*
         * make sure the response is valid, if invalid we do nothing and either
         * userspace can send a valid response or we will clean it up after the
@@ -385,19 +387,24 @@ static int process_access_response(struct fsnotify_group *group,
                ret = process_access_response_info(info, info_len, &friar);
                if (ret < 0)
                        return ret;
-               if (fd == FAN_NOFD)
+               if (id == FAN_NOFD)

fs/notify/fanotify/fanotify_user.c static int process_access_response(struct fsnotify_group *group, · line 399

Quoted 10 lines
fs/notify/fanotify/fanotify_user.c +3 -1
                        return ret;
        } else {
                ret = 0;
        }
+       if (FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID) && id >= -255)
+               return -EINVAL;
 
-       if (fd < 0)
+       if (!FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID) && id < 0)
                return -EINVAL;

Please use helper for both cases above:
static inline fanotify_is_valid_response_id(struct fsnotify_group *group, int id)

fs/notify/fanotify/fanotify_user.c static int process_access_response(struct fsnotify_group *group, · line 407

Quoted 9 lines
fs/notify/fanotify/fanotify_user.c +4 -1
        spin_lock(&group->notification_lock);
        list_for_each_entry(event, &group->fanotify_data.access_list,
                            fae.fse.list) {
-               if (event->fd != fd)
+               int other_id = FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID) ?
+                                      event->id :
+                                      event->fd;
+               if (other_id != id)

No need. can use if (event->id != id)

Quoted 13 lines
fs/notify/fanotify/fanotify_user.c +0 -6
                        continue;
 
                list_del_init(&event->fae.fse.list);
@@ -765,48 +772,58 @@ static ssize_t copy_event_to_user(struct fsnotify_group *group,
            task_tgid(current) != event->pid)
                metadata.pid = 0;
 
-       /*
-        * For now, fid mode is required for an unprivileged listener and
-        * fid mode does not report fd in events.  Keep this check anyway
-        * for safety in case fid mode requirement is relaxed in the future
-        * to allow unprivileged listener to get events with no fd and no fid.
-        */

fs/notify/fanotify/fanotify_user.c static ssize_t copy_event_to_user(struct fsnotify_group *group, · line 781

Quoted 10 lines
fs/notify/fanotify/fanotify_user.c +7 -3
-       if (!FAN_GROUP_FLAG(group, FANOTIFY_UNPRIV) &&
-           path && path->mnt && path->dentry) {
-               fd = create_fd(group, path, &f);
+       if (FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID)) {
+               ret = idr_alloc_cyclic(&group->response_idr, event, 256, INT_MAX,
+                                      GFP_NOWAIT);
+               if (ret < 0)
+                       return ret;
+               metadata.id = -ret;
+       } else {

Please avoid this unneeded churn and unneeded nesting:

+ if (FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID)) {
...
+ } else if (!FAN_GROUP_FLAG(group, FANOTIFY_UNPRIV) && ...

And I would assign fd = -ret; to make the code below simpler...

Quoted 64 lines
fs/notify/fanotify/fanotify_user.c +36 -24
                /*
-                * Opening an fd from dentry can fail for several reasons.
-                * For example, when tasks are gone and we try to open their
-                * /proc files or we try to open a WRONLY file like in sysfs
-                * or when trying to open a file that was deleted on the
-                * remote network server.
-                *
-                * For a group with FAN_REPORT_FD_ERROR, we will send the
-                * event with the error instead of the open fd, otherwise
-                * Userspace may not get the error at all.
-                * In any case, userspace will not know which file failed to
-                * open, so add a debug print for further investigation.
+                * For now, fid mode is required for an unprivileged listener and
+                * fid mode does not report fd in events.  Keep this check anyway
+                * for safety in case fid mode requirement is relaxed in the future
+                * to allow unprivileged listener to get events with no fd and no fid.
                 */
-               if (fd < 0) {
-                       pr_debug("fanotify: create_fd(%pd2) failed err=%d\n",
-                                path->dentry, fd);
-                       if (!FAN_GROUP_FLAG(group, FAN_REPORT_FD_ERROR)) {
-                               /*
-                                * Historically, we've handled EOPENSTALE in a
-                                * special way and silently dropped such
-                                * events. Now we have to keep it to maintain
-                                * backward compatibility...
-                                */
-                               if (fd == -EOPENSTALE)
-                                       fd = 0;
-                               return fd;
+               if (!FAN_GROUP_FLAG(group, FANOTIFY_UNPRIV) && path &&
+                   path->mnt && path->dentry) {
+                       fd = create_fd(group, path, &f);
+                       /*
+                        * Opening an fd from dentry can fail for several reasons.
+                        * For example, when tasks are gone and we try to open their
+                        * /proc files or we try to open a WRONLY file like in sysfs
+                        * or when trying to open a file that was deleted on the
+                        * remote network server.
+                        *
+                        * For a group with FAN_REPORT_FD_ERROR, we will send the
+                        * event with the error instead of the open fd, otherwise
+                        * Userspace may not get the error at all.
+                        * In any case, userspace will not know which file failed to
+                        * open, so add a debug print for further investigation.
+                        */
+                       if (fd < 0) {
+                               pr_debug(
+                                       "fanotify: create_fd(%pd2) failed err=%d\n",
+                                       path->dentry, fd);
+                               if (!FAN_GROUP_FLAG(group,
+                                                   FAN_REPORT_FD_ERROR)) {
+                                       /*
+                                        * Historically, we've handled EOPENSTALE in a
+                                        * special way and silently dropped such
+                                        * events. Now we have to keep it to maintain
+                                        * backward compatibility...
+                                        */
+                                       if (fd == -EOPENSTALE)
+                                               fd = 0;
+                                       return fd;
+                               }
                        }
                }

fs/notify/fanotify/fanotify_user.c static ssize_t copy_event_to_user(struct fsnotify_group *group, · line 827

Quoted 10 lines
fs/notify/fanotify/fanotify_user.c +4 -4
+               if (FAN_GROUP_FLAG(group, FAN_REPORT_FD_ERROR))
+                       metadata.fd = fd;
+               else
+                       metadata.fd = fd >= 0 ? fd : FAN_NOFD;
        }
-       if (FAN_GROUP_FLAG(group, FAN_REPORT_FD_ERROR))
-               metadata.fd = fd;
-       else
-               metadata.fd = fd >= 0 ? fd : FAN_NOFD;
 

IMO, this is shorter and nicer after assigning fd = -ret; above:

if (FAN_GROUP_FLAG(group, FAN_REPORT_FD_ERROR |

FAN_REPORT_RESPONSE_ID))

               metadata.fd = fd;
       else
               metadata.fd = fd >= 0 ? fd : FAN_NOFD;

fs/notify/fanotify/fanotify_user.c static ssize_t copy_event_to_user(struct fsnotify_group *group, · line 882

Quoted 13 lines
fs/notify/fanotify/fanotify_user.c +5 -2
        if (pidfd_mode) {
                /*
@@ -858,8 +875,12 @@ static ssize_t copy_event_to_user(struct fsnotify_group *group,
        if (pidfd_file)
                fd_install(pidfd, pidfd_file);
 
-       if (fanotify_is_perm_event(event->mask))
-               FANOTIFY_PERM(event)->fd = fd;
+       if (fanotify_is_perm_event(event->mask)) {
+               if (FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID))
+                       FANOTIFY_PERM(event)->id = metadata.id;
+               else
+                       FANOTIFY_PERM(event)->fd = fd;

Again, no need for a special case here.

FANOTIFY_PERM(event)->id = fd;

Quoted 5 lines
fs/notify/fanotify/fanotify_user.c +1 -0
+       }
 
        return metadata.event_len;
 

fs/notify/fanotify/fanotify_user.c static ssize_t fanotify_read(struct file *file, char __user *buf, · line 972

Quoted 9 lines
fs/notify/fanotify/fanotify_user.c +5 -1
@@ -944,7 +965,11 @@ static ssize_t fanotify_read(struct file *file, char __user *buf,
                if (!fanotify_is_perm_event(event->mask)) {
                        fsnotify_destroy_event(group, &event->fse);
                } else {
-                       if (ret <= 0 || FANOTIFY_PERM(event)->fd < 0) {
+                       if (ret <= 0 ||
+                           ((FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID) &&
+                             FANOTIFY_PERM(event)->id >= -255) ||
+                            (!FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID) &&
+                             FANOTIFY_PERM(event)->fd < 0))) {

Please create a small helper fanotify_is_valid_response_id()

fs/notify/fanotify/fanotify_user.c SYSCALL_DEFINE2(fanotify_init, unsigned int, flags, unsigned int, event_f_flags) · line 1612

Quoted 8 lines
fs/notify/fanotify/fanotify_user.c +1 -0
                                spin_lock(&group->notification_lock);
                                finish_permission_event(group,
                                        FANOTIFY_PERM(event), FAN_DENY, NULL);
@@ -1584,6 +1609,15 @@ SYSCALL_DEFINE2(fanotify_init, unsigned int, flags, unsigned int, event_f_flags)
                return -EINVAL;
 
        /*
+     * With group that reports fid info and allows only pre-content events,

This line is true, but the word "only" is not clear in this context, after the change from (class != FAN_CLASS_PRE_CONTENT_FID), so I would drop the word "only".

fs/notify/fanotify/fanotify_user.c SYSCALL_DEFINE2(fanotify_init, unsigned int, flags, unsigned int, event_f_flags) · line 1614

Quoted 2 lines
fs/notify/fanotify/fanotify_user.c +2 -0
+     * user may request to get a response id instead of event->fd.
+     * FAN_REPORT_FD_ERROR does not make sense in this case.

This last line is not relevant anymore.

Quoted 31 lines
fs/notify/fanotify/fanotify_user.c +8 -1
+     */
+       if ((flags & FAN_REPORT_RESPONSE_ID) &&
+           (!fid_mode || class == FAN_CLASS_NOTIF))
+               return -EINVAL;
+
+       /*
         * Child name is reported with parent fid so requires dir fid.
         * We can report both child fid and dir fid with or without name.
         */
@@ -1660,6 +1694,7 @@ SYSCALL_DEFINE2(fanotify_init, unsigned int, flags, unsigned int, event_f_flags)
                fd = -EINVAL;
                goto out_destroy_group;
        }
+       idr_init(&group->response_idr);
 
        BUILD_BUG_ON(!(FANOTIFY_ADMIN_INIT_FLAGS & FAN_UNLIMITED_QUEUE));
        if (flags & FAN_UNLIMITED_QUEUE) {
@@ -2145,7 +2180,7 @@ static int __init fanotify_user_setup(void)
                                     FANOTIFY_DEFAULT_MAX_USER_MARKS);
 
        BUILD_BUG_ON(FANOTIFY_INIT_FLAGS & FANOTIFY_INTERNAL_GROUP_FLAGS);
-       BUILD_BUG_ON(HWEIGHT32(FANOTIFY_INIT_FLAGS) != 14);
+       BUILD_BUG_ON(HWEIGHT32(FANOTIFY_INIT_FLAGS) != 15);
        BUILD_BUG_ON(HWEIGHT32(FANOTIFY_MARK_FLAGS) != 11);
 
        fanotify_mark_cache = KMEM_CACHE(fanotify_mark,
include/linux/fanotify.h +0 -0
index 879cff5eccd4..4463fcfd16bb 100644

include/linux/fanotify.h line 43

Quoted 7 lines
include/linux/fanotify.h +2 -1
@@ -38,7 +38,8 @@
                                         FAN_REPORT_PIDFD | \
                                         FAN_REPORT_FD_ERROR | \
                                         FAN_UNLIMITED_QUEUE | \
-                                        FAN_UNLIMITED_MARKS)
+                                        FAN_UNLIMITED_MARKS | \
+                                        FAN_REPORT_RESPONSE_ID)
 

For my OCD, place it after FAN_REPORT_FD_ERROR please ;)

Thanks,
Amir.

#5 lore raw

Re: [PATCH 3/3] [PATCH v2 3/3] fanotify: introduce event response identifier

Quoted 251 lines · Amir Goldstein
Quoted 4 lines · Ibrahim Jirdeh

From: ibrahimjirdeh <[email protected]>

Summary:

Formatting issue.

Quoted 50 lines

This adds support for responding to events via response identifier. This prevents races if there are multiple processes backing the same fanotify group (eg. handover of fanotify group to new instance of a backing daemon). It is also useful for reporting pre-dir-content events without an event->fd:
https://lore.kernel.org/linux-fsdevel/2dx3pbcnv5w75fxb2ghqtsk6gzl6cuxmd2rinzwbq7xxfjf5z7@3nqidi3mno46/.

Rather than introducing a new event identifier field and extending fanotify_event_metadata, we have opted to overload event->fd and restrict this functionality to use-cases which are using file handle apis (FAN_REPORT_FID).

In terms of how response ids are allocated, we use an idr for allocation and restrict the id range to below -255 to ensure there is no overlap with existing fd-as-identifier usage. We can also leverage the added idr for more efficient lookup when handling response although that is not done in this patch.

---
 fs/notify/fanotify/fanotify.c       |   3 +
 fs/notify/fanotify/fanotify.h       |   5 +-
 fs/notify/fanotify/fanotify_user.c  | 129 ++++++++++++++++++----------
 include/linux/fanotify.h            |   3 +-
 include/linux/fsnotify_backend.h    |   1 +
 include/uapi/linux/fanotify.h       |  11 ++-
 tools/include/uapi/linux/fanotify.h |  11 ++-
 7 files changed, 110 insertions(+), 53 deletions(-)
fs/notify/fanotify/fanotify.c +3 -0
index 34acb7c16e8b..d9aebd359199 100644
@@ -1106,6 +1106,9 @@ static void fanotify_free_event(struct fsnotify_group *group,
 
        event = FANOTIFY_E(fsn_event);
        put_pid(event->pid);
+       if (fanotify_is_perm_event(event->mask) &&
+           FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID))
+               idr_remove(&group->response_idr, -FANOTIFY_PERM(event)->id);
        switch (event->type) {
        case FANOTIFY_EVENT_TYPE_PATH:
                fanotify_free_path_event(event);
fs/notify/fanotify/fanotify.h +0 -0
index f6d25fcf8692..8d62321237d6 100644

fs/notify/fanotify/fanotify.h struct fanotify_perm_event { · line 450

Quoted 8 lines
fs/notify/fanotify/fanotify.h +4 -1
@@ -444,7 +444,10 @@ struct fanotify_perm_event {
        size_t count;
        u32 response;                   /* userspace answer to the event */
        unsigned short state;           /* state of the event */
-       int fd;         /* fd we passed to userspace for this event */
+       union {
+               __s32 fd;                       /* fd we passed to userspace for this event */
+               __s32 id;                       /* FAN_REPORT_RESPONSE_ID */
+       };

That's an "int" and I don't think that we need a union in this internal context. int id; /* id we passed to userspace for this event */
is always correct, whether the id is also an fd or not.

Quoted 8 lines
fs/notify/fanotify/fanotify.h +0 -0
        union {
                struct fanotify_response_info_header hdr;
                struct fanotify_response_info_audit_rule audit_rule;
fs/notify/fanotify/fanotify_user.c +0 -0
index 19d3f2d914fe..b033f86e0db3 100644

fs/notify/fanotify/fanotify_user.c static int process_access_response(struct fsnotify_group *group, · line 335

Quoted 7 lines
fs/notify/fanotify/fanotify_user.c +3 -1
@@ -330,14 +330,16 @@ static int process_access_response(struct fsnotify_group *group,
                                   size_t info_len)
 {
        struct fanotify_perm_event *event;
-       int fd = response_struct->fd;
+       int id = FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID) ?
+                        response_struct->id :
+                        response_struct->fd;

Not needed. Can always use int id = response_struct->id; it is never used as an actual fd in this context. But this function would be a good place to add:

BUILD_BUG_ON(sizeof(response_struct->id) != sizeof(response_struct->fd)); BUILD_BUG_ON(offsetof(struct fanotity_response, id) != offsetof(struct fanotify_repose, fd));

to make sure that code can use either alternative safely.

Quoted 18 lines
fs/notify/fanotify/fanotify_user.c +3 -3
        u32 response = response_struct->response;
        int errno = fanotify_get_response_errno(response);
        int ret = info_len;
        struct fanotify_response_info_audit_rule friar;
 
-       pr_debug("%s: group=%p fd=%d response=%x errno=%d buf=%p size=%zu\n",
-                __func__, group, fd, response, errno, info, info_len);
+       pr_debug("%s: group=%p id=%d response=%x errno=%d buf=%p size=%zu\n",
+                __func__, group, id, response, errno, info, info_len);
        /*
         * make sure the response is valid, if invalid we do nothing and either
         * userspace can send a valid response or we will clean it up after the
@@ -385,19 +387,24 @@ static int process_access_response(struct fsnotify_group *group,
                ret = process_access_response_info(info, info_len, &friar);
                if (ret < 0)
                        return ret;
-               if (fd == FAN_NOFD)
+               if (id == FAN_NOFD)

fs/notify/fanotify/fanotify_user.c static int process_access_response(struct fsnotify_group *group, · line 399

Quoted 10 lines
fs/notify/fanotify/fanotify_user.c +3 -1
                        return ret;
        } else {
                ret = 0;
        }
+       if (FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID) && id >= -255)
+               return -EINVAL;
 
-       if (fd < 0)
+       if (!FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID) && id < 0)
                return -EINVAL;

Please use helper for both cases above:
static inline fanotify_is_valid_response_id(struct fsnotify_group *group, int id)

fs/notify/fanotify/fanotify_user.c static int process_access_response(struct fsnotify_group *group, · line 407

Quoted 9 lines
fs/notify/fanotify/fanotify_user.c +4 -1
        spin_lock(&group->notification_lock);
        list_for_each_entry(event, &group->fanotify_data.access_list,
                            fae.fse.list) {
-               if (event->fd != fd)
+               int other_id = FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID) ?
+                                      event->id :
+                                      event->fd;
+               if (other_id != id)

No need. can use if (event->id != id)

Quoted 13 lines
fs/notify/fanotify/fanotify_user.c +0 -6
                        continue;
 
                list_del_init(&event->fae.fse.list);
@@ -765,48 +772,58 @@ static ssize_t copy_event_to_user(struct fsnotify_group *group,
            task_tgid(current) != event->pid)
                metadata.pid = 0;
 
-       /*
-        * For now, fid mode is required for an unprivileged listener and
-        * fid mode does not report fd in events.  Keep this check anyway
-        * for safety in case fid mode requirement is relaxed in the future
-        * to allow unprivileged listener to get events with no fd and no fid.
-        */

fs/notify/fanotify/fanotify_user.c static ssize_t copy_event_to_user(struct fsnotify_group *group, · line 781

Quoted 10 lines
fs/notify/fanotify/fanotify_user.c +7 -3
-       if (!FAN_GROUP_FLAG(group, FANOTIFY_UNPRIV) &&
-           path && path->mnt && path->dentry) {
-               fd = create_fd(group, path, &f);
+       if (FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID)) {
+               ret = idr_alloc_cyclic(&group->response_idr, event, 256, INT_MAX,
+                                      GFP_NOWAIT);
+               if (ret < 0)
+                       return ret;
+               metadata.id = -ret;
+       } else {

Please avoid this unneeded churn and unneeded nesting:

(quoted diff) +2 -0
+       if (FAN_GROUP_FLAG(group, FAN_REPORT_RESPONSE_ID)) {
...
+       } else if (!FAN_GROUP_FLAG(group, FANOTIFY_UNPRIV) && ...

And I would assign fd = -ret; to make the code below simpler...

Quoted 64 lines
fs/notify/fanotify/fanotify_user.c +36 -24
                /*
-                * Opening an fd from dentry can fail for several reasons.
-                * For example, when tasks are gone and we try to open their
-                * /proc files or we try to open a WRONLY file like in sysfs
-                * or when trying to open a file that was deleted on the
-                * remote network server.
-                *
-                * For a group with FAN_REPORT_FD_ERROR, we will send the
-                * event with the error instead of the open fd, otherwise
-                * Userspace may not get the error at all.
-                * In any case, userspace will not know which file failed to
-                * open, so add a debug print for further investigation.
+                * For now, fid mode is required for an unprivileged listener and
+                * fid mode does not report fd in events.  Keep this check anyway
+                * for safety in case fid mode requirement is relaxed in the future
+                * to allow unprivileged listener to get events with no fd and no fid.
                 */
-               if (fd < 0) {
-                       pr_debug("fanotify: create_fd(%pd2) failed err=%d\n",
-                                path->dentry, fd);
-                       if (!FAN_GROUP_FLAG(group, FAN_REPORT_FD_ERROR)) {
-                               /*
-                                * Historically, we've handled EOPENSTALE in a
-                                * special way and silently dropped such
-                                * events. Now we have to keep it to maintain
-                                * backward compatibility...
-                                */
-                               if (fd == -EOPENSTALE)
-                                       fd = 0;
-                               return fd;
+               if (!FAN_GROUP_FLAG(group, FANOTIFY_UNPRIV) && path &&
+                   path->mnt && path->dentry) {
+                       fd = create_fd(group, path, &f);
+                       /*
+                        * Opening an fd from dentry can fail for several reasons.
+                        * For example, when tasks are gone and we try to open their
+                        * /proc files or we try to open a WRONLY file like in sysfs
+                        * or when trying to open a file that was deleted on the
+                        * remote network server.
+                        *
+                        * For a group with FAN_REPORT_FD_ERROR, we will send the
+                        * event with the error instead of the open fd, otherwise
+                        * Userspace may not get the error at all.
+                        * In any case, userspace will not know which file failed to
+                        * open, so add a debug print for further investigation.
+                        */
+                       if (fd < 0) {
+                               pr_debug(
+                                       "fanotify: create_fd(%pd2) failed err=%d\n",
+                                       path->dentry, fd);
+                               if (!FAN_GROUP_FLAG(group,
+                                                   FAN_REPORT_FD_ERROR)) {
+                                       /*
+                                        * Historically, we've handled EOPENSTALE in a
+                                        * special way and silently dropped such
+                                        * events. Now we have to keep it to maintain
+                                        * backward compatibility...
+                                        */
+                                       if (fd == -EOPENSTALE)
+                                               fd = 0;
+                                       return fd;
+                               }
                        }
                }

fs/notify/fanotify/fanotify_user.c static ssize_t copy_event_to_user(struct fsnotify_group *group, · line 827

Quoted 10 lines
fs/notify/fanotify/fanotify_user.c +4 -4
+               if (FAN_GROUP_FLAG(group, FAN_REPORT_FD_ERROR))
+                       metadata.fd = fd;
+               else
+                       metadata.fd = fd >= 0 ? fd : FAN_NOFD;
        }
-       if (FAN_GROUP_FLAG(group, FAN_REPORT_FD_ERROR))
-               metadata.fd = fd;
-       else
-               metadata.fd = fd >= 0 ? fd : FAN_NOFD;
 
Quoted 9 lines

IMO, this is shorter and nicer after assigning fd = -ret; above:

if (FAN_GROUP_FLAG(group, FAN_REPORT_FD_ERROR |

FAN_REPORT_RESPONSE_ID))

               metadata.fd = fd;
       else
               metadata.fd = fd >= 0 ? fd : FAN_NOFD;

And above this code is also a good place to place the build assertion:

BUILD_BUG_ON(sizeof(metadata.id) != sizeof(metadata.fd)); BUILD_BUG_ON(offsetof(struct fanotity_event_metadata, id) != offsetof(struct fanotity_event_metadata, fd));

Which provides the justification to use the union fields interchangeably in this simplified code.

Thanks,
Amir.

#6 lore raw

Re: [PATCH 3/3] [PATCH v2 3/3] fanotify: introduce event response identifier

Quoted 16 lines · On 7/10/25, 1:45 AM, "Amir Goldstein" <[email protected]…
Quoted 9 lines

IMO, this is shorter and nicer after assigning fd = -ret; above:

if (FAN_GROUP_FLAG(group, FAN_REPORT_FD_ERROR |

FAN_REPORT_RESPONSE_ID))

               metadata.fd = fd;
       else
               metadata.fd = fd >= 0 ? fd : FAN_NOFD;

And above this code is also a good place to place the build assertion:

BUILD_BUG_ON(sizeof(metadata.id) != sizeof(metadata.fd)); BUILD_BUG_ON(offsetof(struct fanotity_event_metadata, id) != offsetof(struct fanotity_event_metadata, fd));

Quoted 5 lines

Which provides the justification to use the union fields interchangeably in this simplified code.

Thanks,
Amir.

I will simplify the code to use union fields interchangeably + add the suggested build assertions and resubmit these soon. It gives a chance to fix the various formatting issues :)

#7 lore raw
In reply to Ibrahim Jirdeh
Quoted 9 lines · Ibrahim Jirdeh

These patches are in order to add an identifier other than fd which can be used to respond to fanotify permission events. This is useful for HSM use cases which are backed by a daemon to respond reliably
[1] and also for reporting pre-dir-content events without an event->fd [2]

The first few patches in the series are pulled in from Amir's work to add support for pre-dir-content events.

Quoted 7 lines

In terms of testing, there are some additional LTP test cases to go with these patches which exercise responding to events via response identifier
[3]

[3] https://github.com/ibrahim-jirdeh/ltp/commit/4cdb1ac3b22be7b332cc18ff193686f2be7ea69d

Nice test. See some comments in github.

Thanks,
Amir.