Re: [PATCH] kernfs: refresh the inode before changing attributes

From: Alexander Mikhalitsyn

Date: Fri Dec 04 2026 - 04:38:42 EST


On Thu, 2026-12-03 at 10:51 -0500, Josef Bacik wrote:
> The owner and mode of a node are kept in the kernfs_node. An inode
> only
> has a copy, which ->permission() and ->getattr() bring up to date.
> kernfs_iop_setattr() does not, so setattr_prepare() can go by old
> values
> and, for one, fail a chmod by the owner of the node with EPERM.
>
> Refresh the inode first. notify_change() has looked at the copy as
> well
> by then, so compute the mode for ATTR_KILL_S[UG]ID and check
> ATTR_TOUCH
> again.
>
> Fixes: 3ff195b011d7 ("sysfs: Implement sysfs tagged directory
> support.")
> Signed-off-by: Josef Bacik <josef@xxxxxxxx>

LGTM

Please feel free to add:

Reviewed-by: Alexander Mikhalitsyn <alex@xxxxxxxxxxxx>

Kind regards,
Alex

> ---
>  fs/kernfs/inode.c | 29 +++++++++++++++++++++++++++++
>  1 file changed, 29 insertions(+)
>
> diff --git a/fs/kernfs/inode.c b/fs/kernfs/inode.c
> index 6630b29d7c078..88d0c0c875184 100644
> --- a/fs/kernfs/inode.c
> +++ b/fs/kernfs/inode.c
> @@ -107,6 +107,31 @@ int kernfs_setattr(struct kernfs_node *kn, const
> struct iattr *iattr)
>   return ret;
>  }
>  
> +static void kernfs_refresh_inode(struct kernfs_node *kn, struct
> inode *inode);
> +
> +/* Redo what notify_change() decided by the inode as it was cached.
> */
> +static int kernfs_setattr_refresh(struct kernfs_node *kn, struct
> inode *inode,
> +   struct iattr *iattr)
> +{
> + unsigned int ia_valid = iattr->ia_valid;
> +
> + kernfs_refresh_inode(kn, inode);
> +
> + if (ia_valid & (ATTR_KILL_SUID | ATTR_KILL_SGID)) {
> + iattr->ia_mode = inode->i_mode;
> + if (ia_valid & ATTR_KILL_SUID)
> + iattr->ia_mode &= ~S_ISUID;
> + if (ia_valid & ATTR_KILL_SGID)
> + iattr->ia_mode &= ~S_ISGID;
> + }
> +
> + /* may_setattr() would take kernfs_iattr_rwsem again */
> + if ((ia_valid & ATTR_TOUCH) &&
> +     !inode_owner_or_capable(&nop_mnt_idmap, inode))
> + return generic_permission(&nop_mnt_idmap, inode,
> MAY_WRITE);
> + return 0;
> +}
> +
>  int kernfs_iop_setattr(const struct mnt_idmap *idmap, struct dentry
> *dentry,
>          struct iattr *iattr)
>  {
> @@ -120,6 +145,10 @@ int kernfs_iop_setattr(const struct mnt_idmap
> *idmap, struct dentry *dentry,
>  
>   root = kernfs_root(kn);
>   down_write(&root->kernfs_iattr_rwsem);
> + error = kernfs_setattr_refresh(kn, inode, iattr);
> + if (error)
> + goto out;
> +
>   error = setattr_prepare(&nop_mnt_idmap, dentry, iattr);
>   if (error)
>   goto out;
> ---
> base-commit: b8e026b973764a52b92c0cdc1d3cf96f2abc1058
> change-id: 20261203-b4-kernfs-setattr-refresh-b66a2529427e