diff mbox series

[v16,3/9] mm/gup: Introduce memfd_pin_folios() for pinning memfd folios

Message ID 20240624063952.1572359-4-vivek.kasireddy@intel.com (mailing list archive)
State New
Headers show
Series mm/gup: Introduce memfd_pin_folios() for pinning memfd folios | expand

Commit Message

Kasireddy, Vivek June 24, 2024, 6:36 a.m. UTC
For drivers that would like to longterm-pin the folios associated
with a memfd, the memfd_pin_folios() API provides an option to
not only pin the folios via FOLL_PIN but also to check and migrate
them if they reside in movable zone or CMA block. This API
currently works with memfds but it should work with any files
that belong to either shmemfs or hugetlbfs. Files belonging to
other filesystems are rejected for now.

The folios need to be located first before pinning them via FOLL_PIN.
If they are found in the page cache, they can be immediately pinned.
Otherwise, they need to be allocated using the filesystem specific
APIs and then pinned.

Cc: David Hildenbrand <david@redhat.com>
Cc: Matthew Wilcox (Oracle) <willy@infradead.org>
Cc: Christoph Hellwig <hch@infradead.org>
Cc: Daniel Vetter <daniel.vetter@ffwll.ch>
Cc: Hugh Dickins <hughd@google.com>
Cc: Peter Xu <peterx@redhat.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Dongwon Kim <dongwon.kim@intel.com>
Cc: Junxiao Chang <junxiao.chang@intel.com>
Suggested-by: Jason Gunthorpe <jgg@nvidia.com>
Reviewed-by: Jason Gunthorpe <jgg@nvidia.com> (v2)
Reviewed-by: David Hildenbrand <david@redhat.com> (v3)
Reviewed-by: Christoph Hellwig <hch@lst.de> (v6)
Acked-by: Dave Airlie <airlied@redhat.com>
Acked-by: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Vivek Kasireddy <vivek.kasireddy@intel.com>
---
 include/linux/memfd.h |   5 ++
 include/linux/mm.h    |   3 +
 mm/gup.c              | 137 ++++++++++++++++++++++++++++++++++++++++++
 mm/memfd.c            |  45 ++++++++++++++
 4 files changed, 190 insertions(+)

Comments

SeongJae Park July 5, 2024, 8:48 p.m. UTC | #1
Hello Vivek and Andrew,

On Sun, 23 Jun 2024 23:36:11 -0700 Vivek Kasireddy <vivek.kasireddy@intel.com> wrote:

