diff mbox series

[v14,3/6] mm: Introduce Reported pages

Message ID 20191119214633.24996.46821.stgit@localhost.localdomain (mailing list archive)
State New, archived
Headers show
Series mm / virtio: Provide support for unused page reporting | expand

Commit Message

Alexander H Duyck Nov. 19, 2019, 9:46 p.m. UTC
From: Alexander Duyck <alexander.h.duyck@linux.intel.com>

In order to pave the way for free page reporting in virtualized
environments we will need a way to get pages out of the free lists and
identify those pages after they have been returned. To accomplish this,
this patch adds the concept of a Reported Buddy, which is essentially
meant to just be the Uptodate flag used in conjunction with the Buddy
page type.

To prevent the reported pages from leaking outside of the buddy lists I
have added a call to clear_reported_page to the del_page_from_free_list
function. As a result any reported page that is split, merged, or
allocated will have the flag cleared prior to the PageBuddy value being
cleared.

The process for reporting pages is fairly simple. Once the nr_free for
a given free area has exceeded the number of pages reported for that area
plus a certain high watermark value we will flag the zone as needing
reporting and schedule the worker thread to start reporting. That worker
thread will begin working from the lowest supported page reporting order
up to MAX_ORDER - 1 pulling unreported pages from the free list and
storing them in the scatterlist.

When processing each individual free list it is necessary for the worker
thread to release the zone lock when it needs to stop and report the full
scatterlist of pages. To reduce the work of the next iteration the worker
thread will rotate the free list so that the first unreported page in the
free list becomes the first entry in the list. Doing this we should only
have to walk an entire free list no more than twice assuming large
numbers of pages are not being added to the tail of the list.

It will then call a reporting function providing information on how many
entries are in the scatterlist. Once the function completes it will return
the pages to the tail of the free area from which they were allocated and
start over pulling more pages from the free areas until there are no
longer enough pages to report on to keep the worker busy.

The worker thread will work in a round-robin fashion making its way
though each zone requesting reporting, and through each reportable free
list within that zone. Once all free areas within the zone is below the
high watermark level for free pages to report the flag indicating that the
zone has requested reporting will be cleared, and if no zones are
requesting reporting the worker thread will exit.

Signed-off-by: Alexander Duyck <alexander.h.duyck@linux.intel.com>
---
 include/linux/mmzone.h         |   12 +
 include/linux/page-flags.h     |   11 +
 include/linux/page_reporting.h |   31 ++++
 mm/Kconfig                     |   11 +
 mm/Makefile                    |    1 
 mm/memory_hotplug.c            |    2 
 mm/page_alloc.c                |   53 ++++++
 mm/page_reporting.c            |  337 ++++++++++++++++++++++++++++++++++++++++
 mm/page_reporting.h            |  125 +++++++++++++++
 9 files changed, 579 insertions(+), 4 deletions(-)
 create mode 100644 include/linux/page_reporting.h
 create mode 100644 mm/page_reporting.c
 create mode 100644 mm/page_reporting.h

Comments

Mel Gorman Nov. 27, 2019, 3:24 p.m. UTC | #1
On Tue, Nov 19, 2019 at 01:46:33PM -0800, Alexander Duyck wrote:
> From: Alexander Duyck <alexander.h.duyck@linux.intel.com>
> 
> In order to pave the way for free page reporting in virtualized
> environments we will need a way to get pages out of the free lists and
> identify those pages after they have been returned. To accomplish this,
> this patch adds the concept of a Reported Buddy, which is essentially
> meant to just be the Uptodate flag used in conjunction with the Buddy
> page type.
> 
> To prevent the reported pages from leaking outside of the buddy lists I
> have added a call to clear_reported_page to the del_page_from_free_list
> function. As a result any reported page that is split, merged, or
> allocated will have the flag cleared prior to the PageBuddy value being
> cleared.
> 
> The process for reporting pages is fairly simple. Once the nr_free for
> a given free area has exceeded the number of pages reported for that area
> plus a certain high watermark value we will flag the zone as needing
> reporting and schedule the worker thread to start reporting. That worker
> thread will begin working from the lowest supported page reporting order
> up to MAX_ORDER - 1 pulling unreported pages from the free list and
> storing them in the scatterlist.
> 
> When processing each individual free list it is necessary for the worker
> thread to release the zone lock when it needs to stop and report the full
> scatterlist of pages. To reduce the work of the next iteration the worker
> thread will rotate the free list so that the first unreported page in the
> free list becomes the first entry in the list. Doing this we should only
> have to walk an entire free list no more than twice assuming large
> numbers of pages are not being added to the tail of the list.
> 
> It will then call a reporting function providing information on how many
> entries are in the scatterlist. Once the function completes it will return
> the pages to the tail of the free area from which they were allocated and
> start over pulling more pages from the free areas until there are no
> longer enough pages to report on to keep the worker busy.
> 
> The worker thread will work in a round-robin fashion making its way
> though each zone requesting reporting, and through each reportable free
> list within that zone. Once all free areas within the zone is below the
> high watermark level for free pages to report the flag indicating that the
> zone has requested reporting will be cleared, and if no zones are
> requesting reporting the worker thread will exit.
> 
> Signed-off-by: Alexander Duyck <alexander.h.duyck@linux.intel.com>

Ok, I'm ok with how this hooks into the allocator as the overhead is
minimal. However, the patch itself still includes a number of
optimisations instead of being a bare-boned implementation of the
feature with optimisations layered on top. I think some of the
optimisations are also broken but it's harder to be sure because both
the feature and the optimisations are lumped together.

> ---
>  include/linux/mmzone.h         |   12 +
>  include/linux/page-flags.h     |   11 +
>  include/linux/page_reporting.h |   31 ++++
>  mm/Kconfig                     |   11 +
>  mm/Makefile                    |    1 
>  mm/memory_hotplug.c            |    2 
>  mm/page_alloc.c                |   53 ++++++
>  mm/page_reporting.c            |  337 ++++++++++++++++++++++++++++++++++++++++
>  mm/page_reporting.h            |  125 +++++++++++++++
>  9 files changed, 579 insertions(+), 4 deletions(-)
>  create mode 100644 include/linux/page_reporting.h
>  create mode 100644 mm/page_reporting.c
>  create mode 100644 mm/page_reporting.h
> 
> diff --git a/include/linux/mmzone.h b/include/linux/mmzone.h
> index 8d93106490f3..9647499983b1 100644
> --- a/include/linux/mmzone.h
> +++ b/include/linux/mmzone.h
> @@ -478,6 +478,14 @@ struct zone {
>  	seqlock_t		span_seqlock;
>  #endif
>  
> +#ifdef CONFIG_PAGE_REPORTING
> +	/*
> +	 * Pointer to reported page tracking statistics array. The size of
> +	 * the array is MAX_ORDER - PAGE_REPORTING_MIN_ORDER. NULL when
> +	 * unused page reporting is not present.
> +	 */
> +	unsigned long		*reported_pages;
> +#endif
>  	int initialized;
>  
>  	/* Write-intensive fields used from the page allocator */

Comment could be better. We know it's a pointer.

/*
 * When a device is registered to track free pages, this array tracks
 * the number of pages already reported at each order from
 * PAGE_REPORTING_MIN_ORDER up to MAX_ORDER.
 */

> @@ -550,6 +558,10 @@ enum zone_flags {
>  	ZONE_BOOSTED_WATERMARK,		/* zone recently boosted watermarks.
>  					 * Cleared when kswapd is woken.
>  					 */
> +	ZONE_PAGE_REPORTING_REQUESTED,	/* zone enabled page reporting and has
> +					 * requested flushing the data out of
> +					 * higher order pages.
> +					 */
>  };

Set if a *driver* enabled page reporting and has requested that unused
pages are reported?

"flushing the data" would normally indicate that it's something to do
with writeback.

>  
>  static inline unsigned long zone_managed_pages(struct zone *zone)
> diff --git a/include/linux/page-flags.h b/include/linux/page-flags.h
> index 1bf83c8fcaa7..a3a3b15b56a8 100644
> --- a/include/linux/page-flags.h
> +++ b/include/linux/page-flags.h
> @@ -163,6 +163,9 @@ enum pageflags {
>  
>  	/* non-lru isolated movable page */
>  	PG_isolated = PG_reclaim,
> +
> +	/* Buddy pages. Used to track which pages have been reported */
> +	PG_reported = PG_uptodate,
>  };
>  
>  #ifndef __GENERATING_BOUNDS_H

Only valid for buddy pages.....

> diff --git a/include/linux/page_reporting.h b/include/linux/page_reporting.h
> new file mode 100644
> index 000000000000..925a16b1d14b
> --- /dev/null
> +++ b/include/linux/page_reporting.h
> @@ -0,0 +1,31 @@
> +/* SPDX-License-Identifier: GPL-2.0 */
> +#ifndef _LINUX_PAGE_REPORTING_H
> +#define _LINUX_PAGE_REPORTING_H
> +
> +#include <linux/mmzone.h>
> +
> +struct page_reporting_dev_info {
> +	/* function that alters pages to make them "reported" */
> +	void (*report)(struct page_reporting_dev_info *prdev,
> +		       unsigned int nents);
> +
> +	/* pointer to scatterlist containing pages to be processed */
> +	struct scatterlist *sg;
> +

The choice of scatterlist is curious because it adds unnecessary complexity
without needing the benefits scatterlist and sg_table provides. All you
really need is an array of pages that is NULL terminated because you can
get the order of the struct page when it's a buddy page.

> +	/*
> +	 * Upper limit on the number of pages that the report function
> +	 * expects to be placed into the scatterlist to be processed.
> +	 */
> +	unsigned int capacity;
> +

Instead of requiring the driver to specify capacity, why did you not
simply make it PAGE_REPORTING_HWM and statically declare the array?

> +	/* The number of zones requesting reporting */
> +	atomic_t refcnt;
> +

The refcnt is overkill. Simply loop over all zones until there is a
clear pass. Despite being atomic, it actually requires the zone lock to
avoid races in places like this

		if (test_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags))
			refcnt = page_reporting_process_zone(prdev, zone);

The optimisation is small and it's relatively subtle.

>  static inline void __free_one_page(struct page *page,
>  		unsigned long pfn,
>  		struct zone *zone, unsigned int order,
> -		int migratetype)
> +		int migratetype, bool reported)
>  {
>  	struct capture_control *capc = task_capc(zone);
>  	unsigned long uninitialized_var(buddy_pfn);
> @@ -1048,7 +1053,9 @@ static inline void __free_one_page(struct page *page,
>  done_merging:
>  	set_page_order(page, order);
>  
> -	if (is_shuffle_order(order))
> +	if (reported)
> +		to_tail = true;
> +	else if (is_shuffle_order(order))
>  		to_tail = shuffle_pick_tail();
>  	else
>  		to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order);
> @@ -1057,6 +1064,14 @@ static inline void __free_one_page(struct page *page,
>  		add_to_free_list_tail(page, zone, order, migratetype);
>  	else
>  		add_to_free_list(page, zone, order, migratetype);
> +
> +	/*
> +	 * No need to notify on a reported page as the total count of
> +	 * unreported pages will not have increased since we have essentially
> +	 * merged the reported page with one or more unreported pages.
> +	 */
> +	if (!reported)
> +		page_reporting_notify_free(zone, order);
>  }
>  
>  /*

If a reported page is merged with a larger buddy then the counts for the
lower order needs to be updated or the counter gets out of sync. Then the
reported status of the page needs to be cleared as the larger block may
only be partially reported and the count is wrong. I know why you want
the reported pages but it really should be in its own patch. This patch
really should be just the bare essentials to support reporting of free
pages even if it's sub-optimal. I know you also use reported_pages as
part of a stop condition but a basic stop condition is simply to do a
single pass.

> @@ -3228,6 +3243,36 @@ int __isolate_free_page(struct page *page, unsigned int order)
>  	return 1UL << order;
>  }
>  
> +#ifdef CONFIG_PAGE_REPORTING
> +/**
> + * __free_isolated_page - Return a now-isolated page back where we got it
> + * @page: Page that was isolated
> + * @order: Order of the isolated page
> + *
> + * This function is meant to return a page pulled from the free lists via
> + * __isolate_free_page back to the free lists they were pulled from.
> + */

Isolated within mm has special meaning already. __putback_reported_page?

> +void __free_isolated_page(struct page *page, unsigned int order)
> +{
> +	struct zone *zone = page_zone(page);
> +	unsigned long pfn;
> +	unsigned int mt;
> +
> +	/* zone lock should be held when this function is called */
> +	lockdep_assert_held(&zone->lock);
> +
> +	pfn = page_to_pfn(page);
> +	mt = get_pfnblock_migratetype(page, pfn);
> +
> +	/*
> +	 * Return isolated page to tail of freelist and don't bother with
> +	 * triggering the page reporting notifiers since this page was
> +	 * previously on the freelist and has likely already been reported.
> +	 */
> +	__free_one_page(page, pfn, zone, order, mt, true);
> +}
> +#endif /* CONFIG_PAGE_REPORTING */
> +
>  /*
>   * Update NUMA hit/miss statistics
>   *
> diff --git a/mm/page_reporting.c b/mm/page_reporting.c
> new file mode 100644
> index 000000000000..4844f0aa2904
> --- /dev/null
> +++ b/mm/page_reporting.c
> @@ -0,0 +1,337 @@
> +// SPDX-License-Identifier: GPL-2.0
> +#include <linux/mm.h>
> +#include <linux/mmzone.h>
> +#include <linux/page_reporting.h>
> +#include <linux/gfp.h>
> +#include <linux/export.h>
> +#include <linux/delay.h>
> +#include <linux/scatterlist.h>
> +
> +#include "page_reporting.h"
> +#include "internal.h"
> +
> +static struct page_reporting_dev_info __rcu *pr_dev_info __read_mostly;
> +
> +#define for_each_reporting_migratetype_order(_order, _type) \
> +	for (_order = PAGE_REPORTING_MIN_ORDER; _order < MAX_ORDER; _order++) \
> +		for (_type = 0; _type < MIGRATE_TYPES; _type++) \
> +			if (!is_migrate_isolate(_type))
> +

This only has one user so simply put it in place. As this stands, _order
and _type can be evaluated multiple times which potentially leads to
chaos

> +static void page_reporting_populate_metadata(struct zone *zone)
> +{
> +	size_t size;
> +	int node;
> +
> +	/*
> +	 * We need to make sure we have somewhere to store the tracking
> +	 * data for how many reported pages are in the zone. To do that
> +	 * we need to make certain zone->reported_pages is populated.
> +	 */
> +	if (zone->reported_pages)
> +		return;
> +
> +	node = zone_to_nid(zone);
> +	size = (MAX_ORDER - PAGE_REPORTING_MIN_ORDER) * sizeof(unsigned long);
> +	zone->reported_pages = kzalloc_node(size, GFP_KERNEL, node);
> +}
> +

reported_pages is not necessarily updated by a CPU local to the zone.
There is not much point worrying about its locality.

> +static void
> +page_reporting_drain(struct page_reporting_dev_info *prdev, struct zone *zone)
> +{
> +	struct scatterlist *sg = prdev->sg;
> +
> +	/*
> +	 * Drain the now reported pages back into their respective
> +	 * free lists/areas. We assume at least one page is populated.
> +	 */
> +	do {
> +		unsigned int order = get_order(sg->length);
> +		struct page *page = sg_page(sg);
> +
> +		__free_isolated_page(page, order);
> +
> +		/*
> +		 * If page was not comingled with another page we can
> +		 * consider the result to be "reported" since the page
> +		 * hasn't been modified, otherwise we will need to
> +		 * report on the new larger page when we make our way
> +		 * up to that higher order.
> +		 */
> +		if (PageBuddy(page) && page_order(page) == order)
> +			mark_page_reported(page, zone, order);
> +	} while (!sg_is_last(sg++));
> +}
> +
> +/*
> + * The page reporting cycle consists of 4 stages, fill, report, drain, and
> + * idle. We will cycle through the first 3 stages until we cannot obtain a
> + * full scatterlist of pages, in that case we will switch to idle.
> + */

Document the return value because it's unclear why the number of populated
elements in sg is not tracked in page_reporting_dev_info. It seems
unnecessarily fragile.

> +static unsigned int
> +page_reporting_cycle(struct page_reporting_dev_info *prdev, struct zone *zone,
> +		     unsigned int order, unsigned int mt, unsigned int nents)
> +{
> +	struct list_head *list = &zone->free_area[order].free_list[mt];
> +	unsigned int page_len = PAGE_SIZE << order;
> +	struct scatterlist *sg = prdev->sg;
> +	struct page *page, *next;
> +
> +	/*
> +	 * Perform early check, if free area is empty there is
> +	 * nothing to process so we can skip this free_list.
> +	 */
> +	if (list_empty(list))
> +		return nents;
> +
> +	spin_lock_irq(&zone->lock);
> +
> +	/* loop through free list adding unreported pages to sg list */
> +	list_for_each_entry_safe(page, next, list, lru) {
> +		/* We are going to skip over the reported pages. */
> +		if (PageReported(page))
> +			continue;
> +
> +		/* Attempt to add page to sg list */
> +		if (nents < prdev->capacity) {
> +			if (!__isolate_free_page(page, order))
> +				break;
> +
> +			sg_set_page(&sg[nents++], page, page_len, 0);
> +			continue;
> +		}
> +
> +		/*
> +		 * Make the first non-reported entry in the free list
> +		 * the new head of the free list before we exit.
> +		 */
> +		if (!list_is_first(&page->lru, list))
> +			list_rotate_to_front(&page->lru, list);
> +
> +		/* release lock before waiting on report processing*/
> +		spin_unlock_irq(&zone->lock);
> +
> +		/* begin processing pages in local list */
> +		prdev->report(prdev, nents);
> +
> +		/* reset number of entries */
> +		nents = 0;
> +
> +		/* reacquire zone lock and resume processing free lists */
> +		spin_lock_irq(&zone->lock);
> +
> +		/* flush reported pages from the sg list */
> +		page_reporting_drain(prdev, zone);
> +
> +		/*
> +		 * Reset next to first entry, the old next isn't valid
> +		 * since we dropped the lock to report the pages
> +		 */
> +		next = list_first_entry(list, struct page, lru);
> +	}
> +
> +	spin_unlock_irq(&zone->lock);
> +
> +	return nents;
> +}
> +
> +static int
> +page_reporting_process_zone(struct page_reporting_dev_info *prdev,
> +			    struct zone *zone)
> +{
> +	unsigned int order, mt, nents = 0;
> +	unsigned long watermark;
> +	int refcnt = -1;
> +
> +	page_reporting_populate_metadata(zone);
> +
> +	/* Generate minimum watermark to be able to guarantee progress */
> +	watermark = low_wmark_pages(zone) +
> +		    (prdev->capacity << PAGE_REPORTING_MIN_ORDER);
> +
> +	/*
> +	 * Cancel request if insufficient free memory or if we failed
> +	 * to allocate page reporting statistics for the zone.
> +	 */
> +	if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA) ||
> +	    !zone->reported_pages) {
> +		spin_lock_irq(&zone->lock);
> +		goto zone_not_ready;
> +	}

