diff mbox series

[v18,4/9] mm: hugetlb: alloc the vmemmap pages associated with each HugeTLB page

Message ID 20210308102807.59745-5-songmuchun@bytedance.com (mailing list archive)
State New, archived
Headers show
Series Free some vmemmap pages of HugeTLB page | expand

Commit Message

Muchun Song March 8, 2021, 10:28 a.m. UTC
When we free a HugeTLB page to the buddy allocator, we need to allocate
the vmemmap pages associated with it. However, we may not be able to
allocate the vmemmap pages when the system is under memory pressure. In
this case, we just refuse to free the HugeTLB page. This changes behavior
in some corner cases as listed below:

 1) Failing to free a huge page triggered by the user (decrease nr_pages).

    User needs to try again later.

 2) Failing to free a surplus huge page when freed by the application.

    Try again later when freeing a huge page next time.

 3) Failing to dissolve a free huge page on ZONE_MOVABLE via
    offline_pages().

    This can happen when we have plenty of ZONE_MOVABLE memory, but
    not enough kernel memory to allocate vmemmmap pages.  We may even
    be able to migrate huge page contents, but will not be able to
    dissolve the source huge page.  This will prevent an offline
    operation and is unfortunate as memory offlining is expected to
    succeed on movable zones.  Users that depend on memory hotplug
    to succeed for movable zones should carefully consider whether the
    memory savings gained from this feature are worth the risk of
    possibly not being able to offline memory in certain situations.

 4) Failing to dissolve a huge page on CMA/ZONE_MOVABLE via
    alloc_contig_range() - once we have that handling in place. Mainly
    affects CMA and virtio-mem.

    Similar to 3). virito-mem will handle migration errors gracefully.
    CMA might be able to fallback on other free areas within the CMA
    region.

Vmemmap pages are allocated from the page freeing context. In order for
those allocations to be not disruptive (e.g. trigger oom killer)
__GFP_NORETRY is used. hugetlb_lock is dropped for the allocation
because a non sleeping allocation would be too fragile and it could fail
too easily under memory pressure. GFP_ATOMIC or other modes to access
memory reserves is not used because we want to prevent consuming
reserves under heavy hugetlb freeing.

Signed-off-by: Muchun Song <songmuchun@bytedance.com>
Tested-by: Chen Huang <chenhuang5@huawei.com>
Tested-by: Bodeddula Balasubramaniam <bodeddub@amazon.com>
---
 Documentation/admin-guide/mm/hugetlbpage.rst |  8 +++
 include/linux/mm.h                           |  2 +
 mm/hugetlb.c                                 | 92 +++++++++++++++++++++-------
 mm/hugetlb_vmemmap.c                         | 32 ++++++----
 mm/hugetlb_vmemmap.h                         | 23 +++++++
 mm/sparse-vmemmap.c                          | 75 ++++++++++++++++++++++-
 6 files changed, 197 insertions(+), 35 deletions(-)

Comments

Oscar Salvador March 10, 2021, 2:21 p.m. UTC | #1
On Mon, Mar 08, 2021 at 06:28:02PM +0800, Muchun Song wrote:
> When we free a HugeTLB page to the buddy allocator, we need to allocate
> the vmemmap pages associated with it. However, we may not be able to
> allocate the vmemmap pages when the system is under memory pressure. In
> this case, we just refuse to free the HugeTLB page. This changes behavior
> in some corner cases as listed below:
> 
>  1) Failing to free a huge page triggered by the user (decrease nr_pages).
> 
>     User needs to try again later.
> 
>  2) Failing to free a surplus huge page when freed by the application.
> 
>     Try again later when freeing a huge page next time.
> 
>  3) Failing to dissolve a free huge page on ZONE_MOVABLE via
>     offline_pages().
> 
>     This can happen when we have plenty of ZONE_MOVABLE memory, but
>     not enough kernel memory to allocate vmemmmap pages.  We may even
>     be able to migrate huge page contents, but will not be able to
>     dissolve the source huge page.  This will prevent an offline
>     operation and is unfortunate as memory offlining is expected to
>     succeed on movable zones.  Users that depend on memory hotplug
>     to succeed for movable zones should carefully consider whether the
>     memory savings gained from this feature are worth the risk of
>     possibly not being able to offline memory in certain situations.

This is nice to have it here, but a normal user won't dig in the kernel to
figure this out, so my question is: Do we have this documented somewhere under
Documentation/?
If not, could we document it there? It is nice to warn about this things were
sysadmins can find them.

>  4) Failing to dissolve a huge page on CMA/ZONE_MOVABLE via
>     alloc_contig_range() - once we have that handling in place. Mainly
>     affects CMA and virtio-mem.
> 
>     Similar to 3). virito-mem will handle migration errors gracefully.
>     CMA might be able to fallback on other free areas within the CMA
>     region.
> 
> Vmemmap pages are allocated from the page freeing context. In order for
> those allocations to be not disruptive (e.g. trigger oom killer)
> __GFP_NORETRY is used. hugetlb_lock is dropped for the allocation
> because a non sleeping allocation would be too fragile and it could fail
> too easily under memory pressure. GFP_ATOMIC or other modes to access
> memory reserves is not used because we want to prevent consuming
> reserves under heavy hugetlb freeing.
> 
> Signed-off-by: Muchun Song <songmuchun@bytedance.com>
> Tested-by: Chen Huang <chenhuang5@huawei.com>
> Tested-by: Bodeddula Balasubramaniam <bodeddub@amazon.com>

Sorry for jumping in late.
It looks good to me:

Reviewed-by: Oscar Salvador <osalvador@suse.de>

Minor request above and below:

> ---
>  Documentation/admin-guide/mm/hugetlbpage.rst |  8 +++
>  include/linux/mm.h                           |  2 +
>  mm/hugetlb.c                                 | 92 +++++++++++++++++++++-------
>  mm/hugetlb_vmemmap.c                         | 32 ++++++----
>  mm/hugetlb_vmemmap.h                         | 23 +++++++
>  mm/sparse-vmemmap.c                          | 75 ++++++++++++++++++++++-
>  6 files changed, 197 insertions(+), 35 deletions(-)

[...]



Could we place a brief comment about what we expect to return here?

