Skip to contentSkip to conversation

mm / virtio: Provide support for unused page reporting

PATCH Superseded Alexander Duyck 4 participants 16 messages Aug 21, 2019 – Aug 23, 2019

Subsystems (8)

v6 of 17 Superseded Latest is v17 →

lore
Share & tools
lore
#0 lore raw

v6 cover mm / virtio: Provide support for unused page reporting

This series provides an asynchronous means of reporting to a hypervisor that a guest page is no longer in use and can have the data associated with it dropped. To do this I have implemented functionality that allows for what I am referring to as unused page reporting

The functionality for this is fairly simple. When enabled it will allocate statistics to track the number of reported pages in a given free area. When the number of free pages exceeds this value plus a high water value, currently 32, it will begin performing page reporting which consists of pulling pages off of free list and placing them into a scatter list. The scatterlist is then given to the page reporting device and it will perform the required action to make the pages "reported", in the case of virtio-balloon this results in the pages being madvised as MADV_DONTNEED and as such they are forced out of the guest. After this they are placed back on the free list, and an additional bit is added if they are not merged indicating that they are a reported buddy page instead of a standard buddy page. The cycle then repeats with additional non-reported pages being pulled until the free areas all consist of reported pages.

I am leaving a number of things hard-coded such as limiting the lowest order processed to PAGEBLOCK_ORDER, and have left it up to the guest to determine what the limit is on how many pages it wants to allocate to process the hints. The upper limit for this is based on the size of the queue used to store the scattergather list.

My primary testing has just been to verify the memory is being freed after allocation by running memhog 40g on a 40g guest and watching the total free memory via /proc/meminfo on the host. With this I have verified most of the memory is freed after each iteration. As far as performance I have been mainly focusing on the will-it-scale/page_fault1 test running with 16 vcpus. I have modified it to use Transparent Huge Pages. With this I see almost no difference, -0.08%, with the patches applied and the feature disabled. I see a regression of -0.86% with the feature enabled, but the madvise disabled in the hypervisor due to a device being assigned. With the feature fully enabled I see a regression of -3.27% versus the baseline without these patches applied. In my testing I found that most of the overhead was due to the page zeroing that comes as a result of the pages having to be faulted back into the guest.

One side effect of these patches is that the guest becomes much more resilient in terms of NUMA locality. With the pages being freed and then reallocated when used it allows for the pages to be much closer to the active thread, and as a result there can be situations where this patch set will out-perform the stock kernel when the guest memory is not local to the guest vCPUs. To avoid that in my testing I set the affinity of all the vCPUs and QEMU instance to the same node.

Changes from the RFC:
https://lore.kernel.org/lkml/[email protected]/
Moved aeration requested flag out of aerator and into zone->flags. Moved boundary out of free_area and into local variables for aeration. Moved aeration cycle out of interrupt and into workqueue.
Left nr_free as total pages instead of splitting it between raw and aerated. Combined size and physical address values in virtio ring into one 64b value.

Changes from v1:
https://lore.kernel.org/lkml/[email protected]/
Dropped "waste page treatment" in favor of "page hinting" Renamed files and functions from "aeration" to "page_hinting" Moved from page->lru list to scatterlist
Replaced wait on refcnt in shutdown with RCU and cancel_delayed_work_sync Virtio now uses scatterlist directly instead of intermediate array Moved stats out of free_area, now in separate area and pointed to from zone Merged patch 5 into patch 4 to improve review-ability
Updated various code comments throughout

Changes from v2:
https://lore.kernel.org/lkml/[email protected]/
Dropped "page hinting" in favor of "page reporting" Renamed files from "hinting" to "reporting" Replaced "Hinted" page type with "Reported" page flag Added support for page poisoning while hinting is active Add QEMU patch that implements PAGE_POISON feature

Changes from v3:
https://lore.kernel.org/lkml/[email protected]/
Added mutex lock around page reporting startup and shutdown Fixed reference to "page aeration" in patch 2
Split page reporting function bit out into separate QEMU patch Limited capacity of scatterlist to vq size - 1 instead of vq size Added exception handling for case of virtio descriptor allocation failure

Changes from v4:
https://lore.kernel.org/lkml/[email protected]/
Replaced spin_(un)lock with spin_(un)lock_irq in page_reporting_cycle() Dropped if/continue for ternary operator in page_reporting_process() Added checks for isolate and cma types to for_each_reporting_migratetype_order Added virtio-dev, Michal Hocko, and Oscar Salvador to to:/cc:
Rebased on latest linux-next and QEMU git trees

Changes from v5:
https://lore.kernel.org/lkml/[email protected]/
Replaced spin_(un)lock with spin_(un)lock_irq in page_reporting_startup() Updated shuffle code to use "shuffle_pick_tail" and updated patch description Dropped storage of order and migratettype while page is being reported Used get_pfnblock_migratetype to determine migratetype of page Renamed put_reported_page to free_reported_page, added order as argument Dropped check for CMA type as I believe we should be reporting those Added code to allow moving of reported pages into and out of isolation Defined page reporting order as minimum of Huge Page size vs MAX_ORDER - 1 Cleaned up use of static branch usage for page_reporting_notify_enabled

---

Alexander Duyck (6):
mm: Adjust shuffle code to allow for future coalescing
mm: Move set/get_pcppage_migratetype to mmzone.h
mm: Use zone and order instead of free area in free_list manipulators
mm: Introduce Reported pages
virtio-balloon: Pull page poisoning config out of free page hinting
virtio-balloon: Add support for providing unused page reports to host

 drivers/virtio/Kconfig              |    1 
 drivers/virtio/virtio_balloon.c     |   84 ++++++++-
 include/linux/mmzone.h              |  124 ++++++++-----
 include/linux/page-flags.h          |   11 +
 include/linux/page_reporting.h      |  177 ++++++++++++++++++
 include/uapi/linux/virtio_balloon.h |    1 
 mm/Kconfig                          |    5 +
 mm/Makefile                         |    1 
 mm/internal.h                       |   18 ++
 mm/memory_hotplug.c                 |    1 
 mm/page_alloc.c                     |  216 ++++++++++++++++-------
 mm/page_reporting.c                 |  336 +++++++++++++++++++++++++++++++++++
 mm/shuffle.c                        |   40 +++-
 mm/shuffle.h                        |   12 +
 14 files changed, 896 insertions(+), 131 deletions(-)
 create mode 100644 include/linux/page_reporting.h
 create mode 100644 mm/page_reporting.c

--

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

#1 lore raw

PATCH v6 1/6 mm: Adjust shuffle code to allow for future coalescing

From: Alexander Duyck <[email protected]>

Move the head/tail adding logic out of the shuffle code and into the __free_one_page function since ultimately that is where it is really needed anyway. By doing this we should be able to reduce the overhead and can consolidate all of the list addition bits in one spot.

While changing out the code I also opted to go for a bit more thread safe approach to getting the boolean value. This way we can avoid possible cache line bouncing of the batched entropy between CPUs.

---
 include/linux/mmzone.h |   12 --------
 mm/page_alloc.c        |   70 +++++++++++++++++++++++++++---------------------
 mm/shuffle.c           |   40 ++++++++++++++++-----------
 mm/shuffle.h           |   12 ++++++++
 4 files changed, 75 insertions(+), 59 deletions(-)
include/linux/mmzone.h +0 -12
index 8b5f758942a2..62bfb5a280ce 100644
@@ -116,18 +116,6 @@ static inline void add_to_free_area_tail(struct page *page, struct free_area *ar
 	area->nr_free++;
 }
 
-#ifdef CONFIG_SHUFFLE_PAGE_ALLOCATOR
-/* Used to preserve page allocation order entropy */
-void add_to_free_area_random(struct page *page, struct free_area *area,
-		int migratetype);
-#else
-static inline void add_to_free_area_random(struct page *page,
-		struct free_area *area, int migratetype)
-{
-	add_to_free_area(page, area, migratetype);
-}
-#endif
-
 /* Used for pages which are on another list */
 static inline void move_to_free_area(struct page *page, struct free_area *area,
 			     int migratetype)
mm/page_alloc.c +39 -31

91 lines not on this page · raw message

mm/shuffle.c +24 -16
index 3ce12481b1dc..345cb4347455 100644
@@ -4,7 +4,6 @@
 #include <linux/mm.h>
 #include <linux/init.h>
 #include <linux/mmzone.h>
-#include <linux/random.h>
 #include <linux/moduleparam.h>
 #include "internal.h"
 #include "shuffle.h"
@@ -183,25 +182,34 @@ void __meminit __shuffle_free_memory(pg_data_t *pgdat)
 		shuffle_zone(z);
 }
 
