Re: [PATCH v8 14/18] mm: memfd_luo: allow preserving memfd

From: Mike Rapoport

Date: Wed Jan 14 2026 - 11:59:16 EST


On Tue, Jan 13, 2026 at 06:09:23AM -0800, Chris Mason wrote:
> On Tue, 25 Nov 2025 11:58:44 -0500 Pasha Tatashin <pasha.tatashin@xxxxxxxxxx> wrote:
>
> Hi everyone,
>
> I'm running the v6.19 mm commits through patch review automation, and this
> commit was flagged. I don't know this code well, but it looks like it
> might be a real bug.
>
> [AI review output below]
>
> > diff --git a/mm/memfd_luo.c b/mm/memfd_luo.c
> > new file mode 100644
> > index 0000000000000..4f6ba63b43105
> > --- /dev/null
> > +++ b/mm/memfd_luo.c
>
> [ ... ]
>
> > +static int memfd_luo_retrieve_folios(struct file *file,
> > + struct memfd_luo_folio_ser *folios_ser,
> > + u64 nr_folios)
> > +{
> > + struct inode *inode = file_inode(file);
> > + struct address_space *mapping = inode->i_mapping;
> > + struct folio *folio;
> > + int err = -EIO;
> > + long i;
> > +
> > + for (i = 0; i < nr_folios; i++) {
>
> [ ... ]
>
> > + err = shmem_add_to_page_cache(folio, mapping, index, NULL,
> > + mapping_gfp_mask(mapping));
> > + if (err) {
> > + pr_err("shmem: failed to add to page cache folio index %ld: %d\n",
> > + i, err);
> > + goto unlock_folio;
> > + }
> > +
> > + if (flags & MEMFD_LUO_FOLIO_UPTODATE)
> > + folio_mark_uptodate(folio);
> > + if (flags & MEMFD_LUO_FOLIO_DIRTY)
> > + folio_mark_dirty(folio);
> > +
> > + err = shmem_inode_acct_blocks(inode, 1);
> > + if (err) {
> > + pr_err("shmem: failed to account folio index %ld: %d\n",
> > + i, err);
> > + goto unlock_folio;
> > + }
>
> When shmem_inode_acct_blocks() fails here, the folio has already been
> added to the page cache by shmem_add_to_page_cache(). Should the folio be
> removed from the page cache before going to unlock_folio?
>
> Looking at shmem_alloc_and_add_folio() in mm/shmem.c, when
> shmem_inode_acct_blocks() fails after the folio has been added, it calls
> filemap_remove_folio() to remove it:
>
> error = shmem_inode_acct_blocks(inode, pages);
> if (error) {
> ...
> if (error) {
> filemap_remove_folio(folio);
> goto unlock;
> }
> }
>
> Without this, the folio remains in the page cache (counted in
> mapping->nrpages) but info->alloced is not incremented (since
> shmem_recalc_inode is not called). This could cause shmem accounting
> inconsistency.

My understanding that if anything fails in memfd_luo_retrieve_folios() the
file is destroyed anyway and the accounting wouldn't matter.

But to be on the safe side we should fix the error handling here.
@Pratyush, what do you say?

--
Sincerely yours,
Mike.