> -static inline unsigned long free_vmemmap_pages_size_per_hpage(struct hstate *h)
> +int alloc_huge_page_vmemmap(struct hstate *h, struct page *head)
>  {
> -	return (unsigned long)free_vmemmap_pages_per_hpage(h) << PAGE_SHIFT;
> +	unsigned long vmemmap_addr = (unsigned long)head;
> +	unsigned long vmemmap_end, vmemmap_reuse;
> +
> +	if (!free_vmemmap_pages_per_hpage(h))
> +		return 0;
> +
> +	vmemmap_addr += RESERVE_VMEMMAP_SIZE;
> +	vmemmap_end = vmemmap_addr + free_vmemmap_pages_size_per_hpage(h);
> +	vmemmap_reuse = vmemmap_addr - PAGE_SIZE;
> +	/*
> +	 * The pages which the vmemmap virtual address range [@vmemmap_addr,
> +	 * @vmemmap_end) are mapped to are freed to the buddy allocator, and
> +	 * the range is mapped to the page which @vmemmap_reuse is mapped to.
> +	 * When a HugeTLB page is freed to the buddy allocator, previously
> +	 * discarded vmemmap pages must be allocated and remapping.
> +	 */
> +	return vmemmap_remap_alloc(vmemmap_addr, vmemmap_end, vmemmap_reuse,
> +				   GFP_KERNEL | __GFP_NORETRY | __GFP_THISNODE);
>  }
Michal Hocko March 10, 2021, 3:19 p.m. UTC | #2
On Mon 08-03-21 18:28:02, Muchun Song wrote:
[...]
> -static void update_and_free_page(struct hstate *h, struct page *page)
> +static int update_and_free_page(struct hstate *h, struct page *page)
> +	__releases(&hugetlb_lock) __acquires(&hugetlb_lock)
>  {
>  	int i;
>  	struct page *subpage = page;
> +	int nid = page_to_nid(page);
>  
>  	if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
> -		return;
> +		return 0;
>  
>  	h->nr_huge_pages--;
> -	h->nr_huge_pages_node[page_to_nid(page)]--;
> +	h->nr_huge_pages_node[nid]--;
> +	VM_BUG_ON_PAGE(hugetlb_cgroup_from_page(page), page);
> +	VM_BUG_ON_PAGE(hugetlb_cgroup_from_page_rsvd(page), page);

> +	set_page_refcounted(page);
> +	set_compound_page_dtor(page, NULL_COMPOUND_DTOR);
> +
> +	/*
> +	 * If the vmemmap pages associated with the HugeTLB page can be
> +	 * optimized or the page is gigantic, we might block in
> +	 * alloc_huge_page_vmemmap() or free_gigantic_page(). In both
> +	 * cases, drop the hugetlb_lock.
> +	 */
> +	if (free_vmemmap_pages_per_hpage(h) || hstate_is_gigantic(h))
> +		spin_unlock(&hugetlb_lock);
> +
> +	if (alloc_huge_page_vmemmap(h, page)) {
> +		spin_lock(&hugetlb_lock);
> +		INIT_LIST_HEAD(&page->lru);
> +		set_compound_page_dtor(page, HUGETLB_PAGE_DTOR);
> +		h->nr_huge_pages++;
> +		h->nr_huge_pages_node[nid]++;
> +
> +		/*
> +		 * If we cannot allocate vmemmap pages, just refuse to free the
> +		 * page and put the page back on the hugetlb free list and treat
> +		 * as a surplus page.
> +		 */
> +		h->surplus_huge_pages++;
> +		h->surplus_huge_pages_node[nid]++;
> +
> +		/*
> +		 * The refcount can possibly be increased by memory-failure or
> +		 * soft_offline handlers.

This comment could be more helpful. I believe you want to say this
		/*
		 * HWpoisoning code can increment the reference
		 * count here. If there is a race then bail out
		 * the holder of the additional reference count will
		 * free up the page with put_page.
> +		 */
> +		if (likely(put_page_testzero(page))) {
> +			arch_clear_hugepage_flags(page);
> +			enqueue_huge_page(h, page);
> +		}
> +
> +		return -ENOMEM;
> +	}
> +
>  	for (i = 0; i < pages_per_huge_page(h);
>  	     i++, subpage = mem_map_next(subpage, page, i)) {
>  		subpage->flags &= ~(1 << PG_locked | 1 << PG_error |
[...]
> @@ -1447,7 +1486,7 @@ void free_huge_page(struct page *page)
>  	/*
>  	 * Defer freeing if in non-task context to avoid hugetlb_lock deadlock.
>  	 */
> -	if (!in_task()) {
> +	if (in_atomic()) {

As I've said elsewhere in_atomic doesn't work for CONFIG_PREEMPT_COUNT=n.
We need this change for other reasons and so it would be better to pull
it out into a separate patch which also makes HUGETLB depend on
PREEMPT_COUNT.

[...]
> @@ -1771,8 +1813,12 @@ int dissolve_free_huge_page(struct page *page)
>  		h->free_huge_pages--;
>  		h->free_huge_pages_node[nid]--;
>  		h->max_huge_pages--;
> -		update_and_free_page(h, head);
> -		rc = 0;
> +		rc = update_and_free_page(h, head);
> +		if (rc) {
> +			h->surplus_huge_pages--;
> +			h->surplus_huge_pages_node[nid]--;
> +			h->max_huge_pages++;

This is quite ugly and confusing. update_and_free_page is careful to do
the proper counters accounting and now you just override it partially.
Why cannot we rely on update_and_free_page do the right thing?
Mike Kravetz March 10, 2021, 6:56 p.m. UTC | #3
On 3/10/21 7:19 AM, Michal Hocko wrote:
> On Mon 08-03-21 18:28:02, Muchun Song wrote:
> [...]
>> @@ -1447,7 +1486,7 @@ void free_huge_page(struct page *page)
>>  	/*
>>  	 * Defer freeing if in non-task context to avoid hugetlb_lock deadlock.
>>  	 */
>> -	if (!in_task()) {
>> +	if (in_atomic()) {
> 
> As I've said elsewhere in_atomic doesn't work for CONFIG_PREEMPT_COUNT=n.
> We need this change for other reasons and so it would be better to pull
> it out into a separate patch which also makes HUGETLB depend on
> PREEMPT_COUNT.

Yes, the issue of calling put_page for hugetlb pages from any context
still needs work.  IMO, that is outside the scope of this series.  We
already have code in this path which blocks/sleeps.

Making HUGETLB depend on PREEMPT_COUNT is too restrictive.  IIUC,
PREEMPT_COUNT will only be enabled if we enable:
PREEMPT "Preemptible Kernel (Low-Latency Desktop)"
PREEMPT_RT "Fully Preemptible Kernel (Real-Time)"
or, other 'debug' options.  These are not enabled in 'more common'
kernels.  Of course, we do not want to disable HUGETLB in common
configurations.

I'll put together a separate patch where we can discuss the merits of
making the change from !in_task to in_atomic, and what work remains in
this put_page area.
Michal Hocko March 10, 2021, 9:11 p.m. UTC | #4
On Wed 10-03-21 10:56:08, Mike Kravetz wrote:
> On 3/10/21 7:19 AM, Michal Hocko wrote:
> > On Mon 08-03-21 18:28:02, Muchun Song wrote:
> > [...]
> >> @@ -1447,7 +1486,7 @@ void free_huge_page(struct page *page)
> >>  	/*
> >>  	 * Defer freeing if in non-task context to avoid hugetlb_lock deadlock.
> >>  	 */
> >> -	if (!in_task()) {
> >> +	if (in_atomic()) {
> > 
> > As I've said elsewhere in_atomic doesn't work for CONFIG_PREEMPT_COUNT=n.
> > We need this change for other reasons and so it would be better to pull
> > it out into a separate patch which also makes HUGETLB depend on
> > PREEMPT_COUNT.
> 
> Yes, the issue of calling put_page for hugetlb pages from any context
> still needs work.  IMO, that is outside the scope of this series.  We
> already have code in this path which blocks/sleeps.
> 
> Making HUGETLB depend on PREEMPT_COUNT is too restrictive.  IIUC,
> PREEMPT_COUNT will only be enabled if we enable:
> PREEMPT "Preemptible Kernel (Low-Latency Desktop)"
> PREEMPT_RT "Fully Preemptible Kernel (Real-Time)"
> or, other 'debug' options.  These are not enabled in 'more common'
> kernels.  Of course, we do not want to disable HUGETLB in common
> configurations.

I haven't tried that but PREEMPT_COUNT should be selectable even without
any change to the preemption model (e.g. !PREEMPT).
Paul E. McKenney March 10, 2021, 9:49 p.m. UTC | #5
On Wed, Mar 10, 2021 at 10:11:22PM +0100, Michal Hocko wrote:
> On Wed 10-03-21 10:56:08, Mike Kravetz wrote:
> > On 3/10/21 7:19 AM, Michal Hocko wrote:
> > > On Mon 08-03-21 18:28:02, Muchun Song wrote:
> > > [...]
> > >> @@ -1447,7 +1486,7 @@ void free_huge_page(struct page *page)
> > >>  	/*
> > >>  	 * Defer freeing if in non-task context to avoid hugetlb_lock deadlock.
> > >>  	 */
> > >> -	if (!in_task()) {
> > >> +	if (in_atomic()) {
> > > 
> > > As I've said elsewhere in_atomic doesn't work for CONFIG_PREEMPT_COUNT=n.
> > > We need this change for other reasons and so it would be better to pull
> > > it out into a separate patch which also makes HUGETLB depend on
> > > PREEMPT_COUNT.
> > 
> > Yes, the issue of calling put_page for hugetlb pages from any context
> > still needs work.  IMO, that is outside the scope of this series.  We
> > already have code in this path which blocks/sleeps.
> > 
> > Making HUGETLB depend on PREEMPT_COUNT is too restrictive.  IIUC,
> > PREEMPT_COUNT will only be enabled if we enable:
> > PREEMPT "Preemptible Kernel (Low-Latency Desktop)"
> > PREEMPT_RT "Fully Preemptible Kernel (Real-Time)"
> > or, other 'debug' options.  These are not enabled in 'more common'
> > kernels.  Of course, we do not want to disable HUGETLB in common
> > configurations.
> 
> I haven't tried that but PREEMPT_COUNT should be selectable even without
> any change to the preemption model (e.g. !PREEMPT).

It works reliably for me, for example as in the diff below.  So,
as Michal says, you should be able to add "select PREEMPT_COUNT" to
whatever Kconfig option you need to.

							Thanx, Paul

diff --git a/kernel/rcu/Kconfig b/kernel/rcu/Kconfig
index 3128b7c..7d9f989 100644
--- a/kernel/rcu/Kconfig
+++ b/kernel/rcu/Kconfig
@@ -8,6 +8,7 @@ menu "RCU Subsystem"
 config TREE_RCU
 	bool
 	default y if SMP
+	select PREEMPT_COUNT
 	help
 	  This option selects the RCU implementation that is
 	  designed for very large SMP system with hundreds or
Mike Kravetz March 10, 2021, 10:10 p.m. UTC | #6
On 3/10/21 1:49 PM, Paul E. McKenney wrote:
> On Wed, Mar 10, 2021 at 10:11:22PM +0100, Michal Hocko wrote:
>> On Wed 10-03-21 10:56:08, Mike Kravetz wrote:
>>> On 3/10/21 7:19 AM, Michal Hocko wrote:
>>>> On Mon 08-03-21 18:28:02, Muchun Song wrote:
>>>> [...]
>>>>> @@ -1447,7 +1486,7 @@ void free_huge_page(struct page *page)
>>>>>  	/*
>>>>>  	 * Defer freeing if in non-task context to avoid hugetlb_lock deadlock.
>>>>>  	 */
>>>>> -	if (!in_task()) {
>>>>> +	if (in_atomic()) {
>>>>
>>>> As I've said elsewhere in_atomic doesn't work for CONFIG_PREEMPT_COUNT=n.
>>>> We need this change for other reasons and so it would be better to pull
>>>> it out into a separate patch which also makes HUGETLB depend on
>>>> PREEMPT_COUNT.
>>>
>>> Yes, the issue of calling put_page for hugetlb pages from any context
>>> still needs work.  IMO, that is outside the scope of this series.  We
>>> already have code in this path which blocks/sleeps.
>>>
>>> Making HUGETLB depend on PREEMPT_COUNT is too restrictive.  IIUC,
>>> PREEMPT_COUNT will only be enabled if we enable:
>>> PREEMPT "Preemptible Kernel (Low-Latency Desktop)"
>>> PREEMPT_RT "Fully Preemptible Kernel (Real-Time)"
>>> or, other 'debug' options.  These are not enabled in 'more common'
>>> kernels.  Of course, we do not want to disable HUGETLB in common
>>> configurations.
>>
>> I haven't tried that but PREEMPT_COUNT should be selectable even without
>> any change to the preemption model (e.g. !PREEMPT).
> 
> It works reliably for me, for example as in the diff below.  So,
> as Michal says, you should be able to add "select PREEMPT_COUNT" to
> whatever Kconfig option you need to.
> 

Thanks Paul.

I may have been misreading Michal's suggestion of "make HUGETLB depend on
PREEMPT_COUNT".  We could "select PREEMPT_COUNT" if HUGETLB is enabled.
However, since HUGETLB is enabled in most configs, then this would
result in PREEMPT_COUNT also being enabled in most configs.  I honestly
do not know how much this will cost us?  I assume that if it was free or
really cheap it would already be always on?
Paul E. McKenney March 10, 2021, 11:28 p.m. UTC | #7
On Wed, Mar 10, 2021 at 02:10:12PM -0800, Mike Kravetz wrote:
> On 3/10/21 1:49 PM, Paul E. McKenney wrote:
> > On Wed, Mar 10, 2021 at 10:11:22PM +0100, Michal Hocko wrote:
> >> On Wed 10-03-21 10:56:08, Mike Kravetz wrote:
> >>> On 3/10/21 7:19 AM, Michal Hocko wrote:
> >>>> On Mon 08-03-21 18:28:02, Muchun Song wrote:
> >>>> [...]
> >>>>> @@ -1447,7 +1486,7 @@ void free_huge_page(struct page *page)
> >>>>>  	/*
> >>>>>  	 * Defer freeing if in non-task context to avoid hugetlb_lock deadlock.
> >>>>>  	 */
> >>>>> -	if (!in_task()) {
> >>>>> +	if (in_atomic()) {
> >>>>
> >>>> As I've said elsewhere in_atomic doesn't work for CONFIG_PREEMPT_COUNT=n.
> >>>> We need this change for other reasons and so it would be better to pull
> >>>> it out into a separate patch which also makes HUGETLB depend on
> >>>> PREEMPT_COUNT.
> >>>
> >>> Yes, the issue of calling put_page for hugetlb pages from any context
> >>> still needs work.  IMO, that is outside the scope of this series.  We
> >>> already have code in this path which blocks/sleeps.
> >>>
> >>> Making HUGETLB depend on PREEMPT_COUNT is too restrictive.  IIUC,
> >>> PREEMPT_COUNT will only be enabled if we enable:
> >>> PREEMPT "Preemptible Kernel (Low-Latency Desktop)"
> >>> PREEMPT_RT "Fully Preemptible Kernel (Real-Time)"
> >>> or, other 'debug' options.  These are not enabled in 'more common'
> >>> kernels.  Of course, we do not want to disable HUGETLB in common
> >>> configurations.
> >>
> >> I haven't tried that but PREEMPT_COUNT should be selectable even without
> >> any change to the preemption model (e.g. !PREEMPT).
> > 
> > It works reliably for me, for example as in the diff below.  So,
> > as Michal says, you should be able to add "select PREEMPT_COUNT" to
> > whatever Kconfig option you need to.
> > 
> 
> Thanks Paul.
> 
> I may have been misreading Michal's suggestion of "make HUGETLB depend on
> PREEMPT_COUNT".  We could "select PREEMPT_COUNT" if HUGETLB is enabled.
> However, since HUGETLB is enabled in most configs, then this would
> result in PREEMPT_COUNT also being enabled in most configs.  I honestly
> do not know how much this will cost us?  I assume that if it was free or
> really cheap it would already be always on?

There are a -lot- of configs out there, so are you sure that HUGETLB is
really enabled in most of them?  ;-)

More seriously, I was going by earlier emails in this and related threads
plus Michal's "PREEMPT_COUNT should be selectable".  But there are other
situations that would like PREEMPT_COUNT.  And to your point, some who
would rather PREEMPT_COUNT not be universally enabled.  I haven't seen
any performance or kernel-size numbers from any of them, however.

							Thanx, Paul

> -- 
> Mike Kravetz
> 
> > 							Thanx, Paul
> > 
> > diff --git a/kernel/rcu/Kconfig b/kernel/rcu/Kconfig
> > index 3128b7c..7d9f989 100644
> > --- a/kernel/rcu/Kconfig
> > +++ b/kernel/rcu/Kconfig
> > @@ -8,6 +8,7 @@ menu "RCU Subsystem"
> >  config TREE_RCU
> >  	bool
> >  	default y if SMP
> > +	select PREEMPT_COUNT
> >  	help
> >  	  This option selects the RCU implementation that is
> >  	  designed for very large SMP system with hundreds or
> >
Muchun Song March 11, 2021, 4:13 a.m. UTC | #8
On Wed, Mar 10, 2021 at 10:21 PM Oscar Salvador <osalvador@suse.de> wrote:
>
> On Mon, Mar 08, 2021 at 06:28:02PM +0800, Muchun Song wrote:
> > When we free a HugeTLB page to the buddy allocator, we need to allocate
> > the vmemmap pages associated with it. However, we may not be able to
> > allocate the vmemmap pages when the system is under memory pressure. In
> > this case, we just refuse to free the HugeTLB page. This changes behavior
> > in some corner cases as listed below:
> >
> >  1) Failing to free a huge page triggered by the user (decrease nr_pages).
> >
> >     User needs to try again later.
> >
> >  2) Failing to free a surplus huge page when freed by the application.
> >
> >     Try again later when freeing a huge page next time.
> >
> >  3) Failing to dissolve a free huge page on ZONE_MOVABLE via
> >     offline_pages().
> >
> >     This can happen when we have plenty of ZONE_MOVABLE memory, but
> >     not enough kernel memory to allocate vmemmmap pages.  We may even
> >     be able to migrate huge page contents, but will not be able to
> >     dissolve the source huge page.  This will prevent an offline
> >     operation and is unfortunate as memory offlining is expected to
> >     succeed on movable zones.  Users that depend on memory hotplug
> >     to succeed for movable zones should carefully consider whether the
> >     memory savings gained from this feature are worth the risk of
> >     possibly not being able to offline memory in certain situations.
>
> This is nice to have it here, but a normal user won't dig in the kernel to
> figure this out, so my question is: Do we have this documented somewhere under
> Documentation/?
> If not, could we document it there? It is nice to warn about this things were
> sysadmins can find them.

Make sense. I will do this.

>
> >  4) Failing to dissolve a huge page on CMA/ZONE_MOVABLE via
> >     alloc_contig_range() - once we have that handling in place. Mainly
> >     affects CMA and virtio-mem.
> >
> >     Similar to 3). virito-mem will handle migration errors gracefully.
> >     CMA might be able to fallback on other free areas within the CMA
> >     region.
> >
> > Vmemmap pages are allocated from the page freeing context. In order for
> > those allocations to be not disruptive (e.g. trigger oom killer)
> > __GFP_NORETRY is used. hugetlb_lock is dropped for the allocation
> > because a non sleeping allocation would be too fragile and it could fail
> > too easily under memory pressure. GFP_ATOMIC or other modes to access
> > memory reserves is not used because we want to prevent consuming
> > reserves under heavy hugetlb freeing.
> >
> > Signed-off-by: Muchun Song <songmuchun@bytedance.com>
> > Tested-by: Chen Huang <chenhuang5@huawei.com>
> > Tested-by: Bodeddula Balasubramaniam <bodeddub@amazon.com>
>
> Sorry for jumping in late.
> It looks good to me:
>
> Reviewed-by: Oscar Salvador <osalvador@suse.de>

Thanks.

>
> Minor request above and below:
>
> > ---
> >  Documentation/admin-guide/mm/hugetlbpage.rst |  8 +++
> >  include/linux/mm.h                           |  2 +
> >  mm/hugetlb.c                                 | 92 +++++++++++++++++++++-------
> >  mm/hugetlb_vmemmap.c                         | 32 ++++++----
> >  mm/hugetlb_vmemmap.h                         | 23 +++++++
> >  mm/sparse-vmemmap.c                          | 75 ++++++++++++++++++++++-
> >  6 files changed, 197 insertions(+), 35 deletions(-)
>
> [...]
>
>
>
> Could we place a brief comment about what we expect to return here?

OK. Will do.

>
> > -static inline unsigned long free_vmemmap_pages_size_per_hpage(struct hstate *h)
> > +int alloc_huge_page_vmemmap(struct hstate *h, struct page *head)
> >  {
> > -     return (unsigned long)free_vmemmap_pages_per_hpage(h) << PAGE_SHIFT;
> > +     unsigned long vmemmap_addr = (unsigned long)head;
> > +     unsigned long vmemmap_end, vmemmap_reuse;
> > +
> > +     if (!free_vmemmap_pages_per_hpage(h))
> > +             return 0;
> > +
> > +     vmemmap_addr += RESERVE_VMEMMAP_SIZE;
> > +     vmemmap_end = vmemmap_addr + free_vmemmap_pages_size_per_hpage(h);
> > +     vmemmap_reuse = vmemmap_addr - PAGE_SIZE;
> > +     /*
> > +      * The pages which the vmemmap virtual address range [@vmemmap_addr,
> > +      * @vmemmap_end) are mapped to are freed to the buddy allocator, and
> > +      * the range is mapped to the page which @vmemmap_reuse is mapped to.
> > +      * When a HugeTLB page is freed to the buddy allocator, previously
> > +      * discarded vmemmap pages must be allocated and remapping.
> > +      */
> > +     return vmemmap_remap_alloc(vmemmap_addr, vmemmap_end, vmemmap_reuse,
> > +                                GFP_KERNEL | __GFP_NORETRY | __GFP_THISNODE);
> >  }
>
> --
> Oscar Salvador
> SUSE L3
Muchun Song March 11, 2021, 4:26 a.m. UTC | #9
On Wed, Mar 10, 2021 at 11:19 PM Michal Hocko <mhocko@suse.com> wrote:
>
> On Mon 08-03-21 18:28:02, Muchun Song wrote:
> [...]
> > -static void update_and_free_page(struct hstate *h, struct page *page)
> > +static int update_and_free_page(struct hstate *h, struct page *page)
> > +     __releases(&hugetlb_lock) __acquires(&hugetlb_lock)
> >  {
> >       int i;
> >       struct page *subpage = page;
> > +     int nid = page_to_nid(page);
> >
> >       if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
> > -             return;
> > +             return 0;
> >
> >       h->nr_huge_pages--;
> > -     h->nr_huge_pages_node[page_to_nid(page)]--;
> > +     h->nr_huge_pages_node[nid]--;
> > +     VM_BUG_ON_PAGE(hugetlb_cgroup_from_page(page), page);
> > +     VM_BUG_ON_PAGE(hugetlb_cgroup_from_page_rsvd(page), page);
>
> > +     set_page_refcounted(page);
> > +     set_compound_page_dtor(page, NULL_COMPOUND_DTOR);
> > +
> > +     /*
> > +      * If the vmemmap pages associated with the HugeTLB page can be
> > +      * optimized or the page is gigantic, we might block in
> > +      * alloc_huge_page_vmemmap() or free_gigantic_page(). In both
> > +      * cases, drop the hugetlb_lock.
> > +      */
> > +     if (free_vmemmap_pages_per_hpage(h) || hstate_is_gigantic(h))
> > +             spin_unlock(&hugetlb_lock);
> > +
> > +     if (alloc_huge_page_vmemmap(h, page)) {
> > +             spin_lock(&hugetlb_lock);
> > +             INIT_LIST_HEAD(&page->lru);
> > +             set_compound_page_dtor(page, HUGETLB_PAGE_DTOR);
> > +             h->nr_huge_pages++;
> > +             h->nr_huge_pages_node[nid]++;
> > +
> > +             /*
> > +              * If we cannot allocate vmemmap pages, just refuse to free the
> > +              * page and put the page back on the hugetlb free list and treat
> > +              * as a surplus page.
> > +              */
> > +             h->surplus_huge_pages++;
> > +             h->surplus_huge_pages_node[nid]++;
> > +
> > +             /*
> > +              * The refcount can possibly be increased by memory-failure or
> > +              * soft_offline handlers.
>
> This comment could be more helpful. I believe you want to say this
>                 /*
>                  * HWpoisoning code can increment the reference
>                  * count here. If there is a race then bail out
>                  * the holder of the additional reference count will
>                  * free up the page with put_page.

Right. I will reuse this. Thanks.

> > +              */
> > +             if (likely(put_page_testzero(page))) {
> > +                     arch_clear_hugepage_flags(page);
> > +                     enqueue_huge_page(h, page);
> > +             }
> > +
> > +             return -ENOMEM;
> > +     }
> > +
> >       for (i = 0; i < pages_per_huge_page(h);
> >            i++, subpage = mem_map_next(subpage, page, i)) {
> >               subpage->flags &= ~(1 << PG_locked | 1 << PG_error |
> [...]
> > @@ -1447,7 +1486,7 @@ void free_huge_page(struct page *page)
> >       /*
> >        * Defer freeing if in non-task context to avoid hugetlb_lock deadlock.
> >        */
> > -     if (!in_task()) {
> > +     if (in_atomic()) {
>
> As I've said elsewhere in_atomic doesn't work for CONFIG_PREEMPT_COUNT=n.
> We need this change for other reasons and so it would be better to pull
> it out into a separate patch which also makes HUGETLB depend on
> PREEMPT_COUNT.
>
> [...]
> > @@ -1771,8 +1813,12 @@ int dissolve_free_huge_page(struct page *page)
> >               h->free_huge_pages--;
> >               h->free_huge_pages_node[nid]--;
> >               h->max_huge_pages--;
> > -             update_and_free_page(h, head);
> > -             rc = 0;
> > +             rc = update_and_free_page(h, head);
> > +             if (rc) {
> > +                     h->surplus_huge_pages--;
> > +                     h->surplus_huge_pages_node[nid]--;
> > +                     h->max_huge_pages++;
>
> This is quite ugly and confusing. update_and_free_page is careful to do
> the proper counters accounting and now you just override it partially.
> Why cannot we rely on update_and_free_page do the right thing?

Dissolving path is special here. Since update_and_free_page failed,
the number of surplus pages was incremented.  Surplus pages are
the number of pages greater than max_huge_pages.  Since we are
incrementing max_huge_pages, we should decrement (undo) the
addition to surplus_huge_pages and surplus_huge_pages_node[nid].


>
> --
> Michal Hocko
> SUSE Labs
Michal Hocko March 11, 2021, 8:40 a.m. UTC | #10
On Wed 10-03-21 15:28:51, Paul E. McKenney wrote:
> On Wed, Mar 10, 2021 at 02:10:12PM -0800, Mike Kravetz wrote:
> > On 3/10/21 1:49 PM, Paul E. McKenney wrote:
> > > On Wed, Mar 10, 2021 at 10:11:22PM +0100, Michal Hocko wrote:
> > >> On Wed 10-03-21 10:56:08, Mike Kravetz wrote:
> > >>> On 3/10/21 7:19 AM, Michal Hocko wrote:
> > >>>> On Mon 08-03-21 18:28:02, Muchun Song wrote:
> > >>>> [...]
> > >>>>> @@ -1447,7 +1486,7 @@ void free_huge_page(struct page *page)
> > >>>>>  	/*
> > >>>>>  	 * Defer freeing if in non-task context to avoid hugetlb_lock deadlock.
> > >>>>>  	 */
> > >>>>> -	if (!in_task()) {
> > >>>>> +	if (in_atomic()) {
> > >>>>
> > >>>> As I've said elsewhere in_atomic doesn't work for CONFIG_PREEMPT_COUNT=n.
> > >>>> We need this change for other reasons and so it would be better to pull
> > >>>> it out into a separate patch which also makes HUGETLB depend on
> > >>>> PREEMPT_COUNT.
> > >>>
> > >>> Yes, the issue of calling put_page for hugetlb pages from any context
> > >>> still needs work.  IMO, that is outside the scope of this series.  We
> > >>> already have code in this path which blocks/sleeps.
> > >>>
> > >>> Making HUGETLB depend on PREEMPT_COUNT is too restrictive.  IIUC,
> > >>> PREEMPT_COUNT will only be enabled if we enable:
> > >>> PREEMPT "Preemptible Kernel (Low-Latency Desktop)"
> > >>> PREEMPT_RT "Fully Preemptible Kernel (Real-Time)"
> > >>> or, other 'debug' options.  These are not enabled in 'more common'
> > >>> kernels.  Of course, we do not want to disable HUGETLB in common
> > >>> configurations.
> > >>
> > >> I haven't tried that but PREEMPT_COUNT should be selectable even without
> > >> any change to the preemption model (e.g. !PREEMPT).
> > > 
> > > It works reliably for me, for example as in the diff below.  So,
> > > as Michal says, you should be able to add "select PREEMPT_COUNT" to
> > > whatever Kconfig option you need to.
> > > 
> > 
> > Thanks Paul.
> > 
> > I may have been misreading Michal's suggestion of "make HUGETLB depend on
> > PREEMPT_COUNT".  We could "select PREEMPT_COUNT" if HUGETLB is enabled.
> > However, since HUGETLB is enabled in most configs, then this would
> > result in PREEMPT_COUNT also being enabled in most configs.  I honestly
> > do not know how much this will cost us?  I assume that if it was free or
> > really cheap it would already be always on?
> 
> There are a -lot- of configs out there, so are you sure that HUGETLB is
> really enabled in most of them?  ;-)

It certainly is enabled for all distribution kernels and many are
!PREEMPT so I believe this is what Mike was concerned about.

> More seriously, I was going by earlier emails in this and related threads
> plus Michal's "PREEMPT_COUNT should be selectable".  But there are other
> situations that would like PREEMPT_COUNT.  And to your point, some who
> would rather PREEMPT_COUNT not be universally enabled.  I haven't seen
> any performance or kernel-size numbers from any of them, however.

Yeah per cpu preempt counting shouldn't be noticeable but I have to
confess I haven't benchmarked it.
Michal Hocko March 11, 2021, 8:46 a.m. UTC | #11
On Thu 11-03-21 12:26:32, Muchun Song wrote:
> On Wed, Mar 10, 2021 at 11:19 PM Michal Hocko <mhocko@suse.com> wrote:
> >
> > On Mon 08-03-21 18:28:02, Muchun Song wrote:
[...]
> > > @@ -1771,8 +1813,12 @@ int dissolve_free_huge_page(struct page *page)
> > >               h->free_huge_pages--;
> > >               h->free_huge_pages_node[nid]--;
> > >               h->max_huge_pages--;
> > > -             update_and_free_page(h, head);
> > > -             rc = 0;
> > > +             rc = update_and_free_page(h, head);
> > > +             if (rc) {
> > > +                     h->surplus_huge_pages--;
> > > +                     h->surplus_huge_pages_node[nid]--;
> > > +                     h->max_huge_pages++;
> >
> > This is quite ugly and confusing. update_and_free_page is careful to do
> > the proper counters accounting and now you just override it partially.
> > Why cannot we rely on update_and_free_page do the right thing?
> 
> Dissolving path is special here. Since update_and_free_page failed,
> the number of surplus pages was incremented.  Surplus pages are
> the number of pages greater than max_huge_pages.  Since we are
> incrementing max_huge_pages, we should decrement (undo) the
> addition to surplus_huge_pages and surplus_huge_pages_node[nid].

Can we make dissolve_free_huge_page less special or tell
update_and_free_page to not account against dissolve_free_huge_page?
Muchun Song March 11, 2021, 8:49 a.m. UTC | #12
On Thu, Mar 11, 2021 at 4:46 PM Michal Hocko <mhocko@suse.com> wrote:
>
> On Thu 11-03-21 12:26:32, Muchun Song wrote:
> > On Wed, Mar 10, 2021 at 11:19 PM Michal Hocko <mhocko@suse.com> wrote:
> > >
> > > On Mon 08-03-21 18:28:02, Muchun Song wrote:
> [...]
> > > > @@ -1771,8 +1813,12 @@ int dissolve_free_huge_page(struct page *page)
> > > >               h->free_huge_pages--;
> > > >               h->free_huge_pages_node[nid]--;
> > > >               h->max_huge_pages--;
> > > > -             update_and_free_page(h, head);
> > > > -             rc = 0;
> > > > +             rc = update_and_free_page(h, head);
> > > > +             if (rc) {
> > > > +                     h->surplus_huge_pages--;
> > > > +                     h->surplus_huge_pages_node[nid]--;
> > > > +                     h->max_huge_pages++;
> > >
> > > This is quite ugly and confusing. update_and_free_page is careful to do
> > > the proper counters accounting and now you just override it partially.
> > > Why cannot we rely on update_and_free_page do the right thing?
> >
> > Dissolving path is special here. Since update_and_free_page failed,
> > the number of surplus pages was incremented.  Surplus pages are
> > the number of pages greater than max_huge_pages.  Since we are
> > incrementing max_huge_pages, we should decrement (undo) the
> > addition to surplus_huge_pages and surplus_huge_pages_node[nid].
>
> Can we make dissolve_free_huge_page less special or tell
> update_and_free_page to not account against dissolve_free_huge_page?

Of course can.

Thanks.

> --
> Michal Hocko
> SUSE Labs
Michal Hocko March 11, 2021, 12:17 p.m. UTC | #13
On Thu 11-03-21 09:40:57, Michal Hocko wrote:
> On Wed 10-03-21 15:28:51, Paul E. McKenney wrote:
> > On Wed, Mar 10, 2021 at 02:10:12PM -0800, Mike Kravetz wrote:
> > > On 3/10/21 1:49 PM, Paul E. McKenney wrote:
> > > > On Wed, Mar 10, 2021 at 10:11:22PM +0100, Michal Hocko wrote:
> > > >> On Wed 10-03-21 10:56:08, Mike Kravetz wrote:
> > > >>> On 3/10/21 7:19 AM, Michal Hocko wrote:
> > > >>>> On Mon 08-03-21 18:28:02, Muchun Song wrote:
> > > >>>> [...]
> > > >>>>> @@ -1447,7 +1486,7 @@ void free_huge_page(struct page *page)
> > > >>>>>  	/*
> > > >>>>>  	 * Defer freeing if in non-task context to avoid hugetlb_lock deadlock.
> > > >>>>>  	 */
> > > >>>>> -	if (!in_task()) {
> > > >>>>> +	if (in_atomic()) {
> > > >>>>
> > > >>>> As I've said elsewhere in_atomic doesn't work for CONFIG_PREEMPT_COUNT=n.
> > > >>>> We need this change for other reasons and so it would be better to pull
> > > >>>> it out into a separate patch which also makes HUGETLB depend on
> > > >>>> PREEMPT_COUNT.
> > > >>>
> > > >>> Yes, the issue of calling put_page for hugetlb pages from any context
> > > >>> still needs work.  IMO, that is outside the scope of this series.  We
> > > >>> already have code in this path which blocks/sleeps.
> > > >>>
> > > >>> Making HUGETLB depend on PREEMPT_COUNT is too restrictive.  IIUC,
> > > >>> PREEMPT_COUNT will only be enabled if we enable:
> > > >>> PREEMPT "Preemptible Kernel (Low-Latency Desktop)"
> > > >>> PREEMPT_RT "Fully Preemptible Kernel (Real-Time)"
> > > >>> or, other 'debug' options.  These are not enabled in 'more common'
> > > >>> kernels.  Of course, we do not want to disable HUGETLB in common
> > > >>> configurations.
> > > >>
> > > >> I haven't tried that but PREEMPT_COUNT should be selectable even without
> > > >> any change to the preemption model (e.g. !PREEMPT).
> > > > 
> > > > It works reliably for me, for example as in the diff below.  So,
> > > > as Michal says, you should be able to add "select PREEMPT_COUNT" to
> > > > whatever Kconfig option you need to.
> > > > 
> > > 
> > > Thanks Paul.
> > > 
> > > I may have been misreading Michal's suggestion of "make HUGETLB depend on
> > > PREEMPT_COUNT".  We could "select PREEMPT_COUNT" if HUGETLB is enabled.
> > > However, since HUGETLB is enabled in most configs, then this would
> > > result in PREEMPT_COUNT also being enabled in most configs.  I honestly
> > > do not know how much this will cost us?  I assume that if it was free or
> > > really cheap it would already be always on?
> > 
> > There are a -lot- of configs out there, so are you sure that HUGETLB is
> > really enabled in most of them?  ;-)
> 
> It certainly is enabled for all distribution kernels and many are
> !PREEMPT so I believe this is what Mike was concerned about.
> 
> > More seriously, I was going by earlier emails in this and related threads
> > plus Michal's "PREEMPT_COUNT should be selectable".  But there are other
> > situations that would like PREEMPT_COUNT.  And to your point, some who
> > would rather PREEMPT_COUNT not be universally enabled.  I haven't seen
> > any performance or kernel-size numbers from any of them, however.
> 
> Yeah per cpu preempt counting shouldn't be noticeable but I have to
> confess I haven't benchmarked it.

But all this seems moot now http://lkml.kernel.org/r/YEoA08n60+jzsnAl@hirez.programming.kicks-ass.net
Mike Kravetz March 11, 2021, 5:59 p.m. UTC | #14
On 3/11/21 4:17 AM, Michal Hocko wrote:
>> Yeah per cpu preempt counting shouldn't be noticeable but I have to
>> confess I haven't benchmarked it.
> 
> But all this seems moot now http://lkml.kernel.org/r/YEoA08n60+jzsnAl@hirez.programming.kicks-ass.net
> 

The proper fix for free_huge_page independent of this series would
involve:

- Make hugetlb_lock and subpool lock irq safe
- Hand off freeing to a workque if the freeing could sleep

Today, the only time we can sleep in free_huge_page is for gigantic
pages allocated via cma.  I 'think' the concern about undesirable
user visible side effects in this case is minimal as freeing/allocating
1G pages is not something that is going to happen at a high frequency.
My thinking could be wrong?

Of more concern, is the introduction of this series.  If this feature
is enabled, then ALL free_huge_page requests must be sent to a workqueue.
Any ideas on how to address this?
Mike Kravetz March 11, 2021, 10:53 p.m. UTC | #15
On 3/11/21 9:59 AM, Mike Kravetz wrote:
> On 3/11/21 4:17 AM, Michal Hocko wrote:
>>> Yeah per cpu preempt counting shouldn't be noticeable but I have to
>>> confess I haven't benchmarked it.
>>
>> But all this seems moot now http://lkml.kernel.org/r/YEoA08n60+jzsnAl@hirez.programming.kicks-ass.net
>>
> 
> The proper fix for free_huge_page independent of this series would
> involve:
> 
> - Make hugetlb_lock and subpool lock irq safe
> - Hand off freeing to a workque if the freeing could sleep
> 
> Today, the only time we can sleep in free_huge_page is for gigantic
> pages allocated via cma.  I 'think' the concern about undesirable
> user visible side effects in this case is minimal as freeing/allocating
> 1G pages is not something that is going to happen at a high frequency.
> My thinking could be wrong?
> 
> Of more concern, is the introduction of this series.  If this feature
> is enabled, then ALL free_huge_page requests must be sent to a workqueue.
> Any ideas on how to address this?
> 

Thinking about this more ...

A call to free_huge_page has two distinct outcomes
1) Page is freed back to the original allocator: buddy or cma
2) Page is put on hugetlb free list

We can only possibly sleep in the first case 1.  In addition, freeing a
page back to the original allocator involves these steps:
1) Removing page from hugetlb lists
2) Updating hugetlb counts: nr_hugepages, surplus
3) Updating page fields
4) Allocate vmemmap pages if needed as in this series
5) Calling free routine of original allocator

If hugetlb_lock is irq safe, we can perform the first 3 steps under that
lock without issue.  We would then use a workqueue to perform the last
two steps.  Since we are updating hugetlb user visible data under the
lock, there should be no delays.  Of course, giving those pages back to
the original allocator could still be delayed, and a user may notice
that.  Not sure if that would be acceptable?  I think Muchun had a
similar setup just for vmemmmap allocation in an early version of this
series.

This would also require changes to where accounting is done in
dissolve_free_huge_page and update_and_free_page as mentioned elsewhere.

P.S. We could further optimize to check for the possibility of sleeping
(cma or vmemmap) and only send to workqueue in those cases.
Michal Hocko March 12, 2021, 8:15 a.m. UTC | #16
On Thu 11-03-21 14:53:08, Mike Kravetz wrote:
> On 3/11/21 9:59 AM, Mike Kravetz wrote:
> > On 3/11/21 4:17 AM, Michal Hocko wrote:
> >>> Yeah per cpu preempt counting shouldn't be noticeable but I have to
> >>> confess I haven't benchmarked it.
> >>
> >> But all this seems moot now http://lkml.kernel.org/r/YEoA08n60+jzsnAl@hirez.programming.kicks-ass.net
> >>
> > 
> > The proper fix for free_huge_page independent of this series would
> > involve:
> > 
> > - Make hugetlb_lock and subpool lock irq safe
> > - Hand off freeing to a workque if the freeing could sleep
> > 
> > Today, the only time we can sleep in free_huge_page is for gigantic
> > pages allocated via cma.  I 'think' the concern about undesirable
> > user visible side effects in this case is minimal as freeing/allocating
> > 1G pages is not something that is going to happen at a high frequency.
> > My thinking could be wrong?
> > 
> > Of more concern, is the introduction of this series.  If this feature
> > is enabled, then ALL free_huge_page requests must be sent to a workqueue.
> > Any ideas on how to address this?
> > 
> 
> Thinking about this more ...
> 
> A call to free_huge_page has two distinct outcomes
> 1) Page is freed back to the original allocator: buddy or cma
> 2) Page is put on hugetlb free list
> 
> We can only possibly sleep in the first case 1.  In addition, freeing a
> page back to the original allocator involves these steps:
> 1) Removing page from hugetlb lists
> 2) Updating hugetlb counts: nr_hugepages, surplus
> 3) Updating page fields
> 4) Allocate vmemmap pages if needed as in this series
> 5) Calling free routine of original allocator
> 
> If hugetlb_lock is irq safe, we can perform the first 3 steps under that
> lock without issue.  We would then use a workqueue to perform the last
> two steps.  Since we are updating hugetlb user visible data under the
> lock, there should be no delays.  Of course, giving those pages back to
> the original allocator could still be delayed, and a user may notice
> that.  Not sure if that would be acceptable?

Well, having many in-flight huge pages can certainly be visible. Say you
are freeing hundreds of huge pages and your echo n > nr_hugepages will
return just for you to find out that the memory hasn't been freed and
therefore cannot be reused for another use - recently there was somebody
mentioning their usecase to free up huge pages to prevent OOM for
example. I do expect more people doing something like that.

Now, nr_hugepages can be handled by blocking on the same WQ until all
pre-existing items are processed. Maybe we will need to have a more
generic API to achieve the same for in kernel users but let's wait for
those requests.

> I think Muchun had a
> similar setup just for vmemmmap allocation in an early version of this
> series.
> 
> This would also require changes to where accounting is done in
> dissolve_free_huge_page and update_and_free_page as mentioned elsewhere.

Normalizing dissolve_free_huge_page is definitely a good idea. It is
really tricky how it sticks out and does half of the job of
update_and_free_page.

That being said, if it is possible to have a fully consistent h state
before handing over to WQ for sleeping operation then we should be all
fine. I am slightly worried about potential tricky situations where the
sleeping operation fails because that would require that page to be
added back to the pool again. As said above we would need some sort of
sync with in-flight operations before returning to the userspace.
Mike Kravetz March 12, 2021, 5:50 p.m. UTC | #17
On 3/12/21 12:15 AM, Michal Hocko wrote:
> On Thu 11-03-21 14:53:08, Mike Kravetz wrote:
>> On 3/11/21 9:59 AM, Mike Kravetz wrote:
>>> On 3/11/21 4:17 AM, Michal Hocko wrote:
>>>>> Yeah per cpu preempt counting shouldn't be noticeable but I have to
>>>>> confess I haven't benchmarked it.
>>>>
>>>> But all this seems moot now http://lkml.kernel.org/r/YEoA08n60+jzsnAl@hirez.programming.kicks-ass.net
>>>>
>>>
>>> The proper fix for free_huge_page independent of this series would
>>> involve:
>>>
>>> - Make hugetlb_lock and subpool lock irq safe
>>> - Hand off freeing to a workque if the freeing could sleep
>>>
>>> Today, the only time we can sleep in free_huge_page is for gigantic
>>> pages allocated via cma.  I 'think' the concern about undesirable
>>> user visible side effects in this case is minimal as freeing/allocating
>>> 1G pages is not something that is going to happen at a high frequency.
>>> My thinking could be wrong?
>>>
>>> Of more concern, is the introduction of this series.  If this feature
>>> is enabled, then ALL free_huge_page requests must be sent to a workqueue.
>>> Any ideas on how to address this?
>>>
>>
>> Thinking about this more ...
>>
>> A call to free_huge_page has two distinct outcomes
>> 1) Page is freed back to the original allocator: buddy or cma
>> 2) Page is put on hugetlb free list
>>
>> We can only possibly sleep in the first case 1.  In addition, freeing a
>> page back to the original allocator involves these steps:
>> 1) Removing page from hugetlb lists
>> 2) Updating hugetlb counts: nr_hugepages, surplus
>> 3) Updating page fields
>> 4) Allocate vmemmap pages if needed as in this series
>> 5) Calling free routine of original allocator
>>
>> If hugetlb_lock is irq safe, we can perform the first 3 steps under that
>> lock without issue.  We would then use a workqueue to perform the last
>> two steps.  Since we are updating hugetlb user visible data under the
>> lock, there should be no delays.  Of course, giving those pages back to
>> the original allocator could still be delayed, and a user may notice
>> that.  Not sure if that would be acceptable?
> 
> Well, having many in-flight huge pages can certainly be visible. Say you
> are freeing hundreds of huge pages and your echo n > nr_hugepages will
> return just for you to find out that the memory hasn't been freed and
> therefore cannot be reused for another use - recently there was somebody
> mentioning their usecase to free up huge pages to prevent OOM for
> example. I do expect more people doing something like that.
> 
> Now, nr_hugepages can be handled by blocking on the same WQ until all
> pre-existing items are processed. Maybe we will need to have a more
> generic API to achieve the same for in kernel users but let's wait for
> those requests.
> 
>> I think Muchun had a
>> similar setup just for vmemmmap allocation in an early version of this
>> series.
>>
>> This would also require changes to where accounting is done in
>> dissolve_free_huge_page and update_and_free_page as mentioned elsewhere.
> 
> Normalizing dissolve_free_huge_page is definitely a good idea. It is
> really tricky how it sticks out and does half of the job of
> update_and_free_page.
> 
> That being said, if it is possible to have a fully consistent h state
> before handing over to WQ for sleeping operation then we should be all
> fine. I am slightly worried about potential tricky situations where the
> sleeping operation fails because that would require that page to be
> added back to the pool again. As said above we would need some sort of
> sync with in-flight operations before returning to the userspace.