-void add_to_free_area_random(struct page *page, struct free_area *area,
-		int migratetype)
+struct batched_bit_entropy {
+	unsigned long entropy_bool;
+	int position;
+};
+
+static DEFINE_PER_CPU(struct batched_bit_entropy, batched_entropy_bool);
+
+bool __shuffle_pick_tail(void)
 {
-	static u64 rand;
-	static u8 rand_bits;
+	struct batched_bit_entropy *batch;
+	unsigned long entropy;
+	int position;
 
 	/*
-	 * The lack of locking is deliberate. If 2 threads race to
-	 * update the rand state it just adds to the entropy.
+	 * We shouldn't need to disable IRQs as the only caller is
+	 * __free_one_page and it should only be called with the zone lock
+	 * held and either from IRQ context or with local IRQs disabled.
 	 */
-	if (rand_bits == 0) {
-		rand_bits = 64;
-		rand = get_random_u64();
+	batch = raw_cpu_ptr(&batched_entropy_bool);
+	position = batch->position;
+
+	if (--position < 0) {
+		batch->entropy_bool = get_random_long();
+		position = BITS_PER_LONG - 1;
 	}
 
-	if (rand & 1)
-		add_to_free_area(page, area, migratetype);
-	else
-		add_to_free_area_tail(page, area, migratetype);
-	rand_bits--;
-	rand >>= 1;
+	batch->position = position;
+	entropy = batch->entropy_bool;
+
+	return 1ul & (entropy >> position);
 }
mm/shuffle.h +12 -0
index 777a257a0d2f..0723eb97f22f 100644
@@ -3,6 +3,7 @@
 #ifndef _MM_SHUFFLE_H
 #define _MM_SHUFFLE_H
 #include <linux/jump_label.h>
+#include <linux/random.h>
 
 /*
  * SHUFFLE_ENABLE is called from the command line enabling path, or by
@@ -22,6 +23,7 @@ enum mm_shuffle_ctl {
 DECLARE_STATIC_KEY_FALSE(page_alloc_shuffle_key);
 extern void page_alloc_shuffle(enum mm_shuffle_ctl ctl);
 extern void __shuffle_free_memory(pg_data_t *pgdat);
+extern bool __shuffle_pick_tail(void);
 static inline void shuffle_free_memory(pg_data_t *pgdat)
 {
 	if (!static_branch_unlikely(&page_alloc_shuffle_key))
@@ -43,6 +45,11 @@ static inline bool is_shuffle_order(int order)
 		return false;
 	return order >= SHUFFLE_ORDER;
 }
+
+static inline bool shuffle_pick_tail(void)
+{
+	return __shuffle_pick_tail();
+}
 #else
 static inline void shuffle_free_memory(pg_data_t *pgdat)
 {
@@ -60,5 +67,10 @@ static inline bool is_shuffle_order(int order)
 {
 	return false;
 }
+
+static inline bool shuffle_pick_tail(void)
+{
+	return false;
+}
 #endif
 #endif /* _MM_SHUFFLE_H */

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

#2 lore raw

PATCH v6 2/6 mm: Move set/get_pcppage_migratetype to mmzone.h

In reply to Alexander Duyck

From: Alexander Duyck <[email protected]>

In order to support page reporting it will be necessary to store and retrieve the migratetype of a page. To enable that I am moving the set and get operations for pcppage_migratetype into the mm/internal.h header so that they can be used outside of the page_alloc.c file.

---
 mm/internal.h   |   18 ++++++++++++++++++
 mm/page_alloc.c |   18 ------------------
 2 files changed, 18 insertions(+), 18 deletions(-)
mm/internal.h +18 -0
index 0d5f720c75ab..e4a1a57bbd40 100644
@@ -549,6 +549,24 @@ static inline bool is_migrate_highatomic_page(struct page *page)
 	return get_pageblock_migratetype(page) == MIGRATE_HIGHATOMIC;
 }
 
+/*
+ * A cached value of the page's pageblock's migratetype, used when the page is
+ * put on a pcplist. Used to avoid the pageblock migratetype lookup when
+ * freeing from pcplists in most cases, at the cost of possibly becoming stale.
+ * Also the migratetype set in the page does not necessarily match the pcplist
+ * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
+ * other index - this ensures that it will be put on the correct CMA freelist.
+ */
+static inline int get_pcppage_migratetype(struct page *page)
+{
+	return page->index;
+}
+
+static inline void set_pcppage_migratetype(struct page *page, int migratetype)
+{
+	page->index = migratetype;
+}
+
 void setup_zone_pageset(struct zone *zone);
 extern struct page *alloc_new_node_page(struct page *page, unsigned long node);
 #endif	/* __MM_INTERNAL_H */
mm/page_alloc.c +0 -18
index 3f8d5afe61fa..c1f9a80b3f28 100644
@@ -185,24 +185,6 @@ static int __init early_init_on_free(char *buf)
 }
 early_param("init_on_free", early_init_on_free);
 
-/*
- * A cached value of the page's pageblock's migratetype, used when the page is
- * put on a pcplist. Used to avoid the pageblock migratetype lookup when
- * freeing from pcplists in most cases, at the cost of possibly becoming stale.
- * Also the migratetype set in the page does not necessarily match the pcplist
- * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
- * other index - this ensures that it will be put on the correct CMA freelist.
- */
-static inline int get_pcppage_migratetype(struct page *page)
-{
-	return page->index;
-}
-
-static inline void set_pcppage_migratetype(struct page *page, int migratetype)
-{
-	page->index = migratetype;
-}
-
 #ifdef CONFIG_PM_SLEEP
 /*
  * The following functions are used by the suspend/hibernate code to temporarily

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

#3 lore raw

PATCH v6 3/6 mm: Use zone and order instead of free area in free_list manipulators

In reply to Alexander Duyck

From: Alexander Duyck <[email protected]>

In order to enable the use of the zone from the list manipulator functions I will need access to the zone pointer. As it turns out most of the accessors were always just being directly passed &zone->free_area[order] anyway so it would make sense to just fold that into the function itself and pass the zone and order as arguments instead of the free area.

In order to be able to reference the zone we need to move the declaration of the functions down so that we have the zone defined before we define the list manipulation functions.

---
 include/linux/mmzone.h |   70 ++++++++++++++++++++++++++----------------------
 mm/page_alloc.c        |   30 ++++++++-------------
 2 files changed, 49 insertions(+), 51 deletions(-)
include/linux/mmzone.h +38 -32
index 62bfb5a280ce..73b541cbeaae 100644
@@ -100,29 +100,6 @@ struct free_area {
 	unsigned long		nr_free;
 };
 
-/* Used for pages not on another list */
-static inline void add_to_free_area(struct page *page, struct free_area *area,
-			     int migratetype)
-{
-	list_add(&page->lru, &area->free_list[migratetype]);
-	area->nr_free++;
-}
-
-/* Used for pages not on another list */
-static inline void add_to_free_area_tail(struct page *page, struct free_area *area,
-				  int migratetype)
-{
-	list_add_tail(&page->lru, &area->free_list[migratetype]);
-	area->nr_free++;
-}
-
-/* Used for pages which are on another list */
-static inline void move_to_free_area(struct page *page, struct free_area *area,
-			     int migratetype)
-{
-	list_move(&page->lru, &area->free_list[migratetype]);
-}
-
 static inline struct page *get_page_from_free_area(struct free_area *area,
 					    int migratetype)
 {
@@ -130,15 +107,6 @@ static inline struct page *get_page_from_free_area(struct free_area *area,
 					struct page, lru);
 }
 
-static inline void del_page_from_free_area(struct page *page,
-		struct free_area *area)
-{
-	list_del(&page->lru);
-	__ClearPageBuddy(page);
-	set_page_private(page, 0);
-	area->nr_free--;
-}
-
 static inline bool free_area_empty(struct free_area *area, int migratetype)
 {
 	return list_empty(&area->free_list[migratetype]);
@@ -795,6 +763,44 @@ static inline bool pgdat_is_empty(pg_data_t *pgdat)
 	return !pgdat->node_start_pfn && !pgdat->node_spanned_pages;
 }
 
