[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <20240322183302.197c9b5f@meshulam.tesarici.cz>
Date: Fri, 22 Mar 2024 18:33:15 +0100
From: Petr Tesařík <petr@...arici.cz>
To: Will Deacon <will@...nel.org>
Cc: Christoph Hellwig <hch@....de>, Marek Szyprowski
<m.szyprowski@...sung.com>, Robin Murphy <robin.murphy@....com>, Petr
Tesarik <petr.tesarik1@...wei-partners.com>, Michael Kelley
<mhklinux@...look.com>, open list <linux-kernel@...r.kernel.org>, "open
list:DMA MAPPING HELPERS" <iommu@...ts.linux.dev>, Roberto Sassu
<roberto.sassu@...weicloud.com>
Subject: Re: [PATCH v3 2/2] bug: introduce ASSERT_VAR_CAN_HOLD()
On Fri, 22 Mar 2024 15:37:38 +0000
Will Deacon <will@...nel.org> wrote:
> On Thu, Mar 21, 2024 at 06:19:02PM +0100, Petr Tesarik wrote:
> > From: Petr Tesarik <petr.tesarik1@...wei-partners.com>
> >
> > Introduce an ASSERT_VAR_CAN_HOLD() macro to check at build time that a
> > variable can hold the given value.
> >
> > Use this macro in swiotlb to make sure that the list and pad_slots fields
> > of struct io_tlb_slot are big enough to hold the maximum possible value of
> > IO_TLB_SEGSIZE.
> >
> > Signed-off-by: Petr Tesarik <petr.tesarik1@...wei-partners.com>
> > ---
> > include/linux/build_bug.h | 10 ++++++++++
> > kernel/dma/swiotlb.c | 2 ++
> > 2 files changed, 12 insertions(+)
> >
> > diff --git a/include/linux/build_bug.h b/include/linux/build_bug.h
> > index 3aa3640f8c18..6e2486508af0 100644
> > --- a/include/linux/build_bug.h
> > +++ b/include/linux/build_bug.h
> > @@ -86,4 +86,14 @@
> > "Offset of " #field " in " #type " has changed.")
> >
> >
> > +/*
> > + * Compile time check that a variable can hold the given value
> > + */
> > +#define ASSERT_VAR_CAN_HOLD(var, value) ({ \
> > + typeof(value) __val = (value); \
> > + typeof(var) __tmp = __val; \
> > + BUILD_BUG_ON_MSG(__tmp != __val, \
> > + #var " cannot hold " #value "."); \
> > +})
>
> nit, but I think this prevents putting negative values into unsigned
> types. Not sure whether we care? Arguably it's even correct to complain.
>
> e.g.
>
> u16 s;
> ASSERT_VAR_CAN_HOLD(s, -1);
>
> explodes for me.
Then it works as intended. I specifically aimed at making a macro that
checks at build time whether a given constant is within the value range
of a variable, so it explodes for a signed overflow (in either
direction).
To check the size of a variable, I could have gone with something
simpler like BUG_ON(sizeof(var) < sizeof(val)).
Petr T
Powered by blists - more mailing lists