Re: [PATCH v2 1/8] iio: core: Add opaque_struct_size() helper and use it

From: Uwe Kleine-König
Date: Fri Jul 21 2023 - 14:13:09 EST


Hello Andy,

On Fri, Jul 21, 2023 at 08:25:12PM +0300, Andy Shevchenko wrote:
> On Fri, Jul 21, 2023 at 08:22:35PM +0300, Andy Shevchenko wrote:
> > On Fri, Jul 21, 2023 at 08:00:15PM +0300, Andy Shevchenko wrote:
> > > Introduce opaque_struct_size() helper, which may be moved
> > > to overflow.h in the future, and use it in the IIO core.
>
> ...
>
> > > +#define opaque_struct_size(p, a, s) ({ \
> > > + size_t _psize = sizeof(*(p)); \
> > > + size_t _asize = ALIGN(_psize, (a)); \
> > > + size_t _ssize = s; \
> > > + _ssize ? size_add(_asize, _ssize) : _psize; \
> > > +})
> > > +
> > > +#define opaque_struct_data(p, a) \
> > > + ((void *)(p) + ALIGN(sizeof(*(p)), (a)))
> >
> > Hmm... This can potentially evaluate p twice.

I don't think sizeof evaluates its parameter? It should only defer its
type and then calculate the respective size.

> > Perhaps this variant is better:
> >
> > #define opaque_struct_data(p, a) ALIGN((p) + 1, (a)))

Still I like this better.

> > Besides, I don't think we should worry about @s evaluation in the main macro
> > which may be simplified to
> >
> > #define opaque_struct_size(p, a, s) \
> > ((s) ? size_add(ALIGN(sizeof(*(p)), (a)), (s)) : sizeof(*(p)))
> >
> > Thoughts?
>
> Also we may leave the struct always be aligned which makes the above even
> simpler (but might waste bytes if @s = 0).

Depending on the value of a, the bytes "wasted" here might not be saved
anyhow because the memory allocator will round up the allocation size to
a multiple of some chunk size anyhow.

> #define opaque_struct_size(p, a, s) size_add(ALIGN(sizeof(*(p)), (a)), (s))
>
> (with the respective documentation update).

That would be my favourite.

Possible users of this helper include:

__spi_alloc_controller() in drivers/spi/spi.c
alloc_netdev_mqs in net/core/dev.c

Best regards
Uwe

--
Pengutronix e.K. | Uwe Kleine-König |
Industrial Linux Solutions | https://www.pengutronix.de/ |

Attachment: signature.asc
Description: PGP signature