+/* Used for pages not on another list */
+static inline void add_to_free_list(struct page *page, struct zone *zone,
+				    unsigned int order, int migratetype)
+{
+	struct free_area *area = &zone->free_area[order];
+
+	list_add(&page->lru, &area->free_list[migratetype]);
+	area->nr_free++;
+}
+
+/* Used for pages not on another list */
+static inline void add_to_free_list_tail(struct page *page, struct zone *zone,
+					 unsigned int order, int migratetype)
+{
+	struct free_area *area = &zone->free_area[order];
+
+	list_add_tail(&page->lru, &area->free_list[migratetype]);
+	area->nr_free++;
+}
+
+/* Used for pages which are on another list */
+static inline void move_to_free_list(struct page *page, struct zone *zone,
+				     unsigned int order, int migratetype)
+{
+	struct free_area *area = &zone->free_area[order];
+
+	list_move(&page->lru, &area->free_list[migratetype]);
+}
+
+static inline void del_page_from_free_list(struct page *page, struct zone *zone,
+					   unsigned int order)
+{
+	list_del(&page->lru);
+	__ClearPageBuddy(page);
+	set_page_private(page, 0);
+	zone->free_area[order].nr_free--;
+}
+
 #include <linux/memory_hotplug.h>
 
 void build_all_zonelists(pg_data_t *pgdat);
mm/page_alloc.c +11 -19
index c1f9a80b3f28..fd01031f733d 100644
@@ -921,7 +921,6 @@ static inline void __free_one_page(struct page *page,
 	struct capture_control *capc = task_capc(zone);
 	unsigned long uninitialized_var(buddy_pfn);
 	unsigned long combined_pfn;
-	struct free_area *area;
 	unsigned int max_order;
 	struct page *buddy;
 
@@ -958,7 +957,7 @@ static inline void __free_one_page(struct page *page,
 		if (page_is_guard(buddy))
 			clear_page_guard(zone, buddy, order, migratetype);
 		else
-			del_page_from_free_area(buddy, &zone->free_area[order]);
+			del_page_from_free_list(buddy, zone, order);
 		combined_pfn = buddy_pfn & pfn;
 		page = page + (combined_pfn - pfn);
 		pfn = combined_pfn;
@@ -992,12 +991,11 @@ static inline void __free_one_page(struct page *page,
 done_merging:
 	set_page_order(page, order);
 
-	area = &zone->free_area[order];
 	if (is_shuffle_order(order) ? shuffle_pick_tail() :
 	    buddy_merge_likely(pfn, buddy_pfn, page, order))
-		add_to_free_area_tail(page, area, migratetype);
+		add_to_free_list_tail(page, zone, order, migratetype);
 	else
-		add_to_free_area(page, area, migratetype);
+		add_to_free_list(page, zone, order, migratetype);
 }
 
 /*
@@ -2001,13 +1999,11 @@ void __init init_cma_reserved_pageblock(struct page *page)
  * -- nyc
  */
 static inline void expand(struct zone *zone, struct page *page,
-	int low, int high, struct free_area *area,
-	int migratetype)
+	int low, int high, int migratetype)
 {
 	unsigned long size = 1 << high;
 
 	while (high > low) {
-		area--;
 		high--;
 		size >>= 1;
 		VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
@@ -2021,7 +2017,7 @@ static inline void expand(struct zone *zone, struct page *page,
 		if (set_page_guard(zone, &page[size], high, migratetype))
 			continue;
 
-		add_to_free_area(&page[size], area, migratetype);
+		add_to_free_list(&page[size], zone, high, migratetype);
 		set_page_order(&page[size], high);
 	}
 }
@@ -2179,8 +2175,8 @@ struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
 		page = get_page_from_free_area(area, migratetype);
 		if (!page)
 			continue;
-		del_page_from_free_area(page, area);
-		expand(zone, page, order, current_order, area, migratetype);
+		del_page_from_free_list(page, zone, current_order);
+		expand(zone, page, order, current_order, migratetype);
 		set_pcppage_migratetype(page, migratetype);
 		return page;
 	}
@@ -2188,7 +2184,6 @@ struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
 	return NULL;
 }
 
-
 /*
  * This array describes the order lists are fallen back to when
  * the free lists for the desirable migrate type are depleted
@@ -2254,7 +2249,7 @@ static int move_freepages(struct zone *zone,
 		VM_BUG_ON_PAGE(page_zone(page) != zone, page);
 
 		order = page_order(page);
-		move_to_free_area(page, &zone->free_area[order], migratetype);
+		move_to_free_list(page, zone, order, migratetype);
 		page += 1 << order;
 		pages_moved += 1 << order;
 	}
@@ -2370,7 +2365,6 @@ static void steal_suitable_fallback(struct zone *zone, struct page *page,
 		unsigned int alloc_flags, int start_type, bool whole_block)
 {
 	unsigned int current_order = page_order(page);
-	struct free_area *area;
 	int free_pages, movable_pages, alike_pages;
 	int old_block_type;
 
@@ -2441,8 +2435,7 @@ static void steal_suitable_fallback(struct zone *zone, struct page *page,
 	return;
 
 single_page:
-	area = &zone->free_area[current_order];
-	move_to_free_area(page, area, start_type);
+	move_to_free_list(page, zone, current_order, start_type);
 }
 
 /*
@@ -3113,7 +3106,6 @@ void split_page(struct page *page, unsigned int order)
 
 int __isolate_free_page(struct page *page, unsigned int order)
 {
-	struct free_area *area = &page_zone(page)->free_area[order];
 	unsigned long watermark;
 	struct zone *zone;
 	int mt;
@@ -3139,7 +3131,7 @@ int __isolate_free_page(struct page *page, unsigned int order)
 
 	/* Remove page from free list */
 
-	del_page_from_free_area(page, area);
+	del_page_from_free_list(page, zone, order);
 
 	/*
 	 * Set the pageblock if the isolated page is at least half of a
@@ -8560,7 +8552,7 @@ void zone_pcp_reset(struct zone *zone)
 		pr_info("remove from free list %lx %d %lx\n",
 			pfn, 1 << order, end_pfn);
 #endif
-		del_page_from_free_area(page, &zone->free_area[order]);
+		del_page_from_free_list(page, zone, order);
 		for (i = 0; i < (1 << order); i++)
 			SetPageReserved((page+i));
 		pfn += (1 << order);

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

#4 lore raw

PATCH v6 4/6 mm: Introduce Reported pages

In reply to Alexander Duyck

From: Alexander Duyck <[email protected]>

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.

It adds a set of pointers we shall call "boundary" which represents the upper boundary between the unreported and reported pages. The general idea is that in order for a page to cross from one side of the boundary to the other it will need to go through the reporting process. Ultimately a free_list has been fully processed when the boundary has been moved from the tail all they way up to occupying the first entry in the list.

Doing this we should be able to make certain that we keep the reported pages as one contiguous block in each free list. This will allow us to efficiently manipulate the free lists whenever we need to go in and start sending reports to the hypervisor that there are new pages that have been freed and are no longer in use.

An added advantage to this approach is that we should be reducing the overall memory footprint of the guest as it will be more likely to recycle warm pages versus trying to allocate the reported pages that were likely evicted from the guest memory.

Since we will only be reporting one zone at a time we keep the boundary limited to being defined for just the zone we are currently reporting pages from. Doing this we can keep the number of additional pointers needed quite small. To flag that the boundaries are in place we use a single bit in the zone to indicate that reporting and the boundaries are active.

The determination of when to start reporting is based on the tracking of the number of free pages in a given area versus the number of reported pages in that area. We keep track of the number of reported pages per free_area in a separate zone specific area. We do this to avoid modifying the free_area structure as this can lead to false sharing for the highest order with the zone lock which leads to a noticeable performance degradation.

---
 include/linux/mmzone.h         |   52 ++++++
 include/linux/page-flags.h     |   11 +
 include/linux/page_reporting.h |  177 +++++++++++++++++++++
 mm/Kconfig                     |    5 +
 mm/Makefile                    |    1 
 mm/memory_hotplug.c            |    1 
 mm/page_alloc.c                |  114 +++++++++++++-
 mm/page_reporting.c            |  336 ++++++++++++++++++++++++++++++++++++++++
 8 files changed, 687 insertions(+), 10 deletions(-)
 create mode 100644 include/linux/page_reporting.h
 create mode 100644 mm/page_reporting.c
include/linux/mmzone.h +47 -5
index 73b541cbeaae..4a80bb50b226 100644
@@ -462,6 +462,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 */
@@ -537,6 +545,14 @@ 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.
+					 */
+	ZONE_PAGE_REPORTING_ACTIVE,	/* zone enabled page reporting and is
+					 * activly flushing the data out of
+					 * higher order pages.
+					 */
 };
 
 static inline unsigned long zone_managed_pages(struct zone *zone)
@@ -763,6 +779,8 @@ static inline bool pgdat_is_empty(pg_data_t *pgdat)
 	return !pgdat->node_start_pfn && !pgdat->node_spanned_pages;
 }
 
