btrfs_ioctl_defrag() checks MAY_WRITE against nop_mnt_idmap, so on an
idmapped mount the owner comparison uses the caller's fsuid against the
raw on-disk uid and the ioctl fails with -EPERM even for the file's
owner. Pass the mount idmap down so defrag works on idmapped mounts.
The check, added in
616d374efa23 ("btrfs: allow defrag on a file opened
read-only that has rw permissions"), is not a privilege gate. It only
tests whether the file could have been opened for writing, and a user
who owns the file on the idmapped mount can already open it O_RDWR,
write() to it or fallocate() it. Defragmenting a regular file only
rearranges the caller's own extents; there is nothing it can rewrite
that the caller could not rewrite anyway. Whole-subvolume defrag on a
directory keeps its capable(CAP_SYS_ADMIN) requirement, and the
!capable() guard around this check is left as is.
FIDEDUPERANGE already works this way for unprivileged callers:
may_dedupe_file() in fs/remap_range.c compares the inode owner through
file_mnt_idmap(file) and falls back to inode_permission() with the same
idmap, and dedupe can rewrite one file's extents from another file's
contents, which is a stronger operation than defrag.
On regular mounts file_mnt_idmap() is nop_mnt_idmap and nothing
changes.
Reviewed-by: Seth Forshee <sforshee@kernel.org>
Reviewed-by: Qu Wenruo <wqu@suse.com>
Reviewed-by: Christian Brauner (Amutable) <brauner@kernel.org>
Signed-off-by: Tao Cui <cuitao@kylinos.cn>
Signed-off-by: David Sterba <dsterba@suse.com>