The zone lock is acquired just for the zone bit and the refcnt? That
seems drastic overkill because the bit handling is already racy and the
refcnt is overkill.

> +
> +	sg_init_table(prdev->sg, prdev->capacity);
> +
> +	/* Process each free list starting from lowest order/mt */
> +	for_each_reporting_migratetype_order(order, mt)
> +		nents = page_reporting_cycle(prdev, zone, order, mt, nents);
> +


> +	/* mark end of sg list and report the remainder */
> +	if (nents) {
> +		sg_mark_end(&prdev->sg[nents - 1]);
> +		prdev->report(prdev, nents);
> +	}
> +
> +	spin_lock_irq(&zone->lock);
> +
> +	/* flush any remaining pages out from the last report */
> +	if (nents)
> +		page_reporting_drain(prdev, zone);
> +
> +	/* check to see if values are low enough for us to stop for now */
> +	for (order = PAGE_REPORTING_MIN_ORDER; order < MAX_ORDER; order++) {
> +		if (pages_unreported(zone, order) < PAGE_REPORTING_HWM)
> +			continue;
> +#ifdef CONFIG_MEMORY_ISOLATION
> +		/*
> +		 * Do not allow a free_area with isolated pages to request
> +		 * that we continue with page reporting. Keep the reporting
> +		 * light until the isolated pages have been cleared.
> +		 */
> +		if (!free_area_empty(&zone->free_area[order], MIGRATE_ISOLATE))
> +			continue;
> +#endif
> +		goto zone_not_complete;
> +	}
> +
> +zone_not_ready:
> +	/*
> +	 * If there are no longer enough free pages to fully populate
> +	 * the scatterlist, then we can just shut it down for this zone.
> +	 */
> +	__clear_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags);
> +	refcnt = atomic_dec_return(&prdev->refcnt);

If a request comes in while processing is already happening then the
subsequent request is lost.

> +zone_not_complete:
> +	spin_unlock_irq(&zone->lock);
> +
> +	return refcnt;
> +}
> +
> +static void page_reporting_process(struct work_struct *work)
> +{
> +	struct delayed_work *d_work = to_delayed_work(work);
> +	struct page_reporting_dev_info *prdev =
> +		container_of(d_work, struct page_reporting_dev_info, work);
> +	struct zone *zone = first_online_pgdat()->node_zones;
> +	int refcnt = -1;
> +
> +	do {
> +		if (test_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags))
> +			refcnt = page_reporting_process_zone(prdev, zone);
> +
> +		/* Move to next zone, if at end of list start over */
> +		zone = next_zone(zone) ? : first_online_pgdat()->node_zones;
> +
> +		/*
> +		 * As long as refcnt has not reached zero there are still
> +		 * zones to be processed.
> +		 */
> +	} while (refcnt);
> +}
> +

This is being done from a workqueue context and potentially this runs
forever if the refcnt remains elevated. It's dangerous and should be in
it's own patch. In the basic implementation, just do a single pass of
all zones.

> +/* request page reporting on this zone */
> +void __page_reporting_request(struct zone *zone)
> +{
> +	struct page_reporting_dev_info *prdev;
> +
> +	rcu_read_lock();
> +
> +	/*
> +	 * We use RCU to protect the pr_dev_info pointer. In almost all
> +	 * cases this should be present, however in the unlikely case of
> +	 * a shutdown this will be NULL and we should exit.
> +	 */
> +	prdev = rcu_dereference(pr_dev_info);
> +	if (unlikely(!prdev))
> +		goto out;
> +
> +	/*
> +	 * We can use separate test and set operations here as there
> +	 * is nothing else that can set or clear this bit while we are
> +	 * holding the zone lock. The advantage to doing it this way is
> +	 * that we don't have to dirty the cacheline unless we are
> +	 * changing the value.
> +	 */
> +	__set_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags);
> +

The comment implies that the bit should have been tested first.

> +	/*
> +	 * Delay the start of work to allow a sizable queue to
> +	 * build. For now we are limiting this to running no more
> +	 * than 5 times per second.
> +	 */
> +	if (!atomic_fetch_inc(&prdev->refcnt))
> +		schedule_delayed_work(&prdev->work, HZ / 5);

The refcnt is incremented whether this zone has already been requested or
not but only decremented when the bit is cleared so the refcnt potentially
remains elevated forever.

> +out:
> +	rcu_read_unlock();
> +}
> +
> +static DEFINE_MUTEX(page_reporting_mutex);
> +DEFINE_STATIC_KEY_FALSE(page_reporting_enabled);
> +
> +void page_reporting_unregister(struct page_reporting_dev_info *prdev)
> +{
> +	mutex_lock(&page_reporting_mutex);
> +
> +	if (rcu_access_pointer(pr_dev_info) == prdev) {
> +		/* Disable page reporting notification */
> +		RCU_INIT_POINTER(pr_dev_info, NULL);
> +		synchronize_rcu();
> +
> +		/* Flush any existing work, and lock it out */
> +		cancel_delayed_work_sync(&prdev->work);
> +
> +		/* Free scatterlist */
> +		kfree(prdev->sg);
> +		prdev->sg = NULL;
> +	}
> +
> +	mutex_unlock(&page_reporting_mutex);
> +}
> +EXPORT_SYMBOL_GPL(page_reporting_unregister);
> +
> +int page_reporting_register(struct page_reporting_dev_info *prdev)
> +{
> +	struct zone *zone;
> +	int err = 0;
> +
> +	/* No point in enabling this if it cannot handle any pages */
> +	if (WARN_ON(!prdev->capacity || prdev->capacity > PAGE_REPORTING_HWM))
> +		return -EINVAL;
> +
> +	mutex_lock(&page_reporting_mutex);
> +
> +	/* nothing to do if already in use */
> +	if (rcu_access_pointer(pr_dev_info)) {
> +		err = -EBUSY;
> +		goto err_out;
> +	}
> +
> +	/* allocate scatterlist to store pages being reported on */
> +	prdev->sg = kcalloc(prdev->capacity, sizeof(*prdev->sg), GFP_KERNEL);
> +	if (!prdev->sg) {
> +		err = -ENOMEM;
> +		goto err_out;
> +	}
> +
> +
> +	/* initialize refcnt and work structures */
> +	atomic_set(&prdev->refcnt, 0);
> +	INIT_DELAYED_WORK(&prdev->work, &page_reporting_process);
> +
> +	/* assign device, and begin initial flush of populated zones */
> +	rcu_assign_pointer(pr_dev_info, prdev);
> +	for_each_populated_zone(zone) {
> +		spin_lock_irq(&zone->lock);
> +		__page_reporting_request(zone);
> +		spin_unlock_irq(&zone->lock);
> +	}
> +
> +	/* enable page reporting notification */
> +	if (!static_key_enabled(&page_reporting_enabled)) {
> +		static_branch_enable(&page_reporting_enabled);
> +		pr_info("Unused page reporting enabled\n");
> +	}
> +err_out:
> +	mutex_unlock(&page_reporting_mutex);
> +
> +	return err;
> +}
> +EXPORT_SYMBOL_GPL(page_reporting_register);
> diff --git a/mm/page_reporting.h b/mm/page_reporting.h
> new file mode 100644
> index 000000000000..2ad31bbb0036
> --- /dev/null
> +++ b/mm/page_reporting.h
> @@ -0,0 +1,125 @@
> +/* SPDX-License-Identifier: GPL-2.0 */
> +#ifndef _MM_PAGE_REPORTING_H
> +#define _MM_PAGE_REPORTING_H
> +
> +#include <linux/mmzone.h>
> +#include <linux/pageblock-flags.h>
> +#include <linux/page-isolation.h>
> +#include <linux/jump_label.h>
> +#include <linux/slab.h>
> +#include <asm/pgtable.h>
> +
> +#define PAGE_REPORTING_MIN_ORDER	pageblock_order

This is potentially the same as MAX_ORDER-1. Not sure if it matters or
not.

> +#define PAGE_REPORTING_HWM		32
> +
> +#ifdef CONFIG_PAGE_REPORTING
> +/* Reported page accessors, defined in page_alloc.c */
> +void __free_isolated_page(struct page *page, unsigned int order);
> +
> +/* Free reported_pages and reset reported page tracking count to 0 */
> +static inline void page_reporting_reset_zone(struct zone *zone)
> +{
> +	kfree(zone->reported_pages);
> +	zone->reported_pages = NULL;
> +}
> +
> +DECLARE_STATIC_KEY_FALSE(page_reporting_enabled);
> +void __page_reporting_request(struct zone *zone);
> +
> +static inline bool page_reported(struct page *page)
> +{
> +	return static_branch_unlikely(&page_reporting_enabled) &&
> +	       PageReported(page);
> +}
> +
> +static inline unsigned long
> +pages_unreported(struct zone *zone, int order)
> +{
> +	unsigned long nr_free;
> +	int report_order;
> +
> +	/* Limit notifications only to higher order pages */
> +	report_order = order - PAGE_REPORTING_MIN_ORDER;
> +	if (report_order < 0)
> +		return 0;
> +
> +	nr_free = zone->free_area[order].nr_free;
> +
> +	/* Only subtract reported_pages count if it is present */
> +	if (!zone->reported_pages)
> +		return nr_free;
> +
> +	return nr_free - zone->reported_pages[report_order];
> +}

Initially, this should be a full list traversal because I'm not
convinced the reported_pages count is kept perfectly in sync. The
optimisation confuses the review of the basic feature itself.

> +
> +/**
> + * page_reporting_notify_free - Free page notification to start page processing
> + * @zone: Pointer to current zone of last page processed
> + * @order: Order of last page added to zone
> + *
> + * This function is meant to act as a screener for __page_reporting_request
> + * which will determine if a give zone has crossed over the high-water mark
> + * that will justify us beginning page treatment. If we have crossed that
> + * threshold then it will start the process of pulling some pages and
> + * placing them in the batch list for treatment.
> + */
> +static inline void page_reporting_notify_free(struct zone *zone, int order)
> +{
> +	/* Called from hot path in __free_one_page() */
> +	if (!static_branch_unlikely(&page_reporting_enabled))
> +		return;
> +
> +	/* Do not bother with tests if we have already requested reporting */
> +	if (test_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags))
> +		return;
> +
> +	/* Determine if we have crossed reporting threshold */
> +	if (pages_unreported(zone, order) < PAGE_REPORTING_HWM)
> +		return;
> +
> +	/* This is slow, but should be called very rarely */
> +	__page_reporting_request(zone);
> +}
> +
> +/*
> + * Functions for marking/clearing reported pages from the freelist.
> + * All of them expect the zone lock to be held to maintain
> + * consistency of the reported_pages count versus nr_free.
> + */
> +static inline void
> +mark_page_reported(struct page *page, struct zone *zone, unsigned int order)
> +{
> +	/* flag page as reported */
> +	__SetPageReported(page);
> +
> +	/* update areated page accounting */
> +	zone->reported_pages[order - PAGE_REPORTING_MIN_ORDER]++;
> +}
> +
> +static inline void
> +clear_page_reported(struct page *page, struct zone *zone, unsigned int order)
> +{
> +	/* page_private will contain the page order, so just use it directly */
> +	zone->reported_pages[order - PAGE_REPORTING_MIN_ORDER]--;
> +
> +	/* clear the flag so we can report on it when it returns */
> +	__ClearPageReported(page);
> +}
> +
> +#else /* CONFIG_PAGE_REPORTING */
> +#define page_reported(_page)	false
> +
> +static inline void page_reporting_reset_zone(struct zone *zone)
> +{
> +}
> +
> +static inline void page_reporting_notify_free(struct zone *zone, int order)
> +{
> +}
> +
> +static inline void
> +clear_page_reported(struct page *page, struct zone *zone, unsigned int order)
> +{
> +}
> +#endif /* CONFIG_PAGE_REPORTING */
> +#endif /*_MM_PAGE_REPORTING_H */
>
Alexander Duyck Nov. 27, 2019, 5:22 p.m. UTC | #2
On Wed, 2019-11-27 at 15:24 +0000, Mel Gorman wrote:
> On Tue, Nov 19, 2019 at 01:46:33PM -0800, Alexander Duyck wrote:
> > From: Alexander Duyck <alexander.h.duyck@linux.intel.com>
> > 
> > In order to pave the way for free page reporting in virtualized
> > environments we will need a way to get pages out of the free lists and
> > identify those pages after they have been returned. To accomplish this,
> > this patch adds the concept of a Reported Buddy, which is essentially
> > meant to just be the Uptodate flag used in conjunction with the Buddy
> > page type.
> > 
> > To prevent the reported pages from leaking outside of the buddy lists I
> > have added a call to clear_reported_page to the del_page_from_free_list
> > function. As a result any reported page that is split, merged, or
> > allocated will have the flag cleared prior to the PageBuddy value being
> > cleared.
> > 
> > The process for reporting pages is fairly simple. Once the nr_free for
> > a given free area has exceeded the number of pages reported for that area
> > plus a certain high watermark value we will flag the zone as needing
> > reporting and schedule the worker thread to start reporting. That worker
> > thread will begin working from the lowest supported page reporting order
> > up to MAX_ORDER - 1 pulling unreported pages from the free list and
> > storing them in the scatterlist.
> > 
> > When processing each individual free list it is necessary for the worker
> > thread to release the zone lock when it needs to stop and report the full
> > scatterlist of pages. To reduce the work of the next iteration the worker
> > thread will rotate the free list so that the first unreported page in the
> > free list becomes the first entry in the list. Doing this we should only
> > have to walk an entire free list no more than twice assuming large
> > numbers of pages are not being added to the tail of the list.
> > 
> > It will then call a reporting function providing information on how many
> > entries are in the scatterlist. Once the function completes it will return
> > the pages to the tail of the free area from which they were allocated and
> > start over pulling more pages from the free areas until there are no
> > longer enough pages to report on to keep the worker busy.
> > 
> > The worker thread will work in a round-robin fashion making its way
> > though each zone requesting reporting, and through each reportable free
> > list within that zone. Once all free areas within the zone is below the
> > high watermark level for free pages to report the flag indicating that the
> > zone has requested reporting will be cleared, and if no zones are
> > requesting reporting the worker thread will exit.
> > 
> > Signed-off-by: Alexander Duyck <alexander.h.duyck@linux.intel.com>
> 
> Ok, I'm ok with how this hooks into the allocator as the overhead is
> minimal. However, the patch itself still includes a number of
> optimisations instead of being a bare-boned implementation of the
> feature with optimisations layered on top. I think some of the
> optimisations are also broken but it's harder to be sure because both
> the feature and the optimisations are lumped together.

Well I can work on splitting them out if need be. 

