Re: [PATCH rdma-next v1 1/3] overflow.h: Add arithmetic shift helper

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Mon, Jul 09, 2018 at 06:14:13PM +0000, Bart Van Assche wrote:
> On Sun, 2018-07-08 at 13:38 +0300, Leon Romanovsky wrote:
> > From: Jason Gunthorpe <jgg@xxxxxxxxxxxx>
> > 
> > Add shift_overflow() helper to help driver authors to ensure that
> > shift operand doesn't cause to overflow.
> > 
> > Signed-off-by: Jason Gunthorpe <jgg@xxxxxxxxxxxx>
> > Signed-off-by: Leon Romanovsky <leonro@xxxxxxxxxxxx>
> >  include/linux/overflow.h | 23 +++++++++++++++++++++++
> >  1 file changed, 23 insertions(+)
> > 
> > diff --git a/include/linux/overflow.h b/include/linux/overflow.h
> > index 8712ff70995f..21ff032773e0 100644
> > +++ b/include/linux/overflow.h
> > @@ -202,6 +202,29 @@
> > 
> >  #endif /* COMPILER_HAS_GENERIC_BUILTIN_OVERFLOW */
> > 
> > +/*
> > + * Compute *d = (a << s)
> > + *
> > + * Returns true if '*d' cannot hold the result or 'a << s' doesn't make sense.
> > + * - 'a << s' causes bits to be lost when stored in d
> > + * - 's' is garbage (eg negative) or so large that a << s is guaranteed to be 0
> > + * - 'a' is negative
> > + * - 'a << s' sets the sign bit, if any, in '*d'
> > + * *d is not defined if false is returned.
> > + */
> > +#define check_shift_overflow(a, s, d) ({				\
> > +	typeof(a) _a = a;						\
> > +	typeof(s) _s = s;						\
> > +	typeof(d) _d = d;						\
> > +	u64 _a_full = _a;						\
> > +	unsigned int _to_shift =					\
> > +	_s >= 0 && _s < 8 * sizeof(*d) ? _s : 0;			\
> > +	*_d = (_a_full << _to_shift);					\
> > +	*d = *_d;							\
> > +	(_to_shift != _s || *_d < 0 || _a < 0 ||			\
> > +	(*_d >> _to_shift) != _a);					\
> > +})
> 
> The comment "Compute *d = (a << s)" looks misleading to me because what the macro
> computes is *d = ((u64)a << s). Shouldn't sizeof(*d) be changed into sizeof(a) to
> make this macro compute (a << s)?

Not sure. The definition is to 'compute a << s on infinite precision'
mixing in the type of 'a' seems to just complicate things.

sizeof(_a_full) might be the clearest option though?

> The assignment "*d = *_d" looks superfluous to me. Since _d == d, how could that
> assignment be useful?

Indeed, that doesn't seem useful. Leon? That was not in my original draft?

> Additionally, the above macro stores a value into *d even if an overflow has been
> detected. Is that how this macro is intended to work?

Yes, as explained """*d is not defined if false is returned."""

This matches the most common usage I think.

Jason
--
To unsubscribe from this list: send the line "unsubscribe linux-rdma" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html



[Index of Archives]     [Linux USB Devel]     [Video for Linux]     [Linux Audio Users]     [Photo]     [Yosemite News]     [Yosemite Photos]     [Linux Kernel]     [Linux SCSI]     [XFree86]

  Powered by Linux