Those sysfs interfaces to allocate/free huge pages will need to be
reworked.  One thing that is totally unacceptable with hugetlb_lock
being irq safe, are the calls to cond_resched_lock(&hugetlb_lock).
We will need to significantly reduce lock hold time in these situations.
I have some ideas on how this might work, but it is going to require
some a good deal of code restructuring and will take some time.
diff mbox series

Patch

diff --git a/Documentation/admin-guide/mm/hugetlbpage.rst b/Documentation/admin-guide/mm/hugetlbpage.rst
index f7b1c7462991..6988895d09a8 100644
--- a/Documentation/admin-guide/mm/hugetlbpage.rst
+++ b/Documentation/admin-guide/mm/hugetlbpage.rst
@@ -60,6 +60,10 @@  HugePages_Surp
         the pool above the value in ``/proc/sys/vm/nr_hugepages``. The
         maximum number of surplus huge pages is controlled by
         ``/proc/sys/vm/nr_overcommit_hugepages``.
+	Note: When the feature of freeing unused vmemmap pages associated
+	with each hugetlb page is enabled, the number of surplus huge pages
+	may be temporarily larger than the maximum number of surplus huge
+	pages when the system is under memory pressure.
 Hugepagesize
 	is the default hugepage size (in Kb).
 Hugetlb