> > ---
> >  include/linux/mmzone.h         |   12 +
> >  include/linux/page-flags.h     |   11 +
> >  include/linux/page_reporting.h |   31 ++++
> >  mm/Kconfig                     |   11 +
> >  mm/Makefile                    |    1 
> >  mm/memory_hotplug.c            |    2 
> >  mm/page_alloc.c                |   53 ++++++
> >  mm/page_reporting.c            |  337 ++++++++++++++++++++++++++++++++++++++++
> >  mm/page_reporting.h            |  125 +++++++++++++++
> >  9 files changed, 579 insertions(+), 4 deletions(-)
> >  create mode 100644 include/linux/page_reporting.h
> >  create mode 100644 mm/page_reporting.c
> >  create mode 100644 mm/page_reporting.h
> > 
> > diff --git a/include/linux/mmzone.h b/include/linux/mmzone.h
> > index 8d93106490f3..9647499983b1 100644
> > --- a/include/linux/mmzone.h
> > +++ b/include/linux/mmzone.h
> > @@ -478,6 +478,14 @@ struct zone {
> >  	seqlock_t		span_seqlock;
> >  #endif
> >  
> > +#ifdef CONFIG_PAGE_REPORTING
> > +	/*
> > +	 * Pointer to reported page tracking statistics array. The size of
> > +	 * the array is MAX_ORDER - PAGE_REPORTING_MIN_ORDER. NULL when
> > +	 * unused page reporting is not present.
> > +	 */
> > +	unsigned long		*reported_pages;
> > +#endif
> >  	int initialized;
> >  
> >  	/* Write-intensive fields used from the page allocator */
> 
> Comment could be better. We know it's a pointer.

Okay, I can rework the comment. I'll call out specifically that I am
leaving it as a pointer because PAGE_REPORTING_MIN_ORDER might be variable
on some systems so I cannot allocate it statically.

> /*
>  * When a device is registered to track free pages, this array tracks
>  * the number of pages already reported at each order from
>  * PAGE_REPORTING_MIN_ORDER up to MAX_ORDER.
>  */
> 
> > @@ -550,6 +558,10 @@ enum zone_flags {
> >  	ZONE_BOOSTED_WATERMARK,		/* zone recently boosted watermarks.
> >  					 * Cleared when kswapd is woken.
> >  					 */
> > +	ZONE_PAGE_REPORTING_REQUESTED,	/* zone enabled page reporting and has
> > +					 * requested flushing the data out of
> > +					 * higher order pages.
> > +					 */
> >  };
> 
> Set if a *driver* enabled page reporting and has requested that unused
> pages are reported?
> 
> "flushing the data" would normally indicate that it's something to do
> with writeback.

Okay, I can work on the wording.

> >  
> >  static inline unsigned long zone_managed_pages(struct zone *zone)
> > diff --git a/include/linux/page-flags.h b/include/linux/page-flags.h
> > index 1bf83c8fcaa7..a3a3b15b56a8 100644
> > --- a/include/linux/page-flags.h
> > +++ b/include/linux/page-flags.h
> > @@ -163,6 +163,9 @@ enum pageflags {
> >  
> >  	/* non-lru isolated movable page */
> >  	PG_isolated = PG_reclaim,
> > +
> > +	/* Buddy pages. Used to track which pages have been reported */
> > +	PG_reported = PG_uptodate,
> >  };
> >  
> >  #ifndef __GENERATING_BOUNDS_H
> 
> Only valid for buddy pages.....

Okay I can tweak the wording.

> > diff --git a/include/linux/page_reporting.h b/include/linux/page_reporting.h
> > new file mode 100644
> > index 000000000000..925a16b1d14b
> > --- /dev/null
> > +++ b/include/linux/page_reporting.h
> > @@ -0,0 +1,31 @@
> > +/* SPDX-License-Identifier: GPL-2.0 */
> > +#ifndef _LINUX_PAGE_REPORTING_H
> > +#define _LINUX_PAGE_REPORTING_H
> > +
> > +#include <linux/mmzone.h>
> > +
> > +struct page_reporting_dev_info {
> > +	/* function that alters pages to make them "reported" */
> > +	void (*report)(struct page_reporting_dev_info *prdev,
> > +		       unsigned int nents);
> > +
> > +	/* pointer to scatterlist containing pages to be processed */
> > +	struct scatterlist *sg;
> > +
> 
> The choice of scatterlist is curious because it adds unnecessary complexity
> without needing the benefits scatterlist and sg_table provides. All you
> really need is an array of pages that is NULL terminated because you can
> get the order of the struct page when it's a buddy page.

The scatterlist is mostly about dealing with DMA mapping of the pages.
Most devices will need a way to push the pages out to the device doing the
reporting so I thought a scatterlist was the best way to gather the pages
together so that they could be mapped with one call.

> > +	/*
> > +	 * Upper limit on the number of pages that the report function
> > +	 * expects to be placed into the scatterlist to be processed.
> > +	 */
> > +	unsigned int capacity;
> > +
> 
> Instead of requiring the driver to specify capacity, why did you not
> simply make it PAGE_REPORTING_HWM and statically declare the array?

The problem is the device might not be able to support PAGE_REPORTING_HWM.
So I needed some way for it to communicate that. I could allocate the
array statically if that is what you prefer.

> > +	/* The number of zones requesting reporting */
> > +	atomic_t refcnt;
> > +
> 
> The refcnt is overkill. Simply loop over all zones until there is a
> clear pass. Despite being atomic, it actually requires the zone lock to
> avoid races in places like this
> 
> 		if (test_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags))
> 			refcnt = page_reporting_process_zone(prdev, zone);
> 
> The optimisation is small and it's relatively subtle.

I disagree. Without that we can easily get into states where a zone
requests reporting and we never get around to servicing it. I am using the
refcount to track that so that we don't shutdown the worker thread when
there is at least one zone requesting service.

> >  static inline void __free_one_page(struct page *page,
> >  		unsigned long pfn,
> >  		struct zone *zone, unsigned int order,
> > -		int migratetype)
> > +		int migratetype, bool reported)
> >  {
> >  	struct capture_control *capc = task_capc(zone);
> >  	unsigned long uninitialized_var(buddy_pfn);
> > @@ -1048,7 +1053,9 @@ static inline void __free_one_page(struct page *page,
> >  done_merging:
> >  	set_page_order(page, order);
> >  
> > -	if (is_shuffle_order(order))
> > +	if (reported)
> > +		to_tail = true;
> > +	else if (is_shuffle_order(order))
> >  		to_tail = shuffle_pick_tail();
> >  	else
> >  		to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order);
> > @@ -1057,6 +1064,14 @@ static inline void __free_one_page(struct page *page,
> >  		add_to_free_list_tail(page, zone, order, migratetype);
> >  	else
> >  		add_to_free_list(page, zone, order, migratetype);
> > +
> > +	/*
> > +	 * No need to notify on a reported page as the total count of
> > +	 * unreported pages will not have increased since we have essentially
> > +	 * merged the reported page with one or more unreported pages.
> > +	 */
> > +	if (!reported)
> > +		page_reporting_notify_free(zone, order);
> >  }
> >  
> >  /*
> 
> If a reported page is merged with a larger buddy then the counts for the
> lower order needs to be updated or the counter gets out of sync. Then the
> reported status of the page needs to be cleared as the larger block may
> only be partially reported and the count is wrong. I know why you want
> the reported pages but it really should be in its own patch. This patch
> really should be just the bare essentials to support reporting of free
> pages even if it's sub-optimal. I know you also use reported_pages as
> part of a stop condition but a basic stop condition is simply to do a
> single pass.

Okay so there are actually a few things here to unpack.

First the comment is a bit out of date. The reason I don't need to bother
with reporting is because I process the lower orders before the higher
orders. As such we are still processing this zone if we are returning a
reported page and it is merged. We will reprocess the larger page in the
next pass.

Second, at the point where we call this function with the reported flag
set we have not yet set the page as reported. There is logic that will
check for that later and set the bits and increment the count if the page
becomes a buddy page and the order is still the same as the order we
originally freed it under.

Lastly, if you are concerned about us merging a reported page already on
the list the count is updated and the flag is cleared from the page when
it is deleted from the free list to be merged with the new page.

> > @@ -3228,6 +3243,36 @@ int __isolate_free_page(struct page *page, unsigned int order)
> >  	return 1UL << order;
> >  }
> >  
> > +#ifdef CONFIG_PAGE_REPORTING
> > +/**
> > + * __free_isolated_page - Return a now-isolated page back where we got it
> > + * @page: Page that was isolated
> > + * @order: Order of the isolated page
> > + *
> > + * This function is meant to return a page pulled from the free lists via
> > + * __isolate_free_page back to the free lists they were pulled from.
> > + */
> 
> Isolated within mm has special meaning already. __putback_reported_page?

I wanted to get away from calling it a reported page because it isn't at
the point where we are calling this function. We don't set the reported
bit on the page until we have placed it back into the free list and
verified it wasn't merged.

I'm open to suggestions on how to name a function that is meant to be the
inverse of __isolate_free_page. All I did is swap the isolate and free
verb/adjective.

> > +void __free_isolated_page(struct page *page, unsigned int order)
> > +{
> > +	struct zone *zone = page_zone(page);
> > +	unsigned long pfn;
> > +	unsigned int mt;
> > +
> > +	/* zone lock should be held when this function is called */
> > +	lockdep_assert_held(&zone->lock);
> > +
> > +	pfn = page_to_pfn(page);
> > +	mt = get_pfnblock_migratetype(page, pfn);
> > +
> > +	/*
> > +	 * Return isolated page to tail of freelist and don't bother with
> > +	 * triggering the page reporting notifiers since this page was
> > +	 * previously on the freelist and has likely already been reported.
> > +	 */
> > +	__free_one_page(page, pfn, zone, order, mt, true);
> > +}
> > +#endif /* CONFIG_PAGE_REPORTING */
> > +
> >  /*
> >   * Update NUMA hit/miss statistics
> >   *
> > diff --git a/mm/page_reporting.c b/mm/page_reporting.c
> > new file mode 100644
> > index 000000000000..4844f0aa2904
> > --- /dev/null
> > +++ b/mm/page_reporting.c
> > @@ -0,0 +1,337 @@
> > +// SPDX-License-Identifier: GPL-2.0
> > +#include <linux/mm.h>
> > +#include <linux/mmzone.h>
> > +#include <linux/page_reporting.h>
> > +#include <linux/gfp.h>
> > +#include <linux/export.h>
> > +#include <linux/delay.h>
> > +#include <linux/scatterlist.h>
> > +
> > +#include "page_reporting.h"
> > +#include "internal.h"
> > +
> > +static struct page_reporting_dev_info __rcu *pr_dev_info __read_mostly;
> > +
> > +#define for_each_reporting_migratetype_order(_order, _type) \
> > +	for (_order = PAGE_REPORTING_MIN_ORDER; _order < MAX_ORDER; _order++) \
> > +		for (_type = 0; _type < MIGRATE_TYPES; _type++) \
> > +			if (!is_migrate_isolate(_type))
> > +
> 
> This only has one user so simply put it in place. As this stands, _order
> and _type can be evaluated multiple times which potentially leads to
> chaos

Good point. Back when I started I had several spots using it. I guess I
have consolidated all of them now.

> > +static void page_reporting_populate_metadata(struct zone *zone)
> > +{
> > +	size_t size;
> > +	int node;
> > +
> > +	/*
> > +	 * We need to make sure we have somewhere to store the tracking
> > +	 * data for how many reported pages are in the zone. To do that
> > +	 * we need to make certain zone->reported_pages is populated.
> > +	 */
> > +	if (zone->reported_pages)
> > +		return;
> > +
> > +	node = zone_to_nid(zone);
> > +	size = (MAX_ORDER - PAGE_REPORTING_MIN_ORDER) * sizeof(unsigned long);
> > +	zone->reported_pages = kzalloc_node(size, GFP_KERNEL, node);
> > +}
> > +
> 
> reported_pages is not necessarily updated by a CPU local to the zone.
> There is not much point worrying about its locality.

Okay, I can drop that.

> > +static void
> > +page_reporting_drain(struct page_reporting_dev_info *prdev, struct zone *zone)
> > +{
> > +	struct scatterlist *sg = prdev->sg;
> > +
> > +	/*
> > +	 * Drain the now reported pages back into their respective
> > +	 * free lists/areas. We assume at least one page is populated.
> > +	 */
> > +	do {
> > +		unsigned int order = get_order(sg->length);
> > +		struct page *page = sg_page(sg);
> > +
> > +		__free_isolated_page(page, order);
> > +
> > +		/*
> > +		 * If page was not comingled with another page we can
> > +		 * consider the result to be "reported" since the page
> > +		 * hasn't been modified, otherwise we will need to
> > +		 * report on the new larger page when we make our way
> > +		 * up to that higher order.
> > +		 */
> > +		if (PageBuddy(page) && page_order(page) == order)
> > +			mark_page_reported(page, zone, order);
> > +	} while (!sg_is_last(sg++));
> > +}
> > +
> > +/*
> > + * The page reporting cycle consists of 4 stages, fill, report, drain, and
> > + * idle. We will cycle through the first 3 stages until we cannot obtain a
> > + * full scatterlist of pages, in that case we will switch to idle.
> > + */
> 
> Document the return value because it's unclear why the number of populated
> elements in sg is not tracked in page_reporting_dev_info. It seems
> unnecessarily fragile.

Will do in terms of documenting the return value.

As far as tracking the number of elements it mostly just has to do with
how this code has evolved. Originally this was just going straight to the
report function. However that leads to partial requests and I wanted to
avoid those since the cost for each call into the hypervisor can be high.

> > +static unsigned int
> > +page_reporting_cycle(struct page_reporting_dev_info *prdev, struct zone *zone,
> > +		     unsigned int order, unsigned int mt, unsigned int nents)
> > +{
> > +	struct list_head *list = &zone->free_area[order].free_list[mt];
> > +	unsigned int page_len = PAGE_SIZE << order;
> > +	struct scatterlist *sg = prdev->sg;
> > +	struct page *page, *next;
> > +
> > +	/*
> > +	 * Perform early check, if free area is empty there is
> > +	 * nothing to process so we can skip this free_list.
> > +	 */
> > +	if (list_empty(list))
> > +		return nents;
> > +
> > +	spin_lock_irq(&zone->lock);
> > +
> > +	/* loop through free list adding unreported pages to sg list */
> > +	list_for_each_entry_safe(page, next, list, lru) {
> > +		/* We are going to skip over the reported pages. */
> > +		if (PageReported(page))
> > +			continue;
> > +
> > +		/* Attempt to add page to sg list */
> > +		if (nents < prdev->capacity) {
> > +			if (!__isolate_free_page(page, order))
> > +				break;
> > +
> > +			sg_set_page(&sg[nents++], page, page_len, 0);
> > +			continue;
> > +		}
> > +
> > +		/*
> > +		 * Make the first non-reported entry in the free list
> > +		 * the new head of the free list before we exit.
> > +		 */
> > +		if (!list_is_first(&page->lru, list))
> > +			list_rotate_to_front(&page->lru, list);
> > +
> > +		/* release lock before waiting on report processing*/
> > +		spin_unlock_irq(&zone->lock);
> > +
> > +		/* begin processing pages in local list */
> > +		prdev->report(prdev, nents);
> > +
> > +		/* reset number of entries */
> > +		nents = 0;
> > +
> > +		/* reacquire zone lock and resume processing free lists */
> > +		spin_lock_irq(&zone->lock);
> > +
> > +		/* flush reported pages from the sg list */
> > +		page_reporting_drain(prdev, zone);
> > +
> > +		/*
> > +		 * Reset next to first entry, the old next isn't valid
> > +		 * since we dropped the lock to report the pages
> > +		 */
> > +		next = list_first_entry(list, struct page, lru);
> > +	}
> > +
> > +	spin_unlock_irq(&zone->lock);
> > +
> > +	return nents;
> > +}
> > +
> > +static int
> > +page_reporting_process_zone(struct page_reporting_dev_info *prdev,
> > +			    struct zone *zone)
> > +{
> > +	unsigned int order, mt, nents = 0;
> > +	unsigned long watermark;
> > +	int refcnt = -1;
> > +
> > +	page_reporting_populate_metadata(zone);
> > +
> > +	/* Generate minimum watermark to be able to guarantee progress */
> > +	watermark = low_wmark_pages(zone) +
> > +		    (prdev->capacity << PAGE_REPORTING_MIN_ORDER);
> > +
> > +	/*
> > +	 * Cancel request if insufficient free memory or if we failed
> > +	 * to allocate page reporting statistics for the zone.
> > +	 */
> > +	if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA) ||
> > +	    !zone->reported_pages) {
> > +		spin_lock_irq(&zone->lock);
> > +		goto zone_not_ready;
> > +	}
> 
> The zone lock is acquired just for the zone bit and the refcnt? That
> seems drastic overkill because the bit handling is already racy and the
> refcnt is overkill.

I'm not sure I follow.

> > +
> > +	sg_init_table(prdev->sg, prdev->capacity);
> > +
> > +	/* Process each free list starting from lowest order/mt */
> > +	for_each_reporting_migratetype_order(order, mt)
> > +		nents = page_reporting_cycle(prdev, zone, order, mt, nents);
> > +
> > +	/* mark end of sg list and report the remainder */
> > +	if (nents) {
> > +		sg_mark_end(&prdev->sg[nents - 1]);
> > +		prdev->report(prdev, nents);
> > +	}
> > +
> > +	spin_lock_irq(&zone->lock);
> > +
> > +	/* flush any remaining pages out from the last report */
> > +	if (nents)
> > +		page_reporting_drain(prdev, zone);
> > +
> > +	/* check to see if values are low enough for us to stop for now */
> > +	for (order = PAGE_REPORTING_MIN_ORDER; order < MAX_ORDER; order++) {
> > +		if (pages_unreported(zone, order) < PAGE_REPORTING_HWM)
> > +			continue;
> > +#ifdef CONFIG_MEMORY_ISOLATION
> > +		/*
> > +		 * Do not allow a free_area with isolated pages to request
> > +		 * that we continue with page reporting. Keep the reporting
> > +		 * light until the isolated pages have been cleared.
> > +		 */
> > +		if (!free_area_empty(&zone->free_area[order], MIGRATE_ISOLATE))
> > +			continue;
> > +#endif
> > +		goto zone_not_complete;
> > +	}
> > +
> > +zone_not_ready:
> > +	/*
> > +	 * If there are no longer enough free pages to fully populate
> > +	 * the scatterlist, then we can just shut it down for this zone.
> > +	 */
> > +	__clear_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags);
> > +	refcnt = atomic_dec_return(&prdev->refcnt);
> 
> If a request comes in while processing is already happening then the
> subsequent request is lost.

How can a request come in when we are holding the zone lock? Basically the
notify call can only occur while holding the zone lock. That is one of the
reasons for holding the lock is to protect the flag and keep it consistent
with the page counts as we clear it.

The only case where we are not checking the counts is for the case above
where we clear it due to us being too close to the watermark. In that case
we want to just ignore the request anyway.

> > +zone_not_complete:
> > +	spin_unlock_irq(&zone->lock);
> > +
> > +	return refcnt;
> > +}
> > +
> > +static void page_reporting_process(struct work_struct *work)
> > +{
> > +	struct delayed_work *d_work = to_delayed_work(work);
> > +	struct page_reporting_dev_info *prdev =
> > +		container_of(d_work, struct page_reporting_dev_info, work);
> > +	struct zone *zone = first_online_pgdat()->node_zones;
> > +	int refcnt = -1;
> > +
> > +	do {
> > +		if (test_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags))
> > +			refcnt = page_reporting_process_zone(prdev, zone);
> > +
> > +		/* Move to next zone, if at end of list start over */
> > +		zone = next_zone(zone) ? : first_online_pgdat()->node_zones;
> > +
> > +		/*
> > +		 * As long as refcnt has not reached zero there are still
> > +		 * zones to be processed.
> > +		 */
> > +	} while (refcnt);
> > +}
> > +
> 
> This is being done from a workqueue context and potentially this runs
> forever if the refcnt remains elevated. It's dangerous and should be in
> it's own patch. In the basic implementation, just do a single pass of
> all zones.

So I already have a modification that I have for the next version of the
patch set where instead of doing a do/while I simply reschedule the
delayed work to run again in 200ms if we still have work outstanding.

What I can do is split that out so that it is in the second patch with
optimizations.

> > +/* request page reporting on this zone */
> > +void __page_reporting_request(struct zone *zone)
> > +{
> > +	struct page_reporting_dev_info *prdev;
> > +
> > +	rcu_read_lock();
> > +
> > +	/*
> > +	 * We use RCU to protect the pr_dev_info pointer. In almost all
> > +	 * cases this should be present, however in the unlikely case of
> > +	 * a shutdown this will be NULL and we should exit.
> > +	 */
> > +	prdev = rcu_dereference(pr_dev_info);
> > +	if (unlikely(!prdev))
> > +		goto out;
> > +
> > +	/*
> > +	 * We can use separate test and set operations here as there
> > +	 * is nothing else that can set or clear this bit while we are
> > +	 * holding the zone lock. The advantage to doing it this way is
> > +	 * that we don't have to dirty the cacheline unless we are
> > +	 * changing the value.
> > +	 */
> > +	__set_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags);
> > +
> 
> The comment implies that the bit should have been tested first.

It was in the page_reporting_notify_free() call. I can update the comment.

> > +	/*
> > +	 * Delay the start of work to allow a sizable queue to
> > +	 * build. For now we are limiting this to running no more
> > +	 * than 5 times per second.
> > +	 */
> > +	if (!atomic_fetch_inc(&prdev->refcnt))
> > +		schedule_delayed_work(&prdev->work, HZ / 5);
> 
> The refcnt is incremented whether this zone has already been requested or
> not but only decremented when the bit is cleared so the refcnt potentially
> remains elevated forever.

So this is one of the reasons why all accesses to the flag are protected
by the zone lock. Basically page_reporting_notify_free() and this function
are both called with the zone lock held.

The only other caller of this function is page_reporting_register which
calls it for each populated zone. I suppose I could make it for every zone
since it is possible that someone unloaded the driver, unpopulated a zone,
and then reloaded the driver, but anyway the idea is that the zone lock is
keeping the flag and refcount consistent.

