2023-12-13 18:28:16

by Stefan Roesch

[permalink] [raw]
Subject: [PATCH v4 0/4] mm/ksm: Add ksm advisor

What is the KSM advisor?
=========================
The ksm advisor automatically manages the pages_to_scan setting to
achieve a target scan time. The target scan time defines how many seconds
it should take to scan all the candidate KSM pages. In other words the
pages_to_scan rate is changed by the advisor to achieve the target scan
time.

Why do we need a KSM advisor?
==============================
The number of candidate pages for KSM is dynamic. It can often be observed
that during the startup of an application more candidate pages need to be
processed. Without an advisor the pages_to_scan parameter needs to be
sized for the maximum number of candidate pages. With the scan time
advisor the pages_to_scan parameter based can be changed based on demand.

Algorithm
==========
The algorithm calculates the change value based on the target scan time
and the previous scan time. To avoid pertubations an exponentially
weighted moving average is applied.

The algorithm has a max and min
value to:
- guarantee responsiveness to changes
- to limit CPU resource consumption

Parameters to influence the KSM scan advisor
=============================================
The respective parameters are:
- ksm_advisor_mode
0: None (default), 1: scan time advisor
- ksm_advisor_target_scan_time
how many seconds a scan should of all candidate pages take
- ksm_advisor_max_cpu
upper limit for the cpu usage in percent of the ksmd background thread

The initial value and the max value for the pages_to_scan parameter can
be limited with:
- ksm_advisor_min_pages_to_scan
minimum value for pages_to_scan per batch
- ksm_advisor_max_pages_to_scan
maximum value for pages_to_scan per batch

The default settings for the above two parameters should be suitable for
most workloads.

The parameters are exposed as knobs in /sys/kernel/mm/ksm. By default the
scan time advisor is disabled.

Currently there are two advisors:
- none and
- scan-time.

Resource savings
=================
Tests with various workloads have shown considerable CPU savings. Most
of the workloads I have investigated have more candidate pages during
startup. Once the workload is stable in terms of memory, the number of
candidate pages is reduced. Without the advisor, the pages_to_scan needs
to be sized for the maximum number of candidate pages. So having this
advisor definitely helps in reducing CPU consumption.

For the instagram workload, the advisor achieves a 25% CPU reduction.
Once the memory is stable, the pages_to_scan parameter gets reduced to
about 40% of its max value.

The new advisor works especially well if the smart scan feature is also
enabled.

How is defining a target scan time better?
===========================================
For an administrator it is more logical to set a target scan time.. The
administrator can determine how many pages are scanned on each scan.
Therefore setting a target scan time makes more sense.

In addition the administrator might have a good idea about the memory
sizing of its respective workloads.

Setting cpu limits is easier than setting The pages_to_scan parameter. The
pages_to_scan parameter is per batch. For the administrator it is difficult
to set the pages_to_scan parameter.

Tracing
=======
A new tracing event has been added for the scan time advisor. The new
trace event is called ksm_advisor. It reports the scan time, the new
pages_to_scan setting and the cpu usage of the ksmd background thread.

Other approaches
=================

Approach 1: Adapt pages_to_scan after processing each batch. If KSM
merges pages, increase the scan rate, if less KSM pages, reduce the
the pages_to_scan rate. This doesn't work too well. While it increases
the pages_to_scan for a short period, but generally it ends up with a
too low pages_to_scan rate.

Approach 2: Adapt pages_to_scan after each scan. The problem with that
approach is that the calculated scan rate tends to be high. The more
aggressive KSM scans, the more pages it can de-duplicate.