@@ -80,6 +84,10 @@  returned to the huge page pool when freed by a task.  A user with root
 privileges can dynamically allocate more or free some persistent huge pages
 by increasing or decreasing the value of ``nr_hugepages``.
 
+Note: When the feature of freeing unused vmemmap pages associated with each
+hugetlb page is enabled, we can fail to free the huge pages triggered by
+the user when ths system is under memory pressure.  Please try again later.
+
 Pages that are used as huge pages are reserved inside the kernel and cannot
 be used for other purposes.  Huge pages cannot be swapped out under
 memory pressure.
diff --git a/include/linux/mm.h b/include/linux/mm.h
index 4ddfc31f21c6..77693c944a36 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -2973,6 +2973,8 @@  static inline void print_vma_addr(char *prefix, unsigned long rip)
 
 void vmemmap_remap_free(unsigned long start, unsigned long end,
 			unsigned long reuse);
+int vmemmap_remap_alloc(unsigned long start, unsigned long end,
+			unsigned long reuse, gfp_t gfp_mask);
 
 void *sparse_buffer_alloc(unsigned long size);
 struct page * __populate_section_memmap(unsigned long pfn,
diff --git a/mm/hugetlb.c b/mm/hugetlb.c
index 43fed6785322..377e0c1b283f 100644
--- a/mm/hugetlb.c
+++ b/mm/hugetlb.c
@@ -1304,16 +1304,59 @@  static inline void destroy_compound_gigantic_page(struct page *page,
 						unsigned int order) { }
 #endif
 
-static void update_and_free_page(struct hstate *h, struct page *page)
+static int update_and_free_page(struct hstate *h, struct page *page)
+	__releases(&hugetlb_lock) __acquires(&hugetlb_lock)
 {
 	int i;
 	struct page *subpage = page;
+	int nid = page_to_nid(page);
 
 	if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
-		return;
+		return 0;
 
 	h->nr_huge_pages--;
-	h->nr_huge_pages_node[page_to_nid(page)]--;
+	h->nr_huge_pages_node[nid]--;
+	VM_BUG_ON_PAGE(hugetlb_cgroup_from_page(page), page);
+	VM_BUG_ON_PAGE(hugetlb_cgroup_from_page_rsvd(page), page);
+	set_page_refcounted(page);
+	set_compound_page_dtor(page, NULL_COMPOUND_DTOR);
+
+	/*
+	 * If the vmemmap pages associated with the HugeTLB page can be
+	 * optimized or the page is gigantic, we might block in
+	 * alloc_huge_page_vmemmap() or free_gigantic_page(). In both
+	 * cases, drop the hugetlb_lock.
+	 */
+	if (free_vmemmap_pages_per_hpage(h) || hstate_is_gigantic(h))
+		spin_unlock(&hugetlb_lock);
+
+	if (alloc_huge_page_vmemmap(h, page)) {
+		spin_lock(&hugetlb_lock);
+		INIT_LIST_HEAD(&page->lru);
+		set_compound_page_dtor(page, HUGETLB_PAGE_DTOR);
+		h->nr_huge_pages++;
+		h->nr_huge_pages_node[nid]++;
+
+		/*
+		 * If we cannot allocate vmemmap pages, just refuse to free the
+		 * page and put the page back on the hugetlb free list and treat
+		 * as a surplus page.
+		 */
+		h->surplus_huge_pages++;
+		h->surplus_huge_pages_node[nid]++;
+
+		/*
+		 * The refcount can possibly be increased by memory-failure or
+		 * soft_offline handlers.
+		 */
+		if (likely(put_page_testzero(page))) {
+			arch_clear_hugepage_flags(page);
+			enqueue_huge_page(h, page);
+		}
+
+		return -ENOMEM;
+	}
+
 	for (i = 0; i < pages_per_huge_page(h);
 	     i++, subpage = mem_map_next(subpage, page, i)) {
 		subpage->flags &= ~(1 << PG_locked | 1 << PG_error |
@@ -1321,22 +1364,18 @@  static void update_and_free_page(struct hstate *h, struct page *page)
 				1 << PG_active | 1 << PG_private |
 				1 << PG_writeback);
 	}
-	VM_BUG_ON_PAGE(hugetlb_cgroup_from_page(page), page);
-	VM_BUG_ON_PAGE(hugetlb_cgroup_from_page_rsvd(page), page);
-	set_compound_page_dtor(page, NULL_COMPOUND_DTOR);
-	set_page_refcounted(page);
+
 	if (hstate_is_gigantic(h)) {
-		/*
-		 * Temporarily drop the hugetlb_lock, because
-		 * we might block in free_gigantic_page().
-		 */
-		spin_unlock(&hugetlb_lock);
 		destroy_compound_gigantic_page(page, huge_page_order(h));
 		free_gigantic_page(page, huge_page_order(h));
-		spin_lock(&hugetlb_lock);
 	} else {
 		__free_pages(page, huge_page_order(h));
 	}
+
+	if (free_vmemmap_pages_per_hpage(h) || hstate_is_gigantic(h))
+		spin_lock(&hugetlb_lock);
+
+	return 0;
 }
 
 struct hstate *size_to_hstate(unsigned long size)
@@ -1404,9 +1443,9 @@  static void __free_huge_page(struct page *page)
 	} else if (h->surplus_huge_pages_node[nid]) {
 		/* remove the page from active list */
 		list_del(&page->lru);
-		update_and_free_page(h, page);
 		h->surplus_huge_pages--;
 		h->surplus_huge_pages_node[nid]--;
+		update_and_free_page(h, page);
 	} else {
 		arch_clear_hugepage_flags(page);
 		enqueue_huge_page(h, page);
@@ -1447,7 +1486,7 @@  void free_huge_page(struct page *page)
 	/*
 	 * Defer freeing if in non-task context to avoid hugetlb_lock deadlock.
 	 */
-	if (!in_task()) {
+	if (in_atomic()) {
 		/*
 		 * Only call schedule_work() if hpage_freelist is previously
 		 * empty. Otherwise, schedule_work() had been called but the
@@ -1699,8 +1738,7 @@  static int free_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed,
 				h->surplus_huge_pages--;
 				h->surplus_huge_pages_node[node]--;
 			}
-			update_and_free_page(h, page);
-			ret = 1;
+			ret = !update_and_free_page(h, page);
 			break;
 		}
 	}
@@ -1713,10 +1751,14 @@  static int free_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed,
  * nothing for in-use hugepages and non-hugepages.
  * This function returns values like below:
  *
- *  -EBUSY: failed to dissolved free hugepages or the hugepage is in-use
- *          (allocated or reserved.)
- *       0: successfully dissolved free hugepages or the page is not a
- *          hugepage (considered as already dissolved)
+ *  -ENOMEM: failed to allocate vmemmap pages to free the freed hugepages
+ *           when the system is under memory pressure and the feature of
+ *           freeing unused vmemmap pages associated with each hugetlb page
+ *           is enabled.
+ *  -EBUSY:  failed to dissolved free hugepages or the hugepage is in-use
+ *           (allocated or reserved.)
+ *       0:  successfully dissolved free hugepages or the page is not a
+ *           hugepage (considered as already dissolved)
  */
 int dissolve_free_huge_page(struct page *page)
 {
@@ -1771,8 +1813,12 @@  int dissolve_free_huge_page(struct page *page)
 		h->free_huge_pages--;
 		h->free_huge_pages_node[nid]--;
 		h->max_huge_pages--;
-		update_and_free_page(h, head);
-		rc = 0;
+		rc = update_and_free_page(h, head);
+		if (rc) {
+			h->surplus_huge_pages--;
+			h->surplus_huge_pages_node[nid]--;
+			h->max_huge_pages++;
+		}
 	}
 out:
 	spin_unlock(&hugetlb_lock);
diff --git a/mm/hugetlb_vmemmap.c b/mm/hugetlb_vmemmap.c
index 0209b736e0b4..f7ab3d99250a 100644
--- a/mm/hugetlb_vmemmap.c
+++ b/mm/hugetlb_vmemmap.c
@@ -181,21 +181,31 @@ 
 #define RESERVE_VMEMMAP_NR		2U
 #define RESERVE_VMEMMAP_SIZE		(RESERVE_VMEMMAP_NR << PAGE_SHIFT)
 
-/*
- * How many vmemmap pages associated with a HugeTLB page that can be freed
- * to the buddy allocator.
- *
- * Todo: Returns zero for now, which means the feature is disabled. We will
- * enable it once all the infrastructure is there.
- */
-static inline unsigned int free_vmemmap_pages_per_hpage(struct hstate *h)
+static inline unsigned long free_vmemmap_pages_size_per_hpage(struct hstate *h)
 {
-	return 0;
+	return (unsigned long)free_vmemmap_pages_per_hpage(h) << PAGE_SHIFT;
 }
 
-static inline unsigned long free_vmemmap_pages_size_per_hpage(struct hstate *h)
+int alloc_huge_page_vmemmap(struct hstate *h, struct page *head)
 {
-	return (unsigned long)free_vmemmap_pages_per_hpage(h) << PAGE_SHIFT;
+	unsigned long vmemmap_addr = (unsigned long)head;
+	unsigned long vmemmap_end, vmemmap_reuse;
+
+	if (!free_vmemmap_pages_per_hpage(h))
+		return 0;
+
+	vmemmap_addr += RESERVE_VMEMMAP_SIZE;
+	vmemmap_end = vmemmap_addr + free_vmemmap_pages_size_per_hpage(h);
+	vmemmap_reuse = vmemmap_addr - PAGE_SIZE;
+	/*
+	 * The pages which the vmemmap virtual address range [@vmemmap_addr,
+	 * @vmemmap_end) are mapped to are freed to the buddy allocator, and
+	 * the range is mapped to the page which @vmemmap_reuse is mapped to.
+	 * When a HugeTLB page is freed to the buddy allocator, previously
+	 * discarded vmemmap pages must be allocated and remapping.
+	 */
+	return vmemmap_remap_alloc(vmemmap_addr, vmemmap_end, vmemmap_reuse,
+				   GFP_KERNEL | __GFP_NORETRY | __GFP_THISNODE);
 }
 
 void free_huge_page_vmemmap(struct hstate *h, struct page *head)
diff --git a/mm/hugetlb_vmemmap.h b/mm/hugetlb_vmemmap.h
index 6923f03534d5..a37771b0b82a 100644
--- a/mm/hugetlb_vmemmap.h
+++ b/mm/hugetlb_vmemmap.h
@@ -11,10 +11,33 @@ 
 #include <linux/hugetlb.h>
 
 #ifdef CONFIG_HUGETLB_PAGE_FREE_VMEMMAP
+int alloc_huge_page_vmemmap(struct hstate *h, struct page *head);
 void free_huge_page_vmemmap(struct hstate *h, struct page *head);
+
+/*
+ * How many vmemmap pages associated with a HugeTLB page that can be freed
+ * to the buddy allocator.
+ *
+ * Todo: Returns zero for now, which means the feature is disabled. We will
+ * enable it once all the infrastructure is there.
+ */
+static inline unsigned int free_vmemmap_pages_per_hpage(struct hstate *h)
+{
+	return 0;
+}
 #else
+static inline int alloc_huge_page_vmemmap(struct hstate *h, struct page *head)
+{
+	return 0;
+}
+
 static inline void free_huge_page_vmemmap(struct hstate *h, struct page *head)
 {
 }
+
+static inline unsigned int free_vmemmap_pages_per_hpage(struct hstate *h)
+{
+	return 0;
+}
 #endif /* CONFIG_HUGETLB_PAGE_FREE_VMEMMAP */
 #endif /* _LINUX_HUGETLB_VMEMMAP_H */
diff --git a/mm/sparse-vmemmap.c b/mm/sparse-vmemmap.c
index d3076a7a3783..60fc6cd6cd23 100644
--- a/mm/sparse-vmemmap.c
+++ b/mm/sparse-vmemmap.c
@@ -40,7 +40,8 @@ 
  * @remap_pte:		called for each lowest-level entry (PTE).
  * @reuse_page:		the page which is reused for the tail vmemmap pages.
  * @reuse_addr:		the virtual address of the @reuse_page page.
- * @vmemmap_pages:	the list head of the vmemmap pages that can be freed.
+ * @vmemmap_pages:	the list head of the vmemmap pages that can be freed
+ *			or is mapped from.
  */
 struct vmemmap_remap_walk {
 	void (*remap_pte)(pte_t *pte, unsigned long addr,
@@ -237,6 +238,78 @@  void vmemmap_remap_free(unsigned long start, unsigned long end,
 	free_vmemmap_page_list(&vmemmap_pages);
 }
 
+static void vmemmap_restore_pte(pte_t *pte, unsigned long addr,
+				struct vmemmap_remap_walk *walk)
+{
+	pgprot_t pgprot = PAGE_KERNEL;
+	struct page *page;
+	void *to;
+
+	BUG_ON(pte_page(*pte) != walk->reuse_page);
+
+	page = list_first_entry(walk->vmemmap_pages, struct page, lru);
+	list_del(&page->lru);
+	to = page_to_virt(page);
+	copy_page(to, (void *)walk->reuse_addr);
+
+	set_pte_at(&init_mm, addr, pte, mk_pte(page, pgprot));
+}
+
+static int alloc_vmemmap_page_list(unsigned long start, unsigned long end,
+				   gfp_t gfp_mask, struct list_head *list)
+{
+	unsigned long nr_pages = (end - start) >> PAGE_SHIFT;
+	int nid = page_to_nid((struct page *)start);
+	struct page *page, *next;
+
+	while (nr_pages--) {
+		page = alloc_pages_node(nid, gfp_mask, 0);
+		if (!page)
+			goto out;
+		list_add_tail(&page->lru, list);
+	}
+
+	return 0;
+out:
+	list_for_each_entry_safe(page, next, list, lru)
+		__free_pages(page, 0);
+	return -ENOMEM;
+}
+
+/**
+ * vmemmap_remap_alloc - remap the vmemmap virtual address range [@start, end)
+ *			 to the page which is from the @vmemmap_pages
+ *			 respectively.
+ * @start:	start address of the vmemmap virtual address range that we want
+ *		to remap.
+ * @end:	end address of the vmemmap virtual address range that we want to
+ *		remap.
+ * @reuse:	reuse address.
+ * @gpf_mask:	GFP flag for allocating vmemmap pages.
+ */
+int vmemmap_remap_alloc(unsigned long start, unsigned long end,
+			unsigned long reuse, gfp_t gfp_mask)
+{
+	LIST_HEAD(vmemmap_pages);
+	struct vmemmap_remap_walk walk = {
+		.remap_pte	= vmemmap_restore_pte,
+		.reuse_addr	= reuse,
+		.vmemmap_pages	= &vmemmap_pages,
+	};
+
+	/* See the comment in the vmemmap_remap_free(). */
+	BUG_ON(start - reuse != PAGE_SIZE);
+
+	might_sleep_if(gfpflags_allow_blocking(gfp_mask));
+
+	if (alloc_vmemmap_page_list(start, end, gfp_mask, &vmemmap_pages))
+		return -ENOMEM;
+
+	vmemmap_remap_range(reuse, end, &walk);
+
+	return 0;
+}
+
 /*
  * Allocate a block of memory to be used to back the virtual memory map
  * or to back the page tables that are used to create the mapping.