fs/open.c: micro-optimization by avoiding branch on common path
PATCH 1/1 fs/open.c: micro-optimization by avoiding branch on common path
From: Mateusz Nosek <[email protected]>
If file is a directory it is surely not regular. Therefore, if 'S_ISREG' check returns false one can be sure that vfs_truncate must returns with error. Introduced patch refactors code to avoid one branch in 'likely' control flow path. Moreover, it marks the proper check with 'unlikely' macro to improve both branch prediction and readability. Changes were tested with gcc 8.3.0 on x86 architecture and it is confirmed that slightly better assembly is generated.
--- fs/open.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-)
fs/open.c +6 -4
@@ -74,10 +74,12 @@ long vfs_truncate(const struct path *path, loff_t length) inode = path->dentry->d_inode;/* For directories it's -EISDIR, for other non-regulars - -EINVAL */ -if (S_ISDIR (inode->i_mode)) -return -EISDIR ; -if (!S_ISREG (inode->i_mode)) -return -EINVAL ; +if (unlikely (!S_ISREG (inode->i_mode))) { +if (S_ISDIR (inode->i_mode)) +return -EISDIR ; +else +return -EINVAL ; + } error =mnt_want_write (path->mnt);if (error)
Signature · 1 line
2.20.1
Al Viro
maintainerQuoted 9 lines · On Sat, Sep 19, 2020 at 02:10:21AM +0200, [email protected] wrote:
From: Mateusz Nosek <[email protected]>
If file is a directory it is surely not regular. Therefore, if '
S_ISREG' check returns false one can be sure thatvfs_truncatemust returns with error. Introduced patch refactors code to avoid one branch in 'likely' control flow path. Moreover, it marks the proper check with 'unlikely' macro to improve both branch prediction and readability. Changes were tested with gcc 8.3.0 on x86 architecture and it is confirmed that slightly better assembly is generated.
Does it measurably show in any profiles?
Quoted 13 lines
Signed-off-by Mateusz Nosek <[email protected]>--- fs/open.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-)fs/open.c +0
-0@@ -74,10 +74,12 @@ long vfs_truncate(const struct path *path, loff_t length) inode = path->dentry->d_inode;/* For directories it's -EISDIR, for other non-regulars - -EINVAL */
fs/open.c long vfs_truncate(const struct path *path, loff_t length) · line 82
Quoted 10 lines
fs/open.c +6
-4-if (S_ISDIR (inode->i_mode)) -return -EISDIR ; -if (!S_ISREG (inode->i_mode)) -return -EINVAL ; +if (unlikely (!S_ISREG (inode->i_mode))) { +if (S_ISDIR (inode->i_mode)) +return -EISDIR ; +else +return -EINVAL ; + }
If anything, turn the second if into return S_ISDIR(...) ? -EISDIR : -EINVAL;