There have been earlier attempts at an advisor:
propose auto-run mode of ksm and its tests
(https://marc.info/?l=linux-mm&m=166029880214485&w=2)


Changes:
========
V4:
- rename ksm_advisor_min_pages to ksm_advisor_min_pages_to_scan
- rename ksm_advisor_max_pages to ksm_advisor_max_pages_to_scan
- folded init_advisor() into set_advisor_defaults()
- moved set_advisor_defaults() to second patch
- Fixed long division for 32 bit platforms in scan_time_advisor()
- folded stop_advisor_scan() into scan_time_advisor()
- renamed run_advisor() to stop_advisor_scan()
- Fixed typo
- Added documentation for min and max cpu and how they are used in
the scan time advisor calculation

V3:
- Use string parameters for advisor mode
- Removed min cpu load sysfs knob
- dropped unused enums in ksm_advisor_type
- renamed KSM_ADVISOR_LAST to KSM_ADVISOR_COUNT
- init_advisor() is needed but changed how it is initialized
- don't allow to change pages_to_scan parameter when scan-time advisor
is enabled
- add ksm_advisor_start_scan() and ksm_advisor_stop_scan() functions
to calculate scan time
- removed scan time parameter to scan_time_advisor() function

V2:
- Use functions for long long calculations to support 32 bit platforms
- Use cpu min and cpu max settings for the advisor instead of the pages
min and max parameters.
- pages min and max values are now used for the initial and max values.
Generally they are not required to be changed.
- Add cpu percent usage value to tracepoint definition
- Update documentation for cpu min and cpu max values
- Update commit messages for the above changes



*** BLURB HERE ***

Stefan Roesch (4):
mm/ksm: add ksm advisor
mm/ksm: add sysfs knobs for advisor
mm/ksm: add tracepoint for ksm advisor
mm/ksm: document ksm advisor and its sysfs knobs

Documentation/admin-guide/mm/ksm.rst | 55 +++++
include/trace/events/ksm.h | 33 +++
mm/ksm.c | 298 ++++++++++++++++++++++++++-
3 files changed, 385 insertions(+), 1 deletion(-)


base-commit: 12d04a7bf0da67321229d2bc8b1a7074d65415a9
--
2.39.3


2023-12-13 18:28:21

by Stefan Roesch

[permalink] [raw]
Subject: [PATCH v4 4/4] mm/ksm: document ksm advisor and its sysfs knobs

This documents the KSM advisor and its new knobs in /sys/fs/kernel/mm.

Signed-off-by: Stefan Roesch <[email protected]>
Acked-by: David Hildenbrand <[email protected]>
---
Documentation/admin-guide/mm/ksm.rst | 55 ++++++++++++++++++++++++++++
1 file changed, 55 insertions(+)

diff --git a/Documentation/admin-guide/mm/ksm.rst b/Documentation/admin-guide/mm/ksm.rst
index e59231ac6bb71..a639cac124777 100644
--- a/Documentation/admin-guide/mm/ksm.rst
+++ b/Documentation/admin-guide/mm/ksm.rst
@@ -80,6 +80,9 @@ pages_to_scan
how many pages to scan before ksmd goes to sleep
e.g. ``echo 100 > /sys/kernel/mm/ksm/pages_to_scan``.

+ The pages_to_scan value cannot be changed if ``advisor_mode`` has
+ been set to scan-time.
+
Default: 100 (chosen for demonstration purposes)

sleep_millisecs
@@ -164,6 +167,29 @@ smart_scan
optimization is enabled. The ``pages_skipped`` metric shows how
effective the setting is.

+advisor_mode
+ The ``advisor_mode`` selects the current advisor. Two modes are
+ supported: none and scan-time. The default is none. By setting
+ ``advisor_mode`` to scan-time, the scan time advisor is enabled.
+ The section about ``advisor`` explains in detail how the scan time
+ advisor works.
+
+adivsor_max_cpu
+ specifies the upper limit of the cpu percent usage of the ksmd
+ background thread. The default is 70.
+
+advisor_target_scan_time
+ specifies the target scan time in seconds to scan all the candidate
+ pages. The default value is 200 seconds.
+
+advisor_min_pages_to_scan
+ specifies the lower limit of the ``pages_to_scan`` parameter of the
+ scan time advisor. The default is 500.
+
+adivsor_max_pages_to_scan
+ specifies the upper limit of the ``pages_to_scan`` parameter of the
+ scan time advisor. The default is 30000.
+
The effectiveness of KSM and MADV_MERGEABLE is shown in ``/sys/kernel/mm/ksm/``:

general_profit
@@ -263,6 +289,35 @@ ksm_swpin_copy
note that KSM page might be copied when swapping in because do_swap_page()
cannot do all the locking needed to reconstitute a cross-anon_vma KSM page.

+Advisor
+=======
+
+The number of candidate pages for KSM is dynamic. It can be often observed
+that during the startup of an application more candidate pages need to be
+processed. Without an advisor the ``pages_to_scan`` parameter needs to be
+sized for the maximum number of candidate pages. The scan time advisor can
+changes the ``pages_to_scan`` parameter based on demand.
+
+The advisor can be enabled, so KSM can automatically adapt to changes in the
+number of candidate pages to scan. Two advisors are implemented: none and
+scan-time. With none, no advisor is enabled. The default is none.
+
+The scan time advisor changes the ``pages_to_scan`` parameter based on the
+observed scan times. The possible values for the ``pages_to_scan`` parameter is
+limited by the ``advisor_max_cpu`` parameter. In addition there is also the
+``advisor_target_scan_time`` parameter. This parameter sets the target time to
+scan all the KSM candidate pages. The parameter ``advisor_target_scan_time``
+decides how aggressive the scan time advisor scans candidate pages. Lower
+values make the scan time advisor to scan more aggresively. This is the most
+important parameter for the configuration of the scan time advisor.
+
+The initial value and the maximum value can be changed with
+``advisor_min_pages_to_scan`` and ``advisor_max_pages_to_scan``. The default
+values are sufficient for most workloads and use cases.
+
+The ``pages_to_scan`` parameter is re-calculated after a scan has been completed.
+
+
--
Izik Eidus,
Hugh Dickins, 17 Nov 2009
--
2.39.3

2023-12-13 18:28:32

by Stefan Roesch

[permalink] [raw]
Subject: [PATCH v4 1/4] mm/ksm: add ksm advisor

This adds the ksm advisor. The ksm advisor automatically manages the
pages_to_scan setting to achieve a target scan time. The target scan
time defines how many seconds it should take to scan all the candidate
KSM pages. In other words the pages_to_scan rate is changed by the
advisor to achieve the target scan time. The algorithm has a max and min
value to:
- guarantee responsiveness to changes
- limit CPU resource consumption

The respective parameters are:
- ksm_advisor_target_scan_time (how many seconds a scan should take)
- ksm_advisor_max_cpu (maximum value for cpu percent usage)

- ksm_advisor_min_pages (minimum value for pages_to_scan per batch)
- ksm_advisor_max_pages (maximum value for pages_to_scan per batch)

The algorithm calculates the change value based on the target scan time
and the previous scan time. To avoid pertubations an exponentially
weighted moving average is applied.

The advisor is managed by two main parameters: target scan time,
cpu max time for the ksmd background thread. These parameters determine
how aggresive ksmd scans.

In addition there are min and max values for the pages_to_scan parameter
to make sure that its initial and max values are not set too low or too
high. This ensures that it is able to react to changes quickly enough.

The default values are:
- target scan time: 200 secs
- max cpu: 70%
- min pages: 500
- max pages: 30000

By default the advisor is disabled. Currently there are two advisors:
none and scan-time.

Tests with various workloads have shown considerable CPU savings. Most
of the workloads I have investigated have more candidate pages during
startup, once the workload is stable in terms of memory, the number of
candidate pages is reduced. Without the advisor, the pages_to_scan needs
to be sized for the maximum number of candidate pages. So having this
advisor definitely helps in reducing CPU consumption.

For the instagram workload, the advisor achieves a 25% CPU reduction.
Once the memory is stable, the pages_to_scan parameter gets reduced to
about 40% of its max value.

Signed-off-by: Stefan Roesch <[email protected]>
---
mm/ksm.c | 161 ++++++++++++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 160 insertions(+), 1 deletion(-)

diff --git a/mm/ksm.c b/mm/ksm.c
index 7efcc68ccc6ea..4f7b71a1f3112 100644
--- a/mm/ksm.c
+++ b/mm/ksm.c
@@ -21,6 +21,7 @@
#include <linux/sched.h>
#include <linux/sched/mm.h>
#include <linux/sched/coredump.h>
+#include <linux/sched/cputime.h>
#include <linux/rwsem.h>
#include <linux/pagemap.h>
#include <linux/rmap.h>
@@ -248,6 +249,9 @@ static struct kmem_cache *rmap_item_cache;
static struct kmem_cache *stable_node_cache;
static struct kmem_cache *mm_slot_cache;

+/* Default number of pages to scan per batch */
+#define DEFAULT_PAGES_TO_SCAN 100
+
/* The number of pages scanned */
static unsigned long ksm_pages_scanned;

@@ -276,7 +280,7 @@ static unsigned int ksm_stable_node_chains_prune_millisecs = 2000;
static int ksm_max_page_sharing = 256;

/* Number of pages ksmd should scan in one batch */
-static unsigned int ksm_thread_pages_to_scan = 100;
+static unsigned int ksm_thread_pages_to_scan = DEFAULT_PAGES_TO_SCAN;

/* Milliseconds ksmd should sleep between batches */
static unsigned int ksm_thread_sleep_millisecs = 20;
@@ -297,6 +301,155 @@ unsigned long ksm_zero_pages;
/* The number of pages that have been skipped due to "smart scanning" */
static unsigned long ksm_pages_skipped;

+/* Don't scan more than max pages per batch. */
+static unsigned long ksm_advisor_max_pages = 30000;
+
+/* At least scan this many pages per batch. */
+static unsigned long ksm_advisor_min_pages = 500;
+
+/* Min CPU for scanning pages per scan */
+static unsigned int ksm_advisor_min_cpu = 10;
+
+/* Max CPU for scanning pages per scan */
+static unsigned int ksm_advisor_max_cpu = 70;
+
+/* Target scan time in seconds to analyze all KSM candidate pages. */
+static unsigned long ksm_advisor_target_scan_time = 200;
+
+/* Exponentially weighted moving average. */
+#define EWMA_WEIGHT 30
+
+/**
+ * struct advisor_ctx - metadata for KSM advisor
+ * @start_scan: start time of the current scan
+ * @scan_time: scan time of previous scan
+ * @change: change in percent to pages_to_scan parameter
+ * @cpu_time: cpu time consumed by the ksmd thread in the previous scan
+ */
+struct advisor_ctx {
+ ktime_t start_scan;
+ unsigned long scan_time;
+ unsigned long change;
+ unsigned long long cpu_time;
+};
+static struct advisor_ctx advisor_ctx;
+
+/* Define different advisor's */
+enum ksm_advisor_type {
+ KSM_ADVISOR_NONE,
+ KSM_ADVISOR_SCAN_TIME,
+};
+static enum ksm_advisor_type ksm_advisor;
+
+static inline void advisor_start_scan(void)
+{
+ if (ksm_advisor == KSM_ADVISOR_SCAN_TIME)
+ advisor_ctx.start_scan = ktime_get();
+}
+
+/*
+ * Use previous scan time if available, otherwise use current scan time as an
+ * approximation for the previous scan time.
+ */
+static inline unsigned long prev_scan_time(struct advisor_ctx *ctx,
+ unsigned long scan_time)
+{
+ return ctx->scan_time ? ctx->scan_time : scan_time;
+}
+
+/* Calculate exponential weighted moving average */
+static unsigned long ewma(unsigned long prev, unsigned long curr)
+{
+ return ((100 - EWMA_WEIGHT) * prev + EWMA_WEIGHT * curr) / 100;
+}
+
+/*
+ * The scan time advisor is based on the current scan rate and the target
+ * scan rate.
+ *
+ * new_pages_to_scan = pages_to_scan * (scan_time / target_scan_time)
+ *
+ * To avoid perturbations it calculates a change factor of previous changes.
+ * A new change factor is calculated for each iteration and it uses an
+ * exponentially weighted moving average. The new pages_to_scan value is
+ * multiplied with that change factor:
+ *
+ * new_pages_to_scan *= change facor
+ *
+ * The new_pages_to_scan value is limited by the cpu min and max values. It
+ * calculates the cpu percent for the last scan and calculates the new
+ * estimated cpu percent cost for the next scan. That value is capped by the
+ * cpu min and max setting.
+ *
+ * In addition the new pages_to_scan value is capped by the max and min
+ * limits.
+ */
+static void scan_time_advisor(void)
+{
+ unsigned int cpu_percent;
+ unsigned long cpu_time;
+ unsigned long cpu_time_diff;
+ unsigned long cpu_time_diff_ms;
+ unsigned long pages;
+ unsigned long per_page_cost;
+ unsigned long factor;
+ unsigned long change;
+ unsigned long last_scan_time;
+ unsigned long scan_time;
+
+ /* Convert scan time to seconds */
+ scan_time = div_s64(ktime_ms_delta(ktime_get(), advisor_ctx.start_scan),
+ MSEC_PER_SEC);
+ scan_time = scan_time ? scan_time : 1;
+
+ /* Calculate CPU consumption of ksmd background thread */
+ cpu_time = task_sched_runtime(current);
+ cpu_time_diff = cpu_time - advisor_ctx.cpu_time;
+ cpu_time_diff_ms = cpu_time_diff / 1000 / 1000;
+
+ cpu_percent = (cpu_time_diff_ms * 100) / (scan_time * 1000);
+ cpu_percent = cpu_percent ? cpu_percent : 1;
+ last_scan_time = prev_scan_time(&advisor_ctx, scan_time);
+
+ /* Calculate scan time as percentage of target scan time */
+ factor = ksm_advisor_target_scan_time * 100 / scan_time;
+ factor = factor ? factor : 1;
+
+ /*
+ * Calculate scan time as percentage of last scan time and use
+ * exponentially weighted average to smooth it
+ */
+ change = scan_time * 100 / last_scan_time;
+ change = change ? change : 1;
+ change = ewma(advisor_ctx.change, change);
+
+ /* Calculate new scan rate based on target scan rate. */
+ pages = ksm_thread_pages_to_scan * 100 / factor;
+ /* Update pages_to_scan by weighted change percentage. */
+ pages = pages * change / 100;
+
+ /* Cap new pages_to_scan value */
+ per_page_cost = ksm_thread_pages_to_scan / cpu_percent;
+ per_page_cost = per_page_cost ? per_page_cost : 1;
+
+ pages = min(pages, per_page_cost * ksm_advisor_max_cpu);
+ pages = max(pages, per_page_cost * ksm_advisor_min_cpu);
+ pages = min(pages, ksm_advisor_max_pages);
+
+ /* Update advisor context */
+ advisor_ctx.change = change;
+ advisor_ctx.scan_time = scan_time;
+ advisor_ctx.cpu_time = cpu_time;
+
+ ksm_thread_pages_to_scan = pages;
+}
+
+static void advisor_stop_scan(void)
+{
+ if (ksm_advisor == KSM_ADVISOR_SCAN_TIME)
+ scan_time_advisor();
+}
+
#ifdef CONFIG_NUMA
/* Zeroed when merging across nodes is not allowed */
static unsigned int ksm_merge_across_nodes = 1;
@@ -2401,6 +2554,7 @@ static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page)