> > +out:
> > +	rcu_read_unlock();
> > +}
> > +
> > +static DEFINE_MUTEX(page_reporting_mutex);
> > +DEFINE_STATIC_KEY_FALSE(page_reporting_enabled);
> > +
> > +void page_reporting_unregister(struct page_reporting_dev_info *prdev)
> > +{
> > +	mutex_lock(&page_reporting_mutex);
> > +
> > +	if (rcu_access_pointer(pr_dev_info) == prdev) {
> > +		/* Disable page reporting notification */
> > +		RCU_INIT_POINTER(pr_dev_info, NULL);
> > +		synchronize_rcu();
> > +
> > +		/* Flush any existing work, and lock it out */
> > +		cancel_delayed_work_sync(&prdev->work);
> > +
> > +		/* Free scatterlist */
> > +		kfree(prdev->sg);
> > +		prdev->sg = NULL;
> > +	}
> > +
> > +	mutex_unlock(&page_reporting_mutex);
> > +}
> > +EXPORT_SYMBOL_GPL(page_reporting_unregister);
> > +
> > +int page_reporting_register(struct page_reporting_dev_info *prdev)
> > +{
> > +	struct zone *zone;
> > +	int err = 0;
> > +
> > +	/* No point in enabling this if it cannot handle any pages */
> > +	if (WARN_ON(!prdev->capacity || prdev->capacity > PAGE_REPORTING_HWM))
> > +		return -EINVAL;
> > +
> > +	mutex_lock(&page_reporting_mutex);
> > +
> > +	/* nothing to do if already in use */
> > +	if (rcu_access_pointer(pr_dev_info)) {
> > +		err = -EBUSY;
> > +		goto err_out;
> > +	}
> > +
> > +	/* allocate scatterlist to store pages being reported on */
> > +	prdev->sg = kcalloc(prdev->capacity, sizeof(*prdev->sg), GFP_KERNEL);
> > +	if (!prdev->sg) {
> > +		err = -ENOMEM;
> > +		goto err_out;
> > +	}
> > +
> > +
> > +	/* initialize refcnt and work structures */
> > +	atomic_set(&prdev->refcnt, 0);
> > +	INIT_DELAYED_WORK(&prdev->work, &page_reporting_process);
> > +
> > +	/* assign device, and begin initial flush of populated zones */
> > +	rcu_assign_pointer(pr_dev_info, prdev);
> > +	for_each_populated_zone(zone) {
> > +		spin_lock_irq(&zone->lock);
> > +		__page_reporting_request(zone);
> > +		spin_unlock_irq(&zone->lock);
> > +	}
> > +
> > +	/* enable page reporting notification */
> > +	if (!static_key_enabled(&page_reporting_enabled)) {
> > +		static_branch_enable(&page_reporting_enabled);
> > +		pr_info("Unused page reporting enabled\n");
> > +	}
> > +err_out:
> > +	mutex_unlock(&page_reporting_mutex);
> > +
> > +	return err;
> > +}
> > +EXPORT_SYMBOL_GPL(page_reporting_register);
> > diff --git a/mm/page_reporting.h b/mm/page_reporting.h
> > new file mode 100644
> > index 000000000000..2ad31bbb0036
> > --- /dev/null
> > +++ b/mm/page_reporting.h
> > @@ -0,0 +1,125 @@
> > +/* SPDX-License-Identifier: GPL-2.0 */
> > +#ifndef _MM_PAGE_REPORTING_H
> > +#define _MM_PAGE_REPORTING_H
> > +
> > +#include <linux/mmzone.h>
> > +#include <linux/pageblock-flags.h>
> > +#include <linux/page-isolation.h>
> > +#include <linux/jump_label.h>
> > +#include <linux/slab.h>
> > +#include <asm/pgtable.h>
> > +
> > +#define PAGE_REPORTING_MIN_ORDER	pageblock_order
> 
> This is potentially the same as MAX_ORDER-1. Not sure if it matters or
> not.

It doesn't. Basically what I am going for is the largest order that it is
safe to report on that will not break THP. If THP is not enabled then this
value should be MAX_ORDER - 1 if I am not mistaken.

> > +#define PAGE_REPORTING_HWM		32
> > +
> > +#ifdef CONFIG_PAGE_REPORTING
> > +/* Reported page accessors, defined in page_alloc.c */
> > +void __free_isolated_page(struct page *page, unsigned int order);
> > +
> > +/* Free reported_pages and reset reported page tracking count to 0 */
> > +static inline void page_reporting_reset_zone(struct zone *zone)
> > +{
> > +	kfree(zone->reported_pages);
> > +	zone->reported_pages = NULL;
> > +}
> > +
> > +DECLARE_STATIC_KEY_FALSE(page_reporting_enabled);
> > +void __page_reporting_request(struct zone *zone);
> > +
> > +static inline bool page_reported(struct page *page)
> > +{
> > +	return static_branch_unlikely(&page_reporting_enabled) &&
> > +	       PageReported(page);
> > +}
> > +
> > +static inline unsigned long
> > +pages_unreported(struct zone *zone, int order)
> > +{
> > +	unsigned long nr_free;
> > +	int report_order;
> > +
> > +	/* Limit notifications only to higher order pages */
> > +	report_order = order - PAGE_REPORTING_MIN_ORDER;
> > +	if (report_order < 0)
> > +		return 0;
> > +
> > +	nr_free = zone->free_area[order].nr_free;
> > +
> > +	/* Only subtract reported_pages count if it is present */
> > +	if (!zone->reported_pages)
> > +		return nr_free;
> > +
> > +	return nr_free - zone->reported_pages[report_order];
> > +}
> 
> Initially, this should be a full list traversal because I'm not
> convinced the reported_pages count is kept perfectly in sync. The
> optimisation confuses the review of the basic feature itself.

This is called per freed page in page_reporting_notify_free below. Are you
saying I have to traverse the entire free list per freed page?

If that is what you are wanting I would still probably want to limit it
such that we only walk the first PAGE_REPORTING_HWM worth of pages and if
those are not reported then just report that many.

> > +
> > +/**
> > + * page_reporting_notify_free - Free page notification to start page processing
> > + * @zone: Pointer to current zone of last page processed
> > + * @order: Order of last page added to zone
> > + *
> > + * This function is meant to act as a screener for __page_reporting_request
> > + * which will determine if a give zone has crossed over the high-water mark
> > + * that will justify us beginning page treatment. If we have crossed that
> > + * threshold then it will start the process of pulling some pages and
> > + * placing them in the batch list for treatment.
> > + */
> > +static inline void page_reporting_notify_free(struct zone *zone, int order)
> > +{
> > +	/* Called from hot path in __free_one_page() */
> > +	if (!static_branch_unlikely(&page_reporting_enabled))
> > +		return;
> > +
> > +	/* Do not bother with tests if we have already requested reporting */
> > +	if (test_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags))
> > +		return;
> > +
> > +	/* Determine if we have crossed reporting threshold */
> > +	if (pages_unreported(zone, order) < PAGE_REPORTING_HWM)
> > +		return;
> > +
> > +	/* This is slow, but should be called very rarely */
> > +	__page_reporting_request(zone);
> > +}
> > +
> > +/*
> > + * Functions for marking/clearing reported pages from the freelist.
> > + * All of them expect the zone lock to be held to maintain
> > + * consistency of the reported_pages count versus nr_free.
> > + */
> > +static inline void
> > +mark_page_reported(struct page *page, struct zone *zone, unsigned int order)
> > +{
> > +	/* flag page as reported */
> > +	__SetPageReported(page);
> > +
> > +	/* update areated page accounting */
> > +	zone->reported_pages[order - PAGE_REPORTING_MIN_ORDER]++;
> > +}
> > +
> > +static inline void
> > +clear_page_reported(struct page *page, struct zone *zone, unsigned int order)
> > +{
> > +	/* page_private will contain the page order, so just use it directly */
> > +	zone->reported_pages[order - PAGE_REPORTING_MIN_ORDER]--;
> > +
> > +	/* clear the flag so we can report on it when it returns */
> > +	__ClearPageReported(page);
> > +}
> > +
> > +#else /* CONFIG_PAGE_REPORTING */
> > +#define page_reported(_page)	false
> > +
> > +static inline void page_reporting_reset_zone(struct zone *zone)
> > +{
> > +}
> > +
> > +static inline void page_reporting_notify_free(struct zone *zone, int order)
> > +{
> > +}
> > +
> > +static inline void
> > +clear_page_reported(struct page *page, struct zone *zone, unsigned int order)
> > +{
> > +}
> > +#endif /* CONFIG_PAGE_REPORTING */
> > +#endif /*_MM_PAGE_REPORTING_H */
> >
Mel Gorman Nov. 27, 2019, 6:35 p.m. UTC | #3
On Wed, Nov 27, 2019 at 09:22:09AM -0800, Alexander Duyck wrote:
> > Ok, I'm ok with how this hooks into the allocator as the overhead is
> > minimal. However, the patch itself still includes a number of
> > optimisations instead of being a bare-boned implementation of the
> > feature with optimisations layered on top. I think some of the
> > optimisations are also broken but it's harder to be sure because both
> > the feature and the optimisations are lumped together.
> 
> Well I can work on splitting them out if need be. 
> 

It would be preferred because some of the optimisations are fairly
subtle and it distracts from having a basic implementation of the
feature as a foundation to build upon.

> > > diff --git a/include/linux/page_reporting.h b/include/linux/page_reporting.h
> > > new file mode 100644
> > > index 000000000000..925a16b1d14b
> > > --- /dev/null
> > > +++ b/include/linux/page_reporting.h
> > > @@ -0,0 +1,31 @@
> > > +/* SPDX-License-Identifier: GPL-2.0 */
> > > +#ifndef _LINUX_PAGE_REPORTING_H
> > > +#define _LINUX_PAGE_REPORTING_H
> > > +
> > > +#include <linux/mmzone.h>
> > > +
> > > +struct page_reporting_dev_info {
> > > +	/* function that alters pages to make them "reported" */
> > > +	void (*report)(struct page_reporting_dev_info *prdev,
> > > +		       unsigned int nents);
> > > +
> > > +	/* pointer to scatterlist containing pages to be processed */
> > > +	struct scatterlist *sg;
> > > +
> > 
> > The choice of scatterlist is curious because it adds unnecessary complexity
> > without needing the benefits scatterlist and sg_table provides. All you
> > really need is an array of pages that is NULL terminated because you can
> > get the order of the struct page when it's a buddy page.
> 
> The scatterlist is mostly about dealing with DMA mapping of the pages.
> Most devices will need a way to push the pages out to the device doing the
> reporting so I thought a scatterlist was the best way to gather the pages
> together so that they could be mapped with one call.
> 

Ok, might be worth adding a comment about that noting that it may appear
excessive but it's to avoid a situation where drivers have to convert
page arrays to scatterlists.

> > > +	/*
> > > +	 * Upper limit on the number of pages that the report function
> > > +	 * expects to be placed into the scatterlist to be processed.
> > > +	 */
> > > +	unsigned int capacity;
> > > +
> > 
> > Instead of requiring the driver to specify capacity, why did you not
> > simply make it PAGE_REPORTING_HWM and statically declare the array?
> 
> The problem is the device might not be able to support PAGE_REPORTING_HWM.

I don't see why given that a driver that cannot handle PAGE_REPORTING_HWM
could process subsets of the pages reported. It seems unnecessary.

> So I needed some way for it to communicate that. I could allocate the
> array statically if that is what you prefer.
> 

It would make sense if it's a fixed size and let drivers figure out whether
the full array can be processed at once or has to be split into parts.

> > > +	/* The number of zones requesting reporting */
> > > +	atomic_t refcnt;
> > > +
> > 
> > The refcnt is overkill. Simply loop over all zones until there is a
> > clear pass. Despite being atomic, it actually requires the zone lock to
> > avoid races in places like this
> > 
> > 		if (test_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags))
> > 			refcnt = page_reporting_process_zone(prdev, zone);
> > 
> > The optimisation is small and it's relatively subtle.
> 
> I disagree. Without that we can easily get into states where a zone
> requests reporting and we never get around to servicing it.

Why would that happen if all zones were iterated during a single pass?

> I am using the
> refcount to track that so that we don't shutdown the worker thread when
> there is at least one zone requesting service.
> 

Then either single pass or loop through all zones until a loop completes
with no zones to be processed. It's far simplier than a refcount.

> > >  static inline void __free_one_page(struct page *page,
> > >  		unsigned long pfn,
> > >  		struct zone *zone, unsigned int order,
> > > -		int migratetype)
> > > +		int migratetype, bool reported)
> > >  {
> > >  	struct capture_control *capc = task_capc(zone);
> > >  	unsigned long uninitialized_var(buddy_pfn);
> > > @@ -1048,7 +1053,9 @@ static inline void __free_one_page(struct page *page,
> > >  done_merging:
> > >  	set_page_order(page, order);
> > >  
> > > -	if (is_shuffle_order(order))
> > > +	if (reported)
> > > +		to_tail = true;
> > > +	else if (is_shuffle_order(order))
> > >  		to_tail = shuffle_pick_tail();
> > >  	else
> > >  		to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order);
> > > @@ -1057,6 +1064,14 @@ static inline void __free_one_page(struct page *page,
> > >  		add_to_free_list_tail(page, zone, order, migratetype);
> > >  	else
> > >  		add_to_free_list(page, zone, order, migratetype);
> > > +
> > > +	/*
> > > +	 * No need to notify on a reported page as the total count of
> > > +	 * unreported pages will not have increased since we have essentially
> > > +	 * merged the reported page with one or more unreported pages.
> > > +	 */
> > > +	if (!reported)
> > > +		page_reporting_notify_free(zone, order);
> > >  }
> > >  
> > >  /*
> > 
> > If a reported page is merged with a larger buddy then the counts for the
> > lower order needs to be updated or the counter gets out of sync. Then the
> > reported status of the page needs to be cleared as the larger block may
> > only be partially reported and the count is wrong. I know why you want
> > the reported pages but it really should be in its own patch. This patch
> > really should be just the bare essentials to support reporting of free
> > pages even if it's sub-optimal. I know you also use reported_pages as
> > part of a stop condition but a basic stop condition is simply to do a
> > single pass.
> 
> Okay so there are actually a few things here to unpack.
> 
> First the comment is a bit out of date. The reason I don't need to bother
> with reporting is because I process the lower orders before the higher
> orders.
> As such we are still processing this zone if we are returning a
> reported page and it is merged. We will reprocess the larger page in the
> next pass.
> 

I don't see what guarantees the lower order buddy was definitely
reported. The lower order could have been in an isolated pageblock --
bit insane but not impossible. It also could have failed to be isolated
due to a watermark check. Either way, the accounting gets screwy.

> Second, at the point where we call this function with the reported flag
> set we have not yet set the page as reported. There is logic that will
> check for that later and set the bits and increment the count if the page
> becomes a buddy page and the order is still the same as the order we
> originally freed it under.
> 

That is sufficiently complex that it really should be in its own patch
because right now, any bug there would either revert the whole feature
or do a partial revert if it couldn't be fixed properly. At least having
the option of reverting the optimisation would be useful for testing.
By not splitting it out, we're also prevented from being able to ack the
basic infrastructure itself. Even if the optimisations could not be agreed
upon, the feature would still exist -- just slower than is ideal.

> Lastly, if you are concerned about us merging a reported page already on
> the list the count is updated and the flag is cleared from the page when
> it is deleted from the free list to be merged with the new page.
> 
> > > @@ -3228,6 +3243,36 @@ int __isolate_free_page(struct page *page, unsigned int order)
> > >  	return 1UL << order;
> > >  }
> > >  
> > > +#ifdef CONFIG_PAGE_REPORTING
> > > +/**
> > > + * __free_isolated_page - Return a now-isolated page back where we got it
> > > + * @page: Page that was isolated
> > > + * @order: Order of the isolated page
> > > + *
> > > + * This function is meant to return a page pulled from the free lists via
> > > + * __isolate_free_page back to the free lists they were pulled from.
> > > + */
> > 
> > Isolated within mm has special meaning already. __putback_reported_page?
> 
> I wanted to get away from calling it a reported page because it isn't at
> the point where we are calling this function. We don't set the reported
> bit on the page until we have placed it back into the free list and
> verified it wasn't merged.
> 
> I'm open to suggestions on how to name a function that is meant to be the
> inverse of __isolate_free_page. All I did is swap the isolate and free
> verb/adjective.
> 

__putback_isolated_page would at least have a similar naming pattern to
how LRU pages are isolated and putback.

> > > +static void
> > > +page_reporting_drain(struct page_reporting_dev_info *prdev, struct zone *zone)
> > > +{
> > > +	struct scatterlist *sg = prdev->sg;
> > > +
> > > +	/*
> > > +	 * Drain the now reported pages back into their respective
> > > +	 * free lists/areas. We assume at least one page is populated.
> > > +	 */
> > > +	do {
> > > +		unsigned int order = get_order(sg->length);
> > > +		struct page *page = sg_page(sg);
> > > +
> > > +		__free_isolated_page(page, order);
> > > +
> > > +		/*
> > > +		 * If page was not comingled with another page we can
> > > +		 * consider the result to be "reported" since the page
> > > +		 * hasn't been modified, otherwise we will need to
> > > +		 * report on the new larger page when we make our way
> > > +		 * up to that higher order.
> > > +		 */
> > > +		if (PageBuddy(page) && page_order(page) == order)
> > > +			mark_page_reported(page, zone, order);
> > > +	} while (!sg_is_last(sg++));
> > > +}
> > > +
> > > +/*
> > > + * The page reporting cycle consists of 4 stages, fill, report, drain, and
> > > + * idle. We will cycle through the first 3 stages until we cannot obtain a
> > > + * full scatterlist of pages, in that case we will switch to idle.
> > > + */
> > 
> > Document the return value because it's unclear why the number of populated
> > elements in sg is not tracked in page_reporting_dev_info. It seems
> > unnecessarily fragile.
> 
> Will do in terms of documenting the return value.
> 
> As far as tracking the number of elements it mostly just has to do with
> how this code has evolved. Originally this was just going straight to the
> report function. However that leads to partial requests and I wanted to
> avoid those since the cost for each call into the hypervisor can be high.
> 

It might be worth putting the count into the struct then as it's more
straight-forward than tracking struct state outside of the struct.

> > > +static int
> > > +page_reporting_process_zone(struct page_reporting_dev_info *prdev,
> > > +			    struct zone *zone)
> > > +{
> > > +	unsigned int order, mt, nents = 0;
> > > +	unsigned long watermark;
> > > +	int refcnt = -1;
> > > +
> > > +	page_reporting_populate_metadata(zone);
> > > +
> > > +	/* Generate minimum watermark to be able to guarantee progress */
> > > +	watermark = low_wmark_pages(zone) +
> > > +		    (prdev->capacity << PAGE_REPORTING_MIN_ORDER);
> > > +
> > > +	/*
> > > +	 * Cancel request if insufficient free memory or if we failed
> > > +	 * to allocate page reporting statistics for the zone.
> > > +	 */
> > > +	if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA) ||
> > > +	    !zone->reported_pages) {
> > > +		spin_lock_irq(&zone->lock);
> > > +		goto zone_not_ready;
> > > +	}
> > 
> > The zone lock is acquired just for the zone bit and the refcnt? That
> > seems drastic overkill because the bit handling is already racy and the
> > refcnt is overkill.
> 
> I'm not sure I follow.
> 

The lock is acquired before branching to zone_not_ready for the purpose
of clearing a zone bit and updating the ref count. That is hinting at
the possibility that zone lock is protecting much more than it should.

