Re: [PATCH] ext4: convert to DIV_ROUND_UP() in mpage_process_page_bufs()

From: Eric Biggers
Date: Fri Mar 10 2023 - 01:54:50 EST


On Fri, Mar 10, 2023 at 06:46:12AM +0000, Al Viro wrote:
> On Thu, Mar 09, 2023 at 10:43:55PM -0800, Eric Biggers wrote:
> > On Fri, Mar 10, 2023 at 06:37:29AM +0000, Al Viro wrote:
> > > On Thu, Mar 09, 2023 at 10:17:16PM -0800, Eric Biggers wrote:
> > > > On Fri, Mar 10, 2023 at 02:07:34PM +0800, Yangtao Li wrote:
> > > > > Just for better readability, no code logic change.
> > > > >
> > > > > Signed-off-by: Yangtao Li <frank.li@xxxxxxxx>
> > > > > ---
> > > > > fs/ext4/inode.c | 3 +--
> > > > > 1 file changed, 1 insertion(+), 2 deletions(-)
> > > > >
> > > > > diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c
> > > > > index d251d705c276..d121cde74522 100644
> > > > > --- a/fs/ext4/inode.c
> > > > > +++ b/fs/ext4/inode.c
> > > > > @@ -2218,8 +2218,7 @@ static int mpage_process_page_bufs(struct mpage_da_data *mpd,
> > > > > {
> > > > > struct inode *inode = mpd->inode;
> > > > > int err;
> > > > > - ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
> > > > > - >> inode->i_blkbits;
> > > > > + ext4_lblk_t blocks = DIV_ROUND_UP(i_size_read(inode), i_blocksize(inode));
> > > > >
> > > >
> > > > Please don't do this. This makes the code compile down to a division, which is
> > > > far less efficient. I've verified this by checking the assembly generated.
> > >
> > > Which compiler is doing that?
> >
> > $ gcc --version
> > gcc (GCC) 12.2.1 20230201
> >
> > i_blocksize(inode) is not a constant, so this should not be particularly
> > surprising. One might hope that a / (1 << b) would be optimized into a >> b,
> > but that doesn't seem to happen.
>
> It really ought to be a / (1u << b), though...

Sure, that does better:

uint64_t f(uint64_t a, int b)
{
return a / (1U << b);
}

gcc:
0000000000000000 <f>:
0: 48 89 f8 mov %rdi,%rax
3: 89 f1 mov %esi,%ecx
5: 48 d3 e8 shr %cl,%rax
8: c3 ret

clang:
0000000000000000 <f>:
0: 89 f1 mov %esi,%ecx
2: 48 89 f8 mov %rdi,%rax
5: 48 d3 e8 shr %cl,%rax
8: c3 ret

But with a signed dividend (which is the case here) it gets messed up:

int64_t f(int64_t a, int b)
{
return a / (1U << b);
}

gcc:
0000000000000000 <f>:
0: 48 89 f8 mov %rdi,%rax
3: 89 f1 mov %esi,%ecx
5: bf 01 00 00 00 mov $0x1,%edi
a: d3 e7 shl %cl,%edi
c: 48 99 cqto
e: 48 f7 ff idiv %rdi
11: c3 ret

clang:
0000000000000000 <f>:
0: 89 f1 mov %esi,%ecx
2: be 01 00 00 00 mov $0x1,%esi
7: d3 e6 shl %cl,%esi
9: 48 89 f8 mov %rdi,%rax
c: 48 89 f9 mov %rdi,%rcx
f: 48 c1 e9 20 shr $0x20,%rcx
13: 74 06 je 1b <f+0x1b>
15: 48 99 cqto
17: 48 f7 fe idiv %rsi
1a: c3 ret
1b: 31 d2 xor %edx,%edx
1d: f7 f6 div %esi
1f: c3 ret