mm_slot = ksm_scan.mm_slot;
if (mm_slot == &ksm_mm_head) {
+ advisor_start_scan();
trace_ksm_start_scan(ksm_scan.seqnr, ksm_rmap_items);

/*
@@ -2558,6 +2712,8 @@ static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page)
if (mm_slot != &ksm_mm_head)
goto next_mm;

+ advisor_stop_scan();
+
trace_ksm_stop_scan(ksm_scan.seqnr, ksm_rmap_items);
ksm_scan.seqnr++;
return NULL;
@@ -3244,6 +3400,9 @@ static ssize_t pages_to_scan_store(struct kobject *kobj,
unsigned int nr_pages;
int err;

+ if (ksm_advisor != KSM_ADVISOR_NONE)
+ return -EINVAL;
+
err = kstrtouint(buf, 10, &nr_pages);
if (err)
return -EINVAL;
--
2.39.3

2023-12-18 11:29:56

by David Hildenbrand

[permalink] [raw]
Subject: Re: [PATCH v4 1/4] mm/ksm: add ksm advisor

On 13.12.23 19:27, Stefan Roesch wrote:
> This adds the ksm advisor. The ksm advisor automatically manages the
> pages_to_scan setting to achieve a target scan time. The target scan
> time defines how many seconds it should take to scan all the candidate
> KSM pages. In other words the pages_to_scan rate is changed by the
> advisor to achieve the target scan time. The algorithm has a max and min
> value to:
> - guarantee responsiveness to changes
> - limit CPU resource consumption
>
> The respective parameters are:
> - ksm_advisor_target_scan_time (how many seconds a scan should take)
> - ksm_advisor_max_cpu (maximum value for cpu percent usage)
>
> - ksm_advisor_min_pages (minimum value for pages_to_scan per batch)
> - ksm_advisor_max_pages (maximum value for pages_to_scan per batch)
>
> The algorithm calculates the change value based on the target scan time
> and the previous scan time. To avoid pertubations an exponentially
> weighted moving average is applied.
>
> The advisor is managed by two main parameters: target scan time,
> cpu max time for the ksmd background thread. These parameters determine
> how aggresive ksmd scans.
>
> In addition there are min and max values for the pages_to_scan parameter
> to make sure that its initial and max values are not set too low or too
> high. This ensures that it is able to react to changes quickly enough.
>
> The default values are:
> - target scan time: 200 secs
> - max cpu: 70%
> - min pages: 500
> - max pages: 30000
>
> By default the advisor is disabled. Currently there are two advisors:
> none and scan-time.
>
> Tests with various workloads have shown considerable CPU savings. Most
> of the workloads I have investigated have more candidate pages during
> startup, once the workload is stable in terms of memory, the number of
> candidate pages is reduced. Without the advisor, the pages_to_scan needs
> to be sized for the maximum number of candidate pages. So having this
> advisor definitely helps in reducing CPU consumption.
>
> For the instagram workload, the advisor achieves a 25% CPU reduction.
> Once the memory is stable, the pages_to_scan parameter gets reduced to
> about 40% of its max value.
>
> Signed-off-by: Stefan Roesch <[email protected]>
> ---
> mm/ksm.c | 161 ++++++++++++++++++++++++++++++++++++++++++++++++++++++-
> 1 file changed, 160 insertions(+), 1 deletion(-)
>
> diff --git a/mm/ksm.c b/mm/ksm.c
> index 7efcc68ccc6ea..4f7b71a1f3112 100644
> --- a/mm/ksm.c
> +++ b/mm/ksm.c
> @@ -21,6 +21,7 @@
> #include <linux/sched.h>
> #include <linux/sched/mm.h>
> #include <linux/sched/coredump.h>
> +#include <linux/sched/cputime.h>
> #include <linux/rwsem.h>
> #include <linux/pagemap.h>
> #include <linux/rmap.h>
> @@ -248,6 +249,9 @@ static struct kmem_cache *rmap_item_cache;
> static struct kmem_cache *stable_node_cache;
> static struct kmem_cache *mm_slot_cache;
>
> +/* Default number of pages to scan per batch */
> +#define DEFAULT_PAGES_TO_SCAN 100
> +
> /* The number of pages scanned */
> static unsigned long ksm_pages_scanned;
>
> @@ -276,7 +280,7 @@ static unsigned int ksm_stable_node_chains_prune_millisecs = 2000;
> static int ksm_max_page_sharing = 256;
>
> /* Number of pages ksmd should scan in one batch */
> -static unsigned int ksm_thread_pages_to_scan = 100;
> +static unsigned int ksm_thread_pages_to_scan = DEFAULT_PAGES_TO_SCAN;
>
> /* Milliseconds ksmd should sleep between batches */
> static unsigned int ksm_thread_sleep_millisecs = 20;
> @@ -297,6 +301,155 @@ unsigned long ksm_zero_pages;
> /* The number of pages that have been skipped due to "smart scanning" */
> static unsigned long ksm_pages_skipped;
>
> +/* Don't scan more than max pages per batch. */
> +static unsigned long ksm_advisor_max_pages = 30000;
> +
> +/* At least scan this many pages per batch. */
> +static unsigned long ksm_advisor_min_pages = 500;
> +
> +/* Min CPU for scanning pages per scan */
> +static unsigned int ksm_advisor_min_cpu = 10;

That will never be modified, right? Either mark it const or just turn it
into a define.

[...]

> +/*
> + * The scan time advisor is based on the current scan rate and the target
> + * scan rate.
> + *
> + * new_pages_to_scan = pages_to_scan * (scan_time / target_scan_time)
> + *
> + * To avoid perturbations it calculates a change factor of previous changes.
> + * A new change factor is calculated for each iteration and it uses an
> + * exponentially weighted moving average. The new pages_to_scan value is
> + * multiplied with that change factor:
> + *
> + * new_pages_to_scan *= change facor
> + *
> + * The new_pages_to_scan value is limited by the cpu min and max values. It
> + * calculates the cpu percent for the last scan and calculates the new
> + * estimated cpu percent cost for the next scan. That value is capped by the
> + * cpu min and max setting.
> + *
> + * In addition the new pages_to_scan value is capped by the max and min
> + * limits.
> + */
> +static void scan_time_advisor(void)
> +{
> + unsigned int cpu_percent;
> + unsigned long cpu_time;
> + unsigned long cpu_time_diff;
> + unsigned long cpu_time_diff_ms;
> + unsigned long pages;
> + unsigned long per_page_cost;
> + unsigned long factor;
> + unsigned long change;
> + unsigned long last_scan_time;
> + unsigned long scan_time;
> +
> + /* Convert scan time to seconds */
> + scan_time = div_s64(ktime_ms_delta(ktime_get(), advisor_ctx.start_scan),
> + MSEC_PER_SEC);
> + scan_time = scan_time ? scan_time : 1;
> +
> + /* Calculate CPU consumption of ksmd background thread */
> + cpu_time = task_sched_runtime(current);
> + cpu_time_diff = cpu_time - advisor_ctx.cpu_time;
> + cpu_time_diff_ms = cpu_time_diff / 1000 / 1000;
> +
> + cpu_percent = (cpu_time_diff_ms * 100) / (scan_time * 1000);
> + cpu_percent = cpu_percent ? cpu_percent : 1;
> + last_scan_time = prev_scan_time(&advisor_ctx, scan_time);

I'd simply inline prev_scan_time() here and get rid of it. Whatever you
think is best.


Acked-by: David Hildenbrand <[email protected]>

--
Cheers,

David / dhildenb


2023-12-18 17:28:08

by Stefan Roesch

[permalink] [raw]
Subject: Re: [PATCH v4 1/4] mm/ksm: add ksm advisor



On Mon, Dec 18, 2023, at 3:29 AM, David Hildenbrand wrote:
> On 13.12.23 19:27, Stefan Roesch wrote:
>> This adds the ksm advisor. The ksm advisor automatically manages the
>> pages_to_scan setting to achieve a target scan time. The target scan
>> time defines how many seconds it should take to scan all the candidate
>> KSM pages. In other words the pages_to_scan rate is changed by the
>> advisor to achieve the target scan time. The algorithm has a max and min
>> value to:
>> - guarantee responsiveness to changes
>> - limit CPU resource consumption
>>
>> The respective parameters are:
>> - ksm_advisor_target_scan_time (how many seconds a scan should take)
>> - ksm_advisor_max_cpu (maximum value for cpu percent usage)
>>
>> - ksm_advisor_min_pages (minimum value for pages_to_scan per batch)
>> - ksm_advisor_max_pages (maximum value for pages_to_scan per batch)
>>
>> The algorithm calculates the change value based on the target scan time
>> and the previous scan time. To avoid pertubations an exponentially
>> weighted moving average is applied.
>>
>> The advisor is managed by two main parameters: target scan time,
>> cpu max time for the ksmd background thread. These parameters determine
>> how aggresive ksmd scans.
>>
>> In addition there are min and max values for the pages_to_scan parameter
>> to make sure that its initial and max values are not set too low or too
>> high. This ensures that it is able to react to changes quickly enough.
>>
>> The default values are:
>> - target scan time: 200 secs
>> - max cpu: 70%
>> - min pages: 500
>> - max pages: 30000
>>
>> By default the advisor is disabled. Currently there are two advisors:
>> none and scan-time.
>>
>> Tests with various workloads have shown considerable CPU savings. Most
>> of the workloads I have investigated have more candidate pages during
>> startup, once the workload is stable in terms of memory, the number of
>> candidate pages is reduced. Without the advisor, the pages_to_scan needs
>> to be sized for the maximum number of candidate pages. So having this
>> advisor definitely helps in reducing CPU consumption.
>>
>> For the instagram workload, the advisor achieves a 25% CPU reduction.
>> Once the memory is stable, the pages_to_scan parameter gets reduced to
>> about 40% of its max value.
>>
>> Signed-off-by: Stefan Roesch <[email protected]>
>> ---
>> mm/ksm.c | 161 ++++++++++++++++++++++++++++++++++++++++++++++++++++++-
>> 1 file changed, 160 insertions(+), 1 deletion(-)
>>
>> diff --git a/mm/ksm.c b/mm/ksm.c
>> index 7efcc68ccc6ea..4f7b71a1f3112 100644
>> --- a/mm/ksm.c
>> +++ b/mm/ksm.c
>> @@ -21,6 +21,7 @@
>> #include <linux/sched.h>
>> #include <linux/sched/mm.h>
>> #include <linux/sched/coredump.h>
>> +#include <linux/sched/cputime.h>
>> #include <linux/rwsem.h>
>> #include <linux/pagemap.h>
>> #include <linux/rmap.h>
>> @@ -248,6 +249,9 @@ static struct kmem_cache *rmap_item_cache;
>> static struct kmem_cache *stable_node_cache;
>> static struct kmem_cache *mm_slot_cache;
>>
>> +/* Default number of pages to scan per batch */
>> +#define DEFAULT_PAGES_TO_SCAN 100
>> +
>> /* The number of pages scanned */
>> static unsigned long ksm_pages_scanned;
>>
>> @@ -276,7 +280,7 @@ static unsigned int ksm_stable_node_chains_prune_millisecs = 2000;
>> static int ksm_max_page_sharing = 256;
>>
>> /* Number of pages ksmd should scan in one batch */
>> -static unsigned int ksm_thread_pages_to_scan = 100;
>> +static unsigned int ksm_thread_pages_to_scan = DEFAULT_PAGES_TO_SCAN;
>>
>> /* Milliseconds ksmd should sleep between batches */
>> static unsigned int ksm_thread_sleep_millisecs = 20;
>> @@ -297,6 +301,155 @@ unsigned long ksm_zero_pages;
>> /* The number of pages that have been skipped due to "smart scanning" */
>> static unsigned long ksm_pages_skipped;
>>
>> +/* Don't scan more than max pages per batch. */
>> +static unsigned long ksm_advisor_max_pages = 30000;
>> +
>> +/* At least scan this many pages per batch. */
>> +static unsigned long ksm_advisor_min_pages = 500;
>> +
>> +/* Min CPU for scanning pages per scan */
>> +static unsigned int ksm_advisor_min_cpu = 10;
>
> That will never be modified, right? Either mark it const or just turn it
> into a define.
>


Changed it to a define.

> [...]
>
>> +/*
>> + * The scan time advisor is based on the current scan rate and the target
>> + * scan rate.
>> + *
>> + * new_pages_to_scan = pages_to_scan * (scan_time / target_scan_time)
>> + *
>> + * To avoid perturbations it calculates a change factor of previous changes.
>> + * A new change factor is calculated for each iteration and it uses an
>> + * exponentially weighted moving average. The new pages_to_scan value is
>> + * multiplied with that change factor:
>> + *
>> + * new_pages_to_scan *= change facor
>> + *
>> + * The new_pages_to_scan value is limited by the cpu min and max values. It
>> + * calculates the cpu percent for the last scan and calculates the new
>> + * estimated cpu percent cost for the next scan. That value is capped by the
>> + * cpu min and max setting.
>> + *
>> + * In addition the new pages_to_scan value is capped by the max and min
>> + * limits.
>> + */
>> +static void scan_time_advisor(void)
>> +{
>> + unsigned int cpu_percent;
>> + unsigned long cpu_time;
>> + unsigned long cpu_time_diff;
>> + unsigned long cpu_time_diff_ms;
>> + unsigned long pages;
>> + unsigned long per_page_cost;
>> + unsigned long factor;
>> + unsigned long change;
>> + unsigned long last_scan_time;
>> + unsigned long scan_time;
>> +
>> + /* Convert scan time to seconds */
>> + scan_time = div_s64(ktime_ms_delta(ktime_get(), advisor_ctx.start_scan),
>> + MSEC_PER_SEC);
>> + scan_time = scan_time ? scan_time : 1;
>> +
>> + /* Calculate CPU consumption of ksmd background thread */
>> + cpu_time = task_sched_runtime(current);
>> + cpu_time_diff = cpu_time - advisor_ctx.cpu_time;
>> + cpu_time_diff_ms = cpu_time_diff / 1000 / 1000;
>> +
>> + cpu_percent = (cpu_time_diff_ms * 100) / (scan_time * 1000);
>> + cpu_percent = cpu_percent ? cpu_percent : 1;
>> + last_scan_time = prev_scan_time(&advisor_ctx, scan_time);
>
> I'd simply inline prev_scan_time() here and get rid of it. Whatever you
> think is best.
>

I think prev_scan_time is a bit more expressive.

>
> Acked-by: David Hildenbrand <[email protected]>
>
> --
> Cheers,
>
> David / dhildenb