+#include <linux/page_reporting.h>
+
 /* Used for pages not on another list */
 static inline void add_to_free_list(struct page *page, struct zone *zone,
 				    unsigned int order, int migratetype)
@@ -777,24 +795,48 @@ static inline void add_to_free_list(struct page *page, struct zone *zone,
 static inline void add_to_free_list_tail(struct page *page, struct zone *zone,
 					 unsigned int order, int migratetype)
 {
-	struct free_area *area = &zone->free_area[order];
+	struct list_head *tail = get_unreported_tail(zone, order, migratetype);
 
-	list_add_tail(&page->lru, &area->free_list[migratetype]);
-	area->nr_free++;
+	/*
+	 * To prevent the unreported pages from being interleaved with the
+	 * reported ones while we are actively processing pages we will use
+	 * the head of the reported pages to determine the tail of the free
+	 * list.
+	 */
+	list_add_tail(&page->lru, tail);
+	zone->free_area[order].nr_free++;
 }
 
 /* Used for pages which are on another list */
 static inline void move_to_free_list(struct page *page, struct zone *zone,
 				     unsigned int order, int migratetype)
 {
-	struct free_area *area = &zone->free_area[order];
+	struct list_head *tail = get_unreported_tail(zone, order, migratetype);
+
+	/*
+	 * We must get the tail for our target list before moving the page on
+	 * the reported list as we will possibly be replacing the tail page of
+	 * the list with our current page if it is reported.
+	 */
+	if (unlikely(PageReported(page)))
+		move_page_to_reported_list(page, zone, migratetype);
 
-	list_move(&page->lru, &area->free_list[migratetype]);
+	/*
+	 * To prevent unreported pages from being mixed with the reported
+	 * ones we add pages to the tail of the list. By doing this the function
+	 * above can either label them as included in the reported list or not
+	 * and the result will be consistent.
+	 */
+	list_move_tail(&page->lru, tail);
 }
 
 static inline void del_page_from_free_list(struct page *page, struct zone *zone,
 					   unsigned int order)
 {
+	/* remove page from reported list, and clear reported state */
+	if (unlikely(PageReported(page)))
+		del_page_from_reported_list(page, zone);
+
 	list_del(&page->lru);
 	__ClearPageBuddy(page);
 	set_page_private(page, 0);
include/linux/page-flags.h +11 -0
index f91cb8898ff0..759a3b3956f2 100644
@@ -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.
include/linux/page_reporting.h new file +177 -0

177 lines not on this page · raw message

mm/Kconfig +5 -0
index a5dae9a7eb51..be1a5db50df5 100644
@@ -237,6 +237,11 @@ config COMPACTION
           [email protected].
 
 #
+# support for unused page reporting
+config PAGE_REPORTING
+	bool
+
+#
 # support for page migration
 #
 config MIGRATION
mm/Makefile +1 -0
index d11de59e9c3c..4dcf09cd8280 100644
@@ -104,3 +104,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
mm/memory_hotplug.c +1 -0
index 32a5386758ce..d0b813567ff4 100644
@@ -1614,6 +1614,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);
 	} else
 		zone_pcp_update(zone);
 
mm/page_alloc.c +109 -5

153 lines not on this page · raw message

mm/page_reporting.c new file +336 -0

336 lines not on this page · raw message

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

#5 lore raw

Re: [virtio-dev] [PATCH v6 4/6] mm: Introduce Reported pages

Quoted 40 lines · Alexander Duyck

From: Alexander Duyck <[email protected]>

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.

It adds a set of pointers we shall call "boundary" which represents the upper boundary between the unreported and reported pages. The general idea is that in order for a page to cross from one side of the boundary to the other it will need to go through the reporting process. Ultimately a free_list has been fully processed when the boundary has been moved from the tail all they way up to occupying the first entry in the list.

Doing this we should be able to make certain that we keep the reported pages as one contiguous block in each free list. This will allow us to efficiently manipulate the free lists whenever we need to go in and start sending reports to the hypervisor that there are new pages that have been freed and are no longer in use.

An added advantage to this approach is that we should be reducing the overall memory footprint of the guest as it will be more likely to recycle warm pages versus trying to allocate the reported pages that were likely evicted from the guest memory.

Since we will only be reporting one zone at a time we keep the boundary limited to being defined for just the zone we are currently reporting pages from. Doing this we can keep the number of additional pointers needed quite small. To flag that the boundaries are in place we use a single bit in the zone to indicate that reporting and the boundaries are active.

The determination of when to start reporting is based on the tracking of the number of free pages in a given area versus the number of reported pages in that area. We keep track of the number of reported pages per free_area in a separate zone specific area. We do this to avoid modifying the free_area structure as this can lead to false sharing for the highest order with the zone lock which leads to a noticeable performance degradation.

[...]

Quoted 7 lines
mm/page_reporting.c new file +7 -0
+
+/* request page reporting on this zone */
+void __page_reporting_request(struct zone *zone)
+{
+	struct page_reporting_dev_info *phdev;
+
+	rcu_read_lock();

mm/page_reporting.c line 244

Quoted 10 lines
mm/page_reporting.c new file +10 -0
+
+	/*
+	 * We use RCU to protect the ph_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.
+	 */
+	phdev = rcu_dereference(ph_dev_info);
+	if (unlikely(!phdev))
+		return;
+

Just a minor comment here.
Although this is unlikely to trigger still I think you should release the rcu_read_lock before returning.

Quoted 20 lines
mm/page_reporting.c new file +20 -0
+	/*
+	 * 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 10 times per second.
+	 */
+	if (!atomic_fetch_inc(&phdev->refcnt))
+		schedule_delayed_work(&phdev->work, HZ / 10);
+
+	rcu_read_unlock();
+}
+

[...]

Quoted 16 lines
mm/page_reporting.c new file +10 -1
+	}
+
+	/* enable page reporting notification */
+	static_branch_enable(&page_reporting_notify_enabled);
+err_out:
+	mutex_unlock(&page_reporting_mutex);
+
+	return err;
+}
+EXPORT_SYMBOL_GPL(page_reporting_startup);
 
 
---------------------------------------------------------------------

To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

Signature · 7 lines
Thanks
Nitesh


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
#6 lore raw

Re: [virtio-dev] [PATCH v6 4/6] mm: Introduce Reported pages

Quoted 57 lines · Nitesh Narayan Lal
Quoted 40 lines · Alexander Duyck

From: Alexander Duyck <[email protected]>

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.

It adds a set of pointers we shall call "boundary" which represents the upper boundary between the unreported and reported pages. The general idea is that in order for a page to cross from one side of the boundary to the other it will need to go through the reporting process. Ultimately a free_list has been fully processed when the boundary has been moved from the tail all they way up to occupying the first entry in the list.

Doing this we should be able to make certain that we keep the reported pages as one contiguous block in each free list. This will allow us to efficiently manipulate the free lists whenever we need to go in and start sending reports to the hypervisor that there are new pages that have been freed and are no longer in use.

An added advantage to this approach is that we should be reducing the overall memory footprint of the guest as it will be more likely to recycle warm pages versus trying to allocate the reported pages that were likely evicted from the guest memory.

Since we will only be reporting one zone at a time we keep the boundary limited to being defined for just the zone we are currently reporting pages from. Doing this we can keep the number of additional pointers needed quite small. To flag that the boundaries are in place we use a single bit in the zone to indicate that reporting and the boundaries are active.

The determination of when to start reporting is based on the tracking of the number of free pages in a given area versus the number of reported pages in that area. We keep track of the number of reported pages per free_area in a separate zone specific area. We do this to avoid modifying the free_area structure as this can lead to false sharing for the highest order with the zone lock which leads to a noticeable performance degradation.

[...]

