Skip to contentSkip to conversation

introduce memory hinting API for external process

RFC Superseded Minchan Kim 13 participants 133 messages May 20, 2019 – May 30, 2019

Subsystems (14)

v1 of 9 Superseded Latest is v9 →

lore
Share & tools
lore
#0 lore raw

cover introduce memory hinting API for external process

- Background

The Android terminology used for forking a new process and starting an app from scratch is a cold start, while resuming an existing app is a hot start. While we continually try to improve the performance of cold starts, hot starts will always be significantly less power hungry as well as faster so we are trying to make hot start more likely than cold start.

To increase hot start, Android userspace manages the order that apps should be killed in a process called ActivityManagerService. ActivityManagerService tracks every Android app or service that the user could be interacting with at any time and translates that into a ranked list for lmkd(low memory killer daemon). They are likely to be killed by lmkd if the system has to reclaim memory. In that sense they are similar to entries in any other cache. Those apps are kept alive for opportunistic performance improvements but those performance improvements will vary based on the memory requirements of individual workloads.

- Problem

Naturally, cached apps were dominant consumers of memory on the system. However, they were not significant consumers of swap even though they are good candidate for swap. Under investigation, swapping out only begins once the low zone watermark is hit and kswapd wakes up, but the overall allocation rate in the system might trip lmkd thresholds and cause a cached process to be killed(we measured performance swapping out vs. zapping the memory by killing a process. Unsurprisingly, zapping is 10x times faster even though we use zram which is much faster than real storage) so kill from lmkd will often satisfy the high zone watermark, resulting in very few pages actually being moved to swap.

- Approach

The approach we chose was to use a new interface to allow userspace to proactively reclaim entire processes by leveraging platform information. This allowed us to bypass the inaccuracy of the kernel’s LRUs for pages that are known to be cold from userspace and to avoid races with lmkd by reclaiming apps as soon as they entered the cached state. Additionally, it could provide many chances for platform to use much information to optimize memory efficiency.

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

To achieve the goal, the patchset introduce two new options for madvise. One is MADV_COOL which will deactive activated pages and the other is MADV_COLD which will reclaim private pages instantly. These new options complement MADV_DONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_DONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

This approach is similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to a centralized userspace daemon, and that daemon must be able to initiate reclaim on its own without any app involvement. To solve the concern, this patch introduces new syscall -

	struct pr_madvise_param {
		int size;
		const struct iovec *vec;
	}

	int process_madvise(int pidfd, ssize_t nr_elem, int *behavior,
				struct pr_madvise_param *restuls,
				struct pr_madvise_param *ranges,
				unsigned long flags);

The syscall get pidfd to give hints to external process and provides pair of result/ranges vector arguments so that it could give several hints to each address range all at once.

I guess others have different ideas about the naming of syscall and options so feel free to suggest better naming.

- Experiment

We did bunch of testing with several hundreds of real users, not artificial benchmark on android. We saw about 17% cold start decreasement without any significant battery/app startup latency issues. And with artificial benchmark which launches and switching apps, we saw average 7% app launching improvement, 18% less lmkd kill and good stat from vmstat.

A is vanilla and B is process_madvise.

                                       A          B      delta   ratio(%)
               allocstall_dma          0          0          0       0.00
           allocstall_movable       1464        457      -1007     -69.00
            allocstall_normal     263210     190763     -72447     -28.00
             allocstall_total     264674     191220     -73454     -28.00
          compact_daemon_wake      26912      25294      -1618      -7.00
                 compact_fail      17885      14151      -3734     -21.00
         compact_free_scanned 4204766409 3835994922 -368771487      -9.00
             compact_isolated    3446484    2967618    -478866     -14.00
      compact_migrate_scanned 1621336411 1324695710 -296640701     -19.00
                compact_stall      19387      15343      -4044     -21.00
              compact_success       1502       1192       -310     -21.00
kswapd_high_wmark_hit_quickly        234        184        -50     -22.00
            kswapd_inodesteal     221635     233093      11458       5.00
 kswapd_low_wmark_hit_quickly      66065      54009     -12056     -19.00
                   nr_dirtied     259934     296476      36542      14.00
  nr_vmscan_immediate_reclaim       2587       2356       -231      -9.00
              nr_vmscan_write    1274232    2661733    1387501     108.00
                   nr_written    1514060    2937560    1423500      94.00
                   pageoutrun      67561      55133     -12428     -19.00
                   pgactivate    2335060    1984882    -350178     -15.00
                  pgalloc_dma   13743011   14096463     353452       2.00
              pgalloc_movable          0          0          0       0.00
               pgalloc_normal   18742440   16802065   -1940375     -11.00
                pgalloc_total   32485451   30898528   -1586923      -5.00
                 pgdeactivate    4262210    2930670   -1331540     -32.00
                      pgfault   30812334   31085065     272731       0.00
                       pgfree   33553970   31765164   -1788806      -6.00
                 pginodesteal      33411      15084     -18327     -55.00
                  pglazyfreed          0          0          0       0.00
                   pgmajfault     551312    1508299     956987     173.00
               pgmigrate_fail      43927      29330     -14597     -34.00
            pgmigrate_success    1399851    1203922    -195929     -14.00
                       pgpgin   24141776   19032156   -5109620     -22.00
                      pgpgout     959344    1103316     143972      15.00
                 pgpgoutclean    4639732    3765868    -873864     -19.00
                     pgrefill    4884560    3006938   -1877622     -39.00
                    pgrotated      37828      25897     -11931     -32.00
                pgscan_direct    1456037     957567    -498470     -35.00
       pgscan_direct_throttle          0          0          0       0.00
                pgscan_kswapd    6667767    5047360   -1620407     -25.00
                 pgscan_total    8123804    6004927   -2118877     -27.00
                   pgskip_dma          0          0          0       0.00
               pgskip_movable          0          0          0       0.00
                pgskip_normal      14907      25382      10475      70.00
                 pgskip_total      14907      25382      10475      70.00
               pgsteal_direct    1118986     690215    -428771     -39.00
               pgsteal_kswapd    4750223    3657107   -1093116     -24.00
                pgsteal_total    5869209    4347322   -1521887     -26.00
                       pswpin     417613    1392647     975034     233.00
                      pswpout    1274224    2661731    1387507     108.00
                slabs_scanned   13686905   10807200   -2879705     -22.00
          workingset_activate     668966     569444     -99522     -15.00
       workingset_nodereclaim      38957      32621      -6336     -17.00
           workingset_refault    2816795    2179782    -637013     -23.00
           workingset_restore     294320     168601    -125719     -43.00

pgmajfault is increased by 173% because swapin is increased by 200% by process_madvise hint. However, swap read based on zram is much cheaper than file IO in performance point of view and app hot start by swapin is also cheaper than cold start from the beginning of app which needs many IO from storage and initialization steps.

This patchset is against on next-20190517.

Minchan Kim (7):
mm: introduce MADV_COOL
mm: change PAGEREF_RECLAIM_CLEAN with PAGE_REFRECLAIM
mm: introduce MADV_COLD
mm: factor out madvise's core functionality
mm: introduce external memory hinting API
mm: extend process_madvise syscall to support vector arrary
mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

 arch/x86/entry/syscalls/syscall_32.tbl |   1 +
 arch/x86/entry/syscalls/syscall_64.tbl |   1 +
 include/linux/page-flags.h             |   1 +
 include/linux/page_idle.h              |  15 +
 include/linux/proc_fs.h                |   1 +
 include/linux/swap.h                   |   2 +
 include/linux/syscalls.h               |   2 +
 include/uapi/asm-generic/mman-common.h |  12 +
 include/uapi/asm-generic/unistd.h      |   2 +
 kernel/signal.c                        |   2 +-
 kernel/sys_ni.c                        |   1 +
 mm/madvise.c                           | 600 +++++++++++++++++++++----
 mm/swap.c                              |  43 ++
 mm/vmscan.c                            |  80 +++-
 14 files changed, 680 insertions(+), 83 deletions(-)
Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
#1 lore raw

RFC 1/7 mm: introduce MADV_COOL

When a process expects no accesses to a certain memory range it could hint kernel that the pages can be reclaimed when memory pressure happens but data should be preserved for future use. This could reduce workingset eviction so it ends up increasing performance.

This patch introduces the new MADV_COOL hint to madvise(2) syscall. MADV_COOL can be used by a process to mark a memory range as not expected to be used in the near future. The hint can help kernel in deciding which pages to evict early during memory pressure.

Internally, it works via deactivating memory from active list to inactive's head so when the memory pressure happens, they will be reclaimed earlier than other active pages unless there is no access until the time.

* v1r2
* use clear_page_young in deactivate_page - joelaf

* v1r1
* Revise the description - surenb
* Renaming from MADV_WARM to MADV_COOL - surenb

---
 include/linux/page-flags.h             |   1 +
 include/linux/page_idle.h              |  15 ++++
 include/linux/swap.h                   |   1 +
 include/uapi/asm-generic/mman-common.h |   1 +
 mm/madvise.c                           | 112 +++++++++++++++++++++++++
 mm/swap.c                              |  43 ++++++++++
 6 files changed, 173 insertions(+)
include/linux/page-flags.h +1 -0
index 9f8712a4b1a5..58b06654c8dd 100644
@@ -424,6 +424,7 @@ static inline bool set_hwpoison_free_buddy_page(struct page *page)
 TESTPAGEFLAG(Young, young, PF_ANY)
 SETPAGEFLAG(Young, young, PF_ANY)
 TESTCLEARFLAG(Young, young, PF_ANY)
+CLEARPAGEFLAG(Young, young, PF_ANY)
 PAGEFLAG(Idle, idle, PF_ANY)
 #endif
 
include/linux/page_idle.h +15 -0
index 1e894d34bdce..f3f43b317150 100644
@@ -19,6 +19,11 @@ static inline void set_page_young(struct page *page)
 	SetPageYoung(page);
 }
 
+static inline void clear_page_young(struct page *page)
+{
+	ClearPageYoung(page);
+}
+
 static inline bool test_and_clear_page_young(struct page *page)
 {
 	return TestClearPageYoung(page);
@@ -65,6 +70,16 @@ static inline void set_page_young(struct page *page)
 	set_bit(PAGE_EXT_YOUNG, &page_ext->flags);
 }
 
+static void clear_page_young(struct page *page)
+{
+	struct page_ext *page_ext = lookup_page_ext(page);
+
+	if (unlikely(!page_ext))
+		return;
+
+	clear_bit(PAGE_EXT_YOUNG, &page_ext->flags);
+}
+
 static inline bool test_and_clear_page_young(struct page *page)
 {
 	struct page_ext *page_ext = lookup_page_ext(page);
include/linux/swap.h +1 -0
index 4bfb5c4ac108..64795abea003 100644
@@ -340,6 +340,7 @@ extern void lru_add_drain_cpu(int cpu);
 extern void lru_add_drain_all(void);
 extern void rotate_reclaimable_page(struct page *page);
 extern void deactivate_file_page(struct page *page);
+extern void deactivate_page(struct page *page);
 extern void mark_page_lazyfree(struct page *page);
 extern void swap_setup(void);
 
include/uapi/asm-generic/mman-common.h +1 -0
index abd238d0f7a4..f7a4a5d4b642 100644
@@ -42,6 +42,7 @@
 #define MADV_SEQUENTIAL	2		/* expect sequential page references */
 #define MADV_WILLNEED	3		/* will need these pages */
 #define MADV_DONTNEED	4		/* don't need these pages */
+#define MADV_COOL	5		/* deactivatie these pages */
 
 /* common parameters: try to keep these consistent across architectures */
 #define MADV_FREE	8		/* free pages only if memory pressure */
mm/madvise.c +112 -0

142 lines not on this page · raw message

mm/swap.c +43 -0

73 lines not on this page · raw message

Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
reviewer
#2 lore raw

Re: [RFC 1/7] mm: introduce MADV_COOL

[CC linux-api]

Quoted 11 lines · Minchan Kim

When a process expects no accesses to a certain memory range it could hint kernel that the pages can be reclaimed when memory pressure happens but data should be preserved for future use. This could reduce workingset eviction so it ends up increasing performance.

This patch introduces the new MADV_COOL hint to madvise(2) syscall. MADV_COOL can be used by a process to mark a memory range as not expected to be used in the near future. The hint can help kernel in deciding which pages to evict early during memory pressure.

I do not want to start naming fight but MADV_COOL sounds a bit misleading. Everybody thinks his pages are cool ;). Probably MADV_COLD or MADV_DONTNEED_PRESERVE.

Quoted 4 lines

Internally, it works via deactivating memory from active list to inactive's head so when the memory pressure happens, they will be reclaimed earlier than other active pages unless there is no access until the time.

Could you elaborate about the decision to move to the head rather than tail? What should happen to inactive pages? Should we move them to the tail? Your implementation seems to ignore those completely. Why?

What should happen for shared pages? In other words do we want to allow less privileged process to control evicting of shared pages with a more privileged one? E.g. think of all sorts of side channel attacks. Maybe we want to do the same thing as for mincore where write access is required.

Signature · 2 lines
Michal Hocko
SUSE Labs
reviewer
#3 lore raw

Re: [RFC 1/7] mm: introduce MADV_COOL

Quoted 15 lines · Michal Hocko

[CC linux-api]

Quoted 11 lines · Minchan Kim

When a process expects no accesses to a certain memory range it could hint kernel that the pages can be reclaimed when memory pressure happens but data should be preserved for future use. This could reduce workingset eviction so it ends up increasing performance.

This patch introduces the new MADV_COOL hint to madvise(2) syscall. MADV_COOL can be used by a process to mark a memory range as not expected to be used in the near future. The hint can help kernel in deciding which pages to evict early during memory pressure.

Quoted 3 lines

I do not want to start naming fight but MADV_COOL sounds a bit misleading. Everybody thinks his pages are cool ;). Probably MADV_COLD or MADV_DONTNEED_PRESERVE.

OK, I can see that you have used MADV_COLD for a different mode. So this one is effectively a non destructive MADV_FREE alternative so MADV_FREE_PRESERVE would sound like a good fit. Your MADV_COLD in other patch would then be MADV_DONTNEED_PRESERVE. Right?

Signature · 2 lines
Michal Hocko
SUSE Labs
#4 lore raw

Re: [RFC 1/7] mm: introduce MADV_COOL

Quoted 17 lines · Michal Hocko
Quoted 15 lines · Michal Hocko

[CC linux-api]

Quoted 11 lines · Minchan Kim

When a process expects no accesses to a certain memory range it could hint kernel that the pages can be reclaimed when memory pressure happens but data should be preserved for future use. This could reduce workingset eviction so it ends up increasing performance.

This patch introduces the new MADV_COOL hint to madvise(2) syscall. MADV_COOL can be used by a process to mark a memory range as not expected to be used in the near future. The hint can help kernel in deciding which pages to evict early during memory pressure.

Quoted 9 lines
Quoted 3 lines

I do not want to start naming fight but MADV_COOL sounds a bit misleading. Everybody thinks his pages are cool ;). Probably MADV_COLD or MADV_DONTNEED_PRESERVE.

OK, I can see that you have used MADV_COLD for a different mode. So this one is effectively a non destructive MADV_FREE alternative so MADV_FREE_PRESERVE would sound like a good fit. Your MADV_COLD in other patch would then be MADV_DONTNEED_PRESERVE. Right?

I agree that naming them this way would be more in-line with the existing API. Another good option IMO could be MADV_RECLAIM_NOW / MADV_RECLAIM_LAZY which might explain a bit better what they do but Michal's proposal is more consistent with the current API.

Quoted 3 lines

--
Michal Hocko
SUSE Labs

#5 lore raw

Re: [RFC 1/7] mm: introduce MADV_COOL

In reply to Michal Hocko
Quoted 16 lines · Michal Hocko
Quoted 15 lines · Michal Hocko

[CC linux-api]

Quoted 11 lines · Minchan Kim

When a process expects no accesses to a certain memory range it could hint kernel that the pages can be reclaimed when memory pressure happens but data should be preserved for future use. This could reduce workingset eviction so it ends up increasing performance.

This patch introduces the new MADV_COOL hint to madvise(2) syscall. MADV_COOL can be used by a process to mark a memory range as not expected to be used in the near future. The hint can help kernel in deciding which pages to evict early during memory pressure.

Quoted 8 lines
Quoted 3 lines

I do not want to start naming fight but MADV_COOL sounds a bit misleading. Everybody thinks his pages are cool ;). Probably MADV_COLD or MADV_DONTNEED_PRESERVE.

OK, I can see that you have used MADV_COLD for a different mode. So this one is effectively a non destructive MADV_FREE alternative so MADV_FREE_PRESERVE would sound like a good fit. Your MADV_COLD in other patch would then be MADV_DONTNEED_PRESERVE. Right?

Correct.

#6 lore raw

Re: [RFC 1/7] mm: introduce MADV_COOL

In reply to Michal Hocko
Quoted 1 line · Michal Hocko

[CC linux-api]

Thanks, Michal. I forgot to add it.

Quoted 14 lines · Minchan Kim
Quoted 11 lines

When a process expects no accesses to a certain memory range it could hint kernel that the pages can be reclaimed when memory pressure happens but data should be preserved for future use. This could reduce workingset eviction so it ends up increasing performance.

This patch introduces the new MADV_COOL hint to madvise(2) syscall. MADV_COOL can be used by a process to mark a memory range as not expected to be used in the near future. The hint can help kernel in deciding which pages to evict early during memory pressure.

Quoted 3 lines

I do not want to start naming fight but MADV_COOL sounds a bit misleading. Everybody thinks his pages are cool ;). Probably MADV_COLD or MADV_DONTNEED_PRESERVE.

Thanks for the suggestion. Since I got several suggestions, Let's discuss them all at once in cover-letter.

Quoted 9 lines
Quoted 5 lines

Internally, it works via deactivating memory from active list to inactive's head so when the memory pressure happens, they will be reclaimed earlier than other active pages unless there is no access until the time.

Could you elaborate about the decision to move to the head rather than tail? What should happen to inactive pages? Should we move them to the tail? Your implementation seems to ignore those completely. Why?

Normally, inactive LRU could have used-once pages without any mapping to user's address space. Such pages would be better candicate to reclaim when the memory pressure happens. With deactivating only active LRU pages of the process to the head of inactive LRU, we will keep them in RAM longer than used-once pages and could have more chance to be activated once the process is resumed.

Quoted 6 lines

What should happen for shared pages? In other words do we want to allow less privileged process to control evicting of shared pages with a more privileged one? E.g. think of all sorts of side channel attacks. Maybe we want to do the same thing as for mincore where write access is required.

It doesn't work with shared pages(ie, page_mapcount > 1). I will add it in the description.

Quoted 3 lines
Signature · 2 lines
Michal Hocko
SUSE Labs
reviewer
#7 lore raw

Re: [RFC 1/7] mm: introduce MADV_COOL

Quoted 1 line · Minchan Kim

On Mon, May 20, 2019 at 10:16:21AM +0200, Michal Hocko wrote:

[...]

Quoted 9 lines
Quoted 8 lines
Quoted 4 lines

Internally, it works via deactivating memory from active list to inactive's head so when the memory pressure happens, they will be reclaimed earlier than other active pages unless there is no access until the time.

Could you elaborate about the decision to move to the head rather than tail? What should happen to inactive pages? Should we move them to the tail? Your implementation seems to ignore those completely. Why?

Quoted 6 lines

Normally, inactive LRU could have used-once pages without any mapping to user's address space. Such pages would be better candicate to reclaim when the memory pressure happens. With deactivating only active LRU pages of the process to the head of inactive LRU, we will keep them in RAM longer than used-once pages and could have more chance to be activated once the process is resumed.

You are making some assumptions here. You have an explicit call what is cold now you are assuming something is even colder. Is this assumption a general enough to make people depend on it? Not that we wouldn't be able to change to logic later but that will always be risky - especially in the area when somebody want to make a user space driven memory management.

Quoted 8 lines
Quoted 5 lines

What should happen for shared pages? In other words do we want to allow less privileged process to control evicting of shared pages with a more privileged one? E.g. think of all sorts of side channel attacks. Maybe we want to do the same thing as for mincore where write access is required.

It doesn't work with shared pages(ie, page_mapcount > 1). I will add it in the description.

OK, this is good for the starter. It makes the implementation simpler and we can add shared mappings coverage later.

Although I would argue that touching only writeable mappings should be reasonably safe.

Signature · 2 lines
Michal Hocko
SUSE Labs
#8 lore raw

Re: [RFC 1/7] mm: introduce MADV_COOL

Quoted 19 lines · Michal Hocko
Quoted 1 line · Minchan Kim

On Mon, May 20, 2019 at 10:16:21AM +0200, Michal Hocko wrote:

[...]

Quoted 9 lines
Quoted 8 lines
Quoted 4 lines

Internally, it works via deactivating memory from active list to inactive's head so when the memory pressure happens, they will be reclaimed earlier than other active pages unless there is no access until the time.

Could you elaborate about the decision to move to the head rather than tail? What should happen to inactive pages? Should we move them to the tail? Your implementation seems to ignore those completely. Why?

Quoted 6 lines

Normally, inactive LRU could have used-once pages without any mapping to user's address space. Such pages would be better candicate to reclaim when the memory pressure happens. With deactivating only active LRU pages of the process to the head of inactive LRU, we will keep them in RAM longer than used-once pages and could have more chance to be activated once the process is resumed.

Quoted 6 lines

You are making some assumptions here. You have an explicit call what is cold now you are assuming something is even colder. Is this assumption a general enough to make people depend on it? Not that we wouldn't be able to change to logic later but that will always be risky - especially in the area when somebody want to make a user space driven memory management.

Think about MADV_FREE. It moves those pages into inactive file LRU's head. See the get_scan_count which makes forceful scanning of inactive file LRU if it has enough size based on the memory pressure.
The reason is it's likely to have used-once pages in inactive file LRU, generally. Those pages has been top-priority candidate to be reclaimed for a long time.

Only parts I am aware of moving pages into tail of inactive LRU are places writeback is done for pages VM already decide to reclaim by LRU aging or destructive operation like invalidating but couldn't completed. It's really strong hints with no doubt.

Quoted 19 lines
Quoted 9 lines
Quoted 6 lines

What should happen for shared pages? In other words do we want to allow less privileged process to control evicting of shared pages with a more privileged one? E.g. think of all sorts of side channel attacks. Maybe we want to do the same thing as for mincore where write access is required.

It doesn't work with shared pages(ie, page_mapcount > 1). I will add it in the description.

OK, this is good for the starter. It makes the implementation simpler and we can add shared mappings coverage later.

Although I would argue that touching only writeable mappings should be reasonably safe.

Signature · 2 lines
Michal Hocko
SUSE Labs
reviewer
#9 lore raw

Re: [RFC 1/7] mm: introduce MADV_COOL

Quoted 27 lines · Minchan Kim
Quoted 19 lines · Michal Hocko
Quoted 1 line · Minchan Kim

On Mon, May 20, 2019 at 10:16:21AM +0200, Michal Hocko wrote:

[...]

Quoted 9 lines
Quoted 8 lines
Quoted 4 lines

Internally, it works via deactivating memory from active list to inactive's head so when the memory pressure happens, they will be reclaimed earlier than other active pages unless there is no access until the time.

Could you elaborate about the decision to move to the head rather than tail? What should happen to inactive pages? Should we move them to the tail? Your implementation seems to ignore those completely. Why?

Quoted 6 lines

Normally, inactive LRU could have used-once pages without any mapping to user's address space. Such pages would be better candicate to reclaim when the memory pressure happens. With deactivating only active LRU pages of the process to the head of inactive LRU, we will keep them in RAM longer than used-once pages and could have more chance to be activated once the process is resumed.

Quoted 6 lines

You are making some assumptions here. You have an explicit call what is cold now you are assuming something is even colder. Is this assumption a general enough to make people depend on it? Not that we wouldn't be able to change to logic later but that will always be risky - especially in the area when somebody want to make a user space driven memory management.

Quoted 6 lines

Think about MADV_FREE. It moves those pages into inactive file LRU's head. See the get_scan_count which makes forceful scanning of inactive file LRU if it has enough size based on the memory pressure.
The reason is it's likely to have used-once pages in inactive file LRU, generally. Those pages has been top-priority candidate to be reclaimed for a long time.

OK, fair enough. Being consistent with MADV_FREE is reasonable. I just forgot we do rotate like this there.

Signature · 2 lines
Michal Hocko
SUSE Labs
#10 lore raw

Re: [RFC 1/7] mm: introduce MADV_COOL

In reply to Minchan Kim
Quoted 16 lines · Hillf Danton

mm/madvise.c static long madvise_willneed(struct vm_area_struct *vma, · line 323

Quoted 12 lines · On Mon, 20 May 2019 12:52:48 +0900 Minchan Kim wrote:
mm/madvise.c +12 -0
+static int madvise_cool_pte_range(pmd_t *pmd, unsigned long addr,
+				unsigned long end, struct mm_walk *walk)
+{
+	pte_t *orig_pte, *pte, ptent;
+	spinlock_t *ptl;
+	struct page *page;
+	struct vm_area_struct *vma = walk->vma;
+	unsigned long next;
+
+	next = pmd_addr_end(addr, end);
+	if (pmd_trans_huge(*pmd)) {
+		spinlock_t *ptl;

Seems not needed with another ptl declared above.

Will remove it.

Quoted 9 lines
Quoted 9 lines
mm/madvise.c +9 -0
+
+		ptl = pmd_trans_huge_lock(pmd, vma);
+		if (!ptl)
+			return 0;
+
+		if (is_huge_zero_pmd(*pmd))
+			goto huge_unlock;
+
+		page = pmd_page(*pmd);
Quoted 8 lines

mm/madvise.c static long madvise_willneed(struct vm_area_struct *vma, · line 337

Quoted 5 lines
mm/madvise.c +5 -0
+		if (page_mapcount(page) > 1)
+			goto huge_unlock;
+
+		if (next - addr != HPAGE_PMD_SIZE) {
+			int err;

Alternately, we deactivate thp only if the address range from userspace is sane enough, in order to avoid complex works we have to do here.

Not sure it's a good idea. That's the way we have done in MADV_FREE so want to be consistent.

Quoted 17 lines
Quoted 17 lines
mm/madvise.c +17 -0
+
+			get_page(page);
+			spin_unlock(ptl);
+			lock_page(page);
+			err = split_huge_page(page);
+			unlock_page(page);
+			put_page(page);
+			if (!err)
+				goto regular_page;
+			return 0;
+		}
+
+		pmdp_test_and_clear_young(vma, addr, pmd);
+		deactivate_page(page);
+huge_unlock:
+		spin_unlock(ptl);
+		return 0;
Quoted 8 lines

mm/madvise.c static long madvise_willneed(struct vm_area_struct *vma, · line 360

Quoted 6 lines
mm/madvise.c +6 -0
+	}
+
+	if (pmd_trans_unstable(pmd))
+		return 0;
+
+regular_page:

Take a look at pending signal?

Do you have any reason to see pending signal here? I want to know what's your requirement so that what's the better place to handle it.

Quoted 5 lines

mm/madvise.c static long madvise_willneed(struct vm_area_struct *vma, · line 362

Quoted 3 lines
mm/madvise.c +2 -0
+	orig_pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
+	for (pte = orig_pte; addr < end; pte++, addr += PAGE_SIZE) {

s/end/next/ ?

Why do you think it should be next?

Quoted 27 lines
Quoted 27 lines
mm/madvise.c +27 -0
+		ptent = *pte;
+
+		if (pte_none(ptent))
+			continue;
+
+		if (!pte_present(ptent))
+			continue;
+
+		page = vm_normal_page(vma, addr, ptent);
+		if (!page)
+			continue;
+
+		if (page_mapcount(page) > 1)
+			continue;
+
+		ptep_test_and_clear_young(vma, addr, pte);
+		deactivate_page(page);
+	}
+
+	pte_unmap_unlock(orig_pte, ptl);
+	cond_resched();
+
+	return 0;
+}
+
+static long madvise_cool(struct vm_area_struct *vma,
+			unsigned long start_addr, unsigned long end_addr)
Quoted 8 lines

mm/madvise.c static long madvise_willneed(struct vm_area_struct *vma, · line 409

Quoted 6 lines
mm/madvise.c +6 -0
+{
+	struct mm_struct *mm = vma->vm_mm;
+	struct mmu_gather tlb;
+
+	if (vma->vm_flags & (VM_LOCKED|VM_HUGETLB|VM_PFNMAP))
+		return -EINVAL;

No service in case of VM_IO?

I don't know VM_IO would have regular LRU pages but just follow normal convention for DONTNEED and FREE.
Do you have anything in your mind?

#11 lore raw

RFC 2/7 mm: change PAGEREF_RECLAIM_CLEAN with PAGE_REFRECLAIM

In reply to Minchan Kim

The local variable references in shrink_page_list is PAGEREF_RECLAIM_CLEAN as default. It is for preventing to reclaim dirty pages when CMA try to migrate pages. Strictly speaking, we don't need it because CMA didn't allow to write out by .may_writepage = 0 in reclaim_clean_pages_from_list.

Moreover, it has a problem to prevent anonymous pages's swap out even though force_reclaim = true in shrink_page_list on upcoming patch. So this patch makes references's default value to PAGEREF_RECLAIM and rename force_reclaim with skip_reference_check to make it more clear.

This is a preparatory work for next patch.

---
 mm/vmscan.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
mm/vmscan.c +3 -3
index d9c3e873eca6..a28e5d17b495 100644
@@ -1102,7 +1102,7 @@ static unsigned long shrink_page_list(struct list_head *page_list,
 				      struct scan_control *sc,
 				      enum ttu_flags ttu_flags,
 				      struct reclaim_stat *stat,
-				      bool force_reclaim)
+				      bool skip_reference_check)
 {
 	LIST_HEAD(ret_pages);
 	LIST_HEAD(free_pages);
@@ -1116,7 +1116,7 @@ static unsigned long shrink_page_list(struct list_head *page_list,
 		struct address_space *mapping;
 		struct page *page;
 		int may_enter_fs;
-		enum page_references references = PAGEREF_RECLAIM_CLEAN;
+		enum page_references references = PAGEREF_RECLAIM;
 		bool dirty, writeback;
 
 		cond_resched();
@@ -1248,7 +1248,7 @@ static unsigned long shrink_page_list(struct list_head *page_list,
 			}
 		}
 
-		if (!force_reclaim)
+		if (!skip_reference_check)
 			references = page_check_references(page, sc);
 
 		switch (references) {
Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
maintainer Acked-by on v1 2/7
#12 lore raw

Re: [RFC 2/7] mm: change PAGEREF_RECLAIM_CLEAN with PAGE_REFRECLAIM

Quoted 5 lines · Minchan Kim

The local variable references in shrink_page_list is PAGEREF_RECLAIM_CLEAN as default. It is for preventing to reclaim dirty pages when CMA try to migrate pages. Strictly speaking, we don't need it because CMA didn't allow to write out by .may_writepage = 0 in reclaim_clean_pages_from_list.

Quoted 8 lines

Moreover, it has a problem to prevent anonymous pages's swap out even though force_reclaim = true in shrink_page_list on upcoming patch. So this patch makes references's default value to PAGEREF_RECLAIM and rename force_reclaim with skip_reference_check to make it more clear.

This is a preparatory work for next patch.

Looks good to me, just one nit below.

Quoted 9 lines
---
 mm/vmscan.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
mm/vmscan.c +0 -0
index d9c3e873eca6..a28e5d17b495 100644

mm/vmscan.c static unsigned long shrink_page_list(struct list_head *page_list, · line 1105

Quoted 5 lines
mm/vmscan.c +1 -1
@@ -1102,7 +1102,7 @@ static unsigned long shrink_page_list(struct list_head *page_list,
 				      struct scan_control *sc,
 				      enum ttu_flags ttu_flags,
 				      struct reclaim_stat *stat,
-				      bool force_reclaim)
+				      bool skip_reference_check)

"ignore_references" would be better IMO

#13 lore raw

Re: [RFC 2/7] mm: change PAGEREF_RECLAIM_CLEAN with PAGE_REFRECLAIM

Quoted 11 lines · Johannes Weiner
Quoted 10 lines · Minchan Kim

The local variable references in shrink_page_list is PAGEREF_RECLAIM_CLEAN as default. It is for preventing to reclaim dirty pages when CMA try to migrate pages. Strictly speaking, we don't need it because CMA didn't allow to write out by .may_writepage = 0 in reclaim_clean_pages_from_list.

Moreover, it has a problem to prevent anonymous pages's swap out even though force_reclaim = true in shrink_page_list on upcoming patch. So this patch makes references's default value to PAGEREF_RECLAIM and rename force_reclaim with skip_reference_check to make it more clear.

Quoted 7 lines
Quoted 3 lines

This is a preparatory work for next patch.

Looks good to me, just one nit below.

Thanks, Johannes.

Quoted 5 lines
Quoted 5 lines
---
 mm/vmscan.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
Quoted 12 lines

mm/vmscan.c static unsigned long shrink_page_list(struct list_head *page_list, · line 1105

Quoted 10 lines
mm/vmscan.c +1 -1
index d9c3e873eca6..a28e5d17b495 100644
@@ -1102,7 +1102,7 @@ static unsigned long shrink_page_list(struct list_head *page_list,
 				      struct scan_control *sc,
 				      enum ttu_flags ttu_flags,
 				      struct reclaim_stat *stat,
-				      bool force_reclaim)
+				      bool skip_reference_check)

"ignore_references" would be better IMO

Sure.

#14 lore raw

RFC 3/7 mm: introduce MADV_COLD

In reply to Minchan Kim

When a process expects no accesses to a certain memory range for a long time, it could hint kernel that the pages can be reclaimed instantly but data should be preserved for future use. This could reduce workingset eviction so it ends up increasing performance.

This patch introduces the new MADV_COLD hint to madvise(2) syscall. MADV_COLD can be used by a process to mark a memory range as not expected to be used for a long time. The hint can help kernel in deciding which pages to evict proactively.

Internally, it works via reclaiming memory in process context the syscall is called. If the page is dirty but backing storage is not synchronous device, the written page will be rotate back into LRU's tail once the write is done so they will reclaim easily when memory pressure happens. If backing storage is synchrnous device(e.g., zram), hte page will be reclaimed instantly.

---
 include/linux/swap.h                   |   1 +
 include/uapi/asm-generic/mman-common.h |   1 +
 mm/madvise.c                           | 123 +++++++++++++++++++++++++
 mm/vmscan.c                            |  74 +++++++++++++++
 4 files changed, 199 insertions(+)
include/linux/swap.h +1 -0
index 64795abea003..7f32a948fc6a 100644
@@ -365,6 +365,7 @@ extern int vm_swappiness;
 extern int remove_mapping(struct address_space *mapping, struct page *page);
 extern unsigned long vm_total_pages;
 
+extern unsigned long reclaim_pages(struct list_head *page_list);
 #ifdef CONFIG_NUMA
 extern int node_reclaim_mode;
 extern int sysctl_min_unmapped_ratio;
include/uapi/asm-generic/mman-common.h +1 -0
index f7a4a5d4b642..b9b51eeb8e1a 100644
@@ -43,6 +43,7 @@
 #define MADV_WILLNEED	3		/* will need these pages */
 #define MADV_DONTNEED	4		/* don't need these pages */
 #define MADV_COOL	5		/* deactivatie these pages */
+#define MADV_COLD	6		/* reclaim these pages */
 
 /* common parameters: try to keep these consistent across architectures */
 #define MADV_FREE	8		/* free pages only if memory pressure */
mm/madvise.c +123 -0

147 lines not on this page · raw message

mm/vmscan.c +74 -0

80 lines not on this page · raw message

Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
reviewer
#15 lore raw

Re: [RFC 3/7] mm: introduce MADV_COLD

[Cc linux-api]

Quoted 10 lines · Minchan Kim

When a process expects no accesses to a certain memory range for a long time, it could hint kernel that the pages can be reclaimed instantly but data should be preserved for future use. This could reduce workingset eviction so it ends up increasing performance.

This patch introduces the new MADV_COLD hint to madvise(2) syscall. MADV_COLD can be used by a process to mark a memory range as not expected to be used for a long time. The hint can help kernel in deciding which pages to evict proactively.

As mentioned in other email this looks like a non-destructive MADV_DONTNEED alternative.

Quoted 6 lines

Internally, it works via reclaiming memory in process context the syscall is called. If the page is dirty but backing storage is not synchronous device, the written page will be rotate back into LRU's tail once the write is done so they will reclaim easily when memory pressure happens. If backing storage is synchrnous device(e.g., zram), hte page will be reclaimed instantly.

Why do we special case async backing storage? Please always try to explain _why_ the decision is made.

I haven't checked the implementation yet so I cannot comment on that.

Quoted 275 lines
---
 include/linux/swap.h                   |   1 +
 include/uapi/asm-generic/mman-common.h |   1 +
 mm/madvise.c                           | 123 +++++++++++++++++++++++++
 mm/vmscan.c                            |  74 +++++++++++++++
 4 files changed, 199 insertions(+)
include/linux/swap.h +1 -0
index 64795abea003..7f32a948fc6a 100644
@@ -365,6 +365,7 @@ extern int vm_swappiness;
 extern int remove_mapping(struct address_space *mapping, struct page *page);
 extern unsigned long vm_total_pages;
 
+extern unsigned long reclaim_pages(struct list_head *page_list);
 #ifdef CONFIG_NUMA
 extern int node_reclaim_mode;
 extern int sysctl_min_unmapped_ratio;
include/uapi/asm-generic/mman-common.h +1 -0
index f7a4a5d4b642..b9b51eeb8e1a 100644
@@ -43,6 +43,7 @@
 #define MADV_WILLNEED	3		/* will need these pages */
 #define MADV_DONTNEED	4		/* don't need these pages */
 #define MADV_COOL	5		/* deactivatie these pages */
+#define MADV_COLD	6		/* reclaim these pages */
 
 /* common parameters: try to keep these consistent across architectures */
 #define MADV_FREE	8		/* free pages only if memory pressure */
mm/madvise.c +123 -0
index c05817fb570d..9a6698b56845 100644
@@ -42,6 +42,7 @@ static int madvise_need_mmap_write(int behavior)
 	case MADV_WILLNEED:
 	case MADV_DONTNEED:
 	case MADV_COOL:
+	case MADV_COLD:
 	case MADV_FREE:
 		return 0;
 	default:
@@ -416,6 +417,125 @@ static long madvise_cool(struct vm_area_struct *vma,
 	return 0;
 }
 
+static int madvise_cold_pte_range(pmd_t *pmd, unsigned long addr,
+				unsigned long end, struct mm_walk *walk)
+{
+	pte_t *orig_pte, *pte, ptent;
+	spinlock_t *ptl;
+	LIST_HEAD(page_list);
+	struct page *page;
+	int isolated = 0;
+	struct vm_area_struct *vma = walk->vma;
+	unsigned long next;
+
+	next = pmd_addr_end(addr, end);
+	if (pmd_trans_huge(*pmd)) {
+		spinlock_t *ptl;
+
+		ptl = pmd_trans_huge_lock(pmd, vma);
+		if (!ptl)
+			return 0;
+
+		if (is_huge_zero_pmd(*pmd))
+			goto huge_unlock;
+
+		page = pmd_page(*pmd);
+		if (page_mapcount(page) > 1)
+			goto huge_unlock;
+
+		if (next - addr != HPAGE_PMD_SIZE) {
+			int err;
+
+			get_page(page);
+			spin_unlock(ptl);
+			lock_page(page);
+			err = split_huge_page(page);
+			unlock_page(page);
+			put_page(page);
+			if (!err)
+				goto regular_page;
+			return 0;
+		}
+
+		if (isolate_lru_page(page))
+			goto huge_unlock;
+
+		list_add(&page->lru, &page_list);
+huge_unlock:
+		spin_unlock(ptl);
+		reclaim_pages(&page_list);
+		return 0;
+	}
+
+	if (pmd_trans_unstable(pmd))
+		return 0;
+regular_page:
+	orig_pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
+	for (pte = orig_pte; addr < end; pte++, addr += PAGE_SIZE) {
+		ptent = *pte;
+		if (!pte_present(ptent))
+			continue;
+
+		page = vm_normal_page(vma, addr, ptent);
+		if (!page)
+			continue;
+
+		if (page_mapcount(page) > 1)
+			continue;
+
+		if (isolate_lru_page(page))
+			continue;
+
+		isolated++;
+		list_add(&page->lru, &page_list);
+		if (isolated >= SWAP_CLUSTER_MAX) {
+			pte_unmap_unlock(orig_pte, ptl);
+			reclaim_pages(&page_list);
+			isolated = 0;
+			pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
+			orig_pte = pte;
+		}
+	}
+
+	pte_unmap_unlock(orig_pte, ptl);
+	reclaim_pages(&page_list);
+	cond_resched();
+
+	return 0;
+}
+
+static void madvise_cold_page_range(struct mmu_gather *tlb,
+			     struct vm_area_struct *vma,
+			     unsigned long addr, unsigned long end)
+{
+	struct mm_walk warm_walk = {
+		.pmd_entry = madvise_cold_pte_range,
+		.mm = vma->vm_mm,
+	};
+
+	tlb_start_vma(tlb, vma);
+	walk_page_range(addr, end, &warm_walk);
+	tlb_end_vma(tlb, vma);
+}
+
+
+static long madvise_cold(struct vm_area_struct *vma,
+			unsigned long start_addr, unsigned long end_addr)
+{
+	struct mm_struct *mm = vma->vm_mm;
+	struct mmu_gather tlb;
+
+	if (vma->vm_flags & (VM_LOCKED|VM_HUGETLB|VM_PFNMAP))
+		return -EINVAL;
+
+	lru_add_drain();
+	tlb_gather_mmu(&tlb, mm, start_addr, end_addr);
+	madvise_cold_page_range(&tlb, vma, start_addr, end_addr);
+	tlb_finish_mmu(&tlb, start_addr, end_addr);
+
+	return 0;
+}
+
 static int madvise_free_pte_range(pmd_t *pmd, unsigned long addr,
 				unsigned long end, struct mm_walk *walk)
 
@@ -806,6 +926,8 @@ madvise_vma(struct vm_area_struct *vma, struct vm_area_struct **prev,
 		return madvise_willneed(vma, prev, start, end);
 	case MADV_COOL:
 		return madvise_cool(vma, start, end);
+	case MADV_COLD:
+		return madvise_cold(vma, start, end);
 	case MADV_FREE:
 	case MADV_DONTNEED:
 		return madvise_dontneed_free(vma, prev, start, end, behavior);
@@ -828,6 +950,7 @@ madvise_behavior_valid(int behavior)
 	case MADV_DONTNEED:
 	case MADV_FREE:
 	case MADV_COOL:
+	case MADV_COLD:
 #ifdef CONFIG_KSM
 	case MADV_MERGEABLE:
 	case MADV_UNMERGEABLE:
mm/vmscan.c +74 -0
index a28e5d17b495..1701b31f70a8 100644
@@ -2096,6 +2096,80 @@ static void shrink_active_list(unsigned long nr_to_scan,
 			nr_deactivate, nr_rotated, sc->priority, file);
 }
 
+unsigned long reclaim_pages(struct list_head *page_list)
+{
+	int nid = -1;
+	unsigned long nr_isolated[2] = {0, };
+	unsigned long nr_reclaimed = 0;
+	LIST_HEAD(node_page_list);
+	struct reclaim_stat dummy_stat;
+	struct scan_control sc = {
+		.gfp_mask = GFP_KERNEL,
+		.priority = DEF_PRIORITY,
+		.may_writepage = 1,
+		.may_unmap = 1,
+		.may_swap = 1,
+	};
+
+	while (!list_empty(page_list)) {
+		struct page *page;
+
+		page = lru_to_page(page_list);
+		list_del(&page->lru);
+
+		if (nid == -1) {
+			nid = page_to_nid(page);
+			INIT_LIST_HEAD(&node_page_list);
+			nr_isolated[0] = nr_isolated[1] = 0;
+		}
+
+		if (nid == page_to_nid(page)) {
+			list_add(&page->lru, &node_page_list);
+			nr_isolated[!!page_is_file_cache(page)] +=
+						hpage_nr_pages(page);
+			continue;
+		}
+
+		nid = page_to_nid(page);
+
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_ANON,
+					nr_isolated[0]);
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_FILE,
+					nr_isolated[1]);
+		nr_reclaimed += shrink_page_list(&node_page_list,
+				NODE_DATA(nid), &sc, TTU_IGNORE_ACCESS,
+				&dummy_stat, true);
+		while (!list_empty(&node_page_list)) {
+			struct page *page = lru_to_page(page_list);
+
+			list_del(&page->lru);
+			putback_lru_page(page);
+		}
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_ANON,
+					-nr_isolated[0]);
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_FILE,
+					-nr_isolated[1]);
+		nr_isolated[0] = nr_isolated[1] = 0;
+		INIT_LIST_HEAD(&node_page_list);
+	}
+
+	if (!list_empty(&node_page_list)) {
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_ANON,
+					nr_isolated[0]);
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_FILE,
+					nr_isolated[1]);
+		nr_reclaimed += shrink_page_list(&node_page_list,
+				NODE_DATA(nid), &sc, TTU_IGNORE_ACCESS,
+				&dummy_stat, true);
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_ANON,
+					-nr_isolated[0]);
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_FILE,
+					-nr_isolated[1]);
+	}
+
+	return nr_reclaimed;
+}
+
 /*
  * The inactive anon list should be small enough that the VM never has
  * to do too much work.
Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
Signature · 2 lines
Michal Hocko
SUSE Labs
#16 lore raw

Re: [RFC 3/7] mm: introduce MADV_COLD

Quoted 24 lines · Michal Hocko

[Cc linux-api]

Quoted 10 lines · Minchan Kim

When a process expects no accesses to a certain memory range for a long time, it could hint kernel that the pages can be reclaimed instantly but data should be preserved for future use. This could reduce workingset eviction so it ends up increasing performance.

This patch introduces the new MADV_COLD hint to madvise(2) syscall. MADV_COLD can be used by a process to mark a memory range as not expected to be used for a long time. The hint can help kernel in deciding which pages to evict proactively.

As mentioned in other email this looks like a non-destructive MADV_DONTNEED alternative.

Quoted 6 lines

Internally, it works via reclaiming memory in process context the syscall is called. If the page is dirty but backing storage is not synchronous device, the written page will be rotate back into LRU's tail once the write is done so they will reclaim easily when memory pressure happens. If backing storage is synchrnous device(e.g., zram), hte page will be reclaimed instantly.

Quoted 2 lines

Why do we special case async backing storage? Please always try to explain _why_ the decision is made.

I didn't make any decesion. ;-) That's how current reclaim works to avoid latency of freeing page in interrupt context. I had a patchset to resolve the concern a few years ago but got distracted.

Quoted 282 lines

I haven't checked the implementation yet so I cannot comment on that.

Quoted 275 lines
---
 include/linux/swap.h                   |   1 +
 include/uapi/asm-generic/mman-common.h |   1 +
 mm/madvise.c                           | 123 +++++++++++++++++++++++++
 mm/vmscan.c                            |  74 +++++++++++++++
 4 files changed, 199 insertions(+)
include/linux/swap.h +1 -0
index 64795abea003..7f32a948fc6a 100644
@@ -365,6 +365,7 @@ extern int vm_swappiness;
 extern int remove_mapping(struct address_space *mapping, struct page *page);
 extern unsigned long vm_total_pages;
 
+extern unsigned long reclaim_pages(struct list_head *page_list);
 #ifdef CONFIG_NUMA
 extern int node_reclaim_mode;
 extern int sysctl_min_unmapped_ratio;
include/uapi/asm-generic/mman-common.h +1 -0
index f7a4a5d4b642..b9b51eeb8e1a 100644
@@ -43,6 +43,7 @@
 #define MADV_WILLNEED	3		/* will need these pages */
 #define MADV_DONTNEED	4		/* don't need these pages */
 #define MADV_COOL	5		/* deactivatie these pages */
+#define MADV_COLD	6		/* reclaim these pages */
 
 /* common parameters: try to keep these consistent across architectures */
 #define MADV_FREE	8		/* free pages only if memory pressure */
mm/madvise.c +123 -0
index c05817fb570d..9a6698b56845 100644
@@ -42,6 +42,7 @@ static int madvise_need_mmap_write(int behavior)
 	case MADV_WILLNEED:
 	case MADV_DONTNEED:
 	case MADV_COOL:
+	case MADV_COLD:
 	case MADV_FREE:
 		return 0;
 	default:
@@ -416,6 +417,125 @@ static long madvise_cool(struct vm_area_struct *vma,
 	return 0;
 }
 
+static int madvise_cold_pte_range(pmd_t *pmd, unsigned long addr,
+				unsigned long end, struct mm_walk *walk)
+{
+	pte_t *orig_pte, *pte, ptent;
+	spinlock_t *ptl;
+	LIST_HEAD(page_list);
+	struct page *page;
+	int isolated = 0;
+	struct vm_area_struct *vma = walk->vma;
+	unsigned long next;
+
+	next = pmd_addr_end(addr, end);
+	if (pmd_trans_huge(*pmd)) {
+		spinlock_t *ptl;
+
+		ptl = pmd_trans_huge_lock(pmd, vma);
+		if (!ptl)
+			return 0;
+
+		if (is_huge_zero_pmd(*pmd))
+			goto huge_unlock;
+
+		page = pmd_page(*pmd);
+		if (page_mapcount(page) > 1)
+			goto huge_unlock;
+
+		if (next - addr != HPAGE_PMD_SIZE) {
+			int err;
+
+			get_page(page);
+			spin_unlock(ptl);
+			lock_page(page);
+			err = split_huge_page(page);
+			unlock_page(page);
+			put_page(page);
+			if (!err)
+				goto regular_page;
+			return 0;
+		}
+
+		if (isolate_lru_page(page))
+			goto huge_unlock;
+
+		list_add(&page->lru, &page_list);
+huge_unlock:
+		spin_unlock(ptl);
+		reclaim_pages(&page_list);
+		return 0;
+	}
+
+	if (pmd_trans_unstable(pmd))
+		return 0;
+regular_page:
+	orig_pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
+	for (pte = orig_pte; addr < end; pte++, addr += PAGE_SIZE) {
+		ptent = *pte;
+		if (!pte_present(ptent))
+			continue;
+
+		page = vm_normal_page(vma, addr, ptent);
+		if (!page)
+			continue;
+
+		if (page_mapcount(page) > 1)
+			continue;
+
+		if (isolate_lru_page(page))
+			continue;
+
+		isolated++;
+		list_add(&page->lru, &page_list);
+		if (isolated >= SWAP_CLUSTER_MAX) {
+			pte_unmap_unlock(orig_pte, ptl);
+			reclaim_pages(&page_list);
+			isolated = 0;
+			pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
+			orig_pte = pte;
+		}
+	}
+
+	pte_unmap_unlock(orig_pte, ptl);
+	reclaim_pages(&page_list);
+	cond_resched();
+
+	return 0;
+}
+
+static void madvise_cold_page_range(struct mmu_gather *tlb,
+			     struct vm_area_struct *vma,
+			     unsigned long addr, unsigned long end)
+{
+	struct mm_walk warm_walk = {
+		.pmd_entry = madvise_cold_pte_range,
+		.mm = vma->vm_mm,
+	};
+
+	tlb_start_vma(tlb, vma);
+	walk_page_range(addr, end, &warm_walk);
+	tlb_end_vma(tlb, vma);
+}
+
+
+static long madvise_cold(struct vm_area_struct *vma,
+			unsigned long start_addr, unsigned long end_addr)
+{
+	struct mm_struct *mm = vma->vm_mm;
+	struct mmu_gather tlb;
+
+	if (vma->vm_flags & (VM_LOCKED|VM_HUGETLB|VM_PFNMAP))
+		return -EINVAL;
+
+	lru_add_drain();
+	tlb_gather_mmu(&tlb, mm, start_addr, end_addr);
+	madvise_cold_page_range(&tlb, vma, start_addr, end_addr);
+	tlb_finish_mmu(&tlb, start_addr, end_addr);
+
+	return 0;
+}
+
 static int madvise_free_pte_range(pmd_t *pmd, unsigned long addr,
 				unsigned long end, struct mm_walk *walk)
 
@@ -806,6 +926,8 @@ madvise_vma(struct vm_area_struct *vma, struct vm_area_struct **prev,
 		return madvise_willneed(vma, prev, start, end);
 	case MADV_COOL:
 		return madvise_cool(vma, start, end);
+	case MADV_COLD:
+		return madvise_cold(vma, start, end);
 	case MADV_FREE:
 	case MADV_DONTNEED:
 		return madvise_dontneed_free(vma, prev, start, end, behavior);
@@ -828,6 +950,7 @@ madvise_behavior_valid(int behavior)
 	case MADV_DONTNEED:
 	case MADV_FREE:
 	case MADV_COOL:
+	case MADV_COLD:
 #ifdef CONFIG_KSM
 	case MADV_MERGEABLE:
 	case MADV_UNMERGEABLE:
mm/vmscan.c +74 -0
index a28e5d17b495..1701b31f70a8 100644
@@ -2096,6 +2096,80 @@ static void shrink_active_list(unsigned long nr_to_scan,
 			nr_deactivate, nr_rotated, sc->priority, file);
 }
 
+unsigned long reclaim_pages(struct list_head *page_list)
+{
+	int nid = -1;
+	unsigned long nr_isolated[2] = {0, };
+	unsigned long nr_reclaimed = 0;
+	LIST_HEAD(node_page_list);
+	struct reclaim_stat dummy_stat;
+	struct scan_control sc = {
+		.gfp_mask = GFP_KERNEL,
+		.priority = DEF_PRIORITY,
+		.may_writepage = 1,
+		.may_unmap = 1,
+		.may_swap = 1,
+	};
+
+	while (!list_empty(page_list)) {
+		struct page *page;
+
+		page = lru_to_page(page_list);
+		list_del(&page->lru);
+
+		if (nid == -1) {
+			nid = page_to_nid(page);
+			INIT_LIST_HEAD(&node_page_list);
+			nr_isolated[0] = nr_isolated[1] = 0;
+		}
+
+		if (nid == page_to_nid(page)) {
+			list_add(&page->lru, &node_page_list);
+			nr_isolated[!!page_is_file_cache(page)] +=
+						hpage_nr_pages(page);
+			continue;
+		}
+
+		nid = page_to_nid(page);
+
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_ANON,
+					nr_isolated[0]);
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_FILE,
+					nr_isolated[1]);
+		nr_reclaimed += shrink_page_list(&node_page_list,
+				NODE_DATA(nid), &sc, TTU_IGNORE_ACCESS,
+				&dummy_stat, true);
+		while (!list_empty(&node_page_list)) {
+			struct page *page = lru_to_page(page_list);
+
+			list_del(&page->lru);
+			putback_lru_page(page);
+		}
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_ANON,
+					-nr_isolated[0]);
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_FILE,
+					-nr_isolated[1]);
+		nr_isolated[0] = nr_isolated[1] = 0;
+		INIT_LIST_HEAD(&node_page_list);
+	}
+
+	if (!list_empty(&node_page_list)) {
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_ANON,
+					nr_isolated[0]);
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_FILE,
+					nr_isolated[1]);
+		nr_reclaimed += shrink_page_list(&node_page_list,
+				NODE_DATA(nid), &sc, TTU_IGNORE_ACCESS,
+				&dummy_stat, true);
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_ANON,
+					-nr_isolated[0]);
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_FILE,
+					-nr_isolated[1]);
+	}
+
+	return nr_reclaimed;
+}
+
 /*
  * The inactive anon list should be small enough that the VM never has
  * to do too much work.
Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
Signature · 2 lines
Michal Hocko
SUSE Labs
reviewer
#17 lore raw

Re: [RFC 3/7] mm: introduce MADV_COLD

Quoted 25 lines · Minchan Kim
Quoted 24 lines · Michal Hocko

[Cc linux-api]

Quoted 10 lines · Minchan Kim

When a process expects no accesses to a certain memory range for a long time, it could hint kernel that the pages can be reclaimed instantly but data should be preserved for future use. This could reduce workingset eviction so it ends up increasing performance.

This patch introduces the new MADV_COLD hint to madvise(2) syscall. MADV_COLD can be used by a process to mark a memory range as not expected to be used for a long time. The hint can help kernel in deciding which pages to evict proactively.

As mentioned in other email this looks like a non-destructive MADV_DONTNEED alternative.

Quoted 6 lines

Internally, it works via reclaiming memory in process context the syscall is called. If the page is dirty but backing storage is not synchronous device, the written page will be rotate back into LRU's tail once the write is done so they will reclaim easily when memory pressure happens. If backing storage is synchrnous device(e.g., zram), hte page will be reclaimed instantly.

Quoted 6 lines
Quoted 2 lines

Why do we special case async backing storage? Please always try to explain _why_ the decision is made.

I didn't make any decesion. ;-) That's how current reclaim works to avoid latency of freeing page in interrupt context. I had a patchset to resolve the concern a few years ago but got distracted.

Please articulate that in the changelog then. Or even do not go into implementation details and stick with - reuse the current reclaim implementation. If you call out some of the specific details you are risking people will start depending on them. The fact that this reuses the currect reclaim logic is enough from the review point of view because we know that there is no additional special casing to worry about.

Signature · 2 lines
Michal Hocko
SUSE Labs
#18 lore raw

Re: [RFC 3/7] mm: introduce MADV_COLD

Quoted 33 lines · Michal Hocko
Quoted 25 lines · Minchan Kim
Quoted 24 lines · Michal Hocko

[Cc linux-api]

Quoted 10 lines · Minchan Kim

When a process expects no accesses to a certain memory range for a long time, it could hint kernel that the pages can be reclaimed instantly but data should be preserved for future use. This could reduce workingset eviction so it ends up increasing performance.

This patch introduces the new MADV_COLD hint to madvise(2) syscall. MADV_COLD can be used by a process to mark a memory range as not expected to be used for a long time. The hint can help kernel in deciding which pages to evict proactively.

As mentioned in other email this looks like a non-destructive MADV_DONTNEED alternative.

Quoted 6 lines

Internally, it works via reclaiming memory in process context the syscall is called. If the page is dirty but backing storage is not synchronous device, the written page will be rotate back into LRU's tail once the write is done so they will reclaim easily when memory pressure happens. If backing storage is synchrnous device(e.g., zram), hte page will be reclaimed instantly.

Quoted 6 lines
Quoted 2 lines

Why do we special case async backing storage? Please always try to explain _why_ the decision is made.

I didn't make any decesion. ;-) That's how current reclaim works to avoid latency of freeing page in interrupt context. I had a patchset to resolve the concern a few years ago but got distracted.

Quoted 7 lines

Please articulate that in the changelog then. Or even do not go into implementation details and stick with - reuse the current reclaim implementation. If you call out some of the specific details you are risking people will start depending on them. The fact that this reuses the currect reclaim logic is enough from the review point of view because we know that there is no additional special casing to worry about.

I should have clarified. I will remove those lines in respin.

Quoted 3 lines
Signature · 2 lines
Michal Hocko
SUSE Labs
#19 lore raw

Re: [RFC 3/7] mm: introduce MADV_COLD

In reply to Minchan Kim
Quoted 52 lines · Hillf Danton
Quoted 24 lines · On Mon, 20 May 2019 12:52:50 +0900 Minchan Kim wrote:
mm/vmscan.c +24 -0
+unsigned long reclaim_pages(struct list_head *page_list)
+{
+	int nid = -1;
+	unsigned long nr_isolated[2] = {0, };
+	unsigned long nr_reclaimed = 0;
+	LIST_HEAD(node_page_list);
+	struct reclaim_stat dummy_stat;
+	struct scan_control sc = {
+		.gfp_mask = GFP_KERNEL,
+		.priority = DEF_PRIORITY,
+		.may_writepage = 1,
+		.may_unmap = 1,
+		.may_swap = 1,
+	};
+
+	while (!list_empty(page_list)) {
+		struct page *page;
+
+		page = lru_to_page(page_list);
+		list_del(&page->lru);
+
+		if (nid == -1) {
+			nid = page_to_nid(page);
+			INIT_LIST_HEAD(&node_page_list);

mm/vmscan.c static void shrink_active_list(unsigned long nr_to_scan, · line 2132

Quoted 10 lines
mm/vmscan.c +10 -0
+			nr_isolated[0] = nr_isolated[1] = 0;
+		}
+
+		if (nid == page_to_nid(page)) {
+			list_add(&page->lru, &node_page_list);
+			nr_isolated[!!page_is_file_cache(page)] +=
+						hpage_nr_pages(page);
+			continue;
+		}
+

Now, page's node != nid and any page on the node_page_list has node == nid.

Review

Quoted 1 line
(quoted diff) +1 -0
+		nid = page_to_nid(page);

After updating nid, we get the node id of the isolated pages lost.

mm/vmscan.c static void shrink_active_list(unsigned long nr_to_scan, · line 2140

Quoted 7 lines
mm/vmscan.c +7 -0
+
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_ANON,
+					nr_isolated[0]);
+		mod_node_page_state(NODE_DATA(nid), NR_ISOLATED_FILE,
+					nr_isolated[1]);
+		nr_reclaimed += shrink_page_list(&node_page_list,
+				NODE_DATA(nid), &sc, TTU_IGNORE_ACCESS,

And nid no longer matches the node of the pages to be shrunk.

Quoted 6 lines

mm/vmscan.c static void shrink_active_list(unsigned long nr_to_scan, · line 2143

Quoted 3 lines
mm/vmscan.c +3 -0
+				&dummy_stat, true);
+		while (!list_empty(&node_page_list)) {
+			struct page *page = lru_to_page(page_list);

Non-empty node_page_list will never become empty if pages are deleted only from the page_list.

Sure.
They were last minute change. I will fix it.

Thanks for the review!

#20 lore raw

RFC 4/7 mm: factor out madvise's core functionality

In reply to Minchan Kim

This patch factor out madvise's core functionality so that upcoming patch can reuse it without duplication.

It shouldn't change any behavior.

---
 mm/madvise.c | 168 +++++++++++++++++++++++++++------------------------
 1 file changed, 89 insertions(+), 79 deletions(-)
mm/madvise.c +89 -79
index 9a6698b56845..119e82e1f065 100644
@@ -742,7 +742,8 @@ static long madvise_dontneed_single_vma(struct vm_area_struct *vma,
 	return 0;
 }
 
-static long madvise_dontneed_free(struct vm_area_struct *vma,
+static long madvise_dontneed_free(struct task_struct *tsk,
+				  struct vm_area_struct *vma,
 				  struct vm_area_struct **prev,
 				  unsigned long start, unsigned long end,
 				  int behavior)
@@ -754,8 +755,8 @@ static long madvise_dontneed_free(struct vm_area_struct *vma,
 	if (!userfaultfd_remove(vma, start, end)) {
 		*prev = NULL; /* mmap_sem has been dropped, prev is stale */
 
-		down_read(&current->mm->mmap_sem);
-		vma = find_vma(current->mm, start);
+		down_read(&tsk->mm->mmap_sem);
+		vma = find_vma(tsk->mm, start);
 		if (!vma)
 			return -ENOMEM;
 		if (start < vma->vm_start) {
@@ -802,7 +803,8 @@ static long madvise_dontneed_free(struct vm_area_struct *vma,
  * Application wants to free up the pages and associated backing store.
  * This is effectively punching a hole into the middle of a file.
  */
-static long madvise_remove(struct vm_area_struct *vma,
+static long madvise_remove(struct task_struct *tsk,
+				struct vm_area_struct *vma,
 				struct vm_area_struct **prev,
 				unsigned long start, unsigned long end)
 {
@@ -836,13 +838,13 @@ static long madvise_remove(struct vm_area_struct *vma,
 	get_file(f);
 	if (userfaultfd_remove(vma, start, end)) {
 		/* mmap_sem was not released by userfaultfd_remove() */
-		up_read(&current->mm->mmap_sem);
+		up_read(&tsk->mm->mmap_sem);
 	}
 	error = vfs_fallocate(f,
 				FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
 				offset, end - start);
 	fput(f);
-	down_read(&current->mm->mmap_sem);
+	down_read(&tsk->mm->mmap_sem);
 	return error;
 }
 
@@ -916,12 +918,13 @@ static int madvise_inject_error(int behavior,
 #endif
 
 static long
-madvise_vma(struct vm_area_struct *vma, struct vm_area_struct **prev,
-		unsigned long start, unsigned long end, int behavior)
+madvise_vma(struct task_struct *tsk, struct vm_area_struct *vma,
+		struct vm_area_struct **prev, unsigned long start,
+		unsigned long end, int behavior)
 {
 	switch (behavior) {
 	case MADV_REMOVE:
-		return madvise_remove(vma, prev, start, end);
+		return madvise_remove(tsk, vma, prev, start, end);
 	case MADV_WILLNEED:
 		return madvise_willneed(vma, prev, start, end);
 	case MADV_COOL:
@@ -930,7 +933,8 @@ madvise_vma(struct vm_area_struct *vma, struct vm_area_struct **prev,
 		return madvise_cold(vma, start, end);
 	case MADV_FREE:
 	case MADV_DONTNEED:
-		return madvise_dontneed_free(vma, prev, start, end, behavior);
+		return madvise_dontneed_free(tsk, vma, prev, start,
+						end, behavior);
 	default:
 		return madvise_behavior(vma, prev, start, end, behavior);
 	}
@@ -974,68 +978,8 @@ madvise_behavior_valid(int behavior)
 	}
 }
 
-/*
- * The madvise(2) system call.
- *
- * Applications can use madvise() to advise the kernel how it should
- * handle paging I/O in this VM area.  The idea is to help the kernel
- * use appropriate read-ahead and caching techniques.  The information
- * provided is advisory only, and can be safely disregarded by the
- * kernel without affecting the correct operation of the application.
- *
- * behavior values:
- *  MADV_NORMAL - the default behavior is to read clusters.  This
- *		results in some read-ahead and read-behind.
- *  MADV_RANDOM - the system should read the minimum amount of data
- *		on any access, since it is unlikely that the appli-
- *		cation will need more than what it asks for.
- *  MADV_SEQUENTIAL - pages in the given range will probably be accessed
- *		once, so they can be aggressively read ahead, and
- *		can be freed soon after they are accessed.
- *  MADV_WILLNEED - the application is notifying the system to read
- *		some pages ahead.
- *  MADV_DONTNEED - the application is finished with the given range,
- *		so the kernel can free resources associated with it.
- *  MADV_FREE - the application marks pages in the given range as lazy free,
- *		where actual purges are postponed until memory pressure happens.
- *  MADV_REMOVE - the application wants to free up the given range of
- *		pages and associated backing store.
- *  MADV_DONTFORK - omit this area from child's address space when forking:
- *		typically, to avoid COWing pages pinned by get_user_pages().
- *  MADV_DOFORK - cancel MADV_DONTFORK: no longer omit this area when forking.
- *  MADV_WIPEONFORK - present the child process with zero-filled memory in this
- *              range after a fork.
- *  MADV_KEEPONFORK - undo the effect of MADV_WIPEONFORK
- *  MADV_HWPOISON - trigger memory error handler as if the given memory range
- *		were corrupted by unrecoverable hardware memory failure.
- *  MADV_SOFT_OFFLINE - try to soft-offline the given range of memory.
- *  MADV_MERGEABLE - the application recommends that KSM try to merge pages in
- *		this area with pages of identical content from other such areas.
- *  MADV_UNMERGEABLE- cancel MADV_MERGEABLE: no longer merge pages with others.
- *  MADV_HUGEPAGE - the application wants to back the given range by transparent
- *		huge pages in the future. Existing pages might be coalesced and
- *		new pages might be allocated as THP.
- *  MADV_NOHUGEPAGE - mark the given range as not worth being backed by
- *		transparent huge pages so the existing pages will not be
- *		coalesced into THP and new pages will not be allocated as THP.
- *  MADV_DONTDUMP - the application wants to prevent pages in the given range
- *		from being included in its core dump.
- *  MADV_DODUMP - cancel MADV_DONTDUMP: no longer exclude from core dump.
- *
- * return values:
- *  zero    - success
- *  -EINVAL - start + len < 0, start is not page-aligned,
- *		"behavior" is not a valid value, or application
- *		is attempting to release locked or shared pages,
- *		or the specified address range includes file, Huge TLB,
- *		MAP_SHARED or VMPFNMAP range.
- *  -ENOMEM - addresses in the specified range are not currently
- *		mapped, or are outside the AS of the process.
- *  -EIO    - an I/O error occurred while paging in data.
- *  -EBADF  - map exists, but area maps something that isn't a file.
- *  -EAGAIN - a kernel resource was temporarily unavailable.
- */
-SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
+static int madvise_core(struct task_struct *tsk, unsigned long start,
+			size_t len_in, int behavior)
 {
 	unsigned long end, tmp;
 	struct vm_area_struct *vma, *prev;
@@ -1071,10 +1015,10 @@ SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
 
 	write = madvise_need_mmap_write(behavior);
 	if (write) {
-		if (down_write_killable(&current->mm->mmap_sem))
+		if (down_write_killable(&tsk->mm->mmap_sem))
 			return -EINTR;
 	} else {
-		down_read(&current->mm->mmap_sem);
+		down_read(&tsk->mm->mmap_sem);
 	}
 
 	/*
@@ -1082,7 +1026,7 @@ SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
 	 * ranges, just ignore them, but return -ENOMEM at the end.
 	 * - different from the way of handling in mlock etc.
 	 */
-	vma = find_vma_prev(current->mm, start, &prev);
+	vma = find_vma_prev(tsk->mm, start, &prev);
 	if (vma && start > vma->vm_start)
 		prev = vma;
 
@@ -1107,7 +1051,7 @@ SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
 			tmp = end;
 
 		/* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */
-		error = madvise_vma(vma, &prev, start, tmp, behavior);
+		error = madvise_vma(tsk, vma, &prev, start, tmp, behavior);
 		if (error)
 			goto out;
 		start = tmp;
@@ -1119,14 +1063,80 @@ SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
 		if (prev)
 			vma = prev->vm_next;
 		else	/* madvise_remove dropped mmap_sem */
-			vma = find_vma(current->mm, start);
+			vma = find_vma(tsk->mm, start);
 	}
 out:
 	blk_finish_plug(&plug);
 	if (write)
-		up_write(&current->mm->mmap_sem);
+		up_write(&tsk->mm->mmap_sem);
 	else
-		up_read(&current->mm->mmap_sem);
+		up_read(&tsk->mm->mmap_sem);
 
 	return error;
 }
+
+/*
+ * The madvise(2) system call.
+ *
+ * Applications can use madvise() to advise the kernel how it should
+ * handle paging I/O in this VM area.  The idea is to help the kernel
+ * use appropriate read-ahead and caching techniques.  The information
+ * provided is advisory only, and can be safely disregarded by the
+ * kernel without affecting the correct operation of the application.
+ *
+ * behavior values:
+ *  MADV_NORMAL - the default behavior is to read clusters.  This
+ *		results in some read-ahead and read-behind.
+ *  MADV_RANDOM - the system should read the minimum amount of data
+ *		on any access, since it is unlikely that the appli-
+ *		cation will need more than what it asks for.
+ *  MADV_SEQUENTIAL - pages in the given range will probably be accessed
+ *		once, so they can be aggressively read ahead, and
+ *		can be freed soon after they are accessed.
+ *  MADV_WILLNEED - the application is notifying the system to read
+ *		some pages ahead.
+ *  MADV_DONTNEED - the application is finished with the given range,
+ *		so the kernel can free resources associated with it.
+ *  MADV_FREE - the application marks pages in the given range as lazy free,
+ *		where actual purges are postponed until memory pressure happens.
+ *  MADV_REMOVE - the application wants to free up the given range of
+ *		pages and associated backing store.
+ *  MADV_DONTFORK - omit this area from child's address space when forking:
+ *		typically, to avoid COWing pages pinned by get_user_pages().
+ *  MADV_DOFORK - cancel MADV_DONTFORK: no longer omit this area when forking.
+ *  MADV_WIPEONFORK - present the child process with zero-filled memory in this
+ *              range after a fork.
+ *  MADV_KEEPONFORK - undo the effect of MADV_WIPEONFORK
+ *  MADV_HWPOISON - trigger memory error handler as if the given memory range
+ *		were corrupted by unrecoverable hardware memory failure.
+ *  MADV_SOFT_OFFLINE - try to soft-offline the given range of memory.
+ *  MADV_MERGEABLE - the application recommends that KSM try to merge pages in
+ *		this area with pages of identical content from other such areas.
+ *  MADV_UNMERGEABLE- cancel MADV_MERGEABLE: no longer merge pages with others.
+ *  MADV_HUGEPAGE - the application wants to back the given range by transparent
+ *		huge pages in the future. Existing pages might be coalesced and
+ *		new pages might be allocated as THP.
+ *  MADV_NOHUGEPAGE - mark the given range as not worth being backed by
+ *		transparent huge pages so the existing pages will not be
+ *		coalesced into THP and new pages will not be allocated as THP.
+ *  MADV_DONTDUMP - the application wants to prevent pages in the given range
+ *		from being included in its core dump.
+ *  MADV_DODUMP - cancel MADV_DONTDUMP: no longer exclude from core dump.
+ *
+ * return values:
+ *  zero    - success
+ *  -EINVAL - start + len < 0, start is not page-aligned,
+ *		"behavior" is not a valid value, or application
+ *		is attempting to release locked or shared pages,
+ *		or the specified address range includes file, Huge TLB,
+ *		MAP_SHARED or VMPFNMAP range.
+ *  -ENOMEM - addresses in the specified range are not currently
+ *		mapped, or are outside the AS of the process.
+ *  -EIO    - an I/O error occurred while paging in data.
+ *  -EBADF  - map exists, but area maps something that isn't a file.
+ *  -EAGAIN - a kernel resource was temporarily unavailable.
+ */
+SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
+{
+	return madvise_core(current, start, len_in, behavior);
+}
Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
#21 lore raw

Re: [RFC 4/7] mm: factor out madvise's core functionality

Hi.

Quoted 62 lines · Minchan Kim

This patch factor out madvise's core functionality so that upcoming patch can reuse it without duplication.

It shouldn't change any behavior.

---
 mm/madvise.c | 168 +++++++++++++++++++++++++++------------------------
 1 file changed, 89 insertions(+), 79 deletions(-)
mm/madvise.c +8 -6
index 9a6698b56845..119e82e1f065 100644
@@ -742,7 +742,8 @@ static long madvise_dontneed_single_vma(struct vm_area_struct *vma,
 	return 0;
 }
 
-static long madvise_dontneed_free(struct vm_area_struct *vma,
+static long madvise_dontneed_free(struct task_struct *tsk,
+				  struct vm_area_struct *vma,
 				  struct vm_area_struct **prev,
 				  unsigned long start, unsigned long end,
 				  int behavior)
@@ -754,8 +755,8 @@ static long madvise_dontneed_free(struct vm_area_struct *vma,
 	if (!userfaultfd_remove(vma, start, end)) {
 		*prev = NULL; /* mmap_sem has been dropped, prev is stale */
 
-		down_read(&current->mm->mmap_sem);
-		vma = find_vma(current->mm, start);
+		down_read(&tsk->mm->mmap_sem);
+		vma = find_vma(tsk->mm, start);
 		if (!vma)
 			return -ENOMEM;
 		if (start < vma->vm_start) {
@@ -802,7 +803,8 @@ static long madvise_dontneed_free(struct vm_area_struct *vma,
  * Application wants to free up the pages and associated backing store.
  * This is effectively punching a hole into the middle of a file.
  */
-static long madvise_remove(struct vm_area_struct *vma,
+static long madvise_remove(struct task_struct *tsk,
+				struct vm_area_struct *vma,
 				struct vm_area_struct **prev,
 				unsigned long start, unsigned long end)
 {
@@ -836,13 +838,13 @@ static long madvise_remove(struct vm_area_struct *vma,
 	get_file(f);
 	if (userfaultfd_remove(vma, start, end)) {
 		/* mmap_sem was not released by userfaultfd_remove() */
-		up_read(&current->mm->mmap_sem);
+		up_read(&tsk->mm->mmap_sem);
 	}
 	error = vfs_fallocate(f,
 				FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
 				offset, end - start);
 	fput(f);
-	down_read(&current->mm->mmap_sem);
+	down_read(&tsk->mm->mmap_sem);
 	return error;
 }
 

mm/madvise.c static int madvise_inject_error(int behavior, · line 918

Quoted 1 line
mm/madvise.c +0 -0
@@ -916,12 +918,13 @@ static int madvise_inject_error(int behavior,
 #endif

What about madvise_inject_error() and get_user_pages_fast() in it please?

Quoted 214 lines
mm/madvise.c +81 -73
 static long
-madvise_vma(struct vm_area_struct *vma, struct vm_area_struct **prev,
-		unsigned long start, unsigned long end, int behavior)
+madvise_vma(struct task_struct *tsk, struct vm_area_struct *vma,
+		struct vm_area_struct **prev, unsigned long start,
+		unsigned long end, int behavior)
 {
 	switch (behavior) {
 	case MADV_REMOVE:
-		return madvise_remove(vma, prev, start, end);
+		return madvise_remove(tsk, vma, prev, start, end);
 	case MADV_WILLNEED:
 		return madvise_willneed(vma, prev, start, end);
 	case MADV_COOL:
@@ -930,7 +933,8 @@ madvise_vma(struct vm_area_struct *vma, struct vm_area_struct **prev,
 		return madvise_cold(vma, start, end);
 	case MADV_FREE:
 	case MADV_DONTNEED:
-		return madvise_dontneed_free(vma, prev, start, end, behavior);
+		return madvise_dontneed_free(tsk, vma, prev, start,
+						end, behavior);
 	default:
 		return madvise_behavior(vma, prev, start, end, behavior);
 	}
@@ -974,68 +978,8 @@ madvise_behavior_valid(int behavior)
 	}
 }
 
-/*
- * The madvise(2) system call.
- *
- * Applications can use madvise() to advise the kernel how it should
- * handle paging I/O in this VM area.  The idea is to help the kernel
- * use appropriate read-ahead and caching techniques.  The information
- * provided is advisory only, and can be safely disregarded by the
- * kernel without affecting the correct operation of the application.
- *
- * behavior values:
- *  MADV_NORMAL - the default behavior is to read clusters.  This
- *		results in some read-ahead and read-behind.
- *  MADV_RANDOM - the system should read the minimum amount of data
- *		on any access, since it is unlikely that the appli-
- *		cation will need more than what it asks for.
- *  MADV_SEQUENTIAL - pages in the given range will probably be accessed
- *		once, so they can be aggressively read ahead, and
- *		can be freed soon after they are accessed.
- *  MADV_WILLNEED - the application is notifying the system to read
- *		some pages ahead.
- *  MADV_DONTNEED - the application is finished with the given range,
- *		so the kernel can free resources associated with it.
- *  MADV_FREE - the application marks pages in the given range as lazy free,
- *		where actual purges are postponed until memory pressure happens.
- *  MADV_REMOVE - the application wants to free up the given range of
- *		pages and associated backing store.
- *  MADV_DONTFORK - omit this area from child's address space when forking:
- *		typically, to avoid COWing pages pinned by get_user_pages().
- *  MADV_DOFORK - cancel MADV_DONTFORK: no longer omit this area when forking.
- *  MADV_WIPEONFORK - present the child process with zero-filled memory in this
- *              range after a fork.
- *  MADV_KEEPONFORK - undo the effect of MADV_WIPEONFORK
- *  MADV_HWPOISON - trigger memory error handler as if the given memory range
- *		were corrupted by unrecoverable hardware memory failure.
- *  MADV_SOFT_OFFLINE - try to soft-offline the given range of memory.
- *  MADV_MERGEABLE - the application recommends that KSM try to merge pages in
- *		this area with pages of identical content from other such areas.
- *  MADV_UNMERGEABLE- cancel MADV_MERGEABLE: no longer merge pages with others.
- *  MADV_HUGEPAGE - the application wants to back the given range by transparent
- *		huge pages in the future. Existing pages might be coalesced and
- *		new pages might be allocated as THP.
- *  MADV_NOHUGEPAGE - mark the given range as not worth being backed by
- *		transparent huge pages so the existing pages will not be
- *		coalesced into THP and new pages will not be allocated as THP.
- *  MADV_DONTDUMP - the application wants to prevent pages in the given range
- *		from being included in its core dump.
- *  MADV_DODUMP - cancel MADV_DONTDUMP: no longer exclude from core dump.
- *
- * return values:
- *  zero    - success
- *  -EINVAL - start + len < 0, start is not page-aligned,
- *		"behavior" is not a valid value, or application
- *		is attempting to release locked or shared pages,
- *		or the specified address range includes file, Huge TLB,
- *		MAP_SHARED or VMPFNMAP range.
- *  -ENOMEM - addresses in the specified range are not currently
- *		mapped, or are outside the AS of the process.
- *  -EIO    - an I/O error occurred while paging in data.
- *  -EBADF  - map exists, but area maps something that isn't a file.
- *  -EAGAIN - a kernel resource was temporarily unavailable.
- */
-SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
+static int madvise_core(struct task_struct *tsk, unsigned long start,
+			size_t len_in, int behavior)
 {
 	unsigned long end, tmp;
 	struct vm_area_struct *vma, *prev;
@@ -1071,10 +1015,10 @@ SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
 
 	write = madvise_need_mmap_write(behavior);
 	if (write) {
-		if (down_write_killable(&current->mm->mmap_sem))
+		if (down_write_killable(&tsk->mm->mmap_sem))
 			return -EINTR;
 	} else {
-		down_read(&current->mm->mmap_sem);
+		down_read(&tsk->mm->mmap_sem);
 	}
 
 	/*
@@ -1082,7 +1026,7 @@ SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
 	 * ranges, just ignore them, but return -ENOMEM at the end.
 	 * - different from the way of handling in mlock etc.
 	 */
-	vma = find_vma_prev(current->mm, start, &prev);
+	vma = find_vma_prev(tsk->mm, start, &prev);
 	if (vma && start > vma->vm_start)
 		prev = vma;
 
@@ -1107,7 +1051,7 @@ SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
 			tmp = end;
 
 		/* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */
-		error = madvise_vma(vma, &prev, start, tmp, behavior);
+		error = madvise_vma(tsk, vma, &prev, start, tmp, behavior);
 		if (error)
 			goto out;
 		start = tmp;
@@ -1119,14 +1063,80 @@ SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
 		if (prev)
 			vma = prev->vm_next;
 		else	/* madvise_remove dropped mmap_sem */
-			vma = find_vma(current->mm, start);
+			vma = find_vma(tsk->mm, start);
 	}
 out:
 	blk_finish_plug(&plug);
 	if (write)
-		up_write(&current->mm->mmap_sem);
+		up_write(&tsk->mm->mmap_sem);
 	else
-		up_read(&current->mm->mmap_sem);
+		up_read(&tsk->mm->mmap_sem);
 
 	return error;
 }
+
+/*
+ * The madvise(2) system call.
+ *
+ * Applications can use madvise() to advise the kernel how it should
+ * handle paging I/O in this VM area.  The idea is to help the kernel
+ * use appropriate read-ahead and caching techniques.  The information
+ * provided is advisory only, and can be safely disregarded by the
+ * kernel without affecting the correct operation of the application.
+ *
+ * behavior values:
+ *  MADV_NORMAL - the default behavior is to read clusters.  This
+ *		results in some read-ahead and read-behind.
+ *  MADV_RANDOM - the system should read the minimum amount of data
+ *		on any access, since it is unlikely that the appli-
+ *		cation will need more than what it asks for.
+ *  MADV_SEQUENTIAL - pages in the given range will probably be accessed
+ *		once, so they can be aggressively read ahead, and
+ *		can be freed soon after they are accessed.
+ *  MADV_WILLNEED - the application is notifying the system to read
+ *		some pages ahead.
+ *  MADV_DONTNEED - the application is finished with the given range,
+ *		so the kernel can free resources associated with it.
+ *  MADV_FREE - the application marks pages in the given range as lazy free,
+ *		where actual purges are postponed until memory pressure happens.
+ *  MADV_REMOVE - the application wants to free up the given range of
+ *		pages and associated backing store.
+ *  MADV_DONTFORK - omit this area from child's address space when forking:
+ *		typically, to avoid COWing pages pinned by get_user_pages().
+ *  MADV_DOFORK - cancel MADV_DONTFORK: no longer omit this area when forking.
+ *  MADV_WIPEONFORK - present the child process with zero-filled memory in this
+ *              range after a fork.
+ *  MADV_KEEPONFORK - undo the effect of MADV_WIPEONFORK
+ *  MADV_HWPOISON - trigger memory error handler as if the given memory range
+ *		were corrupted by unrecoverable hardware memory failure.
+ *  MADV_SOFT_OFFLINE - try to soft-offline the given range of memory.
+ *  MADV_MERGEABLE - the application recommends that KSM try to merge pages in
+ *		this area with pages of identical content from other such areas.
+ *  MADV_UNMERGEABLE- cancel MADV_MERGEABLE: no longer merge pages with others.
+ *  MADV_HUGEPAGE - the application wants to back the given range by transparent
+ *		huge pages in the future. Existing pages might be coalesced and
+ *		new pages might be allocated as THP.
+ *  MADV_NOHUGEPAGE - mark the given range as not worth being backed by
+ *		transparent huge pages so the existing pages will not be
+ *		coalesced into THP and new pages will not be allocated as THP.
+ *  MADV_DONTDUMP - the application wants to prevent pages in the given range
+ *		from being included in its core dump.
+ *  MADV_DODUMP - cancel MADV_DONTDUMP: no longer exclude from core dump.
+ *
+ * return values:
+ *  zero    - success
+ *  -EINVAL - start + len < 0, start is not page-aligned,
+ *		"behavior" is not a valid value, or application
+ *		is attempting to release locked or shared pages,
+ *		or the specified address range includes file, Huge TLB,
+ *		MAP_SHARED or VMPFNMAP range.
+ *  -ENOMEM - addresses in the specified range are not currently
+ *		mapped, or are outside the AS of the process.
+ *  -EIO    - an I/O error occurred while paging in data.
+ *  -EBADF  - map exists, but area maps something that isn't a file.
+ *  -EAGAIN - a kernel resource was temporarily unavailable.
+ */
+SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
+{
+	return madvise_core(current, start, len_in, behavior);
+}
Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
Signature · 3 lines
  Best regards,
    Oleksandr Natalenko (post-factum)
    Senior Software Maintenance Engineer
#22 lore raw

Re: [RFC 4/7] mm: factor out madvise's core functionality

Hi Oleksandr,

Quoted 64 lines · Oleksandr Natalenko

Hi.

Quoted 61 lines · Minchan Kim

This patch factor out madvise's core functionality so that upcoming patch can reuse it without duplication.

It shouldn't change any behavior.

---
 mm/madvise.c | 168 +++++++++++++++++++++++++++------------------------
 1 file changed, 89 insertions(+), 79 deletions(-)
mm/madvise.c +8 -6
index 9a6698b56845..119e82e1f065 100644
@@ -742,7 +742,8 @@ static long madvise_dontneed_single_vma(struct vm_area_struct *vma,
 	return 0;
 }
 
-static long madvise_dontneed_free(struct vm_area_struct *vma,
+static long madvise_dontneed_free(struct task_struct *tsk,
+				  struct vm_area_struct *vma,
 				  struct vm_area_struct **prev,
 				  unsigned long start, unsigned long end,
 				  int behavior)
@@ -754,8 +755,8 @@ static long madvise_dontneed_free(struct vm_area_struct *vma,
 	if (!userfaultfd_remove(vma, start, end)) {
 		*prev = NULL; /* mmap_sem has been dropped, prev is stale */
 
-		down_read(&current->mm->mmap_sem);
-		vma = find_vma(current->mm, start);
+		down_read(&tsk->mm->mmap_sem);
+		vma = find_vma(tsk->mm, start);
 		if (!vma)
 			return -ENOMEM;
 		if (start < vma->vm_start) {
@@ -802,7 +803,8 @@ static long madvise_dontneed_free(struct vm_area_struct *vma,
  * Application wants to free up the pages and associated backing store.
  * This is effectively punching a hole into the middle of a file.
  */
-static long madvise_remove(struct vm_area_struct *vma,
+static long madvise_remove(struct task_struct *tsk,
+				struct vm_area_struct *vma,
 				struct vm_area_struct **prev,
 				unsigned long start, unsigned long end)
 {
@@ -836,13 +838,13 @@ static long madvise_remove(struct vm_area_struct *vma,
 	get_file(f);
 	if (userfaultfd_remove(vma, start, end)) {
 		/* mmap_sem was not released by userfaultfd_remove() */
-		up_read(&current->mm->mmap_sem);
+		up_read(&tsk->mm->mmap_sem);
 	}
 	error = vfs_fallocate(f,
 				FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
 				offset, end - start);
 	fput(f);
-	down_read(&current->mm->mmap_sem);
+	down_read(&tsk->mm->mmap_sem);
 	return error;
 }
 
Quoted 5 lines

mm/madvise.c static int madvise_inject_error(int behavior, · line 918

Quoted 2 lines
mm/madvise.c +0 -0
@@ -916,12 +918,13 @@ static int madvise_inject_error(int behavior,
 #endif

What about madvise_inject_error() and get_user_pages_fast() in it please?

Good point. Maybe, there more places where assume context is "current" so I'm thinking to limit hints we could allow from external process. It would be better for maintainance point of view in that we could know the workload/usecases when someone ask new advises from external process without making every hints works both contexts.

Thanks.

#23 lore raw

Re: [RFC 4/7] mm: factor out madvise's core functionality

Hi.

Quoted 71 lines · Minchan Kim
Quoted 64 lines · Oleksandr Natalenko

Hi.

Quoted 61 lines · Minchan Kim

This patch factor out madvise's core functionality so that upcoming patch can reuse it without duplication.

It shouldn't change any behavior.

---
 mm/madvise.c | 168 +++++++++++++++++++++++++++------------------------
 1 file changed, 89 insertions(+), 79 deletions(-)
mm/madvise.c +8 -6
index 9a6698b56845..119e82e1f065 100644
@@ -742,7 +742,8 @@ static long madvise_dontneed_single_vma(struct vm_area_struct *vma,
 	return 0;
 }
 
-static long madvise_dontneed_free(struct vm_area_struct *vma,
+static long madvise_dontneed_free(struct task_struct *tsk,
+				  struct vm_area_struct *vma,
 				  struct vm_area_struct **prev,
 				  unsigned long start, unsigned long end,
 				  int behavior)
@@ -754,8 +755,8 @@ static long madvise_dontneed_free(struct vm_area_struct *vma,
 	if (!userfaultfd_remove(vma, start, end)) {
 		*prev = NULL; /* mmap_sem has been dropped, prev is stale */
 
-		down_read(&current->mm->mmap_sem);
-		vma = find_vma(current->mm, start);
+		down_read(&tsk->mm->mmap_sem);
+		vma = find_vma(tsk->mm, start);
 		if (!vma)
 			return -ENOMEM;
 		if (start < vma->vm_start) {
@@ -802,7 +803,8 @@ static long madvise_dontneed_free(struct vm_area_struct *vma,
  * Application wants to free up the pages and associated backing store.
  * This is effectively punching a hole into the middle of a file.
  */
-static long madvise_remove(struct vm_area_struct *vma,
+static long madvise_remove(struct task_struct *tsk,
+				struct vm_area_struct *vma,
 				struct vm_area_struct **prev,
 				unsigned long start, unsigned long end)
 {
@@ -836,13 +838,13 @@ static long madvise_remove(struct vm_area_struct *vma,
 	get_file(f);
 	if (userfaultfd_remove(vma, start, end)) {
 		/* mmap_sem was not released by userfaultfd_remove() */
-		up_read(&current->mm->mmap_sem);
+		up_read(&tsk->mm->mmap_sem);
 	}
 	error = vfs_fallocate(f,
 				FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
 				offset, end - start);
 	fput(f);
-	down_read(&current->mm->mmap_sem);
+	down_read(&tsk->mm->mmap_sem);
 	return error;
 }
 
Quoted 5 lines

mm/madvise.c static int madvise_inject_error(int behavior, · line 918

Quoted 2 lines
mm/madvise.c +0 -0
@@ -916,12 +918,13 @@ static int madvise_inject_error(int behavior,
 #endif

What about madvise_inject_error() and get_user_pages_fast() in it please?

Quoted 5 lines

Good point. Maybe, there more places where assume context is "current" so I'm thinking to limit hints we could allow from external process. It would be better for maintainance point of view in that we could know the workload/usecases when someone ask new advises from external process without making every hints works both contexts.

Well, for madvise_inject_error() we still have a remote variant of get_user_pages(), and that should work, no?

Regarding restricting the hints, I'm definitely interested in having remote MADV_MERGEABLE/MADV_UNMERGEABLE. But, OTOH, doing it via remote madvise() introduces another issue with traversing remote VMAs reliably. IIUC, one can do this via userspace by parsing [s]maps file only, which is not very consistent, and once some range is parsed, and then it is immediately gone, a wrong hint will be sent.

Isn't this a problem we should worry about?

Quoted 2 lines

Thanks.

Signature · 3 lines
  Best regards,
    Oleksandr Natalenko (post-factum)
    Senior Software Maintenance Engineer
reviewer
#24 lore raw

Re: [RFC 4/7] mm: factor out madvise's core functionality

On Tue 21-05-19 08:36:28, Oleksandr Natalenko wrote:
[...]

Quoted 8 lines

Regarding restricting the hints, I'm definitely interested in having remote MADV_MERGEABLE/MADV_UNMERGEABLE. But, OTOH, doing it via remote madvise() introduces another issue with traversing remote VMAs reliably. IIUC, one can do this via userspace by parsing [s]maps file only, which is not very consistent, and once some range is parsed, and then it is immediately gone, a wrong hint will be sent.

Isn't this a problem we should worry about?

See http://lkml.kernel.org/r/[email protected]

Signature · 2 lines
Michal Hocko
SUSE Labs
#25 lore raw

Re: [RFC 4/7] mm: factor out madvise's core functionality

Hi.

Quoted 9 lines · Michal Hocko

On Tue 21-05-19 08:36:28, Oleksandr Natalenko wrote:
[...]

Quoted 7 lines

Regarding restricting the hints, I'm definitely interested in having remote MADV_MERGEABLE/MADV_UNMERGEABLE. But, OTOH, doing it via remote madvise() introduces another issue with traversing remote VMAs reliably. IIUC, one can do this via userspace by parsing [s]maps file only, which is not very consistent, and once some range is parsed, and then it is immediately gone, a wrong hint will be sent.

Quoted 3 lines
Quoted 1 line

Isn't this a problem we should worry about?

See http://lkml.kernel.org/r/[email protected]

Oh, thanks for the pointer.

Indeed, for my specific task with remote KSM I'd go with map_files instead. This doesn't solve the task completely in case of traversal through all the VMAs in one pass, but makes it easier comparing to a remote syscall.

Signature · 3 lines
  Best regards,
    Oleksandr Natalenko (post-factum)
    Senior Software Maintenance Engineer
#26 lore raw

Re: [RFC 4/7] mm: factor out madvise's core functionality

Quoted 14 lines · Oleksandr Natalenko

Hi.

Quoted 11 lines · Michal Hocko

On Tue 21-05-19 08:36:28, Oleksandr Natalenko wrote:
[...]

Quoted 8 lines

Regarding restricting the hints, I'm definitely interested in having remote MADV_MERGEABLE/MADV_UNMERGEABLE. But, OTOH, doing it via remote madvise() introduces another issue with traversing remote VMAs reliably. IIUC, one can do this via userspace by parsing [s]maps file only, which is not very consistent, and once some range is parsed, and then it is immediately gone, a wrong hint will be sent.

Isn't this a problem we should worry about?

Quoted 8 lines
Quoted 1 line

See http://lkml.kernel.org/r/[email protected]

Oh, thanks for the pointer.

Indeed, for my specific task with remote KSM I'd go with map_files instead. This doesn't solve the task completely in case of traversal through all the VMAs in one pass, but makes it easier comparing to a remote syscall.

I'm wondering how map_files can solve your concern exactly if you have a concern about the race of vma unmap/remap even there are anonymous vma which map_files doesn't support.

Quoted 5 lines
Signature · 4 lines
-- 
  Best regards,
    Oleksandr Natalenko (post-factum)
    Senior Software Maintenance Engineer
reviewer
#27 lore raw

Re: [RFC 4/7] mm: factor out madvise's core functionality

Quoted 19 lines · Minchan Kim
Quoted 18 lines · Oleksandr Natalenko

Hi.

Quoted 9 lines · Michal Hocko

On Tue 21-05-19 08:36:28, Oleksandr Natalenko wrote:
[...]

Quoted 7 lines

Regarding restricting the hints, I'm definitely interested in having remote MADV_MERGEABLE/MADV_UNMERGEABLE. But, OTOH, doing it via remote madvise() introduces another issue with traversing remote VMAs reliably. IIUC, one can do this via userspace by parsing [s]maps file only, which is not very consistent, and once some range is parsed, and then it is immediately gone, a wrong hint will be sent.

Quoted 3 lines
Quoted 1 line

Isn't this a problem we should worry about?

See http://lkml.kernel.org/r/[email protected]

Oh, thanks for the pointer.

Quoted 8 lines
Quoted 4 lines

Indeed, for my specific task with remote KSM I'd go with map_files instead. This doesn't solve the task completely in case of traversal through all the VMAs in one pass, but makes it easier comparing to a remote syscall.

I'm wondering how map_files can solve your concern exactly if you have a concern about the race of vma unmap/remap even there are anonymous vma which map_files doesn't support.

See http://lkml.kernel.org/r/[email protected]

Signature · 2 lines
Michal Hocko
SUSE Labs
#28 lore raw

Re: [RFC 4/7] mm: factor out madvise's core functionality

Quoted 25 lines · Michal Hocko
Quoted 24 lines · Minchan Kim
Quoted 22 lines · Oleksandr Natalenko

Hi.

Quoted 9 lines · Michal Hocko

On Tue 21-05-19 08:36:28, Oleksandr Natalenko wrote:
[...]

Quoted 7 lines

Regarding restricting the hints, I'm definitely interested in having remote MADV_MERGEABLE/MADV_UNMERGEABLE. But, OTOH, doing it via remote madvise() introduces another issue with traversing remote VMAs reliably. IIUC, one can do this via userspace by parsing [s]maps file only, which is not very consistent, and once some range is parsed, and then it is immediately gone, a wrong hint will be sent.

Quoted 3 lines
Quoted 1 line

Isn't this a problem we should worry about?

See http://lkml.kernel.org/r/[email protected]

Oh, thanks for the pointer.

Indeed, for my specific task with remote KSM I'd go with map_files instead. This doesn't solve the task completely in case of traversal through all the VMAs in one pass, but makes it easier comparing to a remote syscall.

Quoted 5 lines
Quoted 3 lines

I'm wondering how map_files can solve your concern exactly if you have a concern about the race of vma unmap/remap even there are anonymous vma which map_files doesn't support.

See http://lkml.kernel.org/r/[email protected]

Question is how it works for anonymous vma which don't have backing file.

Quoted 4 lines
Signature · 3 lines
-- 
Michal Hocko
SUSE Labs
reviewer
#29 lore raw

Re: [RFC 4/7] mm: factor out madvise's core functionality

Quoted 26 lines · Minchan Kim
Quoted 25 lines · Michal Hocko
Quoted 24 lines · Minchan Kim
Quoted 22 lines · Oleksandr Natalenko

Hi.

Quoted 9 lines · Michal Hocko

On Tue 21-05-19 08:36:28, Oleksandr Natalenko wrote:
[...]

Quoted 7 lines

Regarding restricting the hints, I'm definitely interested in having remote MADV_MERGEABLE/MADV_UNMERGEABLE. But, OTOH, doing it via remote madvise() introduces another issue with traversing remote VMAs reliably. IIUC, one can do this via userspace by parsing [s]maps file only, which is not very consistent, and once some range is parsed, and then it is immediately gone, a wrong hint will be sent.

Quoted 3 lines
Quoted 1 line

Isn't this a problem we should worry about?

See http://lkml.kernel.org/r/[email protected]

Oh, thanks for the pointer.

Indeed, for my specific task with remote KSM I'd go with map_files instead. This doesn't solve the task completely in case of traversal through all the VMAs in one pass, but makes it easier comparing to a remote syscall.

Quoted 8 lines
Quoted 5 lines
Quoted 3 lines

I'm wondering how map_files can solve your concern exactly if you have a concern about the race of vma unmap/remap even there are anonymous vma which map_files doesn't support.

See http://lkml.kernel.org/r/[email protected]

Question is how it works for anonymous vma which don't have backing file.

We would have to export map_files like interface for anonymous vmas and have a way to invalidate on the VMA removal (reference counting or something similar), no question this will be some additional work to do.

Signature · 2 lines
Michal Hocko
SUSE Labs
#30 lore raw

Re: [RFC 4/7] mm: factor out madvise's core functionality

In reply to Oleksandr Natalenko
Quoted 74 lines · Oleksandr Natalenko

Hi.

Quoted 71 lines · Minchan Kim
Quoted 69 lines · Oleksandr Natalenko

Hi.

Quoted 62 lines · Minchan Kim

This patch factor out madvise's core functionality so that upcoming patch can reuse it without duplication.

It shouldn't change any behavior.

---
 mm/madvise.c | 168 +++++++++++++++++++++++++++------------------------
 1 file changed, 89 insertions(+), 79 deletions(-)
mm/madvise.c +8 -6
index 9a6698b56845..119e82e1f065 100644
@@ -742,7 +742,8 @@ static long madvise_dontneed_single_vma(struct vm_area_struct *vma,
 	return 0;
 }
 
-static long madvise_dontneed_free(struct vm_area_struct *vma,
+static long madvise_dontneed_free(struct task_struct *tsk,
+				  struct vm_area_struct *vma,
 				  struct vm_area_struct **prev,
 				  unsigned long start, unsigned long end,
 				  int behavior)
@@ -754,8 +755,8 @@ static long madvise_dontneed_free(struct vm_area_struct *vma,
 	if (!userfaultfd_remove(vma, start, end)) {
 		*prev = NULL; /* mmap_sem has been dropped, prev is stale */
 
-		down_read(&current->mm->mmap_sem);
-		vma = find_vma(current->mm, start);
+		down_read(&tsk->mm->mmap_sem);
+		vma = find_vma(tsk->mm, start);
 		if (!vma)
 			return -ENOMEM;
 		if (start < vma->vm_start) {
@@ -802,7 +803,8 @@ static long madvise_dontneed_free(struct vm_area_struct *vma,
  * Application wants to free up the pages and associated backing store.
  * This is effectively punching a hole into the middle of a file.
  */
-static long madvise_remove(struct vm_area_struct *vma,
+static long madvise_remove(struct task_struct *tsk,
+				struct vm_area_struct *vma,
 				struct vm_area_struct **prev,
 				unsigned long start, unsigned long end)
 {
@@ -836,13 +838,13 @@ static long madvise_remove(struct vm_area_struct *vma,
 	get_file(f);
 	if (userfaultfd_remove(vma, start, end)) {
 		/* mmap_sem was not released by userfaultfd_remove() */
-		up_read(&current->mm->mmap_sem);
+		up_read(&tsk->mm->mmap_sem);
 	}
 	error = vfs_fallocate(f,
 				FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
 				offset, end - start);
 	fput(f);
-	down_read(&current->mm->mmap_sem);
+	down_read(&tsk->mm->mmap_sem);
 	return error;
 }
 

mm/madvise.c static int madvise_inject_error(int behavior, · line 918

Quoted 1 line
mm/madvise.c +0 -0
@@ -916,12 +918,13 @@ static int madvise_inject_error(int behavior,
 #endif

What about madvise_inject_error() and get_user_pages_fast() in it please?

Quoted 8 lines
Quoted 5 lines

Good point. Maybe, there more places where assume context is "current" so I'm thinking to limit hints we could allow from external process. It would be better for maintainance point of view in that we could know the workload/usecases when someone ask new advises from external process without making every hints works both contexts.

Well, for madvise_inject_error() we still have a remote variant of get_user_pages(), and that should work, no?

Regardless of madvise_inject_error, it seems to be risky to expose all of hints for external process, I think. For example, MADV_DONTNEED with race, it's critical for stability. So, until we could get the way to prevent the race, I want to restrict hints.

Quoted 4 lines

Regarding restricting the hints, I'm definitely interested in having remote MADV_MERGEABLE/MADV_UNMERGEABLE. But, OTOH, doing it via remote madvise() introduces another issue with traversing remote VMAs reliably.

How is it signifiact when the race happens? It could waste CPU cycle and make unncessary break of that merged pages but expect it should be rare so such non-desruptive hint could be exposed via process_madvise, I think.

If the hint is critical for the race, yes, as Michal suggested, we need a way to close it and I guess non-cooperative userfaultfd with synchronous support would help private anonymous vma.

Quoted 5 lines

IIUC, one can do this via userspace by parsing [s]maps file only, which is not very consistent, and once some range is parsed, and then it is immediately gone, a wrong hint will be sent.

Isn't this a problem we should worry about?

I think it depends on the hint and usecase.

Quoted 8 lines
Quoted 3 lines

Thanks.

Signature · 3 lines
  Best regards,
    Oleksandr Natalenko (post-factum)
    Senior Software Maintenance Engineer
reviewer
#31 lore raw

Re: [RFC 4/7] mm: factor out madvise's core functionality

Quoted 81 lines · Minchan Kim
Quoted 80 lines · Oleksandr Natalenko

Hi.

Quoted 76 lines · Minchan Kim
Quoted 64 lines · Oleksandr Natalenko

Hi.

Quoted 61 lines · Minchan Kim

This patch factor out madvise's core functionality so that upcoming patch can reuse it without duplication.

It shouldn't change any behavior.

---
 mm/madvise.c | 168 +++++++++++++++++++++++++++------------------------
 1 file changed, 89 insertions(+), 79 deletions(-)
mm/madvise.c +8 -6
index 9a6698b56845..119e82e1f065 100644
@@ -742,7 +742,8 @@ static long madvise_dontneed_single_vma(struct vm_area_struct *vma,
 	return 0;
 }
 
-static long madvise_dontneed_free(struct vm_area_struct *vma,
+static long madvise_dontneed_free(struct task_struct *tsk,
+				  struct vm_area_struct *vma,
 				  struct vm_area_struct **prev,
 				  unsigned long start, unsigned long end,
 				  int behavior)
@@ -754,8 +755,8 @@ static long madvise_dontneed_free(struct vm_area_struct *vma,
 	if (!userfaultfd_remove(vma, start, end)) {
 		*prev = NULL; /* mmap_sem has been dropped, prev is stale */
 
-		down_read(&current->mm->mmap_sem);
-		vma = find_vma(current->mm, start);
+		down_read(&tsk->mm->mmap_sem);
+		vma = find_vma(tsk->mm, start);
 		if (!vma)
 			return -ENOMEM;
 		if (start < vma->vm_start) {
@@ -802,7 +803,8 @@ static long madvise_dontneed_free(struct vm_area_struct *vma,
  * Application wants to free up the pages and associated backing store.
  * This is effectively punching a hole into the middle of a file.
  */
-static long madvise_remove(struct vm_area_struct *vma,
+static long madvise_remove(struct task_struct *tsk,
+				struct vm_area_struct *vma,
 				struct vm_area_struct **prev,
 				unsigned long start, unsigned long end)
 {
@@ -836,13 +838,13 @@ static long madvise_remove(struct vm_area_struct *vma,
 	get_file(f);
 	if (userfaultfd_remove(vma, start, end)) {
 		/* mmap_sem was not released by userfaultfd_remove() */
-		up_read(&current->mm->mmap_sem);
+		up_read(&tsk->mm->mmap_sem);
 	}
 	error = vfs_fallocate(f,
 				FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
 				offset, end - start);
 	fput(f);
-	down_read(&current->mm->mmap_sem);
+	down_read(&tsk->mm->mmap_sem);
 	return error;
 }
 
Quoted 5 lines

mm/madvise.c static int madvise_inject_error(int behavior, · line 918

Quoted 2 lines
mm/madvise.c +0 -0
@@ -916,12 +918,13 @@ static int madvise_inject_error(int behavior,
 #endif

What about madvise_inject_error() and get_user_pages_fast() in it please?

Good point. Maybe, there more places where assume context is "current" so I'm thinking to limit hints we could allow from external process. It would be better for maintainance point of view in that we could know the workload/usecases when someone ask new advises from external process without making every hints works both contexts.

Quoted 7 lines
Quoted 2 lines

Well, for madvise_inject_error() we still have a remote variant of get_user_pages(), and that should work, no?

Regardless of madvise_inject_error, it seems to be risky to expose all of hints for external process, I think. For example, MADV_DONTNEED with race, it's critical for stability. So, until we could get the way to prevent the race, I want to restrict hints.

Well, if you allow the full ptrace access then you can shoot the target whatever you like.

Quoted 11 lines
Quoted 3 lines

Regarding restricting the hints, I'm definitely interested in having remote MADV_MERGEABLE/MADV_UNMERGEABLE. But, OTOH, doing it via remote madvise() introduces another issue with traversing remote VMAs reliably.

How is it signifiact when the race happens? It could waste CPU cycle and make unncessary break of that merged pages but expect it should be rare so such non-desruptive hint could be exposed via process_madvise, I think.

If the hint is critical for the race, yes, as Michal suggested, we need a way to close it and I guess non-cooperative userfaultfd with synchronous support would help private anonymous vma.

If we have a per vma fd approach then we can revalidate atomically and make sure the operation is performed on the range that was really requested. I do not think we want to provide a more specific guarantees. Monitor process has to be careful same way ptrace doesn't want to harm the target.

Signature · 2 lines
Michal Hocko
SUSE Labs
#32 lore raw

RFC 5/7 mm: introduce external memory hinting API

In reply to Minchan Kim

There is some usecase that centralized userspace daemon want to give a memory hint like MADV_[COOL|COLD] to other process. Android's ActivityManagerService is one of them.

It's similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to the centralized userspace daemon(ActivityManagerService), and that daemon must be able to initiate reclaim on its own without any app involvement.

To solve the issue, this patch introduces new syscall process_madvise(2) which works based on pidfd so it could give a hint to the exeternal process.

int process_madvise(int pidfd, void *addr, size_t length, int advise);

All advises madvise provides can be supported in process_madvise, too. Since it could affect other process's address range, only privileged process(CAP_SYS_PTRACE) or something else(e.g., being the same UID) gives it the right to ptrrace the process could use it successfully.

Please suggest better idea if you have other idea about the permission.

* from v1r1
* use ptrace capability - surenb, dancol

---
 arch/x86/entry/syscalls/syscall_32.tbl |  1 +
 arch/x86/entry/syscalls/syscall_64.tbl |  1 +
 include/linux/proc_fs.h                |  1 +
 include/linux/syscalls.h               |  2 ++
 include/uapi/asm-generic/unistd.h      |  2 ++
 kernel/signal.c                        |  2 +-
 kernel/sys_ni.c                        |  1 +
 mm/madvise.c                           | 45 ++++++++++++++++++++++++++
 8 files changed, 54 insertions(+), 1 deletion(-)
arch/x86/entry/syscalls/syscall_32.tbl +1 -0
index 4cd5f982b1e5..5b9dd55d6b57 100644
@@ -438,3 +438,4 @@
 425	i386	io_uring_setup		sys_io_uring_setup		__ia32_sys_io_uring_setup
 426	i386	io_uring_enter		sys_io_uring_enter		__ia32_sys_io_uring_enter
 427	i386	io_uring_register	sys_io_uring_register		__ia32_sys_io_uring_register
+428	i386	process_madvise		sys_process_madvise		__ia32_sys_process_madvise
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index 64ca0d06259a..0e5ee78161c9 100644
@@ -355,6 +355,7 @@
 425	common	io_uring_setup		__x64_sys_io_uring_setup
 426	common	io_uring_enter		__x64_sys_io_uring_enter
 427	common	io_uring_register	__x64_sys_io_uring_register
+428	common	process_madvise		__x64_sys_process_madvise
 
 #
 # x32-specific system call numbers start at 512 to avoid cache impact
include/linux/proc_fs.h +1 -0
index 52a283ba0465..f8545d7c5218 100644
@@ -122,6 +122,7 @@ static inline struct pid *tgid_pidfd_to_pid(const struct file *file)
 
 #endif /* CONFIG_PROC_FS */
 
+extern struct pid *pidfd_to_pid(const struct file *file);
 struct net;
 
 static inline struct proc_dir_entry *proc_net_mkdir(
include/linux/syscalls.h +2 -0
index e2870fe1be5b..21c6c9a62006 100644
@@ -872,6 +872,8 @@ asmlinkage long sys_munlockall(void);
 asmlinkage long sys_mincore(unsigned long start, size_t len,
 				unsigned char __user * vec);
 asmlinkage long sys_madvise(unsigned long start, size_t len, int behavior);
+asmlinkage long sys_process_madvise(int pid_fd, unsigned long start,
+				size_t len, int behavior);
 asmlinkage long sys_remap_file_pages(unsigned long start, unsigned long size,
 			unsigned long prot, unsigned long pgoff,
 			unsigned long flags);
include/uapi/asm-generic/unistd.h +2 -0
index dee7292e1df6..7ee82ce04620 100644
@@ -832,6 +832,8 @@ __SYSCALL(__NR_io_uring_setup, sys_io_uring_setup)
 __SYSCALL(__NR_io_uring_enter, sys_io_uring_enter)
 #define __NR_io_uring_register 427
 __SYSCALL(__NR_io_uring_register, sys_io_uring_register)
+#define __NR_process_madvise 428
+__SYSCALL(__NR_process_madvise, sys_process_madvise)
 
 #undef __NR_syscalls
 #define __NR_syscalls 428
kernel/signal.c +1 -1
index 1c86b78a7597..04e75daab1f8 100644
@@ -3620,7 +3620,7 @@ static int copy_siginfo_from_user_any(kernel_siginfo_t *kinfo, siginfo_t *info)
 	return copy_siginfo_from_user(kinfo, info);
 }
 
-static struct pid *pidfd_to_pid(const struct file *file)
+struct pid *pidfd_to_pid(const struct file *file)
 {
 	if (file->f_op == &pidfd_fops)
 		return file->private_data;
kernel/sys_ni.c +1 -0
index 4d9ae5ea6caf..5277421795ab 100644
@@ -278,6 +278,7 @@ COND_SYSCALL(mlockall);
 COND_SYSCALL(munlockall);
 COND_SYSCALL(mincore);
 COND_SYSCALL(madvise);
+COND_SYSCALL(process_madvise);
 COND_SYSCALL(remap_file_pages);
 COND_SYSCALL(mbind);
 COND_SYSCALL_COMPAT(mbind);
mm/madvise.c +45 -0

60 lines not on this page · raw message

Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
reviewer
#33 lore raw

Re: [RFC 5/7] mm: introduce external memory hinting API

[Cc linux-api]

Quoted 9 lines · Minchan Kim

There is some usecase that centralized userspace daemon want to give a memory hint like MADV_[COOL|COLD] to other process. Android's ActivityManagerService is one of them.

It's similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to the centralized userspace daemon(ActivityManagerService), and that daemon must be able to initiate reclaim on its own without any app involvement.

Could you expand some more about how this all works? How does the centralized daemon track respective ranges? How does it synchronize against parallel modification of the address space etc.

Quoted 5 lines

To solve the issue, this patch introduces new syscall process_madvise(2) which works based on pidfd so it could give a hint to the exeternal process.

int process_madvise(int pidfd, void *addr, size_t length, int advise);

OK, this makes some sense from the API point of view. When we have discussed that at LSFMM I was contemplating about something like that except the fd would be a VMA fd rather than the process. We could extend and reuse /proc/<pid>/map_files interface which doesn't support the anonymous memory right now.

I am not saying this would be a better interface but I wanted to mention it here for a further discussion. One slight advantage would be that you know the exact object that you are operating on because you have a fd for the VMA and we would have a more straightforward way to reject operation if the underlying object has changed (e.g. unmapped and reused for a different mapping).

Quoted 4 lines

All advises madvise provides can be supported in process_madvise, too. Since it could affect other process's address range, only privileged process(CAP_SYS_PTRACE) or something else(e.g., being the same UID) gives it the right to ptrrace the process could use it successfully.

proc_mem_open model we use for accessing address space via proc sounds like a good mode. You are doing something similar.

Quoted 171 lines

Please suggest better idea if you have other idea about the permission.

* from v1r1
* use ptrace capability - surenb, dancol

---
 arch/x86/entry/syscalls/syscall_32.tbl |  1 +
 arch/x86/entry/syscalls/syscall_64.tbl |  1 +
 include/linux/proc_fs.h                |  1 +
 include/linux/syscalls.h               |  2 ++
 include/uapi/asm-generic/unistd.h      |  2 ++
 kernel/signal.c                        |  2 +-
 kernel/sys_ni.c                        |  1 +
 mm/madvise.c                           | 45 ++++++++++++++++++++++++++
 8 files changed, 54 insertions(+), 1 deletion(-)
arch/x86/entry/syscalls/syscall_32.tbl +1 -0
index 4cd5f982b1e5..5b9dd55d6b57 100644
@@ -438,3 +438,4 @@
 425	i386	io_uring_setup		sys_io_uring_setup		__ia32_sys_io_uring_setup
 426	i386	io_uring_enter		sys_io_uring_enter		__ia32_sys_io_uring_enter
 427	i386	io_uring_register	sys_io_uring_register		__ia32_sys_io_uring_register
+428	i386	process_madvise		sys_process_madvise		__ia32_sys_process_madvise
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index 64ca0d06259a..0e5ee78161c9 100644
@@ -355,6 +355,7 @@
 425	common	io_uring_setup		__x64_sys_io_uring_setup
 426	common	io_uring_enter		__x64_sys_io_uring_enter
 427	common	io_uring_register	__x64_sys_io_uring_register
+428	common	process_madvise		__x64_sys_process_madvise
 
 #
 # x32-specific system call numbers start at 512 to avoid cache impact
include/linux/proc_fs.h +1 -0
index 52a283ba0465..f8545d7c5218 100644
@@ -122,6 +122,7 @@ static inline struct pid *tgid_pidfd_to_pid(const struct file *file)
 
 #endif /* CONFIG_PROC_FS */
 
+extern struct pid *pidfd_to_pid(const struct file *file);
 struct net;
 
 static inline struct proc_dir_entry *proc_net_mkdir(
include/linux/syscalls.h +2 -0
index e2870fe1be5b..21c6c9a62006 100644
@@ -872,6 +872,8 @@ asmlinkage long sys_munlockall(void);
 asmlinkage long sys_mincore(unsigned long start, size_t len,
 				unsigned char __user * vec);
 asmlinkage long sys_madvise(unsigned long start, size_t len, int behavior);
+asmlinkage long sys_process_madvise(int pid_fd, unsigned long start,
+				size_t len, int behavior);
 asmlinkage long sys_remap_file_pages(unsigned long start, unsigned long size,
 			unsigned long prot, unsigned long pgoff,
 			unsigned long flags);
include/uapi/asm-generic/unistd.h +2 -0
index dee7292e1df6..7ee82ce04620 100644
@@ -832,6 +832,8 @@ __SYSCALL(__NR_io_uring_setup, sys_io_uring_setup)
 __SYSCALL(__NR_io_uring_enter, sys_io_uring_enter)
 #define __NR_io_uring_register 427
 __SYSCALL(__NR_io_uring_register, sys_io_uring_register)
+#define __NR_process_madvise 428
+__SYSCALL(__NR_process_madvise, sys_process_madvise)
 
 #undef __NR_syscalls
 #define __NR_syscalls 428
kernel/signal.c +1 -1
index 1c86b78a7597..04e75daab1f8 100644
@@ -3620,7 +3620,7 @@ static int copy_siginfo_from_user_any(kernel_siginfo_t *kinfo, siginfo_t *info)
 	return copy_siginfo_from_user(kinfo, info);
 }
 
-static struct pid *pidfd_to_pid(const struct file *file)
+struct pid *pidfd_to_pid(const struct file *file)
 {
 	if (file->f_op == &pidfd_fops)
 		return file->private_data;
kernel/sys_ni.c +1 -0
index 4d9ae5ea6caf..5277421795ab 100644
@@ -278,6 +278,7 @@ COND_SYSCALL(mlockall);
 COND_SYSCALL(munlockall);
 COND_SYSCALL(mincore);
 COND_SYSCALL(madvise);
+COND_SYSCALL(process_madvise);
 COND_SYSCALL(remap_file_pages);
 COND_SYSCALL(mbind);
 COND_SYSCALL_COMPAT(mbind);
mm/madvise.c +45 -0
index 119e82e1f065..af02aa17e5c1 100644
@@ -9,6 +9,7 @@
 #include <linux/mman.h>
 #include <linux/pagemap.h>
 #include <linux/page_idle.h>
+#include <linux/proc_fs.h>
 #include <linux/syscalls.h>
 #include <linux/mempolicy.h>
 #include <linux/page-isolation.h>
@@ -16,6 +17,7 @@
 #include <linux/hugetlb.h>
 #include <linux/falloc.h>
 #include <linux/sched.h>
+#include <linux/sched/mm.h>
 #include <linux/ksm.h>
 #include <linux/fs.h>
 #include <linux/file.h>
@@ -1140,3 +1142,46 @@ SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
 {
 	return madvise_core(current, start, len_in, behavior);
 }
+
+SYSCALL_DEFINE4(process_madvise, int, pidfd, unsigned long, start,
+		size_t, len_in, int, behavior)
+{
+	int ret;
+	struct fd f;
+	struct pid *pid;
+	struct task_struct *tsk;
+	struct mm_struct *mm;
+
+	f = fdget(pidfd);
+	if (!f.file)
+		return -EBADF;
+
+	pid = pidfd_to_pid(f.file);
+	if (IS_ERR(pid)) {
+		ret = PTR_ERR(pid);
+		goto err;
+	}
+
+	ret = -EINVAL;
+	rcu_read_lock();
+	tsk = pid_task(pid, PIDTYPE_PID);
+	if (!tsk) {
+		rcu_read_unlock();
+		goto err;
+	}
+	get_task_struct(tsk);
+	rcu_read_unlock();
+	mm = mm_access(tsk, PTRACE_MODE_ATTACH_REALCREDS);
+	if (!mm || IS_ERR(mm)) {
+		ret = IS_ERR(mm) ? PTR_ERR(mm) : -ESRCH;
+		if (ret == -EACCES)
+			ret = -EPERM;
+		goto err;
+	}
+	ret = madvise_core(tsk, start, len_in, behavior);
+	mmput(mm);
+	put_task_struct(tsk);
+err:
+	fdput(f);
+	return ret;
+}
Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
Signature · 2 lines
Michal Hocko
SUSE Labs
#34 lore raw

Re: [RFC 5/7] mm: introduce external memory hinting API

Quoted 13 lines · Michal Hocko

[Cc linux-api]

Quoted 9 lines · Minchan Kim

There is some usecase that centralized userspace daemon want to give a memory hint like MADV_[COOL|COLD] to other process. Android's ActivityManagerService is one of them.

It's similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to the centralized userspace daemon(ActivityManagerService), and that daemon must be able to initiate reclaim on its own without any app involvement.

Quoted 3 lines

Could you expand some more about how this all works? How does the centralized daemon track respective ranges? How does it synchronize against parallel modification of the address space etc.

Currently, we don't track each address ranges because we have two policies at this moment:

deactive file pages and reclaim anonymous pages of the app.

Since the daemon has a ability to let background apps resume(IOW, process will be run by the daemon) and both hints are non-disruptive stabilty point of view, we are okay for the race.

Quoted 13 lines
Quoted 6 lines

To solve the issue, this patch introduces new syscall process_madvise(2) which works based on pidfd so it could give a hint to the exeternal process.

int process_madvise(int pidfd, void *addr, size_t length, int advise);

OK, this makes some sense from the API point of view. When we have discussed that at LSFMM I was contemplating about something like that except the fd would be a VMA fd rather than the process. We could extend and reuse /proc/<pid>/map_files interface which doesn't support the anonymous memory right now.

Quoted 6 lines

I am not saying this would be a better interface but I wanted to mention it here for a further discussion. One slight advantage would be that you know the exact object that you are operating on because you have a fd for the VMA and we would have a more straightforward way to reject operation if the underlying object has changed (e.g. unmapped and reused for a different mapping).

I agree your point. If I didn't miss something, such kinds of vma level modify notification doesn't work even file mapped vma at this moment. For anonymous vma, I think we could use userfaultfd, pontentially. It would be great if someone want to do with disruptive hints like MADV_DONTNEED.

I'd like to see it further enhancement after landing address range based operation via limiting hints process_madvise supports to non-disruptive only(e.g., MADV_[COOL|COLD]) so that we could catch up the usercase/workload when someone want to extend the API.

Quoted 184 lines
Quoted 5 lines

All advises madvise provides can be supported in process_madvise, too. Since it could affect other process's address range, only privileged process(CAP_SYS_PTRACE) or something else(e.g., being the same UID) gives it the right to ptrrace the process could use it successfully.

proc_mem_open model we use for accessing address space via proc sounds like a good mode. You are doing something similar.

Quoted 171 lines

Please suggest better idea if you have other idea about the permission.

* from v1r1
* use ptrace capability - surenb, dancol

---
 arch/x86/entry/syscalls/syscall_32.tbl |  1 +
 arch/x86/entry/syscalls/syscall_64.tbl |  1 +
 include/linux/proc_fs.h                |  1 +
 include/linux/syscalls.h               |  2 ++
 include/uapi/asm-generic/unistd.h      |  2 ++
 kernel/signal.c                        |  2 +-
 kernel/sys_ni.c                        |  1 +
 mm/madvise.c                           | 45 ++++++++++++++++++++++++++
 8 files changed, 54 insertions(+), 1 deletion(-)
arch/x86/entry/syscalls/syscall_32.tbl +1 -0
index 4cd5f982b1e5..5b9dd55d6b57 100644
@@ -438,3 +438,4 @@
 425	i386	io_uring_setup		sys_io_uring_setup		__ia32_sys_io_uring_setup
 426	i386	io_uring_enter		sys_io_uring_enter		__ia32_sys_io_uring_enter
 427	i386	io_uring_register	sys_io_uring_register		__ia32_sys_io_uring_register
+428	i386	process_madvise		sys_process_madvise		__ia32_sys_process_madvise
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index 64ca0d06259a..0e5ee78161c9 100644
@@ -355,6 +355,7 @@
 425	common	io_uring_setup		__x64_sys_io_uring_setup
 426	common	io_uring_enter		__x64_sys_io_uring_enter
 427	common	io_uring_register	__x64_sys_io_uring_register
+428	common	process_madvise		__x64_sys_process_madvise
 
 #
 # x32-specific system call numbers start at 512 to avoid cache impact
include/linux/proc_fs.h +1 -0
index 52a283ba0465..f8545d7c5218 100644
@@ -122,6 +122,7 @@ static inline struct pid *tgid_pidfd_to_pid(const struct file *file)
 
 #endif /* CONFIG_PROC_FS */
 
+extern struct pid *pidfd_to_pid(const struct file *file);
 struct net;
 
 static inline struct proc_dir_entry *proc_net_mkdir(
include/linux/syscalls.h +2 -0
index e2870fe1be5b..21c6c9a62006 100644
@@ -872,6 +872,8 @@ asmlinkage long sys_munlockall(void);
 asmlinkage long sys_mincore(unsigned long start, size_t len,
 				unsigned char __user * vec);
 asmlinkage long sys_madvise(unsigned long start, size_t len, int behavior);
+asmlinkage long sys_process_madvise(int pid_fd, unsigned long start,
+				size_t len, int behavior);
 asmlinkage long sys_remap_file_pages(unsigned long start, unsigned long size,
 			unsigned long prot, unsigned long pgoff,
 			unsigned long flags);
include/uapi/asm-generic/unistd.h +2 -0
index dee7292e1df6..7ee82ce04620 100644
@@ -832,6 +832,8 @@ __SYSCALL(__NR_io_uring_setup, sys_io_uring_setup)
 __SYSCALL(__NR_io_uring_enter, sys_io_uring_enter)
 #define __NR_io_uring_register 427
 __SYSCALL(__NR_io_uring_register, sys_io_uring_register)
+#define __NR_process_madvise 428
+__SYSCALL(__NR_process_madvise, sys_process_madvise)
 
 #undef __NR_syscalls
 #define __NR_syscalls 428
kernel/signal.c +1 -1
index 1c86b78a7597..04e75daab1f8 100644
@@ -3620,7 +3620,7 @@ static int copy_siginfo_from_user_any(kernel_siginfo_t *kinfo, siginfo_t *info)
 	return copy_siginfo_from_user(kinfo, info);
 }
 
-static struct pid *pidfd_to_pid(const struct file *file)
+struct pid *pidfd_to_pid(const struct file *file)
 {
 	if (file->f_op == &pidfd_fops)
 		return file->private_data;
kernel/sys_ni.c +1 -0
index 4d9ae5ea6caf..5277421795ab 100644
@@ -278,6 +278,7 @@ COND_SYSCALL(mlockall);
 COND_SYSCALL(munlockall);
 COND_SYSCALL(mincore);
 COND_SYSCALL(madvise);
+COND_SYSCALL(process_madvise);
 COND_SYSCALL(remap_file_pages);
 COND_SYSCALL(mbind);
 COND_SYSCALL_COMPAT(mbind);
mm/madvise.c +45 -0
index 119e82e1f065..af02aa17e5c1 100644
@@ -9,6 +9,7 @@
 #include <linux/mman.h>
 #include <linux/pagemap.h>
 #include <linux/page_idle.h>
+#include <linux/proc_fs.h>
 #include <linux/syscalls.h>
 #include <linux/mempolicy.h>
 #include <linux/page-isolation.h>
@@ -16,6 +17,7 @@
 #include <linux/hugetlb.h>
 #include <linux/falloc.h>
 #include <linux/sched.h>
+#include <linux/sched/mm.h>
 #include <linux/ksm.h>
 #include <linux/fs.h>
 #include <linux/file.h>
@@ -1140,3 +1142,46 @@ SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
 {
 	return madvise_core(current, start, len_in, behavior);
 }
+
+SYSCALL_DEFINE4(process_madvise, int, pidfd, unsigned long, start,
+		size_t, len_in, int, behavior)
+{
+	int ret;
+	struct fd f;
+	struct pid *pid;
+	struct task_struct *tsk;
+	struct mm_struct *mm;
+
+	f = fdget(pidfd);
+	if (!f.file)
+		return -EBADF;
+
+	pid = pidfd_to_pid(f.file);
+	if (IS_ERR(pid)) {
+		ret = PTR_ERR(pid);
+		goto err;
+	}
+
+	ret = -EINVAL;
+	rcu_read_lock();
+	tsk = pid_task(pid, PIDTYPE_PID);
+	if (!tsk) {
+		rcu_read_unlock();
+		goto err;
+	}
+	get_task_struct(tsk);
+	rcu_read_unlock();
+	mm = mm_access(tsk, PTRACE_MODE_ATTACH_REALCREDS);
+	if (!mm || IS_ERR(mm)) {
+		ret = IS_ERR(mm) ? PTR_ERR(mm) : -ESRCH;
+		if (ret == -EACCES)
+			ret = -EPERM;
+		goto err;
+	}
+	ret = madvise_core(tsk, start, len_in, behavior);
+	mmput(mm);
+	put_task_struct(tsk);
+err:
+	fdput(f);
+	return ret;
+}
Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
Signature · 2 lines
Michal Hocko
SUSE Labs
reviewer
#35 lore raw

Re: [RFC 5/7] mm: introduce external memory hinting API

Quoted 18 lines · Minchan Kim
Quoted 13 lines · Michal Hocko

[Cc linux-api]

Quoted 9 lines · Minchan Kim

There is some usecase that centralized userspace daemon want to give a memory hint like MADV_[COOL|COLD] to other process. Android's ActivityManagerService is one of them.

It's similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to the centralized userspace daemon(ActivityManagerService), and that daemon must be able to initiate reclaim on its own without any app involvement.

Quoted 3 lines

Could you expand some more about how this all works? How does the centralized daemon track respective ranges? How does it synchronize against parallel modification of the address space etc.

Quoted 8 lines

Currently, we don't track each address ranges because we have two policies at this moment:

deactive file pages and reclaim anonymous pages of the app.

Since the daemon has a ability to let background apps resume(IOW, process will be run by the daemon) and both hints are non-disruptive stabilty point of view, we are okay for the race.

Fair enough but the API should consider future usecases where this might be a problem. So we should really think about those potential scenarios now. If we are ok with that, fine, but then we should be explicit and document it that way. Essentially say that any sort of synchronization is supposed to be done by monitor. This will make the API less usable but maybe that is enough.

Quoted 25 lines
Quoted 12 lines
Quoted 5 lines

To solve the issue, this patch introduces new syscall process_madvise(2) which works based on pidfd so it could give a hint to the exeternal process.

int process_madvise(int pidfd, void *addr, size_t length, int advise);

OK, this makes some sense from the API point of view. When we have discussed that at LSFMM I was contemplating about something like that except the fd would be a VMA fd rather than the process. We could extend and reuse /proc/<pid>/map_files interface which doesn't support the anonymous memory right now.

Quoted 6 lines

I am not saying this would be a better interface but I wanted to mention it here for a further discussion. One slight advantage would be that you know the exact object that you are operating on because you have a fd for the VMA and we would have a more straightforward way to reject operation if the underlying object has changed (e.g. unmapped and reused for a different mapping).

I agree your point. If I didn't miss something, such kinds of vma level modify notification doesn't work even file mapped vma at this moment. For anonymous vma, I think we could use userfaultfd, pontentially. It would be great if someone want to do with disruptive hints like MADV_DONTNEED.

Quoted 4 lines

I'd like to see it further enhancement after landing address range based operation via limiting hints process_madvise supports to non-disruptive only(e.g., MADV_[COOL|COLD]) so that we could catch up the usercase/workload when someone want to extend the API.

So do you think we want both interfaces (process_madvise and madvisefd)?

Signature · 2 lines
Michal Hocko
SUSE Labs
#36 lore raw

Re: [RFC 5/7] mm: introduce external memory hinting API

Quoted 28 lines · Michal Hocko
Quoted 18 lines · Minchan Kim
Quoted 13 lines · Michal Hocko

[Cc linux-api]

Quoted 9 lines · Minchan Kim

There is some usecase that centralized userspace daemon want to give a memory hint like MADV_[COOL|COLD] to other process. Android's ActivityManagerService is one of them.

It's similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to the centralized userspace daemon(ActivityManagerService), and that daemon must be able to initiate reclaim on its own without any app involvement.

Quoted 3 lines

Could you expand some more about how this all works? How does the centralized daemon track respective ranges? How does it synchronize against parallel modification of the address space etc.

Quoted 8 lines

Currently, we don't track each address ranges because we have two policies at this moment:

deactive file pages and reclaim anonymous pages of the app.

Since the daemon has a ability to let background apps resume(IOW, process will be run by the daemon) and both hints are non-disruptive stabilty point of view, we are okay for the race.

Quoted 6 lines

Fair enough but the API should consider future usecases where this might be a problem. So we should really think about those potential scenarios now. If we are ok with that, fine, but then we should be explicit and document it that way. Essentially say that any sort of synchronization is supposed to be done by monitor. This will make the API less usable but maybe that is enough.

Okay, I will add more about that in the description.

Quoted 26 lines
Quoted 26 lines
Quoted 13 lines
Quoted 6 lines

To solve the issue, this patch introduces new syscall process_madvise(2) which works based on pidfd so it could give a hint to the exeternal process.

int process_madvise(int pidfd, void *addr, size_t length, int advise);

OK, this makes some sense from the API point of view. When we have discussed that at LSFMM I was contemplating about something like that except the fd would be a VMA fd rather than the process. We could extend and reuse /proc/<pid>/map_files interface which doesn't support the anonymous memory right now.

Quoted 6 lines

I am not saying this would be a better interface but I wanted to mention it here for a further discussion. One slight advantage would be that you know the exact object that you are operating on because you have a fd for the VMA and we would have a more straightforward way to reject operation if the underlying object has changed (e.g. unmapped and reused for a different mapping).

I agree your point. If I didn't miss something, such kinds of vma level modify notification doesn't work even file mapped vma at this moment. For anonymous vma, I think we could use userfaultfd, pontentially. It would be great if someone want to do with disruptive hints like MADV_DONTNEED.

Quoted 6 lines
Quoted 4 lines

I'd like to see it further enhancement after landing address range based operation via limiting hints process_madvise supports to non-disruptive only(e.g., MADV_[COOL|COLD]) so that we could catch up the usercase/workload when someone want to extend the API.

So do you think we want both interfaces (process_madvise and madvisefd)?

What I have in mind is to extend process_madvise later like this

struct pr_madvise_param {
    int size;                       /* the size of this structure */
    union {
    	const struct iovec __user *vec; /* address range array */
	int fd;				/* supported from 6.0 */
    }
}

with introducing new hint Or-able PR_MADV_RANGE_FD, so that process_madvise can go with fd instead of address range.

#37 lore raw

Re: [RFC 5/7] mm: introduce external memory hinting API

In reply to Minchan Kim
Cc Jann and Oleg too
Quoted 151 lines · Minchan Kim

There is some usecase that centralized userspace daemon want to give a memory hint like MADV_[COOL|COLD] to other process. Android's ActivityManagerService is one of them.

It's similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to the centralized userspace daemon(ActivityManagerService), and that daemon must be able to initiate reclaim on its own without any app involvement.

To solve the issue, this patch introduces new syscall process_madvise(2) which works based on pidfd so it could give a hint to the exeternal process.

int process_madvise(int pidfd, void *addr, size_t length, int advise);

All advises madvise provides can be supported in process_madvise, too. Since it could affect other process's address range, only privileged process(CAP_SYS_PTRACE) or something else(e.g., being the same UID) gives it the right to ptrrace the process could use it successfully.

Please suggest better idea if you have other idea about the permission.

* from v1r1
* use ptrace capability - surenb, dancol

---
 arch/x86/entry/syscalls/syscall_32.tbl |  1 +
 arch/x86/entry/syscalls/syscall_64.tbl |  1 +
 include/linux/proc_fs.h                |  1 +
 include/linux/syscalls.h               |  2 ++
 include/uapi/asm-generic/unistd.h      |  2 ++
 kernel/signal.c                        |  2 +-
 kernel/sys_ni.c                        |  1 +
 mm/madvise.c                           | 45 ++++++++++++++++++++++++++
 8 files changed, 54 insertions(+), 1 deletion(-)
arch/x86/entry/syscalls/syscall_32.tbl +1 -0
index 4cd5f982b1e5..5b9dd55d6b57 100644
@@ -438,3 +438,4 @@
 425	i386	io_uring_setup		sys_io_uring_setup		__ia32_sys_io_uring_setup
 426	i386	io_uring_enter		sys_io_uring_enter		__ia32_sys_io_uring_enter
 427	i386	io_uring_register	sys_io_uring_register		__ia32_sys_io_uring_register
+428	i386	process_madvise		sys_process_madvise		__ia32_sys_process_madvise
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index 64ca0d06259a..0e5ee78161c9 100644
@@ -355,6 +355,7 @@
 425	common	io_uring_setup		__x64_sys_io_uring_setup
 426	common	io_uring_enter		__x64_sys_io_uring_enter
 427	common	io_uring_register	__x64_sys_io_uring_register
+428	common	process_madvise		__x64_sys_process_madvise
 
 #
 # x32-specific system call numbers start at 512 to avoid cache impact
include/linux/proc_fs.h +1 -0
index 52a283ba0465..f8545d7c5218 100644
@@ -122,6 +122,7 @@ static inline struct pid *tgid_pidfd_to_pid(const struct file *file)
 
 #endif /* CONFIG_PROC_FS */
 
+extern struct pid *pidfd_to_pid(const struct file *file);
 struct net;
 
 static inline struct proc_dir_entry *proc_net_mkdir(
include/linux/syscalls.h +2 -0
index e2870fe1be5b..21c6c9a62006 100644
@@ -872,6 +872,8 @@ asmlinkage long sys_munlockall(void);
 asmlinkage long sys_mincore(unsigned long start, size_t len,
 				unsigned char __user * vec);
 asmlinkage long sys_madvise(unsigned long start, size_t len, int behavior);
+asmlinkage long sys_process_madvise(int pid_fd, unsigned long start,
+				size_t len, int behavior);
 asmlinkage long sys_remap_file_pages(unsigned long start, unsigned long size,
 			unsigned long prot, unsigned long pgoff,
 			unsigned long flags);
include/uapi/asm-generic/unistd.h +2 -0
index dee7292e1df6..7ee82ce04620 100644
@@ -832,6 +832,8 @@ __SYSCALL(__NR_io_uring_setup, sys_io_uring_setup)
 __SYSCALL(__NR_io_uring_enter, sys_io_uring_enter)
 #define __NR_io_uring_register 427
 __SYSCALL(__NR_io_uring_register, sys_io_uring_register)
+#define __NR_process_madvise 428
+__SYSCALL(__NR_process_madvise, sys_process_madvise)
 
 #undef __NR_syscalls
 #define __NR_syscalls 428
kernel/signal.c +1 -1
index 1c86b78a7597..04e75daab1f8 100644
@@ -3620,7 +3620,7 @@ static int copy_siginfo_from_user_any(kernel_siginfo_t *kinfo, siginfo_t *info)
 	return copy_siginfo_from_user(kinfo, info);
 }
 
-static struct pid *pidfd_to_pid(const struct file *file)
+struct pid *pidfd_to_pid(const struct file *file)
 {
 	if (file->f_op == &pidfd_fops)
 		return file->private_data;
kernel/sys_ni.c +1 -0
index 4d9ae5ea6caf..5277421795ab 100644
@@ -278,6 +278,7 @@ COND_SYSCALL(mlockall);
 COND_SYSCALL(munlockall);
 COND_SYSCALL(mincore);
 COND_SYSCALL(madvise);
+COND_SYSCALL(process_madvise);
 COND_SYSCALL(remap_file_pages);
 COND_SYSCALL(mbind);
 COND_SYSCALL_COMPAT(mbind);
mm/madvise.c +7 -0
index 119e82e1f065..af02aa17e5c1 100644
@@ -9,6 +9,7 @@
 #include <linux/mman.h>
 #include <linux/pagemap.h>
 #include <linux/page_idle.h>
+#include <linux/proc_fs.h>
 #include <linux/syscalls.h>
 #include <linux/mempolicy.h>
 #include <linux/page-isolation.h>
@@ -16,6 +17,7 @@
 #include <linux/hugetlb.h>
 #include <linux/falloc.h>
 #include <linux/sched.h>
+#include <linux/sched/mm.h>
 #include <linux/ksm.h>
 #include <linux/fs.h>
 #include <linux/file.h>
@@ -1140,3 +1142,46 @@ SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
 {
 	return madvise_core(current, start, len_in, behavior);
 }
+
+SYSCALL_DEFINE4(process_madvise, int, pidfd, unsigned long, start,
+		size_t, len_in, int, behavior)
+{
+	int ret;

mm/madvise.c SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior) · line 1159

Quoted 10 lines
mm/madvise.c +10 -0
+	struct fd f;
+	struct pid *pid;
+	struct task_struct *tsk;
+	struct mm_struct *mm;
+
+	f = fdget(pidfd);
+	if (!f.file)
+		return -EBADF;
+
+	pid = pidfd_to_pid(f.file);

pidfd_to_pid() should not be directly exported since this allows /proc/<pid> fds to be used too. That's something we won't be going forward with. All new syscalls should only allow to operate on pidfds created through CLONE_PIDFD or pidfd_open() (cf. [1]).

So e.g. please export a simple helper like

struct pid *pidfd_to_pid(const struct file *file)

{
        if (file->f_op == &pidfd_fops)
                return file->private_data;

        return NULL;
}

turning the old pidfd_to_pid() into something like:

static struct pid *__fd_to_pid(const struct file *file)

{
        struct pid *pid;

        pid = pidfd_to_pid(file);
        if (pid)
                return pid;

        return tgid_pidfd_to_pid(file);
}

All new syscalls should only be using anon inode pidfds since they can actually have a clean security model built around them in the future. Note, pidfd_open() will be sent out together with making pidfds pollable for the 5.3 merge window.

[1]: https://lore.kernel.org/lkml/[email protected]/

Thanks!
Christian

#38 lore raw

Re: [RFC 5/7] mm: introduce external memory hinting API

Quoted 161 lines · Christian Brauner
Cc Jann and Oleg too
Quoted 158 lines · Minchan Kim

There is some usecase that centralized userspace daemon want to give a memory hint like MADV_[COOL|COLD] to other process. Android's ActivityManagerService is one of them.

It's similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to the centralized userspace daemon(ActivityManagerService), and that daemon must be able to initiate reclaim on its own without any app involvement.

To solve the issue, this patch introduces new syscall process_madvise(2) which works based on pidfd so it could give a hint to the exeternal process.

int process_madvise(int pidfd, void *addr, size_t length, int advise);

All advises madvise provides can be supported in process_madvise, too. Since it could affect other process's address range, only privileged process(CAP_SYS_PTRACE) or something else(e.g., being the same UID) gives it the right to ptrrace the process could use it successfully.

Please suggest better idea if you have other idea about the permission.

* from v1r1
* use ptrace capability - surenb, dancol

---
 arch/x86/entry/syscalls/syscall_32.tbl |  1 +
 arch/x86/entry/syscalls/syscall_64.tbl |  1 +
 include/linux/proc_fs.h                |  1 +
 include/linux/syscalls.h               |  2 ++
 include/uapi/asm-generic/unistd.h      |  2 ++
 kernel/signal.c                        |  2 +-
 kernel/sys_ni.c                        |  1 +
 mm/madvise.c                           | 45 ++++++++++++++++++++++++++
 8 files changed, 54 insertions(+), 1 deletion(-)
arch/x86/entry/syscalls/syscall_32.tbl +1 -0
index 4cd5f982b1e5..5b9dd55d6b57 100644
@@ -438,3 +438,4 @@
 425	i386	io_uring_setup		sys_io_uring_setup		__ia32_sys_io_uring_setup
 426	i386	io_uring_enter		sys_io_uring_enter		__ia32_sys_io_uring_enter
 427	i386	io_uring_register	sys_io_uring_register		__ia32_sys_io_uring_register
+428	i386	process_madvise		sys_process_madvise		__ia32_sys_process_madvise
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index 64ca0d06259a..0e5ee78161c9 100644
@@ -355,6 +355,7 @@
 425	common	io_uring_setup		__x64_sys_io_uring_setup
 426	common	io_uring_enter		__x64_sys_io_uring_enter
 427	common	io_uring_register	__x64_sys_io_uring_register
+428	common	process_madvise		__x64_sys_process_madvise
 
 #
 # x32-specific system call numbers start at 512 to avoid cache impact
include/linux/proc_fs.h +1 -0
index 52a283ba0465..f8545d7c5218 100644
@@ -122,6 +122,7 @@ static inline struct pid *tgid_pidfd_to_pid(const struct file *file)
 
 #endif /* CONFIG_PROC_FS */
 
+extern struct pid *pidfd_to_pid(const struct file *file);
 struct net;
 
 static inline struct proc_dir_entry *proc_net_mkdir(
include/linux/syscalls.h +2 -0
index e2870fe1be5b..21c6c9a62006 100644
@@ -872,6 +872,8 @@ asmlinkage long sys_munlockall(void);
 asmlinkage long sys_mincore(unsigned long start, size_t len,
 				unsigned char __user * vec);
 asmlinkage long sys_madvise(unsigned long start, size_t len, int behavior);
+asmlinkage long sys_process_madvise(int pid_fd, unsigned long start,
+				size_t len, int behavior);
 asmlinkage long sys_remap_file_pages(unsigned long start, unsigned long size,
 			unsigned long prot, unsigned long pgoff,
 			unsigned long flags);
include/uapi/asm-generic/unistd.h +2 -0
index dee7292e1df6..7ee82ce04620 100644
@@ -832,6 +832,8 @@ __SYSCALL(__NR_io_uring_setup, sys_io_uring_setup)
 __SYSCALL(__NR_io_uring_enter, sys_io_uring_enter)
 #define __NR_io_uring_register 427
 __SYSCALL(__NR_io_uring_register, sys_io_uring_register)
+#define __NR_process_madvise 428
+__SYSCALL(__NR_process_madvise, sys_process_madvise)
 
 #undef __NR_syscalls
 #define __NR_syscalls 428
kernel/signal.c +1 -1
index 1c86b78a7597..04e75daab1f8 100644
@@ -3620,7 +3620,7 @@ static int copy_siginfo_from_user_any(kernel_siginfo_t *kinfo, siginfo_t *info)
 	return copy_siginfo_from_user(kinfo, info);
 }
 
-static struct pid *pidfd_to_pid(const struct file *file)
+struct pid *pidfd_to_pid(const struct file *file)
 {
 	if (file->f_op == &pidfd_fops)
 		return file->private_data;
kernel/sys_ni.c +1 -0
index 4d9ae5ea6caf..5277421795ab 100644
@@ -278,6 +278,7 @@ COND_SYSCALL(mlockall);
 COND_SYSCALL(munlockall);
 COND_SYSCALL(mincore);
 COND_SYSCALL(madvise);
+COND_SYSCALL(process_madvise);
 COND_SYSCALL(remap_file_pages);
 COND_SYSCALL(mbind);
 COND_SYSCALL_COMPAT(mbind);
mm/madvise.c +14 -0
index 119e82e1f065..af02aa17e5c1 100644
@@ -9,6 +9,7 @@
 #include <linux/mman.h>
 #include <linux/pagemap.h>
 #include <linux/page_idle.h>
+#include <linux/proc_fs.h>
 #include <linux/syscalls.h>
 #include <linux/mempolicy.h>
 #include <linux/page-isolation.h>
@@ -16,6 +17,7 @@
 #include <linux/hugetlb.h>
 #include <linux/falloc.h>
 #include <linux/sched.h>
+#include <linux/sched/mm.h>
 #include <linux/ksm.h>
 #include <linux/fs.h>
 #include <linux/file.h>
@@ -1140,3 +1142,46 @@ SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
 {
 	return madvise_core(current, start, len_in, behavior);
 }
+
+SYSCALL_DEFINE4(process_madvise, int, pidfd, unsigned long, start,
+		size_t, len_in, int, behavior)
+{
+	int ret;
+	struct fd f;
+	struct pid *pid;
+	struct task_struct *tsk;
+	struct mm_struct *mm;
+
+	f = fdget(pidfd);
+	if (!f.file)
Quoted 8 lines

mm/madvise.c SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior) · line 1159

Quoted 3 lines
mm/madvise.c +3 -0
+		return -EBADF;
+
+	pid = pidfd_to_pid(f.file);

pidfd_to_pid() should not be directly exported since this allows /proc/<pid> fds to be used too. That's something we won't be going forward with. All new syscalls should only allow to operate on pidfds created through CLONE_PIDFD or pidfd_open() (cf. [1]).

Thanks for the information.

Quoted 14 lines

So e.g. please export a simple helper like

struct pid *pidfd_to_pid(const struct file *file)

{
        if (file->f_op == &pidfd_fops)
                return file->private_data;

        return NULL;
}

turning the old pidfd_to_pid() into something like:

static struct pid *__fd_to_pid(const struct file *file)

Quoted 9 lines
{
        struct pid *pid;

        pid = pidfd_to_pid(file);
        if (pid)
                return pid;

        return tgid_pidfd_to_pid(file);
}

So, I want to clarify what you suggest here.

1. modify pidfd_to_pid as what you described above(ie, return NULL instead of returning tgid_pidfd_to_pid(file);
2. never export pidfd_to_pid
3. create wrapper __fd_to_pid which calls pidfd_to_pid internally
4. export __fd_to_pid and use it

Correct?

Thanks.

Quoted 10 lines

All new syscalls should only be using anon inode pidfds since they can actually have a clean security model built around them in the future. Note, pidfd_open() will be sent out together with making pidfds pollable for the 5.3 merge window.

[1]: https://lore.kernel.org/lkml/[email protected]/

Thanks!
Christian

#39 lore raw

Re: [RFC 5/7] mm: introduce external memory hinting API

Quoted 197 lines · Minchan Kim
Quoted 161 lines · Christian Brauner
Cc Jann and Oleg too
Quoted 158 lines · Minchan Kim

There is some usecase that centralized userspace daemon want to give a memory hint like MADV_[COOL|COLD] to other process. Android's ActivityManagerService is one of them.

It's similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to the centralized userspace daemon(ActivityManagerService), and that daemon must be able to initiate reclaim on its own without any app involvement.

To solve the issue, this patch introduces new syscall process_madvise(2) which works based on pidfd so it could give a hint to the exeternal process.

int process_madvise(int pidfd, void *addr, size_t length, int advise);

All advises madvise provides can be supported in process_madvise, too. Since it could affect other process's address range, only privileged process(CAP_SYS_PTRACE) or something else(e.g., being the same UID) gives it the right to ptrrace the process could use it successfully.

Please suggest better idea if you have other idea about the permission.

* from v1r1
* use ptrace capability - surenb, dancol

---
 arch/x86/entry/syscalls/syscall_32.tbl |  1 +
 arch/x86/entry/syscalls/syscall_64.tbl |  1 +
 include/linux/proc_fs.h                |  1 +
 include/linux/syscalls.h               |  2 ++
 include/uapi/asm-generic/unistd.h      |  2 ++
 kernel/signal.c                        |  2 +-
 kernel/sys_ni.c                        |  1 +
 mm/madvise.c                           | 45 ++++++++++++++++++++++++++
 8 files changed, 54 insertions(+), 1 deletion(-)
arch/x86/entry/syscalls/syscall_32.tbl +1 -0
index 4cd5f982b1e5..5b9dd55d6b57 100644
@@ -438,3 +438,4 @@
 425	i386	io_uring_setup		sys_io_uring_setup		__ia32_sys_io_uring_setup
 426	i386	io_uring_enter		sys_io_uring_enter		__ia32_sys_io_uring_enter
 427	i386	io_uring_register	sys_io_uring_register		__ia32_sys_io_uring_register
+428	i386	process_madvise		sys_process_madvise		__ia32_sys_process_madvise
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
index 64ca0d06259a..0e5ee78161c9 100644
@@ -355,6 +355,7 @@
 425	common	io_uring_setup		__x64_sys_io_uring_setup
 426	common	io_uring_enter		__x64_sys_io_uring_enter
 427	common	io_uring_register	__x64_sys_io_uring_register
+428	common	process_madvise		__x64_sys_process_madvise
 
 #
 # x32-specific system call numbers start at 512 to avoid cache impact
include/linux/proc_fs.h +1 -0
index 52a283ba0465..f8545d7c5218 100644
@@ -122,6 +122,7 @@ static inline struct pid *tgid_pidfd_to_pid(const struct file *file)
 
 #endif /* CONFIG_PROC_FS */
 
+extern struct pid *pidfd_to_pid(const struct file *file);
 struct net;
 
 static inline struct proc_dir_entry *proc_net_mkdir(
include/linux/syscalls.h +2 -0
index e2870fe1be5b..21c6c9a62006 100644
@@ -872,6 +872,8 @@ asmlinkage long sys_munlockall(void);
 asmlinkage long sys_mincore(unsigned long start, size_t len,
 				unsigned char __user * vec);
 asmlinkage long sys_madvise(unsigned long start, size_t len, int behavior);
+asmlinkage long sys_process_madvise(int pid_fd, unsigned long start,
+				size_t len, int behavior);
 asmlinkage long sys_remap_file_pages(unsigned long start, unsigned long size,
 			unsigned long prot, unsigned long pgoff,
 			unsigned long flags);
include/uapi/asm-generic/unistd.h +2 -0
index dee7292e1df6..7ee82ce04620 100644
@@ -832,6 +832,8 @@ __SYSCALL(__NR_io_uring_setup, sys_io_uring_setup)
 __SYSCALL(__NR_io_uring_enter, sys_io_uring_enter)
 #define __NR_io_uring_register 427
 __SYSCALL(__NR_io_uring_register, sys_io_uring_register)
+#define __NR_process_madvise 428
+__SYSCALL(__NR_process_madvise, sys_process_madvise)
 
 #undef __NR_syscalls
 #define __NR_syscalls 428
kernel/signal.c +1 -1
index 1c86b78a7597..04e75daab1f8 100644
@@ -3620,7 +3620,7 @@ static int copy_siginfo_from_user_any(kernel_siginfo_t *kinfo, siginfo_t *info)
 	return copy_siginfo_from_user(kinfo, info);
 }
 
-static struct pid *pidfd_to_pid(const struct file *file)
+struct pid *pidfd_to_pid(const struct file *file)
 {
 	if (file->f_op == &pidfd_fops)
 		return file->private_data;
kernel/sys_ni.c +1 -0
index 4d9ae5ea6caf..5277421795ab 100644
@@ -278,6 +278,7 @@ COND_SYSCALL(mlockall);
 COND_SYSCALL(munlockall);
 COND_SYSCALL(mincore);
 COND_SYSCALL(madvise);
+COND_SYSCALL(process_madvise);
 COND_SYSCALL(remap_file_pages);
 COND_SYSCALL(mbind);
 COND_SYSCALL_COMPAT(mbind);
mm/madvise.c +14 -0
index 119e82e1f065..af02aa17e5c1 100644
@@ -9,6 +9,7 @@
 #include <linux/mman.h>
 #include <linux/pagemap.h>
 #include <linux/page_idle.h>
+#include <linux/proc_fs.h>
 #include <linux/syscalls.h>
 #include <linux/mempolicy.h>
 #include <linux/page-isolation.h>
@@ -16,6 +17,7 @@
 #include <linux/hugetlb.h>
 #include <linux/falloc.h>
 #include <linux/sched.h>
+#include <linux/sched/mm.h>
 #include <linux/ksm.h>
 #include <linux/fs.h>
 #include <linux/file.h>
@@ -1140,3 +1142,46 @@ SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
 {
 	return madvise_core(current, start, len_in, behavior);
 }
+
+SYSCALL_DEFINE4(process_madvise, int, pidfd, unsigned long, start,
+		size_t, len_in, int, behavior)
+{
+	int ret;
+	struct fd f;
+	struct pid *pid;
+	struct task_struct *tsk;
+	struct mm_struct *mm;
+
+	f = fdget(pidfd);
+	if (!f.file)
Quoted 8 lines

mm/madvise.c SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior) · line 1159

Quoted 3 lines
mm/madvise.c +3 -0
+		return -EBADF;
+
+	pid = pidfd_to_pid(f.file);

pidfd_to_pid() should not be directly exported since this allows /proc/<pid> fds to be used too. That's something we won't be going forward with. All new syscalls should only allow to operate on pidfds created through CLONE_PIDFD or pidfd_open() (cf. [1]).

Thanks for the information.

Quoted 14 lines

So e.g. please export a simple helper like

struct pid *pidfd_to_pid(const struct file *file)

{
        if (file->f_op == &pidfd_fops)
                return file->private_data;

        return NULL;
}

turning the old pidfd_to_pid() into something like:

static struct pid *__fd_to_pid(const struct file *file)

Quoted 9 lines
{
        struct pid *pid;

        pid = pidfd_to_pid(file);
        if (pid)
                return pid;

        return tgid_pidfd_to_pid(file);
}
Quoted 7 lines

So, I want to clarify what you suggest here.

1. modify pidfd_to_pid as what you described above(ie, return NULL instead of returning tgid_pidfd_to_pid(file);
2. never export pidfd_to_pid
3. create wrapper __fd_to_pid which calls pidfd_to_pid internally
4. export __fd_to_pid and use it

Sorry, seems I was not clear enough. :)
What I meant was something along the lines of (not compile tested):

include/linux/pid.h +4 -0
index 3c8ef5a199ca..3ccc07010603 100644
@@ -68,6 +68,10 @@ extern struct pid init_struct_pid;
 
 extern const struct file_operations pidfd_fops;
 
+struct file;
+
+extern struct pid *pidfd_pid(const struct file *file);
+
 static inline struct pid *get_pid(struct pid *pid)
 {
 	if (pid)
kernel/fork.c +8 -0
index b4cba953040a..0fcfffaf5fdc 100644
@@ -1711,6 +1711,14 @@ const struct file_operations pidfd_fops = {
 #endif
 };
 
+struct pid *pidfd_pid(const struct file *file)
+{
+	if (file->f_op == &pidfd_fops)
+		return file->private_data;
+
+	return ERR_PTR(-EBADF);
+}
+
 /**
  * pidfd_create() - Create a new pid file descriptor.
  *
kernel/signal.c +5 -2
index a1eb44dc9ff5..7fca9d7e1633 100644
@@ -3611,8 +3611,11 @@ static int copy_siginfo_from_user_any(kernel_siginfo_t *kinfo, siginfo_t *info)
 
 static struct pid *pidfd_to_pid(const struct file *file)
 {
-	if (file->f_op == &pidfd_fops)
-		return file->private_data;
+	struct pid *pid;
+
+	pid = pidfd_pid(file);
+	if (pid)
+		return pid;
 
 	return tgid_pidfd_to_pid(file);
 }
#40 lore raw

Re: [RFC 5/7] mm: introduce external memory hinting API

In reply to Minchan Kim
Quoted 7 lines · Minchan Kim
mm/madvise.c +6 -0
+	rcu_read_lock();
+	tsk = pid_task(pid, PIDTYPE_PID);
+	if (!tsk) {
+		rcu_read_unlock();
+		goto err;
+	}

mm/madvise.c SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior) · line 1181

Quoted 10 lines
mm/madvise.c +10 -0
+	get_task_struct(tsk);
+	rcu_read_unlock();
+	mm = mm_access(tsk, PTRACE_MODE_ATTACH_REALCREDS);
+	if (!mm || IS_ERR(mm)) {
+		ret = IS_ERR(mm) ? PTR_ERR(mm) : -ESRCH;
+		if (ret == -EACCES)
+			ret = -EPERM;
+		goto err;
+	}
+	ret = madvise_core(tsk, start, len_in, behavior);

IIUC, madvise_core(tsk) plays with tsk->mm->mmap_sem. But this tsk can exit and nullify its ->mm right after mm_access() succeeds.

another problem is that pid_task(pid) can return a zombie leader, in this case mm_access() will fail while it shouldn't.

Oleg.

#41 lore raw

Re: [RFC 5/7] mm: introduce external memory hinting API

Sorry for the late response. I miseed your comment. :(

Quoted 13 lines · Oleg Nesterov
Quoted 12 lines · Minchan Kim
mm/madvise.c +11 -0
+	rcu_read_lock();
+	tsk = pid_task(pid, PIDTYPE_PID);
+	if (!tsk) {
+		rcu_read_unlock();
+		goto err;
+	}
+	get_task_struct(tsk);
+	rcu_read_unlock();
+	mm = mm_access(tsk, PTRACE_MODE_ATTACH_REALCREDS);
+	if (!mm || IS_ERR(mm)) {
+		ret = IS_ERR(mm) ? PTR_ERR(mm) : -ESRCH;
Quoted 8 lines

mm/madvise.c SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior) · line 1181

Quoted 5 lines
mm/madvise.c +5 -0
+		if (ret == -EACCES)
+			ret = -EPERM;
+		goto err;
+	}
+	ret = madvise_core(tsk, start, len_in, behavior);

IIUC, madvise_core(tsk) plays with tsk->mm->mmap_sem. But this tsk can exit and nullify its ->mm right after mm_access() succeeds.

You're absolutely right. I will fix it via passing mm_struct instead of task_struct.

Thanks!

Quoted 3 lines

another problem is that pid_task(pid) can return a zombie leader, in this case mm_access() will fail while it shouldn't.

I'm sorry. I didn't notice that. However, I couldn't understand your point. Why do you think mm_access shouldn't fail even though pid_task returns a zombie leader? I thought it's okay since the target process is exiting so hinting operation would be meaniness for the process.

#42 lore raw

Re: [RFC 5/7] mm: introduce external memory hinting API

Quoted 7 lines · Minchan Kim
Quoted 3 lines

another problem is that pid_task(pid) can return a zombie leader, in this case mm_access() will fail while it shouldn't.

I'm sorry. I didn't notice that. However, I couldn't understand your point. Why do you think mm_access shouldn't fail even though pid_task returns a zombie leader?

The leader can exit (call sys_exit(), not sys_exit_group()), this won't affect other threads. In this case the process is still alive even if the leader thread is zombie. That is why we have find_lock_task_mm().

Oleg.

#43 lore raw

Re: [RFC 5/7] mm: introduce external memory hinting API

Quoted 5 lines · Oleg Nesterov
Quoted 4 lines · Minchan Kim
Quoted 3 lines

another problem is that pid_task(pid) can return a zombie leader, in this case mm_access() will fail while it shouldn't.

Quoted 7 lines
Quoted 3 lines

I'm sorry. I didn't notice that. However, I couldn't understand your point. Why do you think mm_access shouldn't fail even though pid_task returns a zombie leader?

The leader can exit (call sys_exit(), not sys_exit_group()), this won't affect other threads. In this case the process is still alive even if the leader thread is zombie. That is why we have find_lock_task_mm().

Thanks for clarification, Oleg. Then, Let me have a further question.

It means process_vm_readv, move_pages have same problem too because find_task_by_vpid can return a zomebie leader and next line checks for mm_struct validation makes a failure. My understand is correct? If so, we need to fix all places.

reviewer
#44 lore raw

Re: [RFC 5/7] mm: introduce external memory hinting API

Quoted 14 lines · Minchan Kim
Quoted 5 lines · Oleg Nesterov
Quoted 4 lines · Minchan Kim
Quoted 3 lines

another problem is that pid_task(pid) can return a zombie leader, in this case mm_access() will fail while it shouldn't.

Quoted 7 lines
Quoted 3 lines

I'm sorry. I didn't notice that. However, I couldn't understand your point. Why do you think mm_access shouldn't fail even though pid_task returns a zombie leader?

The leader can exit (call sys_exit(), not sys_exit_group()), this won't affect other threads. In this case the process is still alive even if the leader thread is zombie. That is why we have find_lock_task_mm().

Quoted 5 lines

Thanks for clarification, Oleg. Then, Let me have a further question.

It means process_vm_readv, move_pages have same problem too because find_task_by_vpid can return a zomebie leader and next line checks for mm_struct validation makes a failure. My understand is correct? If so, we need to fix all places.

Isn't that a problem of most callers of get_task_mm? Shouldn't we fix it turning it into find_lock_task_mm?

Signature · 2 lines
Michal Hocko
SUSE Labs
#45 lore raw

Re: [RFC 5/7] mm: introduce external memory hinting API

In reply to Minchan Kim
Quoted 11 lines · Hillf Danton

arch/x86/entry/syscalls/syscall_64.tbl line 359

Quoted 8 lines · On Mon, 20 May 2019 12:52:52 +0900 Minchan Kim wrote:
arch/x86/entry/syscalls/syscall_64.tbl +1 -0
@@ -355,6 +355,7 @@
 425	common	io_uring_setup		__x64_sys_io_uring_setup
 426	common	io_uring_enter		__x64_sys_io_uring_enter
 427	common	io_uring_register	__x64_sys_io_uring_register
+428	common	process_madvise		__x64_sys_process_madvise
 

Much better if something similar is added for arm64.

I will port every architecture once we figure out RFC and reaches the conclusion for right interface.

Quoted 12 lines
Quoted 12 lines
arch/x86/entry/syscalls/syscall_64.tbl +0 -0
 #
 # x32-specific system call numbers start at 512 to avoid cache impact
include/uapi/asm-generic/unistd.h +2 -0
@@ -832,6 +832,8 @@ __SYSCALL(__NR_io_uring_setup, sys_io_uring_setup)
 __SYSCALL(__NR_io_uring_enter, sys_io_uring_enter)
 #define __NR_io_uring_register 427
 __SYSCALL(__NR_io_uring_register, sys_io_uring_register)
+#define __NR_process_madvise 428
+__SYSCALL(__NR_process_madvise, sys_process_madvise)
 
Quoted 4 lines

include/uapi/asm-generic/unistd.h __SYSCALL(__NR_io_uring_setup, sys_io_uring_setup) · line 839

Quoted 2 lines
include/uapi/asm-generic/unistd.h +0 -0
 #undef __NR_syscalls
 #define __NR_syscalls 428

Seems __NR_syscalls needs to increment by one.

Thanks. I will fix it.

#46 lore raw

RFC 6/7 mm: extend process_madvise syscall to support vector arrary

In reply to Minchan Kim

Currently, process_madvise syscall works for only one address range so user should call the syscall several times to give hints to multiple address range.

This patch extends process_madvise syscall to support multiple hints, address ranges and return vaules so user could give hints all at once.

struct pr_madvise_param {
int size; /* the size of this structure */
const struct iovec __user *vec; /* address range array */
}

int process_madvise(int pidfd, ssize_t nr_elem,
int *behavior,
struct pr_madvise_param *results, struct pr_madvise_param *ranges, unsigned long flags);

- pidfd

target process fd

- nr_elem

the number of elemenent of array behavior, results, ranges

- behavior

hints for each address range in remote process so that user could give different hints for each range.

- results

array of buffers to get results for associated remote address range action.

- ranges

array to buffers to have remote process's address ranges to be processed

- flags

extra argument for the future. It should be zero this moment.

Example)

struct pr_madvise_param {
        int size;
        const struct iovec *vec;
};

int main(int argc, char *argv[])

{
        struct pr_madvise_param retp, rangep;
        struct iovec result_vec[2], range_vec[2];
        int hints[2];
        long ret[2];
        void *addr[2];

        pid_t pid;
        char cmd[64] = {0,};
        addr[0] = mmap(NULL, ALLOC_SIZE, PROT_READ|PROT_WRITE,
                          MAP_POPULATE|MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);

        if (MAP_FAILED == addr[0])
                return 1;

        addr[1] = mmap(NULL, ALLOC_SIZE, PROT_READ|PROT_WRITE,
                          MAP_POPULATE|MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);

        if (MAP_FAILED == addr[1])
                return 1;

        hints[0] = MADV_COLD;
	range_vec[0].iov_base = addr[0];
        range_vec[0].iov_len = ALLOC_SIZE;
        result_vec[0].iov_base = &ret[0];
        result_vec[0].iov_len = sizeof(long);
	retp.vec = result_vec;
        retp.size = sizeof(struct pr_madvise_param);

        hints[1] = MADV_COOL;
        range_vec[1].iov_base = addr[1];
        range_vec[1].iov_len = ALLOC_SIZE;
        result_vec[1].iov_base = &ret[1];
        result_vec[1].iov_len = sizeof(long);
        rangep.vec = range_vec;
        rangep.size = sizeof(struct pr_madvise_param);

        pid = fork();
        if (!pid) {
                sleep(10);
        } else {
                int pidfd = open(cmd,  O_DIRECTORY | O_CLOEXEC);
                if (pidfd < 0)
                        return 1;

                /* munmap to make pages private for the child */
                munmap(addr[0], ALLOC_SIZE);
                munmap(addr[1], ALLOC_SIZE);
                system("cat /proc/vmstat | egrep 'pswpout|deactivate'");
                if (syscall(__NR_process_madvise, pidfd, 2, behaviors,
						&retp, &rangep, 0))
                        perror("process_madvise fail\n");
                system("cat /proc/vmstat | egrep 'pswpout|deactivate'");
        }

        return 0;
}
---
 include/uapi/asm-generic/mman-common.h |   5 +
 mm/madvise.c                           | 184 +++++++++++++++++++++----
 2 files changed, 166 insertions(+), 23 deletions(-)
include/uapi/asm-generic/mman-common.h +5 -0
index b9b51eeb8e1a..b8e230de84a6 100644
@@ -74,4 +74,9 @@
 #define PKEY_ACCESS_MASK	(PKEY_DISABLE_ACCESS |\
 				 PKEY_DISABLE_WRITE)
 
+struct pr_madvise_param {
+	int size;			/* the size of this structure */
+	const struct iovec __user *vec;	/* address range array */
+};
+
 #endif /* __ASM_GENERIC_MMAN_COMMON_H */
mm/madvise.c +161 -23

336 lines not on this page · raw message

Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
reviewer
#47 lore raw

Re: [RFC 6/7] mm: extend process_madvise syscall to support vector arrary

[Cc linux-api]

Quoted 3 lines · Minchan Kim

Currently, process_madvise syscall works for only one address range so user should call the syscall several times to give hints to multiple address range.

Is that a problem? How big of a problem? Any numbers?

Quoted 19 lines

This patch extends process_madvise syscall to support multiple hints, address ranges and return vaules so user could give hints all at once.

struct pr_madvise_param {
int size; /* the size of this structure */
const struct iovec __user *vec; /* address range array */
}

int process_madvise(int pidfd, ssize_t nr_elem,
int *behavior,
struct pr_madvise_param *results, struct pr_madvise_param *ranges, unsigned long flags);

- pidfd

target process fd

Quoted 8 lines

- nr_elem

the number of elemenent of array behavior, results, ranges

- behavior

hints for each address range in remote process so that user could give different hints for each range.

What is the guarantee of a single call? Do all hints get applied or the first failure backs of? What are the atomicity guarantees?

Quoted 463 lines

- results

array of buffers to get results for associated remote address range action.

- ranges

array to buffers to have remote process's address ranges to be processed

- flags

extra argument for the future. It should be zero this moment.

Example)

struct pr_madvise_param {
        int size;
        const struct iovec *vec;
};

int main(int argc, char *argv[])

{
        struct pr_madvise_param retp, rangep;
        struct iovec result_vec[2], range_vec[2];
        int hints[2];
        long ret[2];
        void *addr[2];

        pid_t pid;
        char cmd[64] = {0,};
        addr[0] = mmap(NULL, ALLOC_SIZE, PROT_READ|PROT_WRITE,
                          MAP_POPULATE|MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);

        if (MAP_FAILED == addr[0])
                return 1;

        addr[1] = mmap(NULL, ALLOC_SIZE, PROT_READ|PROT_WRITE,
                          MAP_POPULATE|MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);

        if (MAP_FAILED == addr[1])
                return 1;

        hints[0] = MADV_COLD;
	range_vec[0].iov_base = addr[0];
        range_vec[0].iov_len = ALLOC_SIZE;
        result_vec[0].iov_base = &ret[0];
        result_vec[0].iov_len = sizeof(long);
	retp.vec = result_vec;
        retp.size = sizeof(struct pr_madvise_param);

        hints[1] = MADV_COOL;
        range_vec[1].iov_base = addr[1];
        range_vec[1].iov_len = ALLOC_SIZE;
        result_vec[1].iov_base = &ret[1];
        result_vec[1].iov_len = sizeof(long);
        rangep.vec = range_vec;
        rangep.size = sizeof(struct pr_madvise_param);

        pid = fork();
        if (!pid) {
                sleep(10);
        } else {
                int pidfd = open(cmd,  O_DIRECTORY | O_CLOEXEC);
                if (pidfd < 0)
                        return 1;

                /* munmap to make pages private for the child */
                munmap(addr[0], ALLOC_SIZE);
                munmap(addr[1], ALLOC_SIZE);
                system("cat /proc/vmstat | egrep 'pswpout|deactivate'");
                if (syscall(__NR_process_madvise, pidfd, 2, behaviors,
						&retp, &rangep, 0))
                        perror("process_madvise fail\n");
                system("cat /proc/vmstat | egrep 'pswpout|deactivate'");
        }

        return 0;
}
---
 include/uapi/asm-generic/mman-common.h |   5 +
 mm/madvise.c                           | 184 +++++++++++++++++++++----
 2 files changed, 166 insertions(+), 23 deletions(-)
include/uapi/asm-generic/mman-common.h +5 -0
index b9b51eeb8e1a..b8e230de84a6 100644
@@ -74,4 +74,9 @@
 #define PKEY_ACCESS_MASK	(PKEY_DISABLE_ACCESS |\
 				 PKEY_DISABLE_WRITE)
 
+struct pr_madvise_param {
+	int size;			/* the size of this structure */
+	const struct iovec __user *vec;	/* address range array */
+};
+
 #endif /* __ASM_GENERIC_MMAN_COMMON_H */
mm/madvise.c +161 -23
index af02aa17e5c1..f4f569dac2bd 100644
@@ -320,6 +320,7 @@ static int madvise_cool_pte_range(pmd_t *pmd, unsigned long addr,
 	struct page *page;
 	struct vm_area_struct *vma = walk->vma;
 	unsigned long next;
+	long nr_pages = 0;
 
 	next = pmd_addr_end(addr, end);
 	if (pmd_trans_huge(*pmd)) {
@@ -380,9 +381,12 @@ static int madvise_cool_pte_range(pmd_t *pmd, unsigned long addr,
 
 		ptep_test_and_clear_young(vma, addr, pte);
 		deactivate_page(page);
+		nr_pages++;
+
 	}
 
 	pte_unmap_unlock(orig_pte, ptl);
+	*(long *)walk->private += nr_pages;
 	cond_resched();
 
 	return 0;
@@ -390,11 +394,13 @@ static int madvise_cool_pte_range(pmd_t *pmd, unsigned long addr,
 
 static void madvise_cool_page_range(struct mmu_gather *tlb,
 			     struct vm_area_struct *vma,
-			     unsigned long addr, unsigned long end)
+			     unsigned long addr, unsigned long end,
+			     long *nr_pages)
 {
 	struct mm_walk cool_walk = {
 		.pmd_entry = madvise_cool_pte_range,
 		.mm = vma->vm_mm,
+		.private = nr_pages
 	};
 
 	tlb_start_vma(tlb, vma);
@@ -403,7 +409,8 @@ static void madvise_cool_page_range(struct mmu_gather *tlb,
 }
 
 static long madvise_cool(struct vm_area_struct *vma,
-			unsigned long start_addr, unsigned long end_addr)
+			unsigned long start_addr, unsigned long end_addr,
+			long *nr_pages)
 {
 	struct mm_struct *mm = vma->vm_mm;
 	struct mmu_gather tlb;
@@ -413,7 +420,7 @@ static long madvise_cool(struct vm_area_struct *vma,
 
 	lru_add_drain();
 	tlb_gather_mmu(&tlb, mm, start_addr, end_addr);
-	madvise_cool_page_range(&tlb, vma, start_addr, end_addr);
+	madvise_cool_page_range(&tlb, vma, start_addr, end_addr, nr_pages);
 	tlb_finish_mmu(&tlb, start_addr, end_addr);
 
 	return 0;
@@ -429,6 +436,7 @@ static int madvise_cold_pte_range(pmd_t *pmd, unsigned long addr,
 	int isolated = 0;
 	struct vm_area_struct *vma = walk->vma;
 	unsigned long next;
+	long nr_pages = 0;
 
 	next = pmd_addr_end(addr, end);
 	if (pmd_trans_huge(*pmd)) {
@@ -492,7 +500,7 @@ static int madvise_cold_pte_range(pmd_t *pmd, unsigned long addr,
 		list_add(&page->lru, &page_list);
 		if (isolated >= SWAP_CLUSTER_MAX) {
 			pte_unmap_unlock(orig_pte, ptl);
-			reclaim_pages(&page_list);
+			nr_pages += reclaim_pages(&page_list);
 			isolated = 0;
 			pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
 			orig_pte = pte;
@@ -500,19 +508,22 @@ static int madvise_cold_pte_range(pmd_t *pmd, unsigned long addr,
 	}
 
 	pte_unmap_unlock(orig_pte, ptl);
-	reclaim_pages(&page_list);
+	nr_pages += reclaim_pages(&page_list);
 	cond_resched();
 
+	*(long *)walk->private += nr_pages;
 	return 0;
 }
 
 static void madvise_cold_page_range(struct mmu_gather *tlb,
 			     struct vm_area_struct *vma,
-			     unsigned long addr, unsigned long end)
+			     unsigned long addr, unsigned long end,
+			     long *nr_pages)
 {
 	struct mm_walk warm_walk = {
 		.pmd_entry = madvise_cold_pte_range,
 		.mm = vma->vm_mm,
+		.private = nr_pages,
 	};
 
 	tlb_start_vma(tlb, vma);
@@ -522,7 +533,8 @@ static void madvise_cold_page_range(struct mmu_gather *tlb,
 
 
 static long madvise_cold(struct vm_area_struct *vma,
-			unsigned long start_addr, unsigned long end_addr)
+			unsigned long start_addr, unsigned long end_addr,
+			long *nr_pages)
 {
 	struct mm_struct *mm = vma->vm_mm;
 	struct mmu_gather tlb;
@@ -532,7 +544,7 @@ static long madvise_cold(struct vm_area_struct *vma,
 
 	lru_add_drain();
 	tlb_gather_mmu(&tlb, mm, start_addr, end_addr);
-	madvise_cold_page_range(&tlb, vma, start_addr, end_addr);
+	madvise_cold_page_range(&tlb, vma, start_addr, end_addr, nr_pages);
 	tlb_finish_mmu(&tlb, start_addr, end_addr);
 
 	return 0;
@@ -922,7 +934,7 @@ static int madvise_inject_error(int behavior,
 static long
 madvise_vma(struct task_struct *tsk, struct vm_area_struct *vma,
 		struct vm_area_struct **prev, unsigned long start,
-		unsigned long end, int behavior)
+		unsigned long end, int behavior, long *nr_pages)
 {
 	switch (behavior) {
 	case MADV_REMOVE:
@@ -930,9 +942,9 @@ madvise_vma(struct task_struct *tsk, struct vm_area_struct *vma,
 	case MADV_WILLNEED:
 		return madvise_willneed(vma, prev, start, end);
 	case MADV_COOL:
-		return madvise_cool(vma, start, end);
+		return madvise_cool(vma, start, end, nr_pages);
 	case MADV_COLD:
-		return madvise_cold(vma, start, end);
+		return madvise_cold(vma, start, end, nr_pages);
 	case MADV_FREE:
 	case MADV_DONTNEED:
 		return madvise_dontneed_free(tsk, vma, prev, start,
@@ -981,7 +993,7 @@ madvise_behavior_valid(int behavior)
 }
 
 static int madvise_core(struct task_struct *tsk, unsigned long start,
-			size_t len_in, int behavior)
+			size_t len_in, int behavior, long *nr_pages)
 {
 	unsigned long end, tmp;
 	struct vm_area_struct *vma, *prev;
@@ -996,6 +1008,7 @@ static int madvise_core(struct task_struct *tsk, unsigned long start,
 
 	if (start & ~PAGE_MASK)
 		return error;
+
 	len = (len_in + ~PAGE_MASK) & PAGE_MASK;
 
 	/* Check to see whether len was rounded up from small -ve to zero */
@@ -1035,6 +1048,8 @@ static int madvise_core(struct task_struct *tsk, unsigned long start,
 	blk_start_plug(&plug);
 	for (;;) {
 		/* Still start < end. */
+		long pages = 0;
+
 		error = -ENOMEM;
 		if (!vma)
 			goto out;
@@ -1053,9 +1068,11 @@ static int madvise_core(struct task_struct *tsk, unsigned long start,
 			tmp = end;
 
 		/* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */
-		error = madvise_vma(tsk, vma, &prev, start, tmp, behavior);
+		error = madvise_vma(tsk, vma, &prev, start, tmp,
+					behavior, &pages);
 		if (error)
 			goto out;
+		*nr_pages += pages;
 		start = tmp;
 		if (prev && start < prev->vm_end)
 			start = prev->vm_end;
@@ -1140,26 +1157,137 @@ static int madvise_core(struct task_struct *tsk, unsigned long start,
  */
 SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
 {
-	return madvise_core(current, start, len_in, behavior);
+	unsigned long dummy;
+
+	return madvise_core(current, start, len_in, behavior, &dummy);
 }
 
-SYSCALL_DEFINE4(process_madvise, int, pidfd, unsigned long, start,
-		size_t, len_in, int, behavior)
+static int pr_madvise_copy_param(struct pr_madvise_param __user *u_param,
+		struct pr_madvise_param *param)
+{
+	u32 size;
+	int ret;
+
+	memset(param, 0, sizeof(*param));
+
+	ret = get_user(size, &u_param->size);
+	if (ret)
+		return ret;
+
+	if (size > PAGE_SIZE)
+		return -E2BIG;
+
+	if (!size || size > sizeof(struct pr_madvise_param))
+		return -EINVAL;
+
+	ret = copy_from_user(param, u_param, size);
+	if (ret)
+		return -EFAULT;
+
+	return ret;
+}
+
+static int process_madvise_core(struct task_struct *tsk, int *behaviors,
+				struct iov_iter *iter,
+				const struct iovec *range_vec,
+				unsigned long riovcnt,
+				unsigned long flags)
+{
+	int i;
+	long err;
+
+	for (err = 0, i = 0; i < riovcnt && iov_iter_count(iter); i++) {
+		long ret = 0;
+
+		err = madvise_core(tsk, (unsigned long)range_vec[i].iov_base,
+				range_vec[i].iov_len, behaviors[i],
+				&ret);
+		if (err)
+			ret = err;
+
+		if (copy_to_iter(&ret, sizeof(long), iter) !=
+				sizeof(long)) {
+			err = -EFAULT;
+			break;
+		}
+
+		err = 0;
+	}
+
+	return err;
+}
+
+SYSCALL_DEFINE6(process_madvise, int, pidfd, ssize_t, nr_elem,
+			const int __user *, hints,
+			struct pr_madvise_param __user *, results,
+			struct pr_madvise_param __user *, ranges,
+			unsigned long, flags)
 {
 	int ret;
 	struct fd f;
 	struct pid *pid;
 	struct task_struct *tsk;
 	struct mm_struct *mm;
+	struct pr_madvise_param result_p, range_p;
+	const struct iovec __user *result_vec, __user *range_vec;
+	int *behaviors;
+	struct iovec iovstack_result[UIO_FASTIOV];
+	struct iovec iovstack_r[UIO_FASTIOV];
+	struct iovec *iov_l = iovstack_result;
+	struct iovec *iov_r = iovstack_r;
+	struct iov_iter iter;
+
+	if (flags != 0)
+		return -EINVAL;
+
+	ret = pr_madvise_copy_param(results, &result_p);
+	if (ret)
+		return ret;
+
+	ret = pr_madvise_copy_param(ranges, &range_p);
+	if (ret)
+		return ret;
+
+	result_vec = result_p.vec;
+	range_vec = range_p.vec;
+
+	if (result_p.size != sizeof(struct pr_madvise_param) ||
+			range_p.size != sizeof(struct pr_madvise_param))
+		return -EINVAL;
+
+	behaviors = kmalloc_array(nr_elem, sizeof(int), GFP_KERNEL);
+	if (!behaviors)
+		return -ENOMEM;
+
+	ret = copy_from_user(behaviors, hints, sizeof(int) * nr_elem);
+	if (ret < 0)
+		goto free_behavior_vec;
+
+	ret = import_iovec(READ, result_vec, nr_elem, UIO_FASTIOV,
+				&iov_l, &iter);
+	if (ret < 0)
+		goto free_behavior_vec;
+
+	if (!iov_iter_count(&iter)) {
+		ret = -EINVAL;
+		goto free_iovecs;
+	}
+
+	ret = rw_copy_check_uvector(CHECK_IOVEC_ONLY, range_vec, nr_elem,
+				UIO_FASTIOV, iovstack_r, &iov_r);
+	if (ret <= 0)
+		goto free_iovecs;
 
 	f = fdget(pidfd);
-	if (!f.file)
-		return -EBADF;
+	if (!f.file) {
+		ret = -EBADF;
+		goto free_iovecs;
+	}
 
 	pid = pidfd_to_pid(f.file);
 	if (IS_ERR(pid)) {
 		ret = PTR_ERR(pid);
-		goto err;
+		goto put_fd;
 	}
 
 	ret = -EINVAL;
@@ -1167,7 +1295,7 @@ SYSCALL_DEFINE4(process_madvise, int, pidfd, unsigned long, start,
 	tsk = pid_task(pid, PIDTYPE_PID);
 	if (!tsk) {
 		rcu_read_unlock();
-		goto err;
+		goto put_fd;
 	}
 	get_task_struct(tsk);
 	rcu_read_unlock();
@@ -1176,12 +1304,22 @@ SYSCALL_DEFINE4(process_madvise, int, pidfd, unsigned long, start,
 		ret = IS_ERR(mm) ? PTR_ERR(mm) : -ESRCH;
 		if (ret == -EACCES)
 			ret = -EPERM;
-		goto err;
+		goto put_task;
 	}
-	ret = madvise_core(tsk, start, len_in, behavior);
+
+	ret = process_madvise_core(tsk, behaviors, &iter, iov_r,
+					nr_elem, flags);
 	mmput(mm);
+put_task:
 	put_task_struct(tsk);
-err:
+put_fd:
 	fdput(f);
+free_iovecs:
+	if (iov_r != iovstack_r)
+		kfree(iov_r);
+	kfree(iov_l);
+free_behavior_vec:
+	kfree(behaviors);
+
 	return ret;
 }
Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
Signature · 2 lines
Michal Hocko
SUSE Labs
#48 lore raw

Re: [RFC 6/7] mm: extend process_madvise syscall to support vector arrary

Quoted 8 lines · Michal Hocko

[Cc linux-api]

Quoted 3 lines · Minchan Kim

Currently, process_madvise syscall works for only one address range so user should call the syscall several times to give hints to multiple address range.

Is that a problem? How big of a problem? Any numbers?

We easily have 2000+ vma so it's not trivial overhead. I will come up with number in the description at respin.

Quoted 24 lines
Quoted 24 lines

This patch extends process_madvise syscall to support multiple hints, address ranges and return vaules so user could give hints all at once.

struct pr_madvise_param {
int size; /* the size of this structure */
const struct iovec __user *vec; /* address range array */
}

int process_madvise(int pidfd, ssize_t nr_elem,
int *behavior,
struct pr_madvise_param *results, struct pr_madvise_param *ranges, unsigned long flags);

- pidfd

target process fd

- nr_elem

the number of elemenent of array behavior, results, ranges

Quoted 7 lines
Quoted 4 lines

- behavior

hints for each address range in remote process so that user could give different hints for each range.

What is the guarantee of a single call? Do all hints get applied or the first failure backs of? What are the atomicity guarantees?

All hints will be tried even though one of them is failed. User will see the success or failure from the restuls parameter. For the single call, there is no guarantee of atomicity.

Quoted 468 lines
Quoted 464 lines

- results

array of buffers to get results for associated remote address range action.

- ranges

array to buffers to have remote process's address ranges to be processed

- flags

extra argument for the future. It should be zero this moment.

Example)

struct pr_madvise_param {
        int size;
        const struct iovec *vec;
};

int main(int argc, char *argv[])

{
        struct pr_madvise_param retp, rangep;
        struct iovec result_vec[2], range_vec[2];
        int hints[2];
        long ret[2];
        void *addr[2];

        pid_t pid;
        char cmd[64] = {0,};
        addr[0] = mmap(NULL, ALLOC_SIZE, PROT_READ|PROT_WRITE,
                          MAP_POPULATE|MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);

        if (MAP_FAILED == addr[0])
                return 1;

        addr[1] = mmap(NULL, ALLOC_SIZE, PROT_READ|PROT_WRITE,
                          MAP_POPULATE|MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);

        if (MAP_FAILED == addr[1])
                return 1;

        hints[0] = MADV_COLD;
	range_vec[0].iov_base = addr[0];
        range_vec[0].iov_len = ALLOC_SIZE;
        result_vec[0].iov_base = &ret[0];
        result_vec[0].iov_len = sizeof(long);
	retp.vec = result_vec;
        retp.size = sizeof(struct pr_madvise_param);

        hints[1] = MADV_COOL;
        range_vec[1].iov_base = addr[1];
        range_vec[1].iov_len = ALLOC_SIZE;
        result_vec[1].iov_base = &ret[1];
        result_vec[1].iov_len = sizeof(long);
        rangep.vec = range_vec;
        rangep.size = sizeof(struct pr_madvise_param);

        pid = fork();
        if (!pid) {
                sleep(10);
        } else {
                int pidfd = open(cmd,  O_DIRECTORY | O_CLOEXEC);
                if (pidfd < 0)
                        return 1;

                /* munmap to make pages private for the child */
                munmap(addr[0], ALLOC_SIZE);
                munmap(addr[1], ALLOC_SIZE);
                system("cat /proc/vmstat | egrep 'pswpout|deactivate'");
                if (syscall(__NR_process_madvise, pidfd, 2, behaviors,
						&retp, &rangep, 0))
                        perror("process_madvise fail\n");
                system("cat /proc/vmstat | egrep 'pswpout|deactivate'");
        }

        return 0;
}
---
 include/uapi/asm-generic/mman-common.h |   5 +
 mm/madvise.c                           | 184 +++++++++++++++++++++----
 2 files changed, 166 insertions(+), 23 deletions(-)
include/uapi/asm-generic/mman-common.h +5 -0
index b9b51eeb8e1a..b8e230de84a6 100644
@@ -74,4 +74,9 @@
 #define PKEY_ACCESS_MASK	(PKEY_DISABLE_ACCESS |\
 				 PKEY_DISABLE_WRITE)
 
+struct pr_madvise_param {
+	int size;			/* the size of this structure */
+	const struct iovec __user *vec;	/* address range array */
+};
+
 #endif /* __ASM_GENERIC_MMAN_COMMON_H */
mm/madvise.c +161 -23
index af02aa17e5c1..f4f569dac2bd 100644
@@ -320,6 +320,7 @@ static int madvise_cool_pte_range(pmd_t *pmd, unsigned long addr,
 	struct page *page;
 	struct vm_area_struct *vma = walk->vma;
 	unsigned long next;
+	long nr_pages = 0;
 
 	next = pmd_addr_end(addr, end);
 	if (pmd_trans_huge(*pmd)) {
@@ -380,9 +381,12 @@ static int madvise_cool_pte_range(pmd_t *pmd, unsigned long addr,
 
 		ptep_test_and_clear_young(vma, addr, pte);
 		deactivate_page(page);
+		nr_pages++;
+
 	}
 
 	pte_unmap_unlock(orig_pte, ptl);
+	*(long *)walk->private += nr_pages;
 	cond_resched();
 
 	return 0;
@@ -390,11 +394,13 @@ static int madvise_cool_pte_range(pmd_t *pmd, unsigned long addr,
 
 static void madvise_cool_page_range(struct mmu_gather *tlb,
 			     struct vm_area_struct *vma,
-			     unsigned long addr, unsigned long end)
+			     unsigned long addr, unsigned long end,
+			     long *nr_pages)
 {
 	struct mm_walk cool_walk = {
 		.pmd_entry = madvise_cool_pte_range,
 		.mm = vma->vm_mm,
+		.private = nr_pages
 	};
 
 	tlb_start_vma(tlb, vma);
@@ -403,7 +409,8 @@ static void madvise_cool_page_range(struct mmu_gather *tlb,
 }
 
 static long madvise_cool(struct vm_area_struct *vma,
-			unsigned long start_addr, unsigned long end_addr)
+			unsigned long start_addr, unsigned long end_addr,
+			long *nr_pages)
 {
 	struct mm_struct *mm = vma->vm_mm;
 	struct mmu_gather tlb;
@@ -413,7 +420,7 @@ static long madvise_cool(struct vm_area_struct *vma,
 
 	lru_add_drain();
 	tlb_gather_mmu(&tlb, mm, start_addr, end_addr);
-	madvise_cool_page_range(&tlb, vma, start_addr, end_addr);
+	madvise_cool_page_range(&tlb, vma, start_addr, end_addr, nr_pages);
 	tlb_finish_mmu(&tlb, start_addr, end_addr);
 
 	return 0;
@@ -429,6 +436,7 @@ static int madvise_cold_pte_range(pmd_t *pmd, unsigned long addr,
 	int isolated = 0;
 	struct vm_area_struct *vma = walk->vma;
 	unsigned long next;
+	long nr_pages = 0;
 
 	next = pmd_addr_end(addr, end);
 	if (pmd_trans_huge(*pmd)) {
@@ -492,7 +500,7 @@ static int madvise_cold_pte_range(pmd_t *pmd, unsigned long addr,
 		list_add(&page->lru, &page_list);
 		if (isolated >= SWAP_CLUSTER_MAX) {
 			pte_unmap_unlock(orig_pte, ptl);
-			reclaim_pages(&page_list);
+			nr_pages += reclaim_pages(&page_list);
 			isolated = 0;
 			pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
 			orig_pte = pte;
@@ -500,19 +508,22 @@ static int madvise_cold_pte_range(pmd_t *pmd, unsigned long addr,
 	}
 
 	pte_unmap_unlock(orig_pte, ptl);
-	reclaim_pages(&page_list);
+	nr_pages += reclaim_pages(&page_list);
 	cond_resched();
 
+	*(long *)walk->private += nr_pages;
 	return 0;
 }
 
 static void madvise_cold_page_range(struct mmu_gather *tlb,
 			     struct vm_area_struct *vma,
-			     unsigned long addr, unsigned long end)
+			     unsigned long addr, unsigned long end,
+			     long *nr_pages)
 {
 	struct mm_walk warm_walk = {
 		.pmd_entry = madvise_cold_pte_range,
 		.mm = vma->vm_mm,
+		.private = nr_pages,
 	};
 
 	tlb_start_vma(tlb, vma);
@@ -522,7 +533,8 @@ static void madvise_cold_page_range(struct mmu_gather *tlb,
 
 
 static long madvise_cold(struct vm_area_struct *vma,
-			unsigned long start_addr, unsigned long end_addr)
+			unsigned long start_addr, unsigned long end_addr,
+			long *nr_pages)
 {
 	struct mm_struct *mm = vma->vm_mm;
 	struct mmu_gather tlb;
@@ -532,7 +544,7 @@ static long madvise_cold(struct vm_area_struct *vma,
 
 	lru_add_drain();
 	tlb_gather_mmu(&tlb, mm, start_addr, end_addr);
-	madvise_cold_page_range(&tlb, vma, start_addr, end_addr);
+	madvise_cold_page_range(&tlb, vma, start_addr, end_addr, nr_pages);
 	tlb_finish_mmu(&tlb, start_addr, end_addr);
 
 	return 0;
@@ -922,7 +934,7 @@ static int madvise_inject_error(int behavior,
 static long
 madvise_vma(struct task_struct *tsk, struct vm_area_struct *vma,
 		struct vm_area_struct **prev, unsigned long start,
-		unsigned long end, int behavior)
+		unsigned long end, int behavior, long *nr_pages)
 {
 	switch (behavior) {
 	case MADV_REMOVE:
@@ -930,9 +942,9 @@ madvise_vma(struct task_struct *tsk, struct vm_area_struct *vma,
 	case MADV_WILLNEED:
 		return madvise_willneed(vma, prev, start, end);
 	case MADV_COOL:
-		return madvise_cool(vma, start, end);
+		return madvise_cool(vma, start, end, nr_pages);
 	case MADV_COLD:
-		return madvise_cold(vma, start, end);
+		return madvise_cold(vma, start, end, nr_pages);
 	case MADV_FREE:
 	case MADV_DONTNEED:
 		return madvise_dontneed_free(tsk, vma, prev, start,
@@ -981,7 +993,7 @@ madvise_behavior_valid(int behavior)
 }
 
 static int madvise_core(struct task_struct *tsk, unsigned long start,
-			size_t len_in, int behavior)
+			size_t len_in, int behavior, long *nr_pages)
 {
 	unsigned long end, tmp;
 	struct vm_area_struct *vma, *prev;
@@ -996,6 +1008,7 @@ static int madvise_core(struct task_struct *tsk, unsigned long start,
 
 	if (start & ~PAGE_MASK)
 		return error;
+
 	len = (len_in + ~PAGE_MASK) & PAGE_MASK;
 
 	/* Check to see whether len was rounded up from small -ve to zero */
@@ -1035,6 +1048,8 @@ static int madvise_core(struct task_struct *tsk, unsigned long start,
 	blk_start_plug(&plug);
 	for (;;) {
 		/* Still start < end. */
+		long pages = 0;
+
 		error = -ENOMEM;
 		if (!vma)
 			goto out;
@@ -1053,9 +1068,11 @@ static int madvise_core(struct task_struct *tsk, unsigned long start,
 			tmp = end;
 
 		/* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */
-		error = madvise_vma(tsk, vma, &prev, start, tmp, behavior);
+		error = madvise_vma(tsk, vma, &prev, start, tmp,
+					behavior, &pages);
 		if (error)
 			goto out;
+		*nr_pages += pages;
 		start = tmp;
 		if (prev && start < prev->vm_end)
 			start = prev->vm_end;
@@ -1140,26 +1157,137 @@ static int madvise_core(struct task_struct *tsk, unsigned long start,
  */
 SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
 {
-	return madvise_core(current, start, len_in, behavior);
+	unsigned long dummy;
+
+	return madvise_core(current, start, len_in, behavior, &dummy);
 }
 
-SYSCALL_DEFINE4(process_madvise, int, pidfd, unsigned long, start,
-		size_t, len_in, int, behavior)
+static int pr_madvise_copy_param(struct pr_madvise_param __user *u_param,
+		struct pr_madvise_param *param)
+{
+	u32 size;
+	int ret;
+
+	memset(param, 0, sizeof(*param));
+
+	ret = get_user(size, &u_param->size);
+	if (ret)
+		return ret;
+
+	if (size > PAGE_SIZE)
+		return -E2BIG;
+
+	if (!size || size > sizeof(struct pr_madvise_param))
+		return -EINVAL;
+
+	ret = copy_from_user(param, u_param, size);
+	if (ret)
+		return -EFAULT;
+
+	return ret;
+}
+
+static int process_madvise_core(struct task_struct *tsk, int *behaviors,
+				struct iov_iter *iter,
+				const struct iovec *range_vec,
+				unsigned long riovcnt,
+				unsigned long flags)
+{
+	int i;
+	long err;
+
+	for (err = 0, i = 0; i < riovcnt && iov_iter_count(iter); i++) {
+		long ret = 0;
+
+		err = madvise_core(tsk, (unsigned long)range_vec[i].iov_base,
+				range_vec[i].iov_len, behaviors[i],
+				&ret);
+		if (err)
+			ret = err;
+
+		if (copy_to_iter(&ret, sizeof(long), iter) !=
+				sizeof(long)) {
+			err = -EFAULT;
+			break;
+		}
+
+		err = 0;
+	}
+
+	return err;
+}
+
+SYSCALL_DEFINE6(process_madvise, int, pidfd, ssize_t, nr_elem,
+			const int __user *, hints,
+			struct pr_madvise_param __user *, results,
+			struct pr_madvise_param __user *, ranges,
+			unsigned long, flags)
 {
 	int ret;
 	struct fd f;
 	struct pid *pid;
 	struct task_struct *tsk;
 	struct mm_struct *mm;
+	struct pr_madvise_param result_p, range_p;
+	const struct iovec __user *result_vec, __user *range_vec;
+	int *behaviors;
+	struct iovec iovstack_result[UIO_FASTIOV];
+	struct iovec iovstack_r[UIO_FASTIOV];
+	struct iovec *iov_l = iovstack_result;
+	struct iovec *iov_r = iovstack_r;
+	struct iov_iter iter;
+
+	if (flags != 0)
+		return -EINVAL;
+
+	ret = pr_madvise_copy_param(results, &result_p);
+	if (ret)
+		return ret;
+
+	ret = pr_madvise_copy_param(ranges, &range_p);
+	if (ret)
+		return ret;
+
+	result_vec = result_p.vec;
+	range_vec = range_p.vec;
+
+	if (result_p.size != sizeof(struct pr_madvise_param) ||
+			range_p.size != sizeof(struct pr_madvise_param))
+		return -EINVAL;
+
+	behaviors = kmalloc_array(nr_elem, sizeof(int), GFP_KERNEL);
+	if (!behaviors)
+		return -ENOMEM;
+
+	ret = copy_from_user(behaviors, hints, sizeof(int) * nr_elem);
+	if (ret < 0)
+		goto free_behavior_vec;
+
+	ret = import_iovec(READ, result_vec, nr_elem, UIO_FASTIOV,
+				&iov_l, &iter);
+	if (ret < 0)
+		goto free_behavior_vec;
+
+	if (!iov_iter_count(&iter)) {
+		ret = -EINVAL;
+		goto free_iovecs;
+	}
+
+	ret = rw_copy_check_uvector(CHECK_IOVEC_ONLY, range_vec, nr_elem,
+				UIO_FASTIOV, iovstack_r, &iov_r);
+	if (ret <= 0)
+		goto free_iovecs;
 
 	f = fdget(pidfd);
-	if (!f.file)
-		return -EBADF;
+	if (!f.file) {
+		ret = -EBADF;
+		goto free_iovecs;
+	}
 
 	pid = pidfd_to_pid(f.file);
 	if (IS_ERR(pid)) {
 		ret = PTR_ERR(pid);
-		goto err;
+		goto put_fd;
 	}
 
 	ret = -EINVAL;
@@ -1167,7 +1295,7 @@ SYSCALL_DEFINE4(process_madvise, int, pidfd, unsigned long, start,
 	tsk = pid_task(pid, PIDTYPE_PID);
 	if (!tsk) {
 		rcu_read_unlock();
-		goto err;
+		goto put_fd;
 	}
 	get_task_struct(tsk);
 	rcu_read_unlock();
@@ -1176,12 +1304,22 @@ SYSCALL_DEFINE4(process_madvise, int, pidfd, unsigned long, start,
 		ret = IS_ERR(mm) ? PTR_ERR(mm) : -ESRCH;
 		if (ret == -EACCES)
 			ret = -EPERM;
-		goto err;
+		goto put_task;
 	}
-	ret = madvise_core(tsk, start, len_in, behavior);
+
+	ret = process_madvise_core(tsk, behaviors, &iter, iov_r,
+					nr_elem, flags);
 	mmput(mm);
+put_task:
 	put_task_struct(tsk);
-err:
+put_fd:
 	fdput(f);
+free_iovecs:
+	if (iov_r != iovstack_r)
+		kfree(iov_r);
+	kfree(iov_l);
+free_behavior_vec:
+	kfree(behaviors);
+
 	return ret;
 }
Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
Signature · 2 lines
Michal Hocko
SUSE Labs
reviewer
#49 lore raw

Re: [RFC 6/7] mm: extend process_madvise syscall to support vector arrary

Quoted 4 lines · Minchan Kim
Quoted 3 lines · Michal Hocko

[Cc linux-api]

On Mon 20-05-19 12:52:53, Minchan Kim wrote:

Quoted 8 lines
Quoted 5 lines
Quoted 3 lines

Currently, process_madvise syscall works for only one address range so user should call the syscall several times to give hints to multiple address range.

Is that a problem? How big of a problem? Any numbers?

We easily have 2000+ vma so it's not trivial overhead. I will come up with number in the description at respin.

Does this really have to be a fast operation? I would expect the monitor is by no means a fast path. The system call overhead is not what it used to be, sigh, but still for something that is not a hot path it should be tolerable, especially when the whole operation is quite expensive on its own (wrt. the syscall entry/exit).

I am not saying we do not need a multiplexing API, I am just not sure we need it right away. Btw. there was some demand for other MM syscalls to provide a multiplexing API (e.g. mprotect), maybe it would be better to handle those in one go?

Signature · 2 lines
Michal Hocko
SUSE Labs
#50 lore raw

Re: [RFC 6/7] mm: extend process_madvise syscall to support vector arrary

Quoted 11 lines · Michal Hocko
Quoted 10 lines · Minchan Kim
Quoted 8 lines · Michal Hocko

[Cc linux-api]

Quoted 3 lines · Minchan Kim

Currently, process_madvise syscall works for only one address range so user should call the syscall several times to give hints to multiple address range.

Is that a problem? How big of a problem? Any numbers?

Quoted 8 lines
Quoted 2 lines

We easily have 2000+ vma so it's not trivial overhead. I will come up with number in the description at respin.

Does this really have to be a fast operation? I would expect the monitor is by no means a fast path. The system call overhead is not what it used to be, sigh, but still for something that is not a hot path it should be tolerable, especially when the whole operation is quite expensive on its own (wrt. the syscall entry/exit).

What's different with process_vm_[readv|writev] and vmsplice? If the range needed to be covered is a lot, vector operation makes senese to me.

Quoted 5 lines

I am not saying we do not need a multiplexing API, I am just not sure we need it right away. Btw. there was some demand for other MM syscalls to provide a multiplexing API (e.g. mprotect), maybe it would be better to handle those in one go?

That's the exactly what Daniel Colascione suggested from internal review. That would be a interesting approach if we could aggregate all of system call in one go.

Quoted 3 lines
Signature · 2 lines
Michal Hocko
SUSE Labs
reviewer
#51 lore raw

Re: [RFC 6/7] mm: extend process_madvise syscall to support vector arrary

Quoted 21 lines · Minchan Kim
Quoted 11 lines · Michal Hocko
Quoted 10 lines · Minchan Kim
Quoted 8 lines · Michal Hocko

[Cc linux-api]

Quoted 3 lines · Minchan Kim

Currently, process_madvise syscall works for only one address range so user should call the syscall several times to give hints to multiple address range.

Is that a problem? How big of a problem? Any numbers?

Quoted 8 lines
Quoted 2 lines

We easily have 2000+ vma so it's not trivial overhead. I will come up with number in the description at respin.

Does this really have to be a fast operation? I would expect the monitor is by no means a fast path. The system call overhead is not what it used to be, sigh, but still for something that is not a hot path it should be tolerable, especially when the whole operation is quite expensive on its own (wrt. the syscall entry/exit).

Quoted 3 lines

What's different with process_vm_[readv|writev] and vmsplice? If the range needed to be covered is a lot, vector operation makes senese to me.

I am not saying that the vector API is wrong. All I am trying to say is that the benefit is not really clear so far. If you want to push it through then you should better get some supporting data.

Signature · 2 lines
Michal Hocko
SUSE Labs
#52 lore raw

Re: [RFC 6/7] mm: extend process_madvise syscall to support vector arrary

Quoted 22 lines · Michal Hocko
Quoted 21 lines · Minchan Kim
Quoted 19 lines · Michal Hocko
Quoted 4 lines · Minchan Kim
Quoted 3 lines · Michal Hocko

[Cc linux-api]

On Mon 20-05-19 12:52:53, Minchan Kim wrote:

Quoted 8 lines
Quoted 5 lines
Quoted 3 lines

Currently, process_madvise syscall works for only one address range so user should call the syscall several times to give hints to multiple address range.

Is that a problem? How big of a problem? Any numbers?

We easily have 2000+ vma so it's not trivial overhead. I will come up with number in the description at respin.

Does this really have to be a fast operation? I would expect the monitor is by no means a fast path. The system call overhead is not what it used to be, sigh, but still for something that is not a hot path it should be tolerable, especially when the whole operation is quite expensive on its own (wrt. the syscall entry/exit).

Quoted 7 lines
Quoted 3 lines

What's different with process_vm_[readv|writev] and vmsplice? If the range needed to be covered is a lot, vector operation makes senese to me.

I am not saying that the vector API is wrong. All I am trying to say is that the benefit is not really clear so far. If you want to push it through then you should better get some supporting data.

I measured 1000 madvise syscall vs. a vector range syscall with 1000 ranges on ARM64 mordern device. Even though I saw 15% improvement but absoluate gain is just 1ms so I don't think it's worth to support. I will drop vector support at next revision.

Thanks for the review, Michal!

#53 lore raw

Re: [RFC 6/7] mm: extend process_madvise syscall to support vector arrary

Quoted 28 lines · Minchan Kim
Quoted 26 lines · Michal Hocko
Quoted 24 lines · Minchan Kim
Quoted 11 lines · Michal Hocko
Quoted 10 lines · Minchan Kim
Quoted 8 lines · Michal Hocko

[Cc linux-api]

Quoted 3 lines · Minchan Kim

Currently, process_madvise syscall works for only one address range so user should call the syscall several times to give hints to multiple address range.

Is that a problem? How big of a problem? Any numbers?

Quoted 8 lines
Quoted 2 lines

We easily have 2000+ vma so it's not trivial overhead. I will come up with number in the description at respin.

Does this really have to be a fast operation? I would expect the monitor is by no means a fast path. The system call overhead is not what it used to be, sigh, but still for something that is not a hot path it should be tolerable, especially when the whole operation is quite expensive on its own (wrt. the syscall entry/exit).

What's different with process_vm_[readv|writev] and vmsplice? If the range needed to be covered is a lot, vector operation makes senese to me.

Quoted 8 lines
Quoted 3 lines

I am not saying that the vector API is wrong. All I am trying to say is that the benefit is not really clear so far. If you want to push it through then you should better get some supporting data.

I measured 1000 madvise syscall vs. a vector range syscall with 1000 ranges on ARM64 mordern device. Even though I saw 15% improvement but absoluate gain is just 1ms so I don't think it's worth to support. I will drop vector support at next revision.

Please do keep the vector support. Absolute timing is misleading, since in a tight loop, you're not going to contend on mmap_sem. We've seen tons of improvements in things like camera start come from coalescing mprotect calls, with the gains coming from taking and releasing various locks a lot less often and bouncing around less on the contended lock paths. Raw throughput doesn't tell the whole story, especially on mobile.

reviewer
#54 lore raw

Re: [RFC 6/7] mm: extend process_madvise syscall to support vector arrary

Quoted 38 lines · Daniel Colascione
Quoted 28 lines · Minchan Kim
Quoted 26 lines · Michal Hocko
Quoted 24 lines · Minchan Kim
Quoted 11 lines · Michal Hocko
Quoted 10 lines · Minchan Kim
Quoted 8 lines · Michal Hocko

[Cc linux-api]

Quoted 3 lines · Minchan Kim

Currently, process_madvise syscall works for only one address range so user should call the syscall several times to give hints to multiple address range.

Is that a problem? How big of a problem? Any numbers?

Quoted 8 lines
Quoted 2 lines

We easily have 2000+ vma so it's not trivial overhead. I will come up with number in the description at respin.

Does this really have to be a fast operation? I would expect the monitor is by no means a fast path. The system call overhead is not what it used to be, sigh, but still for something that is not a hot path it should be tolerable, especially when the whole operation is quite expensive on its own (wrt. the syscall entry/exit).

What's different with process_vm_[readv|writev] and vmsplice? If the range needed to be covered is a lot, vector operation makes senese to me.

Quoted 8 lines
Quoted 3 lines

I am not saying that the vector API is wrong. All I am trying to say is that the benefit is not really clear so far. If you want to push it through then you should better get some supporting data.

I measured 1000 madvise syscall vs. a vector range syscall with 1000 ranges on ARM64 mordern device. Even though I saw 15% improvement but absoluate gain is just 1ms so I don't think it's worth to support. I will drop vector support at next revision.

Quoted 7 lines

Please do keep the vector support. Absolute timing is misleading, since in a tight loop, you're not going to contend on mmap_sem. We've seen tons of improvements in things like camera start come from coalescing mprotect calls, with the gains coming from taking and releasing various locks a lot less often and bouncing around less on the contended lock paths. Raw throughput doesn't tell the whole story, especially on mobile.

This will always be a double edge sword. Taking a lock for longer can improve a throughput of a single call but it would make a latency for anybody contending on the lock much worse.

Besides that, please do not overcomplicate the thing from the early beginning please. Let's start with a simple and well defined remote madvise alternative first and build a vector API on top with some numbers based on _real_ workloads.

Signature · 2 lines
Michal Hocko
SUSE Labs
#55 lore raw

Re: [RFC 6/7] mm: extend process_madvise syscall to support vector arrary

Quoted 47 lines · Michal Hocko
Quoted 38 lines · Daniel Colascione
Quoted 28 lines · Minchan Kim
Quoted 26 lines · Michal Hocko
Quoted 24 lines · Minchan Kim
Quoted 11 lines · Michal Hocko
Quoted 10 lines · Minchan Kim
Quoted 8 lines · Michal Hocko

[Cc linux-api]

Quoted 3 lines · Minchan Kim

Currently, process_madvise syscall works for only one address range so user should call the syscall several times to give hints to multiple address range.

Is that a problem? How big of a problem? Any numbers?

Quoted 8 lines
Quoted 2 lines

We easily have 2000+ vma so it's not trivial overhead. I will come up with number in the description at respin.

Does this really have to be a fast operation? I would expect the monitor is by no means a fast path. The system call overhead is not what it used to be, sigh, but still for something that is not a hot path it should be tolerable, especially when the whole operation is quite expensive on its own (wrt. the syscall entry/exit).

What's different with process_vm_[readv|writev] and vmsplice? If the range needed to be covered is a lot, vector operation makes senese to me.

Quoted 8 lines
Quoted 3 lines

I am not saying that the vector API is wrong. All I am trying to say is that the benefit is not really clear so far. If you want to push it through then you should better get some supporting data.

I measured 1000 madvise syscall vs. a vector range syscall with 1000 ranges on ARM64 mordern device. Even though I saw 15% improvement but absoluate gain is just 1ms so I don't think it's worth to support. I will drop vector support at next revision.

Quoted 7 lines

Please do keep the vector support. Absolute timing is misleading, since in a tight loop, you're not going to contend on mmap_sem. We've seen tons of improvements in things like camera start come from coalescing mprotect calls, with the gains coming from taking and releasing various locks a lot less often and bouncing around less on the contended lock paths. Raw throughput doesn't tell the whole story, especially on mobile.

Quoted 8 lines

This will always be a double edge sword. Taking a lock for longer can improve a throughput of a single call but it would make a latency for anybody contending on the lock much worse.

Besides that, please do not overcomplicate the thing from the early beginning please. Let's start with a simple and well defined remote madvise alternative first and build a vector API on top with some numbers based on _real_ workloads.

First time, I didn't think about atomicity about address range race because MADV_COLD/PAGEOUT is not critical for the race. However you raised the atomicity issue because people would extend hints to destructive ones easily. I agree with that and that's why we discussed how to guarantee the race and Daniel comes up with good idea.

- vma configuration seq number via process_getinfo(2).

We discussed the race issue without _read_ workloads/requests because it's common sense that people might extend the syscall later.

Here is same. For current workload, we don't need to support vector for perfomance point of view based on my experiment. However, it's rather limited experiment. Some configuration might have 10000+ vmas or really slow CPU.

Furthermore, I want to have vector support due to atomicity issue if it's really the one we should consider.
With vector support of the API and vma configuration sequence number from Daniel, we could support address ranges operations's atomicity. However, since we don't introduce vector at this moment, we need to introduce *another syscall* later to be able to handle multile ranges all at once atomically if it's okay.

Other thought:
Maybe we could extend address range batch syscall covers other MM syscall like mmap/munmap/madvise/mprotect and so on because there are multiple users that would benefit from this general batching mechanism.

reviewer
#56 lore raw

Re: [RFC 6/7] mm: extend process_madvise syscall to support vector arrary

Quoted 57 lines · Minchan Kim
Quoted 47 lines · Michal Hocko
Quoted 38 lines · Daniel Colascione
Quoted 28 lines · Minchan Kim
Quoted 26 lines · Michal Hocko
Quoted 24 lines · Minchan Kim
Quoted 11 lines · Michal Hocko
Quoted 10 lines · Minchan Kim
Quoted 8 lines · Michal Hocko

[Cc linux-api]

Quoted 3 lines · Minchan Kim

Currently, process_madvise syscall works for only one address range so user should call the syscall several times to give hints to multiple address range.

Is that a problem? How big of a problem? Any numbers?

Quoted 8 lines
Quoted 2 lines

We easily have 2000+ vma so it's not trivial overhead. I will come up with number in the description at respin.

Does this really have to be a fast operation? I would expect the monitor is by no means a fast path. The system call overhead is not what it used to be, sigh, but still for something that is not a hot path it should be tolerable, especially when the whole operation is quite expensive on its own (wrt. the syscall entry/exit).

What's different with process_vm_[readv|writev] and vmsplice? If the range needed to be covered is a lot, vector operation makes senese to me.

Quoted 8 lines
Quoted 3 lines

I am not saying that the vector API is wrong. All I am trying to say is that the benefit is not really clear so far. If you want to push it through then you should better get some supporting data.

I measured 1000 madvise syscall vs. a vector range syscall with 1000 ranges on ARM64 mordern device. Even though I saw 15% improvement but absoluate gain is just 1ms so I don't think it's worth to support. I will drop vector support at next revision.

Quoted 7 lines

Please do keep the vector support. Absolute timing is misleading, since in a tight loop, you're not going to contend on mmap_sem. We've seen tons of improvements in things like camera start come from coalescing mprotect calls, with the gains coming from taking and releasing various locks a lot less often and bouncing around less on the contended lock paths. Raw throughput doesn't tell the whole story, especially on mobile.

Quoted 8 lines

This will always be a double edge sword. Taking a lock for longer can improve a throughput of a single call but it would make a latency for anybody contending on the lock much worse.

Besides that, please do not overcomplicate the thing from the early beginning please. Let's start with a simple and well defined remote madvise alternative first and build a vector API on top with some numbers based on _real_ workloads.

Quoted 5 lines

First time, I didn't think about atomicity about address range race because MADV_COLD/PAGEOUT is not critical for the race. However you raised the atomicity issue because people would extend hints to destructive ones easily. I agree with that and that's why we discussed how to guarantee the race and Daniel comes up with good idea.

Just for the clarification, I didn't really mean atomicity but rather a _consistency_ (essentially time to check to time to use consistency).

Quoted 10 lines

- vma configuration seq number via process_getinfo(2).

We discussed the race issue without _read_ workloads/requests because it's common sense that people might extend the syscall later.

Here is same. For current workload, we don't need to support vector for perfomance point of view based on my experiment. However, it's rather limited experiment. Some configuration might have 10000+ vmas or really slow CPU.

Quoted 4 lines

Furthermore, I want to have vector support due to atomicity issue if it's really the one we should consider.
With vector support of the API and vma configuration sequence number from Daniel, we could support address ranges operations's atomicity.

I am not sure what do you mean here. Perform all ranges atomicaly wrt. other address space modifications? If yes I am not sure we want that semantic because it can cause really long stalls for other operations but that is a discussion on its own and I would rather focus on a simple interface first.

Quoted 3 lines

However, since we don't introduce vector at this moment, we need to introduce *another syscall* later to be able to handle multile ranges all at once atomically if it's okay.

Agreed.

Quoted 5 lines

Other thought:
Maybe we could extend address range batch syscall covers other MM syscall like mmap/munmap/madvise/mprotect and so on because there are multiple users that would benefit from this general batching mechanism.

Again a discussion on its own ;)

Signature · 2 lines
Michal Hocko
SUSE Labs
#57 lore raw

Re: [RFC 6/7] mm: extend process_madvise syscall to support vector arrary

Quoted 58 lines · Michal Hocko
Quoted 57 lines · Minchan Kim
Quoted 55 lines · Michal Hocko
Quoted 38 lines · Daniel Colascione
Quoted 28 lines · Minchan Kim
Quoted 26 lines · Michal Hocko
Quoted 24 lines · Minchan Kim
Quoted 11 lines · Michal Hocko
Quoted 10 lines · Minchan Kim
Quoted 8 lines · Michal Hocko

[Cc linux-api]

Quoted 3 lines · Minchan Kim

Currently, process_madvise syscall works for only one address range so user should call the syscall several times to give hints to multiple address range.

Is that a problem? How big of a problem? Any numbers?

Quoted 8 lines
Quoted 2 lines

We easily have 2000+ vma so it's not trivial overhead. I will come up with number in the description at respin.

Does this really have to be a fast operation? I would expect the monitor is by no means a fast path. The system call overhead is not what it used to be, sigh, but still for something that is not a hot path it should be tolerable, especially when the whole operation is quite expensive on its own (wrt. the syscall entry/exit).

What's different with process_vm_[readv|writev] and vmsplice? If the range needed to be covered is a lot, vector operation makes senese to me.

Quoted 8 lines
Quoted 3 lines

I am not saying that the vector API is wrong. All I am trying to say is that the benefit is not really clear so far. If you want to push it through then you should better get some supporting data.

I measured 1000 madvise syscall vs. a vector range syscall with 1000 ranges on ARM64 mordern device. Even though I saw 15% improvement but absoluate gain is just 1ms so I don't think it's worth to support. I will drop vector support at next revision.

Quoted 7 lines

Please do keep the vector support. Absolute timing is misleading, since in a tight loop, you're not going to contend on mmap_sem. We've seen tons of improvements in things like camera start come from coalescing mprotect calls, with the gains coming from taking and releasing various locks a lot less often and bouncing around less on the contended lock paths. Raw throughput doesn't tell the whole story, especially on mobile.

This will always be a double edge sword. Taking a lock for longer can improve a throughput of a single call but it would make a latency for anybody contending on the lock much worse.

Besides that, please do not overcomplicate the thing from the early beginning please. Let's start with a simple and well defined remote madvise alternative first and build a vector API on top with some numbers based on _real_ workloads.

Quoted 8 lines
Quoted 5 lines

First time, I didn't think about atomicity about address range race because MADV_COLD/PAGEOUT is not critical for the race. However you raised the atomicity issue because people would extend hints to destructive ones easily. I agree with that and that's why we discussed how to guarantee the race and Daniel comes up with good idea.

Just for the clarification, I didn't really mean atomicity but rather a _consistency_ (essentially time to check to time to use consistency).

What do you mean by *consistency*? Could you elaborate it more?

Quoted 11 lines
Quoted 11 lines

- vma configuration seq number via process_getinfo(2).

We discussed the race issue without _read_ workloads/requests because it's common sense that people might extend the syscall later.

Here is same. For current workload, we don't need to support vector for perfomance point of view based on my experiment. However, it's rather limited experiment. Some configuration might have 10000+ vmas or really slow CPU.

Quoted 7 lines
Quoted 4 lines

Furthermore, I want to have vector support due to atomicity issue if it's really the one we should consider.
With vector support of the API and vma configuration sequence number from Daniel, we could support address ranges operations's atomicity.

I am not sure what do you mean here. Perform all ranges atomicaly wrt. other address space modifications? If yes I am not sure we want that

Yub, I think it's *necessary* if we want to support destructive hints via process_madvise.

Quoted 1 line

semantic because it can cause really long stalls for other operations

It could be or it couldn't be.

For example, if we could multiplex several syscalls which we should enumerate all of page table lookup, it could be more effective rather than doing each page table on each syscall.

Quoted 2 lines

but that is a discussion on its own and I would rather focus on a simple interface first.

It seems it's time to send RFCv2 since we discussed a lot although we don't have clear conclution yet. But still want to understand what you meant _consistency_.

Thanks for the review, Michal! It's very helpful.

Quoted 18 lines
Quoted 4 lines

However, since we don't introduce vector at this moment, we need to introduce *another syscall* later to be able to handle multile ranges all at once atomically if it's okay.

Agreed.

Quoted 5 lines

Other thought:
Maybe we could extend address range batch syscall covers other MM syscall like mmap/munmap/madvise/mprotect and so on because there are multiple users that would benefit from this general batching mechanism.

Again a discussion on its own ;)

Signature · 2 lines
Michal Hocko
SUSE Labs
#58 lore raw

Re: [RFC 6/7] mm: extend process_madvise syscall to support vector arrary

Quoted 87 lines · Minchan Kim
Quoted 58 lines · Michal Hocko
Quoted 57 lines · Minchan Kim
Quoted 55 lines · Michal Hocko
Quoted 38 lines · Daniel Colascione
Quoted 28 lines · Minchan Kim
Quoted 26 lines · Michal Hocko
Quoted 24 lines · Minchan Kim
Quoted 11 lines · Michal Hocko
Quoted 10 lines · Minchan Kim
Quoted 8 lines · Michal Hocko

[Cc linux-api]

Quoted 3 lines · Minchan Kim

Currently, process_madvise syscall works for only one address range so user should call the syscall several times to give hints to multiple address range.

Is that a problem? How big of a problem? Any numbers?

Quoted 8 lines
Quoted 2 lines

We easily have 2000+ vma so it's not trivial overhead. I will come up with number in the description at respin.

Does this really have to be a fast operation? I would expect the monitor is by no means a fast path. The system call overhead is not what it used to be, sigh, but still for something that is not a hot path it should be tolerable, especially when the whole operation is quite expensive on its own (wrt. the syscall entry/exit).

What's different with process_vm_[readv|writev] and vmsplice? If the range needed to be covered is a lot, vector operation makes senese to me.

Quoted 8 lines
Quoted 3 lines

I am not saying that the vector API is wrong. All I am trying to say is that the benefit is not really clear so far. If you want to push it through then you should better get some supporting data.

I measured 1000 madvise syscall vs. a vector range syscall with 1000 ranges on ARM64 mordern device. Even though I saw 15% improvement but absoluate gain is just 1ms so I don't think it's worth to support. I will drop vector support at next revision.

Quoted 7 lines

Please do keep the vector support. Absolute timing is misleading, since in a tight loop, you're not going to contend on mmap_sem. We've seen tons of improvements in things like camera start come from coalescing mprotect calls, with the gains coming from taking and releasing various locks a lot less often and bouncing around less on the contended lock paths. Raw throughput doesn't tell the whole story, especially on mobile.

This will always be a double edge sword. Taking a lock for longer can improve a throughput of a single call but it would make a latency for anybody contending on the lock much worse.

Besides that, please do not overcomplicate the thing from the early beginning please. Let's start with a simple and well defined remote madvise alternative first and build a vector API on top with some numbers based on _real_ workloads.

Quoted 8 lines
Quoted 5 lines

First time, I didn't think about atomicity about address range race because MADV_COLD/PAGEOUT is not critical for the race. However you raised the atomicity issue because people would extend hints to destructive ones easily. I agree with that and that's why we discussed how to guarantee the race and Daniel comes up with good idea.

Just for the clarification, I didn't really mean atomicity but rather a _consistency_ (essentially time to check to time to use consistency).

What do you mean by *consistency*? Could you elaborate it more?

Quoted 16 lines
Quoted 15 lines

- vma configuration seq number via process_getinfo(2).

We discussed the race issue without _read_ workloads/requests because it's common sense that people might extend the syscall later.

Here is same. For current workload, we don't need to support vector for perfomance point of view based on my experiment. However, it's rather limited experiment. Some configuration might have 10000+ vmas or really slow CPU.

Furthermore, I want to have vector support due to atomicity issue if it's really the one we should consider.
With vector support of the API and vma configuration sequence number from Daniel, we could support address ranges operations's atomicity.

Quoted 5 lines
Quoted 2 lines

I am not sure what do you mean here. Perform all ranges atomicaly wrt. other address space modifications? If yes I am not sure we want that

Yub, I think it's *necessary* if we want to support destructive hints via process_madvise.

[Puts on flame-proof suit]

Here's a quick sketch of what I have in mind for process_getinfo(2). Keep in mind that it's still just a rough idea.

We've had trouble efficiently learning about process and memory state of the system via procfs. Android background memory-use scans (the android.bg daemon) consume quite a bit of CPU time for PSS; Minchan's done a lot of thinking for how we can specify desired page sets for compaction as part of this patch set; and the full procfs walks that some trace collection tools need to undertake take more than 200ms to collect (sometimes much more) due mostly to procfs iteration. ISTM we can do better.

While procfs *works* on a functional level, it's inefficient due to the splatting of information we want across several different files (which need to be independently opened --- e.g., /proc/pid/oom_score_adj *and* /proc/pid/status), inefficient due to the ad-hoc text formatting, inefficient due to information over-fetch, and cumbersome due to the fundamental impedance mismatch between filesystem APIs and process lifetimes. procfs itself is also optional, which has caused various bits of awkwardness that you'll recall from the pidfd discussions.

How about we solve the problem once and for all? I'm imagining a new process_getinfo(2) that solves all of these problems at the same time. I want something with a few properties:

1) if we want to learn M facts about N things, we enter the kernel once and learn all M*N things,
2) the information we collect is self-consistent (which implies atomicity most of the time),
3) we retrieve the information we want in an efficient binary format, and
4) we don't pay to learn anything not in M.

I've jotted down a quick sketch of the API below; I'm curious what everyone else thinks. It'd basically look like this:

int process_getinfo(int nr_proc, int* proc, int flags, unsigned long mask, void* out_buf, size_t* inout_sz)

We wouldn't use the return value for much: 0 on success and -1 on error with errno set. NR_PROC and PROC together would specify the objects we want to learn about, which would be either PIDs or PIDFDs or maybe nothing at all if FLAGS tells us to inspect every process on the system. MASK is a bitset of facts we want to learn, described below. OUT_BUF and INOUT_SZ are for actually communicating the result. On input, the caller would fill *INOUT_SZ with the size of the buffer to which OUT_BUF points; on success, we'd fill *INOUT_SZ with the number of bytes we actually used. If the output buffer is too small, we'll truncate the result, fail the system call with E2BIG, and fill *INOUT_SZ with the number of needed bytes, inviting the caller to try again. (If a caller supplies something huge like a reusable 512KB buffer on the first call, no reallocation and retries will be necessary in practice on a typically-sized system.)

The actual returned buffer is a collection of structures and data blocks starting with a struct process_info. The structures in the returned buffer sometimes contain "pointers" to other structures encoded as byte offsets from the start of the information buffer. Using offsets instead of actual pointers keeps the format the same across 32- and 64-bit versions of process_getinfo and makes it possible to relocate the returned information buffer with memcpy.

struct process_info {
int first_procrec_offset; // struct procrec* // Examples of system-wide things we could ask for int mem_total_kb;
int mem_free_kb;
int mem_available_kb;
char reserved[];
};

struct procrec {
int next_procrec_offset; // struct procrec*
// Following fields are self-explanatory and are only examples of the // kind of information we could provide.
int tid;
int tgid;
char status;
int oom_score_adj;
struct { int real, effective, saved, fs; } uids;
int prio;
int comm_offset; // char*
uint64_t rss_file_kb
uint64_t rss_anon_fb;
uint64_t vm_seq;
int first_procrec_vma_offset; // struct procrec_vma*
char reserved[];
};

struct procrec_vma {
int next_procrec_vma_offset; // struct procrec_vma* unsigned long start;
unsigned long end;
int backing_file_name_offset; // char*
int prot;
char reserved[];
};

Callers would use the returned buffer by casting it to a struct process_info and following the internal "pointers".

MASK would specify which bits of information we wanted: for example, if we asked for PROCESS_VM_MEMORY_MAP, the kernel would fill in each struct procret's memory_map field and have it point to a struct procrec_vma in the returned output buffer. If we omitted PROCESS_VM_MEMORY_MAP, we'd leave the memory_map field as NULL (encoded as offset zero). The kernel would embed any strings (like comm and VMA names) into the output buffer; the precise locations would be unspecified so long as callers could find these fields via output-buffer pointers.

Because all the structures are variable-length and are chained together with explicit pointers (or offsets) instead of being stuffed into a literal array, we can add additional fields to the output structures any time we want without breaking binary compatibility. Callers would tell the kernel that they're interested in the added struct fields by asking for them via bits in MASK, and kernels that don't understand those fields would just fail the system call with EINVAL or something.

Depending on how we call it, we can use this API as a bunch of different things:

1) Quick retrieval of system-wide memory counters, like /proc/meminfo
2) Quick snapshot of all process-thread identities (asking for the wildcard TID match via FLAGS)
3) Fast enumeration of one process's address space
4) Collecting process-summary VM counters (e.g., rss_anon and rss_file) for a set of processes
5) Retrieval of every VMA of every process on the system for debugging

We can do all of this with one entry into the kernel and without opening any new file descriptors (unless we want to use pidfds as inputs). We can also make this operation as atomic as we want, e.g., taking mmap_sem while looking at each process and taking tasklist_lock so all the thread IDs line up with their processes. We don't necessarily need to take the mmap_sems of all processes we care about at the same time.

Since this isn't a filesystem-based API, we don't have to deal with seq_file or deal with consistency issues arising from userspace programs doing strange things like reading procfs files very slowly in small chunks. Security-wise, we'd just use different access checks for different requested information bits in MASK, maybe supplying "no access" struct procrec entries if a caller doesn't happen to have access to a particular process. I suppose we can talk about whether access check failures should result in dummy values or syscall
failure: maybe callers should select which behavior they want. Format-wise, we could also just return flatbuffer messages from the kernel, but I suspect that we don't want flatbuffer in the kernel right now. :-)

The API I'm proposing accepts an array of processes to inspect. We could simplify it by accepting just one process and making the caller enter the kernel once per process it wants to learn about, but this simplification would make the API less useful for answering questions like "What's the RSS of every process on the system right now?".

What do you think?

reviewer
#59 lore raw

Re: [RFC 6/7] mm: extend process_madvise syscall to support vector arrary

In reply to Minchan Kim
Quoted 2 lines · Minchan Kim
Quoted 1 line · Michal Hocko

On Thu 30-05-19 11:17:48, Minchan Kim wrote:

[...]

Quoted 10 lines
Quoted 8 lines
Quoted 5 lines

First time, I didn't think about atomicity about address range race because MADV_COLD/PAGEOUT is not critical for the race. However you raised the atomicity issue because people would extend hints to destructive ones easily. I agree with that and that's why we discussed how to guarantee the race and Daniel comes up with good idea.

Just for the clarification, I didn't really mean atomicity but rather a _consistency_ (essentially time to check to time to use consistency).

What do you mean by *consistency*? Could you elaborate it more?

That you operate on the object you have got by some means. In other words that the range you want to call madvise on hasn't been remapped/replaced by a different mmap operation.

Signature · 2 lines
Michal Hocko
SUSE Labs
#60 lore raw

Re: [RFC 6/7] mm: extend process_madvise syscall to support vector arrary

In reply to Minchan Kim
Quoted 6 lines · Hillf Danton
Quoted 2 lines · On Mon, 20 May 2019 12:52:53 +0900 Minchan Kim wrote:

Example)

Better if the following stuff is stored somewhere under the tools/testing directory.

Sure, I will do once we figure out RFC stage.

#61 lore raw

RFC 7/7 mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

In reply to Minchan Kim

System could have much faster swap device like zRAM. In that case, swapping is extremely cheaper than file-IO on the low-end storage.
In this configuration, userspace could handle different strategy for each kinds of vma. IOW, they want to reclaim anonymous pages by MADV_COLD while it keeps file-backed pages in inactive LRU by MADV_COOL because file IO is more expensive in this case so want to keep them in memory until memory pressure happens.

To support such strategy easier, this patch introduces MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER options in madvise(2) like that /proc/<pid>/clear_refs already has supported same filters. They are filters could be Ored with other existing hints using top two bits of (int behavior).

Once either of them is set, the hint could affect only the interested vma either anonymous or file-backed.

With that, user could call a process_madvise syscall simply with a entire range(0x0 - 0xFFFFFFFFFFFFFFFF) but either of MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER so there is no need to call the syscall range by range.

* from v1r2
* use consistent check with clear_refs to identify anon/file vma - surenb

* from v1r1
* use naming "filter" for new madvise option - dancol

---
 include/uapi/asm-generic/mman-common.h |  5 +++++
 mm/madvise.c                           | 14 ++++++++++++++
 2 files changed, 19 insertions(+)
include/uapi/asm-generic/mman-common.h +5 -0
index b8e230de84a6..be59a1b90284 100644
@@ -66,6 +66,11 @@
 #define MADV_WIPEONFORK 18		/* Zero memory on fork, child only */
 #define MADV_KEEPONFORK 19		/* Undo MADV_WIPEONFORK */
 
+#define MADV_BEHAVIOR_MASK (~(MADV_ANONYMOUS_FILTER|MADV_FILE_FILTER))
+
+#define MADV_ANONYMOUS_FILTER	(1<<31)	/* works for only anonymous vma */
+#define MADV_FILE_FILTER	(1<<30)	/* works for only file-backed vma */
+
 /* compatibility flags */
 #define MAP_FILE	0
 
mm/madvise.c +14 -0
index f4f569dac2bd..116131243540 100644
@@ -1002,7 +1002,15 @@ static int madvise_core(struct task_struct *tsk, unsigned long start,
 	int write;
 	size_t len;
 	struct blk_plug plug;
+	bool anon_only, file_only;
 
+	anon_only = behavior & MADV_ANONYMOUS_FILTER;
+	file_only = behavior & MADV_FILE_FILTER;
+
+	if (anon_only && file_only)
+		return error;
+
+	behavior = behavior & MADV_BEHAVIOR_MASK;
 	if (!madvise_behavior_valid(behavior))
 		return error;
 
@@ -1067,12 +1075,18 @@ static int madvise_core(struct task_struct *tsk, unsigned long start,
 		if (end < tmp)
 			tmp = end;
 
+		if (anon_only && vma->vm_file)
+			goto next;
+		if (file_only && !vma->vm_file)
+			goto next;
+
 		/* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */
 		error = madvise_vma(tsk, vma, &prev, start, tmp,
 					behavior, &pages);
 		if (error)
 			goto out;
 		*nr_pages += pages;
+next:
 		start = tmp;
 		if (prev && start < prev->vm_end)
 			start = prev->vm_end;
Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
reviewer
#62 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

[cc linux-api]

Quoted 8 lines · Minchan Kim

System could have much faster swap device like zRAM. In that case, swapping is extremely cheaper than file-IO on the low-end storage.
In this configuration, userspace could handle different strategy for each kinds of vma. IOW, they want to reclaim anonymous pages by MADV_COLD while it keeps file-backed pages in inactive LRU by MADV_COOL because file IO is more expensive in this case so want to keep them in memory until memory pressure happens.

Quoted 5 lines

To support such strategy easier, this patch introduces MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER options in madvise(2) like that /proc/<pid>/clear_refs already has supported same filters. They are filters could be Ored with other existing hints using top two bits of (int behavior).

madvise operates on top of ranges and it is quite trivial to do the filtering from the userspace so why do we need any additional filtering?

Quoted 6 lines

Once either of them is set, the hint could affect only the interested vma either anonymous or file-backed.

With that, user could call a process_madvise syscall simply with a entire range(0x0 - 0xFFFFFFFFFFFFFFFF) but either of MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER so there is no need to call the syscall range by range.

OK, so here is the reason you want that. The immediate question is why cannot the monitor do the filtering from the userspace. Slightly more work, all right, but less of an API to expose and that itself is a strong argument against.

Quoted 70 lines

* from v1r2
* use consistent check with clear_refs to identify anon/file vma - surenb

* from v1r1
* use naming "filter" for new madvise option - dancol

---
 include/uapi/asm-generic/mman-common.h |  5 +++++
 mm/madvise.c                           | 14 ++++++++++++++
 2 files changed, 19 insertions(+)
include/uapi/asm-generic/mman-common.h +5 -0
index b8e230de84a6..be59a1b90284 100644
@@ -66,6 +66,11 @@
 #define MADV_WIPEONFORK 18		/* Zero memory on fork, child only */
 #define MADV_KEEPONFORK 19		/* Undo MADV_WIPEONFORK */
 
+#define MADV_BEHAVIOR_MASK (~(MADV_ANONYMOUS_FILTER|MADV_FILE_FILTER))
+
+#define MADV_ANONYMOUS_FILTER	(1<<31)	/* works for only anonymous vma */
+#define MADV_FILE_FILTER	(1<<30)	/* works for only file-backed vma */
+
 /* compatibility flags */
 #define MAP_FILE	0
 
mm/madvise.c +14 -0
index f4f569dac2bd..116131243540 100644
@@ -1002,7 +1002,15 @@ static int madvise_core(struct task_struct *tsk, unsigned long start,
 	int write;
 	size_t len;
 	struct blk_plug plug;
+	bool anon_only, file_only;
 
+	anon_only = behavior & MADV_ANONYMOUS_FILTER;
+	file_only = behavior & MADV_FILE_FILTER;
+
+	if (anon_only && file_only)
+		return error;
+
+	behavior = behavior & MADV_BEHAVIOR_MASK;
 	if (!madvise_behavior_valid(behavior))
 		return error;
 
@@ -1067,12 +1075,18 @@ static int madvise_core(struct task_struct *tsk, unsigned long start,
 		if (end < tmp)
 			tmp = end;
 
+		if (anon_only && vma->vm_file)
+			goto next;
+		if (file_only && !vma->vm_file)
+			goto next;
+
 		/* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */
 		error = madvise_vma(tsk, vma, &prev, start, tmp,
 					behavior, &pages);
 		if (error)
 			goto out;
 		*nr_pages += pages;
+next:
 		start = tmp;
 		if (prev && start < prev->vm_end)
 			start = prev->vm_end;
Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
Signature · 2 lines
Michal Hocko
SUSE Labs
#63 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 23 lines · Michal Hocko

[cc linux-api]

Quoted 8 lines · Minchan Kim

System could have much faster swap device like zRAM. In that case, swapping is extremely cheaper than file-IO on the low-end storage.
In this configuration, userspace could handle different strategy for each kinds of vma. IOW, they want to reclaim anonymous pages by MADV_COLD while it keeps file-backed pages in inactive LRU by MADV_COOL because file IO is more expensive in this case so want to keep them in memory until memory pressure happens.

Quoted 5 lines

To support such strategy easier, this patch introduces MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER options in madvise(2) like that /proc/<pid>/clear_refs already has supported same filters. They are filters could be Ored with other existing hints using top two bits of (int behavior).

madvise operates on top of ranges and it is quite trivial to do the filtering from the userspace so why do we need any additional filtering?

Quoted 3 lines

Once either of them is set, the hint could affect only the interested vma either anonymous or file-backed.

Quoted 8 lines
Quoted 3 lines

With that, user could call a process_madvise syscall simply with a entire range(0x0 - 0xFFFFFFFFFFFFFFFF) but either of MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER so there is no need to call the syscall range by range.

OK, so here is the reason you want that. The immediate question is why cannot the monitor do the filtering from the userspace. Slightly more work, all right, but less of an API to expose and that itself is a strong argument against.

What I should do if we don't have such filter option is to enumerate all of vma via /proc/<pid>/maps and then parse every ranges and inode from string, which would be painful for 2000+ vmas.

Quoted 75 lines
Quoted 71 lines

* from v1r2
* use consistent check with clear_refs to identify anon/file vma - surenb

* from v1r1
* use naming "filter" for new madvise option - dancol

---
 include/uapi/asm-generic/mman-common.h |  5 +++++
 mm/madvise.c                           | 14 ++++++++++++++
 2 files changed, 19 insertions(+)
include/uapi/asm-generic/mman-common.h +5 -0
index b8e230de84a6..be59a1b90284 100644
@@ -66,6 +66,11 @@
 #define MADV_WIPEONFORK 18		/* Zero memory on fork, child only */
 #define MADV_KEEPONFORK 19		/* Undo MADV_WIPEONFORK */
 
+#define MADV_BEHAVIOR_MASK (~(MADV_ANONYMOUS_FILTER|MADV_FILE_FILTER))
+
+#define MADV_ANONYMOUS_FILTER	(1<<31)	/* works for only anonymous vma */
+#define MADV_FILE_FILTER	(1<<30)	/* works for only file-backed vma */
+
 /* compatibility flags */
 #define MAP_FILE	0
 
mm/madvise.c +14 -0
index f4f569dac2bd..116131243540 100644
@@ -1002,7 +1002,15 @@ static int madvise_core(struct task_struct *tsk, unsigned long start,
 	int write;
 	size_t len;
 	struct blk_plug plug;
+	bool anon_only, file_only;
 
+	anon_only = behavior & MADV_ANONYMOUS_FILTER;
+	file_only = behavior & MADV_FILE_FILTER;
+
+	if (anon_only && file_only)
+		return error;
+
+	behavior = behavior & MADV_BEHAVIOR_MASK;
 	if (!madvise_behavior_valid(behavior))
 		return error;
 
@@ -1067,12 +1075,18 @@ static int madvise_core(struct task_struct *tsk, unsigned long start,
 		if (end < tmp)
 			tmp = end;
 
+		if (anon_only && vma->vm_file)
+			goto next;
+		if (file_only && !vma->vm_file)
+			goto next;
+
 		/* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */
 		error = madvise_vma(tsk, vma, &prev, start, tmp,
 					behavior, &pages);
 		if (error)
 			goto out;
 		*nr_pages += pages;
+next:
 		start = tmp;
 		if (prev && start < prev->vm_end)
 			start = prev->vm_end;
Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
Signature · 2 lines
Michal Hocko
SUSE Labs
reviewer
#64 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 28 lines · Minchan Kim
Quoted 27 lines · Michal Hocko

[cc linux-api]

Quoted 8 lines · Minchan Kim

System could have much faster swap device like zRAM. In that case, swapping is extremely cheaper than file-IO on the low-end storage.
In this configuration, userspace could handle different strategy for each kinds of vma. IOW, they want to reclaim anonymous pages by MADV_COLD while it keeps file-backed pages in inactive LRU by MADV_COOL because file IO is more expensive in this case so want to keep them in memory until memory pressure happens.

Quoted 5 lines

To support such strategy easier, this patch introduces MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER options in madvise(2) like that /proc/<pid>/clear_refs already has supported same filters. They are filters could be Ored with other existing hints using top two bits of (int behavior).

madvise operates on top of ranges and it is quite trivial to do the filtering from the userspace so why do we need any additional filtering?

Quoted 6 lines

Once either of them is set, the hint could affect only the interested vma either anonymous or file-backed.

With that, user could call a process_madvise syscall simply with a entire range(0x0 - 0xFFFFFFFFFFFFFFFF) but either of MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER so there is no need to call the syscall range by range.

Quoted 8 lines
Quoted 4 lines

OK, so here is the reason you want that. The immediate question is why cannot the monitor do the filtering from the userspace. Slightly more work, all right, but less of an API to expose and that itself is a strong argument against.

What I should do if we don't have such filter option is to enumerate all of vma via /proc/<pid>/maps and then parse every ranges and inode from string, which would be painful for 2000+ vmas.

Painful is not an argument to add a new user API. If the existing API suits the purpose then it should be used. If it is not usable, we can think of a different way.

Signature · 2 lines
Michal Hocko
SUSE Labs
#65 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 34 lines · Michal Hocko
Quoted 33 lines · Minchan Kim
Quoted 31 lines · Michal Hocko

[cc linux-api]

Quoted 8 lines · Minchan Kim

System could have much faster swap device like zRAM. In that case, swapping is extremely cheaper than file-IO on the low-end storage.
In this configuration, userspace could handle different strategy for each kinds of vma. IOW, they want to reclaim anonymous pages by MADV_COLD while it keeps file-backed pages in inactive LRU by MADV_COOL because file IO is more expensive in this case so want to keep them in memory until memory pressure happens.

Quoted 5 lines

To support such strategy easier, this patch introduces MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER options in madvise(2) like that /proc/<pid>/clear_refs already has supported same filters. They are filters could be Ored with other existing hints using top two bits of (int behavior).

madvise operates on top of ranges and it is quite trivial to do the filtering from the userspace so why do we need any additional filtering?

Quoted 6 lines

Once either of them is set, the hint could affect only the interested vma either anonymous or file-backed.

With that, user could call a process_madvise syscall simply with a entire range(0x0 - 0xFFFFFFFFFFFFFFFF) but either of MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER so there is no need to call the syscall range by range.

OK, so here is the reason you want that. The immediate question is why cannot the monitor do the filtering from the userspace. Slightly more work, all right, but less of an API to expose and that itself is a strong argument against.

Quoted 7 lines
Quoted 3 lines

What I should do if we don't have such filter option is to enumerate all of vma via /proc/<pid>/maps and then parse every ranges and inode from string, which would be painful for 2000+ vmas.

Painful is not an argument to add a new user API. If the existing API suits the purpose then it should be used. If it is not usable, we can think of a different way.

I measured 1568 vma parsing overhead of /proc/<pid>/maps in ARM64 modern mobile CPU. It takes 60ms and 185ms on big cores depending on cpu governor. It's never trivial.

reviewer
#66 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 39 lines · Minchan Kim
Quoted 38 lines · Michal Hocko
Quoted 36 lines · Minchan Kim
Quoted 23 lines · Michal Hocko

[cc linux-api]

Quoted 8 lines · Minchan Kim

System could have much faster swap device like zRAM. In that case, swapping is extremely cheaper than file-IO on the low-end storage.
In this configuration, userspace could handle different strategy for each kinds of vma. IOW, they want to reclaim anonymous pages by MADV_COLD while it keeps file-backed pages in inactive LRU by MADV_COOL because file IO is more expensive in this case so want to keep them in memory until memory pressure happens.

Quoted 5 lines

To support such strategy easier, this patch introduces MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER options in madvise(2) like that /proc/<pid>/clear_refs already has supported same filters. They are filters could be Ored with other existing hints using top two bits of (int behavior).

madvise operates on top of ranges and it is quite trivial to do the filtering from the userspace so why do we need any additional filtering?

Quoted 3 lines

Once either of them is set, the hint could affect only the interested vma either anonymous or file-backed.

Quoted 8 lines
Quoted 3 lines

With that, user could call a process_madvise syscall simply with a entire range(0x0 - 0xFFFFFFFFFFFFFFFF) but either of MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER so there is no need to call the syscall range by range.

OK, so here is the reason you want that. The immediate question is why cannot the monitor do the filtering from the userspace. Slightly more work, all right, but less of an API to expose and that itself is a strong argument against.

What I should do if we don't have such filter option is to enumerate all of vma via /proc/<pid>/maps and then parse every ranges and inode from string, which would be painful for 2000+ vmas.

Quoted 7 lines
Quoted 3 lines

Painful is not an argument to add a new user API. If the existing API suits the purpose then it should be used. If it is not usable, we can think of a different way.

I measured 1568 vma parsing overhead of /proc/<pid>/maps in ARM64 modern mobile CPU. It takes 60ms and 185ms on big cores depending on cpu governor. It's never trivial.

This is not the only option. Have you tried to simply use /proc/<pid>/map_files interface? This will provide you with all the file backed mappings.

Signature · 2 lines
Michal Hocko
SUSE Labs
#67 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 44 lines · Michal Hocko
Quoted 43 lines · Minchan Kim
Quoted 41 lines · Michal Hocko
Quoted 28 lines · Minchan Kim
Quoted 27 lines · Michal Hocko

[cc linux-api]

Quoted 8 lines · Minchan Kim

System could have much faster swap device like zRAM. In that case, swapping is extremely cheaper than file-IO on the low-end storage.
In this configuration, userspace could handle different strategy for each kinds of vma. IOW, they want to reclaim anonymous pages by MADV_COLD while it keeps file-backed pages in inactive LRU by MADV_COOL because file IO is more expensive in this case so want to keep them in memory until memory pressure happens.

Quoted 5 lines

To support such strategy easier, this patch introduces MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER options in madvise(2) like that /proc/<pid>/clear_refs already has supported same filters. They are filters could be Ored with other existing hints using top two bits of (int behavior).

madvise operates on top of ranges and it is quite trivial to do the filtering from the userspace so why do we need any additional filtering?

Quoted 6 lines

Once either of them is set, the hint could affect only the interested vma either anonymous or file-backed.

With that, user could call a process_madvise syscall simply with a entire range(0x0 - 0xFFFFFFFFFFFFFFFF) but either of MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER so there is no need to call the syscall range by range.

Quoted 8 lines
Quoted 4 lines

OK, so here is the reason you want that. The immediate question is why cannot the monitor do the filtering from the userspace. Slightly more work, all right, but less of an API to expose and that itself is a strong argument against.

What I should do if we don't have such filter option is to enumerate all of vma via /proc/<pid>/maps and then parse every ranges and inode from string, which would be painful for 2000+ vmas.

Painful is not an argument to add a new user API. If the existing API suits the purpose then it should be used. If it is not usable, we can think of a different way.

Quoted 7 lines
Quoted 3 lines

I measured 1568 vma parsing overhead of /proc/<pid>/maps in ARM64 modern mobile CPU. It takes 60ms and 185ms on big cores depending on cpu governor. It's never trivial.

This is not the only option. Have you tried to simply use /proc/<pid>/map_files interface? This will provide you with all the file backed mappings.

I compared maps vs. map_files with 3036 file-backed vma.
Test scenario is to dump all of vmas of the process and parse address ranges.
For map_files, it's easy to parse each address range because directory name itself is range. However, in case of maps, I need to parse each range line by line so need to scan all of lines.

(maps cover additional non-file-backed vmas so nr_vma is a little bigger)

performance mode:
map_files: nr_vma 3036 usec 13387
maps : nr_vma 3078 usec 12923

powersave mode:

map_files: nr_vma 3036 usec 52614
maps : nr_vma 3078 usec 41089

map_files is slower than maps if we dump all of vmas. I guess directory operation needs much more jobs(e.g., dentry lookup, instantiation) compared to maps.

reviewer
#68 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 66 lines · Minchan Kim
Quoted 44 lines · Michal Hocko
Quoted 43 lines · Minchan Kim
Quoted 41 lines · Michal Hocko
Quoted 28 lines · Minchan Kim
Quoted 27 lines · Michal Hocko

[cc linux-api]

Quoted 8 lines · Minchan Kim

System could have much faster swap device like zRAM. In that case, swapping is extremely cheaper than file-IO on the low-end storage.
In this configuration, userspace could handle different strategy for each kinds of vma. IOW, they want to reclaim anonymous pages by MADV_COLD while it keeps file-backed pages in inactive LRU by MADV_COOL because file IO is more expensive in this case so want to keep them in memory until memory pressure happens.

Quoted 5 lines

To support such strategy easier, this patch introduces MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER options in madvise(2) like that /proc/<pid>/clear_refs already has supported same filters. They are filters could be Ored with other existing hints using top two bits of (int behavior).

madvise operates on top of ranges and it is quite trivial to do the filtering from the userspace so why do we need any additional filtering?

Quoted 6 lines

Once either of them is set, the hint could affect only the interested vma either anonymous or file-backed.

With that, user could call a process_madvise syscall simply with a entire range(0x0 - 0xFFFFFFFFFFFFFFFF) but either of MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER so there is no need to call the syscall range by range.

Quoted 8 lines
Quoted 4 lines

OK, so here is the reason you want that. The immediate question is why cannot the monitor do the filtering from the userspace. Slightly more work, all right, but less of an API to expose and that itself is a strong argument against.

What I should do if we don't have such filter option is to enumerate all of vma via /proc/<pid>/maps and then parse every ranges and inode from string, which would be painful for 2000+ vmas.

Painful is not an argument to add a new user API. If the existing API suits the purpose then it should be used. If it is not usable, we can think of a different way.

Quoted 7 lines
Quoted 3 lines

I measured 1568 vma parsing overhead of /proc/<pid>/maps in ARM64 modern mobile CPU. It takes 60ms and 185ms on big cores depending on cpu governor. It's never trivial.

This is not the only option. Have you tried to simply use /proc/<pid>/map_files interface? This will provide you with all the file backed mappings.

I compared maps vs. map_files with 3036 file-backed vma.
Test scenario is to dump all of vmas of the process and parse address ranges.
For map_files, it's easy to parse each address range because directory name itself is range. However, in case of maps, I need to parse each range line by line so need to scan all of lines.

(maps cover additional non-file-backed vmas so nr_vma is a little bigger)

performance mode:
map_files: nr_vma 3036 usec 13387
maps : nr_vma 3078 usec 12923

Quoted 8 lines

powersave mode:

map_files: nr_vma 3036 usec 52614
maps : nr_vma 3078 usec 41089

map_files is slower than maps if we dump all of vmas. I guess directory operation needs much more jobs(e.g., dentry lookup, instantiation) compared to maps.

OK, that is somehow surprising. I am still not convinced the filter is a good idea though. The primary reason is that it encourages using madvise on a wide range without having a clue what the range contains. E.g. the full address range and rely the right thing will happen. Do we really want madvise to operate in that mode?

Btw. if we went with the per vma fd approach then you would get this feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

Signature · 2 lines
Michal Hocko
SUSE Labs
#69 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 76 lines · Michal Hocko
Quoted 66 lines · Minchan Kim
Quoted 44 lines · Michal Hocko
Quoted 43 lines · Minchan Kim
Quoted 41 lines · Michal Hocko
Quoted 28 lines · Minchan Kim
Quoted 27 lines · Michal Hocko

[cc linux-api]

Quoted 8 lines · Minchan Kim

System could have much faster swap device like zRAM. In that case, swapping is extremely cheaper than file-IO on the low-end storage.
In this configuration, userspace could handle different strategy for each kinds of vma. IOW, they want to reclaim anonymous pages by MADV_COLD while it keeps file-backed pages in inactive LRU by MADV_COOL because file IO is more expensive in this case so want to keep them in memory until memory pressure happens.

Quoted 5 lines

To support such strategy easier, this patch introduces MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER options in madvise(2) like that /proc/<pid>/clear_refs already has supported same filters. They are filters could be Ored with other existing hints using top two bits of (int behavior).

madvise operates on top of ranges and it is quite trivial to do the filtering from the userspace so why do we need any additional filtering?

Quoted 6 lines

Once either of them is set, the hint could affect only the interested vma either anonymous or file-backed.

With that, user could call a process_madvise syscall simply with a entire range(0x0 - 0xFFFFFFFFFFFFFFFF) but either of MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER so there is no need to call the syscall range by range.

Quoted 8 lines
Quoted 4 lines

OK, so here is the reason you want that. The immediate question is why cannot the monitor do the filtering from the userspace. Slightly more work, all right, but less of an API to expose and that itself is a strong argument against.

What I should do if we don't have such filter option is to enumerate all of vma via /proc/<pid>/maps and then parse every ranges and inode from string, which would be painful for 2000+ vmas.

Painful is not an argument to add a new user API. If the existing API suits the purpose then it should be used. If it is not usable, we can think of a different way.

Quoted 7 lines
Quoted 3 lines

I measured 1568 vma parsing overhead of /proc/<pid>/maps in ARM64 modern mobile CPU. It takes 60ms and 185ms on big cores depending on cpu governor. It's never trivial.

This is not the only option. Have you tried to simply use /proc/<pid>/map_files interface? This will provide you with all the file backed mappings.

I compared maps vs. map_files with 3036 file-backed vma.
Test scenario is to dump all of vmas of the process and parse address ranges.
For map_files, it's easy to parse each address range because directory name itself is range. However, in case of maps, I need to parse each range line by line so need to scan all of lines.

(maps cover additional non-file-backed vmas so nr_vma is a little bigger)

performance mode:
map_files: nr_vma 3036 usec 13387
maps : nr_vma 3078 usec 12923

Quoted 8 lines

powersave mode:

map_files: nr_vma 3036 usec 52614
maps : nr_vma 3078 usec 41089

map_files is slower than maps if we dump all of vmas. I guess directory operation needs much more jobs(e.g., dentry lookup, instantiation) compared to maps.

Quoted 5 lines

OK, that is somehow surprising. I am still not convinced the filter is a good idea though. The primary reason is that it encourages using madvise on a wide range without having a clue what the range contains. E.g. the full address range and rely the right thing will happen. Do we really want madvise to operate in that mode?

If user space daemon(e.g., activity manager service) could know a certain process is bakground and idle for a while, yeb, that would be good option.

Quoted 4 lines

Btw. if we went with the per vma fd approach then you would get this feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Quoted 4 lines
Signature · 3 lines
-- 
Michal Hocko
SUSE Labs
#70 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

#71 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 8 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Quoted 7 lines

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

I agree it's the best we can get *generally*.
Michal, any opinion?

reviewer
#72 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 17 lines · Minchan Kim
Quoted 8 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Quoted 7 lines

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

An interface to query address range information is a separate but although a related topic. We have /proc/<pid>/[s]maps for that right now and I understand it is not a general win for all usecases because it tends to be slow for some. I can see how /proc/<pid>/map_anons could provide per vma information in a binary form via a fd based interface. But I would rather not conflate those two discussions much - well except if it could give one of the approaches more justification but let's focus on the madvise part first.

Signature · 2 lines
Michal Hocko
SUSE Labs
#73 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 19 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 15 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 8 lines
Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

I don't think the vma fd approach is viable. We have some processes with a *lot* of VMAs --- system_server had 4204 when I checked just now (and that's typical) --- and an FD operation per VMA would be excessive. VMAs also come and go pretty easily depending on changes in protections and various faults. It's also not entirely clear what the semantics of vma FDs should be over address space mutations, while the semantics of address ranges are well-understood. I would much prefer an interface operating on address ranges to one operating on VMA FDs, both for efficiency and for consistency with other memory management APIs.

Quoted 8 lines

An interface to query address range information is a separate but although a related topic. We have /proc/<pid>/[s]maps for that right now and I understand it is not a general win for all usecases because it tends to be slow for some. I can see how /proc/<pid>/map_anons could provide per vma information in a binary form via a fd based interface. But I would rather not conflate those two discussions much - well except if it could give one of the approaches more justification but let's focus on the madvise part first.

I don't think it's a good idea to focus on one feature in a multi-feature change when the interactions between features can be very important for overall design of the multi-feature system and the design of each feature.

Here's my thinking on the high-level design:

I'm imagining an address-range system that would work like this: we'd create some kind of process_vm_getinfo(2) system call [1] that would accept a statx-like attribute map and a pid/fd parameter as input and return, on output, two things: 1) an array [2] of VMA descriptors containing the requested information, and 2) a VMA configuration sequence number. We'd then have process_madvise() and other cross-process VM interfaces accept both address ranges and this sequence number; they'd succeed only if the VMA configuration sequence number is still current, i.e., the target process hasn't changed its VMA configuration (implicitly or explicitly) since the call to process_vm_getinfo().

This way, a process A that wants to perform some VM operation on process B can slurp B's VMA configuration using process_vm_getinfo(), figure out what it wants to do, and attempt to do it. If B modifies its memory map in the meantime, If A finds that its local knowledge of B's memory map has become invalid between the process_vm_getinfo() and A taking some action based on the result, A can retry [3]. While A could instead ptrace or otherwise suspend B, *then* read B's memory map (knowing B is quiescent), *then* operate on B, the optimistic approach I'm describing would be much lighter-weight in the typical case. It's also pretty simple, IMHO. If the "operate on B" step is some kind of vectorized operation over multiple address ranges, this approach also gets us all-or-nothing semantics.

Or maybe the whole sequence number thing is overkill and we don't need atomicity? But if there's a concern that A shouldn't operate on B's memory without knowing what it's operating on, then the scheme I've proposed above solves this knowledge problem in a pretty lightweight way.

[1] or some other interface
[2] or something more complicated if we want the descriptors to contain variable-length elements, e.g., strings
[3] or override the sequence number check if it's feeling bold?

reviewer
#74 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 29 lines · Daniel Colascione
Quoted 19 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 15 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 8 lines
Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

Quoted 4 lines

I don't think the vma fd approach is viable. We have some processes with a *lot* of VMAs --- system_server had 4204 when I checked just now (and that's typical) --- and an FD operation per VMA would be excessive.

What do you mean by excessive here? Do you expect the process to have them open all at once?

Quoted 2 lines

VMAs also come and go pretty easily depending on changes in protections and various faults.

Is this really too much different from /proc/<pid>/map_files?

[...]

Quoted 16 lines
Quoted 8 lines

An interface to query address range information is a separate but although a related topic. We have /proc/<pid>/[s]maps for that right now and I understand it is not a general win for all usecases because it tends to be slow for some. I can see how /proc/<pid>/map_anons could provide per vma information in a binary form via a fd based interface. But I would rather not conflate those two discussions much - well except if it could give one of the approaches more justification but let's focus on the madvise part first.

I don't think it's a good idea to focus on one feature in a multi-feature change when the interactions between features can be very important for overall design of the multi-feature system and the design of each feature.

Here's my thinking on the high-level design:

Quoted 11 lines

I'm imagining an address-range system that would work like this: we'd create some kind of process_vm_getinfo(2) system call [1] that would accept a statx-like attribute map and a pid/fd parameter as input and return, on output, two things: 1) an array [2] of VMA descriptors containing the requested information, and 2) a VMA configuration sequence number. We'd then have process_madvise() and other cross-process VM interfaces accept both address ranges and this sequence number; they'd succeed only if the VMA configuration sequence number is still current, i.e., the target process hasn't changed its VMA configuration (implicitly or explicitly) since the call to process_vm_getinfo().

The sequence number is essentially a cookie that is transparent to the userspace right? If yes, how does it differ from a fd (returned from /proc/<pid>/map_{anons,files}/range) which is a cookie itself and it can be used to revalidate when the operation is requested and fail if something has changed. Moreover we already do have a fd based madvise syscall so there shouldn't be really a large need to add a new set of syscalls.

[...]

Quoted 5 lines

Or maybe the whole sequence number thing is overkill and we don't need atomicity? But if there's a concern that A shouldn't operate on B's memory without knowing what it's operating on, then the scheme I've proposed above solves this knowledge problem in a pretty lightweight way.

This is the main question here. Do we really want to enforce an external synchronization between the two processes to make sure that they are both operating on the same range - aka protect from the range going away and being reused for a different purpose. Right now it wouldn't be fatal because both operations are non destructive but I can imagine that there will be more madvise operations to follow (including those that are destructive) because people will simply find usecases for that. This should be reflected in the proposed API.

Signature · 2 lines
Michal Hocko
SUSE Labs
#75 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 31 lines · Michal Hocko
Quoted 29 lines · Daniel Colascione
Quoted 27 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 8 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Quoted 7 lines

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

Quoted 7 lines
Quoted 4 lines

I don't think the vma fd approach is viable. We have some processes with a *lot* of VMAs --- system_server had 4204 when I checked just now (and that's typical) --- and an FD operation per VMA would be excessive.

What do you mean by excessive here? Do you expect the process to have them open all at once?

Minchan's already done timing. More broadly, in an era with various speculative execution mitigations, making a system call is pretty expensive. If we have two options for remote VMA manipulation, one that requires thousands of system calls (with the count proportional to the address space size of the process) and one that requires only a few system calls no matter how large the target process is, the latter ought to start off with more points than the former under any kind of design scoring.

Quoted 4 lines
Quoted 2 lines

VMAs also come and go pretty easily depending on changes in protections and various faults.

Is this really too much different from /proc/<pid>/map_files?

It's very different. See below.

Quoted 28 lines
Quoted 16 lines
Quoted 8 lines

An interface to query address range information is a separate but although a related topic. We have /proc/<pid>/[s]maps for that right now and I understand it is not a general win for all usecases because it tends to be slow for some. I can see how /proc/<pid>/map_anons could provide per vma information in a binary form via a fd based interface. But I would rather not conflate those two discussions much - well except if it could give one of the approaches more justification but let's focus on the madvise part first.

I don't think it's a good idea to focus on one feature in a multi-feature change when the interactions between features can be very important for overall design of the multi-feature system and the design of each feature.

Here's my thinking on the high-level design:

Quoted 11 lines

I'm imagining an address-range system that would work like this: we'd create some kind of process_vm_getinfo(2) system call [1] that would accept a statx-like attribute map and a pid/fd parameter as input and return, on output, two things: 1) an array [2] of VMA descriptors containing the requested information, and 2) a VMA configuration sequence number. We'd then have process_madvise() and other cross-process VM interfaces accept both address ranges and this sequence number; they'd succeed only if the VMA configuration sequence number is still current, i.e., the target process hasn't changed its VMA configuration (implicitly or explicitly) since the call to process_vm_getinfo().

Quoted 3 lines

The sequence number is essentially a cookie that is transparent to the userspace right? If yes, how does it differ from a fd (returned from /proc/<pid>/map_{anons,files}/range) which is a cookie itself and it can

If you want to operate on N VMAs simultaneously under an FD-per-VMA model, you'd need to have those N FDs all open at the same time *and* add some kind of system call that accepted those N FDs and an operation to perform. The sequence number I'm proposing also applies to the whole address space, not just one VMA. Even if you did have these N FDs open all at once and supplied them all to some batch operation, you couldn't guarantee via the FD mechanism that some *new* VMA didn't appear in the address range you want to manipulate. A global sequence number would catch this case. I still think supplying a list of address ranges (like we already do for scatter-gather IO) is less error-prone, less resource-intensive, more consistent with existing practice, and equally flexible, especially if we start supporting destructive cross-process memory operations, which may be useful for things like checkpointing and optimizing process startup.

Besides: process_vm_readv and process_vm_writev already work on address ranges. Why should other cross-process memory APIs use a very different model for naming memory regions?

Quoted 4 lines

be used to revalidate when the operation is requested and fail if something has changed. Moreover we already do have a fd based madvise syscall so there shouldn't be really a large need to add a new set of syscalls.

We have various system calls that provide hints for open files, but the memory operations are distinct. Modeling anonymous memory as a kind of file-backed memory for purposes of VMA manipulation would also be a departure from existing practice. Can you help me understand why you seem to favor the FD-per-VMA approach so heavily? I don't see any arguments *for* an FD-per-VMA model for remove memory manipulation and I see a lot of arguments against it. Is there some compelling advantage I'm missing?

Quoted 6 lines
Quoted 5 lines

Or maybe the whole sequence number thing is overkill and we don't need atomicity? But if there's a concern that A shouldn't operate on B's memory without knowing what it's operating on, then the scheme I've proposed above solves this knowledge problem in a pretty lightweight way.

Quoted 8 lines

This is the main question here. Do we really want to enforce an external synchronization between the two processes to make sure that they are both operating on the same range - aka protect from the range going away and being reused for a different purpose. Right now it wouldn't be fatal because both operations are non destructive but I can imagine that there will be more madvise operations to follow (including those that are destructive) because people will simply find usecases for that. This should be reflected in the proposed API.

A sequence number gives us this synchronization at very low cost and adds safety. It's also a general-purpose mechanism that would safeguard *any* cross-process VM operation, not just the VM operations we're discussing right now.

reviewer
#76 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 37 lines · Daniel Colascione
Quoted 36 lines · Michal Hocko
Quoted 33 lines · Daniel Colascione
Quoted 19 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 15 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 8 lines
Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

I don't think the vma fd approach is viable. We have some processes with a *lot* of VMAs --- system_server had 4204 when I checked just now (and that's typical) --- and an FD operation per VMA would be excessive.

Quoted 6 lines
Quoted 2 lines

What do you mean by excessive here? Do you expect the process to have them open all at once?

Minchan's already done timing. More broadly, in an era with various speculative execution mitigations, making a system call is pretty expensive.

This is a completely separate discussion. This could be argued about many other syscalls. Let's make the semantic correct first before we even start thinking about mutliplexing. It is easier to multiplex on an existing and sane interface.

Btw. Minchan concluded that multiplexing is not really all that
important based on his numbers http://lkml.kernel.org/r/[email protected]

[...]

Quoted 36 lines
Quoted 1 line

Is this really too much different from /proc/<pid>/map_files?

It's very different. See below.

Quoted 28 lines
Quoted 16 lines
Quoted 8 lines

An interface to query address range information is a separate but although a related topic. We have /proc/<pid>/[s]maps for that right now and I understand it is not a general win for all usecases because it tends to be slow for some. I can see how /proc/<pid>/map_anons could provide per vma information in a binary form via a fd based interface. But I would rather not conflate those two discussions much - well except if it could give one of the approaches more justification but let's focus on the madvise part first.

I don't think it's a good idea to focus on one feature in a multi-feature change when the interactions between features can be very important for overall design of the multi-feature system and the design of each feature.

Here's my thinking on the high-level design:

Quoted 11 lines

I'm imagining an address-range system that would work like this: we'd create some kind of process_vm_getinfo(2) system call [1] that would accept a statx-like attribute map and a pid/fd parameter as input and return, on output, two things: 1) an array [2] of VMA descriptors containing the requested information, and 2) a VMA configuration sequence number. We'd then have process_madvise() and other cross-process VM interfaces accept both address ranges and this sequence number; they'd succeed only if the VMA configuration sequence number is still current, i.e., the target process hasn't changed its VMA configuration (implicitly or explicitly) since the call to process_vm_getinfo().

Quoted 3 lines

The sequence number is essentially a cookie that is transparent to the userspace right? If yes, how does it differ from a fd (returned from /proc/<pid>/map_{anons,files}/range) which is a cookie itself and it can

Quoted 14 lines

If you want to operate on N VMAs simultaneously under an FD-per-VMA model, you'd need to have those N FDs all open at the same time *and* add some kind of system call that accepted those N FDs and an operation to perform. The sequence number I'm proposing also applies to the whole address space, not just one VMA. Even if you did have these N FDs open all at once and supplied them all to some batch operation, you couldn't guarantee via the FD mechanism that some *new* VMA didn't appear in the address range you want to manipulate. A global sequence number would catch this case. I still think supplying a list of address ranges (like we already do for scatter-gather IO) is less error-prone, less resource-intensive, more consistent with existing practice, and equally flexible, especially if we start supporting destructive cross-process memory operations, which may be useful for things like checkpointing and optimizing process startup.

I have a strong feeling you are over optimizing here. We are talking about a pro-active memory management and so far I haven't heard any usecase where all this would happen in the fast path. There are essentially two usecases I have heard so far. Age/Reclaim the whole process (with anon/fs preferency) and do the same on a particular and well specified range (e.g. a garbage collector or an inactive large image in browsert etc...). The former doesn't really care about parallel address range manipulations because it can tolerate them. The later is a completely different story.

Are there any others where saving few ms matter so much?

Quoted 3 lines

Besides: process_vm_readv and process_vm_writev already work on address ranges. Why should other cross-process memory APIs use a very different model for naming memory regions?

I would consider those APIs not a great example. They are racy on more levels (pid reuse and address space modification), and require a non-trivial synchronization. Do you want something similar for madvise on a non-cooperating remote application?

Quoted 5 lines
Quoted 4 lines

be used to revalidate when the operation is requested and fail if something has changed. Moreover we already do have a fd based madvise syscall so there shouldn't be really a large need to add a new set of syscalls.

Quoted 8 lines

We have various system calls that provide hints for open files, but the memory operations are distinct. Modeling anonymous memory as a kind of file-backed memory for purposes of VMA manipulation would also be a departure from existing practice. Can you help me understand why you seem to favor the FD-per-VMA approach so heavily? I don't see any arguments *for* an FD-per-VMA model for remove memory manipulation and I see a lot of arguments against it. Is there some compelling advantage I'm missing?

First and foremost it provides an easy cookie to the userspace to guarantee time-to-check-time-to-use consistency. It also naturally extend an existing fadvise interface that achieves madvise semantic on files. I am not really pushing hard for this particular API but I really do care about a programming model that would be sane. If we have a different means to achieve the same then all fine by me but so far I haven't heard any sound arguments to invent something completely new when we have established APIs to use. Exporting anonymous mappings via proc the same way we do for file mappings doesn't seem to be stepping outside of the current practice way too much.

All I am trying to say here is that process_madvise(fd, start, len) is inherently racy API and we should focus on discussing whether this is a sane model. And I think it would be much better to discuss that under the respective patch which introduces that API rather than here.

Signature · 2 lines
Michal Hocko
SUSE Labs
#77 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 42 lines · Michal Hocko
Quoted 40 lines · Daniel Colascione
Quoted 38 lines · Michal Hocko
Quoted 29 lines · Daniel Colascione
Quoted 19 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 15 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 8 lines
Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

Quoted 4 lines

I don't think the vma fd approach is viable. We have some processes with a *lot* of VMAs --- system_server had 4204 when I checked just now (and that's typical) --- and an FD operation per VMA would be excessive.

What do you mean by excessive here? Do you expect the process to have them open all at once?

Quoted 6 lines
Quoted 3 lines

Minchan's already done timing. More broadly, in an era with various speculative execution mitigations, making a system call is pretty expensive.

This is a completely separate discussion. This could be argued about many other syscalls.

Yes, it can be. That's why we have scatter-gather IO system calls in the first place.

Quoted 3 lines

Let's make the semantic correct first before we
even start thinking about mutliplexing. It is easier to multiplex on an existing and sane interface.

I don't think of it as "multiplexing" yet, not in the fundamental unit of operation is the address range.

Quoted 66 lines

Btw. Minchan concluded that multiplexing is not really all that
important based on his numbers http://lkml.kernel.org/r/[email protected]

[...]

Quoted 36 lines
Quoted 1 line

Is this really too much different from /proc/<pid>/map_files?

It's very different. See below.

Quoted 28 lines
Quoted 16 lines
Quoted 8 lines

An interface to query address range information is a separate but although a related topic. We have /proc/<pid>/[s]maps for that right now and I understand it is not a general win for all usecases because it tends to be slow for some. I can see how /proc/<pid>/map_anons could provide per vma information in a binary form via a fd based interface. But I would rather not conflate those two discussions much - well except if it could give one of the approaches more justification but let's focus on the madvise part first.

I don't think it's a good idea to focus on one feature in a multi-feature change when the interactions between features can be very important for overall design of the multi-feature system and the design of each feature.

Here's my thinking on the high-level design:

Quoted 11 lines

I'm imagining an address-range system that would work like this: we'd create some kind of process_vm_getinfo(2) system call [1] that would accept a statx-like attribute map and a pid/fd parameter as input and return, on output, two things: 1) an array [2] of VMA descriptors containing the requested information, and 2) a VMA configuration sequence number. We'd then have process_madvise() and other cross-process VM interfaces accept both address ranges and this sequence number; they'd succeed only if the VMA configuration sequence number is still current, i.e., the target process hasn't changed its VMA configuration (implicitly or explicitly) since the call to process_vm_getinfo().

Quoted 3 lines

The sequence number is essentially a cookie that is transparent to the userspace right? If yes, how does it differ from a fd (returned from /proc/<pid>/map_{anons,files}/range) which is a cookie itself and it can

Quoted 14 lines

If you want to operate on N VMAs simultaneously under an FD-per-VMA model, you'd need to have those N FDs all open at the same time *and* add some kind of system call that accepted those N FDs and an operation to perform. The sequence number I'm proposing also applies to the whole address space, not just one VMA. Even if you did have these N FDs open all at once and supplied them all to some batch operation, you couldn't guarantee via the FD mechanism that some *new* VMA didn't appear in the address range you want to manipulate. A global sequence number would catch this case. I still think supplying a list of address ranges (like we already do for scatter-gather IO) is less error-prone, less resource-intensive, more consistent with existing practice, and equally flexible, especially if we start supporting destructive cross-process memory operations, which may be useful for things like checkpointing and optimizing process startup.

I have a strong feeling you are over optimizing here. We are talking about a pro-active memory management and so far I haven't heard any usecase where all this would happen in the fast path. There are essentially two usecases I have heard so far. Age/Reclaim the whole process (with anon/fs preferency) and do the same on a particular and well specified range (e.g. a garbage collector or an inactive large image in browsert etc...). The former doesn't really care about parallel address range manipulations because it can tolerate them. The later is a completely different story.

Quoted 1 line

Are there any others where saving few ms matter so much?

Saving ms matters quite a bit. We may want to perform some of this eager memory management in response to user activity, e.g., application switch, and even if that work isn't quite synchronous, every cycle the system spends on management overhead is a cycle it can't spend on rendering frames. Overhead means jank. Additionally, we're on battery-operated devices. Milliseconds of CPU overhead accumulated over a long time is a real energy sink.

Quoted 23 lines
Quoted 3 lines

Besides: process_vm_readv and process_vm_writev already work on address ranges. Why should other cross-process memory APIs use a very different model for naming memory regions?

I would consider those APIs not a great example. They are racy on more levels (pid reuse and address space modification), and require a non-trivial synchronization. Do you want something similar for madvise on a non-cooperating remote application?

Quoted 5 lines
Quoted 4 lines

be used to revalidate when the operation is requested and fail if something has changed. Moreover we already do have a fd based madvise syscall so there shouldn't be really a large need to add a new set of syscalls.

Quoted 8 lines

We have various system calls that provide hints for open files, but the memory operations are distinct. Modeling anonymous memory as a kind of file-backed memory for purposes of VMA manipulation would also be a departure from existing practice. Can you help me understand why you seem to favor the FD-per-VMA approach so heavily? I don't see any arguments *for* an FD-per-VMA model for remove memory manipulation and I see a lot of arguments against it. Is there some compelling advantage I'm missing?

Quoted 2 lines

First and foremost it provides an easy cookie to the userspace to guarantee time-to-check-time-to-use consistency.

But only for one VMA at a time.

Quoted 3 lines

It also naturally
extend an existing fadvise interface that achieves madvise semantic on files.

There are lots of things that madvise can do that fadvise can't and that don't even really make sense for fadvise, e.g., MADV_FREE. It seems odd to me to duplicate much of the madvise interface into fadvise so that we can use file APIs to give madvise hints. It seems simpler to me to just provide a mechanism to put the madvise hints where they're needed.

Quoted 2 lines

I am not really pushing hard for this particular API but I really do care about a programming model that would be sane.

You've used "sane" twice so far in this message. Can you specify more precisely what you mean by that word? I agree that there needs to be some defense against TOCTOU races when doing remote memory management, but I don't think providing this robustness via a file descriptor is any more sane than alternative approaches. A file descriptor comes with a lot of other features --- e.g., SCM_RIGHTS, fstat, and a concept of owning a resource --- that aren't needed to achieve robustness.

Normally, a file descriptor refers to some resource that the kernel holds as long as the file descriptor (well, the open file description or struct file) lives -- things like graphics buffers, files, and sockets. If we're using an FD *just* as a cookie and not a resource, I'd rather just expose the cookie directly.

Quoted 4 lines

If we have a
different means to achieve the same then all fine by me but so far I haven't heard any sound arguments to invent something completely new when we have established APIs to use.

Doesn't the next sentence describe something profoundly new? :-)

Quoted 3 lines

Exporting anonymous mappings via
proc the same way we do for file mappings doesn't seem to be stepping outside of the current practice way too much.

It seems like a radical departure from existing practice to provide filesystem interfaces to anonymous memory regions, e.g., anon_vma. You've never been able to refer to those memory regions with file descriptors.

All I'm suggesting is that we take the existing madvise mechanism, make it work cross-process, and make it robust against TOCTOU problems, all one step at a time. Maybe my sense of API "size" is miscalibrated, but adding a new type of FD to refer to anonymous VMA regions feels like a bigger departure and so requires stronger justification, especially if the result of the FD approach is probably something less efficient than a cookie-based one.

Quoted 3 lines

and we should focus on discussing whether this is a
sane model. And I think it would be much better to discuss that under the respective patch which introduces that API rather than here.

I think it's important to discuss what that API should look like. :-)

reviewer
#78 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 1 line · Daniel Colascione

On Tue, May 28, 2019 at 4:49 AM Michal Hocko <[email protected]> wrote:

[...]

Quoted 9 lines
Quoted 9 lines
Quoted 8 lines

We have various system calls that provide hints for open files, but the memory operations are distinct. Modeling anonymous memory as a kind of file-backed memory for purposes of VMA manipulation would also be a departure from existing practice. Can you help me understand why you seem to favor the FD-per-VMA approach so heavily? I don't see any arguments *for* an FD-per-VMA model for remove memory manipulation and I see a lot of arguments against it. Is there some compelling advantage I'm missing?

Quoted 4 lines
Quoted 2 lines

First and foremost it provides an easy cookie to the userspace to guarantee time-to-check-time-to-use consistency.

But only for one VMA at a time.

Which is the unit we operate on, right?

Quoted 10 lines
Quoted 3 lines

It also naturally
extend an existing fadvise interface that achieves madvise semantic on files.

There are lots of things that madvise can do that fadvise can't and that don't even really make sense for fadvise, e.g., MADV_FREE. It seems odd to me to duplicate much of the madvise interface into fadvise so that we can use file APIs to give madvise hints. It seems simpler to me to just provide a mechanism to put the madvise hints where they're needed.

I do not see why we would duplicate. I confess I haven't tried to implement this so I might be overlooking something but it seems to me that we could simply reuse the same functionality from both APIs.

Quoted 5 lines
Quoted 2 lines

I am not really pushing hard for this particular API but I really do care about a programming model that would be sane.

You've used "sane" twice so far in this message. Can you specify more precisely what you mean by that word?

Well, I would consider a model which would prevent from unintended side effects (e.g. working on a completely different object) without a tricky synchronization sane.

Quoted 8 lines

I agree that there needs to be
some defense against TOCTOU races when doing remote memory management, but I don't think providing this robustness via a file descriptor is any more sane than alternative approaches. A file descriptor comes with a lot of other features --- e.g., SCM_RIGHTS, fstat, and a concept of owning a resource --- that aren't needed to achieve robustness.

Quoted 5 lines

Normally, a file descriptor refers to some resource that the kernel holds as long as the file descriptor (well, the open file description or struct file) lives -- things like graphics buffers, files, and sockets. If we're using an FD *just* as a cookie and not a resource, I'd rather just expose the cookie directly.

You are absolutely right. But doesn't that apply to any other revalidation method that would be tracking VMA status as well. As I've said I am not married to this approach as long as there are better alternatives. So far we are in a discussion what should be the actual semantic of the operation and how much do we want to tolerate races. And it seems that we are diving into implementation details rather than landing with a firm decision that the current proposed API is suitable or not.

Quoted 16 lines
Quoted 4 lines

If we have a
different means to achieve the same then all fine by me but so far I haven't heard any sound arguments to invent something completely new when we have established APIs to use.

Doesn't the next sentence describe something profoundly new? :-)

Quoted 3 lines

Exporting anonymous mappings via
proc the same way we do for file mappings doesn't seem to be stepping outside of the current practice way too much.

It seems like a radical departure from existing practice to provide filesystem interfaces to anonymous memory regions, e.g., anon_vma. You've never been able to refer to those memory regions with file descriptors.

Quoted 7 lines

All I'm suggesting is that we take the existing madvise mechanism, make it work cross-process, and make it robust against TOCTOU problems, all one step at a time. Maybe my sense of API "size" is miscalibrated, but adding a new type of FD to refer to anonymous VMA regions feels like a bigger departure and so requires stronger justification, especially if the result of the FD approach is probably something less efficient than a cookie-based one.

Feel free to propose the way to achieve that in the respective email thread.

Quoted 5 lines
Quoted 3 lines

and we should focus on discussing whether this is a
sane model. And I think it would be much better to discuss that under the respective patch which introduces that API rather than here.

I think it's important to discuss what that API should look like. :-)

It will be fun to follow this discussion and make some sense of different parallel threads.

Signature · 2 lines
Michal Hocko
SUSE Labs
#79 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

In reply to Michal Hocko
Quoted 18 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 15 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 8 lines
Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

With current usecase, it's per-process API with distinguishable anon/file but thought it could be easily extended later for each address range operation as userspace getting smarter with more information.

reviewer
#80 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 28 lines · Minchan Kim
Quoted 18 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 15 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 8 lines
Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

Quoted 3 lines

With current usecase, it's per-process API with distinguishable anon/file but thought it could be easily extended later for each address range operation as userspace getting smarter with more information.

Never design user API based on a single usecase, please. The "easily extended" part is by far not clear to me TBH. As I've already mentioned several times, the synchronization model has to be thought through carefuly before a remote process address range operation can be implemented.

Signature · 2 lines
Michal Hocko
SUSE Labs
#81 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 33 lines · Michal Hocko
Quoted 28 lines · Minchan Kim
Quoted 18 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 15 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 8 lines
Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

Quoted 3 lines

With current usecase, it's per-process API with distinguishable anon/file but thought it could be easily extended later for each address range operation as userspace getting smarter with more information.

Quoted 5 lines

Never design user API based on a single usecase, please. The "easily extended" part is by far not clear to me TBH. As I've already mentioned several times, the synchronization model has to be thought through carefuly before a remote process address range operation can be implemented.

I agree with you that we shouldn't design API on single usecase but what you are concerning is actually not our usecase because we are resilient with the race since MADV_COLD|PAGEOUT is not destruptive. Actually, many hints are already racy in that the upcoming pattern would be different with the behavior you thought at the moment.

If you are still concerning of address range synchronization, how about moving such hints to per-process level like prctl?
Does it make sense to you?

reviewer
#82 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 40 lines · Minchan Kim
Quoted 33 lines · Michal Hocko
Quoted 28 lines · Minchan Kim
Quoted 18 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 15 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 8 lines
Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

Quoted 3 lines

With current usecase, it's per-process API with distinguishable anon/file but thought it could be easily extended later for each address range operation as userspace getting smarter with more information.

Quoted 5 lines

Never design user API based on a single usecase, please. The "easily extended" part is by far not clear to me TBH. As I've already mentioned several times, the synchronization model has to be thought through carefuly before a remote process address range operation can be implemented.

Quoted 5 lines

I agree with you that we shouldn't design API on single usecase but what you are concerning is actually not our usecase because we are resilient with the race since MADV_COLD|PAGEOUT is not destruptive. Actually, many hints are already racy in that the upcoming pattern would be different with the behavior you thought at the moment.

How come they are racy wrt address ranges? You would have to be in multithreaded environment and then the onus of synchronization is on threads. That model is quite clear. But we are talking about separate processes and some of them might be even not aware of an external entity tweaking their address space.

Quoted 3 lines

If you are still concerning of address range synchronization, how about moving such hints to per-process level like prctl?
Does it make sense to you?

No it doesn't. How is prctl any relevant to any address range operations.

Signature · 2 lines
Michal Hocko
SUSE Labs
#83 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 48 lines · Michal Hocko
Quoted 40 lines · Minchan Kim
Quoted 33 lines · Michal Hocko
Quoted 28 lines · Minchan Kim
Quoted 18 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 15 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 8 lines
Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

Quoted 3 lines

With current usecase, it's per-process API with distinguishable anon/file but thought it could be easily extended later for each address range operation as userspace getting smarter with more information.

Quoted 5 lines

Never design user API based on a single usecase, please. The "easily extended" part is by far not clear to me TBH. As I've already mentioned several times, the synchronization model has to be thought through carefuly before a remote process address range operation can be implemented.

Quoted 5 lines

I agree with you that we shouldn't design API on single usecase but what you are concerning is actually not our usecase because we are resilient with the race since MADV_COLD|PAGEOUT is not destruptive. Actually, many hints are already racy in that the upcoming pattern would be different with the behavior you thought at the moment.

Quoted 5 lines

How come they are racy wrt address ranges? You would have to be in multithreaded environment and then the onus of synchronization is on threads. That model is quite clear. But we are talking about separate processes and some of them might be even not aware of an external entity tweaking their address space.

I don't think the difference between a thread and a process matters in this context. Threads race on address space operations all the time --- in the sense that multiple threads modify a process's address space without synchronization. The main reasons that these races hasn't been a problem are: 1) threads mostly "mind their own business" and modify different parts of the address space or use locks to ensure that they don't stop on each other (e.g., the malloc heap lock), and
2) POSIX mmap atomic-replacement semantics make certain classes of operation (like "magic ring buffer" setup) safe even in the presence of other threads stomping over an address space.

The thing that's new in this discussion from a synchronization point of view isn't that the VM operation we're talking about is coming from outside the process, but that we want to do a read-decide-modify-ish thing. We want to affect (using various hints) classes of pages like "all file pages" or "all anonymous pages" or "some pages referring to graphics buffers up to 100MB" (to pick an example off the top of my head of a policy that might make sense). From a synchronization point of view, it doesn't really matter whether it's a thread within the target process or a thread outside the target process that does the address space manipulation. What's new is the inspection of the address space before performing an operation.

Minchan started this thread by proposing some flags that would implement a few of the filtering policies I used as examples above. Personally, instead of providing a few pre-built policies as flags, I'd rather push the page manipulation policy to userspace as much as possible and just have the kernel provide a mechanism that *in general* makes these read-decide-modify operations efficient and robust. I still think there's way to achieve this goal very inexpensively without compromising on flexibility.

reviewer
#84 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 55 lines · Daniel Colascione
Quoted 48 lines · Michal Hocko
Quoted 40 lines · Minchan Kim
Quoted 33 lines · Michal Hocko
Quoted 28 lines · Minchan Kim
Quoted 18 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 15 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 8 lines
Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

Quoted 3 lines

With current usecase, it's per-process API with distinguishable anon/file but thought it could be easily extended later for each address range operation as userspace getting smarter with more information.

Quoted 5 lines

Never design user API based on a single usecase, please. The "easily extended" part is by far not clear to me TBH. As I've already mentioned several times, the synchronization model has to be thought through carefuly before a remote process address range operation can be implemented.

Quoted 5 lines

I agree with you that we shouldn't design API on single usecase but what you are concerning is actually not our usecase because we are resilient with the race since MADV_COLD|PAGEOUT is not destruptive. Actually, many hints are already racy in that the upcoming pattern would be different with the behavior you thought at the moment.

Quoted 5 lines

How come they are racy wrt address ranges? You would have to be in multithreaded environment and then the onus of synchronization is on threads. That model is quite clear. But we are talking about separate processes and some of them might be even not aware of an external entity tweaking their address space.

Quoted 4 lines

I don't think the difference between a thread and a process matters in this context. Threads race on address space operations all the time --- in the sense that multiple threads modify a process's address space without synchronization.

I would disagree. They do have in-kernel synchronization as long as they do not use MAP_FIXED. If they do want to use MAP_FIXED then they better synchronize or the result is undefined.

Quoted 7 lines

The main reasons that these races
hasn't been a problem are: 1) threads mostly "mind their own business" and modify different parts of the address space or use locks to ensure that they don't stop on each other (e.g., the malloc heap lock), and
2) POSIX mmap atomic-replacement semantics make certain classes of operation (like "magic ring buffer" setup) safe even in the presence of other threads stomping over an address space.

Agreed here.

[...]

Quoted 5 lines

From a synchronization point
of view, it doesn't really matter whether it's a thread within the target process or a thread outside the target process that does the address space manipulation. What's new is the inspection of the address space before performing an operation.

The fundamental difference is that if you want to achieve the same inside the process then your application is inherenly aware of the operation and use whatever synchronization is needed to achieve a consistency. As soon as you allow the same from outside you either have to have an aware target application as well or you need a mechanism to find out that your decision has been invalidated by a later unsynchronized action.

Quoted 8 lines

Minchan started this thread by proposing some flags that would implement a few of the filtering policies I used as examples above. Personally, instead of providing a few pre-built policies as flags, I'd rather push the page manipulation policy to userspace as much as possible and just have the kernel provide a mechanism that *in general* makes these read-decide-modify operations efficient and robust. I still think there's way to achieve this goal very inexpensively without compromising on flexibility.

Agreed here.

Signature · 2 lines
Michal Hocko
SUSE Labs
#85 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 57 lines · Michal Hocko
Quoted 55 lines · Daniel Colascione
Quoted 53 lines · Michal Hocko
Quoted 40 lines · Minchan Kim
Quoted 33 lines · Michal Hocko
Quoted 28 lines · Minchan Kim
Quoted 18 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 15 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 8 lines
Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

Quoted 3 lines

With current usecase, it's per-process API with distinguishable anon/file but thought it could be easily extended later for each address range operation as userspace getting smarter with more information.

Quoted 5 lines

Never design user API based on a single usecase, please. The "easily extended" part is by far not clear to me TBH. As I've already mentioned several times, the synchronization model has to be thought through carefuly before a remote process address range operation can be implemented.

Quoted 5 lines

I agree with you that we shouldn't design API on single usecase but what you are concerning is actually not our usecase because we are resilient with the race since MADV_COLD|PAGEOUT is not destruptive. Actually, many hints are already racy in that the upcoming pattern would be different with the behavior you thought at the moment.

How come they are racy wrt address ranges? You would have to be in multithreaded environment and then the onus of synchronization is on threads. That model is quite clear. But we are talking about separate processes and some of them might be even not aware of an external entity tweaking their address space.

Quoted 8 lines
Quoted 4 lines

I don't think the difference between a thread and a process matters in this context. Threads race on address space operations all the time --- in the sense that multiple threads modify a process's address space without synchronization.

I would disagree. They do have in-kernel synchronization as long as they do not use MAP_FIXED. If they do want to use MAP_FIXED then they better synchronize or the result is undefined.

Right. It's because the kernel hands off different regions to different non-MAP_FIXED mmap callers that it's pretty easy for threads to mind their own business, but they're all still using the same address space.

Quoted 6 lines
Quoted 5 lines

From a synchronization point
of view, it doesn't really matter whether it's a thread within the target process or a thread outside the target process that does the address space manipulation. What's new is the inspection of the address space before performing an operation.

Quoted 7 lines

The fundamental difference is that if you want to achieve the same inside the process then your application is inherenly aware of the operation and use whatever synchronization is needed to achieve a consistency. As soon as you allow the same from outside you either have to have an aware target application as well or you need a mechanism to find out that your decision has been invalidated by a later unsynchronized action.

I thought of this objection immediately after I hit send. :-)

I still don't think the intra- vs inter-process difference matters. It's true that threads can synchronize with each other, but different processes can synchronize with each other too. I mean, you *could* use sem_open(3) for your heap lock and open the semaphore from two different processes. That's silly, but it'd work.

The important requirement, I think, is that we need to support managing "memory-naive" uncooperative tasks (perhaps legacy ones written before cross-process memory management even became possible), and I think that the cooperative-vs-uncooperative distinction matters a lot more than the tgid of the thread doing the memory manipulation. (Although in our case, we really do need a separate tgid. :-))

reviewer
#86 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

On Tue 28-05-19 05:18:48, Daniel Colascione wrote:
[...]

Quoted 6 lines

The important requirement, I think, is that we need to support managing "memory-naive" uncooperative tasks (perhaps legacy ones written before cross-process memory management even became possible), and I think that the cooperative-vs-uncooperative distinction matters a lot more than the tgid of the thread doing the memory manipulation. (Although in our case, we really do need a separate tgid. :-))

Agreed here and that requires some sort of revalidation and failure on "object has changed" in one form or another IMHO.

Signature · 2 lines
Michal Hocko
SUSE Labs
#87 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

In reply to Daniel Colascione
Quoted 78 lines · Daniel Colascione
Quoted 48 lines · Michal Hocko
Quoted 40 lines · Minchan Kim
Quoted 33 lines · Michal Hocko
Quoted 28 lines · Minchan Kim
Quoted 18 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 15 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 8 lines
Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

Quoted 3 lines

With current usecase, it's per-process API with distinguishable anon/file but thought it could be easily extended later for each address range operation as userspace getting smarter with more information.

Quoted 5 lines

Never design user API based on a single usecase, please. The "easily extended" part is by far not clear to me TBH. As I've already mentioned several times, the synchronization model has to be thought through carefuly before a remote process address range operation can be implemented.

Quoted 5 lines

I agree with you that we shouldn't design API on single usecase but what you are concerning is actually not our usecase because we are resilient with the race since MADV_COLD|PAGEOUT is not destruptive. Actually, many hints are already racy in that the upcoming pattern would be different with the behavior you thought at the moment.

Quoted 5 lines

How come they are racy wrt address ranges? You would have to be in multithreaded environment and then the onus of synchronization is on threads. That model is quite clear. But we are talking about separate processes and some of them might be even not aware of an external entity tweaking their address space.

I don't think the difference between a thread and a process matters in this context. Threads race on address space operations all the time --- in the sense that multiple threads modify a process's address space without synchronization. The main reasons that these races hasn't been a problem are: 1) threads mostly "mind their own business" and modify different parts of the address space or use locks to ensure that they don't stop on each other (e.g., the malloc heap lock), and
2) POSIX mmap atomic-replacement semantics make certain classes of operation (like "magic ring buffer" setup) safe even in the presence of other threads stomping over an address space.

The thing that's new in this discussion from a synchronization point of view isn't that the VM operation we're talking about is coming from outside the process, but that we want to do a read-decide-modify-ish thing. We want to affect (using various hints) classes of pages like "all file pages" or "all anonymous pages" or "some pages referring to graphics buffers up to 100MB" (to pick an example off the top of my head of a policy that might make sense). From a synchronization point of view, it doesn't really matter whether it's a thread within the target process or a thread outside the target process that does the address space manipulation. What's new is the inspection of the address space before performing an operation.

Quoted 8 lines

Minchan started this thread by proposing some flags that would implement a few of the filtering policies I used as examples above. Personally, instead of providing a few pre-built policies as flags, I'd rather push the page manipulation policy to userspace as much as possible and just have the kernel provide a mechanism that *in general* makes these read-decide-modify operations efficient and robust. I still think there's way to achieve this goal very inexpensively without compromising on flexibility.

I'm looking forward to seeing the way. ;-)

#88 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

In reply to Michal Hocko
Quoted 47 lines · Michal Hocko
Quoted 40 lines · Minchan Kim
Quoted 33 lines · Michal Hocko
Quoted 28 lines · Minchan Kim
Quoted 18 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 15 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 8 lines
Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

Quoted 3 lines

With current usecase, it's per-process API with distinguishable anon/file but thought it could be easily extended later for each address range operation as userspace getting smarter with more information.

Quoted 5 lines

Never design user API based on a single usecase, please. The "easily extended" part is by far not clear to me TBH. As I've already mentioned several times, the synchronization model has to be thought through carefuly before a remote process address range operation can be implemented.

Quoted 5 lines

I agree with you that we shouldn't design API on single usecase but what you are concerning is actually not our usecase because we are resilient with the race since MADV_COLD|PAGEOUT is not destruptive. Actually, many hints are already racy in that the upcoming pattern would be different with the behavior you thought at the moment.

Quoted 3 lines

How come they are racy wrt address ranges? You would have to be in multithreaded environment and then the onus of synchronization is on threads. That model is quite clear. But we are talking about separate

Think about MADV_FREE. Allocator would think the chunk is worth to mark "freeable" but soon, user of the allocator asked the chunk - ie, it's not freeable any longer once user start to use it.

My point is that kinds of *hints* are always racy so any synchronization couldn't help a lot. That's why I want to restrict hints process_madvise supports as such kinds of non-destruptive one at next respin.

Quoted 9 lines

processes and some of them might be even not aware of an external entity tweaking their address space.

Quoted 3 lines

If you are still concerning of address range synchronization, how about moving such hints to per-process level like prctl?
Does it make sense to you?

No it doesn't. How is prctl any relevant to any address range operations.

"whether we want to have the remote madvise call process or vma fd based."

You asked the above question and I answered we are using process level hints but anon/vma filter at this moment. That's why I told you prctl to make forward progress on discussion.

#89 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 53 lines · Minchan Kim
Quoted 47 lines · Michal Hocko
Quoted 40 lines · Minchan Kim
Quoted 33 lines · Michal Hocko
Quoted 28 lines · Minchan Kim
Quoted 18 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 15 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 8 lines
Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

Quoted 3 lines

With current usecase, it's per-process API with distinguishable anon/file but thought it could be easily extended later for each address range operation as userspace getting smarter with more information.

Quoted 5 lines

Never design user API based on a single usecase, please. The "easily extended" part is by far not clear to me TBH. As I've already mentioned several times, the synchronization model has to be thought through carefuly before a remote process address range operation can be implemented.

Quoted 5 lines

I agree with you that we shouldn't design API on single usecase but what you are concerning is actually not our usecase because we are resilient with the race since MADV_COLD|PAGEOUT is not destruptive. Actually, many hints are already racy in that the upcoming pattern would be different with the behavior you thought at the moment.

Quoted 3 lines

How come they are racy wrt address ranges? You would have to be in multithreaded environment and then the onus of synchronization is on threads. That model is quite clear. But we are talking about separate

Quoted 7 lines

Think about MADV_FREE. Allocator would think the chunk is worth to mark "freeable" but soon, user of the allocator asked the chunk - ie, it's not freeable any longer once user start to use it.

My point is that kinds of *hints* are always racy so any synchronization couldn't help a lot. That's why I want to restrict hints process_madvise supports as such kinds of non-destruptive one at next respin.

I think it's more natural for process_madvise to be a superset of regular madvise. What's the harm? There are no security implications, since anyone who could process_madvise could just ptrace anyway. I also don't think limiting the hinting to non-destructive operations guarantees safety (in a broad sense) either, since operating on the wrong memory range can still cause unexpected system performance issues even if there's no data loss.

More broadly, what I want to see is a family of process_* APIs that provide a superset of the functionality that the existing intraprocess APIs provide. I think this approach is elegant and generalizes easily. I'm worried about prematurely limiting the interprocess memory APIs and creating limitations that will last a long time in order to avoid having to consider issues like VMA synchronization.

reviewer
#90 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

In reply to Minchan Kim
Quoted 48 lines · Minchan Kim
Quoted 47 lines · Michal Hocko
Quoted 45 lines · Minchan Kim
Quoted 33 lines · Michal Hocko
Quoted 28 lines · Minchan Kim
Quoted 18 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 15 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 8 lines
Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

Quoted 3 lines

With current usecase, it's per-process API with distinguishable anon/file but thought it could be easily extended later for each address range operation as userspace getting smarter with more information.

Quoted 5 lines

Never design user API based on a single usecase, please. The "easily extended" part is by far not clear to me TBH. As I've already mentioned several times, the synchronization model has to be thought through carefuly before a remote process address range operation can be implemented.

I agree with you that we shouldn't design API on single usecase but what you are concerning is actually not our usecase because we are resilient with the race since MADV_COLD|PAGEOUT is not destruptive. Actually, many hints are already racy in that the upcoming pattern would be different with the behavior you thought at the moment.

Quoted 7 lines
Quoted 3 lines

How come they are racy wrt address ranges? You would have to be in multithreaded environment and then the onus of synchronization is on threads. That model is quite clear. But we are talking about separate

Think about MADV_FREE. Allocator would think the chunk is worth to mark "freeable" but soon, user of the allocator asked the chunk - ie, it's not freeable any longer once user start to use it.

That is not a race in the address space, right. The underlying object hasn't changed. It has been declared as freeable and since that moment nobody can rely on the content because it might have been discarded. Or put simply, the content is undefined. It is responsibility of the madvise caller to make sure that the object is not in active use while it is marking it.

Quoted 3 lines

My point is that kinds of *hints* are always racy so any synchronization couldn't help a lot. That's why I want to restrict hints process_madvise supports as such kinds of non-destruptive one at next respin.

I agree that a non-destructive operations are safer against paralel modifications because you just get a annoying and unexpected latency at worst case. But we should discuss whether this assumption is sufficient for further development. I am pretty sure once we open remote madvise people will find usecases for destructive operations or even new madvise modes we haven't heard of. What then?

Quoted 11 lines
Quoted 9 lines

processes and some of them might be even not aware of an external entity tweaking their address space.

Quoted 3 lines

If you are still concerning of address range synchronization, how about moving such hints to per-process level like prctl?
Does it make sense to you?

No it doesn't. How is prctl any relevant to any address range operations.

"whether we want to have the remote madvise call process or vma fd based."

Still not following. So you want to have a prctl (one of the worst API we have along with ioctl) to tell the semantic? This sounds like a terrible idea to me.

Signature · 2 lines
Michal Hocko
SUSE Labs
#91 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 68 lines · Michal Hocko
Quoted 48 lines · Minchan Kim
Quoted 47 lines · Michal Hocko
Quoted 45 lines · Minchan Kim
Quoted 33 lines · Michal Hocko
Quoted 28 lines · Minchan Kim
Quoted 18 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 15 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 8 lines
Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

Quoted 3 lines

With current usecase, it's per-process API with distinguishable anon/file but thought it could be easily extended later for each address range operation as userspace getting smarter with more information.

Quoted 5 lines

Never design user API based on a single usecase, please. The "easily extended" part is by far not clear to me TBH. As I've already mentioned several times, the synchronization model has to be thought through carefuly before a remote process address range operation can be implemented.

I agree with you that we shouldn't design API on single usecase but what you are concerning is actually not our usecase because we are resilient with the race since MADV_COLD|PAGEOUT is not destruptive. Actually, many hints are already racy in that the upcoming pattern would be different with the behavior you thought at the moment.

Quoted 7 lines
Quoted 3 lines

How come they are racy wrt address ranges? You would have to be in multithreaded environment and then the onus of synchronization is on threads. That model is quite clear. But we are talking about separate

Think about MADV_FREE. Allocator would think the chunk is worth to mark "freeable" but soon, user of the allocator asked the chunk - ie, it's not freeable any longer once user start to use it.

That is not a race in the address space, right. The underlying object hasn't changed. It has been declared as freeable and since that moment nobody can rely on the content because it might have been discarded. Or put simply, the content is undefined. It is responsibility of the madvise caller to make sure that the object is not in active use while it is marking it.

Quoted 3 lines

My point is that kinds of *hints* are always racy so any synchronization couldn't help a lot. That's why I want to restrict hints process_madvise supports as such kinds of non-destruptive one at next respin.

Quoted 6 lines

I agree that a non-destructive operations are safer against paralel modifications because you just get a annoying and unexpected latency at worst case. But we should discuss whether this assumption is sufficient for further development. I am pretty sure once we open remote madvise people will find usecases for destructive operations or even new madvise modes we haven't heard of. What then?

I support Daniel's vma seq number approach for the future plan.

#92 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

In reply to Michal Hocko
Quoted 34 lines · Michal Hocko
Quoted 28 lines · Minchan Kim
Quoted 18 lines · Michal Hocko
Quoted 17 lines · Minchan Kim
Quoted 15 lines · Daniel Colascione
Quoted 6 lines · Minchan Kim

if we went with the per vma fd approach then you would get this

Quoted 2 lines

feature automatically because map_files would refer to file backed mappings while map_anon could refer only to anonymous mappings.

The reason to add such filter option is to avoid the parsing overhead so map_anon wouldn't be helpful.

Without chiming on whether the filter option is a good idea, I'd like to suggest that providing an efficient binary interfaces for pulling memory map information out of processes. Some single-system-call method for retrieving a binary snapshot of a process's address space complete with attributes (selectable, like statx?) for each VMA would reduce complexity and increase performance in a variety of areas, e.g., Android memory map debugging commands.

Quoted 8 lines
Quoted 2 lines

I agree it's the best we can get *generally*.
Michal, any opinion?

I am not really sure this is directly related. I think the primary question that we have to sort out first is whether we want to have the remote madvise call process or vma fd based. This is an important distinction wrt. usability. I have only seen pid vs. pidfd discussions so far unfortunately.

Quoted 3 lines

With current usecase, it's per-process API with distinguishable anon/file but thought it could be easily extended later for each address range operation as userspace getting smarter with more information.

Quoted 5 lines

Never design user API based on a single usecase, please. The "easily extended" part is by far not clear to me TBH. As I've already mentioned several times, the synchronization model has to be thought through carefuly before a remote process address range operation can be implemented.

I don't think anyone is overfitting for a specific use case. When some process A wants to manipulate process B's memory, it's fair for A to want to know what memory it's manipulating. That's a general concern that applies to a large family of cross-process memory operations. It's less important for non-destructive hints than for some kind of destructive operation, but the same idea applies. If there's a simple way to solve this A-B information problem in a general way, it seems to be that we should apply that general solution. Likewise, an API to get an efficiently-collected snapshot of a process's address space would be immediately useful in several very different use cases, including debuggers, Android memory use reporting tools, and various kinds of metric collection. Because we're talking about mechanisms that solve several independent problems at the same time and in a general way, it doesn't sound to me like overfitting for a particular use case.

maintainer
#93 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

In reply to Minchan Kim
Quoted 28 lines · Minchan Kim
Quoted 27 lines · Michal Hocko

[cc linux-api]

Quoted 8 lines · Minchan Kim

System could have much faster swap device like zRAM. In that case, swapping is extremely cheaper than file-IO on the low-end storage.
In this configuration, userspace could handle different strategy for each kinds of vma. IOW, they want to reclaim anonymous pages by MADV_COLD while it keeps file-backed pages in inactive LRU by MADV_COOL because file IO is more expensive in this case so want to keep them in memory until memory pressure happens.

Quoted 5 lines

To support such strategy easier, this patch introduces MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER options in madvise(2) like that /proc/<pid>/clear_refs already has supported same filters. They are filters could be Ored with other existing hints using top two bits of (int behavior).

madvise operates on top of ranges and it is quite trivial to do the filtering from the userspace so why do we need any additional filtering?

Quoted 6 lines

Once either of them is set, the hint could affect only the interested vma either anonymous or file-backed.

With that, user could call a process_madvise syscall simply with a entire range(0x0 - 0xFFFFFFFFFFFFFFFF) but either of MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER so there is no need to call the syscall range by range.

Quoted 8 lines
Quoted 4 lines

OK, so here is the reason you want that. The immediate question is why cannot the monitor do the filtering from the userspace. Slightly more work, all right, but less of an API to expose and that itself is a strong argument against.

What I should do if we don't have such filter option is to enumerate all of vma via /proc/<pid>/maps and then parse every ranges and inode from string, which would be painful for 2000+ vmas.

Just out of curiosity, how do you get to 2000+ distinct memory regions in the address space of a mobile app? I'm assuming these aren't files, but rather anon objects with poor grouping. Is that from guard pages between individual heap allocations or something?

#94 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 34 lines · Johannes Weiner
Quoted 33 lines · Minchan Kim
Quoted 31 lines · Michal Hocko

[cc linux-api]

Quoted 8 lines · Minchan Kim

System could have much faster swap device like zRAM. In that case, swapping is extremely cheaper than file-IO on the low-end storage.
In this configuration, userspace could handle different strategy for each kinds of vma. IOW, they want to reclaim anonymous pages by MADV_COLD while it keeps file-backed pages in inactive LRU by MADV_COOL because file IO is more expensive in this case so want to keep them in memory until memory pressure happens.

Quoted 5 lines

To support such strategy easier, this patch introduces MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER options in madvise(2) like that /proc/<pid>/clear_refs already has supported same filters. They are filters could be Ored with other existing hints using top two bits of (int behavior).

madvise operates on top of ranges and it is quite trivial to do the filtering from the userspace so why do we need any additional filtering?

Quoted 6 lines

Once either of them is set, the hint could affect only the interested vma either anonymous or file-backed.

With that, user could call a process_madvise syscall simply with a entire range(0x0 - 0xFFFFFFFFFFFFFFFF) but either of MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER so there is no need to call the syscall range by range.

OK, so here is the reason you want that. The immediate question is why cannot the monitor do the filtering from the userspace. Slightly more work, all right, but less of an API to expose and that itself is a strong argument against.

Quoted 8 lines
Quoted 3 lines

What I should do if we don't have such filter option is to enumerate all of vma via /proc/<pid>/maps and then parse every ranges and inode from string, which would be painful for 2000+ vmas.

Just out of curiosity, how do you get to 2000+ distinct memory regions in the address space of a mobile app? I'm assuming these aren't files, but rather anon objects with poor grouping. Is that from guard pages between individual heap allocations or something?

Android uses preload library model to speed up app launch so it loads all of library in advance on zygote and forks new app based on it.

#95 lore raw

Re: [RFC 7/7] mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

In reply to Minchan Kim
Quoted 10 lines · Hillf Danton
Quoted 5 lines · On Mon, 20 May 2019 12:52:54 +0900 Minchan Kim wrote:

With that, user could call a process_madvise syscall simply with a entire range(0x0 - 0xFFFFFFFFFFFFFFFF) but either of MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER so there is no need to call the syscall range by range.

Cool.

Look forward to seeing the non-RFC delivery.

I will drop this filter patch if userspace can parse address range fast. Daniel suggested a new interface which could get necessary information from the process with binary format so will it will remove endoce/decode overhead as well as overhead we don't need to get like directory look up.

Yes, with this filter option, it's best performance for a specific usecase but sometime we need to give up *best* thing for *general* stuff. I belive it's one of the category. ;-)

#96 lore raw
In reply to Minchan Kim
Quoted 12 lines · Minchan Kim

- Problem

Naturally, cached apps were dominant consumers of memory on the system. However, they were not significant consumers of swap even though they are good candidate for swap. Under investigation, swapping out only begins once the low zone watermark is hit and kswapd wakes up, but the overall allocation rate in the system might trip lmkd thresholds and cause a cached process to be killed(we measured performance swapping out vs. zapping the memory by killing a process. Unsurprisingly, zapping is 10x times faster even though we use zram which is much faster than real storage) so kill from lmkd will often satisfy the high zone watermark, resulting in very few pages actually being moved to swap.

Getting killed by lmkd which is triggered by custom system memory allocation parameters and hence not being able to swap out is a problem ? But is not the problem created by lmkd itself.

Or Is the objective here is reduce the number of processes which get killed by lmkd by triggering swapping for the unused memory (user hinted) sooner so that they dont get picked by lmkd. Under utilization for zram hardware is a concern here as well ?

Swapping out memory into zram wont increase the latency for a hot start ? Or is it because as it will prevent a fresh cold start which anyway will be slower than a slow hot start. Just being curious.

#97 lore raw
Quoted 5 lines · Anshuman Khandual

Or Is the objective here is reduce the number of processes which get killed by lmkd by triggering swapping for the unused memory (user hinted) sooner so that they dont get picked by lmkd. Under utilization for zram hardware is a concern here as well ?

The objective is to avoid some instances of memory pressure by proactively swapping pages that userspace knows to be cold before those pages reach the end of the LRUs, which in turn can prevent some apps from being killed by lmk/lmkd. As soon as Android userspace knows that an application is not being used and is only resident to improve performance if the user returns to that app, we can kick off process_madvise on that process's pages (or some portion of those pages) in a power-efficient way to reduce memory pressure long before the system hits the free page watermark. This allows the system more time to put pages into zram versus waiting for the watermark to trigger kswapd, which decreases the likelihood that later memory allocations will cause enough pressure to trigger a kill of one of these apps.

Quoted 3 lines

Swapping out memory into zram wont increase the latency for a hot start ? Or is it because as it will prevent a fresh cold start which anyway will be slower than a slow hot start. Just being curious.

First, not all swapped pages will be reloaded immediately once an app is resumed. We've found that an app's working set post-process_madvise is significantly smaller than what an app allocates when it first launches (see the delta between pswpin and pswpout in Minchan's results). Presumably because of this, faulting to fetch from zram does not seem to introduce a noticeable hot start penalty, not does it cause an increase in performance problems later in the app's lifecycle. I've measured with and without process_madvise, and the differences are within our noise bounds. Second, because we're not preemptively evicting file pages and only making them more likely to be evicted when there's already memory pressure, we avoid the case where we process_madvise an app then immediately return to the app and reload all file pages in the working set even though there was no intervening memory pressure. Our initial version of this work evicted file pages preemptively and did cause a noticeable slowdown (~15%) for that case; this patch set avoids that slowdown. Finally, the benefit from avoiding cold starts is huge. The performance improvement from having a hot start instead of a cold start ranges from 3x for very small apps to 50x+ for larger apps like high-fidelity games.

#98 lore raw
Quoted 8 lines · Tim Murray
Quoted 5 lines · Anshuman Khandual

Or Is the objective here is reduce the number of processes which get killed by lmkd by triggering swapping for the unused memory (user hinted) sooner so that they dont get picked by lmkd. Under utilization for zram hardware is a concern here as well ?

Quoted 13 lines

The objective is to avoid some instances of memory pressure by proactively swapping pages that userspace knows to be cold before those pages reach the end of the LRUs, which in turn can prevent some apps from being killed by lmk/lmkd. As soon as Android userspace knows that an application is not being used and is only resident to improve performance if the user returns to that app, we can kick off process_madvise on that process's pages (or some portion of those pages) in a power-efficient way to reduce memory pressure long before the system hits the free page watermark. This allows the system more time to put pages into zram versus waiting for the watermark to trigger kswapd, which decreases the likelihood that later memory allocations will cause enough pressure to trigger a kill of one of these apps.

So this opens up bit of LRU management to user space hints. Also because the app in itself wont know about the memory situation of the entire system, new system call needs to be called from an external process.

Quoted 10 lines
Quoted 4 lines

Swapping out memory into zram wont increase the latency for a hot start ? Or is it because as it will prevent a fresh cold start which anyway will be slower than a slow hot start. Just being curious.

First, not all swapped pages will be reloaded immediately once an app is resumed. We've found that an app's working set post-process_madvise is significantly smaller than what an app allocates when it first launches (see the delta between pswpin and pswpout in Minchan's results). Presumably because of this, faulting to fetch from zram does

pswpin      417613    1392647     975034     233.00
pswpout    1274224    2661731    1387507     108.00

IIUC the swap-in ratio is way higher in comparison to that of swap out. Is that always the case ? Or it tend to swap out from an active area of the working set which faulted back again.

Quoted 4 lines

not seem to introduce a noticeable hot start penalty, not does it cause an increase in performance problems later in the app's lifecycle. I've measured with and without process_madvise, and the differences are within our noise bounds. Second, because we're not

That is assuming that post process_madvise() working set for the application is always smaller. There is another challenge. The external process should ideally have the knowledge of active areas of the working set for an application in question for it to invoke process_madvise() correctly to prevent such scenarios.

Quoted 5 lines

preemptively evicting file pages and only making them more likely to be evicted when there's already memory pressure, we avoid the case where we process_madvise an app then immediately return to the app and reload all file pages in the working set even though there was no intervening memory pressure. Our initial version of this work evicted

That would be the worst case scenario which should be avoided. Memory pressure must be a parameter before actually doing the swap out. But pages if know to be inactive/cold can be marked high priority to be swapped out.

Quoted 5 lines

file pages preemptively and did cause a noticeable slowdown (~15%) for that case; this patch set avoids that slowdown. Finally, the benefit from avoiding cold starts is huge. The performance improvement from having a hot start instead of a cold start ranges from 3x for very small apps to 50x+ for larger apps like high-fidelity games.

Is there any other real world scenario apart from this app based ecosystem where user hinted LRU management might be helpful ? Just being curious. Thanks for the detailed explanation. I will continue looking into this series.

#99 lore raw
Quoted 25 lines · Anshuman Khandual
Quoted 8 lines · Tim Murray
Quoted 5 lines · Anshuman Khandual

Or Is the objective here is reduce the number of processes which get killed by lmkd by triggering swapping for the unused memory (user hinted) sooner so that they dont get picked by lmkd. Under utilization for zram hardware is a concern here as well ?

Quoted 13 lines

The objective is to avoid some instances of memory pressure by proactively swapping pages that userspace knows to be cold before those pages reach the end of the LRUs, which in turn can prevent some apps from being killed by lmk/lmkd. As soon as Android userspace knows that an application is not being used and is only resident to improve performance if the user returns to that app, we can kick off process_madvise on that process's pages (or some portion of those pages) in a power-efficient way to reduce memory pressure long before the system hits the free page watermark. This allows the system more time to put pages into zram versus waiting for the watermark to trigger kswapd, which decreases the likelihood that later memory allocations will cause enough pressure to trigger a kill of one of these apps.

Quoted 3 lines

So this opens up bit of LRU management to user space hints. Also because the app in itself wont know about the memory situation of the entire system, new system call needs to be called from an external process.

That's why process_madvise is introduced here.

Quoted 12 lines
Quoted 11 lines
Quoted 5 lines

Swapping out memory into zram wont increase the latency for a hot start ? Or is it because as it will prevent a fresh cold start which anyway will be slower than a slow hot start. Just being curious.

First, not all swapped pages will be reloaded immediately once an app is resumed. We've found that an app's working set post-process_madvise is significantly smaller than what an app allocates when it first launches (see the delta between pswpin and pswpout in Minchan's results). Presumably because of this, faulting to fetch from zram does

Quoted 6 lines
pswpin      417613    1392647     975034     233.00
pswpout    1274224    2661731    1387507     108.00

IIUC the swap-in ratio is way higher in comparison to that of swap out. Is that always the case ? Or it tend to swap out from an active area of the working set which faulted back again.

I think it's because apps are alive longer via reducing being killed so turn into from pgpgin to swapin.

Quoted 10 lines
Quoted 5 lines

not seem to introduce a noticeable hot start penalty, not does it cause an increase in performance problems later in the app's lifecycle. I've measured with and without process_madvise, and the differences are within our noise bounds. Second, because we're not

That is assuming that post process_madvise() working set for the application is always smaller. There is another challenge. The external process should ideally have the knowledge of active areas of the working set for an application in question for it to invoke process_madvise() correctly to prevent such scenarios.

There are several ways to detect workingset more accurately at the cost of runtime. For example, with idle page tracking or clear_refs. Accuracy is always trade-off of overhead for LRU aging.

Quoted 20 lines
Quoted 6 lines

preemptively evicting file pages and only making them more likely to be evicted when there's already memory pressure, we avoid the case where we process_madvise an app then immediately return to the app and reload all file pages in the working set even though there was no intervening memory pressure. Our initial version of this work evicted

That would be the worst case scenario which should be avoided. Memory pressure must be a parameter before actually doing the swap out. But pages if know to be inactive/cold can be marked high priority to be swapped out.

Quoted 5 lines

file pages preemptively and did cause a noticeable slowdown (~15%) for that case; this patch set avoids that slowdown. Finally, the benefit from avoiding cold starts is huge. The performance improvement from having a hot start instead of a cold start ranges from 3x for very small apps to 50x+ for larger apps like high-fidelity games.

Is there any other real world scenario apart from this app based ecosystem where user hinted LRU management might be helpful ? Just being curious. Thanks for the detailed explanation. I will continue looking into this series.

reviewer
#100 lore raw
In reply to Anshuman Khandual
Quoted 1 line · Anshuman Khandual

On 05/20/2019 10:29 PM, Tim Murray wrote:

[...]

Quoted 9 lines
Quoted 4 lines

not seem to introduce a noticeable hot start penalty, not does it cause an increase in performance problems later in the app's lifecycle. I've measured with and without process_madvise, and the differences are within our noise bounds. Second, because we're not

That is assuming that post process_madvise() working set for the application is always smaller. There is another challenge. The external process should ideally have the knowledge of active areas of the working set for an application in question for it to invoke process_madvise() correctly to prevent such scenarios.

But that doesn't really seem relevant for the API itself, right? The higher level logic the monitor's business.

Signature · 2 lines
Michal Hocko
SUSE Labs
#101 lore raw
Quoted 8 lines · Michal Hocko
Quoted 1 line · Anshuman Khandual

On 05/20/2019 10:29 PM, Tim Murray wrote:

[...]

Quoted 5 lines
Quoted 4 lines

not seem to introduce a noticeable hot start penalty, not does it cause an increase in performance problems later in the app's lifecycle. I've measured with and without process_madvise, and the differences are within our noise bounds. Second, because we're not

Quoted 7 lines
Quoted 4 lines

That is assuming that post process_madvise() working set for the application is always smaller. There is another challenge. The external process should ideally have the knowledge of active areas of the working set for an application in question for it to invoke process_madvise() correctly to prevent such scenarios.

But that doesn't really seem relevant for the API itself, right? The higher level logic the monitor's business.

Right. I was just wondering how the monitor would even decide what areas of the target application is active or inactive. The target application is still just an opaque entity for the monitor unless there is some sort of communication. But you are right, this not relevant to the API itself.

#102 lore raw
In reply to Anshuman Khandual
Quoted 74 lines · Anshuman Khandual
Quoted 8 lines · Tim Murray
Quoted 5 lines · Anshuman Khandual

Or Is the objective here is reduce the number of processes which get killed by lmkd by triggering swapping for the unused memory (user hinted) sooner so that they dont get picked by lmkd. Under utilization for zram hardware is a concern here as well ?

Quoted 13 lines

The objective is to avoid some instances of memory pressure by proactively swapping pages that userspace knows to be cold before those pages reach the end of the LRUs, which in turn can prevent some apps from being killed by lmk/lmkd. As soon as Android userspace knows that an application is not being used and is only resident to improve performance if the user returns to that app, we can kick off process_madvise on that process's pages (or some portion of those pages) in a power-efficient way to reduce memory pressure long before the system hits the free page watermark. This allows the system more time to put pages into zram versus waiting for the watermark to trigger kswapd, which decreases the likelihood that later memory allocations will cause enough pressure to trigger a kill of one of these apps.

So this opens up bit of LRU management to user space hints. Also because the app in itself wont know about the memory situation of the entire system, new system call needs to be called from an external process.

Quoted 10 lines
Quoted 4 lines

Swapping out memory into zram wont increase the latency for a hot start ? Or is it because as it will prevent a fresh cold start which anyway will be slower than a slow hot start. Just being curious.

First, not all swapped pages will be reloaded immediately once an app is resumed. We've found that an app's working set post-process_madvise is significantly smaller than what an app allocates when it first launches (see the delta between pswpin and pswpout in Minchan's results). Presumably because of this, faulting to fetch from zram does

pswpin      417613    1392647     975034     233.00
pswpout    1274224    2661731    1387507     108.00

IIUC the swap-in ratio is way higher in comparison to that of swap out. Is that always the case ? Or it tend to swap out from an active area of the working set which faulted back again.

Quoted 4 lines

not seem to introduce a noticeable hot start penalty, not does it cause an increase in performance problems later in the app's lifecycle. I've measured with and without process_madvise, and the differences are within our noise bounds. Second, because we're not

That is assuming that post process_madvise() working set for the application is always smaller. There is another challenge. The external process should ideally have the knowledge of active areas of the working set for an application in question for it to invoke process_madvise() correctly to prevent such scenarios.

Quoted 5 lines

preemptively evicting file pages and only making them more likely to be evicted when there's already memory pressure, we avoid the case where we process_madvise an app then immediately return to the app and reload all file pages in the working set even though there was no intervening memory pressure. Our initial version of this work evicted

That would be the worst case scenario which should be avoided. Memory pressure must be a parameter before actually doing the swap out. But pages if know to be inactive/cold can be marked high priority to be swapped out.

Quoted 5 lines

file pages preemptively and did cause a noticeable slowdown (~15%) for that case; this patch set avoids that slowdown. Finally, the benefit from avoiding cold starts is huge. The performance improvement from having a hot start instead of a cold start ranges from 3x for very small apps to 50x+ for larger apps like high-fidelity games.

Quoted 3 lines

Is there any other real world scenario apart from this app based ecosystem where user hinted LRU management might be helpful ? Just being curious. Thanks for the detailed explanation. I will continue looking into this series.

Chrome OS is another real world use-case for this user hinted LRU management approach by proactively reclaiming reclaim from tabs not accessed by the user for some time.

#103 lore raw

To expand on the ChromeOS use case we're in a very similar situation to Android. For example, the Chrome browser uses a separate process for each individual tab (with some exceptions) and over time many tabs remain open in a back-grounded or idle state. Given that we have a lot of information about the weight of a tab, when it was last active, etc, we can benefit tremendously from per-process reclaim. We're working on getting real world numbers but all of our initial testing shows very promising results.

Quoted 101 lines · Shakeel Butt
Quoted 8 lines · Anshuman Khandual
Quoted 4 lines · Tim Murray
Quoted 2 lines · Anshuman Khandual

Or Is the objective here is reduce the number of processes which get

killed by

Quoted 1 line
Quoted 1 line
Quoted 1 line

lmkd by triggering swapping for the unused memory (user hinted)

sooner so that

Quoted 1 line
Quoted 1 line
Quoted 1 line

they dont get picked by lmkd. Under utilization for zram hardware is

a concern

Quoted 16 lines
Quoted 15 lines
Quoted 1 line

here as well ?

The objective is to avoid some instances of memory pressure by proactively swapping pages that userspace knows to be cold before those pages reach the end of the LRUs, which in turn can prevent some apps from being killed by lmk/lmkd. As soon as Android userspace knows that an application is not being used and is only resident to improve performance if the user returns to that app, we can kick off process_madvise on that process's pages (or some portion of those pages) in a power-efficient way to reduce memory pressure long before the system hits the free page watermark. This allows the system more time to put pages into zram versus waiting for the watermark to trigger kswapd, which decreases the likelihood that later memory allocations will cause enough pressure to trigger a kill of one of these apps.

Quoted 1 line

So this opens up bit of LRU management to user space hints. Also because

the app

Quoted 1 line

in itself wont know about the memory situation of the entire system, new

system

Quoted 4 lines

call needs to be called from an external process.

Quoted 2 lines
Quoted 2 lines

Swapping out memory into zram wont increase the latency for a hot

start ? Or

Quoted 1 line
Quoted 1 line
Quoted 1 line

is it because as it will prevent a fresh cold start which anyway will

be slower

Quoted 8 lines
Quoted 7 lines
Quoted 1 line

than a slow hot start. Just being curious.

First, not all swapped pages will be reloaded immediately once an app is resumed. We've found that an app's working set post-process_madvise is significantly smaller than what an app allocates when it first launches (see the delta between pswpin and pswpout in Minchan's results). Presumably because of this, faulting to fetch from zram does

Quoted 4 lines
pswpin      417613    1392647     975034     233.00
pswpout    1274224    2661731    1387507     108.00

IIUC the swap-in ratio is way higher in comparison to that of swap out.

Is that

Quoted 1 line

always the case ? Or it tend to swap out from an active area of the

working set

Quoted 8 lines

which faulted back again.

Quoted 4 lines

not seem to introduce a noticeable hot start penalty, not does it cause an increase in performance problems later in the app's lifecycle. I've measured with and without process_madvise, and the differences are within our noise bounds. Second, because we're not

That is assuming that post process_madvise() working set for the

application is

Quoted 1 line

always smaller. There is another challenge. The external process should

ideally

Quoted 1 line

have the knowledge of active areas of the working set for an application

in

Quoted 1 line

question for it to invoke process_madvise() correctly to prevent such

scenarios.

Quoted 8 lines
Quoted 6 lines

preemptively evicting file pages and only making them more likely to be evicted when there's already memory pressure, we avoid the case where we process_madvise an app then immediately return to the app and reload all file pages in the working set even though there was no intervening memory pressure. Our initial version of this work evicted

That would be the worst case scenario which should be avoided. Memory

pressure

Quoted 1 line

must be a parameter before actually doing the swap out. But pages if

know to be

Quoted 9 lines

inactive/cold can be marked high priority to be swapped out.

Quoted 5 lines

file pages preemptively and did cause a noticeable slowdown (~15%) for that case; this patch set avoids that slowdown. Finally, the benefit from avoiding cold starts is huge. The performance improvement from having a hot start instead of a cold start ranges from 3x for very small apps to 50x+ for larger apps like high-fidelity games.

Is there any other real world scenario apart from this app based

ecosystem where

Quoted 1 line

user hinted LRU management might be helpful ? Just being curious. Thanks

for the

Quoted 1 line

detailed explanation. I will continue looking into this series.

Chrome OS is another real world use-case for this user hinted LRU management approach by proactively reclaiming reclaim from tabs not accessed by the user for some time.

#104 lore raw
In reply to Shakeel Butt

To expand on the ChromeOS use case we're in a very similar situation to Android. For example, the Chrome browser uses a separate process for each individual tab (with some exceptions) and over time many tabs remain open in a back-grounded or idle state. Given that we have a lot of information about the weight of a tab, when it was last active, etc, we can benefit tremendously from per-process reclaim. We're working on getting real world numbers but all of our initial testing shows very promising results.

Quoted 84 lines · Shakeel Butt
Quoted 74 lines · Anshuman Khandual
Quoted 8 lines · Tim Murray
Quoted 5 lines · Anshuman Khandual

Or Is the objective here is reduce the number of processes which get killed by lmkd by triggering swapping for the unused memory (user hinted) sooner so that they dont get picked by lmkd. Under utilization for zram hardware is a concern here as well ?

Quoted 13 lines

The objective is to avoid some instances of memory pressure by proactively swapping pages that userspace knows to be cold before those pages reach the end of the LRUs, which in turn can prevent some apps from being killed by lmk/lmkd. As soon as Android userspace knows that an application is not being used and is only resident to improve performance if the user returns to that app, we can kick off process_madvise on that process's pages (or some portion of those pages) in a power-efficient way to reduce memory pressure long before the system hits the free page watermark. This allows the system more time to put pages into zram versus waiting for the watermark to trigger kswapd, which decreases the likelihood that later memory allocations will cause enough pressure to trigger a kill of one of these apps.

So this opens up bit of LRU management to user space hints. Also because the app in itself wont know about the memory situation of the entire system, new system call needs to be called from an external process.

Quoted 10 lines
Quoted 4 lines

Swapping out memory into zram wont increase the latency for a hot start ? Or is it because as it will prevent a fresh cold start which anyway will be slower than a slow hot start. Just being curious.

First, not all swapped pages will be reloaded immediately once an app is resumed. We've found that an app's working set post-process_madvise is significantly smaller than what an app allocates when it first launches (see the delta between pswpin and pswpout in Minchan's results). Presumably because of this, faulting to fetch from zram does

pswpin      417613    1392647     975034     233.00
pswpout    1274224    2661731    1387507     108.00

IIUC the swap-in ratio is way higher in comparison to that of swap out. Is that always the case ? Or it tend to swap out from an active area of the working set which faulted back again.

Quoted 4 lines

not seem to introduce a noticeable hot start penalty, not does it cause an increase in performance problems later in the app's lifecycle. I've measured with and without process_madvise, and the differences are within our noise bounds. Second, because we're not

That is assuming that post process_madvise() working set for the application is always smaller. There is another challenge. The external process should ideally have the knowledge of active areas of the working set for an application in question for it to invoke process_madvise() correctly to prevent such scenarios.

Quoted 5 lines

preemptively evicting file pages and only making them more likely to be evicted when there's already memory pressure, we avoid the case where we process_madvise an app then immediately return to the app and reload all file pages in the working set even though there was no intervening memory pressure. Our initial version of this work evicted

That would be the worst case scenario which should be avoided. Memory pressure must be a parameter before actually doing the swap out. But pages if know to be inactive/cold can be marked high priority to be swapped out.

Quoted 5 lines

file pages preemptively and did cause a noticeable slowdown (~15%) for that case; this patch set avoids that slowdown. Finally, the benefit from avoiding cold starts is huge. The performance improvement from having a hot start instead of a cold start ranges from 3x for very small apps to 50x+ for larger apps like high-fidelity games.

Quoted 3 lines

Is there any other real world scenario apart from this app based ecosystem where user hinted LRU management might be helpful ? Just being curious. Thanks for the detailed explanation. I will continue looking into this series.

Chrome OS is another real world use-case for this user hinted LRU management approach by proactively reclaiming reclaim from tabs not accessed by the user for some time.

reviewer
#105 lore raw
In reply to Minchan Kim

[Cc linux-api]

Quoted 186 lines · Minchan Kim

- Background

The Android terminology used for forking a new process and starting an app from scratch is a cold start, while resuming an existing app is a hot start. While we continually try to improve the performance of cold starts, hot starts will always be significantly less power hungry as well as faster so we are trying to make hot start more likely than cold start.

To increase hot start, Android userspace manages the order that apps should be killed in a process called ActivityManagerService. ActivityManagerService tracks every Android app or service that the user could be interacting with at any time and translates that into a ranked list for lmkd(low memory killer daemon). They are likely to be killed by lmkd if the system has to reclaim memory. In that sense they are similar to entries in any other cache. Those apps are kept alive for opportunistic performance improvements but those performance improvements will vary based on the memory requirements of individual workloads.

- Problem

Naturally, cached apps were dominant consumers of memory on the system. However, they were not significant consumers of swap even though they are good candidate for swap. Under investigation, swapping out only begins once the low zone watermark is hit and kswapd wakes up, but the overall allocation rate in the system might trip lmkd thresholds and cause a cached process to be killed(we measured performance swapping out vs. zapping the memory by killing a process. Unsurprisingly, zapping is 10x times faster even though we use zram which is much faster than real storage) so kill from lmkd will often satisfy the high zone watermark, resulting in very few pages actually being moved to swap.

- Approach

The approach we chose was to use a new interface to allow userspace to proactively reclaim entire processes by leveraging platform information. This allowed us to bypass the inaccuracy of the kernel’s LRUs for pages that are known to be cold from userspace and to avoid races with lmkd by reclaiming apps as soon as they entered the cached state. Additionally, it could provide many chances for platform to use much information to optimize memory efficiency.

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

To achieve the goal, the patchset introduce two new options for madvise. One is MADV_COOL which will deactive activated pages and the other is MADV_COLD which will reclaim private pages instantly. These new options complement MADV_DONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_DONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

This approach is similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to a centralized userspace daemon, and that daemon must be able to initiate reclaim on its own without any app involvement. To solve the concern, this patch introduces new syscall -

	struct pr_madvise_param {
		int size;
		const struct iovec *vec;
	}

	int process_madvise(int pidfd, ssize_t nr_elem, int *behavior,
				struct pr_madvise_param *restuls,
				struct pr_madvise_param *ranges,
				unsigned long flags);

The syscall get pidfd to give hints to external process and provides pair of result/ranges vector arguments so that it could give several hints to each address range all at once.

I guess others have different ideas about the naming of syscall and options so feel free to suggest better naming.

- Experiment

We did bunch of testing with several hundreds of real users, not artificial benchmark on android. We saw about 17% cold start decreasement without any significant battery/app startup latency issues. And with artificial benchmark which launches and switching apps, we saw average 7% app launching improvement, 18% less lmkd kill and good stat from vmstat.

A is vanilla and B is process_madvise.

                                       A          B      delta   ratio(%)
               allocstall_dma          0          0          0       0.00
           allocstall_movable       1464        457      -1007     -69.00
            allocstall_normal     263210     190763     -72447     -28.00
             allocstall_total     264674     191220     -73454     -28.00
          compact_daemon_wake      26912      25294      -1618      -7.00
                 compact_fail      17885      14151      -3734     -21.00
         compact_free_scanned 4204766409 3835994922 -368771487      -9.00
             compact_isolated    3446484    2967618    -478866     -14.00
      compact_migrate_scanned 1621336411 1324695710 -296640701     -19.00
                compact_stall      19387      15343      -4044     -21.00
              compact_success       1502       1192       -310     -21.00
kswapd_high_wmark_hit_quickly        234        184        -50     -22.00
            kswapd_inodesteal     221635     233093      11458       5.00
 kswapd_low_wmark_hit_quickly      66065      54009     -12056     -19.00
                   nr_dirtied     259934     296476      36542      14.00
  nr_vmscan_immediate_reclaim       2587       2356       -231      -9.00
              nr_vmscan_write    1274232    2661733    1387501     108.00
                   nr_written    1514060    2937560    1423500      94.00
                   pageoutrun      67561      55133     -12428     -19.00
                   pgactivate    2335060    1984882    -350178     -15.00
                  pgalloc_dma   13743011   14096463     353452       2.00
              pgalloc_movable          0          0          0       0.00
               pgalloc_normal   18742440   16802065   -1940375     -11.00
                pgalloc_total   32485451   30898528   -1586923      -5.00
                 pgdeactivate    4262210    2930670   -1331540     -32.00
                      pgfault   30812334   31085065     272731       0.00
                       pgfree   33553970   31765164   -1788806      -6.00
                 pginodesteal      33411      15084     -18327     -55.00
                  pglazyfreed          0          0          0       0.00
                   pgmajfault     551312    1508299     956987     173.00
               pgmigrate_fail      43927      29330     -14597     -34.00
            pgmigrate_success    1399851    1203922    -195929     -14.00
                       pgpgin   24141776   19032156   -5109620     -22.00
                      pgpgout     959344    1103316     143972      15.00
                 pgpgoutclean    4639732    3765868    -873864     -19.00
                     pgrefill    4884560    3006938   -1877622     -39.00
                    pgrotated      37828      25897     -11931     -32.00
                pgscan_direct    1456037     957567    -498470     -35.00
       pgscan_direct_throttle          0          0          0       0.00
                pgscan_kswapd    6667767    5047360   -1620407     -25.00
                 pgscan_total    8123804    6004927   -2118877     -27.00
                   pgskip_dma          0          0          0       0.00
               pgskip_movable          0          0          0       0.00
                pgskip_normal      14907      25382      10475      70.00
                 pgskip_total      14907      25382      10475      70.00
               pgsteal_direct    1118986     690215    -428771     -39.00
               pgsteal_kswapd    4750223    3657107   -1093116     -24.00
                pgsteal_total    5869209    4347322   -1521887     -26.00
                       pswpin     417613    1392647     975034     233.00
                      pswpout    1274224    2661731    1387507     108.00
                slabs_scanned   13686905   10807200   -2879705     -22.00
          workingset_activate     668966     569444     -99522     -15.00
       workingset_nodereclaim      38957      32621      -6336     -17.00
           workingset_refault    2816795    2179782    -637013     -23.00
           workingset_restore     294320     168601    -125719     -43.00

pgmajfault is increased by 173% because swapin is increased by 200% by process_madvise hint. However, swap read based on zram is much cheaper than file IO in performance point of view and app hot start by swapin is also cheaper than cold start from the beginning of app which needs many IO from storage and initialization steps.

This patchset is against on next-20190517.

Minchan Kim (7):
mm: introduce MADV_COOL
mm: change PAGEREF_RECLAIM_CLEAN with PAGE_REFRECLAIM
mm: introduce MADV_COLD
mm: factor out madvise's core functionality
mm: introduce external memory hinting API
mm: extend process_madvise syscall to support vector arrary
mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

 arch/x86/entry/syscalls/syscall_32.tbl |   1 +
 arch/x86/entry/syscalls/syscall_64.tbl |   1 +
 include/linux/page-flags.h             |   1 +
 include/linux/page_idle.h              |  15 +
 include/linux/proc_fs.h                |   1 +
 include/linux/swap.h                   |   2 +
 include/linux/syscalls.h               |   2 +
 include/uapi/asm-generic/mman-common.h |  12 +
 include/uapi/asm-generic/unistd.h      |   2 +
 kernel/signal.c                        |   2 +-
 kernel/sys_ni.c                        |   1 +
 mm/madvise.c                           | 600 +++++++++++++++++++++----
 mm/swap.c                              |  43 ++
 mm/vmscan.c                            |  80 +++-
 14 files changed, 680 insertions(+), 83 deletions(-)
Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
Signature · 2 lines
Michal Hocko
SUSE Labs
#106 lore raw
In reply to Minchan Kim

Hi.

Quoted 167 lines · Minchan Kim

- Background

The Android terminology used for forking a new process and starting an app from scratch is a cold start, while resuming an existing app is a hot start. While we continually try to improve the performance of cold starts, hot starts will always be significantly less power hungry as well as faster so we are trying to make hot start more likely than cold start.

To increase hot start, Android userspace manages the order that apps should be killed in a process called ActivityManagerService. ActivityManagerService tracks every Android app or service that the user could be interacting with at any time and translates that into a ranked list for lmkd(low memory killer daemon). They are likely to be killed by lmkd if the system has to reclaim memory. In that sense they are similar to entries in any other cache. Those apps are kept alive for opportunistic performance improvements but those performance improvements will vary based on the memory requirements of individual workloads.

- Problem

Naturally, cached apps were dominant consumers of memory on the system. However, they were not significant consumers of swap even though they are good candidate for swap. Under investigation, swapping out only begins once the low zone watermark is hit and kswapd wakes up, but the overall allocation rate in the system might trip lmkd thresholds and cause a cached process to be killed(we measured performance swapping out vs. zapping the memory by killing a process. Unsurprisingly, zapping is 10x times faster even though we use zram which is much faster than real storage) so kill from lmkd will often satisfy the high zone watermark, resulting in very few pages actually being moved to swap.

- Approach

The approach we chose was to use a new interface to allow userspace to proactively reclaim entire processes by leveraging platform information. This allowed us to bypass the inaccuracy of the kernel’s LRUs for pages that are known to be cold from userspace and to avoid races with lmkd by reclaiming apps as soon as they entered the cached state. Additionally, it could provide many chances for platform to use much information to optimize memory efficiency.

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

To achieve the goal, the patchset introduce two new options for madvise. One is MADV_COOL which will deactive activated pages and the other is MADV_COLD which will reclaim private pages instantly. These new options complement MADV_DONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_DONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

This approach is similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to a centralized userspace daemon, and that daemon must be able to initiate reclaim on its own without any app involvement. To solve the concern, this patch introduces new syscall -

	struct pr_madvise_param {
		int size;
		const struct iovec *vec;
	}

	int process_madvise(int pidfd, ssize_t nr_elem, int *behavior,
				struct pr_madvise_param *restuls,
				struct pr_madvise_param *ranges,
				unsigned long flags);

The syscall get pidfd to give hints to external process and provides pair of result/ranges vector arguments so that it could give several hints to each address range all at once.

I guess others have different ideas about the naming of syscall and options so feel free to suggest better naming.

- Experiment

We did bunch of testing with several hundreds of real users, not artificial benchmark on android. We saw about 17% cold start decreasement without any significant battery/app startup latency issues. And with artificial benchmark which launches and switching apps, we saw average 7% app launching improvement, 18% less lmkd kill and good stat from vmstat.

A is vanilla and B is process_madvise.

                                       A          B      delta   ratio(%)
               allocstall_dma          0          0          0       0.00
           allocstall_movable       1464        457      -1007     -69.00
            allocstall_normal     263210     190763     -72447     -28.00
             allocstall_total     264674     191220     -73454     -28.00
          compact_daemon_wake      26912      25294      -1618      -7.00
                 compact_fail      17885      14151      -3734     -21.00
         compact_free_scanned 4204766409 3835994922 -368771487      -9.00
             compact_isolated    3446484    2967618    -478866     -14.00
      compact_migrate_scanned 1621336411 1324695710 -296640701     -19.00
                compact_stall      19387      15343      -4044     -21.00
              compact_success       1502       1192       -310     -21.00
kswapd_high_wmark_hit_quickly        234        184        -50     -22.00
            kswapd_inodesteal     221635     233093      11458       5.00
 kswapd_low_wmark_hit_quickly      66065      54009     -12056     -19.00
                   nr_dirtied     259934     296476      36542      14.00
  nr_vmscan_immediate_reclaim       2587       2356       -231      -9.00
              nr_vmscan_write    1274232    2661733    1387501     108.00
                   nr_written    1514060    2937560    1423500      94.00
                   pageoutrun      67561      55133     -12428     -19.00
                   pgactivate    2335060    1984882    -350178     -15.00
                  pgalloc_dma   13743011   14096463     353452       2.00
              pgalloc_movable          0          0          0       0.00
               pgalloc_normal   18742440   16802065   -1940375     -11.00
                pgalloc_total   32485451   30898528   -1586923      -5.00
                 pgdeactivate    4262210    2930670   -1331540     -32.00
                      pgfault   30812334   31085065     272731       0.00
                       pgfree   33553970   31765164   -1788806      -6.00
                 pginodesteal      33411      15084     -18327     -55.00
                  pglazyfreed          0          0          0       0.00
                   pgmajfault     551312    1508299     956987     173.00
               pgmigrate_fail      43927      29330     -14597     -34.00
            pgmigrate_success    1399851    1203922    -195929     -14.00
                       pgpgin   24141776   19032156   -5109620     -22.00
                      pgpgout     959344    1103316     143972      15.00
                 pgpgoutclean    4639732    3765868    -873864     -19.00
                     pgrefill    4884560    3006938   -1877622     -39.00
                    pgrotated      37828      25897     -11931     -32.00
                pgscan_direct    1456037     957567    -498470     -35.00
       pgscan_direct_throttle          0          0          0       0.00
                pgscan_kswapd    6667767    5047360   -1620407     -25.00
                 pgscan_total    8123804    6004927   -2118877     -27.00
                   pgskip_dma          0          0          0       0.00
               pgskip_movable          0          0          0       0.00
                pgskip_normal      14907      25382      10475      70.00
                 pgskip_total      14907      25382      10475      70.00
               pgsteal_direct    1118986     690215    -428771     -39.00
               pgsteal_kswapd    4750223    3657107   -1093116     -24.00
                pgsteal_total    5869209    4347322   -1521887     -26.00
                       pswpin     417613    1392647     975034     233.00
                      pswpout    1274224    2661731    1387507     108.00
                slabs_scanned   13686905   10807200   -2879705     -22.00
          workingset_activate     668966     569444     -99522     -15.00
       workingset_nodereclaim      38957      32621      -6336     -17.00
           workingset_refault    2816795    2179782    -637013     -23.00
           workingset_restore     294320     168601    -125719     -43.00

pgmajfault is increased by 173% because swapin is increased by 200% by process_madvise hint. However, swap read based on zram is much cheaper than file IO in performance point of view and app hot start by swapin is also cheaper than cold start from the beginning of app which needs many IO from storage and initialization steps.

This patchset is against on next-20190517.

Minchan Kim (7):
mm: introduce MADV_COOL
mm: change PAGEREF_RECLAIM_CLEAN with PAGE_REFRECLAIM
mm: introduce MADV_COLD
mm: factor out madvise's core functionality
mm: introduce external memory hinting API
mm: extend process_madvise syscall to support vector arrary
mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 19 lines
 arch/x86/entry/syscalls/syscall_32.tbl |   1 +
 arch/x86/entry/syscalls/syscall_64.tbl |   1 +
 include/linux/page-flags.h             |   1 +
 include/linux/page_idle.h              |  15 +
 include/linux/proc_fs.h                |   1 +
 include/linux/swap.h                   |   2 +
 include/linux/syscalls.h               |   2 +
 include/uapi/asm-generic/mman-common.h |  12 +
 include/uapi/asm-generic/unistd.h      |   2 +
 kernel/signal.c                        |   2 +-
 kernel/sys_ni.c                        |   1 +
 mm/madvise.c                           | 600 +++++++++++++++++++++----
 mm/swap.c                              |  43 ++
 mm/vmscan.c                            |  80 +++-
 14 files changed, 680 insertions(+), 83 deletions(-)
Signature · 1 line
2.21.0.1020.gf2820cf01a-goog

Please Cc me for the next iteration since I was working on the very same thing recently [1].

Thank you.

[1] https://gitlab.com/post-factum/pf-kernel/commits/remote-madvise-v3

Signature · 3 lines
  Best regards,
    Oleksandr Natalenko (post-factum)
    Senior Software Maintenance Engineer
#107 lore raw
Quoted 190 lines · Oleksandr Natalenko

Hi.

Quoted 167 lines · Minchan Kim

- Background

The Android terminology used for forking a new process and starting an app from scratch is a cold start, while resuming an existing app is a hot start. While we continually try to improve the performance of cold starts, hot starts will always be significantly less power hungry as well as faster so we are trying to make hot start more likely than cold start.

To increase hot start, Android userspace manages the order that apps should be killed in a process called ActivityManagerService. ActivityManagerService tracks every Android app or service that the user could be interacting with at any time and translates that into a ranked list for lmkd(low memory killer daemon). They are likely to be killed by lmkd if the system has to reclaim memory. In that sense they are similar to entries in any other cache. Those apps are kept alive for opportunistic performance improvements but those performance improvements will vary based on the memory requirements of individual workloads.

- Problem

Naturally, cached apps were dominant consumers of memory on the system. However, they were not significant consumers of swap even though they are good candidate for swap. Under investigation, swapping out only begins once the low zone watermark is hit and kswapd wakes up, but the overall allocation rate in the system might trip lmkd thresholds and cause a cached process to be killed(we measured performance swapping out vs. zapping the memory by killing a process. Unsurprisingly, zapping is 10x times faster even though we use zram which is much faster than real storage) so kill from lmkd will often satisfy the high zone watermark, resulting in very few pages actually being moved to swap.

- Approach

The approach we chose was to use a new interface to allow userspace to proactively reclaim entire processes by leveraging platform information. This allowed us to bypass the inaccuracy of the kernel’s LRUs for pages that are known to be cold from userspace and to avoid races with lmkd by reclaiming apps as soon as they entered the cached state. Additionally, it could provide many chances for platform to use much information to optimize memory efficiency.

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

To achieve the goal, the patchset introduce two new options for madvise. One is MADV_COOL which will deactive activated pages and the other is MADV_COLD which will reclaim private pages instantly. These new options complement MADV_DONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_DONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

This approach is similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to a centralized userspace daemon, and that daemon must be able to initiate reclaim on its own without any app involvement. To solve the concern, this patch introduces new syscall -

	struct pr_madvise_param {
		int size;
		const struct iovec *vec;
	}

	int process_madvise(int pidfd, ssize_t nr_elem, int *behavior,
				struct pr_madvise_param *restuls,
				struct pr_madvise_param *ranges,
				unsigned long flags);

The syscall get pidfd to give hints to external process and provides pair of result/ranges vector arguments so that it could give several hints to each address range all at once.

I guess others have different ideas about the naming of syscall and options so feel free to suggest better naming.

- Experiment

We did bunch of testing with several hundreds of real users, not artificial benchmark on android. We saw about 17% cold start decreasement without any significant battery/app startup latency issues. And with artificial benchmark which launches and switching apps, we saw average 7% app launching improvement, 18% less lmkd kill and good stat from vmstat.

A is vanilla and B is process_madvise.

                                       A          B      delta   ratio(%)
               allocstall_dma          0          0          0       0.00
           allocstall_movable       1464        457      -1007     -69.00
            allocstall_normal     263210     190763     -72447     -28.00
             allocstall_total     264674     191220     -73454     -28.00
          compact_daemon_wake      26912      25294      -1618      -7.00
                 compact_fail      17885      14151      -3734     -21.00
         compact_free_scanned 4204766409 3835994922 -368771487      -9.00
             compact_isolated    3446484    2967618    -478866     -14.00
      compact_migrate_scanned 1621336411 1324695710 -296640701     -19.00
                compact_stall      19387      15343      -4044     -21.00
              compact_success       1502       1192       -310     -21.00
kswapd_high_wmark_hit_quickly        234        184        -50     -22.00
            kswapd_inodesteal     221635     233093      11458       5.00
 kswapd_low_wmark_hit_quickly      66065      54009     -12056     -19.00
                   nr_dirtied     259934     296476      36542      14.00
  nr_vmscan_immediate_reclaim       2587       2356       -231      -9.00
              nr_vmscan_write    1274232    2661733    1387501     108.00
                   nr_written    1514060    2937560    1423500      94.00
                   pageoutrun      67561      55133     -12428     -19.00
                   pgactivate    2335060    1984882    -350178     -15.00
                  pgalloc_dma   13743011   14096463     353452       2.00
              pgalloc_movable          0          0          0       0.00
               pgalloc_normal   18742440   16802065   -1940375     -11.00
                pgalloc_total   32485451   30898528   -1586923      -5.00
                 pgdeactivate    4262210    2930670   -1331540     -32.00
                      pgfault   30812334   31085065     272731       0.00
                       pgfree   33553970   31765164   -1788806      -6.00
                 pginodesteal      33411      15084     -18327     -55.00
                  pglazyfreed          0          0          0       0.00
                   pgmajfault     551312    1508299     956987     173.00
               pgmigrate_fail      43927      29330     -14597     -34.00
            pgmigrate_success    1399851    1203922    -195929     -14.00
                       pgpgin   24141776   19032156   -5109620     -22.00
                      pgpgout     959344    1103316     143972      15.00
                 pgpgoutclean    4639732    3765868    -873864     -19.00
                     pgrefill    4884560    3006938   -1877622     -39.00
                    pgrotated      37828      25897     -11931     -32.00
                pgscan_direct    1456037     957567    -498470     -35.00
       pgscan_direct_throttle          0          0          0       0.00
                pgscan_kswapd    6667767    5047360   -1620407     -25.00
                 pgscan_total    8123804    6004927   -2118877     -27.00
                   pgskip_dma          0          0          0       0.00
               pgskip_movable          0          0          0       0.00
                pgskip_normal      14907      25382      10475      70.00
                 pgskip_total      14907      25382      10475      70.00
               pgsteal_direct    1118986     690215    -428771     -39.00
               pgsteal_kswapd    4750223    3657107   -1093116     -24.00
                pgsteal_total    5869209    4347322   -1521887     -26.00
                       pswpin     417613    1392647     975034     233.00
                      pswpout    1274224    2661731    1387507     108.00
                slabs_scanned   13686905   10807200   -2879705     -22.00
          workingset_activate     668966     569444     -99522     -15.00
       workingset_nodereclaim      38957      32621      -6336     -17.00
           workingset_refault    2816795    2179782    -637013     -23.00
           workingset_restore     294320     168601    -125719     -43.00

pgmajfault is increased by 173% because swapin is increased by 200% by process_madvise hint. However, swap read based on zram is much cheaper than file IO in performance point of view and app hot start by swapin is also cheaper than cold start from the beginning of app which needs many IO from storage and initialization steps.

This patchset is against on next-20190517.

Minchan Kim (7):
mm: introduce MADV_COOL
mm: change PAGEREF_RECLAIM_CLEAN with PAGE_REFRECLAIM
mm: introduce MADV_COLD
mm: factor out madvise's core functionality
mm: introduce external memory hinting API
mm: extend process_madvise syscall to support vector arrary
mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

Quoted 19 lines
 arch/x86/entry/syscalls/syscall_32.tbl |   1 +
 arch/x86/entry/syscalls/syscall_64.tbl |   1 +
 include/linux/page-flags.h             |   1 +
 include/linux/page_idle.h              |  15 +
 include/linux/proc_fs.h                |   1 +
 include/linux/swap.h                   |   2 +
 include/linux/syscalls.h               |   2 +
 include/uapi/asm-generic/mman-common.h |  12 +
 include/uapi/asm-generic/unistd.h      |   2 +
 kernel/signal.c                        |   2 +-
 kernel/sys_ni.c                        |   1 +
 mm/madvise.c                           | 600 +++++++++++++++++++++----
 mm/swap.c                              |  43 ++
 mm/vmscan.c                            |  80 +++-
 14 files changed, 680 insertions(+), 83 deletions(-)
Signature · 1 line
2.21.0.1020.gf2820cf01a-goog
Quoted 6 lines

Please Cc me for the next iteration since I was working on the very same thing recently [1].

Thank you.

[1] https://gitlab.com/post-factum/pf-kernel/commits/remote-madvise-v3

Sure, I'm happy to see others have similar requirement.

maintainer
#108 lore raw
In reply to Minchan Kim
Quoted 10 lines · Minchan Kim

- Approach

The approach we chose was to use a new interface to allow userspace to proactively reclaim entire processes by leveraging platform information. This allowed us to bypass the inaccuracy of the kernel’s LRUs for pages that are known to be cold from userspace and to avoid races with lmkd by reclaiming apps as soon as they entered the cached state. Additionally, it could provide many chances for platform to use much information to optimize memory efficiency.

Quoted 7 lines

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

I agree with this approach and the semantics. But these names are very vague and extremely easy to confuse since they're so similar.

MADV_COLD could be a good name, but for deactivating pages, not reclaiming them - marking memory "cold" on the LRU for later reclaim.

For the immediate reclaim one, I think there is a better option too:
In virtual memory speak, putting a page into secondary storage (or ensuring it's already there), and then freeing its in-memory copy, is called "paging out". And that's what this flag is supposed to do. So how about MADV_PAGEOUT?

With that, we'd have:

MADV_FREE: Mark data invalid, free memory when needed
MADV_DONTNEED: Mark data invalid, free memory immediately

MADV_COLD: Data is not used for a while, free memory when needed
MADV_PAGEOUT: Data is not used for a while, free memory immediately

What do you think?

#109 lore raw
Quoted 33 lines · Johannes Weiner
Quoted 10 lines · Minchan Kim

- Approach

The approach we chose was to use a new interface to allow userspace to proactively reclaim entire processes by leveraging platform information. This allowed us to bypass the inaccuracy of the kernel’s LRUs for pages that are known to be cold from userspace and to avoid races with lmkd by reclaiming apps as soon as they entered the cached state. Additionally, it could provide many chances for platform to use much information to optimize memory efficiency.

Quoted 7 lines

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

I agree with this approach and the semantics. But these names are very vague and extremely easy to confuse since they're so similar.

MADV_COLD could be a good name, but for deactivating pages, not reclaiming them - marking memory "cold" on the LRU for later reclaim.

For the immediate reclaim one, I think there is a better option too:
In virtual memory speak, putting a page into secondary storage (or ensuring it's already there), and then freeing its in-memory copy, is called "paging out". And that's what this flag is supposed to do. So how about MADV_PAGEOUT?

With that, we'd have:

Quoted 7 lines

MADV_FREE: Mark data invalid, free memory when needed
MADV_DONTNEED: Mark data invalid, free memory immediately

MADV_COLD: Data is not used for a while, free memory when needed
MADV_PAGEOUT: Data is not used for a while, free memory immediately

What do you think?

There are several suggestions until now. Thanks, Folks!

For deactivating:

- MADV_COOL
- MADV_RECLAIM_LAZY
- MADV_DEACTIVATE
- MADV_COLD
- MADV_FREE_PRESERVE

For reclaiming:

- MADV_COLD
- MADV_RECLAIM_NOW
- MADV_RECLAIMING
- MADV_PAGEOUT
- MADV_DONTNEED_PRESERVE

It seems everybody doesn't like MADV_COLD so want to go with other. For consisteny of view with other existing hints of madvise, -preserve postfix suits well. However, originally, I don't like the naming FREE vs DONTNEED from the beginning. They were easily confused. I prefer PAGEOUT to RECLAIM since it's more likely to be nuance to represent reclaim with memory pressure and is supposed to paged-in if someone need it later. So, it imply PRESERVE.
If there is not strong against it, I want to go with MADV_COLD and MADV_PAGEOUT.

Other opinion?

reviewer
#110 lore raw

[Cc linux-api]

Quoted 71 lines · Minchan Kim
Quoted 33 lines · Johannes Weiner
Quoted 10 lines · Minchan Kim

- Approach

The approach we chose was to use a new interface to allow userspace to proactively reclaim entire processes by leveraging platform information. This allowed us to bypass the inaccuracy of the kernel’s LRUs for pages that are known to be cold from userspace and to avoid races with lmkd by reclaiming apps as soon as they entered the cached state. Additionally, it could provide many chances for platform to use much information to optimize memory efficiency.

Quoted 7 lines

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

I agree with this approach and the semantics. But these names are very vague and extremely easy to confuse since they're so similar.

MADV_COLD could be a good name, but for deactivating pages, not reclaiming them - marking memory "cold" on the LRU for later reclaim.

For the immediate reclaim one, I think there is a better option too:
In virtual memory speak, putting a page into secondary storage (or ensuring it's already there), and then freeing its in-memory copy, is called "paging out". And that's what this flag is supposed to do. So how about MADV_PAGEOUT?

With that, we'd have:

Quoted 7 lines

MADV_FREE: Mark data invalid, free memory when needed
MADV_DONTNEED: Mark data invalid, free memory immediately

MADV_COLD: Data is not used for a while, free memory when needed
MADV_PAGEOUT: Data is not used for a while, free memory immediately

What do you think?

There are several suggestions until now. Thanks, Folks!

For deactivating:

- MADV_COOL
- MADV_RECLAIM_LAZY
- MADV_DEACTIVATE
- MADV_COLD
- MADV_FREE_PRESERVE

For reclaiming:

- MADV_COLD
- MADV_RECLAIM_NOW
- MADV_RECLAIMING
- MADV_PAGEOUT
- MADV_DONTNEED_PRESERVE

It seems everybody doesn't like MADV_COLD so want to go with other. For consisteny of view with other existing hints of madvise, -preserve postfix suits well. However, originally, I don't like the naming FREE vs DONTNEED from the beginning. They were easily confused. I prefer PAGEOUT to RECLAIM since it's more likely to be nuance to represent reclaim with memory pressure and is supposed to paged-in if someone need it later. So, it imply PRESERVE.
If there is not strong against it, I want to go with MADV_COLD and MADV_PAGEOUT.

Quoted 1 line

Other opinion?

I do not really care strongly. I am pretty sure we will have a lot of suggestions because people tend to be good at arguing about that... Anyway, unlike DONTNEED/FREE we do not have any other OS to implement these features, right? So we shouldn't be tight to existing names. On the other hand I kinda like the reference to the existing names but DEACTIVATE/PAGEOUT seem a good fit to me as well. Unless there is way much better name suggested I would go with one of those. Up to you.

Signature · 2 lines
Michal Hocko
SUSE Labs
#111 lore raw
In reply to Minchan Kim
Quoted 7 lines · Minchan Kim

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

Do we tear down page tables for these ranges? That seems like a good way of reclaiming potentially a substantial amount of memory.

#112 lore raw
Quoted 10 lines · Matthew Wilcox
Quoted 7 lines · Minchan Kim

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

Do we tear down page tables for these ranges? That seems like a good

True for MADV_COLD(reclaiming) but false for MADV_COOL(deactivating) at this implementation.

Quoted 1 line

way of reclaiming potentially a substantial amount of memory.

Given that consider refauting are spread out over time and reclaim occurs in burst, that does make sense to speed up the reclaiming. However, a concern to me is anonymous pages since they need swap cache insertion, which would be wasteful if they are not reclaimed, finally.

reviewer
#113 lore raw
In reply to Matthew Wilcox

[linux-api]

Quoted 11 lines · Matthew Wilcox
Quoted 7 lines · Minchan Kim

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

Do we tear down page tables for these ranges? That seems like a good way of reclaiming potentially a substantial amount of memory.

I do not think we can in general because this is a non-destructive operation. So at least we cannot tear down anonymous ptes (they will turn into swap entries).

Signature · 2 lines
Michal Hocko
SUSE Labs
#114 lore raw
In reply to Minchan Kim
Quoted 75 lines · Minchan Kim

- Background

The Android terminology used for forking a new process and starting an app from scratch is a cold start, while resuming an existing app is a hot start. While we continually try to improve the performance of cold starts, hot starts will always be significantly less power hungry as well as faster so we are trying to make hot start more likely than cold start.

To increase hot start, Android userspace manages the order that apps should be killed in a process called ActivityManagerService. ActivityManagerService tracks every Android app or service that the user could be interacting with at any time and translates that into a ranked list for lmkd(low memory killer daemon). They are likely to be killed by lmkd if the system has to reclaim memory. In that sense they are similar to entries in any other cache. Those apps are kept alive for opportunistic performance improvements but those performance improvements will vary based on the memory requirements of individual workloads.

- Problem

Naturally, cached apps were dominant consumers of memory on the system. However, they were not significant consumers of swap even though they are good candidate for swap. Under investigation, swapping out only begins once the low zone watermark is hit and kswapd wakes up, but the overall allocation rate in the system might trip lmkd thresholds and cause a cached process to be killed(we measured performance swapping out vs. zapping the memory by killing a process. Unsurprisingly, zapping is 10x times faster even though we use zram which is much faster than real storage) so kill from lmkd will often satisfy the high zone watermark, resulting in very few pages actually being moved to swap.

- Approach

The approach we chose was to use a new interface to allow userspace to proactively reclaim entire processes by leveraging platform information. This allowed us to bypass the inaccuracy of the kernel’s LRUs for pages that are known to be cold from userspace and to avoid races with lmkd by reclaiming apps as soon as they entered the cached state. Additionally, it could provide many chances for platform to use much information to optimize memory efficiency.

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

To achieve the goal, the patchset introduce two new options for madvise. One is MADV_COOL which will deactive activated pages and the other is MADV_COLD which will reclaim private pages instantly. These new options complement MADV_DONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_DONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

This approach is similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to a centralized userspace daemon, and that daemon must be able to initiate reclaim on its own without any app involvement. To solve the concern, this patch introduces new syscall -

	struct pr_madvise_param {
		int size;
		const struct iovec *vec;
	}

	int process_madvise(int pidfd, ssize_t nr_elem, int *behavior,
				struct pr_madvise_param *restuls,
				struct pr_madvise_param *ranges,
				unsigned long flags);
Quoted 6 lines

The syscall get pidfd to give hints to external process and provides pair of result/ranges vector arguments so that it could give several hints to each address range all at once.

I guess others have different ideas about the naming of syscall and options so feel free to suggest better naming.

Yes, all new syscalls making use of pidfds should be named pidfd_<action>. So please make this pidfd_madvise.

Please make sure to Cc me on this in the future as I'm maintaining pidfds. Would be great to have Jann on this too since he's been touching both mm and parts of the pidfd stuff with me.

#115 lore raw
Quoted 80 lines · Christian Brauner
Quoted 79 lines · Minchan Kim

- Background

The Android terminology used for forking a new process and starting an app from scratch is a cold start, while resuming an existing app is a hot start. While we continually try to improve the performance of cold starts, hot starts will always be significantly less power hungry as well as faster so we are trying to make hot start more likely than cold start.

To increase hot start, Android userspace manages the order that apps should be killed in a process called ActivityManagerService. ActivityManagerService tracks every Android app or service that the user could be interacting with at any time and translates that into a ranked list for lmkd(low memory killer daemon). They are likely to be killed by lmkd if the system has to reclaim memory. In that sense they are similar to entries in any other cache. Those apps are kept alive for opportunistic performance improvements but those performance improvements will vary based on the memory requirements of individual workloads.

- Problem

Naturally, cached apps were dominant consumers of memory on the system. However, they were not significant consumers of swap even though they are good candidate for swap. Under investigation, swapping out only begins once the low zone watermark is hit and kswapd wakes up, but the overall allocation rate in the system might trip lmkd thresholds and cause a cached process to be killed(we measured performance swapping out vs. zapping the memory by killing a process. Unsurprisingly, zapping is 10x times faster even though we use zram which is much faster than real storage) so kill from lmkd will often satisfy the high zone watermark, resulting in very few pages actually being moved to swap.

- Approach

The approach we chose was to use a new interface to allow userspace to proactively reclaim entire processes by leveraging platform information. This allowed us to bypass the inaccuracy of the kernel’s LRUs for pages that are known to be cold from userspace and to avoid races with lmkd by reclaiming apps as soon as they entered the cached state. Additionally, it could provide many chances for platform to use much information to optimize memory efficiency.

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

To achieve the goal, the patchset introduce two new options for madvise. One is MADV_COOL which will deactive activated pages and the other is MADV_COLD which will reclaim private pages instantly. These new options complement MADV_DONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_DONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

This approach is similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to a centralized userspace daemon, and that daemon must be able to initiate reclaim on its own without any app involvement. To solve the concern, this patch introduces new syscall -

	struct pr_madvise_param {
		int size;
		const struct iovec *vec;
	}

	int process_madvise(int pidfd, ssize_t nr_elem, int *behavior,
				struct pr_madvise_param *restuls,
				struct pr_madvise_param *ranges,
				unsigned long flags);

The syscall get pidfd to give hints to external process and provides pair of result/ranges vector arguments so that it could give several hints to each address range all at once.

Quoted 5 lines
Quoted 2 lines

I guess others have different ideas about the naming of syscall and options so feel free to suggest better naming.

Yes, all new syscalls making use of pidfds should be named pidfd_<action>. So please make this pidfd_madvise.

I don't have any particular preference but just wondering why pidfd is so special to have it as prefix of system call name.

Quoted 4 lines

Please make sure to Cc me on this in the future as I'm maintaining pidfds. Would be great to have Jann on this too since he's been touching both mm and parts of the pidfd stuff with me.

Sure!

#116 lore raw
Quoted 81 lines · Minchan Kim
Quoted 80 lines · Christian Brauner
Quoted 79 lines · Minchan Kim

- Background

The Android terminology used for forking a new process and starting an app from scratch is a cold start, while resuming an existing app is a hot start. While we continually try to improve the performance of cold starts, hot starts will always be significantly less power hungry as well as faster so we are trying to make hot start more likely than cold start.

To increase hot start, Android userspace manages the order that apps should be killed in a process called ActivityManagerService. ActivityManagerService tracks every Android app or service that the user could be interacting with at any time and translates that into a ranked list for lmkd(low memory killer daemon). They are likely to be killed by lmkd if the system has to reclaim memory. In that sense they are similar to entries in any other cache. Those apps are kept alive for opportunistic performance improvements but those performance improvements will vary based on the memory requirements of individual workloads.

- Problem

Naturally, cached apps were dominant consumers of memory on the system. However, they were not significant consumers of swap even though they are good candidate for swap. Under investigation, swapping out only begins once the low zone watermark is hit and kswapd wakes up, but the overall allocation rate in the system might trip lmkd thresholds and cause a cached process to be killed(we measured performance swapping out vs. zapping the memory by killing a process. Unsurprisingly, zapping is 10x times faster even though we use zram which is much faster than real storage) so kill from lmkd will often satisfy the high zone watermark, resulting in very few pages actually being moved to swap.

- Approach

The approach we chose was to use a new interface to allow userspace to proactively reclaim entire processes by leveraging platform information. This allowed us to bypass the inaccuracy of the kernel’s LRUs for pages that are known to be cold from userspace and to avoid races with lmkd by reclaiming apps as soon as they entered the cached state. Additionally, it could provide many chances for platform to use much information to optimize memory efficiency.

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

To achieve the goal, the patchset introduce two new options for madvise. One is MADV_COOL which will deactive activated pages and the other is MADV_COLD which will reclaim private pages instantly. These new options complement MADV_DONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_DONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

This approach is similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to a centralized userspace daemon, and that daemon must be able to initiate reclaim on its own without any app involvement. To solve the concern, this patch introduces new syscall -

	struct pr_madvise_param {
		int size;
		const struct iovec *vec;
	}

	int process_madvise(int pidfd, ssize_t nr_elem, int *behavior,
				struct pr_madvise_param *restuls,
				struct pr_madvise_param *ranges,
				unsigned long flags);

The syscall get pidfd to give hints to external process and provides pair of result/ranges vector arguments so that it could give several hints to each address range all at once.

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

I guess others have different ideas about the naming of syscall and options so feel free to suggest better naming.

Yes, all new syscalls making use of pidfds should be named pidfd_<action>. So please make this pidfd_madvise.

I don't have any particular preference but just wondering why pidfd is so special to have it as prefix of system call name.

It's a whole new API to address processes. We already have clone(CLONE_PIDFD) and pidfd_send_signal() as you have seen since you exported pidfd_to_pid(). And we're going to have pidfd_open(). Your syscall works only with pidfds so it's tied to this api as well so it should follow the naming scheme. This also makes life easier for userspace and is consistent.

Quoted 7 lines
Quoted 5 lines

Please make sure to Cc me on this in the future as I'm maintaining pidfds. Would be great to have Jann on this too since he's been touching both mm and parts of the pidfd stuff with me.

Sure!

Thanks!

#117 lore raw
Quoted 91 lines · Christian Brauner
Quoted 81 lines · Minchan Kim
Quoted 80 lines · Christian Brauner
Quoted 79 lines · Minchan Kim

- Background

The Android terminology used for forking a new process and starting an app from scratch is a cold start, while resuming an existing app is a hot start. While we continually try to improve the performance of cold starts, hot starts will always be significantly less power hungry as well as faster so we are trying to make hot start more likely than cold start.

To increase hot start, Android userspace manages the order that apps should be killed in a process called ActivityManagerService. ActivityManagerService tracks every Android app or service that the user could be interacting with at any time and translates that into a ranked list for lmkd(low memory killer daemon). They are likely to be killed by lmkd if the system has to reclaim memory. In that sense they are similar to entries in any other cache. Those apps are kept alive for opportunistic performance improvements but those performance improvements will vary based on the memory requirements of individual workloads.

- Problem

Naturally, cached apps were dominant consumers of memory on the system. However, they were not significant consumers of swap even though they are good candidate for swap. Under investigation, swapping out only begins once the low zone watermark is hit and kswapd wakes up, but the overall allocation rate in the system might trip lmkd thresholds and cause a cached process to be killed(we measured performance swapping out vs. zapping the memory by killing a process. Unsurprisingly, zapping is 10x times faster even though we use zram which is much faster than real storage) so kill from lmkd will often satisfy the high zone watermark, resulting in very few pages actually being moved to swap.

- Approach

The approach we chose was to use a new interface to allow userspace to proactively reclaim entire processes by leveraging platform information. This allowed us to bypass the inaccuracy of the kernel’s LRUs for pages that are known to be cold from userspace and to avoid races with lmkd by reclaiming apps as soon as they entered the cached state. Additionally, it could provide many chances for platform to use much information to optimize memory efficiency.

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

To achieve the goal, the patchset introduce two new options for madvise. One is MADV_COOL which will deactive activated pages and the other is MADV_COLD which will reclaim private pages instantly. These new options complement MADV_DONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_DONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

This approach is similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to a centralized userspace daemon, and that daemon must be able to initiate reclaim on its own without any app involvement. To solve the concern, this patch introduces new syscall -

	struct pr_madvise_param {
		int size;
		const struct iovec *vec;
	}

	int process_madvise(int pidfd, ssize_t nr_elem, int *behavior,
				struct pr_madvise_param *restuls,
				struct pr_madvise_param *ranges,
				unsigned long flags);

The syscall get pidfd to give hints to external process and provides pair of result/ranges vector arguments so that it could give several hints to each address range all at once.

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

I guess others have different ideas about the naming of syscall and options so feel free to suggest better naming.

Yes, all new syscalls making use of pidfds should be named pidfd_<action>. So please make this pidfd_madvise.

I don't have any particular preference but just wondering why pidfd is so special to have it as prefix of system call name.

Quoted 6 lines

It's a whole new API to address processes. We already have clone(CLONE_PIDFD) and pidfd_send_signal() as you have seen since you exported pidfd_to_pid(). And we're going to have pidfd_open(). Your syscall works only with pidfds so it's tied to this api as well so it should follow the naming scheme. This also makes life easier for userspace and is consistent.

This is at least my reasoning. I'm not going to make this a whole big pedantic argument. If people have really strong feelings about not using this prefix then fine. But if syscalls can be grouped together and have consistent naming this is always a big plus.

#118 lore raw
Quoted 100 lines · Christian Brauner
Quoted 91 lines · Christian Brauner
Quoted 81 lines · Minchan Kim
Quoted 80 lines · Christian Brauner
Quoted 79 lines · Minchan Kim

- Background

The Android terminology used for forking a new process and starting an app from scratch is a cold start, while resuming an existing app is a hot start. While we continually try to improve the performance of cold starts, hot starts will always be significantly less power hungry as well as faster so we are trying to make hot start more likely than cold start.

To increase hot start, Android userspace manages the order that apps should be killed in a process called ActivityManagerService. ActivityManagerService tracks every Android app or service that the user could be interacting with at any time and translates that into a ranked list for lmkd(low memory killer daemon). They are likely to be killed by lmkd if the system has to reclaim memory. In that sense they are similar to entries in any other cache. Those apps are kept alive for opportunistic performance improvements but those performance improvements will vary based on the memory requirements of individual workloads.

- Problem

Naturally, cached apps were dominant consumers of memory on the system. However, they were not significant consumers of swap even though they are good candidate for swap. Under investigation, swapping out only begins once the low zone watermark is hit and kswapd wakes up, but the overall allocation rate in the system might trip lmkd thresholds and cause a cached process to be killed(we measured performance swapping out vs. zapping the memory by killing a process. Unsurprisingly, zapping is 10x times faster even though we use zram which is much faster than real storage) so kill from lmkd will often satisfy the high zone watermark, resulting in very few pages actually being moved to swap.

- Approach

The approach we chose was to use a new interface to allow userspace to proactively reclaim entire processes by leveraging platform information. This allowed us to bypass the inaccuracy of the kernel’s LRUs for pages that are known to be cold from userspace and to avoid races with lmkd by reclaiming apps as soon as they entered the cached state. Additionally, it could provide many chances for platform to use much information to optimize memory efficiency.

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

To achieve the goal, the patchset introduce two new options for madvise. One is MADV_COOL which will deactive activated pages and the other is MADV_COLD which will reclaim private pages instantly. These new options complement MADV_DONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_DONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

This approach is similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to a centralized userspace daemon, and that daemon must be able to initiate reclaim on its own without any app involvement. To solve the concern, this patch introduces new syscall -

        struct pr_madvise_param {
                int size;
                const struct iovec *vec;
        }

        int process_madvise(int pidfd, ssize_t nr_elem, int *behavior,
                                struct pr_madvise_param *restuls,
                                struct pr_madvise_param *ranges,
                                unsigned long flags);

The syscall get pidfd to give hints to external process and provides pair of result/ranges vector arguments so that it could give several hints to each address range all at once.

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

I guess others have different ideas about the naming of syscall and options so feel free to suggest better naming.

Yes, all new syscalls making use of pidfds should be named pidfd_<action>. So please make this pidfd_madvise.

I don't have any particular preference but just wondering why pidfd is so special to have it as prefix of system call name.

Quoted 6 lines

It's a whole new API to address processes. We already have clone(CLONE_PIDFD) and pidfd_send_signal() as you have seen since you exported pidfd_to_pid(). And we're going to have pidfd_open(). Your syscall works only with pidfds so it's tied to this api as well so it should follow the naming scheme. This also makes life easier for userspace and is consistent.

Quoted 4 lines

This is at least my reasoning. I'm not going to make this a whole big pedantic argument. If people have really strong feelings about not using this prefix then fine. But if syscalls can be grouped together and have consistent naming this is always a big plus.

My hope has been that pidfd use becomes normalized enough that prefixing "pidfd_" to pidfd-accepting system calls becomes redundant. We write write(), not fd_write(), right? :-) pidfd_open() makes sense because the primary purpose of this system call is to operate on a pidfd, but I think process_madvise() is fine.

#119 lore raw
Quoted 107 lines · Daniel Colascione
Quoted 100 lines · Christian Brauner
Quoted 91 lines · Christian Brauner
Quoted 81 lines · Minchan Kim
Quoted 80 lines · Christian Brauner
Quoted 79 lines · Minchan Kim

- Background

The Android terminology used for forking a new process and starting an app from scratch is a cold start, while resuming an existing app is a hot start. While we continually try to improve the performance of cold starts, hot starts will always be significantly less power hungry as well as faster so we are trying to make hot start more likely than cold start.

To increase hot start, Android userspace manages the order that apps should be killed in a process called ActivityManagerService. ActivityManagerService tracks every Android app or service that the user could be interacting with at any time and translates that into a ranked list for lmkd(low memory killer daemon). They are likely to be killed by lmkd if the system has to reclaim memory. In that sense they are similar to entries in any other cache. Those apps are kept alive for opportunistic performance improvements but those performance improvements will vary based on the memory requirements of individual workloads.

- Problem

Naturally, cached apps were dominant consumers of memory on the system. However, they were not significant consumers of swap even though they are good candidate for swap. Under investigation, swapping out only begins once the low zone watermark is hit and kswapd wakes up, but the overall allocation rate in the system might trip lmkd thresholds and cause a cached process to be killed(we measured performance swapping out vs. zapping the memory by killing a process. Unsurprisingly, zapping is 10x times faster even though we use zram which is much faster than real storage) so kill from lmkd will often satisfy the high zone watermark, resulting in very few pages actually being moved to swap.

- Approach

The approach we chose was to use a new interface to allow userspace to proactively reclaim entire processes by leveraging platform information. This allowed us to bypass the inaccuracy of the kernel’s LRUs for pages that are known to be cold from userspace and to avoid races with lmkd by reclaiming apps as soon as they entered the cached state. Additionally, it could provide many chances for platform to use much information to optimize memory efficiency.

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

To achieve the goal, the patchset introduce two new options for madvise. One is MADV_COOL which will deactive activated pages and the other is MADV_COLD which will reclaim private pages instantly. These new options complement MADV_DONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_DONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

This approach is similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to a centralized userspace daemon, and that daemon must be able to initiate reclaim on its own without any app involvement. To solve the concern, this patch introduces new syscall -

        struct pr_madvise_param {
                int size;
                const struct iovec *vec;
        }

        int process_madvise(int pidfd, ssize_t nr_elem, int *behavior,
                                struct pr_madvise_param *restuls,
                                struct pr_madvise_param *ranges,
                                unsigned long flags);

The syscall get pidfd to give hints to external process and provides pair of result/ranges vector arguments so that it could give several hints to each address range all at once.

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

I guess others have different ideas about the naming of syscall and options so feel free to suggest better naming.

Yes, all new syscalls making use of pidfds should be named pidfd_<action>. So please make this pidfd_madvise.

I don't have any particular preference but just wondering why pidfd is so special to have it as prefix of system call name.

Quoted 6 lines

It's a whole new API to address processes. We already have clone(CLONE_PIDFD) and pidfd_send_signal() as you have seen since you exported pidfd_to_pid(). And we're going to have pidfd_open(). Your syscall works only with pidfds so it's tied to this api as well so it should follow the naming scheme. This also makes life easier for userspace and is consistent.

Quoted 4 lines

This is at least my reasoning. I'm not going to make this a whole big pedantic argument. If people have really strong feelings about not using this prefix then fine. But if syscalls can be grouped together and have consistent naming this is always a big plus.

Quoted 5 lines

My hope has been that pidfd use becomes normalized enough that prefixing "pidfd_" to pidfd-accepting system calls becomes redundant. We write write(), not fd_write(), right? :-) pidfd_open() makes sense because the primary purpose of this system call is to operate on a pidfd, but I think process_madvise() is fine.

This madvise syscall just operates on pidfds. It would make sense to name it process_madvise() if were to operate both on pid_t and int pidfd. Giving specific names to system calls won't stop it from becoming normalized. The fact that people built other system calls around it is enough proof of that. :)
For userspace pidfd_madvise is nicer and it clearly expresses that it only accepts pidfds.
So please, Minchan make it pidfd_madvise() in the next version. :)

Christian

#120 lore raw
Quoted 109 lines · Christian Brauner
Quoted 107 lines · Daniel Colascione
Quoted 104 lines · Christian Brauner
Quoted 91 lines · Christian Brauner
Quoted 81 lines · Minchan Kim
Quoted 80 lines · Christian Brauner
Quoted 79 lines · Minchan Kim

- Background

The Android terminology used for forking a new process and starting an app from scratch is a cold start, while resuming an existing app is a hot start. While we continually try to improve the performance of cold starts, hot starts will always be significantly less power hungry as well as faster so we are trying to make hot start more likely than cold start.

To increase hot start, Android userspace manages the order that apps should be killed in a process called ActivityManagerService. ActivityManagerService tracks every Android app or service that the user could be interacting with at any time and translates that into a ranked list for lmkd(low memory killer daemon). They are likely to be killed by lmkd if the system has to reclaim memory. In that sense they are similar to entries in any other cache. Those apps are kept alive for opportunistic performance improvements but those performance improvements will vary based on the memory requirements of individual workloads.

- Problem

Naturally, cached apps were dominant consumers of memory on the system. However, they were not significant consumers of swap even though they are good candidate for swap. Under investigation, swapping out only begins once the low zone watermark is hit and kswapd wakes up, but the overall allocation rate in the system might trip lmkd thresholds and cause a cached process to be killed(we measured performance swapping out vs. zapping the memory by killing a process. Unsurprisingly, zapping is 10x times faster even though we use zram which is much faster than real storage) so kill from lmkd will often satisfy the high zone watermark, resulting in very few pages actually being moved to swap.

- Approach

The approach we chose was to use a new interface to allow userspace to proactively reclaim entire processes by leveraging platform information. This allowed us to bypass the inaccuracy of the kernel’s LRUs for pages that are known to be cold from userspace and to avoid races with lmkd by reclaiming apps as soon as they entered the cached state. Additionally, it could provide many chances for platform to use much information to optimize memory efficiency.

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

To achieve the goal, the patchset introduce two new options for madvise. One is MADV_COOL which will deactive activated pages and the other is MADV_COLD which will reclaim private pages instantly. These new options complement MADV_DONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_DONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

This approach is similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to a centralized userspace daemon, and that daemon must be able to initiate reclaim on its own without any app involvement. To solve the concern, this patch introduces new syscall -

        struct pr_madvise_param {
                int size;
                const struct iovec *vec;
        }

        int process_madvise(int pidfd, ssize_t nr_elem, int *behavior,
                                struct pr_madvise_param *restuls,
                                struct pr_madvise_param *ranges,
                                unsigned long flags);

The syscall get pidfd to give hints to external process and provides pair of result/ranges vector arguments so that it could give several hints to each address range all at once.

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

I guess others have different ideas about the naming of syscall and options so feel free to suggest better naming.

Yes, all new syscalls making use of pidfds should be named pidfd_<action>. So please make this pidfd_madvise.

I don't have any particular preference but just wondering why pidfd is so special to have it as prefix of system call name.

Quoted 6 lines

It's a whole new API to address processes. We already have clone(CLONE_PIDFD) and pidfd_send_signal() as you have seen since you exported pidfd_to_pid(). And we're going to have pidfd_open(). Your syscall works only with pidfds so it's tied to this api as well so it should follow the naming scheme. This also makes life easier for userspace and is consistent.

This is at least my reasoning. I'm not going to make this a whole big pedantic argument. If people have really strong feelings about not using this prefix then fine. But if syscalls can be grouped together and have consistent naming this is always a big plus.

Quoted 8 lines
Quoted 5 lines

My hope has been that pidfd use becomes normalized enough that prefixing "pidfd_" to pidfd-accepting system calls becomes redundant. We write write(), not fd_write(), right? :-) pidfd_open() makes sense because the primary purpose of this system call is to operate on a pidfd, but I think process_madvise() is fine.

This madvise syscall just operates on pidfds. It would make sense to name it process_madvise() if were to operate both on pid_t and int pidfd.

The name of the function ought to encode its purpose, not its signature. The system call under discussion operates on processes and so should be called "process_madvise". That this system call happens to accept a pidfd to identify the process on which it operates is not its most interesting aspect of the system call. The argument type isn't important enough to spotlight in the permanent name of an API. Pidfds are novel now, but they won't be novel in the future.

Quoted 2 lines

Giving specific names to system calls won't stop it from becoming normalized.

We could name system calls with cat /dev/urandom | xxd and they'd still get used. It doesn't follow that all names are equally good.

#121 lore raw
Quoted 119 lines · Daniel Colascione
Quoted 109 lines · Christian Brauner
Quoted 107 lines · Daniel Colascione
Quoted 104 lines · Christian Brauner
Quoted 91 lines · Christian Brauner
Quoted 81 lines · Minchan Kim
Quoted 80 lines · Christian Brauner
Quoted 79 lines · Minchan Kim

- Background

The Android terminology used for forking a new process and starting an app from scratch is a cold start, while resuming an existing app is a hot start. While we continually try to improve the performance of cold starts, hot starts will always be significantly less power hungry as well as faster so we are trying to make hot start more likely than cold start.

To increase hot start, Android userspace manages the order that apps should be killed in a process called ActivityManagerService. ActivityManagerService tracks every Android app or service that the user could be interacting with at any time and translates that into a ranked list for lmkd(low memory killer daemon). They are likely to be killed by lmkd if the system has to reclaim memory. In that sense they are similar to entries in any other cache. Those apps are kept alive for opportunistic performance improvements but those performance improvements will vary based on the memory requirements of individual workloads.

- Problem

Naturally, cached apps were dominant consumers of memory on the system. However, they were not significant consumers of swap even though they are good candidate for swap. Under investigation, swapping out only begins once the low zone watermark is hit and kswapd wakes up, but the overall allocation rate in the system might trip lmkd thresholds and cause a cached process to be killed(we measured performance swapping out vs. zapping the memory by killing a process. Unsurprisingly, zapping is 10x times faster even though we use zram which is much faster than real storage) so kill from lmkd will often satisfy the high zone watermark, resulting in very few pages actually being moved to swap.

- Approach

The approach we chose was to use a new interface to allow userspace to proactively reclaim entire processes by leveraging platform information. This allowed us to bypass the inaccuracy of the kernel’s LRUs for pages that are known to be cold from userspace and to avoid races with lmkd by reclaiming apps as soon as they entered the cached state. Additionally, it could provide many chances for platform to use much information to optimize memory efficiency.

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

To achieve the goal, the patchset introduce two new options for madvise. One is MADV_COOL which will deactive activated pages and the other is MADV_COLD which will reclaim private pages instantly. These new options complement MADV_DONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_DONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

This approach is similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to a centralized userspace daemon, and that daemon must be able to initiate reclaim on its own without any app involvement. To solve the concern, this patch introduces new syscall -

        struct pr_madvise_param {
                int size;
                const struct iovec *vec;
        }

        int process_madvise(int pidfd, ssize_t nr_elem, int *behavior,
                                struct pr_madvise_param *restuls,
                                struct pr_madvise_param *ranges,
                                unsigned long flags);

The syscall get pidfd to give hints to external process and provides pair of result/ranges vector arguments so that it could give several hints to each address range all at once.

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

I guess others have different ideas about the naming of syscall and options so feel free to suggest better naming.

Yes, all new syscalls making use of pidfds should be named pidfd_<action>. So please make this pidfd_madvise.

I don't have any particular preference but just wondering why pidfd is so special to have it as prefix of system call name.

Quoted 6 lines

It's a whole new API to address processes. We already have clone(CLONE_PIDFD) and pidfd_send_signal() as you have seen since you exported pidfd_to_pid(). And we're going to have pidfd_open(). Your syscall works only with pidfds so it's tied to this api as well so it should follow the naming scheme. This also makes life easier for userspace and is consistent.

This is at least my reasoning. I'm not going to make this a whole big pedantic argument. If people have really strong feelings about not using this prefix then fine. But if syscalls can be grouped together and have consistent naming this is always a big plus.

Quoted 8 lines
Quoted 5 lines

My hope has been that pidfd use becomes normalized enough that prefixing "pidfd_" to pidfd-accepting system calls becomes redundant. We write write(), not fd_write(), right? :-) pidfd_open() makes sense because the primary purpose of this system call is to operate on a pidfd, but I think process_madvise() is fine.

This madvise syscall just operates on pidfds. It would make sense to name it process_madvise() if were to operate both on pid_t and int pidfd.

Quoted 7 lines

The name of the function ought to encode its purpose, not its signature. The system call under discussion operates on processes and so should be called "process_madvise". That this system call happens to accept a pidfd to identify the process on which it operates is not its most interesting aspect of the system call. The argument type isn't important enough to spotlight in the permanent name of an API. Pidfds are novel now, but they won't be novel in the future.

I'm not going to go into yet another long argument. I prefer pidfd_*. It's tied to the api, transparent for userspace, and disambiguates it from process_vm_{read,write}v that both take a pid_t.

#122 lore raw
Quoted 1 line · Christian Brauner

I'm not going to go into yet another long argument. I prefer pidfd_*.

Ok. We're each allowed our opinion.

Quoted 2 lines

It's tied to the api, transparent for userspace, and disambiguates it from process_vm_{read,write}v that both take a pid_t.

Speaking of process_vm_readv and process_vm_writev: both have a currently-unused flags argument. Both should grow a flag that tells them to interpret the pid argument as a pidfd. Or do you support adding pidfd_vm_readv and pidfd_vm_writev system calls? If not, why should process_madvise be called pidfd_madvise while process_vm_readv isn't called pidfd_vm_readv?

#123 lore raw
Quoted 8 lines · Daniel Colascione
Quoted 1 line · Christian Brauner

I'm not going to go into yet another long argument. I prefer pidfd_*.

Ok. We're each allowed our opinion.

Quoted 2 lines

It's tied to the api, transparent for userspace, and disambiguates it from process_vm_{read,write}v that both take a pid_t.

Quoted 6 lines

Speaking of process_vm_readv and process_vm_writev: both have a currently-unused flags argument. Both should grow a flag that tells them to interpret the pid argument as a pidfd. Or do you support adding pidfd_vm_readv and pidfd_vm_writev system calls? If not, why should process_madvise be called pidfd_madvise while process_vm_readv isn't called pidfd_vm_readv?

Actually, you should then do the same with process_madvise() and give it a flag for that too if that's not too crazy.

Christian

#124 lore raw
Quoted 17 lines · Christian Brauner
Quoted 8 lines · Daniel Colascione
Quoted 1 line · Christian Brauner

I'm not going to go into yet another long argument. I prefer pidfd_*.

Ok. We're each allowed our opinion.

Quoted 2 lines

It's tied to the api, transparent for userspace, and disambiguates it from process_vm_{read,write}v that both take a pid_t.

Quoted 6 lines

Speaking of process_vm_readv and process_vm_writev: both have a currently-unused flags argument. Both should grow a flag that tells them to interpret the pid argument as a pidfd. Or do you support adding pidfd_vm_readv and pidfd_vm_writev system calls? If not, why should process_madvise be called pidfd_madvise while process_vm_readv isn't called pidfd_vm_readv?

Quoted 2 lines

Actually, you should then do the same with process_madvise() and give it a flag for that too if that's not too crazy.

I don't know what you mean. My gut feeling is that for the sake of consistency, process_madvise, process_vm_readv, and process_vm_writev should all accept a first argument interpreted as either a numeric PID or a pidfd depending on a flag --- ideally the same flag. Is that what you have in mind?

#125 lore raw
Quoted 18 lines · Daniel Colascione
Quoted 17 lines · Christian Brauner
Quoted 14 lines · Daniel Colascione
Quoted 1 line · Christian Brauner

I'm not going to go into yet another long argument. I prefer pidfd_*.

Ok. We're each allowed our opinion.

Quoted 2 lines

It's tied to the api, transparent for userspace, and disambiguates it from process_vm_{read,write}v that both take a pid_t.

Speaking of process_vm_readv and process_vm_writev: both have a currently-unused flags argument. Both should grow a flag that tells them to interpret the pid argument as a pidfd. Or do you support adding pidfd_vm_readv and pidfd_vm_writev system calls? If not, why should process_madvise be called pidfd_madvise while process_vm_readv isn't called pidfd_vm_readv?

Quoted 8 lines
Quoted 2 lines

Actually, you should then do the same with process_madvise() and give it a flag for that too if that's not too crazy.

I don't know what you mean. My gut feeling is that for the sake of consistency, process_madvise, process_vm_readv, and process_vm_writev should all accept a first argument interpreted as either a numeric PID or a pidfd depending on a flag --- ideally the same flag. Is that what you have in mind?

Yes. For the sake of consistency they should probably all default to interpret as pid and if say PROCESS_{VM_}PIDFD is passed as flag interpret as pidfd.

#126 lore raw
Quoted 29 lines · Christian Brauner
Quoted 18 lines · Daniel Colascione
Quoted 17 lines · Christian Brauner
Quoted 14 lines · Daniel Colascione
Quoted 1 line · Christian Brauner

I'm not going to go into yet another long argument. I prefer pidfd_*.

Ok. We're each allowed our opinion.

Quoted 2 lines

It's tied to the api, transparent for userspace, and disambiguates it from process_vm_{read,write}v that both take a pid_t.

Speaking of process_vm_readv and process_vm_writev: both have a currently-unused flags argument. Both should grow a flag that tells them to interpret the pid argument as a pidfd. Or do you support adding pidfd_vm_readv and pidfd_vm_writev system calls? If not, why should process_madvise be called pidfd_madvise while process_vm_readv isn't called pidfd_vm_readv?

Quoted 8 lines
Quoted 2 lines

Actually, you should then do the same with process_madvise() and give it a flag for that too if that's not too crazy.

I don't know what you mean. My gut feeling is that for the sake of consistency, process_madvise, process_vm_readv, and process_vm_writev should all accept a first argument interpreted as either a numeric PID or a pidfd depending on a flag --- ideally the same flag. Is that what you have in mind?

Quoted 3 lines

Yes. For the sake of consistency they should probably all default to interpret as pid and if say PROCESS_{VM_}PIDFD is passed as flag interpret as pidfd.

Sounds good to me!

#127 lore raw
Quoted 30 lines · Daniel Colascione
Quoted 29 lines · Christian Brauner
Quoted 26 lines · Daniel Colascione
Quoted 17 lines · Christian Brauner
Quoted 8 lines · Daniel Colascione
Quoted 1 line · Christian Brauner

I'm not going to go into yet another long argument. I prefer pidfd_*.

Ok. We're each allowed our opinion.

Quoted 2 lines

It's tied to the api, transparent for userspace, and disambiguates it from process_vm_{read,write}v that both take a pid_t.

Quoted 6 lines

Speaking of process_vm_readv and process_vm_writev: both have a currently-unused flags argument. Both should grow a flag that tells them to interpret the pid argument as a pidfd. Or do you support adding pidfd_vm_readv and pidfd_vm_writev system calls? If not, why should process_madvise be called pidfd_madvise while process_vm_readv isn't called pidfd_vm_readv?

Quoted 2 lines

Actually, you should then do the same with process_madvise() and give it a flag for that too if that's not too crazy.

I don't know what you mean. My gut feeling is that for the sake of consistency, process_madvise, process_vm_readv, and process_vm_writev should all accept a first argument interpreted as either a numeric PID or a pidfd depending on a flag --- ideally the same flag. Is that what you have in mind?

Quoted 5 lines
Quoted 3 lines

Yes. For the sake of consistency they should probably all default to interpret as pid and if say PROCESS_{VM_}PIDFD is passed as flag interpret as pidfd.

Sounds good to me!

Then, I want to change from pidfd to pid at next revsion and stick to process_madvise as naming. Later, you guys could define PROCESS_PIDFD flag and change all at once every process_xxx syscall friends.

If you are faster so that I see PROCESS_PIDFD earlier, I am happy to use it.

Thanks.

#128 lore raw
Quoted 35 lines · Minchan Kim
Quoted 34 lines · Daniel Colascione
Quoted 32 lines · Christian Brauner
Quoted 18 lines · Daniel Colascione
Quoted 17 lines · Christian Brauner
Quoted 14 lines · Daniel Colascione
Quoted 1 line · Christian Brauner

I'm not going to go into yet another long argument. I prefer pidfd_*.

Ok. We're each allowed our opinion.

Quoted 2 lines

It's tied to the api, transparent for userspace, and disambiguates it from process_vm_{read,write}v that both take a pid_t.

Speaking of process_vm_readv and process_vm_writev: both have a currently-unused flags argument. Both should grow a flag that tells them to interpret the pid argument as a pidfd. Or do you support adding pidfd_vm_readv and pidfd_vm_writev system calls? If not, why should process_madvise be called pidfd_madvise while process_vm_readv isn't called pidfd_vm_readv?

Quoted 8 lines
Quoted 2 lines

Actually, you should then do the same with process_madvise() and give it a flag for that too if that's not too crazy.

I don't know what you mean. My gut feeling is that for the sake of consistency, process_madvise, process_vm_readv, and process_vm_writev should all accept a first argument interpreted as either a numeric PID or a pidfd depending on a flag --- ideally the same flag. Is that what you have in mind?

Yes. For the sake of consistency they should probably all default to interpret as pid and if say PROCESS_{VM_}PIDFD is passed as flag interpret as pidfd.

Quoted 8 lines
Quoted 1 line

Sounds good to me!

Then, I want to change from pidfd to pid at next revsion and stick to process_madvise as naming. Later, you guys could define PROCESS_PIDFD flag and change all at once every process_xxx syscall friends.

If you are faster so that I see PROCESS_PIDFD earlier, I am happy to use it.

Hi Folks,

I don't want to consume a new API argument too early so want to say I will use process_madvise with pidfs argument because I agree with Daniel that we don't need to export implmentation on the syscall name.

I hope every upcoming new syscall with process has by default pidfs so people are familiar with pidfd slowly so finallly they forgot pid in the long run so naturally replace pid with pidfs.

#129 lore raw
In reply to Christian Brauner
Quoted 91 lines · Christian Brauner
Quoted 81 lines · Minchan Kim
Quoted 80 lines · Christian Brauner
Quoted 79 lines · Minchan Kim

- Background

The Android terminology used for forking a new process and starting an app from scratch is a cold start, while resuming an existing app is a hot start. While we continually try to improve the performance of cold starts, hot starts will always be significantly less power hungry as well as faster so we are trying to make hot start more likely than cold start.

To increase hot start, Android userspace manages the order that apps should be killed in a process called ActivityManagerService. ActivityManagerService tracks every Android app or service that the user could be interacting with at any time and translates that into a ranked list for lmkd(low memory killer daemon). They are likely to be killed by lmkd if the system has to reclaim memory. In that sense they are similar to entries in any other cache. Those apps are kept alive for opportunistic performance improvements but those performance improvements will vary based on the memory requirements of individual workloads.

- Problem

Naturally, cached apps were dominant consumers of memory on the system. However, they were not significant consumers of swap even though they are good candidate for swap. Under investigation, swapping out only begins once the low zone watermark is hit and kswapd wakes up, but the overall allocation rate in the system might trip lmkd thresholds and cause a cached process to be killed(we measured performance swapping out vs. zapping the memory by killing a process. Unsurprisingly, zapping is 10x times faster even though we use zram which is much faster than real storage) so kill from lmkd will often satisfy the high zone watermark, resulting in very few pages actually being moved to swap.

- Approach

The approach we chose was to use a new interface to allow userspace to proactively reclaim entire processes by leveraging platform information. This allowed us to bypass the inaccuracy of the kernel’s LRUs for pages that are known to be cold from userspace and to avoid races with lmkd by reclaiming apps as soon as they entered the cached state. Additionally, it could provide many chances for platform to use much information to optimize memory efficiency.

IMHO we should spell it out that this patchset complements MADV_WONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

To achieve the goal, the patchset introduce two new options for madvise. One is MADV_COOL which will deactive activated pages and the other is MADV_COLD which will reclaim private pages instantly. These new options complement MADV_DONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_DONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

This approach is similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to a centralized userspace daemon, and that daemon must be able to initiate reclaim on its own without any app involvement. To solve the concern, this patch introduces new syscall -

	struct pr_madvise_param {
		int size;
		const struct iovec *vec;
	}

	int process_madvise(int pidfd, ssize_t nr_elem, int *behavior,
				struct pr_madvise_param *restuls,
				struct pr_madvise_param *ranges,
				unsigned long flags);

The syscall get pidfd to give hints to external process and provides pair of result/ranges vector arguments so that it could give several hints to each address range all at once.

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

I guess others have different ideas about the naming of syscall and options so feel free to suggest better naming.

Yes, all new syscalls making use of pidfds should be named pidfd_<action>. So please make this pidfd_madvise.

I don't have any particular preference but just wondering why pidfd is so special to have it as prefix of system call name.

Quoted 6 lines

It's a whole new API to address processes. We already have clone(CLONE_PIDFD) and pidfd_send_signal() as you have seen since you exported pidfd_to_pid(). And we're going to have pidfd_open(). Your syscall works only with pidfds so it's tied to this api as well so it should follow the naming scheme. This also makes life easier for userspace and is consistent.

Okay. I will change the API name at next revision. Thanks.

#130 lore raw
Quoted 148 lines · Minchan Kim
Quoted 6 lines · Christian Brauner
Quoted 5 lines · Minchan Kim
Quoted 4 lines · Christian Brauner
Quoted 3 lines · Minchan Kim

- Background

The Android terminology used for forking a new process and

starting an app

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

from scratch is a cold start, while resuming an existing app is

a hot start.

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

While we continually try to improve the performance of cold

starts, hot

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

starts will always be significantly less power hungry as well

as faster so

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

we are trying to make hot start more likely than cold start.

To increase hot start, Android userspace manages the order that

apps should

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

be killed in a process called ActivityManagerService.

ActivityManagerService

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

tracks every Android app or service that the user could be

interacting with

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

at any time and translates that into a ranked list for lmkd(low

memory

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

killer daemon). They are likely to be killed by lmkd if the

system has to

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

reclaim memory. In that sense they are similar to entries in

any other cache.

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

Those apps are kept alive for opportunistic performance

improvements but

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

those performance improvements will vary based on the memory

requirements of

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

individual workloads.

- Problem

Naturally, cached apps were dominant consumers of memory on the

system.

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

However, they were not significant consumers of swap even

though they are

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

good candidate for swap. Under investigation, swapping out only

begins

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

once the low zone watermark is hit and kswapd wakes up, but the

overall

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

allocation rate in the system might trip lmkd thresholds and

cause a cached

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

process to be killed(we measured performance swapping out vs.

zapping the

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

memory by killing a process. Unsurprisingly, zapping is 10x

times faster

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

even though we use zram which is much faster than real storage)

so kill

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

from lmkd will often satisfy the high zone watermark, resulting

in very

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

few pages actually being moved to swap.

- Approach

The approach we chose was to use a new interface to allow

userspace to

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

proactively reclaim entire processes by leveraging platform

information.

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

This allowed us to bypass the inaccuracy of the kernel’s LRUs

for pages

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

that are known to be cold from userspace and to avoid races

with lmkd

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

by reclaiming apps as soon as they entered the cached state.

Additionally,

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

it could provide many chances for platform to use much

information to

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

optimize memory efficiency.

IMHO we should spell it out that this patchset complements

MADV_WONTNEED

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

and MADV_FREE by adding non-destructive ways to gain some free

memory

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

space. MADV_COLD is similar to MADV_WONTNEED in a way that it

hints the

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

kernel that memory region is not currently needed and should be

reclaimed

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

immediately; MADV_COOL is similar to MADV_FREE in a way that it

hints the

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

kernel that memory region is not currently needed and should be

reclaimed

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

when memory pressure rises.

To achieve the goal, the patchset introduce two new options for

madvise.

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

One is MADV_COOL which will deactive activated pages and the

other is

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

MADV_COLD which will reclaim private pages instantly. These new

options

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

complement MADV_DONTNEED and MADV_FREE by adding

non-destructive ways to

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

gain some free memory space. MADV_COLD is similar to

MADV_DONTNEED in a way

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

that it hints the kernel that memory region is not currently

needed and

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

should be reclaimed immediately; MADV_COOL is similar to

MADV_FREE in a way

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

that it hints the kernel that memory region is not currently

needed and

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

should be reclaimed when memory pressure rises.

This approach is similar in spirit to madvise(MADV_WONTNEED),

but the

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

information required to make the reclaim decision is not known

to the app.

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

Instead, it is known to a centralized userspace daemon, and

that daemon

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

must be able to initiate reclaim on its own without any app

involvement.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

To solve the concern, this patch introduces new syscall -

	struct pr_madvise_param {
		int size;
		const struct iovec *vec;
	}
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

int process_madvise(int pidfd, ssize_t nr_elem, int *behavior,
struct pr_madvise_param *restuls, struct pr_madvise_param *ranges, unsigned long flags);

The syscall get pidfd to give hints to external process and

provides

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

pair of result/ranges vector arguments so that it could give

several

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

hints to each address range all at once.

I guess others have different ideas about the naming of syscall

and options

Quoted 6 lines
Quoted 6 lines
Quoted 4 lines
Quoted 1 line

so feel free to suggest better naming.

Yes, all new syscalls making use of pidfds should be named pidfd_<action>. So please make this pidfd_madvise.

I don't have any particular preference but just wondering why pidfd

is

Quoted 8 lines
Quoted 1 line

so special to have it as prefix of system call name.

It's a whole new API to address processes. We already have clone(CLONE_PIDFD) and pidfd_send_signal() as you have seen since you exported pidfd_to_pid(). And we're going to have pidfd_open(). Your syscall works only with pidfds so it's tied to this api as well so it should follow the naming scheme. This also makes life easier for userspace and is consistent.

Quoted 2 lines

Okay. I will change the API name at next revision. Thanks.

Thanks!
Fwiw, there's been a similar patch by Oleksandr for pidfd_madvise I stumbled upon a few days back:
https://gitlab.com/post-factum/pf-kernel/commit/0595f874a53fa898739ac315ddf208554d9dc897

He wanted to be cc'ed but I forgot.

Christian

#131 lore raw
Quoted 149 lines · Christian Brauner
Quoted 148 lines · Minchan Kim
Quoted 6 lines · Christian Brauner
Quoted 5 lines · Minchan Kim
Quoted 4 lines · Christian Brauner
Quoted 3 lines · Minchan Kim

- Background

The Android terminology used for forking a new process and

starting an app

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

from scratch is a cold start, while resuming an existing app is

a hot start.

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

While we continually try to improve the performance of cold

starts, hot

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

starts will always be significantly less power hungry as well

as faster so

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

we are trying to make hot start more likely than cold start.

To increase hot start, Android userspace manages the order that

apps should

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

be killed in a process called ActivityManagerService.

ActivityManagerService

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

tracks every Android app or service that the user could be

interacting with

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

at any time and translates that into a ranked list for lmkd(low

memory

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

killer daemon). They are likely to be killed by lmkd if the

system has to

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

reclaim memory. In that sense they are similar to entries in

any other cache.

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

Those apps are kept alive for opportunistic performance

improvements but

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

those performance improvements will vary based on the memory

requirements of

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

individual workloads.

- Problem

Naturally, cached apps were dominant consumers of memory on the

system.

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

However, they were not significant consumers of swap even

though they are

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

good candidate for swap. Under investigation, swapping out only

begins

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

once the low zone watermark is hit and kswapd wakes up, but the

overall

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

allocation rate in the system might trip lmkd thresholds and

cause a cached

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

process to be killed(we measured performance swapping out vs.

zapping the

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

memory by killing a process. Unsurprisingly, zapping is 10x

times faster

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

even though we use zram which is much faster than real storage)

so kill

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

from lmkd will often satisfy the high zone watermark, resulting

in very

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

few pages actually being moved to swap.

- Approach

The approach we chose was to use a new interface to allow

userspace to

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

proactively reclaim entire processes by leveraging platform

information.

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

This allowed us to bypass the inaccuracy of the kernel’s LRUs

for pages

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

that are known to be cold from userspace and to avoid races

with lmkd

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

by reclaiming apps as soon as they entered the cached state.

Additionally,

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

it could provide many chances for platform to use much

information to

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

optimize memory efficiency.

IMHO we should spell it out that this patchset complements

MADV_WONTNEED

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

and MADV_FREE by adding non-destructive ways to gain some free

memory

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

space. MADV_COLD is similar to MADV_WONTNEED in a way that it

hints the

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

kernel that memory region is not currently needed and should be

reclaimed

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

immediately; MADV_COOL is similar to MADV_FREE in a way that it

hints the

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

kernel that memory region is not currently needed and should be

reclaimed

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

when memory pressure rises.

To achieve the goal, the patchset introduce two new options for

madvise.

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

One is MADV_COOL which will deactive activated pages and the

other is

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

MADV_COLD which will reclaim private pages instantly. These new

options

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

complement MADV_DONTNEED and MADV_FREE by adding

non-destructive ways to

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

gain some free memory space. MADV_COLD is similar to

MADV_DONTNEED in a way

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

that it hints the kernel that memory region is not currently

needed and

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

should be reclaimed immediately; MADV_COOL is similar to

MADV_FREE in a way

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

that it hints the kernel that memory region is not currently

needed and

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

should be reclaimed when memory pressure rises.

This approach is similar in spirit to madvise(MADV_WONTNEED),

but the

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

information required to make the reclaim decision is not known

to the app.

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

Instead, it is known to a centralized userspace daemon, and

that daemon

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

must be able to initiate reclaim on its own without any app

involvement.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

To solve the concern, this patch introduces new syscall -

	struct pr_madvise_param {
		int size;
		const struct iovec *vec;
	}
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

int process_madvise(int pidfd, ssize_t nr_elem, int *behavior,
struct pr_madvise_param *restuls, struct pr_madvise_param *ranges, unsigned long flags);

The syscall get pidfd to give hints to external process and

provides

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

pair of result/ranges vector arguments so that it could give

several

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

hints to each address range all at once.

I guess others have different ideas about the naming of syscall

and options

Quoted 6 lines
Quoted 6 lines
Quoted 4 lines
Quoted 1 line

so feel free to suggest better naming.

Yes, all new syscalls making use of pidfds should be named pidfd_<action>. So please make this pidfd_madvise.

I don't have any particular preference but just wondering why pidfd

is

Quoted 8 lines
Quoted 1 line

so special to have it as prefix of system call name.

It's a whole new API to address processes. We already have clone(CLONE_PIDFD) and pidfd_send_signal() as you have seen since you exported pidfd_to_pid(). And we're going to have pidfd_open(). Your syscall works only with pidfds so it's tied to this api as well so it should follow the naming scheme. This also makes life easier for userspace and is consistent.

Quoted 8 lines
Quoted 2 lines

Okay. I will change the API name at next revision. Thanks.

Thanks!
Fwiw, there's been a similar patch by Oleksandr for pidfd_madvise I stumbled upon a few days back:
https://gitlab.com/post-factum/pf-kernel/commit/0595f874a53fa898739ac315ddf208554d9dc897

He wanted to be cc'ed but I forgot.

Thanks :).

FWIW, since this submission is essentially a continuation of our discussion involving my earlier KSM submissions here, I won't move my gitlab branch forward and will be happy to assist with what we have here, be it pidfd_madvise() or a set or /proc files (or smth else).

Quoted 3 lines

Christian

Signature · 3 lines
  Best regards,
    Oleksandr Natalenko (post-factum)
    Senior Software Maintenance Engineer
#132 lore raw
In reply to Minchan Kim
Quoted 21 lines · Minchan Kim

- Background

The Android terminology used for forking a new process and starting an app from scratch is a cold start, while resuming an existing app is a hot start. While we continually try to improve the performance of cold starts, hot starts will always be significantly less power hungry as well as faster so we are trying to make hot start more likely than cold start.

To increase hot start, Android userspace manages the order that apps should be killed in a process called ActivityManagerService. ActivityManagerService tracks every Android app or service that the user could be interacting with at any time and translates that into a ranked list for lmkd(low memory killer daemon). They are likely to be killed by lmkd if the system has to reclaim memory. In that sense they are similar to entries in any other cache. Those apps are kept alive for opportunistic performance improvements but those performance improvements will vary based on the memory requirements of individual workloads.

- Problem

Quoted 10 lines

Naturally, cached apps were dominant consumers of memory on the system. However, they were not significant consumers of swap even though they are good candidate for swap. Under investigation, swapping out only begins once the low zone watermark is hit and kswapd wakes up, but the overall allocation rate in the system might trip lmkd thresholds and cause a cached process to be killed(we measured performance swapping out vs. zapping the memory by killing a process. Unsurprisingly, zapping is 10x times faster even though we use zram which is much faster than real storage) so kill from lmkd will often satisfy the high zone watermark, resulting in very few pages actually being moved to swap.

It is not clear what exactly is the problem from the above para. IMO low usage of swap is not the problem but rather global memory pressure and the reactive response to it is the problem. Killing apps over swap is preferred as you have noted zapping frees memory faster but it indirectly increases cold start. Also swapping on allocation causes latency issues for the app. So, a proactive mechanism is needed to keep global pressure away and indirectly reduces cold starts and alloc stalls.

Quoted 10 lines

- Approach

The approach we chose was to use a new interface to allow userspace to proactively reclaim entire processes by leveraging platform information. This allowed us to bypass the inaccuracy of the kernel’s LRUs for pages that are known to be cold from userspace and to avoid races with lmkd by reclaiming apps as soon as they entered the cached state. Additionally, it could provide many chances for platform to use much information to optimize memory efficiency.

I think it would be good to have clear reasoning on why "reclaim from userspace" approach is taken. Android runtime clearly has more accurate stale/cold information at the app/process level and can positively influence kernel's reclaim decisions. So, "reclaim from userspace" approach makes total sense for Android. I envision that Chrome OS would be another very obvious user of this approach. There can be tens of tabs which the user have not touched for sometime. Chrome OS can proactively reclaim memory from such tabs.

Quoted 2 lines

IMHO we should spell it out that this patchset complements MADV_WONTNEED

MADV_DONTNEED? same at couple of places below.

Quoted 144 lines

and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_WONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

To achieve the goal, the patchset introduce two new options for madvise. One is MADV_COOL which will deactive activated pages and the other is MADV_COLD which will reclaim private pages instantly. These new options complement MADV_DONTNEED and MADV_FREE by adding non-destructive ways to gain some free memory space. MADV_COLD is similar to MADV_DONTNEED in a way that it hints the kernel that memory region is not currently needed and should be reclaimed immediately; MADV_COOL is similar to MADV_FREE in a way that it hints the kernel that memory region is not currently needed and should be reclaimed when memory pressure rises.

This approach is similar in spirit to madvise(MADV_WONTNEED), but the information required to make the reclaim decision is not known to the app. Instead, it is known to a centralized userspace daemon, and that daemon must be able to initiate reclaim on its own without any app involvement. To solve the concern, this patch introduces new syscall -

        struct pr_madvise_param {
                int size;
                const struct iovec *vec;
        }

        int process_madvise(int pidfd, ssize_t nr_elem, int *behavior,
                                struct pr_madvise_param *restuls,
                                struct pr_madvise_param *ranges,
                                unsigned long flags);

The syscall get pidfd to give hints to external process and provides pair of result/ranges vector arguments so that it could give several hints to each address range all at once.

I guess others have different ideas about the naming of syscall and options so feel free to suggest better naming.

- Experiment

We did bunch of testing with several hundreds of real users, not artificial benchmark on android. We saw about 17% cold start decreasement without any significant battery/app startup latency issues. And with artificial benchmark which launches and switching apps, we saw average 7% app launching improvement, 18% less lmkd kill and good stat from vmstat.

A is vanilla and B is process_madvise.

                                       A          B      delta   ratio(%)
               allocstall_dma          0          0          0       0.00
           allocstall_movable       1464        457      -1007     -69.00
            allocstall_normal     263210     190763     -72447     -28.00
             allocstall_total     264674     191220     -73454     -28.00
          compact_daemon_wake      26912      25294      -1618      -7.00
                 compact_fail      17885      14151      -3734     -21.00
         compact_free_scanned 4204766409 3835994922 -368771487      -9.00
             compact_isolated    3446484    2967618    -478866     -14.00
      compact_migrate_scanned 1621336411 1324695710 -296640701     -19.00
                compact_stall      19387      15343      -4044     -21.00
              compact_success       1502       1192       -310     -21.00
kswapd_high_wmark_hit_quickly        234        184        -50     -22.00
            kswapd_inodesteal     221635     233093      11458       5.00
 kswapd_low_wmark_hit_quickly      66065      54009     -12056     -19.00
                   nr_dirtied     259934     296476      36542      14.00
  nr_vmscan_immediate_reclaim       2587       2356       -231      -9.00
              nr_vmscan_write    1274232    2661733    1387501     108.00
                   nr_written    1514060    2937560    1423500      94.00
                   pageoutrun      67561      55133     -12428     -19.00
                   pgactivate    2335060    1984882    -350178     -15.00
                  pgalloc_dma   13743011   14096463     353452       2.00
              pgalloc_movable          0          0          0       0.00
               pgalloc_normal   18742440   16802065   -1940375     -11.00
                pgalloc_total   32485451   30898528   -1586923      -5.00
                 pgdeactivate    4262210    2930670   -1331540     -32.00
                      pgfault   30812334   31085065     272731       0.00
                       pgfree   33553970   31765164   -1788806      -6.00
                 pginodesteal      33411      15084     -18327     -55.00
                  pglazyfreed          0          0          0       0.00
                   pgmajfault     551312    1508299     956987     173.00
               pgmigrate_fail      43927      29330     -14597     -34.00
            pgmigrate_success    1399851    1203922    -195929     -14.00
                       pgpgin   24141776   19032156   -5109620     -22.00
                      pgpgout     959344    1103316     143972      15.00
                 pgpgoutclean    4639732    3765868    -873864     -19.00
                     pgrefill    4884560    3006938   -1877622     -39.00
                    pgrotated      37828      25897     -11931     -32.00
                pgscan_direct    1456037     957567    -498470     -35.00
       pgscan_direct_throttle          0          0          0       0.00
                pgscan_kswapd    6667767    5047360   -1620407     -25.00
                 pgscan_total    8123804    6004927   -2118877     -27.00
                   pgskip_dma          0          0          0       0.00
               pgskip_movable          0          0          0       0.00
                pgskip_normal      14907      25382      10475      70.00
                 pgskip_total      14907      25382      10475      70.00
               pgsteal_direct    1118986     690215    -428771     -39.00
               pgsteal_kswapd    4750223    3657107   -1093116     -24.00
                pgsteal_total    5869209    4347322   -1521887     -26.00
                       pswpin     417613    1392647     975034     233.00
                      pswpout    1274224    2661731    1387507     108.00
                slabs_scanned   13686905   10807200   -2879705     -22.00
          workingset_activate     668966     569444     -99522     -15.00
       workingset_nodereclaim      38957      32621      -6336     -17.00
           workingset_refault    2816795    2179782    -637013     -23.00
           workingset_restore     294320     168601    -125719     -43.00

pgmajfault is increased by 173% because swapin is increased by 200% by process_madvise hint. However, swap read based on zram is much cheaper than file IO in performance point of view and app hot start by swapin is also cheaper than cold start from the beginning of app which needs many IO from storage and initialization steps.

This patchset is against on next-20190517.

Minchan Kim (7):
mm: introduce MADV_COOL
mm: change PAGEREF_RECLAIM_CLEAN with PAGE_REFRECLAIM
mm: introduce MADV_COLD
mm: factor out madvise's core functionality
mm: introduce external memory hinting API
mm: extend process_madvise syscall to support vector arrary
mm: madvise support MADV_ANONYMOUS_FILTER and MADV_FILE_FILTER

 arch/x86/entry/syscalls/syscall_32.tbl |   1 +
 arch/x86/entry/syscalls/syscall_64.tbl |   1 +
 include/linux/page-flags.h             |   1 +
 include/linux/page_idle.h              |  15 +
 include/linux/proc_fs.h                |   1 +
 include/linux/swap.h                   |   2 +
 include/linux/syscalls.h               |   2 +
 include/uapi/asm-generic/mman-common.h |  12 +
 include/uapi/asm-generic/unistd.h      |   2 +
 kernel/signal.c                        |   2 +-
 kernel/sys_ni.c                        |   1 +
 mm/madvise.c                           | 600 +++++++++++++++++++++----
 mm/swap.c                              |  43 ++
 mm/vmscan.c                            |  80 +++-
 14 files changed, 680 insertions(+), 83 deletions(-)

--
2.21.0.1020.gf2820cf01a-goog