> > > +
> > > +	sg_init_table(prdev->sg, prdev->capacity);
> > > +
> > > +	/* Process each free list starting from lowest order/mt */
> > > +	for_each_reporting_migratetype_order(order, mt)
> > > +		nents = page_reporting_cycle(prdev, zone, order, mt, nents);
> > > +
> > > +	/* mark end of sg list and report the remainder */
> > > +	if (nents) {
> > > +		sg_mark_end(&prdev->sg[nents - 1]);
> > > +		prdev->report(prdev, nents);
> > > +	}
> > > +
> > > +	spin_lock_irq(&zone->lock);
> > > +
> > > +	/* flush any remaining pages out from the last report */
> > > +	if (nents)
> > > +		page_reporting_drain(prdev, zone);
> > > +
> > > +	/* check to see if values are low enough for us to stop for now */
> > > +	for (order = PAGE_REPORTING_MIN_ORDER; order < MAX_ORDER; order++) {
> > > +		if (pages_unreported(zone, order) < PAGE_REPORTING_HWM)
> > > +			continue;
> > > +#ifdef CONFIG_MEMORY_ISOLATION
> > > +		/*
> > > +		 * Do not allow a free_area with isolated pages to request
> > > +		 * that we continue with page reporting. Keep the reporting
> > > +		 * light until the isolated pages have been cleared.
> > > +		 */
> > > +		if (!free_area_empty(&zone->free_area[order], MIGRATE_ISOLATE))
> > > +			continue;
> > > +#endif
> > > +		goto zone_not_complete;
> > > +	}
> > > +
> > > +zone_not_ready:
> > > +	/*
> > > +	 * If there are no longer enough free pages to fully populate
> > > +	 * the scatterlist, then we can just shut it down for this zone.
> > > +	 */
> > > +	__clear_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags);
> > > +	refcnt = atomic_dec_return(&prdev->refcnt);
> > 
> > If a request comes in while processing is already happening then the
> > subsequent request is lost.
> 
> How can a request come in when we are holding the zone lock?
 
page_reporting_cycle drops the lock so there is no obvious guarantee
that requests are not lost.

> Basically the
> notify call can only occur while holding the zone lock. That is one of the
> reasons for holding the lock is to protect the flag and keep it consistent
> with the page counts as we clear it.
> 

Ok, you really should not be relying on the zone lock for protecting
state like this. It's fragile and it abuses what zone lock is for. It's
fragile because zone flags is not intended to protected by the zone
lock. Historically there would have been more flags but even currently,
the flag is tested and set outside of the zone lock. As you are using
non-atomic ops, it gets even more fragile because flag updates are
potentially lost.

The zone lock is primarily to protect the free lists and the watermarks
which are strongly related to the free lists and expanding that scope to
protect an atomic and a zone flag is very questionable. At some point,
zone lock is going to have to be broken up somehow because it's a very
heavy lock on the allocator side. If zone lock is protecting multiple
things like this, that would get even harder.

If necessary, add a separate lock and use it to protect state related to
the page reporting but as part of that, you almost certainly will have
to move to atomic versions of bit operations for zone flags because it's
not protected as such.

Again, it really should be the case that ZONE_PAGE_REPORTING_REQUESTED
is split out into a separate patch and introduced standalone. It would
probably be on the justification of avoiding unnecessary zone free list
searches but still, the optimisation should be reviewed separately and
the locking of state should be clear.

> The only case where we are not checking the counts is for the case above
> where we clear it due to us being too close to the watermark. In that case
> we want to just ignore the request anyway.
> 
> > > +zone_not_complete:
> > > +	spin_unlock_irq(&zone->lock);
> > > +
> > > +	return refcnt;
> > > +}
> > > +
> > > +static void page_reporting_process(struct work_struct *work)
> > > +{
> > > +	struct delayed_work *d_work = to_delayed_work(work);
> > > +	struct page_reporting_dev_info *prdev =
> > > +		container_of(d_work, struct page_reporting_dev_info, work);
> > > +	struct zone *zone = first_online_pgdat()->node_zones;
> > > +	int refcnt = -1;
> > > +
> > > +	do {
> > > +		if (test_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags))
> > > +			refcnt = page_reporting_process_zone(prdev, zone);
> > > +
> > > +		/* Move to next zone, if at end of list start over */
> > > +		zone = next_zone(zone) ? : first_online_pgdat()->node_zones;
> > > +
> > > +		/*
> > > +		 * As long as refcnt has not reached zero there are still
> > > +		 * zones to be processed.
> > > +		 */
> > > +	} while (refcnt);
> > > +}
> > > +
> > 
> > This is being done from a workqueue context and potentially this runs
> > forever if the refcnt remains elevated. It's dangerous and should be in
> > it's own patch. In the basic implementation, just do a single pass of
> > all zones.
> 
> So I already have a modification that I have for the next version of the
> patch set where instead of doing a do/while I simply reschedule the
> delayed work to run again in 200ms if we still have work outstanding.
> 

That would be a bit more reasonable. It would probably remove the need
for the refcount entirely but either way -- split out the optimisations.
Otherwise the entirity of the feature has to be re-reviewed every time
which is time consuming.

> What I can do is split that out so that it is in the second patch with
> optimizations.
> 

One patch per optimisation please with data backing it up because it should
be possible to show that pages are reported faster or that overhead is
much lower. It would give a hint on whether the complexity is justified,
particularly if the locking is subtle.

> > > +/* request page reporting on this zone */
> > > +void __page_reporting_request(struct zone *zone)
> > > +{
> > > +	struct page_reporting_dev_info *prdev;
> > > +
> > > +	rcu_read_lock();
> > > +
> > > +	/*
> > > +	 * We use RCU to protect the pr_dev_info pointer. In almost all
> > > +	 * cases this should be present, however in the unlikely case of
> > > +	 * a shutdown this will be NULL and we should exit.
> > > +	 */
> > > +	prdev = rcu_dereference(pr_dev_info);
> > > +	if (unlikely(!prdev))
> > > +		goto out;
> > > +
> > > +	/*
> > > +	 * We can use separate test and set operations here as there
> > > +	 * is nothing else that can set or clear this bit while we are
> > > +	 * holding the zone lock. The advantage to doing it this way is
> > > +	 * that we don't have to dirty the cacheline unless we are
> > > +	 * changing the value.
> > > +	 */
> > > +	__set_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags);
> > > +
> > 
> > The comment implies that the bit should have been tested first.
> 
> It was in the page_reporting_notify_free() call. I can update the comment.
> 

But not the registration path (which probably doesn't matter). What is
much more critical is that again you are relying on the zone lock for
protection and correctness of a tiny micro-optimisation. Page reporting
really must not rely on the zone lock for anything outside of the free
list. We've already had a massive headache with mmap_sem protecting way
too much unnecessarily, we don't need a new one with zone that might
make it very difficult to break up that lock in the future.

> > > +	/*
> > > +	 * Delay the start of work to allow a sizable queue to
> > > +	 * build. For now we are limiting this to running no more
> > > +	 * than 5 times per second.
> > > +	 */
> > > +	if (!atomic_fetch_inc(&prdev->refcnt))
> > > +		schedule_delayed_work(&prdev->work, HZ / 5);
> > 
> > The refcnt is incremented whether this zone has already been requested or
> > not but only decremented when the bit is cleared so the refcnt potentially
> > remains elevated forever.
> 
> So this is one of the reasons why all accesses to the flag are protected
> by the zone lock.  Basically page_reporting_notify_free() and this function
> are both called with the zone lock held.
> 

This is extremely subtle and again, it's really not what zone lock is
for. It's too fragile but maybe refcnt is going away anyway. If not,
make a separate lock and document what it's protecting in the patch
introducing the optimisation.

> The only other caller of this function is page_reporting_register which
> calls it for each populated zone. I suppose I could make it for every zone
> since it is possible that someone unloaded the driver, unpopulated a zone,
> and then reloaded the driver, but anyway the idea is that the zone lock is
> keeping the flag and refcount consistent.
> 

I think you can guess at this point what I'll say about zone lock.

> > > +#define PAGE_REPORTING_MIN_ORDER	pageblock_order
> > 
> > This is potentially the same as MAX_ORDER-1. Not sure if it matters or
> > not.
> 
> It doesn't. Basically what I am going for is the largest order that it is
> safe to report on that will not break THP. If THP is not enabled then this
> value should be MAX_ORDER - 1 if I am not mistaken.
> 

Well, it's more about huge pages but yes, if you're ok with the
possibility that reporting only happens for the largest possible page
then that's fine.

> > > +	/* Limit notifications only to higher order pages */
> > > +	report_order = order - PAGE_REPORTING_MIN_ORDER;
> > > +	if (report_order < 0)
> > > +		return 0;
> > > +
> > > +	nr_free = zone->free_area[order].nr_free;
> > > +
> > > +	/* Only subtract reported_pages count if it is present */
> > > +	if (!zone->reported_pages)
> > > +		return nr_free;
> > > +
> > > +	return nr_free - zone->reported_pages[report_order];
> > > +}
> > 
> > Initially, this should be a full list traversal because I'm not
> > convinced the reported_pages count is kept perfectly in sync. The
> > optimisation confuses the review of the basic feature itself.
> 
> This is called per freed page in page_reporting_notify_free below. Are you
> saying I have to traverse the entire free list per freed page?
> 

In a basic unoptimised version -- yes. Put optimisations in separate
patches because then the basic feature itself can be reviewed and
commented upon. It'll also make it easier to understand any special
locking requirements for state.

> If that is what you are wanting I would still probably want to limit it
> such that we only walk the first PAGE_REPORTING_HWM worth of pages and if
> those are not reported then just report that many.
> 

Which in itself could be an optimisation patch. Maybe it'll be enough that
keeping track of the count is not worthwhile. Either way, the separate
patch could have supporting data on how much it improves the speed of
reporting pages so it can be compared to any other optimisation that
may be proposed. Supporting data would also help make the case that any
complexity introduced by the optimisation is worthwhile.
Alexander Duyck Nov. 27, 2019, 9:55 p.m. UTC | #4
On Wed, 2019-11-27 at 18:35 +0000, Mel Gorman wrote:
> On Wed, Nov 27, 2019 at 09:22:09AM -0800, Alexander Duyck wrote:
> > > Ok, I'm ok with how this hooks into the allocator as the overhead is
> > > minimal. However, the patch itself still includes a number of
> > > optimisations instead of being a bare-boned implementation of the
> > > feature with optimisations layered on top. I think some of the
> > > optimisations are also broken but it's harder to be sure because both
> > > the feature and the optimisations are lumped together.
> > 
> > Well I can work on splitting them out if need be. 
> > 
> 
> It would be preferred because some of the optimisations are fairly
> subtle and it distracts from having a basic implementation of the
> feature as a foundation to build upon.

Yeah, I will work on cleaning this up and then splitting out the
optimizations.

> > > > diff --git a/include/linux/page_reporting.h b/include/linux/page_reporting.h
> > > > new file mode 100644
> > > > index 000000000000..925a16b1d14b
> > > > --- /dev/null
> > > > +++ b/include/linux/page_reporting.h
> > > > @@ -0,0 +1,31 @@
> > > > +/* SPDX-License-Identifier: GPL-2.0 */
> > > > +#ifndef _LINUX_PAGE_REPORTING_H
> > > > +#define _LINUX_PAGE_REPORTING_H
> > > > +
> > > > +#include <linux/mmzone.h>
> > > > +
> > > > +struct page_reporting_dev_info {
> > > > +	/* function that alters pages to make them "reported" */
> > > > +	void (*report)(struct page_reporting_dev_info *prdev,
> > > > +		       unsigned int nents);
> > > > +
> > > > +	/* pointer to scatterlist containing pages to be processed */
> > > > +	struct scatterlist *sg;
> > > > +
> > > 
> > > The choice of scatterlist is curious because it adds unnecessary complexity
> > > without needing the benefits scatterlist and sg_table provides. All you
> > > really need is an array of pages that is NULL terminated because you can
> > > get the order of the struct page when it's a buddy page.
> > 
> > The scatterlist is mostly about dealing with DMA mapping of the pages.
> > Most devices will need a way to push the pages out to the device doing the
> > reporting so I thought a scatterlist was the best way to gather the pages
> > together so that they could be mapped with one call.
> > 
> 
> Ok, might be worth adding a comment about that noting that it may appear
> excessive but it's to avoid a situation where drivers have to convert
> page arrays to scatterlists.

I'll probably do that. I might also be able to split this out of the
structure. I will still pass around the scatterlist but I can explain the
purpose.

> > > > +	/*
> > > > +	 * Upper limit on the number of pages that the report function
> > > > +	 * expects to be placed into the scatterlist to be processed.
> > > > +	 */
> > > > +	unsigned int capacity;
> > > > +
> > > 
> > > Instead of requiring the driver to specify capacity, why did you not
> > > simply make it PAGE_REPORTING_HWM and statically declare the array?
> > 
> > The problem is the device might not be able to support PAGE_REPORTING_HWM.
> 
> I don't see why given that a driver that cannot handle PAGE_REPORTING_HWM
> could process subsets of the pages reported. It seems unnecessary.

I suppose it might be considered an optimization. Basically what I was
wanting to avoid is pulling out more pages then the device can process in
a single call. That is what the capacity represents. Basically the virtio
device can have a limited ring size which limits how many pages we can
have outstanding at a time. So I wanted to avoid pulling pages that I
couldn't immediately report.

> > So I needed some way for it to communicate that. I could allocate the
> > array statically if that is what you prefer.
> > 
> 
> It would make sense if it's a fixed size and let drivers figure out whether
> the full array can be processed at once or has to be split into parts.

In terms of allocation the fixed size makes sense to me. I still think it
would be good to communicate how many the device can process in a single
request so we don't have pages having to wait as the device has to segment
the scatterlist to process pieces of it.

> > > > +	/* The number of zones requesting reporting */
> > > > +	atomic_t refcnt;
> > > > +
> > > 
> > > The refcnt is overkill. Simply loop over all zones until there is a
> > > clear pass. Despite being atomic, it actually requires the zone lock to
> > > avoid races in places like this
> > > 
> > > 		if (test_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags))
> > > 			refcnt = page_reporting_process_zone(prdev, zone);
> > > 
> > > The optimisation is small and it's relatively subtle.
> > 
> > I disagree. Without that we can easily get into states where a zone
> > requests reporting and we never get around to servicing it.
> 
> Why would that happen if all zones were iterated during a single pass?

It is because I am not rescheduling the work while it is ongoing. My
notifier is using the reference count to only schedule on the first
request and not stop processing until we reach 0. Without that I have to
schedule the worker ever time a zone requests processing.

> > I am using the
> > refcount to track that so that we don't shutdown the worker thread when
> > there is at least one zone requesting service.
> > 
> 
> Then either single pass or loop through all zones until a loop completes
> with no zones to be processed. It's far simplier than a refcount.

I could do that if we only had one zone to process. However the problem is
that we could be processing multiple zones.

