Re: [PATCH] mm/cma: simplify cma_declare_contiguous_multi()

From: Mike Rapoport

Date: Sat Nov 07 2026 - 06:33:16 EST


On Fri, Nov 06, 2026 at 02:30:38PM -0800, Frank van der Linden wrote:
> On Fri, Nov 6, 2026 at 4:56 AM Mike Rapoport (Microsoft)
> <rppt@xxxxxxxxxx> wrote:
> >
> > When cma_declare_contiguous_multi() cannot allocate a CMA area as a
> > single range, it falls back to collecting a list of up to CMA_MAX_RANGES
> > largest free ranges above 4G, reserves them in memblock and adds them to
> > cma->ranges.
> >
> > Replace the current code with a loop that finds the largest free range
> > above 4G, reserves as much of it as needed and repeats until the entire
> > area is reserved or CMA_MAX_RANGES ranges are used.
> >
> > After successful alocation sort the cma->ranges by their base address.
> >
> > The new code scans free memory once for every range rather than once
> > for all ranges, so it is slightly slower, but it is way simpler and more
> > robust.
>
> Thanks for cleaning this up. You're right, what I did with the list
> sorting was too much, and it contained some bugs too.
>
> Just one remark here: I don't think you need to sort the ranges by
> base address at the end, I am not aware of anything relying on the CMA
> ranges being sorted. The sorting was just there to mimic bottom-up
> memblock allocations while acquiring the ranges, but the eventual
> result doesn't need to be sorted. I'm not aware of any CMA code that
> relies on this.

The bottom-up was added by the commit df2ff39e78da7 ("mm: cma: allocate cma
areas bottom-up")

"... to guarantee that the compaction is moving pages out of the
cma area and not into it".

I think sorting an array of up to 8 entries is not too costly to keep it
that way.

> - Frank
>

--
Sincerely yours,
Mike.