> For drivers that would like to longterm-pin the folios associated
> with a memfd, the memfd_pin_folios() API provides an option to
> not only pin the folios via FOLL_PIN but also to check and migrate
> them if they reside in movable zone or CMA block. This API
> currently works with memfds but it should work with any files
> that belong to either shmemfs or hugetlbfs. Files belonging to
> other filesystems are rejected for now.
> 
> The folios need to be located first before pinning them via FOLL_PIN.
> If they are found in the page cache, they can be immediately pinned.
> Otherwise, they need to be allocated using the filesystem specific
> APIs and then pinned.
> 
> Cc: David Hildenbrand <david@redhat.com>
> Cc: Matthew Wilcox (Oracle) <willy@infradead.org>
> Cc: Christoph Hellwig <hch@infradead.org>
> Cc: Daniel Vetter <daniel.vetter@ffwll.ch>
> Cc: Hugh Dickins <hughd@google.com>
> Cc: Peter Xu <peterx@redhat.com>
> Cc: Gerd Hoffmann <kraxel@redhat.com>
> Cc: Dongwon Kim <dongwon.kim@intel.com>
> Cc: Junxiao Chang <junxiao.chang@intel.com>
> Suggested-by: Jason Gunthorpe <jgg@nvidia.com>
> Reviewed-by: Jason Gunthorpe <jgg@nvidia.com> (v2)
> Reviewed-by: David Hildenbrand <david@redhat.com> (v3)
> Reviewed-by: Christoph Hellwig <hch@lst.de> (v6)
> Acked-by: Dave Airlie <airlied@redhat.com>
> Acked-by: Gerd Hoffmann <kraxel@redhat.com>
> Signed-off-by: Vivek Kasireddy <vivek.kasireddy@intel.com>
> ---
>  include/linux/memfd.h |   5 ++
>  include/linux/mm.h    |   3 +
>  mm/gup.c              | 137 ++++++++++++++++++++++++++++++++++++++++++
>  mm/memfd.c            |  45 ++++++++++++++
>  4 files changed, 190 insertions(+)
> 
[...]
> diff --git a/mm/gup.c b/mm/gup.c
> index a88e19c78730..94160abbf499 100644
> --- a/mm/gup.c
> +++ b/mm/gup.c
[...]
> @@ -3747,3 +3749,138 @@ long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
>  				     &locked, gup_flags);
>  }
>  EXPORT_SYMBOL(pin_user_pages_unlocked);
> +
> +/**
> + * memfd_pin_folios() - pin folios associated with a memfd
[...]
> +			for (i = 0; i < nr_found; i++) {
> +				/*
> +				 * As there can be multiple entries for a
> +				 * given folio in the batch returned by
> +				 * filemap_get_folios_contig(), the below
> +				 * check is to ensure that we pin and return a
> +				 * unique set of folios between start and end.
> +				 */
> +				if (next_idx &&
> +				    next_idx != folio_index(fbatch.folios[i]))
> +					continue;
> +
> +				folio = try_grab_folio(&fbatch.folios[i]->page,
> +						       1, FOLL_PIN);
> +				if (!folio) {
> +					folio_batch_release(&fbatch);
> +					ret = -EINVAL;
> +					goto err;
> +				}