> > > >  static inline void __free_one_page(struct page *page,
> > > >  		unsigned long pfn,
> > > >  		struct zone *zone, unsigned int order,
> > > > -		int migratetype)
> > > > +		int migratetype, bool reported)
> > > >  {
> > > >  	struct capture_control *capc = task_capc(zone);
> > > >  	unsigned long uninitialized_var(buddy_pfn);
> > > > @@ -1048,7 +1053,9 @@ static inline void __free_one_page(struct page *page,
> > > >  done_merging:
> > > >  	set_page_order(page, order);
> > > >  
> > > > -	if (is_shuffle_order(order))
> > > > +	if (reported)
> > > > +		to_tail = true;
> > > > +	else if (is_shuffle_order(order))
> > > >  		to_tail = shuffle_pick_tail();
> > > >  	else
> > > >  		to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order);
> > > > @@ -1057,6 +1064,14 @@ static inline void __free_one_page(struct page *page,
> > > >  		add_to_free_list_tail(page, zone, order, migratetype);
> > > >  	else
> > > >  		add_to_free_list(page, zone, order, migratetype);
> > > > +
> > > > +	/*
> > > > +	 * No need to notify on a reported page as the total count of
> > > > +	 * unreported pages will not have increased since we have essentially
> > > > +	 * merged the reported page with one or more unreported pages.
> > > > +	 */
> > > > +	if (!reported)
> > > > +		page_reporting_notify_free(zone, order);
> > > >  }
> > > >  
> > > >  /*
> > > 
> > > If a reported page is merged with a larger buddy then the counts for the
> > > lower order needs to be updated or the counter gets out of sync. Then the
> > > reported status of the page needs to be cleared as the larger block may
> > > only be partially reported and the count is wrong. I know why you want
> > > the reported pages but it really should be in its own patch. This patch
> > > really should be just the bare essentials to support reporting of free
> > > pages even if it's sub-optimal. I know you also use reported_pages as
> > > part of a stop condition but a basic stop condition is simply to do a
> > > single pass.
> > 
> > Okay so there are actually a few things here to unpack.
> > 
> > First the comment is a bit out of date. The reason I don't need to bother
> > with reporting is because I process the lower orders before the higher
> > orders.
> > As such we are still processing this zone if we are returning a
> > reported page and it is merged. We will reprocess the larger page in the
> > next pass.
> > 
> 
> I don't see what guarantees the lower order buddy was definitely
> reported. The lower order could have been in an isolated pageblock --
> bit insane but not impossible. It also could have failed to be isolated
> due to a watermark check. Either way, the accounting gets screwy.

So if we merge a page it is not considered reported. I think you might be
confusing this with the bits in page_reporting_drain which check to verify
that the page we freed became a buddy and that buddy is the same order as
what we originally released. If a reported page is merged it is no longer
considered to be reported.

Basically if we pull a reported page from the free list to merge it then
we clear the reported status and decrement the reported page count for
that order.

> > Second, at the point where we call this function with the reported flag
> > set we have not yet set the page as reported. There is logic that will
> > check for that later and set the bits and increment the count if the page
> > becomes a buddy page and the order is still the same as the order we
> > originally freed it under.
> > 
> 
> That is sufficiently complex that it really should be in its own patch
> because right now, any bug there would either revert the whole feature
> or do a partial revert if it couldn't be fixed properly. At least having
> the option of reverting the optimisation would be useful for testing.
> By not splitting it out, we're also prevented from being able to ack the
> basic infrastructure itself. Even if the optimisations could not be agreed
> upon, the feature would still exist -- just slower than is ideal.

The only optimization here is the use of the reported variable. That can
actually go away since I hadn't realized I had changed things in the page
reporting cycle so that we don't clear the REPORTING_REQUESTED flag until
after the last drain has completed.

I'll work on splitting out the reported_pages bit into a separate patch,
and I will see what I can do about refcount since that seems to be the
other pain point.

> > Lastly, if you are concerned about us merging a reported page already on
> > the list the count is updated and the flag is cleared from the page when
> > it is deleted from the free list to be merged with the new page.
> > 
> > > > @@ -3228,6 +3243,36 @@ int __isolate_free_page(struct page *page, unsigned int order)
> > > >  	return 1UL << order;
> > > >  }
> > > >  
> > > > +#ifdef CONFIG_PAGE_REPORTING
> > > > +/**
> > > > + * __free_isolated_page - Return a now-isolated page back where we got it
> > > > + * @page: Page that was isolated
> > > > + * @order: Order of the isolated page
> > > > + *
> > > > + * This function is meant to return a page pulled from the free lists via
> > > > + * __isolate_free_page back to the free lists they were pulled from.
> > > > + */
> > > 
> > > Isolated within mm has special meaning already. __putback_reported_page?
> > 
> > I wanted to get away from calling it a reported page because it isn't at
> > the point where we are calling this function. We don't set the reported
> > bit on the page until we have placed it back into the free list and
> > verified it wasn't merged.
> > 
> > I'm open to suggestions on how to name a function that is meant to be the
> > inverse of __isolate_free_page. All I did is swap the isolate and free
> > verb/adjective.
> > 
> 
> __putback_isolated_page would at least have a similar naming pattern to
> how LRU pages are isolated and putback.

I can work with that then.

> > > > +static void
> > > > +page_reporting_drain(struct page_reporting_dev_info *prdev, struct zone *zone)
> > > > +{
> > > > +	struct scatterlist *sg = prdev->sg;
> > > > +
> > > > +	/*
> > > > +	 * Drain the now reported pages back into their respective
> > > > +	 * free lists/areas. We assume at least one page is populated.
> > > > +	 */
> > > > +	do {
> > > > +		unsigned int order = get_order(sg->length);
> > > > +		struct page *page = sg_page(sg);
> > > > +
> > > > +		__free_isolated_page(page, order);
> > > > +
> > > > +		/*
> > > > +		 * If page was not comingled with another page we can
> > > > +		 * consider the result to be "reported" since the page
> > > > +		 * hasn't been modified, otherwise we will need to
> > > > +		 * report on the new larger page when we make our way
> > > > +		 * up to that higher order.
> > > > +		 */
> > > > +		if (PageBuddy(page) && page_order(page) == order)
> > > > +			mark_page_reported(page, zone, order);
> > > > +	} while (!sg_is_last(sg++));
> > > > +}
> > > > +
> > > > +/*
> > > > + * The page reporting cycle consists of 4 stages, fill, report, drain, and
> > > > + * idle. We will cycle through the first 3 stages until we cannot obtain a
> > > > + * full scatterlist of pages, in that case we will switch to idle.
> > > > + */
> > > 
> > > Document the return value because it's unclear why the number of populated
> > > elements in sg is not tracked in page_reporting_dev_info. It seems
> > > unnecessarily fragile.
> > 
> > Will do in terms of documenting the return value.
> > 
> > As far as tracking the number of elements it mostly just has to do with
> > how this code has evolved. Originally this was just going straight to the
> > report function. However that leads to partial requests and I wanted to
> > avoid those since the cost for each call into the hypervisor can be high.
> > 
> 
> It might be worth putting the count into the struct then as it's more
> straight-forward than tracking struct state outside of the struct.

Yeah, that is kind of what I was thinking. If nothing else I might look at
using something like an sg_table structure to pass the entries around.

> > > > +static int
> > > > +page_reporting_process_zone(struct page_reporting_dev_info *prdev,
> > > > +			    struct zone *zone)
> > > > +{
> > > > +	unsigned int order, mt, nents = 0;
> > > > +	unsigned long watermark;
> > > > +	int refcnt = -1;
> > > > +
> > > > +	page_reporting_populate_metadata(zone);
> > > > +
> > > > +	/* Generate minimum watermark to be able to guarantee progress */
> > > > +	watermark = low_wmark_pages(zone) +
> > > > +		    (prdev->capacity << PAGE_REPORTING_MIN_ORDER);
> > > > +
> > > > +	/*
> > > > +	 * Cancel request if insufficient free memory or if we failed
> > > > +	 * to allocate page reporting statistics for the zone.
> > > > +	 */
> > > > +	if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA) ||
> > > > +	    !zone->reported_pages) {
> > > > +		spin_lock_irq(&zone->lock);
> > > > +		goto zone_not_ready;
> > > > +	}
> > > 
> > > The zone lock is acquired just for the zone bit and the refcnt? That
> > > seems drastic overkill because the bit handling is already racy and the
> > > refcnt is overkill.
> > 
> > I'm not sure I follow.
> > 
> 
> The lock is acquired before branching to zone_not_ready for the purpose
> of clearing a zone bit and updating the ref count. That is hinting at
> the possibility that zone lock is protecting much more than it should.

I'm using it to protect the bit and the page counts. Basically I cannot
rely on the page counts being valid if I am not holding the lock. So in
order to avoid races between the bit and the page counts I hold the lock
when I clear the bit.

> > > > +
> > > > +	sg_init_table(prdev->sg, prdev->capacity);
> > > > +
> > > > +	/* Process each free list starting from lowest order/mt */
> > > > +	for_each_reporting_migratetype_order(order, mt)
> > > > +		nents = page_reporting_cycle(prdev, zone, order, mt, nents);
> > > > +
> > > > +	/* mark end of sg list and report the remainder */
> > > > +	if (nents) {
> > > > +		sg_mark_end(&prdev->sg[nents - 1]);
> > > > +		prdev->report(prdev, nents);
> > > > +	}
> > > > +
> > > > +	spin_lock_irq(&zone->lock);
> > > > +
> > > > +	/* flush any remaining pages out from the last report */
> > > > +	if (nents)
> > > > +		page_reporting_drain(prdev, zone);
> > > > +
> > > > +	/* check to see if values are low enough for us to stop for now */
> > > > +	for (order = PAGE_REPORTING_MIN_ORDER; order < MAX_ORDER; order++) {
> > > > +		if (pages_unreported(zone, order) < PAGE_REPORTING_HWM)
> > > > +			continue;
> > > > +#ifdef CONFIG_MEMORY_ISOLATION
> > > > +		/*
> > > > +		 * Do not allow a free_area with isolated pages to request
> > > > +		 * that we continue with page reporting. Keep the reporting
> > > > +		 * light until the isolated pages have been cleared.
> > > > +		 */
> > > > +		if (!free_area_empty(&zone->free_area[order], MIGRATE_ISOLATE))
> > > > +			continue;
> > > > +#endif
> > > > +		goto zone_not_complete;
> > > > +	}
> > > > +
> > > > +zone_not_ready:
> > > > +	/*
> > > > +	 * If there are no longer enough free pages to fully populate
> > > > +	 * the scatterlist, then we can just shut it down for this zone.
> > > > +	 */
> > > > +	__clear_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags);
> > > > +	refcnt = atomic_dec_return(&prdev->refcnt);
> > > 
> > > If a request comes in while processing is already happening then the
> > > subsequent request is lost.
> > 
> > How can a request come in when we are holding the zone lock?
>  
> page_reporting_cycle drops the lock so there is no obvious guarantee
> that requests are not lost.

Yes, but page_reporting_cycle will not clear the bit. It is only cleared
in this last bleock where we go through and verify the page counts are low
enough that we can justify clearing the bit.

This is what I am talking about in terms of the page counts and the bit
being synchronized via the lock. Both the notifier and this piece of code
will not set nor clear the bit without first having to check
pages_unreported and then either setting or clearing the bit depending on
if we are the notifier or the reporting process.

> > Basically the
> > notify call can only occur while holding the zone lock. That is one of the
> > reasons for holding the lock is to protect the flag and keep it consistent
> > with the page counts as we clear it.
> > 
> 
> Ok, you really should not be relying on the zone lock for protecting
> state like this. It's fragile and it abuses what zone lock is for. It's
> fragile because zone flags is not intended to protected by the zone
> lock. Historically there would have been more flags but even currently,
> the flag is tested and set outside of the zone lock. As you are using
> non-atomic ops, it gets even more fragile because flag updates are
> potentially lost.
> 
> The zone lock is primarily to protect the free lists and the watermarks
> which are strongly related to the free lists and expanding that scope to
> protect an atomic and a zone flag is very questionable. At some point,
> zone lock is going to have to be broken up somehow because it's a very
> heavy lock on the allocator side. If zone lock is protecting multiple
> things like this, that would get even harder.

So I am not necessarily using it to protect the atomic refcount. The
placement of the atomic refcount as more to do with the setting and
clearing of the flag bit.

What I am using the lock for is mostly to keep the farea[x].nr_free
coherent versus the reported_pages counts.

> If necessary, add a separate lock and use it to protect state related to
> the page reporting but as part of that, you almost certainly will have
> to move to atomic versions of bit operations for zone flags because it's
> not protected as such.
> 
> Again, it really should be the case that ZONE_PAGE_REPORTING_REQUESTED
> is split out into a separate patch and introduced standalone. It would
> probably be on the justification of avoiding unnecessary zone free list
> searches but still, the optimisation should be reviewed separately and
> the locking of state should be clear.

I can look into it. However between this, the removal of the
reported_pages counters, and the desire to remove the reference count it
sounds like what we have is essentially just a blind scanner that will
never really know when it is done and would likely be very lossy.

> > The only case where we are not checking the counts is for the case above
> > where we clear it due to us being too close to the watermark. In that case
> > we want to just ignore the request anyway.
> > 
> > > > +zone_not_complete:
> > > > +	spin_unlock_irq(&zone->lock);
> > > > +
> > > > +	return refcnt;
> > > > +}
> > > > +
> > > > +static void page_reporting_process(struct work_struct *work)
> > > > +{
> > > > +	struct delayed_work *d_work = to_delayed_work(work);
> > > > +	struct page_reporting_dev_info *prdev =
> > > > +		container_of(d_work, struct page_reporting_dev_info, work);
> > > > +	struct zone *zone = first_online_pgdat()->node_zones;
> > > > +	int refcnt = -1;
> > > > +
> > > > +	do {
> > > > +		if (test_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags))
> > > > +			refcnt = page_reporting_process_zone(prdev, zone);
> > > > +
> > > > +		/* Move to next zone, if at end of list start over */
> > > > +		zone = next_zone(zone) ? : first_online_pgdat()->node_zones;
> > > > +
> > > > +		/*
> > > > +		 * As long as refcnt has not reached zero there are still
> > > > +		 * zones to be processed.
> > > > +		 */
> > > > +	} while (refcnt);
> > > > +}
> > > > +
> > > 
> > > This is being done from a workqueue context and potentially this runs
> > > forever if the refcnt remains elevated. It's dangerous and should be in
> > > it's own patch. In the basic implementation, just do a single pass of
> > > all zones.
> > 
> > So I already have a modification that I have for the next version of the
> > patch set where instead of doing a do/while I simply reschedule the
> > delayed work to run again in 200ms if we still have work outstanding.
> > 
> 
> That would be a bit more reasonable. It would probably remove the need
> for the refcount entirely but either way -- split out the optimisations.
> Otherwise the entirity of the feature has to be re-reviewed every time
> which is time consuming.

Okay.

> > What I can do is split that out so that it is in the second patch with
> > optimizations.
> > 
> 
> One patch per optimisation please with data backing it up because it should
> be possible to show that pages are reported faster or that overhead is
> much lower. It would give a hint on whether the complexity is justified,
> particularly if the locking is subtle.

Okay, got it.

> > > > +/* request page reporting on this zone */
> > > > +void __page_reporting_request(struct zone *zone)
> > > > +{
> > > > +	struct page_reporting_dev_info *prdev;
> > > > +
> > > > +	rcu_read_lock();
> > > > +
> > > > +	/*
> > > > +	 * We use RCU to protect the pr_dev_info pointer. In almost all
> > > > +	 * cases this should be present, however in the unlikely case of
> > > > +	 * a shutdown this will be NULL and we should exit.
> > > > +	 */
> > > > +	prdev = rcu_dereference(pr_dev_info);
> > > > +	if (unlikely(!prdev))
> > > > +		goto out;
> > > > +
> > > > +	/*
> > > > +	 * We can use separate test and set operations here as there
> > > > +	 * is nothing else that can set or clear this bit while we are
> > > > +	 * holding the zone lock. The advantage to doing it this way is
> > > > +	 * that we don't have to dirty the cacheline unless we are
> > > > +	 * changing the value.
> > > > +	 */
> > > > +	__set_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags);
> > > > +
> > > 
> > > The comment implies that the bit should have been tested first.
> > 
> > It was in the page_reporting_notify_free() call. I can update the comment.
> > 
> 
> But not the registration path (which probably doesn't matter). What is
> much more critical is that again you are relying on the zone lock for
> protection and correctness of a tiny micro-optimisation. Page reporting
> really must not rely on the zone lock for anything outside of the free
> list. We've already had a massive headache with mmap_sem protecting way
> too much unnecessarily, we don't need a new one with zone that might
> make it very difficult to break up that lock in the future.

So the main use of the zone lock is for the nr_free values,
reported_pages, and the REPORTING_REQUESTED flag. I had lumped them
together under the zone lock as they were already all being used together
anyway.

Adding another lock would likely just add more complexity since then we
have to worry about lock inversions and such. That was one motivation for
not taking that approach.

> > > > +	/*
> > > > +	 * Delay the start of work to allow a sizable queue to
> > > > +	 * build. For now we are limiting this to running no more
> > > > +	 * than 5 times per second.
> > > > +	 */
> > > > +	if (!atomic_fetch_inc(&prdev->refcnt))
> > > > +		schedule_delayed_work(&prdev->work, HZ / 5);
> > > 
> > > The refcnt is incremented whether this zone has already been requested or
> > > not but only decremented when the bit is cleared so the refcnt potentially
> > > remains elevated forever.
> > 
> > So this is one of the reasons why all accesses to the flag are protected
> > by the zone lock.  Basically page_reporting_notify_free() and this function
> > are both called with the zone lock held.
> > 
> 
> This is extremely subtle and again, it's really not what zone lock is
> for. It's too fragile but maybe refcnt is going away anyway. If not,
> make a separate lock and document what it's protecting in the patch
> introducing the optimisation.

Again the problem is I have 3 elements that I have to keep in sync. In the
case of the page_reporting_notify_free I wouldn't be able to drop the zone
lock without either adding additional complexity to the page freeing path.

> > The only other caller of this function is page_reporting_register which
> > calls it for each populated zone. I suppose I could make it for every zone
> > since it is possible that someone unloaded the driver, unpopulated a zone,
> > and then reloaded the driver, but anyway the idea is that the zone lock is
> > keeping the flag and refcount consistent.
> > 
> 
> I think you can guess at this point what I'll say about zone lock.

I get that you don't like the use of the zone lock but the problem is I am
not sure there is a good way for the reported_pages and flag to stay in
sync without it. I could do away with the flag if that is what we really
want but then I am still stuck using the zone lock as I have to either
walk the lists or read the nr_free from the free area to determine if a
zone has to be processed.

> > > > +#define PAGE_REPORTING_MIN_ORDER	pageblock_order
> > > 
> > > This is potentially the same as MAX_ORDER-1. Not sure if it matters or
> > > not.
> > 
> > It doesn't. Basically what I am going for is the largest order that it is
> > safe to report on that will not break THP. If THP is not enabled then this
> > value should be MAX_ORDER - 1 if I am not mistaken.
> > 
> 
> Well, it's more about huge pages but yes, if you're ok with the
> possibility that reporting only happens for the largest possible page
> then that's fine.
> 
> > > > +	/* Limit notifications only to higher order pages */
> > > > +	report_order = order - PAGE_REPORTING_MIN_ORDER;
> > > > +	if (report_order < 0)
> > > > +		return 0;
> > > > +
> > > > +	nr_free = zone->free_area[order].nr_free;
> > > > +
> > > > +	/* Only subtract reported_pages count if it is present */
> > > > +	if (!zone->reported_pages)
> > > > +		return nr_free;
> > > > +
> > > > +	return nr_free - zone->reported_pages[report_order];
> > > > +}
> > > 
> > > Initially, this should be a full list traversal because I'm not
> > > convinced the reported_pages count is kept perfectly in sync. The
> > > optimisation confuses the review of the basic feature itself.
> > 
> > This is called per freed page in page_reporting_notify_free below. Are you
> > saying I have to traverse the entire free list per freed page?
> > 
> 
> In a basic unoptimised version -- yes. Put optimisations in separate
> patches because then the basic feature itself can be reviewed and
> commented upon. It'll also make it easier to understand any special
> locking requirements for state.
> 
> > If that is what you are wanting I would still probably want to limit it
> > such that we only walk the first PAGE_REPORTING_HWM worth of pages and if
> > those are not reported then just report that many.
> > 
> 
> Which in itself could be an optimisation patch. Maybe it'll be enough that
> keeping track of the count is not worthwhile. Either way, the separate
> patch could have supporting data on how much it improves the speed of
> reporting pages so it can be compared to any other optimisation that
> may be proposed. Supporting data would also help make the case that any
> complexity introduced by the optimisation is worthwhile.

I'll see what I can do to break this apart. I'm just not a fan of redoing
the work multiple times so that I can have a non-optimized version versus
an optimized one.

I'll also go take a look over the work scheduler. It is possible that
maybe I can get away from some of the refcount stuff if the scheduling of
delayed work takes care of it for me.
Mel Gorman Nov. 28, 2019, 9:22 a.m. UTC | #5
On Wed, Nov 27, 2019 at 01:55:02PM -0800, Alexander Duyck wrote:
> > > > > +	/*
> > > > > +	 * Upper limit on the number of pages that the report function
> > > > > +	 * expects to be placed into the scatterlist to be processed.
> > > > > +	 */
> > > > > +	unsigned int capacity;
> > > > > +
> > > > 
> > > > Instead of requiring the driver to specify capacity, why did you not
> > > > simply make it PAGE_REPORTING_HWM and statically declare the array?
> > > 
> > > The problem is the device might not be able to support PAGE_REPORTING_HWM.
> > 
> > I don't see why given that a driver that cannot handle PAGE_REPORTING_HWM
> > could process subsets of the pages reported. It seems unnecessary.
> 
> I suppose it might be considered an optimization. Basically what I was
> wanting to avoid is pulling out more pages then the device can process in
> a single call. That is what the capacity represents. Basically the virtio
> device can have a limited ring size which limits how many pages we can
> have outstanding at a time. So I wanted to avoid pulling pages that I
> couldn't immediately report.
> 

Given that the first user of this is part of the same series, I think
it's reasonable to only consider its limitations and keep it relatively
simple. We don't know what additional users, if any, may exist. Even if
they do, notifiers will need to be chained and there will be additional
work necessary no matter what way we jump now.

> > > So I needed some way for it to communicate that. I could allocate the
> > > array statically if that is what you prefer.
> > > 
> > 
> > It would make sense if it's a fixed size and let drivers figure out whether
> > the full array can be processed at once or has to be split into parts.
> 
> In terms of allocation the fixed size makes sense to me. I still think it
> would be good to communicate how many the device can process in a single
> request so we don't have pages having to wait as the device has to segment
> the scatterlist to process pieces of it.
> 