Quoted 13 lines
mm/page_reporting.c new file +13 -0
+
+/* request page reporting on this zone */
+void __page_reporting_request(struct zone *zone)
+{
+     struct page_reporting_dev_info *phdev;
+
+     rcu_read_lock();
+
+     /*
+      * We use RCU to protect the ph_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.
+      */
Quoted 8 lines

mm/page_reporting.c line 244

Quoted 4 lines
mm/page_reporting.c new file +4 -0
+     phdev = rcu_dereference(ph_dev_info);
+     if (unlikely(!phdev))
+             return;
+

Just a minor comment here.
Although this is unlikely to trigger still I think you should release the rcu_read_lock before returning.

Thanks for catching that. I will have that fixed for next version.

- Alex

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

#7 lore raw

PATCH v6 5/6 virtio-balloon: Pull page poisoning config out of free page hinting

In reply to Alexander Duyck

From: Alexander Duyck <[email protected]>

Currently the page poisoning setting wasn't being enabled unless free page hinting was enabled. However we will need the page poisoning tracking logic as well for unused page reporting. As such pull it out and make it a separate bit of config in the probe function.

In addition we can actually wrap the code in a check for NO_SANITY. If we don't care what is actually in the page we can just default to 0 and leave it there.

---
 drivers/virtio/virtio_balloon.c |   19 +++++++++++++------
 1 file changed, 13 insertions(+), 6 deletions(-)
drivers/virtio/virtio_balloon.c +13 -6
index 226fbb995fb0..2c19457ab573 100644
@@ -842,7 +842,6 @@ static int virtio_balloon_register_shrinker(struct virtio_balloon *vb)
 static int virtballoon_probe(struct virtio_device *vdev)
 {
 	struct virtio_balloon *vb;
-	__u32 poison_val;
 	int err;
 
 	if (!vdev->config->get) {
@@ -909,11 +908,19 @@ static int virtballoon_probe(struct virtio_device *vdev)
 						  VIRTIO_BALLOON_CMD_ID_STOP);
 		spin_lock_init(&vb->free_page_list_lock);
 		INIT_LIST_HEAD(&vb->free_page_list);
-		if (virtio_has_feature(vdev, VIRTIO_BALLOON_F_PAGE_POISON)) {
-			memset(&poison_val, PAGE_POISON, sizeof(poison_val));
-			virtio_cwrite(vb->vdev, struct virtio_balloon_config,
-				      poison_val, &poison_val);
-		}
+	}
+	if (virtio_has_feature(vdev, VIRTIO_BALLOON_F_PAGE_POISON)) {
+		__u32 poison_val = 0;
+
+#if !defined(CONFIG_PAGE_POISONING_NO_SANITY)
+		/*
+		 * Let hypervisor know that we are expecting a specific
+		 * value to be written back in unused pages.
+		 */
+		memset(&poison_val, PAGE_POISON, sizeof(poison_val));
+#endif
+		virtio_cwrite(vb->vdev, struct virtio_balloon_config,
+			      poison_val, &poison_val);
 	}
 	/*
 	 * We continue to use VIRTIO_BALLOON_F_DEFLATE_ON_OOM to decide if a

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

#8 lore raw

PATCH v6 6/6 virtio-balloon: Add support for providing unused page reports to host

In reply to Alexander Duyck

From: Alexander Duyck <[email protected]>

Add support for the page reporting feature provided by virtio-balloon. Reporting differs from the regular balloon functionality in that is is much less durable than a standard memory balloon. Instead of creating a list of pages that cannot be accessed the pages are only inaccessible while they are being indicated to the virtio interface. Once the interface has acknowledged them they are placed back into their respective free lists and are once again accessible by the guest system.

---
 drivers/virtio/Kconfig              |    1 +
 drivers/virtio/virtio_balloon.c     |   65 +++++++++++++++++++++++++++++++++++
 include/uapi/linux/virtio_balloon.h |    1 +
 3 files changed, 67 insertions(+)
drivers/virtio/Kconfig +1 -0
index 078615cf2afc..4b2dd8259ff5 100644
@@ -58,6 +58,7 @@ config VIRTIO_BALLOON
 	tristate "Virtio balloon driver"
 	depends on VIRTIO
 	select MEMORY_BALLOON
+	select PAGE_REPORTING
 	---help---
 	 This driver supports increasing and decreasing the amount
 	 of memory within a KVM guest.
drivers/virtio/virtio_balloon.c +65 -0

136 lines not on this page · raw message

include/uapi/linux/virtio_balloon.h +1 -0
index a1966cd7b677..19974392d324 100644
@@ -36,6 +36,7 @@
 #define VIRTIO_BALLOON_F_DEFLATE_ON_OOM	2 /* Deflate balloon on OOM */
 #define VIRTIO_BALLOON_F_FREE_PAGE_HINT	3 /* VQ to report free pages */
 #define VIRTIO_BALLOON_F_PAGE_POISON	4 /* Guest is using page poisoning */
+#define VIRTIO_BALLOON_F_REPORTING	5 /* Page reporting virtqueue */
 
 /* Size of a PFN in the balloon interface. */
 #define VIRTIO_BALLOON_PFN_SHIFT 12

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

#9 lore raw

PATCH v6 1/3 virtio-ballon: Implement support for page poison tracking feature

In reply to Alexander Duyck

From: Alexander Duyck <[email protected]>

We need to make certain to advertise support for page poison tracking if we want to actually get data on if the guest will be poisoning pages. So if free page hinting is active we should add page poisoning support and let the guest disable it if it isn't using it.

Page poisoning will result in a page being dirtied on free. As such we cannot really avoid having to copy the page at least one more time since we will need to write the poison value to the destination. As such we can just ignore free page hinting if page poisoning is enabled as it will actually reduce the work we have to do.

---
 hw/virtio/virtio-balloon.c         |   25 +++++++++++++++++++++----
 include/hw/virtio/virtio-balloon.h |    1 +
 2 files changed, 22 insertions(+), 4 deletions(-)
hw/virtio/virtio-balloon.c +21 -4
index 25de15430710..003b3ebcfdfb 100644
@@ -530,6 +530,15 @@ static void virtio_balloon_free_page_start(VirtIOBalloon *s)
         return;
     }
 