I found this patch is applied on mm-unstable as commit 7618d1ff59ef ("mm/gup:
introduce memfd_pin_folios() for pinning memfd folios").  Somehow, however, the
commit has changd the above try_grab_folio() call to try_grab_folio_fast()
call.

As a result, building kernel without CONFIG_MMU fais as below:

      CC      mm/gup.o
    mm/gup.c: In function 'memfd_pin_folios':
    mm/gup.c:3862:41: error: implicit declaration of function 'try_grab_folio_fast'; did you mean 'try_grab_folio'? [-Werror=implicit-function-declaration]
     3862 |                                 folio = try_grab_folio_fast(&fbatch.folios[i]->page,
          |                                         ^~~~~~~~~~~~~~~~~~~
          |                                         try_grab_folio
    mm/gup.c:3862:39: warning: assignment to 'struct folio *' from 'int' makes pointer from integer without a cast [-Wint-conversion]
     3862 |                                 folio = try_grab_folio_fast(&fbatch.folios[i]->page,
          |                                       ^

But simply changing the call back to try_grab_folio() causes another failure:

      CC      mm/gup.o
    mm/gup.c: In function 'memfd_pin_folios':
    mm/gup.c:3862:56: error: passing argument 1 of 'try_grab_folio' from incompatible pointer type [-Werror=incompatible-pointer-types]
     3862 |                                 folio = try_grab_folio(&fbatch.folios[i]->page,
          |                                                        ^~~~~~~~~~~~~~~~~~~~~~~
          |                                                        |
          |                                                        struct page *
    mm/gup.c:141:47: note: expected 'struct folio *' but argument is of type 'struct page *'
      141 | int __must_check try_grab_folio(struct folio *folio, int refs,
          |                                 ~~~~~~~~~~~~~~^~~~~
    mm/gup.c:3862:39: warning: assignment to 'struct folio *' from 'int' makes pointer from integer without a cast [-Wint-conversion]
     3862 |                                 folio = try_grab_folio(&fbatch.folios[i]->page,
          |                                       ^

Maybe the change has made to fix conflict with another mm-unstable commit
02a2d55767d1 ("mm: gup: stop abusing try_grab_folio"), but forgot the
CONFIG_MMU unset case?

I confirmed the failure disappears after further cleanup like below:

diff --git a/mm/gup.c b/mm/gup.c
index 46a266ed84f7..9f4902425070 100644
--- a/mm/gup.c
+++ b/mm/gup.c
@@ -3859,9 +3859,9 @@ long memfd_pin_folios(struct file *memfd, loff_t start, loff_t end,
                                    next_idx != folio_index(fbatch.folios[i]))
                                        continue;

-                               folio = try_grab_folio_fast(&fbatch.folios[i]->page,
-                                                      1, FOLL_PIN);
-                               if (!folio) {
+                               folio = page_folio(&fbatch.folios[i]->page);
+
+                               if (try_grab_folio(folio, 1, FOLL_PIN)) {
                                        folio_batch_release(&fbatch);
                                        ret = -EINVAL;
                                        goto err;

I didn't look deep into the patch, so unsure if that's a valid fix, though.
May I ask your thoughts?


Thanks,
SJ

[...]
Andrew Morton July 5, 2024, 9:23 p.m. UTC | #2
On Fri,  5 Jul 2024 13:48:25 -0700 SeongJae Park <sj@kernel.org> wrote:

> > + * memfd_pin_folios() - pin folios associated with a memfd
> [...]
> > +			for (i = 0; i < nr_found; i++) {
> > +				/*
> > +				 * As there can be multiple entries for a
> > +				 * given folio in the batch returned by
> > +				 * filemap_get_folios_contig(), the below
> > +				 * check is to ensure that we pin and return a
> > +				 * unique set of folios between start and end.
> > +				 */
> > +				if (next_idx &&
> > +				    next_idx != folio_index(fbatch.folios[i]))
> > +					continue;
> > +
> > +				folio = try_grab_folio(&fbatch.folios[i]->page,
> > +						       1, FOLL_PIN);
> > +				if (!folio) {
> > +					folio_batch_release(&fbatch);
> > +					ret = -EINVAL;
> > +					goto err;
> > +				}
> 
> I found this patch is applied on mm-unstable as commit 7618d1ff59ef ("mm/gup:
> introduce memfd_pin_folios() for pinning memfd folios").  Somehow, however, the
> commit has changd the above try_grab_folio() call to try_grab_folio_fast()
> call.
> 
> As a result, building kernel without CONFIG_MMU fais as below:
> 
> ...
>
> Maybe the change has made to fix conflict with another mm-unstable commit
> 02a2d55767d1 ("mm: gup: stop abusing try_grab_folio"), but forgot the
> CONFIG_MMU unset case?

Yes.  That patch didn't add a CONFIG_MMU=n version of
try_grab_folio_fast().  Maybe it should have?

> I confirmed the failure disappears after further cleanup like below:
> 
> diff --git a/mm/gup.c b/mm/gup.c
> index 46a266ed84f7..9f4902425070 100644
> --- a/mm/gup.c
> +++ b/mm/gup.c
> @@ -3859,9 +3859,9 @@ long memfd_pin_folios(struct file *memfd, loff_t start, loff_t end,
>                                     next_idx != folio_index(fbatch.folios[i]))
>                                         continue;
> 
> -                               folio = try_grab_folio_fast(&fbatch.folios[i]->page,
> -                                                      1, FOLL_PIN);
> -                               if (!folio) {
> +                               folio = page_folio(&fbatch.folios[i]->page);
> +
> +                               if (try_grab_folio(folio, 1, FOLL_PIN)) {
>                                         folio_batch_release(&fbatch);
>                                         ret = -EINVAL;
>                                         goto err;
> 
> I didn't look deep into the patch, so unsure if that's a valid fix, though.
> May I ask your thoughts?

Perhaps we should propagate the errno which was returned by
try_grab_folio()?

I'll do it this way.  Vivek, please check and let us know?
Kasireddy, Vivek July 5, 2024, 10:11 p.m. UTC | #3
Hi Andrew and SJ, 

> 
> On Fri,  5 Jul 2024 13:48:25 -0700 SeongJae Park <sj@kernel.org> wrote:
> 
> > > + * memfd_pin_folios() - pin folios associated with a memfd
> > [...]
> > > +			for (i = 0; i < nr_found; i++) {
> > > +				/*
> > > +				 * As there can be multiple entries for a
> > > +				 * given folio in the batch returned by
> > > +				 * filemap_get_folios_contig(), the below
> > > +				 * check is to ensure that we pin and return a
> > > +				 * unique set of folios between start and end.
> > > +				 */
> > > +				if (next_idx &&
> > > +				    next_idx != folio_index(fbatch.folios[i]))
> > > +					continue;
> > > +
> > > +				folio = try_grab_folio(&fbatch.folios[i]->page,
> > > +						       1, FOLL_PIN);
> > > +				if (!folio) {
> > > +					folio_batch_release(&fbatch);
> > > +					ret = -EINVAL;
> > > +					goto err;
> > > +				}
> >
> > I found this patch is applied on mm-unstable as commit 7618d1ff59ef
> ("mm/gup:
> > introduce memfd_pin_folios() for pinning memfd folios").  Somehow,
> however, the
> > commit has changd the above try_grab_folio() call to try_grab_folio_fast()
> > call.
> >
> > As a result, building kernel without CONFIG_MMU fais as below:
> >
> > ...
> >
> > Maybe the change has made to fix conflict with another mm-unstable
> commit
> > 02a2d55767d1 ("mm: gup: stop abusing try_grab_folio"), but forgot the
> > CONFIG_MMU unset case?
> 
> Yes.  That patch didn't add a CONFIG_MMU=n version of
> try_grab_folio_fast().  Maybe it should have?
> 
> > I confirmed the failure disappears after further cleanup like below:
> >
> > diff --git a/mm/gup.c b/mm/gup.c
> > index 46a266ed84f7..9f4902425070 100644
> > --- a/mm/gup.c
> > +++ b/mm/gup.c
> > @@ -3859,9 +3859,9 @@ long memfd_pin_folios(struct file *memfd, loff_t
> start, loff_t end,
> >                                     next_idx != folio_index(fbatch.folios[i]))
> >                                         continue;
> >
> > -                               folio = try_grab_folio_fast(&fbatch.folios[i]->page,
> > -                                                      1, FOLL_PIN);
> > -                               if (!folio) {
> > +                               folio = page_folio(&fbatch.folios[i]->page);
> > +
> > +                               if (try_grab_folio(folio, 1, FOLL_PIN)) {
> >                                         folio_batch_release(&fbatch);
> >                                         ret = -EINVAL;
> >                                         goto err;
> >
> > I didn't look deep into the patch, so unsure if that's a valid fix, though.
> > May I ask your thoughts?
> 
> Perhaps we should propagate the errno which was returned by
> try_grab_folio()?
> 
> I'll do it this way.  Vivek, please check and let us know?
Yeah, memfd_pin_folios() doesn't need the fast version, so replacing with
the slow version (try_grab_folio) should be fine. And, as you suggest,
propagating the errno returned by try_grab_folio() would be the right thing
to do instead of explicitly setting errno to -EINVAL. Either way, this change is
Acked-by: Vivek Kasireddy <vivek.kasireddy@intel.com>

Thanks,
Vivek
Andrew Morton July 5, 2024, 10:55 p.m. UTC | #4
On Fri, 5 Jul 2024 22:11:14 +0000 "Kasireddy, Vivek" <vivek.kasireddy@intel.com> wrote:

> Hi Andrew and SJ, 
> 
> > 
> > >
> > > I didn't look deep into the patch, so unsure if that's a valid fix, though.
> > > May I ask your thoughts?
> > 
> > Perhaps we should propagate the errno which was returned by
> > try_grab_folio()?
> > 
> > I'll do it this way.  Vivek, please check and let us know?
> Yeah, memfd_pin_folios() doesn't need the fast version, so replacing with
> the slow version (try_grab_folio) should be fine. And, as you suggest,
> propagating the errno returned by try_grab_folio() would be the right thing
> to do instead of explicitly setting errno to -EINVAL. Either way, this change is
> Acked-by: Vivek Kasireddy <vivek.kasireddy@intel.com>

Cool, thanks.

We could do this to propagate the try_grab_folio() return value:

--- a/mm/gup.c~mm-gup-introduce-memfd_pin_folios-for-pinning-memfd-folios-fix-fix
+++ a/mm/gup.c
@@ -3848,6 +3848,8 @@ long memfd_pin_folios(struct file *memfd
 
 			next_idx = 0;
 			for (i = 0; i < nr_found; i++) {
+				int ret2;
+
 				/*
 				 * As there can be multiple entries for a
 				 * given folio in the batch returned by
@@ -3860,10 +3862,10 @@ long memfd_pin_folios(struct file *memfd
 					continue;
 
 				folio = page_folio(&fbatch.folios[i]->page);
-
-				if (try_grab_folio(folio, 1, FOLL_PIN)) {
+				ret2 = try_grab_folio(folio, 1, FOLL_PIN);
+				if (ret2) {
 					folio_batch_release(&fbatch);
-					ret = -EINVAL;
+					ret = ret2;
 					goto err;
 				}
 

But try_grab_folio can return that weird -EREMOTEIO.  The
try_grab_folio() kerneldoc doesn't even mention that - it incorrectly
claims that only -ENOMEM can be returned. (needs fixing!).

And if memfd_pin_folios() returns -EREMOTEIO then I expect
udmabuf_ioctl() will return -EREMOTEIO to userspace.  And userspace
will wonder "what the hell is that".  If there's a udmabuf_ioctl
manpage then will that explain this errno?  And similar concerns for
future callers of memfd_pin_folios().
Andrew Morton July 12, 2024, 10:32 p.m. UTC | #5
On Fri, 5 Jul 2024 15:55:23 -0700 Andrew Morton <akpm@linux-foundation.org> wrote:

> On Fri, 5 Jul 2024 22:11:14 +0000 "Kasireddy, Vivek" <vivek.kasireddy@intel.com> wrote:
> 
> > Hi Andrew and SJ, 
> > 
> > > 
> > > >
> > > > I didn't look deep into the patch, so unsure if that's a valid fix, though.
> > > > May I ask your thoughts?
> > > 
> > > Perhaps we should propagate the errno which was returned by
> > > try_grab_folio()?
> > > 
> > > I'll do it this way.  Vivek, please check and let us know?
> > Yeah, memfd_pin_folios() doesn't need the fast version, so replacing with
> > the slow version (try_grab_folio) should be fine. And, as you suggest,
> > propagating the errno returned by try_grab_folio() would be the right thing
> > to do instead of explicitly setting errno to -EINVAL. Either way, this change is
> > Acked-by: Vivek Kasireddy <vivek.kasireddy@intel.com>
> 
> Cool, thanks.
> 
> We could do this to propagate the try_grab_folio() return value:
> 
> --- a/mm/gup.c~mm-gup-introduce-memfd_pin_folios-for-pinning-memfd-folios-fix-fix
> +++ a/mm/gup.c
> @@ -3848,6 +3848,8 @@ long memfd_pin_folios(struct file *memfd
>  
>  			next_idx = 0;
>  			for (i = 0; i < nr_found; i++) {
> +				int ret2;
> +
>  				/*
>  				 * As there can be multiple entries for a
>  				 * given folio in the batch returned by
> @@ -3860,10 +3862,10 @@ long memfd_pin_folios(struct file *memfd
>  					continue;
>  
>  				folio = page_folio(&fbatch.folios[i]->page);
> -
> -				if (try_grab_folio(folio, 1, FOLL_PIN)) {
> +				ret2 = try_grab_folio(folio, 1, FOLL_PIN);
> +				if (ret2) {
>  					folio_batch_release(&fbatch);
> -					ret = -EINVAL;
> +					ret = ret2;
>  					goto err;
>  				}
>  
> 
> But try_grab_folio can return that weird -EREMOTEIO.  The
> try_grab_folio() kerneldoc doesn't even mention that - it incorrectly
> claims that only -ENOMEM can be returned. (needs fixing!).
> 
> And if memfd_pin_folios() returns -EREMOTEIO then I expect
> udmabuf_ioctl() will return -EREMOTEIO to userspace.  And userspace
> will wonder "what the hell is that".  If there's a udmabuf_ioctl
> manpage then will that explain this errno?  And similar concerns for
> future callers of memfd_pin_folios().

-ENOREPLY.  I'll drop the above fixup.
Kasireddy, Vivek July 14, 2024, 2:30 a.m. UTC | #6
Hi Andrew,

> 
> > Hi Andrew and SJ,
> >
> > >
> > > >
> > > > I didn't look deep into the patch, so unsure if that's a valid fix, though.
> > > > May I ask your thoughts?
> > >
> > > Perhaps we should propagate the errno which was returned by
> > > try_grab_folio()?
> > >
> > > I'll do it this way.  Vivek, please check and let us know?
> > Yeah, memfd_pin_folios() doesn't need the fast version, so replacing with
> > the slow version (try_grab_folio) should be fine. And, as you suggest,
> > propagating the errno returned by try_grab_folio() would be the right thing
> > to do instead of explicitly setting errno to -EINVAL. Either way, this change is
> > Acked-by: Vivek Kasireddy <vivek.kasireddy@intel.com>
> 
> Cool, thanks.
> 
> We could do this to propagate the try_grab_folio() return value:
> 
> --- a/mm/gup.c~mm-gup-introduce-memfd_pin_folios-for-pinning-memfd-
> folios-fix-fix
> +++ a/mm/gup.c
> @@ -3848,6 +3848,8 @@ long memfd_pin_folios(struct file *memfd
> 
>  			next_idx = 0;
>  			for (i = 0; i < nr_found; i++) {
> +				int ret2;
Is there any reason why you introduced a new variable instead of just reusing ret?

> +
>  				/*
>  				 * As there can be multiple entries for a
>  				 * given folio in the batch returned by
> @@ -3860,10 +3862,10 @@ long memfd_pin_folios(struct file *memfd
>  					continue;
> 
>  				folio = page_folio(&fbatch.folios[i]->page);
> -
> -				if (try_grab_folio(folio, 1, FOLL_PIN)) {
> +				ret2 = try_grab_folio(folio, 1, FOLL_PIN);
> +				if (ret2) {
>  					folio_batch_release(&fbatch);
> -					ret = -EINVAL;
> +					ret = ret2;
>  					goto err;
>  				}
> 
> 
> But try_grab_folio can return that weird -EREMOTEIO.  The
> try_grab_folio() kerneldoc doesn't even mention that - it incorrectly
> claims that only -ENOMEM can be returned. (needs fixing!).
> 
> And if memfd_pin_folios() returns -EREMOTEIO then I expect
> udmabuf_ioctl() will return -EREMOTEIO to userspace.  And userspace
It is not clear to me if userspace needs to do anything in particular to handle
this specific error. At the moment, Qemu (userspace user of udmabuf_ioctl)
does not do anything special for any error codes, and just treats them all as
failures though.

> will wonder "what the hell is that".  If there's a udmabuf_ioctl
> manpage then will that explain this errno?  And similar concerns for
> future callers of memfd_pin_folios().
Sure, we can definitely add documentation explaining this situation once we
agree how the userspace needs to handle this specific error code.

Thanks,
Vivek
diff mbox series

Patch

diff --git a/include/linux/memfd.h b/include/linux/memfd.h
index e7abf6fa4c52..3f2cf339ceaf 100644
--- a/include/linux/memfd.h
+++ b/include/linux/memfd.h
@@ -6,11 +6,16 @@ 
 
 #ifdef CONFIG_MEMFD_CREATE
 extern long memfd_fcntl(struct file *file, unsigned int cmd, unsigned int arg);
+struct folio *memfd_alloc_folio(struct file *memfd, pgoff_t idx);
 #else
 static inline long memfd_fcntl(struct file *f, unsigned int c, unsigned int a)
 {
 	return -EINVAL;
 }
+static inline struct folio *memfd_alloc_folio(struct file *memfd, pgoff_t idx)
+{
+	return ERR_PTR(-EINVAL);
+}
 #endif
 
 #endif /* __LINUX_MEMFD_H */
diff --git a/include/linux/mm.h b/include/linux/mm.h
index c0ee5f7978a0..2bdeb94c2a28 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -2510,6 +2510,9 @@  long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
 		    struct page **pages, unsigned int gup_flags);
 long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
 		    struct page **pages, unsigned int gup_flags);
+long memfd_pin_folios(struct file *memfd, loff_t start, loff_t end,
+		      struct folio **folios, unsigned int max_folios,
+		      pgoff_t *offset);
 
 int get_user_pages_fast(unsigned long start, int nr_pages,
 			unsigned int gup_flags, struct page **pages);
diff --git a/mm/gup.c b/mm/gup.c
index a88e19c78730..94160abbf499 100644
--- a/mm/gup.c
+++ b/mm/gup.c
@@ -5,6 +5,7 @@ 
 #include <linux/spinlock.h>
 
 #include <linux/mm.h>
+#include <linux/memfd.h>
 #include <linux/memremap.h>
 #include <linux/pagemap.h>
 #include <linux/rmap.h>
@@ -17,6 +18,7 @@ 
 #include <linux/hugetlb.h>
 #include <linux/migrate.h>
 #include <linux/mm_inline.h>
+#include <linux/pagevec.h>
 #include <linux/sched/mm.h>
 #include <linux/shmem_fs.h>
 
@@ -3747,3 +3749,138 @@  long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
 				     &locked, gup_flags);
 }
 EXPORT_SYMBOL(pin_user_pages_unlocked);
+
+/**
+ * memfd_pin_folios() - pin folios associated with a memfd
+ * @memfd:      the memfd whose folios are to be pinned
+ * @start:      the first memfd offset
+ * @end:        the last memfd offset (inclusive)
+ * @folios:     array that receives pointers to the folios pinned
+ * @max_folios: maximum number of entries in @folios
+ * @offset:     the offset into the first folio
+ *
+ * Attempt to pin folios associated with a memfd in the contiguous range
+ * [start, end]. Given that a memfd is either backed by shmem or hugetlb,
+ * the folios can either be found in the page cache or need to be allocated
+ * if necessary. Once the folios are located, they are all pinned via
+ * FOLL_PIN and @offset is populatedwith the offset into the first folio.
+ * And, eventually, these pinned folios must be released either using
+ * unpin_folios() or unpin_folio().
+ *
+ * It must be noted that the folios may be pinned for an indefinite amount
+ * of time. And, in most cases, the duration of time they may stay pinned
+ * would be controlled by the userspace. This behavior is effectively the
+ * same as using FOLL_LONGTERM with other GUP APIs.
+ *
+ * Returns number of folios pinned, which could be less than @max_folios
+ * as it depends on the folio sizes that cover the range [start, end].
+ * If no folios were pinned, it returns -errno.
+ */
+long memfd_pin_folios(struct file *memfd, loff_t start, loff_t end,
+		      struct folio **folios, unsigned int max_folios,
+		      pgoff_t *offset)
+{
+	unsigned int flags, nr_folios, nr_found;
+	unsigned int i, pgshift = PAGE_SHIFT;
+	pgoff_t start_idx, end_idx, next_idx;
+	struct folio *folio = NULL;
+	struct folio_batch fbatch;
+	struct hstate *h;
+	long ret = -EINVAL;
+
+	if (start < 0 || start > end || !max_folios)
+		return -EINVAL;
+
+	if (!memfd)
+		return -EINVAL;
+
+	if (!shmem_file(memfd) && !is_file_hugepages(memfd))
+		return -EINVAL;
+
+	if (is_file_hugepages(memfd)) {
+		h = hstate_file(memfd);
+		pgshift = huge_page_shift(h);
+	}
+
+	flags = memalloc_pin_save();
+	do {
+		nr_folios = 0;
+		start_idx = start >> pgshift;
+		end_idx = end >> pgshift;
+		if (is_file_hugepages(memfd)) {
+			start_idx <<= huge_page_order(h);
+			end_idx <<= huge_page_order(h);
+		}
+
+		folio_batch_init(&fbatch);
+		while (start_idx <= end_idx && nr_folios < max_folios) {
+			/*
+			 * In most cases, we should be able to find the folios
+			 * in the page cache. If we cannot find them for some
+			 * reason, we try to allocate them and add them to the
+			 * page cache.
+			 */
+			nr_found = filemap_get_folios_contig(memfd->f_mapping,
+							     &start_idx,
+							     end_idx,
+							     &fbatch);
+			if (folio) {
+				folio_put(folio);
+				folio = NULL;
+			}
+
+			next_idx = 0;
+			for (i = 0; i < nr_found; i++) {
+				/*
+				 * As there can be multiple entries for a
+				 * given folio in the batch returned by
+				 * filemap_get_folios_contig(), the below
+				 * check is to ensure that we pin and return a
+				 * unique set of folios between start and end.
+				 */
+				if (next_idx &&
+				    next_idx != folio_index(fbatch.folios[i]))
+					continue;
+
+				folio = try_grab_folio(&fbatch.folios[i]->page,
+						       1, FOLL_PIN);
+				if (!folio) {
+					folio_batch_release(&fbatch);
+					ret = -EINVAL;
+					goto err;
+				}
+
+				if (nr_folios == 0)
+					*offset = offset_in_folio(folio, start);
+
+				folios[nr_folios] = folio;
+				next_idx = folio_next_index(folio);
+				if (++nr_folios == max_folios)
+					break;
+			}
+
+			folio = NULL;
+			folio_batch_release(&fbatch);
+			if (!nr_found) {
+				folio = memfd_alloc_folio(memfd, start_idx);
+				if (IS_ERR(folio)) {
+					ret = PTR_ERR(folio);
+					if (ret != -EEXIST)
+						goto err;
+				}
+			}
+		}
+
+		ret = check_and_migrate_movable_folios(nr_folios, folios);
+	} while (ret == -EAGAIN);
+
+	memalloc_pin_restore(flags);
+	return ret ? ret : nr_folios;
+err:
+	memalloc_pin_restore(flags);
+	unpin_folios(folios, nr_folios);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(memfd_pin_folios);
+
diff --git a/mm/memfd.c b/mm/memfd.c
index 7d8d3ab3fa37..e7b7c5294d59 100644
--- a/mm/memfd.c
+++ b/mm/memfd.c
@@ -59,6 +59,51 @@  static void memfd_tag_pins(struct xa_state *xas)
 	xas_unlock_irq(xas);
 }
 
+/*
+ * This is a helper function used by memfd_pin_user_pages() in GUP (gup.c).
+ * It is mainly called to allocate a folio in a memfd when the caller
+ * (memfd_pin_folios()) cannot find a folio in the page cache at a given
+ * index in the mapping.
+ */
+struct folio *memfd_alloc_folio(struct file *memfd, pgoff_t idx)
+{
+#ifdef CONFIG_HUGETLB_PAGE
+	struct folio *folio;
+	gfp_t gfp_mask;
+	int err;
+
+	if (is_file_hugepages(memfd)) {
+		/*
+		 * The folio would most likely be accessed by a DMA driver,
+		 * therefore, we have zone memory constraints where we can
+		 * alloc from. Also, the folio will be pinned for an indefinite
+		 * amount of time, so it is not expected to be migrated away.
+		 */
+		gfp_mask = htlb_alloc_mask(hstate_file(memfd));
+		gfp_mask &= ~(__GFP_HIGHMEM | __GFP_MOVABLE);
+
+		folio = alloc_hugetlb_folio_nodemask(hstate_file(memfd),
+						     numa_node_id(),
+						     NULL,
+						     gfp_mask,
+						     false);
+		if (folio && folio_try_get(folio)) {
+			err = hugetlb_add_to_page_cache(folio,
+							memfd->f_mapping,
+							idx);
+			if (err) {
+				folio_put(folio);
+				free_huge_folio(folio);
+				return ERR_PTR(err);
+			}
+			return folio;
+		}
+		return ERR_PTR(-ENOMEM);
+	}
+#endif
+	return shmem_read_folio(memfd->f_mapping, idx);
+}
+
 /*
  * Setting SEAL_WRITE requires us to verify there's no pending writer. However,
  * via get_user_pages(), drivers might have some pending I/O without any active