If that limitation should arise in the future, it can be considered
then.

> > > > > +	/* The number of zones requesting reporting */
> > > > > +	atomic_t refcnt;
> > > > > +
> > > > 
> > > > The refcnt is overkill. Simply loop over all zones until there is a
> > > > clear pass. Despite being atomic, it actually requires the zone lock to
> > > > avoid races in places like this
> > > > 
> > > > 		if (test_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags))
> > > > 			refcnt = page_reporting_process_zone(prdev, zone);
> > > > 
> > > > The optimisation is small and it's relatively subtle.
> > > 
> > > I disagree. Without that we can easily get into states where a zone
> > > requests reporting and we never get around to servicing it.
> > 
> > Why would that happen if all zones were iterated during a single pass?
> 
> It is because I am not rescheduling the work while it is ongoing. My
> notifier is using the reference count to only schedule on the first
> request and not stop processing until we reach 0. Without that I have to
> schedule the worker ever time a zone requests processing.
> 

Which in itself is simpler than trying to maintain a coherent refcount
with separate locking. When it gets down to it, a reschedule is not that
bad and it's a lot less subtle.

> > > I am using the
> > > refcount to track that so that we don't shutdown the worker thread when
> > > there is at least one zone requesting service.
> > > 
> > 
> > Then either single pass or loop through all zones until a loop completes
> > with no zones to be processed. It's far simplier than a refcount.
> 
> I could do that if we only had one zone to process. However the problem is
> that we could be processing multiple zones.
> 

Again, not necessarily a problem. There is no data on how much of a
problem, if any, there is with delays in zone processing.

> > > Second, at the point where we call this function with the reported flag
> > > set we have not yet set the page as reported. There is logic that will
> > > check for that later and set the bits and increment the count if the page
> > > becomes a buddy page and the order is still the same as the order we
> > > originally freed it under.
> > > 
> > 
> > That is sufficiently complex that it really should be in its own patch
> > because right now, any bug there would either revert the whole feature
> > or do a partial revert if it couldn't be fixed properly. At least having
> > the option of reverting the optimisation would be useful for testing.
> > By not splitting it out, we're also prevented from being able to ack the
> > basic infrastructure itself. Even if the optimisations could not be agreed
> > upon, the feature would still exist -- just slower than is ideal.
> 
> The only optimization here is the use of the reported variable. That can
> actually go away since I hadn't realized I had changed things in the page
> reporting cycle so that we don't clear the REPORTING_REQUESTED flag until
> after the last drain has completed.
> 
> I'll work on splitting out the reported_pages bit into a separate patch,
> and I will see what I can do about refcount since that seems to be the
> other pain point.
> 

Thanks

> > > > > +static int
> > > > > +page_reporting_process_zone(struct page_reporting_dev_info *prdev,
> > > > > +			    struct zone *zone)
> > > > > +{
> > > > > +	unsigned int order, mt, nents = 0;
> > > > > +	unsigned long watermark;
> > > > > +	int refcnt = -1;
> > > > > +
> > > > > +	page_reporting_populate_metadata(zone);
> > > > > +
> > > > > +	/* Generate minimum watermark to be able to guarantee progress */
> > > > > +	watermark = low_wmark_pages(zone) +
> > > > > +		    (prdev->capacity << PAGE_REPORTING_MIN_ORDER);
> > > > > +
> > > > > +	/*
> > > > > +	 * Cancel request if insufficient free memory or if we failed
> > > > > +	 * to allocate page reporting statistics for the zone.
> > > > > +	 */
> > > > > +	if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA) ||
> > > > > +	    !zone->reported_pages) {
> > > > > +		spin_lock_irq(&zone->lock);
> > > > > +		goto zone_not_ready;
> > > > > +	}
> > > > 
> > > > The zone lock is acquired just for the zone bit and the refcnt? That
> > > > seems drastic overkill because the bit handling is already racy and the
> > > > refcnt is overkill.
> > > 
> > > I'm not sure I follow.
> > > 
> > 
> > The lock is acquired before branching to zone_not_ready for the purpose
> > of clearing a zone bit and updating the ref count. That is hinting at
> > the possibility that zone lock is protecting much more than it should.
> 
> I'm using it to protect the bit and the page counts. Basically I cannot
> rely on the page counts being valid if I am not holding the lock. So in
> order to avoid races between the bit and the page counts I hold the lock
> when I clear the bit.
> 

In the initial step, avoid the page counts and take the hit. I might be
willing to give ground on the zone lock protecting the reported counts
as it is tightly related to the free page count. The zone lock should
definitely not protect the zone flags or refcount because it would make
the zone lock difficult, if not impossible, to split in the future. For
example, the most obvious approach to splitting the zone lock would be
to split it by PFN range within the zone or hash it based on some low
bits in the PFN number. That would be relatively trivial to implement
but impossible if the lock is also protecting zone-wide state such as a
refcount or zone flag. Sure, someone dealing with the zone lock could
try to fix page reporting at the same time but it'll be harder for them
to test and puts an unfortunate obstacle in their way.

> > > > If a request comes in while processing is already happening then the
> > > > subsequent request is lost.
> > > 
> > > How can a request come in when we are holding the zone lock?
> >  
> > page_reporting_cycle drops the lock so there is no obvious guarantee
> > that requests are not lost.
> 
> Yes, but page_reporting_cycle will not clear the bit. It is only cleared
> in this last bleock where we go through and verify the page counts are low
> enough that we can justify clearing the bit.
> 

Ok, that makes some sense although it could do with comments on the
lifecycle of the bit.

> This is what I am talking about in terms of the page counts and the bit
> being synchronized via the lock. Both the notifier and this piece of code
> will not set nor clear the bit without first having to check
> pages_unreported and then either setting or clearing the bit depending on
> if we are the notifier or the reporting process.
> 

But using the zone lock to protect that bit is a hard no because that zone
lock is way too heavy as it is, particularly as zone sizes are growing
ever larger and we now have machine where multiple L3 caches share the
same zone lock which is very expensive to bounce around.

Someone else reviewing might override me on this one as being an
obstacle based on patches that don't exist but I think they would find
it very hard to argue that the zone lock is fine as it is.

> > If necessary, add a separate lock and use it to protect state related to
> > the page reporting but as part of that, you almost certainly will have
> > to move to atomic versions of bit operations for zone flags because it's
> > not protected as such.
> > 
> > Again, it really should be the case that ZONE_PAGE_REPORTING_REQUESTED
> > is split out into a separate patch and introduced standalone. It would
> > probably be on the justification of avoiding unnecessary zone free list
> > searches but still, the optimisation should be reviewed separately and
> > the locking of state should be clear.
> 
> I can look into it. However between this, the removal of the
> reported_pages counters, and the desire to remove the reference count it
> sounds like what we have is essentially just a blind scanner that will
> never really know when it is done and would likely be very lossy.
> 

Well yes, initially that's exactly what it would be. Free page reporting
is not a critical path and the initial implementation should be simple.
That allows it to be determined how much complexity and maintenance
burden is needed to make it a bit faster. Prematurely expanding the
scope of the zone lock is such a maintenance burden.