+    /*
+     * If page poisoning is enabled then we probably shouldn't bother with
+     * the hinting since the poisoning will dirty the page and invalidate
+     * the work we are doing anyway.
+     */
+    if (virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_PAGE_POISON)) {
+        return;
+    }
+
     if (s->free_page_report_cmd_id == UINT_MAX) {
         s->free_page_report_cmd_id =
                        VIRTIO_BALLOON_FREE_PAGE_REPORT_CMD_ID_MIN;
@@ -617,12 +626,10 @@ static size_t virtio_balloon_config_size(VirtIOBalloon *s)
     if (s->qemu_4_0_config_size) {
         return sizeof(struct virtio_balloon_config);
     }
-    if (virtio_has_feature(features, VIRTIO_BALLOON_F_PAGE_POISON)) {
+    if (virtio_has_feature(features, VIRTIO_BALLOON_F_PAGE_POISON) ||
+        virtio_has_feature(features, VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
         return sizeof(struct virtio_balloon_config);
     }
-    if (virtio_has_feature(features, VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
-        return offsetof(struct virtio_balloon_config, poison_val);
-    }
     return offsetof(struct virtio_balloon_config, free_page_report_cmd_id);
 }
 
@@ -633,6 +640,7 @@ static void virtio_balloon_get_config(VirtIODevice *vdev, uint8_t *config_data)
 
     config.num_pages = cpu_to_le32(dev->num_pages);
     config.actual = cpu_to_le32(dev->actual);
+    config.poison_val = cpu_to_le32(dev->poison_val);
 
     if (dev->free_page_report_status == FREE_PAGE_REPORT_S_REQUESTED) {
         config.free_page_report_cmd_id =
@@ -696,6 +704,8 @@ static void virtio_balloon_set_config(VirtIODevice *vdev,
         qapi_event_send_balloon_change(vm_ram_size -
                         ((ram_addr_t) dev->actual << VIRTIO_BALLOON_PFN_SHIFT));
     }
+    dev->poison_val = virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_PAGE_POISON) ? 
+                      le32_to_cpu(config.poison_val) : 0;
     trace_virtio_balloon_set_config(dev->actual, oldactual);
 }
 
@@ -705,6 +715,9 @@ static uint64_t virtio_balloon_get_features(VirtIODevice *vdev, uint64_t f,
     VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
     f |= dev->host_features;
     virtio_add_feature(&f, VIRTIO_BALLOON_F_STATS_VQ);
+    if (virtio_has_feature(f, VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
+        virtio_add_feature(&f, VIRTIO_BALLOON_F_PAGE_POISON);
+    }
 
     return f;
 }
@@ -846,6 +859,8 @@ static void virtio_balloon_device_reset(VirtIODevice *vdev)
         g_free(s->stats_vq_elem);
         s->stats_vq_elem = NULL;
     }
+
+    s->poison_val = 0;
 }
 
 static void virtio_balloon_set_status(VirtIODevice *vdev, uint8_t status)
@@ -908,6 +923,8 @@ static Property virtio_balloon_properties[] = {
                     VIRTIO_BALLOON_F_DEFLATE_ON_OOM, false),
     DEFINE_PROP_BIT("free-page-hint", VirtIOBalloon, host_features,
                     VIRTIO_BALLOON_F_FREE_PAGE_HINT, false),
+    DEFINE_PROP_BIT("x-page-poison", VirtIOBalloon, host_features,
+                    VIRTIO_BALLOON_F_PAGE_POISON, false),
     /* QEMU 4.0 accidentally changed the config size even when free-page-hint
      * is disabled, resulting in QEMU 3.1 migration incompatibility.  This
      * property retains this quirk for QEMU 4.1 machine types.
include/hw/virtio/virtio-balloon.h +1 -0
index d1c968d2376e..7fe78e5c14d7 100644
@@ -70,6 +70,7 @@ typedef struct VirtIOBalloon {
     uint32_t host_features;
 
     bool qemu_4_0_config_size;
+    uint32_t poison_val;
 } VirtIOBalloon;
 
 #endif
#10 lore raw

PATCH v6 2/3 virtio-balloon: Add bit to notify guest of unused page reporting

In reply to Alexander Duyck

From: Alexander Duyck <[email protected]>

Add a bit for the page reporting feature provided by virtio-balloon.

This patch should be replaced once the feature is added to the Linux kernel and the bit is backported into this exported kernel header.

---
 include/standard-headers/linux/virtio_balloon.h |    1 +
 1 file changed, 1 insertion(+)
include/standard-headers/linux/virtio_balloon.h +1 -0
index 9375ca2a70de..1c5f6d6f2de6 100644
@@ -36,6 +36,7 @@
 #define VIRTIO_BALLOON_F_DEFLATE_ON_OOM	2 /* Deflate balloon on OOM */
 #define VIRTIO_BALLOON_F_FREE_PAGE_HINT	3 /* VQ to report free pages */
 #define VIRTIO_BALLOON_F_PAGE_POISON	4 /* Guest is using page poisoning */
+#define VIRTIO_BALLOON_F_REPORTING	5 /* Page reporting virtqueue */
 
 /* Size of a PFN in the balloon interface. */
 #define VIRTIO_BALLOON_PFN_SHIFT 12

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

#11 lore raw

PATCH v6 3/3 virtio-balloon: Provide a interface for unused page reporting

In reply to Alexander Duyck

From: Alexander Duyck <[email protected]>

Add support for what I am referring to as "unused page reporting". Basically the idea is to function very similar to how the balloon works in that we basically end up madvising the page as not being used. However we don't really need to bother with any deflate type logic since the page will be faulted back into the guest when it is read or written to.

This is meant to be a simplification of the existing balloon interface to use for providing hints to what memory needs to be freed. I am assuming this is safe to do as the deflate logic does not actually appear to do very much other than tracking what subpages have been released and which ones haven't.

---
 hw/virtio/virtio-balloon.c         |   46 ++++++++++++++++++++++++++++++++++--
 include/hw/virtio/virtio-balloon.h |    2 +-
 2 files changed, 45 insertions(+), 3 deletions(-)
hw/virtio/virtio-balloon.c +44 -2
index 003b3ebcfdfb..7a30df63bc77 100644
@@ -320,6 +320,40 @@ static void balloon_stats_set_poll_interval(Object *obj, Visitor *v,
     balloon_stats_change_timer(s, 0);
 }
 
+static void virtio_balloon_handle_report(VirtIODevice *vdev, VirtQueue *vq)
+{
+    VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
+    VirtQueueElement *elem;
+
+    while ((elem = virtqueue_pop(vq, sizeof(VirtQueueElement)))) {
+    	unsigned int i;
+
+        for (i = 0; i < elem->in_num; i++) {
+            void *addr = elem->in_sg[i].iov_base;
+            size_t size = elem->in_sg[i].iov_len;
+            ram_addr_t ram_offset;
+            size_t rb_page_size;
+            RAMBlock *rb;
+
+            if (qemu_balloon_is_inhibited() || dev->poison_val)
+                continue;
+
+            rb = qemu_ram_block_from_host(addr, false, &ram_offset);
+            rb_page_size = qemu_ram_pagesize(rb);
+
+            /* For now we will simply ignore unaligned memory regions */
+            if ((ram_offset | size) & (rb_page_size - 1))
+                continue;
+
+            ram_block_discard_range(rb, ram_offset, size);
+        }
+
+        virtqueue_push(vq, elem, 0);
+        virtio_notify(vdev, vq);
+        g_free(elem);
+    }
+}
+
 static void virtio_balloon_handle_output(VirtIODevice *vdev, VirtQueue *vq)
 {
     VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
@@ -627,7 +661,8 @@ static size_t virtio_balloon_config_size(VirtIOBalloon *s)
         return sizeof(struct virtio_balloon_config);
     }
     if (virtio_has_feature(features, VIRTIO_BALLOON_F_PAGE_POISON) ||
-        virtio_has_feature(features, VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
+        virtio_has_feature(features, VIRTIO_BALLOON_F_FREE_PAGE_HINT) ||
+        virtio_has_feature(features, VIRTIO_BALLOON_F_REPORTING)) {
         return sizeof(struct virtio_balloon_config);
     }
     return offsetof(struct virtio_balloon_config, free_page_report_cmd_id);
@@ -715,7 +750,8 @@ static uint64_t virtio_balloon_get_features(VirtIODevice *vdev, uint64_t f,
     VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
     f |= dev->host_features;
     virtio_add_feature(&f, VIRTIO_BALLOON_F_STATS_VQ);
-    if (virtio_has_feature(f, VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
+    if (virtio_has_feature(f, VIRTIO_BALLOON_F_FREE_PAGE_HINT) ||
+        virtio_has_feature(f, VIRTIO_BALLOON_F_REPORTING)) {
         virtio_add_feature(&f, VIRTIO_BALLOON_F_PAGE_POISON);
     }
 
@@ -805,6 +841,10 @@ static void virtio_balloon_device_realize(DeviceState *dev, Error **errp)
     s->dvq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
     s->svq = virtio_add_queue(vdev, 128, virtio_balloon_receive_stats);
 
+    if (virtio_has_feature(s->host_features, VIRTIO_BALLOON_F_REPORTING)) {
+        s->rvq = virtio_add_queue(vdev, 32, virtio_balloon_handle_report);
+    }
+
     if (virtio_has_feature(s->host_features,
                            VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
         s->free_page_vq = virtio_add_queue(vdev, VIRTQUEUE_MAX_SIZE,
@@ -931,6 +971,8 @@ static Property virtio_balloon_properties[] = {
      */
     DEFINE_PROP_BOOL("qemu-4-0-config-size", VirtIOBalloon,
                      qemu_4_0_config_size, false),
+    DEFINE_PROP_BIT("unused-page-reporting", VirtIOBalloon, host_features,
+                    VIRTIO_BALLOON_F_REPORTING, true),
     DEFINE_PROP_LINK("iothread", VirtIOBalloon, iothread, TYPE_IOTHREAD,
                      IOThread *),
     DEFINE_PROP_END_OF_LIST(),
include/hw/virtio/virtio-balloon.h +1 -1
index 7fe78e5c14d7..db5bf7127112 100644
@@ -42,7 +42,7 @@ enum virtio_balloon_free_page_report_status {
 
 typedef struct VirtIOBalloon {
     VirtIODevice parent_obj;
-    VirtQueue *ivq, *dvq, *svq, *free_page_vq;
+    VirtQueue *ivq, *dvq, *svq, *free_page_vq, *rvq;
     uint32_t free_page_report_status;
     uint32_t num_pages;
     uint32_t actual;

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

#12 lore raw
In reply to Alexander Duyck
Quoted 27 lines

This series provides an asynchronous means of reporting to a hypervisor that a guest page is no longer in use and can have the data associated with it dropped. To do this I have implemented functionality that allows for what I am referring to as unused page reporting

The functionality for this is fairly simple. When enabled it will allocate statistics to track the number of reported pages in a given free area. When the number of free pages exceeds this value plus a high water value, currently 32, it will begin performing page reporting which consists of pulling pages off of free list and placing them into a scatter list. The scatterlist is then given to the page reporting device and it will perform the required action to make the pages "reported", in the case of virtio-balloon this results in the pages being madvised as MADV_DONTNEED and as such they are forced out of the guest. After this they are placed back on the free list, and an additional bit is added if they are not merged indicating that they are a reported buddy page instead of a standard buddy page. The cycle then repeats with additional non-reported pages being pulled until the free areas all consist of reported pages.

I am leaving a number of things hard-coded such as limiting the lowest order processed to PAGEBLOCK_ORDER, and have left it up to the guest to determine what the limit is on how many pages it wants to allocate to process the hints. The upper limit for this is based on the size of the queue used to store the scattergather list.

Quoted 4 lines

My primary testing has just been to verify the memory is being freed after allocation by running memhog 40g on a 40g guest and watching the total free memory via /proc/meminfo on the host. With this I have verified most of the memory is freed after each iteration.

I tried to go through the entire patch series. I can see you reported a -3.27 drop from the baseline. If its because of re-faulting the page after host has freed them? Can we avoid freeing all the pages from the guest free_area and keep some pages(maybe some mixed order), so that next allocation is done from the guest itself than faulting to host. This will work with real workload where allocation and deallocation happen at regular intervals.

This can be further optimized based on other factors like host memory pressure etc.

Thanks,
Pankaj

As far as performance I have

Quoted 107 lines

been mainly focusing on the will-it-scale/page_fault1 test running with 16 vcpus. I have modified it to use Transparent Huge Pages. With this I see almost no difference, -0.08%, with the patches applied and the feature disabled. I see a regression of -0.86% with the feature enabled, but the madvise disabled in the hypervisor due to a device being assigned. With the feature fully enabled I see a regression of -3.27% versus the baseline without these patches applied. In my testing I found that most of the overhead was due to the page zeroing that comes as a result of the pages having to be faulted back into the guest.

One side effect of these patches is that the guest becomes much more resilient in terms of NUMA locality. With the pages being freed and then reallocated when used it allows for the pages to be much closer to the active thread, and as a result there can be situations where this patch set will out-perform the stock kernel when the guest memory is not local to the guest vCPUs. To avoid that in my testing I set the affinity of all the vCPUs and QEMU instance to the same node.

Changes from the RFC:
https://lore.kernel.org/lkml/[email protected]/
Moved aeration requested flag out of aerator and into zone->flags. Moved boundary out of free_area and into local variables for aeration. Moved aeration cycle out of interrupt and into workqueue.
Left nr_free as total pages instead of splitting it between raw and aerated. Combined size and physical address values in virtio ring into one 64b value.

Changes from v1:
https://lore.kernel.org/lkml/[email protected]/
Dropped "waste page treatment" in favor of "page hinting" Renamed files and functions from "aeration" to "page_hinting" Moved from page->lru list to scatterlist
Replaced wait on refcnt in shutdown with RCU and cancel_delayed_work_sync Virtio now uses scatterlist directly instead of intermediate array Moved stats out of free_area, now in separate area and pointed to from zone Merged patch 5 into patch 4 to improve review-ability
Updated various code comments throughout

Changes from v2:
https://lore.kernel.org/lkml/[email protected]/
Dropped "page hinting" in favor of "page reporting" Renamed files from "hinting" to "reporting" Replaced "Hinted" page type with "Reported" page flag Added support for page poisoning while hinting is active Add QEMU patch that implements PAGE_POISON feature

Changes from v3:
https://lore.kernel.org/lkml/[email protected]/
Added mutex lock around page reporting startup and shutdown Fixed reference to "page aeration" in patch 2
Split page reporting function bit out into separate QEMU patch Limited capacity of scatterlist to vq size - 1 instead of vq size Added exception handling for case of virtio descriptor allocation failure

Changes from v4:
https://lore.kernel.org/lkml/[email protected]/
Replaced spin_(un)lock with spin_(un)lock_irq in page_reporting_cycle() Dropped if/continue for ternary operator in page_reporting_process() Added checks for isolate and cma types to for_each_reporting_migratetype_order
Added virtio-dev, Michal Hocko, and Oscar Salvador to to:/cc:
Rebased on latest linux-next and QEMU git trees

Changes from v5:
https://lore.kernel.org/lkml/[email protected]/
Replaced spin_(un)lock with spin_(un)lock_irq in page_reporting_startup() Updated shuffle code to use "shuffle_pick_tail" and updated patch description Dropped storage of order and migratettype while page is being reported Used get_pfnblock_migratetype to determine migratetype of page Renamed put_reported_page to free_reported_page, added order as argument Dropped check for CMA type as I believe we should be reporting those Added code to allow moving of reported pages into and out of isolation Defined page reporting order as minimum of Huge Page size vs MAX_ORDER - 1 Cleaned up use of static branch usage for page_reporting_notify_enabled

---

Alexander Duyck (6):
mm: Adjust shuffle code to allow for future coalescing
mm: Move set/get_pcppage_migratetype to mmzone.h
mm: Use zone and order instead of free area in free_list manipulators
mm: Introduce Reported pages
virtio-balloon: Pull page poisoning config out of free page hinting
virtio-balloon: Add support for providing unused page reports to host

 drivers/virtio/Kconfig              |    1
 drivers/virtio/virtio_balloon.c     |   84 ++++++++-
 include/linux/mmzone.h              |  124 ++++++++-----
 include/linux/page-flags.h          |   11 +
 include/linux/page_reporting.h      |  177 ++++++++++++++++++
 include/uapi/linux/virtio_balloon.h |    1
 mm/Kconfig                          |    5 +
 mm/Makefile                         |    1
 mm/internal.h                       |   18 ++
 mm/memory_hotplug.c                 |    1
 mm/page_alloc.c                     |  216 ++++++++++++++++-------
 mm/page_reporting.c                 |  336
 +++++++++++++++++++++++++++++++++++
 mm/shuffle.c                        |   40 +++-
 mm/shuffle.h                        |   12 +
 14 files changed, 896 insertions(+), 131 deletions(-)
 create mode 100644 include/linux/page_reporting.h
 create mode 100644 mm/page_reporting.c

--

#13 lore raw
Quoted 37 lines · Pankaj Gupta
Quoted 25 lines

This series provides an asynchronous means of reporting to a hypervisor that a guest page is no longer in use and can have the data associated with it dropped. To do this I have implemented functionality that allows for what I am referring to as unused page reporting

The functionality for this is fairly simple. When enabled it will allocate statistics to track the number of reported pages in a given free area. When the number of free pages exceeds this value plus a high water value, currently 32, it will begin performing page reporting which consists of pulling pages off of free list and placing them into a scatter list. The scatterlist is then given to the page reporting device and it will perform the required action to make the pages "reported", in the case of virtio-balloon this results in the pages being madvised as MADV_DONTNEED and as such they are forced out of the guest. After this they are placed back on the free list, and an additional bit is added if they are not merged indicating that they are a reported buddy page instead of a standard buddy page. The cycle then repeats with additional non-reported pages being pulled until the free areas all consist of reported pages.

I am leaving a number of things hard-coded such as limiting the lowest order processed to PAGEBLOCK_ORDER, and have left it up to the guest to determine what the limit is on how many pages it wants to allocate to process the hints. The upper limit for this is based on the size of the queue used to store the scattergather list.

Quoted 4 lines

My primary testing has just been to verify the memory is being freed after allocation by running memhog 40g on a 40g guest and watching the total free memory via /proc/meminfo on the host. With this I have verified most of the memory is freed after each iteration.

I tried to go through the entire patch series. I can see you reported a -3.27 drop from the baseline. If its because of re-faulting the page after host has freed them? Can we avoid freeing all the pages from the guest free_area and keep some pages(maybe some mixed order), so that next allocation is done from the guest itself than faulting to host. This will work with real workload where allocation and deallocation happen at regular intervals.

Quoted 4 lines

This can be further optimized based on other factors like host memory pressure etc.

Thanks,
Pankaj

When I originally started implementing and testing this code I was seeing less than a 1% regression. I didn't feel like that was really an accurate result since it wasn't putting much stress on the changed code so I have modified my tests and kernel so that I have memory shuffting and THP enabled. In addition I have gone out of my way to lock things down to a single NUMA node on my host system as the code I had would sometimes perform better than baseline when running the test due to the fact that memory was being freed back to the hose and then reallocated which actually allowed for better NUMA locality.

The general idea was I wanted to know what the worst case penalty would be for running this code, and it turns out most of that is just the cost of faulting back in the pages. By enabling memory shuffling I am forcing the memory to churn as pages are added to both the head and tail of the free_list. The test itself was modified so that it didn't allocate order 0 pages and instead was allocating transparent huge pages so the effects were as visible as possible. Without that the page faulting overhead would mostly fall into the noise of having to allocate the memory as order 0 pages, that is what I had essentially seen earlier when I was running the stock page_fault1 test.

This code does no hinting on anything smaller than either MAX_ORDER - 1 or HUGETLB_PAGE_ORDER pages, and it only starts when there are at least 32 of them available to hint on. This results in us not starting to perform the hinting until there is 64MB to 128MB of memory sitting in the higher order regions of the zone.

The hinting itself stops as soon as we run out of unhinted pages to pull from. When this occurs we let any pages that are freed after that accumulate until we get back to 32 pages being free in a given order. During this time we should build up the cache of warm pages that you mentioned, assuming that shuffling is not enabled.

As far as further optimizations I don't think there is anything here that prevents us from doing that. For now I am focused on just getting the basics in place so we have a foundation to start from.

Thanks.

- Alex

#14 lore raw
Quoted 61 lines · Pankaj Gupta
Quoted 43 lines
Quoted 27 lines

This series provides an asynchronous means of reporting to a hypervisor that a guest page is no longer in use and can have the data associated with it dropped. To do this I have implemented functionality that allows for what I am referring to as unused page reporting

The functionality for this is fairly simple. When enabled it will allocate
statistics to track the number of reported pages in a given free area. When the number of free pages exceeds this value plus a high water value, currently 32, it will begin performing page reporting which consists of pulling pages off of free list and placing them into a scatter list. The scatterlist is then given to the page reporting device and it will perform
the required action to make the pages "reported", in the case of virtio-balloon this results in the pages being madvised as MADV_DONTNEED and as such they are forced out of the guest. After this they are placed back on the free list, and an additional bit is added if they are not merged indicating that they are a reported buddy page instead of a standard buddy page. The cycle then repeats with additional non-reported pages being pulled until the free areas all consist of reported pages.

I am leaving a number of things hard-coded such as limiting the lowest order processed to PAGEBLOCK_ORDER, and have left it up to the guest to determine what the limit is on how many pages it wants to allocate to process the hints. The upper limit for this is based on the size of the queue used to store the scattergather list.

Quoted 5 lines

My primary testing has just been to verify the memory is being freed after
allocation by running memhog 40g on a 40g guest and watching the total free memory via /proc/meminfo on the host. With this I have verified most of the memory is freed after each iteration.

I tried to go through the entire patch series. I can see you reported a -3.27 drop from the baseline. If its because of re-faulting the page after host has freed them? Can we avoid freeing all the pages from the guest free_area
and keep some pages(maybe some mixed order), so that next allocation is done from
the guest itself than faulting to host. This will work with real workload where
allocation and deallocation happen at regular intervals.

Quoted 5 lines

This can be further optimized based on other factors like host memory pressure etc.

Thanks,
Pankaj

When I originally started implementing and testing this code I was seeing less than a 1% regression. I didn't feel like that was really an accurate result since it wasn't putting much stress on the changed code so I have modified my tests and kernel so that I have memory shuffting and THP enabled. In addition I have gone out of my way to lock things down to a single NUMA node on my host system as the code I had would sometimes perform better than baseline when running the test due to the fact that memory was being freed back to the hose and then reallocated which actually allowed for better NUMA locality.

Quoted 10 lines

The general idea was I wanted to know what the worst case penalty would be for running this code, and it turns out most of that is just the cost of faulting back in the pages. By enabling memory shuffling I am forcing the memory to churn as pages are added to both the head and tail of the free_list. The test itself was modified so that it didn't allocate order 0 pages and instead was allocating transparent huge pages so the effects were as visible as possible. Without that the page faulting overhead would mostly fall into the noise of having to allocate the memory as order 0 pages, that is what I had essentially seen earlier when I was running the stock page_fault1 test.

Right. I think the reason is this test is allocating THP's in guest, host side you are still using order 0 pages, I assume?

Quoted 6 lines

This code does no hinting on anything smaller than either MAX_ORDER - 1 or HUGETLB_PAGE_ORDER pages, and it only starts when there are at least 32 of them available to hint on. This results in us not starting to perform the hinting until there is 64MB to 128MB of memory sitting in the higher order regions of the zone.

o.k

Quoted 6 lines

The hinting itself stops as soon as we run out of unhinted pages to pull from. When this occurs we let any pages that are freed after that accumulate until we get back to 32 pages being free in a given order. During this time we should build up the cache of warm pages that you mentioned, assuming that shuffling is not enabled.

I was thinking about something like retaining pages to a lower watermark here. Looks like we still might have few lower order pages in free list if they are not merged to orders which are hinted.

Quoted 4 lines

As far as further optimizations I don't think there is anything here that prevents us from doing that. For now I am focused on just getting the basics in place so we have a foundation to start from.

Agree. Thanks for explaining.

Best rgards,
Pankaj

Quoted 6 lines

Thanks.

- Alex

#15 lore raw
Quoted 71 lines · Pankaj Gupta
Quoted 60 lines · Pankaj Gupta
Quoted 43 lines
Quoted 27 lines

This series provides an asynchronous means of reporting to a hypervisor that a guest page is no longer in use and can have the data associated with it dropped. To do this I have implemented functionality that allows for what I am referring to as unused page reporting

The functionality for this is fairly simple. When enabled it will allocate
statistics to track the number of reported pages in a given free area. When the number of free pages exceeds this value plus a high water value, currently 32, it will begin performing page reporting which consists of pulling pages off of free list and placing them into a scatter list. The scatterlist is then given to the page reporting device and it will perform
the required action to make the pages "reported", in the case of virtio-balloon this results in the pages being madvised as MADV_DONTNEED and as such they are forced out of the guest. After this they are placed back on the free list, and an additional bit is added if they are not merged indicating that they are a reported buddy page instead of a standard buddy page. The cycle then repeats with additional non-reported pages being pulled until the free areas all consist of reported pages.

I am leaving a number of things hard-coded such as limiting the lowest order processed to PAGEBLOCK_ORDER, and have left it up to the guest to determine what the limit is on how many pages it wants to allocate to process the hints. The upper limit for this is based on the size of the queue used to store the scattergather list.

Quoted 5 lines

My primary testing has just been to verify the memory is being freed after
allocation by running memhog 40g on a 40g guest and watching the total free memory via /proc/meminfo on the host. With this I have verified most of the memory is freed after each iteration.

I tried to go through the entire patch series. I can see you reported a -3.27 drop from the baseline. If its because of re-faulting the page after host has freed them? Can we avoid freeing all the pages from the guest free_area
and keep some pages(maybe some mixed order), so that next allocation is done from
the guest itself than faulting to host. This will work with real workload where
allocation and deallocation happen at regular intervals.

Quoted 5 lines

This can be further optimized based on other factors like host memory pressure etc.

Thanks,
Pankaj

When I originally started implementing and testing this code I was seeing less than a 1% regression. I didn't feel like that was really an accurate result since it wasn't putting much stress on the changed code so I have modified my tests and kernel so that I have memory shuffting and THP enabled. In addition I have gone out of my way to lock things down to a single NUMA node on my host system as the code I had would sometimes perform better than baseline when running the test due to the fact that memory was being freed back to the hose and then reallocated which actually allowed for better NUMA locality.

Quoted 10 lines

The general idea was I wanted to know what the worst case penalty would be for running this code, and it turns out most of that is just the cost of faulting back in the pages. By enabling memory shuffling I am forcing the memory to churn as pages are added to both the head and tail of the free_list. The test itself was modified so that it didn't allocate order 0 pages and instead was allocating transparent huge pages so the effects were as visible as possible. Without that the page faulting overhead would mostly fall into the noise of having to allocate the memory as order 0 pages, that is what I had essentially seen earlier when I was running the stock page_fault1 test.

Quoted 2 lines

Right. I think the reason is this test is allocating THP's in guest, host side you are still using order 0 pages, I assume?

No, on host side they should be huge pages as well. Most of the cost for the fault is the page zeroing I believe since we are having to zero a 2MB page twice, once in the host and once in the guest.

Basically if I disable THP in the guest the results are roughly half what they are with THP enabled, and the difference between the patchset and baseline drops to less than 1%.

Quoted 14 lines
Quoted 5 lines

This code does no hinting on anything smaller than either MAX_ORDER - 1 or HUGETLB_PAGE_ORDER pages, and it only starts when there are at least 32 of them available to hint on. This results in us not starting to perform the hinting until there is 64MB to 128MB of memory sitting in the higher order regions of the zone.

o.k

Quoted 5 lines

The hinting itself stops as soon as we run out of unhinted pages to pull from. When this occurs we let any pages that are freed after that accumulate until we get back to 32 pages being free in a given order. During this time we should build up the cache of warm pages that you mentioned, assuming that shuffling is not enabled.

Quoted 3 lines

I was thinking about something like retaining pages to a lower watermark here. Looks like we still might have few lower order pages in free list if they are not merged to orders which are hinted.

Right. We should have everything below the reporting order untouched and as such it will not be faulted. It is only if the page gets merged back up to reporting order that we will reported it, and only if we have at least 32 of them available.

Quoted 8 lines
Quoted 3 lines

As far as further optimizations I don't think there is anything here that prevents us from doing that. For now I am focused on just getting the basics in place so we have a foundation to start from.

Agree. Thanks for explaining.

Best rgards,
Pankaj

Thanks.

- Alex

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]