Skip to contentSkip to conversation

sysfs: check if one entry has been removed before freeing

PATCH New Ming Lei 1 participant 1 message Apr 4, 2013 Driver core

lore
Share & tools
lore

Ming Lei

author
#0 lore raw

PATCH 1/1 sysfs: check if one entry has been removed before freeing

It might be a kernel disaster if one sysfs entry is freed but still referenced by sysfs tree.

Recently Dave and Sasha reported one use-after-free problem on sysfs entry, and the problem has been troubleshooted with help of debug message added in this patch.

Given sysfs_get_dirent/sysfs_put are exported APIs, even inside sysfs they are called in many contexts(kobject/attribe add/delete, inode init/drop, dentry lookup/release, readdir, ...), it is healthful to check the removed flag before freeing one entry and dump message if it is freeing without being removed first.

Cc Dave Jones <[email protected]>
Cc Sasha Levin <[email protected]>

---
v1:
- use WARN() instead of BUG() as suggested by Dave and Greg

 fs/sysfs/dir.c |    9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
fs/sysfs/dir.c +8 -1
index 1bf016b..e8e0e71 100644
@@ -268,6 +268,10 @@ void release_sysfs_dirent(struct sysfs_dirent * sd)
 	 */
 	parent_sd = sd->s_parent;
 
+	WARN(!(sd->s_flags & SYSFS_FLAG_REMOVED),
+		"sysfs: free using entry: %s/%s\n",
+		parent_sd ? parent_sd->s_name : "", sd->s_name);
+
 	if (sysfs_type(sd) == SYSFS_KOBJ_LINK)
 		sysfs_put(sd->s_symlink.target_sd);
 	if (sysfs_type(sd) & SYSFS_COPY_NAME)
@@ -386,7 +390,7 @@ struct sysfs_dirent *sysfs_new_dirent(const char *name, umode_t mode, int type)
 
 	sd->s_name = name;
 	sd->s_mode = mode;
-	sd->s_flags = type;
+	sd->s_flags = type | SYSFS_FLAG_REMOVED;
 
 	return sd;
 
@@ -466,6 +470,9 @@ int __sysfs_add_one(struct sysfs_addrm_cxt *acxt, struct sysfs_dirent *sd)
 		ps_iattrs->ia_ctime = ps_iattrs->ia_mtime = CURRENT_TIME;
 	}
 
+	/* Mark the entry added into directory tree */
+	sd->s_flags &= ~SYSFS_FLAG_REMOVED;
+
 	return 0;
 }
 
Signature · 1 line
1.7.9.5