> > But not the registration path (which probably doesn't matter). What is
> > much more critical is that again you are relying on the zone lock for
> > protection and correctness of a tiny micro-optimisation. Page reporting
> > really must not rely on the zone lock for anything outside of the free
> > list. We've already had a massive headache with mmap_sem protecting way
> > too much unnecessarily, we don't need a new one with zone that might
> > make it very difficult to break up that lock in the future.
> 
> So the main use of the zone lock is for the nr_free values,
> reported_pages, and the REPORTING_REQUESTED flag. I had lumped them
> together under the zone lock as they were already all being used together
> anyway.
> 

reported_pages may not be too bad because it's tightly related to the
free page count and would be updated at the same time that list operations
take place but not other zone-wide state.

> Adding another lock would likely just add more complexity since then we
> have to worry about lock inversions and such. That was one motivation for
> not taking that approach.
> 

Which is a fair reason but it gets hung up on the fact that it makes
splitting the zone lock and free list handling much harder.

> > > > > +	/*
> > > > > +	 * Delay the start of work to allow a sizable queue to
> > > > > +	 * build. For now we are limiting this to running no more
> > > > > +	 * than 5 times per second.
> > > > > +	 */
> > > > > +	if (!atomic_fetch_inc(&prdev->refcnt))
> > > > > +		schedule_delayed_work(&prdev->work, HZ / 5);
> > > > 
> > > > The refcnt is incremented whether this zone has already been requested or
> > > > not but only decremented when the bit is cleared so the refcnt potentially
> > > > remains elevated forever.
> > > 
> > > So this is one of the reasons why all accesses to the flag are protected
> > > by the zone lock.  Basically page_reporting_notify_free() and this function
> > > are both called with the zone lock held.
> > > 
> > 
> > This is extremely subtle and again, it's really not what zone lock is
> > for. It's too fragile but maybe refcnt is going away anyway. If not,
> > make a separate lock and document what it's protecting in the patch
> > introducing the optimisation.
> 
> Again the problem is I have 3 elements that I have to keep in sync. In the
> case of the page_reporting_notify_free I wouldn't be able to drop the zone
> lock without either adding additional complexity to the page freeing path.
> 

It leaks an unnecessary amount of maintenance burden into page_alloc,
which is performance critical, to optimise page reporting which is not
performance critical. Minimally, if zone lock is protecting an entire page
reporting cycle, it's blocking other allocations taking place at the same
time as reporting for an unnecessary length of time and incurring stalls.

> > > The only other caller of this function is page_reporting_register which
> > > calls it for each populated zone. I suppose I could make it for every zone
> > > since it is possible that someone unloaded the driver, unpopulated a zone,
> > > and then reloaded the driver, but anyway the idea is that the zone lock is
> > > keeping the flag and refcount consistent.
> > > 
> > 
> > I think you can guess at this point what I'll say about zone lock.
> 
> I get that you don't like the use of the zone lock but the problem is I am
> not sure there is a good way for the reported_pages and flag to stay in
> sync without it. I could do away with the flag if that is what we really
> want but then I am still stuck using the zone lock as I have to either
> walk the lists or read the nr_free from the free area to determine if a
> zone has to be processed.
> 

I'm not saying the flag needs to go away entirely, just that it should
not share the same lock as the page allocators free list unnecessarily.
Free page reporting can afford to stall or even go to sleep if protected
by a mutex when it's not manipulating free lists even if that means some
duplicate processing may be necessary.

> > 
> > Which in itself could be an optimisation patch. Maybe it'll be enough that
> > keeping track of the count is not worthwhile. Either way, the separate
> > patch could have supporting data on how much it improves the speed of
> > reporting pages so it can be compared to any other optimisation that
> > may be proposed. Supporting data would also help make the case that any
> > complexity introduced by the optimisation is worthwhile.
> 
> I'll see what I can do to break this apart. I'm just not a fan of redoing
> the work multiple times so that I can have a non-optimized version versus
> an optimized one.
> 

While I understand that, right now the optimisations are blocking the
feature itself which is also not a situation you want to be in.
Alexander H Duyck Nov. 29, 2019, 7:25 p.m. UTC | #6
On Thu, Nov 28, 2019 at 1:22 AM Mel Gorman <mgorman@techsingularity.net> wrote:
>
> On Wed, Nov 27, 2019 at 01:55:02PM -0800, Alexander Duyck wrote:

< snip >

> > >
> > > Which in itself could be an optimisation patch. Maybe it'll be enough that
> > > keeping track of the count is not worthwhile. Either way, the separate
> > > patch could have supporting data on how much it improves the speed of
> > > reporting pages so it can be compared to any other optimisation that
> > > may be proposed. Supporting data would also help make the case that any
> > > complexity introduced by the optimisation is worthwhile.
> >
> > I'll see what I can do to break this apart. I'm just not a fan of redoing
> > the work multiple times so that I can have a non-optimized version versus
> > an optimized one.
> >
>
> While I understand that, right now the optimisations are blocking the
> feature itself which is also not a situation you want to be in.

I'll see what I can do. I can probably replace the reference count and
zone flags with an atomic state in the prdev that cycles between
inactive, requested, and active. With that I can at least guarantee
that we shouldn't have any races that result in us missing freed
pages. The only downside is that I have to keep a boolean in the
__free_one_page call so that when we free back the reported pages we
don't retrigger the reporting and cause an infinite loop.
diff mbox series

Patch

diff --git a/include/linux/mmzone.h b/include/linux/mmzone.h
index 8d93106490f3..9647499983b1 100644
--- a/include/linux/mmzone.h
+++ b/include/linux/mmzone.h
@@ -478,6 +478,14 @@  struct zone {
 	seqlock_t		span_seqlock;
 #endif
 
+#ifdef CONFIG_PAGE_REPORTING
+	/*
+	 * Pointer to reported page tracking statistics array. The size of
+	 * the array is MAX_ORDER - PAGE_REPORTING_MIN_ORDER. NULL when
+	 * unused page reporting is not present.
+	 */
+	unsigned long		*reported_pages;
+#endif
 	int initialized;
 
 	/* Write-intensive fields used from the page allocator */
@@ -550,6 +558,10 @@  enum zone_flags {
 	ZONE_BOOSTED_WATERMARK,		/* zone recently boosted watermarks.
 					 * Cleared when kswapd is woken.
 					 */
+	ZONE_PAGE_REPORTING_REQUESTED,	/* zone enabled page reporting and has
+					 * requested flushing the data out of
+					 * higher order pages.
+					 */
 };
 
 static inline unsigned long zone_managed_pages(struct zone *zone)
diff --git a/include/linux/page-flags.h b/include/linux/page-flags.h
index 1bf83c8fcaa7..a3a3b15b56a8 100644
--- a/include/linux/page-flags.h
+++ b/include/linux/page-flags.h
@@ -163,6 +163,9 @@  enum pageflags {
 
 	/* non-lru isolated movable page */
 	PG_isolated = PG_reclaim,
+
+	/* Buddy pages. Used to track which pages have been reported */
+	PG_reported = PG_uptodate,
 };
 
 #ifndef __GENERATING_BOUNDS_H
@@ -432,6 +435,14 @@  static inline bool set_hwpoison_free_buddy_page(struct page *page)
 #endif
 
 /*
+ * PageReported() is used to track reported free pages within the Buddy
+ * allocator. We can use the non-atomic version of the test and set
+ * operations as both should be shielded with the zone lock to prevent
+ * any possible races on the setting or clearing of the bit.
+ */
+__PAGEFLAG(Reported, reported, PF_NO_COMPOUND)
+
+/*
  * On an anonymous page mapped into a user virtual memory area,
  * page->mapping points to its anon_vma, not to a struct address_space;
  * with the PAGE_MAPPING_ANON bit set to distinguish it.  See rmap.h.
diff --git a/include/linux/page_reporting.h b/include/linux/page_reporting.h
new file mode 100644
index 000000000000..925a16b1d14b
--- /dev/null
+++ b/include/linux/page_reporting.h
@@ -0,0 +1,31 @@ 
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _LINUX_PAGE_REPORTING_H
+#define _LINUX_PAGE_REPORTING_H
+
+#include <linux/mmzone.h>
+
+struct page_reporting_dev_info {
+	/* function that alters pages to make them "reported" */
+	void (*report)(struct page_reporting_dev_info *prdev,
+		       unsigned int nents);
+
+	/* pointer to scatterlist containing pages to be processed */
+	struct scatterlist *sg;
+
+	/*
+	 * Upper limit on the number of pages that the report function
+	 * expects to be placed into the scatterlist to be processed.
+	 */
+	unsigned int capacity;
+
+	/* The number of zones requesting reporting */
+	atomic_t refcnt;
+
+	/* work struct for processing reports */
+	struct delayed_work work;
+};
+
+/* Tear-down and bring-up for page reporting devices */
+void page_reporting_unregister(struct page_reporting_dev_info *prdev);
+int page_reporting_register(struct page_reporting_dev_info *prdev);
+#endif /*_LINUX_PAGE_REPORTING_H */
diff --git a/mm/Kconfig b/mm/Kconfig
index e38ff1d5968d..bd68901bbfe2 100644
--- a/mm/Kconfig
+++ b/mm/Kconfig
@@ -237,6 +237,17 @@  config COMPACTION
           linux-mm@kvack.org.
 
 #
+# support for unused page reporting
+config PAGE_REPORTING
+	bool "Allow for reporting of unused pages"
+	def_bool n
+	help
+	  Unused page reporting allows for the incremental acquisition of
+	  unused pages from the buddy allocator for the purpose of reporting
+	  those pages to another entity, such as a hypervisor, so that the
+	  memory can be freed up for other uses.
+
+#
 # support for page migration
 #
 config MIGRATION
diff --git a/mm/Makefile b/mm/Makefile
index fa02f19f8e50..41e6aa432781 100644
--- a/mm/Makefile
+++ b/mm/Makefile
@@ -108,3 +108,4 @@  obj-$(CONFIG_PERCPU_STATS) += percpu-stats.o
 obj-$(CONFIG_ZONE_DEVICE) += memremap.o
 obj-$(CONFIG_HMM_MIRROR) += hmm.o
 obj-$(CONFIG_MEMFD_CREATE) += memfd.o
+obj-$(CONFIG_PAGE_REPORTING) += page_reporting.o
diff --git a/mm/memory_hotplug.c b/mm/memory_hotplug.c
index 46b2e056a43f..bf19d94cb206 100644
--- a/mm/memory_hotplug.c
+++ b/mm/memory_hotplug.c
@@ -41,6 +41,7 @@ 
 
 #include "internal.h"
 #include "shuffle.h"
+#include "page_reporting.h"
 
 /*
  * online_page_callback contains pointer to current page onlining function.
@@ -1566,6 +1567,7 @@  static int __ref __offline_pages(unsigned long start_pfn,
 	if (!populated_zone(zone)) {
 		zone_pcp_reset(zone);
 		build_all_zonelists(NULL);
+		page_reporting_reset_zone(zone);
 	} else
 		zone_pcp_update(zone);
 
diff --git a/mm/page_alloc.c b/mm/page_alloc.c
index e0a7895300fb..5ef8f5abdd4d 100644
--- a/mm/page_alloc.c
+++ b/mm/page_alloc.c
@@ -74,6 +74,7 @@ 
 #include <asm/div64.h>
 #include "internal.h"
 #include "shuffle.h"
+#include "page_reporting.h"
 
 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
 static DEFINE_MUTEX(pcp_batch_high_lock);
@@ -909,6 +910,10 @@  static inline void move_to_free_list(struct page *page, struct zone *zone,
 static inline void del_page_from_free_list(struct page *page, struct zone *zone,
 					   unsigned int order)
 {
+	/* clear reported state and update reported page count */
+	if (page_reported(page))
+		clear_page_reported(page, zone, order);
+
 	list_del(&page->lru);
 	__ClearPageBuddy(page);
 	set_page_private(page, 0);
@@ -972,7 +977,7 @@  static inline void del_page_from_free_list(struct page *page, struct zone *zone,
 static inline void __free_one_page(struct page *page,
 		unsigned long pfn,
 		struct zone *zone, unsigned int order,
-		int migratetype)
+		int migratetype, bool reported)
 {
 	struct capture_control *capc = task_capc(zone);
 	unsigned long uninitialized_var(buddy_pfn);
@@ -1048,7 +1053,9 @@  static inline void __free_one_page(struct page *page,
 done_merging:
 	set_page_order(page, order);
 
-	if (is_shuffle_order(order))
+	if (reported)
+		to_tail = true;
+	else if (is_shuffle_order(order))
 		to_tail = shuffle_pick_tail();
 	else
 		to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order);
@@ -1057,6 +1064,14 @@  static inline void __free_one_page(struct page *page,
 		add_to_free_list_tail(page, zone, order, migratetype);
 	else
 		add_to_free_list(page, zone, order, migratetype);
+
+	/*
+	 * No need to notify on a reported page as the total count of
+	 * unreported pages will not have increased since we have essentially
+	 * merged the reported page with one or more unreported pages.
+	 */
+	if (!reported)
+		page_reporting_notify_free(zone, order);
 }
 
 /*
@@ -1373,7 +1388,7 @@  static void free_pcppages_bulk(struct zone *zone, int count,
 		if (unlikely(isolated_pageblocks))
 			mt = get_pageblock_migratetype(page);
 
-		__free_one_page(page, page_to_pfn(page), zone, 0, mt);
+		__free_one_page(page, page_to_pfn(page), zone, 0, mt, false);
 		trace_mm_page_pcpu_drain(page, 0, mt);
 	}
 	spin_unlock(&zone->lock);
@@ -1389,7 +1404,7 @@  static void free_one_page(struct zone *zone,
 		is_migrate_isolate(migratetype))) {
 		migratetype = get_pfnblock_migratetype(page, pfn);
 	}
-	__free_one_page(page, pfn, zone, order, migratetype);
+	__free_one_page(page, pfn, zone, order, migratetype, false);
 	spin_unlock(&zone->lock);
 }
 
@@ -3228,6 +3243,36 @@  int __isolate_free_page(struct page *page, unsigned int order)
 	return 1UL << order;
 }
 
+#ifdef CONFIG_PAGE_REPORTING
+/**
+ * __free_isolated_page - Return a now-isolated page back where we got it
+ * @page: Page that was isolated
+ * @order: Order of the isolated page
+ *
+ * This function is meant to return a page pulled from the free lists via
+ * __isolate_free_page back to the free lists they were pulled from.
+ */
+void __free_isolated_page(struct page *page, unsigned int order)
+{
+	struct zone *zone = page_zone(page);
+	unsigned long pfn;
+	unsigned int mt;
+
+	/* zone lock should be held when this function is called */
+	lockdep_assert_held(&zone->lock);
+
+	pfn = page_to_pfn(page);
+	mt = get_pfnblock_migratetype(page, pfn);
+
+	/*
+	 * Return isolated page to tail of freelist and don't bother with
+	 * triggering the page reporting notifiers since this page was
+	 * previously on the freelist and has likely already been reported.
+	 */
+	__free_one_page(page, pfn, zone, order, mt, true);
+}
+#endif /* CONFIG_PAGE_REPORTING */
+
 /*
  * Update NUMA hit/miss statistics
  *
diff --git a/mm/page_reporting.c b/mm/page_reporting.c
new file mode 100644
index 000000000000..4844f0aa2904
--- /dev/null
+++ b/mm/page_reporting.c
@@ -0,0 +1,337 @@ 
+// SPDX-License-Identifier: GPL-2.0
+#include <linux/mm.h>
+#include <linux/mmzone.h>
+#include <linux/page_reporting.h>
+#include <linux/gfp.h>
+#include <linux/export.h>
+#include <linux/delay.h>
+#include <linux/scatterlist.h>
+
+#include "page_reporting.h"
+#include "internal.h"
+
+static struct page_reporting_dev_info __rcu *pr_dev_info __read_mostly;
+
+#define for_each_reporting_migratetype_order(_order, _type) \
+	for (_order = PAGE_REPORTING_MIN_ORDER; _order < MAX_ORDER; _order++) \
+		for (_type = 0; _type < MIGRATE_TYPES; _type++) \
+			if (!is_migrate_isolate(_type))
+
+static void page_reporting_populate_metadata(struct zone *zone)
+{
+	size_t size;
+	int node;
+
+	/*
+	 * We need to make sure we have somewhere to store the tracking
+	 * data for how many reported pages are in the zone. To do that
+	 * we need to make certain zone->reported_pages is populated.
+	 */
+	if (zone->reported_pages)
+		return;
+
+	node = zone_to_nid(zone);
+	size = (MAX_ORDER - PAGE_REPORTING_MIN_ORDER) * sizeof(unsigned long);
+	zone->reported_pages = kzalloc_node(size, GFP_KERNEL, node);
+}
+
+static void
+page_reporting_drain(struct page_reporting_dev_info *prdev, struct zone *zone)
+{
+	struct scatterlist *sg = prdev->sg;
+
+	/*
+	 * Drain the now reported pages back into their respective
+	 * free lists/areas. We assume at least one page is populated.
+	 */
+	do {
+		unsigned int order = get_order(sg->length);
+		struct page *page = sg_page(sg);
+
+		__free_isolated_page(page, order);
+
+		/*
+		 * If page was not comingled with another page we can
+		 * consider the result to be "reported" since the page
+		 * hasn't been modified, otherwise we will need to
+		 * report on the new larger page when we make our way
+		 * up to that higher order.
+		 */
+		if (PageBuddy(page) && page_order(page) == order)
+			mark_page_reported(page, zone, order);
+	} while (!sg_is_last(sg++));
+}
+
+/*
+ * The page reporting cycle consists of 4 stages, fill, report, drain, and
+ * idle. We will cycle through the first 3 stages until we cannot obtain a
+ * full scatterlist of pages, in that case we will switch to idle.
+ */
+static unsigned int
+page_reporting_cycle(struct page_reporting_dev_info *prdev, struct zone *zone,
+		     unsigned int order, unsigned int mt, unsigned int nents)
+{
+	struct list_head *list = &zone->free_area[order].free_list[mt];
+	unsigned int page_len = PAGE_SIZE << order;
+	struct scatterlist *sg = prdev->sg;
+	struct page *page, *next;
+
+	/*
+	 * Perform early check, if free area is empty there is
+	 * nothing to process so we can skip this free_list.
+	 */
+	if (list_empty(list))
+		return nents;
+
+	spin_lock_irq(&zone->lock);
+
+	/* loop through free list adding unreported pages to sg list */
+	list_for_each_entry_safe(page, next, list, lru) {
+		/* We are going to skip over the reported pages. */
+		if (PageReported(page))
+			continue;
+
+		/* Attempt to add page to sg list */
+		if (nents < prdev->capacity) {
+			if (!__isolate_free_page(page, order))
+				break;
+
+			sg_set_page(&sg[nents++], page, page_len, 0);
+			continue;
+		}
+
+		/*
+		 * Make the first non-reported entry in the free list
+		 * the new head of the free list before we exit.
+		 */
+		if (!list_is_first(&page->lru, list))
+			list_rotate_to_front(&page->lru, list);
+
+		/* release lock before waiting on report processing*/
+		spin_unlock_irq(&zone->lock);
+
+		/* begin processing pages in local list */
+		prdev->report(prdev, nents);
+
+		/* reset number of entries */
+		nents = 0;
+
+		/* reacquire zone lock and resume processing free lists */
+		spin_lock_irq(&zone->lock);
+
+		/* flush reported pages from the sg list */
+		page_reporting_drain(prdev, zone);
+
+		/*
+		 * Reset next to first entry, the old next isn't valid
+		 * since we dropped the lock to report the pages
+		 */
+		next = list_first_entry(list, struct page, lru);
+	}
+
+	spin_unlock_irq(&zone->lock);
+
+	return nents;
+}
+
+static int
+page_reporting_process_zone(struct page_reporting_dev_info *prdev,
+			    struct zone *zone)
+{
+	unsigned int order, mt, nents = 0;
+	unsigned long watermark;
+	int refcnt = -1;
+
+	page_reporting_populate_metadata(zone);
+
+	/* Generate minimum watermark to be able to guarantee progress */
+	watermark = low_wmark_pages(zone) +
+		    (prdev->capacity << PAGE_REPORTING_MIN_ORDER);
+
+	/*
+	 * Cancel request if insufficient free memory or if we failed
+	 * to allocate page reporting statistics for the zone.
+	 */
+	if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA) ||
+	    !zone->reported_pages) {
+		spin_lock_irq(&zone->lock);
+		goto zone_not_ready;
+	}
+
+	sg_init_table(prdev->sg, prdev->capacity);
+
+	/* Process each free list starting from lowest order/mt */
+	for_each_reporting_migratetype_order(order, mt)
+		nents = page_reporting_cycle(prdev, zone, order, mt, nents);
+
+	/* mark end of sg list and report the remainder */
+	if (nents) {
+		sg_mark_end(&prdev->sg[nents - 1]);
+		prdev->report(prdev, nents);
+	}
+
+	spin_lock_irq(&zone->lock);
+
+	/* flush any remaining pages out from the last report */
+	if (nents)
+		page_reporting_drain(prdev, zone);
+
+	/* check to see if values are low enough for us to stop for now */
+	for (order = PAGE_REPORTING_MIN_ORDER; order < MAX_ORDER; order++) {
+		if (pages_unreported(zone, order) < PAGE_REPORTING_HWM)
+			continue;
+#ifdef CONFIG_MEMORY_ISOLATION
+		/*
+		 * Do not allow a free_area with isolated pages to request
+		 * that we continue with page reporting. Keep the reporting
+		 * light until the isolated pages have been cleared.
+		 */
+		if (!free_area_empty(&zone->free_area[order], MIGRATE_ISOLATE))
+			continue;
+#endif
+		goto zone_not_complete;
+	}
+
+zone_not_ready:
+	/*
+	 * If there are no longer enough free pages to fully populate
+	 * the scatterlist, then we can just shut it down for this zone.
+	 */
+	__clear_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags);
+	refcnt = atomic_dec_return(&prdev->refcnt);
+zone_not_complete:
+	spin_unlock_irq(&zone->lock);
+
+	return refcnt;
+}
+
+static void page_reporting_process(struct work_struct *work)
+{
+	struct delayed_work *d_work = to_delayed_work(work);
+	struct page_reporting_dev_info *prdev =
+		container_of(d_work, struct page_reporting_dev_info, work);
+	struct zone *zone = first_online_pgdat()->node_zones;
+	int refcnt = -1;
+
+	do {
+		if (test_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags))
+			refcnt = page_reporting_process_zone(prdev, zone);
+
+		/* Move to next zone, if at end of list start over */
+		zone = next_zone(zone) ? : first_online_pgdat()->node_zones;
+
+		/*
+		 * As long as refcnt has not reached zero there are still
+		 * zones to be processed.
+		 */
+	} while (refcnt);
+}
+
+/* request page reporting on this zone */
+void __page_reporting_request(struct zone *zone)
+{
+	struct page_reporting_dev_info *prdev;
+
+	rcu_read_lock();
+
+	/*
+	 * We use RCU to protect the pr_dev_info pointer. In almost all
+	 * cases this should be present, however in the unlikely case of
+	 * a shutdown this will be NULL and we should exit.
+	 */
+	prdev = rcu_dereference(pr_dev_info);
+	if (unlikely(!prdev))
+		goto out;
+
+	/*
+	 * We can use separate test and set operations here as there
+	 * is nothing else that can set or clear this bit while we are
+	 * holding the zone lock. The advantage to doing it this way is
+	 * that we don't have to dirty the cacheline unless we are
+	 * changing the value.
+	 */
+	__set_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags);
+
+	/*
+	 * Delay the start of work to allow a sizable queue to
+	 * build. For now we are limiting this to running no more
+	 * than 5 times per second.
+	 */
+	if (!atomic_fetch_inc(&prdev->refcnt))
+		schedule_delayed_work(&prdev->work, HZ / 5);
+out:
+	rcu_read_unlock();
+}
+
+static DEFINE_MUTEX(page_reporting_mutex);
+DEFINE_STATIC_KEY_FALSE(page_reporting_enabled);
+
+void page_reporting_unregister(struct page_reporting_dev_info *prdev)
+{
+	mutex_lock(&page_reporting_mutex);
+
+	if (rcu_access_pointer(pr_dev_info) == prdev) {
+		/* Disable page reporting notification */
+		RCU_INIT_POINTER(pr_dev_info, NULL);
+		synchronize_rcu();
+
+		/* Flush any existing work, and lock it out */
+		cancel_delayed_work_sync(&prdev->work);
+
+		/* Free scatterlist */
+		kfree(prdev->sg);
+		prdev->sg = NULL;
+	}
+
+	mutex_unlock(&page_reporting_mutex);
+}
+EXPORT_SYMBOL_GPL(page_reporting_unregister);
+
+int page_reporting_register(struct page_reporting_dev_info *prdev)
+{
+	struct zone *zone;
+	int err = 0;
+
+	/* No point in enabling this if it cannot handle any pages */
+	if (WARN_ON(!prdev->capacity || prdev->capacity > PAGE_REPORTING_HWM))
+		return -EINVAL;
+
+	mutex_lock(&page_reporting_mutex);
+
+	/* nothing to do if already in use */
+	if (rcu_access_pointer(pr_dev_info)) {
+		err = -EBUSY;
+		goto err_out;
+	}
+
+	/* allocate scatterlist to store pages being reported on */
+	prdev->sg = kcalloc(prdev->capacity, sizeof(*prdev->sg), GFP_KERNEL);
+	if (!prdev->sg) {
+		err = -ENOMEM;
+		goto err_out;
+	}
+
+
+	/* initialize refcnt and work structures */
+	atomic_set(&prdev->refcnt, 0);
+	INIT_DELAYED_WORK(&prdev->work, &page_reporting_process);
+
+	/* assign device, and begin initial flush of populated zones */
+	rcu_assign_pointer(pr_dev_info, prdev);
+	for_each_populated_zone(zone) {
+		spin_lock_irq(&zone->lock);
+		__page_reporting_request(zone);
+		spin_unlock_irq(&zone->lock);
+	}
+
+	/* enable page reporting notification */
+	if (!static_key_enabled(&page_reporting_enabled)) {
+		static_branch_enable(&page_reporting_enabled);
+		pr_info("Unused page reporting enabled\n");
+	}
+err_out:
+	mutex_unlock(&page_reporting_mutex);
+
+	return err;
+}
+EXPORT_SYMBOL_GPL(page_reporting_register);
diff --git a/mm/page_reporting.h b/mm/page_reporting.h
new file mode 100644
index 000000000000..2ad31bbb0036
--- /dev/null
+++ b/mm/page_reporting.h
@@ -0,0 +1,125 @@ 
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _MM_PAGE_REPORTING_H
+#define _MM_PAGE_REPORTING_H
+
+#include <linux/mmzone.h>
+#include <linux/pageblock-flags.h>
+#include <linux/page-isolation.h>
+#include <linux/jump_label.h>
+#include <linux/slab.h>
+#include <asm/pgtable.h>
+
+#define PAGE_REPORTING_MIN_ORDER	pageblock_order
+#define PAGE_REPORTING_HWM		32
+
+#ifdef CONFIG_PAGE_REPORTING
+/* Reported page accessors, defined in page_alloc.c */
+void __free_isolated_page(struct page *page, unsigned int order);
+
+/* Free reported_pages and reset reported page tracking count to 0 */
+static inline void page_reporting_reset_zone(struct zone *zone)
+{
+	kfree(zone->reported_pages);
+	zone->reported_pages = NULL;
+}
+
+DECLARE_STATIC_KEY_FALSE(page_reporting_enabled);
+void __page_reporting_request(struct zone *zone);
+
+static inline bool page_reported(struct page *page)
+{
+	return static_branch_unlikely(&page_reporting_enabled) &&
+	       PageReported(page);
+}
+
+static inline unsigned long
+pages_unreported(struct zone *zone, int order)
+{
+	unsigned long nr_free;
+	int report_order;
+
+	/* Limit notifications only to higher order pages */
+	report_order = order - PAGE_REPORTING_MIN_ORDER;
+	if (report_order < 0)
+		return 0;
+
+	nr_free = zone->free_area[order].nr_free;
+
+	/* Only subtract reported_pages count if it is present */
+	if (!zone->reported_pages)
+		return nr_free;
+
+	return nr_free - zone->reported_pages[report_order];
+}
+
+/**
+ * page_reporting_notify_free - Free page notification to start page processing
+ * @zone: Pointer to current zone of last page processed
+ * @order: Order of last page added to zone
+ *
+ * This function is meant to act as a screener for __page_reporting_request
+ * which will determine if a give zone has crossed over the high-water mark
+ * that will justify us beginning page treatment. If we have crossed that
+ * threshold then it will start the process of pulling some pages and
+ * placing them in the batch list for treatment.
+ */
+static inline void page_reporting_notify_free(struct zone *zone, int order)
+{
+	/* Called from hot path in __free_one_page() */
+	if (!static_branch_unlikely(&page_reporting_enabled))
+		return;
+
+	/* Do not bother with tests if we have already requested reporting */
+	if (test_bit(ZONE_PAGE_REPORTING_REQUESTED, &zone->flags))
+		return;
+
+	/* Determine if we have crossed reporting threshold */
+	if (pages_unreported(zone, order) < PAGE_REPORTING_HWM)
+		return;
+
+	/* This is slow, but should be called very rarely */
+	__page_reporting_request(zone);
+}
+
+/*
+ * Functions for marking/clearing reported pages from the freelist.
+ * All of them expect the zone lock to be held to maintain
+ * consistency of the reported_pages count versus nr_free.
+ */
+static inline void
+mark_page_reported(struct page *page, struct zone *zone, unsigned int order)
+{
+	/* flag page as reported */
+	__SetPageReported(page);
+
+	/* update areated page accounting */
+	zone->reported_pages[order - PAGE_REPORTING_MIN_ORDER]++;
+}
+
+static inline void
+clear_page_reported(struct page *page, struct zone *zone, unsigned int order)
+{
+	/* page_private will contain the page order, so just use it directly */
+	zone->reported_pages[order - PAGE_REPORTING_MIN_ORDER]--;
+
+	/* clear the flag so we can report on it when it returns */
+	__ClearPageReported(page);
+}
+
+#else /* CONFIG_PAGE_REPORTING */
+#define page_reported(_page)	false
+
+static inline void page_reporting_reset_zone(struct zone *zone)
+{
+}
+
+static inline void page_reporting_notify_free(struct zone *zone, int order)
+{
+}
+
+static inline void
+clear_page_reported(struct page *page, struct zone *zone, unsigned int order)
+{
+}
+#endif /* CONFIG_PAGE_REPORTING */
+#endif /*_MM_PAGE_REPORTING_H */