Re: [PATCH] nvme: replace max(a, min(b, c)) by clamp(b, a, c)

From: David Laight
Date: Wed Mar 19 2025 - 17:34:37 EST


On Wed, 19 Mar 2025 21:00:32 +0000
David Laight <david.laight.linux@xxxxxxxxx> wrote:

> On Mon, 17 Mar 2025 15:39:09 +0800 (CST)
> <shao.mingyin@xxxxxxxxxx> wrote:
>
> > From: LiHaoran <li.haoran7@xxxxxxxxxx>
> >
> > This patch replaces max(a, min(b, c)) by clamp(b, a, c) in the nvme
> > driver. This improves the readability.
> >
> > Signed-off-by: LiHaoran <li.haoran7@xxxxxxxxxx>
> > Cc: ShaoMingyin <shao.mingyin@xxxxxxxxxx>
> > ---
> > drivers/nvme/target/nvmet.h | 2 +-
> > 1 file changed, 1 insertion(+), 1 deletion(-)
> >
> > diff --git a/drivers/nvme/target/nvmet.h b/drivers/nvme/target/nvmet.h
> > index fcf4f460dc9a..30804b0ca66e 100644
> > --- a/drivers/nvme/target/nvmet.h
> > +++ b/drivers/nvme/target/nvmet.h
> > @@ -819,7 +819,7 @@ static inline u8 nvmet_cc_iocqes(u32 cc)
> > /* Convert a 32-bit number to a 16-bit 0's based number */
> > static inline __le16 to0based(u32 a)
> > {
> > - return cpu_to_le16(max(1U, min(1U << 16, a)) - 1);
> > + return cpu_to_le16(clamp(1U << 16, 1U, a) - 1);
>
> Swap the arguments into a sane order - clamp(a, 1, 1 << 16)

To clarify further it is clamp(val, lo, hi) and is only well defined if 'lo <= hi'.
In particular the order of the comparisons is not defined.
It might be val > hi ? hi : val < lo ? lo : val.
Which won't give the value you expect when 'a' is zero.

>
> David
>
> > }
> >
> > static inline bool nvmet_ns_has_pi(struct nvmet_ns *ns)
>