mm: fix race between MADV_FREE reclaim and blkdev direct IO read
Subsystems (5)
PATCH v2 1/1 mm: fix race between MADV_FREE reclaim and blkdev direct IO read
Problem:
=======
Userspace might read the zero-page instead of actual data from a direct IO read on a block device if the buffers have been called madvise(MADV_FREE) on earlier (this is discussed below) due to a race between page reclaim on MADV_FREE and blkdev direct IO read.
Race condition:
==============
During page reclaim, the MADV_FREE page check in try_to_unmap_one() checks if the page is not dirty, then discards its PTE (vs remap it back if the page is dirty).
However, after try_to_unmap_one() returns to shrink_page_list(), it might keep the page _anyway_ if page_ref_freeze() fails (it expects a single page ref from the isolation).
Well, blkdev_direct_IO() gets references for all pages, and on READ operations it sets them dirty later.
So, if MADV_FREE pages (i.e., not dirty) are used as buffers (more later) for direct IO read from block devices and page reclaim runs during __blkdev_direct_IO[_simple]() AFTER bio_iov_iter_get_pages() but BEFORE it sets pages dirty, that situation happens.
The direct IO read eventually completes. Now, when userspace reads the buffers, the PTE is no longer there and the page fault handler do_anonymous_page() services that with the zero-page, NOT the data!
A synthetic reproducer is provided.
Page faults:
===========
The data read from the block device probably won't generate faults due to DMA (no MMU) but even in the case it wouldn't use DMA, that happens on different virtual addresses (not user-mapped addresses) because struct bio_vec stores struct page to figure addresses out (which are different from/unrelated to user-mapped addresses) for the data read.
Thus userspace reads (to user-mapped addresses) still fault, then do_anonymous_page() gets another struct page that would address/ map to other memory than the struct page used by struct bio_vec for the read (which runs correctly as the page wasn't freed due to page_ref_freeze(), and is reclaimed later) -- but even if the page addresses matched, that handler maps the zero-page in the PTE, not that page's memory (on read faults.)
If page reclaim happens BEFORE bio_iov_iter_get_pages() the issue doesn't happen, because that faults-in all pages as writeable, so do_anonymous_page() sets up a new page/rmap/PTE, and that is used by direct IO. The userspace reads don't fault as the PTE is there (thus zero-page is not used.)
Solution:
========
One solution is to check for the expected page reference count in try_to_unmap_one() too, which should be exactly two: one from the isolation (checked by shrink_page_list()), and the other from the rmap (dropped by the discard: label). If that doesn't match, then remap the PTE back, just like page dirty does.
The new check in try_to_unmap_one() should be safe in races with bio_iov_iter_get_pages() in get_user_pages() fast and slow paths, as it's done under the PTE lock. The fast path doesn't take that lock but it checks the PTE has changed, then drops the reference and leaves the page for the slow path (which does take that lock).
- try_to_unmap_one()
- page_vma_mapped_walk()
- map_pte() # see pte_offset_map_lock():
pte_offset_map()
spin_lock()
- page_ref_count() # new check
- page_vma_mapped_walk_done() # see pte_unmap_unlock():
pte_unmap()
spin_unlock()- bio_iov_iter_get_pages()
- __bio_iov_iter_get_pages()
- iov_iter_get_pages()
- get_user_pages_fast()
- internal_get_user_pages_fast()
# fast path
- lockless_pages_from_mm()
- gup_{pgd,p4d,pud,pmd,pte}_range() ptep = pte_offset_map() # not _lock() pte = ptep_get_lockless(ptep) page = pte_page(pte) try_grab_compound_head(page) # get ref if (pte_val(pte) != pte_val(*ptep)) put_compound_head(page) # put ref # leave page for slow path
# slow path
- __gup_longterm_unlocked()
- get_user_pages_unlocked()
- __get_user_pages_locked()
- __get_user_pages()
- follow_{page,p4d,pud,pmd}_mask()
- follow_page_pte()
ptep = pte_offset_map_lock() pte = *ptep
page = vm_normal_page(pte) try_grab_page(page) # get ref pte_unmap_unlock()
Regarding transparent hugepages, that number shouldn't change, as MADV_FREE (aka lazyfree) pages are PageAnon() && !PageSwapBacked() (madvise_free_pte_range() -> mark_page_lazyfree() -> lru_lazyfree_fn()) thus should reach shrink_page_list() -> split_huge_page_to_list() before try_to_unmap[_one](), so it deals with normal pages only.
(And in case unlikely/TTU_SPLIT_HUGE_PMD/split_huge_pmd_address() happens, which it should not or be rare, the page refcount is not two, as the head page counts tail pages, and tail pages have zero. That also prevents checking the head page then incorrectly call page_remove_rmap(subpage) for a tail page, that isn't even in the shrink_page_list()'s page_list (an effect of split huge pmd/pmvw), as it might happen today in this unlikely scenario.)
MADV_FREE'd buffers:
===================
So, back to the "if MADV_FREE pages are used as buffers" note. The case is arguable, and subject to multiple interpretations.
The madvise(2) manual page on the MADV_FREE advice value says:
- 'After a successful MADV_FREE ... data will be lost when the kernel frees the pages.'
- 'the free operation will be canceled if the caller writes into the page' / 'subsequent writes ... will succeed and then [the] kernel cannot free those dirtied pages'
- 'If there is no subsequent write, the kernel can free the pages at any time.'
Thoughts, questions, considerations...
- Since the kernel didn't actually free the page (page_ref_freeze() failed), should the data not have been lost? (on userspace read.)
- Should writes performed by the direct IO read be able to cancel the free operation?
- Should the direct IO read be considered as 'the caller' too, as it's been requested by 'the caller'?
- Should the bio technique to dirty pages on return to userspace (bio_check_pages_dirty() is called/used by __blkdev_direct_IO()) be considered in another/special way here?
- Should an upcoming write from a previously requested direct IO read be considered as a subsequent write, so the kernel should not free the pages? (as it's known at the time of page reclaim.)
Technically, the last point would seem a reasonable consideration and balance, as the madvise(2) manual page apparently (and fairly) seem to assume that 'writes' are memory access from the userspace process (not explicitly considering writes from the kernel or its corner cases; again, fairly).. plus the kernel fix implementation for the corner case of the largely 'non-atomic write' encompassed by a direct IO read operation, is relatively simple; and it helps.
Reproducer:
==========
@ test.c (simplified, but works)
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
int main() {
int fd, i;
char *buf;
fd = open(DEV, O_RDONLY | O_DIRECT);
buf = mmap(NULL, BUF_SIZE, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
for (i = 0; i < BUF_SIZE; i += PAGE_SIZE)
buf[i] = 1; // init to non-zero
madvise(buf, BUF_SIZE, MADV_FREE);
read(fd, buf, BUF_SIZE);
for (i = 0; i < BUF_SIZE; i += PAGE_SIZE)
printf("%p: 0x%x\n", &buf[i], buf[i]);
return 0;
}@ block/fops.c (formerly fs/block_dev.c)
+#include <linux/swap.h>
...
... __blkdev_direct_IO[_simple](...)
{
...
+ if (!strcmp(current->comm, "good"))
+ shrink_all_memory(ULONG_MAX);
+
ret = bio_iov_iter_get_pages(...);
+
+ if (!strcmp(current->comm, "bad"))
+ shrink_all_memory(ULONG_MAX);
...
}@ shell
# yes | dd of=test.img bs=1k count=16 # DEV=$(losetup -f --show test.img) # gcc -DDEV=\"$DEV\" -DBUF_SIZE=16384 -DPAGE_SIZE=4096 test.c -o test
# od -tx1 $DEV 0000000 79 0a 79 0a 79 0a 79 0a 79 0a 79 0a 79 0a 79 0a * 0040000
# mv test good # ./good 0x7f1509206000: 0x79 0x7f1509207000: 0x79 0x7f1509208000: 0x79 0x7f1509209000: 0x79
# mv good bad # ./bad 0x7fd87272f000: 0x0 0x7fd872730000: 0x0 0x7fd872731000: 0x0 0x7fd872732000: 0x0
Ceph/TCMalloc:
=============
For documentation purposes, the use case driving the analysis/fix is Ceph on Ubuntu 18.04, as the TCMalloc library there still uses MADV_FREE to release unused memory to the system from the mmap'ed page heap (might be committed back/used again; it's not munmap'ed.)
- PageHeap::DecommitSpan() -> TCMalloc_SystemRelease() -> madvise()
- PageHeap::CommitSpan() -> TCMalloc_SystemCommit() -> do nothing.
Note: TCMalloc switched back to MADV_DONTNEED a few commits after the release in Ubuntu 18.04 (google-perftools/gperftools 2.5), so the issue just 'disappeared' on Ceph on later Ubuntu releases but is still present in the kernel, and can be hit by other use cases.
The observed issue seems to be the old Ceph bug #22464 [1], where checksum mismatches are observed (and instrumentation with buffer dumps shows zero-pages read from mmap'ed/MADV_FREE'd page ranges).
The issue in Ceph was reasonably deemed a kernel bug (comment #50) and mostly worked around with a retry mechanism, but other parts of Ceph could still hit that (rocksdb). Anyway, it's less likely to be hit again as TCMalloc switched out of MADV_FREE by default.
(Some kernel versions/reports from the Ceph bug, and relation with the MADV_FREE introduction/changes; TCMalloc versions not checked.)
- 4.4 good
- 4.5 (madv_free: introduction)
- 4.9 bad
- 4.10 good? maybe a swapless system
- 4.12 (madv_free: no longer free instantly on swapless systems)
- 4.13 bad
[1] https://tracker.ceph.com/issues/22464
Thanks:
======
Several people contributed to analysis/discussions/tests/reproducers in the first stages when drilling down on ceph/tcmalloc/linux kernel:
- Dan Hill <[email protected]>
- Dan Streetman <[email protected]>
- Dongdong Tao <[email protected]>
- Gavin Guo <[email protected]>
- Gerald Yang <[email protected]>
- Heitor Alves de Siqueira <[email protected]>
- Ioanna Alifieraki <[email protected]>
- Jay Vosburgh <[email protected]>
- Matthew Ruffell <[email protected]>
- Ponnuvel Palaniyappan <[email protected]>
v2: check refcount against mapcount rather than a static 2.
Thanks: Minchan Kim <[email protected]>
--- mm/rmap.c | 15 ++++++++++++++- mm/vmscan.c | 2 +- 2 files changed, 15 insertions(+), 2 deletions(-)
mm/rmap.c +14 -1
@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* +* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {/* Invalidate as we cleared the pte */ mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );
mm/vmscan.c +1 -1
@@ -1688,7 +1688,7 @@ static unsigned int shrink_page_list(struct list_head *page_list, mapping =page_mapping (page); } }else if (unlikely (PageTransHuge (page))) { -/* Split file THP */ +/* Split file/lazyfree THP */ if (split_huge_page_to_list (page, page_list)) goto keep_locked; }
Signature · 1 line
2.32.0
Quoted 311 lines · Mauricio Faria de Oliveira
Problem:
=======Userspace might read the zero-page instead of actual data from a direct IO read on a block device if the buffers have been called
madvise(MADV_FREE)on earlier (this is discussed below) due to a race between page reclaim onMADV_FREEand blkdev direct IO read.Race condition:
==============During page reclaim, the
MADV_FREEpage check intry_to_unmap_one()checks if the page is not dirty, then discards its PTE (vs remap it back if the page is dirty).However, after
try_to_unmap_one()returns toshrink_page_list(), it might keep the page _anyway_ ifpage_ref_freeze()fails (it expects a single page ref from the isolation).Well,
blkdev_direct_IO()gets references for all pages, and on READ operations it sets them dirty later.So, if
MADV_FREEpages (i.e., not dirty) are used as buffers (more later) for direct IO read from block devices and page reclaim runs during __blkdev_direct_IO[_simple]() AFTERbio_iov_iter_get_pages()but BEFORE it sets pages dirty, that situation happens.The direct IO read eventually completes. Now, when userspace reads the buffers, the PTE is no longer there and the page fault handler
do_anonymous_page()services that with the zero-page, NOT the data!A synthetic reproducer is provided.
Page faults:
===========The data read from the block device probably won't generate faults due to DMA (no MMU) but even in the case it wouldn't use DMA, that happens on different virtual addresses (not user-mapped addresses) because
struct bio_vecstoresstruct pageto figure addresses out (which are different from/unrelated to user-mapped addresses) for the data read.Thus userspace reads (to user-mapped addresses) still fault, then
do_anonymous_page()gets anotherstruct pagethat would address/ map to other memory than thestruct pageused bystruct bio_vecfor the read (which runs correctly as the page wasn't freed due topage_ref_freeze(), and is reclaimed later) -- but even if the page addresses matched, that handler maps the zero-page in the PTE, not that page's memory (on read faults.)If page reclaim happens BEFORE
bio_iov_iter_get_pages()the issue doesn't happen, because that faults-in all pages as writeable, sodo_anonymous_page()sets up a new page/rmap/PTE, and that is used by direct IO. The userspace reads don't fault as the PTE is there (thus zero-page is not used.)Solution:
========One solution is to check for the expected page reference count in
try_to_unmap_one()too, which should be exactly two: one from the isolation (checked byshrink_page_list()), and the other from the rmap (dropped by the discard: label). If that doesn't match, then remap the PTE back, just like page dirty does.The new check in
try_to_unmap_one()should be safe in races withbio_iov_iter_get_pages()inget_user_pages()fast and slow paths, as it's done under the PTE lock. The fast path doesn't take that lock but it checks the PTE has changed, then drops the reference and leaves the page for the slow path (which does take that lock).-
try_to_unmap_one()
-page_vma_mapped_walk()
-map_pte()# seepte_offset_map_lock():
pte_offset_map()
spin_lock()
-page_ref_count()# new check
-page_vma_mapped_walk_done()# seepte_unmap_unlock():pte_unmap() spin_unlock()-
bio_iov_iter_get_pages()
-__bio_iov_iter_get_pages()
-iov_iter_get_pages()
-get_user_pages_fast()
-internal_get_user_pages_fast()# fast path
-lockless_pages_from_mm()
- gup_{pgd,p4d,pud,pmd,pte}_range() ptep =pte_offset_map()# not_lock()pte =ptep_get_lockless(ptep)page =pte_page(pte)try_grab_compound_head(page)# get ref if (pte_val(pte)!=pte_val(*ptep))put_compound_head(page)# put ref # leave page for slow path
# slow path
-__gup_longterm_unlocked()
-get_user_pages_unlocked()
-__get_user_pages_locked()
-__get_user_pages()
- follow_{page,p4d,pud,pmd}_mask()
-follow_page_pte()
ptep =pte_offset_map_lock()pte = *ptep
page =vm_normal_page(pte)try_grab_page(page)# get refpte_unmap_unlock()Regarding transparent hugepages, that number shouldn't change, as
MADV_FREE(aka lazyfree) pages arePageAnon()&& !PageSwapBacked() (madvise_free_pte_range()->mark_page_lazyfree()->lru_lazyfree_fn()) thus should reachshrink_page_list()->split_huge_page_to_list()before try_to_unmap[_one](), so it deals with normal pages only.(And in case unlikely/TTU_SPLIT_HUGE_PMD/split_huge_pmd_address() happens, which it should not or be rare, the page refcount is not two, as the head page counts tail pages, and tail pages have zero. That also prevents checking the head
pagethen incorrectly callpage_remove_rmap(subpage)for a tail page, that isn't even in the shrink_page_list()'spage_list(an effect of split huge pmd/pmvw), as it might happen today in this unlikely scenario.)MADV_FREE'd buffers:
===================So, back to the "if
MADV_FREEpages are used as buffers" note. The case is arguable, and subject to multiple interpretations.The madvise(2) manual page on the
MADV_FREEadvice value says:
- 'After a successfulMADV_FREE... data will be lost when the kernel frees the pages.'
- 'the free operation will be canceled if the caller writes into the page' / 'subsequent writes ... will succeed and then [the] kernel cannot free those dirtied pages'
- 'If there is no subsequent write, the kernel can free the pages at any time.'Thoughts, questions, considerations...
- Since the kernel didn't actually free the page (page_ref_freeze()failed), should the data not have been lost? (on userspace read.)
- Should writes performed by the direct IO read be able to cancel the free operation?
- Should the direct IO read be considered as 'the caller' too, as it's been requested by 'the caller'?
- Should the bio technique to dirty pages on return to userspace (bio_check_pages_dirty()is called/used by__blkdev_direct_IO()) be considered in another/special way here?
- Should an upcoming write from a previously requested direct IO read be considered as a subsequent write, so the kernel should not free the pages? (as it's known at the time of page reclaim.)Technically, the last point would seem a reasonable consideration and balance, as the madvise(2) manual page apparently (and fairly) seem to assume that 'writes' are memory access from the userspace process (not explicitly considering writes from the kernel or its corner cases; again, fairly).. plus the kernel fix implementation for the corner case of the largely 'non-atomic write' encompassed by a direct IO read operation, is relatively simple; and it helps.
Reproducer:
==========@
test.c(simplified, but works)#define _GNU_SOURCE #include <fcntl.h> #include <stdio.h> #include <unistd.h> #include <sys/mman.h> int main() { int fd, i; char *buf; fd = open(DEV, O_RDONLY | O_DIRECT); buf = mmap(NULL, BUF_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); for (i = 0; i < BUF_SIZE; i += PAGE_SIZE) buf[i] = 1; // init to non-zero madvise(buf, BUF_SIZE, MADV_FREE); read(fd, buf, BUF_SIZE); for (i = 0; i < BUF_SIZE; i += PAGE_SIZE) printf("%p: 0x%x\n", &buf[i], buf[i]); return 0; }@
block/fops.c(formerlyfs/block_dev.c)+#include <linux/swap.h> ... ... __blkdev_direct_IO[_simple](...) { ... + if (!strcmp(current->comm, "good")) + shrink_all_memory(ULONG_MAX); + ret = bio_iov_iter_get_pages(...); + + if (!strcmp(current->comm, "bad")) + shrink_all_memory(ULONG_MAX); ... }@ shell
# yes | dd of=test.img bs=1k count=16 # DEV=$(losetup -f --show test.img) # gcc -DDEV=\"$DEV\" -DBUF_SIZE=16384 -DPAGE_SIZE=4096 test.c -o test# od -tx1 $DEV 0000000 79 0a 79 0a 79 0a 79 0a 79 0a 79 0a 79 0a 79 0a * 0040000# mv test good # ./good 0x7f1509206000: 0x79 0x7f1509207000: 0x79 0x7f1509208000: 0x79 0x7f1509209000: 0x79# mv good bad # ./bad 0x7fd87272f000: 0x0 0x7fd872730000: 0x0 0x7fd872731000: 0x0 0x7fd872732000: 0x0Ceph/TCMalloc:
=============For documentation purposes, the use case driving the analysis/fix is Ceph on Ubuntu 18.04, as the TCMalloc library there still uses
MADV_FREEto release unused memory to the system from the mmap'ed page heap (might be committed back/used again; it's not munmap'ed.)
-PageHeap::DecommitSpan()->TCMalloc_SystemRelease()->madvise()
-PageHeap::CommitSpan()->TCMalloc_SystemCommit()-> do nothing.Note: TCMalloc switched back to
MADV_DONTNEEDa few commits after the release in Ubuntu 18.04 (google-perftools/gperftools 2.5), so the issue just 'disappeared' on Ceph on later Ubuntu releases but is still present in the kernel, and can be hit by other use cases.The observed issue seems to be the old Ceph bug #22464 [1], where checksum mismatches are observed (and instrumentation with buffer dumps shows zero-pages read from mmap'ed/MADV_FREE'd page ranges).
The issue in Ceph was reasonably deemed a kernel bug (comment #50) and mostly worked around with a retry mechanism, but other parts of Ceph could still hit that (rocksdb). Anyway, it's less likely to be hit again as TCMalloc switched out of
MADV_FREEby default.(Some kernel versions/reports from the Ceph bug, and relation with the
MADV_FREEintroduction/changes; TCMalloc versions not checked.)
- 4.4 good
- 4.5 (madv_free: introduction)
- 4.9 bad
- 4.10 good? maybe a swapless system
- 4.12 (madv_free: no longer free instantly on swapless systems)
- 4.13 bad[1] https://tracker.ceph.com/issues/22464
Thanks:
======Several people contributed to analysis/discussions/tests/reproducers in the first stages when drilling down on ceph/tcmalloc/linux kernel:
- Dan Hill <[email protected]>
- Dan Streetman <[email protected]>
- Dongdong Tao <[email protected]>
- Gavin Guo <[email protected]>
- Gerald Yang <[email protected]>
- Heitor Alves de Siqueira <[email protected]>
- Ioanna Alifieraki <[email protected]>
- Jay Vosburgh <[email protected]>
- Matthew Ruffell <[email protected]>
- Ponnuvel Palaniyappan <[email protected]>v2: check refcount against mapcount rather than a static 2.
Thanks: Minchan Kim <[email protected]>Signed-off-by Mauricio Faria de Oliveira <[email protected]>--- mm/rmap.c | 15 ++++++++++++++- mm/vmscan.c | 2 +- 2 files changed, 15 insertions(+), 2 deletions(-)mm/rmap.c +4
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/*
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1586
Quoted 10 lines
mm/rmap.c +10
-0+* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {
Thanks. Looks good to me.
I'd like to invite more folks for better eyes since this could be a rather subtle issue.
Quoted 326 lines · Minchan Kim
Quoted 311 lines · Mauricio Faria de Oliveira
Problem:
=======Userspace might read the zero-page instead of actual data from a direct IO read on a block device if the buffers have been called
madvise(MADV_FREE)on earlier (this is discussed below) due to a race between page reclaim onMADV_FREEand blkdev direct IO read.Race condition:
==============During page reclaim, the
MADV_FREEpage check intry_to_unmap_one()checks if the page is not dirty, then discards its PTE (vs remap it back if the page is dirty).However, after
try_to_unmap_one()returns toshrink_page_list(), it might keep the page _anyway_ ifpage_ref_freeze()fails (it expects a single page ref from the isolation).Well,
blkdev_direct_IO()gets references for all pages, and on READ operations it sets them dirty later.So, if
MADV_FREEpages (i.e., not dirty) are used as buffers (more later) for direct IO read from block devices and page reclaim runs during __blkdev_direct_IO[_simple]() AFTERbio_iov_iter_get_pages()but BEFORE it sets pages dirty, that situation happens.The direct IO read eventually completes. Now, when userspace reads the buffers, the PTE is no longer there and the page fault handler
do_anonymous_page()services that with the zero-page, NOT the data!A synthetic reproducer is provided.
Page faults:
===========The data read from the block device probably won't generate faults due to DMA (no MMU) but even in the case it wouldn't use DMA, that happens on different virtual addresses (not user-mapped addresses) because
struct bio_vecstoresstruct pageto figure addresses out (which are different from/unrelated to user-mapped addresses) for the data read.Thus userspace reads (to user-mapped addresses) still fault, then
do_anonymous_page()gets anotherstruct pagethat would address/ map to other memory than thestruct pageused bystruct bio_vecfor the read (which runs correctly as the page wasn't freed due topage_ref_freeze(), and is reclaimed later) -- but even if the page addresses matched, that handler maps the zero-page in the PTE, not that page's memory (on read faults.)If page reclaim happens BEFORE
bio_iov_iter_get_pages()the issue doesn't happen, because that faults-in all pages as writeable, sodo_anonymous_page()sets up a new page/rmap/PTE, and that is used by direct IO. The userspace reads don't fault as the PTE is there (thus zero-page is not used.)Solution:
========One solution is to check for the expected page reference count in
try_to_unmap_one()too, which should be exactly two: one from the isolation (checked byshrink_page_list()), and the other from the rmap (dropped by the discard: label). If that doesn't match, then remap the PTE back, just like page dirty does.The new check in
try_to_unmap_one()should be safe in races withbio_iov_iter_get_pages()inget_user_pages()fast and slow paths, as it's done under the PTE lock. The fast path doesn't take that lock but it checks the PTE has changed, then drops the reference and leaves the page for the slow path (which does take that lock).-
try_to_unmap_one()
-page_vma_mapped_walk()
-map_pte()# seepte_offset_map_lock():
pte_offset_map()
spin_lock()
-page_ref_count()# new check
-page_vma_mapped_walk_done()# seepte_unmap_unlock():pte_unmap() spin_unlock()-
bio_iov_iter_get_pages()
-__bio_iov_iter_get_pages()
-iov_iter_get_pages()
-get_user_pages_fast()
-internal_get_user_pages_fast()# fast path
-lockless_pages_from_mm()
- gup_{pgd,p4d,pud,pmd,pte}_range() ptep =pte_offset_map()# not_lock()pte =ptep_get_lockless(ptep)page =pte_page(pte)try_grab_compound_head(page)# get ref if (pte_val(pte)!=pte_val(*ptep))put_compound_head(page)# put ref # leave page for slow path
# slow path
-__gup_longterm_unlocked()
-get_user_pages_unlocked()
-__get_user_pages_locked()
-__get_user_pages()
- follow_{page,p4d,pud,pmd}_mask()
-follow_page_pte()
ptep =pte_offset_map_lock()pte = *ptep
page =vm_normal_page(pte)try_grab_page(page)# get refpte_unmap_unlock()Regarding transparent hugepages, that number shouldn't change, as
MADV_FREE(aka lazyfree) pages arePageAnon()&& !PageSwapBacked() (madvise_free_pte_range()->mark_page_lazyfree()->lru_lazyfree_fn()) thus should reachshrink_page_list()->split_huge_page_to_list()before try_to_unmap[_one](), so it deals with normal pages only.(And in case unlikely/TTU_SPLIT_HUGE_PMD/split_huge_pmd_address() happens, which it should not or be rare, the page refcount is not two, as the head page counts tail pages, and tail pages have zero. That also prevents checking the head
pagethen incorrectly callpage_remove_rmap(subpage)for a tail page, that isn't even in the shrink_page_list()'spage_list(an effect of split huge pmd/pmvw), as it might happen today in this unlikely scenario.)MADV_FREE'd buffers:
===================So, back to the "if
MADV_FREEpages are used as buffers" note. The case is arguable, and subject to multiple interpretations.The madvise(2) manual page on the
MADV_FREEadvice value says:
- 'After a successfulMADV_FREE... data will be lost when the kernel frees the pages.'
- 'the free operation will be canceled if the caller writes into the page' / 'subsequent writes ... will succeed and then [the] kernel cannot free those dirtied pages'
- 'If there is no subsequent write, the kernel can free the pages at any time.'Thoughts, questions, considerations...
- Since the kernel didn't actually free the page (page_ref_freeze()failed), should the data not have been lost? (on userspace read.)
- Should writes performed by the direct IO read be able to cancel the free operation?
- Should the direct IO read be considered as 'the caller' too, as it's been requested by 'the caller'?
- Should the bio technique to dirty pages on return to userspace (bio_check_pages_dirty()is called/used by__blkdev_direct_IO()) be considered in another/special way here?
- Should an upcoming write from a previously requested direct IO read be considered as a subsequent write, so the kernel should not free the pages? (as it's known at the time of page reclaim.)Technically, the last point would seem a reasonable consideration and balance, as the madvise(2) manual page apparently (and fairly) seem to assume that 'writes' are memory access from the userspace process (not explicitly considering writes from the kernel or its corner cases; again, fairly).. plus the kernel fix implementation for the corner case of the largely 'non-atomic write' encompassed by a direct IO read operation, is relatively simple; and it helps.
Reproducer:
==========@
test.c(simplified, but works)#define _GNU_SOURCE #include <fcntl.h> #include <stdio.h> #include <unistd.h> #include <sys/mman.h> int main() { int fd, i; char *buf; fd = open(DEV, O_RDONLY | O_DIRECT); buf = mmap(NULL, BUF_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); for (i = 0; i < BUF_SIZE; i += PAGE_SIZE) buf[i] = 1; // init to non-zero madvise(buf, BUF_SIZE, MADV_FREE); read(fd, buf, BUF_SIZE); for (i = 0; i < BUF_SIZE; i += PAGE_SIZE) printf("%p: 0x%x\n", &buf[i], buf[i]); return 0; }@
block/fops.c(formerlyfs/block_dev.c)+#include <linux/swap.h> ... ... __blkdev_direct_IO[_simple](...) { ... + if (!strcmp(current->comm, "good")) + shrink_all_memory(ULONG_MAX); + ret = bio_iov_iter_get_pages(...); + + if (!strcmp(current->comm, "bad")) + shrink_all_memory(ULONG_MAX); ... }@ shell
# yes | dd of=test.img bs=1k count=16 # DEV=$(losetup -f --show test.img) # gcc -DDEV=\"$DEV\" -DBUF_SIZE=16384 -DPAGE_SIZE=4096 test.c -o test# od -tx1 $DEV 0000000 79 0a 79 0a 79 0a 79 0a 79 0a 79 0a 79 0a 79 0a * 0040000# mv test good # ./good 0x7f1509206000: 0x79 0x7f1509207000: 0x79 0x7f1509208000: 0x79 0x7f1509209000: 0x79# mv good bad # ./bad 0x7fd87272f000: 0x0 0x7fd872730000: 0x0 0x7fd872731000: 0x0 0x7fd872732000: 0x0Ceph/TCMalloc:
=============For documentation purposes, the use case driving the analysis/fix is Ceph on Ubuntu 18.04, as the TCMalloc library there still uses
MADV_FREEto release unused memory to the system from the mmap'ed page heap (might be committed back/used again; it's not munmap'ed.)
-PageHeap::DecommitSpan()->TCMalloc_SystemRelease()->madvise()
-PageHeap::CommitSpan()->TCMalloc_SystemCommit()-> do nothing.Note: TCMalloc switched back to
MADV_DONTNEEDa few commits after the release in Ubuntu 18.04 (google-perftools/gperftools 2.5), so the issue just 'disappeared' on Ceph on later Ubuntu releases but is still present in the kernel, and can be hit by other use cases.The observed issue seems to be the old Ceph bug #22464 [1], where checksum mismatches are observed (and instrumentation with buffer dumps shows zero-pages read from mmap'ed/MADV_FREE'd page ranges).
The issue in Ceph was reasonably deemed a kernel bug (comment #50) and mostly worked around with a retry mechanism, but other parts of Ceph could still hit that (rocksdb). Anyway, it's less likely to be hit again as TCMalloc switched out of
MADV_FREEby default.(Some kernel versions/reports from the Ceph bug, and relation with the
MADV_FREEintroduction/changes; TCMalloc versions not checked.)
- 4.4 good
- 4.5 (madv_free: introduction)
- 4.9 bad
- 4.10 good? maybe a swapless system
- 4.12 (madv_free: no longer free instantly on swapless systems)
- 4.13 bad[1] https://tracker.ceph.com/issues/22464
Thanks:
======Several people contributed to analysis/discussions/tests/reproducers in the first stages when drilling down on ceph/tcmalloc/linux kernel:
- Dan Hill <[email protected]>
- Dan Streetman <[email protected]>
- Dongdong Tao <[email protected]>
- Gavin Guo <[email protected]>
- Gerald Yang <[email protected]>
- Heitor Alves de Siqueira <[email protected]>
- Ioanna Alifieraki <[email protected]>
- Jay Vosburgh <[email protected]>
- Matthew Ruffell <[email protected]>
- Ponnuvel Palaniyappan <[email protected]>v2: check refcount against mapcount rather than a static 2.
Thanks: Minchan Kim <[email protected]>Signed-off-by Mauricio Faria de Oliveira <[email protected]>--- mm/rmap.c | 15 ++++++++++++++- mm/vmscan.c | 2 +- 2 files changed, 15 insertions(+), 2 deletions(-)mm/rmap.c +4
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1586
Quoted 10 lines
mm/rmap.c +10
-0+* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {Thanks. Looks good to me.
Quoted 2 lines
I'd like to invite more folks for better eyes since this could be a rather subtle issue.
I don't spot anything wrong either. But I'm wondering if we could remove the PageDirty check or not.
It seems racy to have MADV_FREE solely rely on PageDirty bit to tell if the page is going to be redirtied or re-accessed or not. The pge refcount itself should be enough. As long as elevated refcount is observed we know this page is going to be or has been re-accessed by someone (particularly, fast GUP). The PageDirty bit may be set much later, just like what the commit log said.
But I'm not quite sure if there is any path that sets PageDirty bit then elevates refcount, TBH I don't look very hard.
Quoted 328 lines · Yang Shi
Quoted 326 lines · Minchan Kim
Quoted 311 lines · Mauricio Faria de Oliveira
Problem:
=======Userspace might read the zero-page instead of actual data from a direct IO read on a block device if the buffers have been called
madvise(MADV_FREE)on earlier (this is discussed below) due to a race between page reclaim onMADV_FREEand blkdev direct IO read.Race condition:
==============During page reclaim, the
MADV_FREEpage check intry_to_unmap_one()checks if the page is not dirty, then discards its PTE (vs remap it back if the page is dirty).However, after
try_to_unmap_one()returns toshrink_page_list(), it might keep the page _anyway_ ifpage_ref_freeze()fails (it expects a single page ref from the isolation).Well,
blkdev_direct_IO()gets references for all pages, and on READ operations it sets them dirty later.So, if
MADV_FREEpages (i.e., not dirty) are used as buffers (more later) for direct IO read from block devices and page reclaim runs during __blkdev_direct_IO[_simple]() AFTERbio_iov_iter_get_pages()but BEFORE it sets pages dirty, that situation happens.The direct IO read eventually completes. Now, when userspace reads the buffers, the PTE is no longer there and the page fault handler
do_anonymous_page()services that with the zero-page, NOT the data!A synthetic reproducer is provided.
Page faults:
===========The data read from the block device probably won't generate faults due to DMA (no MMU) but even in the case it wouldn't use DMA, that happens on different virtual addresses (not user-mapped addresses) because
struct bio_vecstoresstruct pageto figure addresses out (which are different from/unrelated to user-mapped addresses) for the data read.Thus userspace reads (to user-mapped addresses) still fault, then
do_anonymous_page()gets anotherstruct pagethat would address/ map to other memory than thestruct pageused bystruct bio_vecfor the read (which runs correctly as the page wasn't freed due topage_ref_freeze(), and is reclaimed later) -- but even if the page addresses matched, that handler maps the zero-page in the PTE, not that page's memory (on read faults.)If page reclaim happens BEFORE
bio_iov_iter_get_pages()the issue doesn't happen, because that faults-in all pages as writeable, sodo_anonymous_page()sets up a new page/rmap/PTE, and that is used by direct IO. The userspace reads don't fault as the PTE is there (thus zero-page is not used.)Solution:
========One solution is to check for the expected page reference count in
try_to_unmap_one()too, which should be exactly two: one from the isolation (checked byshrink_page_list()), and the other from the rmap (dropped by the discard: label). If that doesn't match, then remap the PTE back, just like page dirty does.The new check in
try_to_unmap_one()should be safe in races withbio_iov_iter_get_pages()inget_user_pages()fast and slow paths, as it's done under the PTE lock. The fast path doesn't take that lock but it checks the PTE has changed, then drops the reference and leaves the page for the slow path (which does take that lock).-
try_to_unmap_one()
-page_vma_mapped_walk()
-map_pte()# seepte_offset_map_lock():
pte_offset_map()
spin_lock()
-page_ref_count()# new check
-page_vma_mapped_walk_done()# seepte_unmap_unlock():pte_unmap() spin_unlock()-
bio_iov_iter_get_pages()
-__bio_iov_iter_get_pages()
-iov_iter_get_pages()
-get_user_pages_fast()
-internal_get_user_pages_fast()# fast path
-lockless_pages_from_mm()
- gup_{pgd,p4d,pud,pmd,pte}_range() ptep =pte_offset_map()# not_lock()pte =ptep_get_lockless(ptep)page =pte_page(pte)try_grab_compound_head(page)# get ref if (pte_val(pte)!=pte_val(*ptep))put_compound_head(page)# put ref # leave page for slow path
# slow path
-__gup_longterm_unlocked()
-get_user_pages_unlocked()
-__get_user_pages_locked()
-__get_user_pages()
- follow_{page,p4d,pud,pmd}_mask()
-follow_page_pte()
ptep =pte_offset_map_lock()pte = *ptep
page =vm_normal_page(pte)try_grab_page(page)# get refpte_unmap_unlock()Regarding transparent hugepages, that number shouldn't change, as
MADV_FREE(aka lazyfree) pages arePageAnon()&& !PageSwapBacked() (madvise_free_pte_range()->mark_page_lazyfree()->lru_lazyfree_fn()) thus should reachshrink_page_list()->split_huge_page_to_list()before try_to_unmap[_one](), so it deals with normal pages only.(And in case unlikely/TTU_SPLIT_HUGE_PMD/split_huge_pmd_address() happens, which it should not or be rare, the page refcount is not two, as the head page counts tail pages, and tail pages have zero. That also prevents checking the head
pagethen incorrectly callpage_remove_rmap(subpage)for a tail page, that isn't even in the shrink_page_list()'spage_list(an effect of split huge pmd/pmvw), as it might happen today in this unlikely scenario.)MADV_FREE'd buffers:
===================So, back to the "if
MADV_FREEpages are used as buffers" note. The case is arguable, and subject to multiple interpretations.The madvise(2) manual page on the
MADV_FREEadvice value says:
- 'After a successfulMADV_FREE... data will be lost when the kernel frees the pages.'
- 'the free operation will be canceled if the caller writes into the page' / 'subsequent writes ... will succeed and then [the] kernel cannot free those dirtied pages'
- 'If there is no subsequent write, the kernel can free the pages at any time.'Thoughts, questions, considerations...
- Since the kernel didn't actually free the page (page_ref_freeze()failed), should the data not have been lost? (on userspace read.)
- Should writes performed by the direct IO read be able to cancel the free operation?
- Should the direct IO read be considered as 'the caller' too, as it's been requested by 'the caller'?
- Should the bio technique to dirty pages on return to userspace (bio_check_pages_dirty()is called/used by__blkdev_direct_IO()) be considered in another/special way here?
- Should an upcoming write from a previously requested direct IO read be considered as a subsequent write, so the kernel should not free the pages? (as it's known at the time of page reclaim.)Technically, the last point would seem a reasonable consideration and balance, as the madvise(2) manual page apparently (and fairly) seem to assume that 'writes' are memory access from the userspace process (not explicitly considering writes from the kernel or its corner cases; again, fairly).. plus the kernel fix implementation for the corner case of the largely 'non-atomic write' encompassed by a direct IO read operation, is relatively simple; and it helps.
Reproducer:
==========@
test.c(simplified, but works)#define _GNU_SOURCE #include <fcntl.h> #include <stdio.h> #include <unistd.h> #include <sys/mman.h> int main() { int fd, i; char *buf; fd = open(DEV, O_RDONLY | O_DIRECT); buf = mmap(NULL, BUF_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); for (i = 0; i < BUF_SIZE; i += PAGE_SIZE) buf[i] = 1; // init to non-zero madvise(buf, BUF_SIZE, MADV_FREE); read(fd, buf, BUF_SIZE); for (i = 0; i < BUF_SIZE; i += PAGE_SIZE) printf("%p: 0x%x\n", &buf[i], buf[i]); return 0; }@
block/fops.c(formerlyfs/block_dev.c)+#include <linux/swap.h> ... ... __blkdev_direct_IO[_simple](...) { ... + if (!strcmp(current->comm, "good")) + shrink_all_memory(ULONG_MAX); + ret = bio_iov_iter_get_pages(...); + + if (!strcmp(current->comm, "bad")) + shrink_all_memory(ULONG_MAX); ... }@ shell
# yes | dd of=test.img bs=1k count=16 # DEV=$(losetup -f --show test.img) # gcc -DDEV=\"$DEV\" -DBUF_SIZE=16384 -DPAGE_SIZE=4096 test.c -o test# od -tx1 $DEV 0000000 79 0a 79 0a 79 0a 79 0a 79 0a 79 0a 79 0a 79 0a * 0040000# mv test good # ./good 0x7f1509206000: 0x79 0x7f1509207000: 0x79 0x7f1509208000: 0x79 0x7f1509209000: 0x79# mv good bad # ./bad 0x7fd87272f000: 0x0 0x7fd872730000: 0x0 0x7fd872731000: 0x0 0x7fd872732000: 0x0Ceph/TCMalloc:
=============For documentation purposes, the use case driving the analysis/fix is Ceph on Ubuntu 18.04, as the TCMalloc library there still uses
MADV_FREEto release unused memory to the system from the mmap'ed page heap (might be committed back/used again; it's not munmap'ed.)
-PageHeap::DecommitSpan()->TCMalloc_SystemRelease()->madvise()
-PageHeap::CommitSpan()->TCMalloc_SystemCommit()-> do nothing.Note: TCMalloc switched back to
MADV_DONTNEEDa few commits after the release in Ubuntu 18.04 (google-perftools/gperftools 2.5), so the issue just 'disappeared' on Ceph on later Ubuntu releases but is still present in the kernel, and can be hit by other use cases.The observed issue seems to be the old Ceph bug #22464 [1], where checksum mismatches are observed (and instrumentation with buffer dumps shows zero-pages read from mmap'ed/MADV_FREE'd page ranges).
The issue in Ceph was reasonably deemed a kernel bug (comment #50) and mostly worked around with a retry mechanism, but other parts of Ceph could still hit that (rocksdb). Anyway, it's less likely to be hit again as TCMalloc switched out of
MADV_FREEby default.(Some kernel versions/reports from the Ceph bug, and relation with the
MADV_FREEintroduction/changes; TCMalloc versions not checked.)
- 4.4 good
- 4.5 (madv_free: introduction)
- 4.9 bad
- 4.10 good? maybe a swapless system
- 4.12 (madv_free: no longer free instantly on swapless systems)
- 4.13 bad[1] https://tracker.ceph.com/issues/22464
Thanks:
======Several people contributed to analysis/discussions/tests/reproducers in the first stages when drilling down on ceph/tcmalloc/linux kernel:
- Dan Hill <[email protected]>
- Dan Streetman <[email protected]>
- Dongdong Tao <[email protected]>
- Gavin Guo <[email protected]>
- Gerald Yang <[email protected]>
- Heitor Alves de Siqueira <[email protected]>
- Ioanna Alifieraki <[email protected]>
- Jay Vosburgh <[email protected]>
- Matthew Ruffell <[email protected]>
- Ponnuvel Palaniyappan <[email protected]>v2: check refcount against mapcount rather than a static 2.
Thanks: Minchan Kim <[email protected]>Signed-off-by Mauricio Faria de Oliveira <[email protected]>--- mm/rmap.c | 15 ++++++++++++++- mm/vmscan.c | 2 +- 2 files changed, 15 insertions(+), 2 deletions(-)mm/rmap.c +4
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1586
Quoted 10 lines
mm/rmap.c +10
-0+* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {Thanks. Looks good to me.
Quoted 5 lines
Quoted 2 lines
I'd like to invite more folks for better eyes since this could be a rather subtle issue.
I don't spot anything wrong either. But I'm wondering if we could remove the PageDirty check or not.
Sorry, take this back. PageDirty check is still needed since the page could be redirtied even though the refcount is not elevated.
Quoted 10 lines
It seems racy to have
MADV_FREEsolely rely on PageDirty bit to tell if the page is going to be redirtied or re-accessed or not. The pge refcount itself should be enough. As long as elevated refcount is observed we know this page is going to be or has been re-accessed by someone (particularly, fast GUP). The PageDirty bit may be set much later, just like what the commit log said.But I'm not quite sure if there is any path that sets PageDirty bit then elevates refcount, TBH I don't look very hard.
Huang, Ying
Reviewed-byQuoted 325 lines · Minchan Kim
Quoted 311 lines · Mauricio Faria de Oliveira
Problem:
=======Userspace might read the zero-page instead of actual data from a direct IO read on a block device if the buffers have been called
madvise(MADV_FREE)on earlier (this is discussed below) due to a race between page reclaim onMADV_FREEand blkdev direct IO read.Race condition:
==============During page reclaim, the
MADV_FREEpage check intry_to_unmap_one()checks if the page is not dirty, then discards its PTE (vs remap it back if the page is dirty).However, after
try_to_unmap_one()returns toshrink_page_list(), it might keep the page _anyway_ ifpage_ref_freeze()fails (it expects a single page ref from the isolation).Well,
blkdev_direct_IO()gets references for all pages, and on READ operations it sets them dirty later.So, if
MADV_FREEpages (i.e., not dirty) are used as buffers (more later) for direct IO read from block devices and page reclaim runs during __blkdev_direct_IO[_simple]() AFTERbio_iov_iter_get_pages()but BEFORE it sets pages dirty, that situation happens.The direct IO read eventually completes. Now, when userspace reads the buffers, the PTE is no longer there and the page fault handler
do_anonymous_page()services that with the zero-page, NOT the data!A synthetic reproducer is provided.
Page faults:
===========The data read from the block device probably won't generate faults due to DMA (no MMU) but even in the case it wouldn't use DMA, that happens on different virtual addresses (not user-mapped addresses) because
struct bio_vecstoresstruct pageto figure addresses out (which are different from/unrelated to user-mapped addresses) for the data read.Thus userspace reads (to user-mapped addresses) still fault, then
do_anonymous_page()gets anotherstruct pagethat would address/ map to other memory than thestruct pageused bystruct bio_vecfor the read (which runs correctly as the page wasn't freed due topage_ref_freeze(), and is reclaimed later) -- but even if the page addresses matched, that handler maps the zero-page in the PTE, not that page's memory (on read faults.)If page reclaim happens BEFORE
bio_iov_iter_get_pages()the issue doesn't happen, because that faults-in all pages as writeable, sodo_anonymous_page()sets up a new page/rmap/PTE, and that is used by direct IO. The userspace reads don't fault as the PTE is there (thus zero-page is not used.)Solution:
========One solution is to check for the expected page reference count in
try_to_unmap_one()too, which should be exactly two: one from the isolation (checked byshrink_page_list()), and the other from the rmap (dropped by the discard: label). If that doesn't match, then remap the PTE back, just like page dirty does.The new check in
try_to_unmap_one()should be safe in races withbio_iov_iter_get_pages()inget_user_pages()fast and slow paths, as it's done under the PTE lock. The fast path doesn't take that lock but it checks the PTE has changed, then drops the reference and leaves the page for the slow path (which does take that lock).-
try_to_unmap_one()
-page_vma_mapped_walk()
-map_pte()# seepte_offset_map_lock():
pte_offset_map()
spin_lock()
-page_ref_count()# new check
-page_vma_mapped_walk_done()# seepte_unmap_unlock():pte_unmap() spin_unlock()-
bio_iov_iter_get_pages()
-__bio_iov_iter_get_pages()
-iov_iter_get_pages()
-get_user_pages_fast()
-internal_get_user_pages_fast()# fast path
-lockless_pages_from_mm()
- gup_{pgd,p4d,pud,pmd,pte}_range() ptep =pte_offset_map()# not_lock()pte =ptep_get_lockless(ptep)page =pte_page(pte)try_grab_compound_head(page)# get ref if (pte_val(pte)!=pte_val(*ptep))put_compound_head(page)# put ref # leave page for slow path
# slow path
-__gup_longterm_unlocked()
-get_user_pages_unlocked()
-__get_user_pages_locked()
-__get_user_pages()
- follow_{page,p4d,pud,pmd}_mask()
-follow_page_pte()
ptep =pte_offset_map_lock()pte = *ptep
page =vm_normal_page(pte)try_grab_page(page)# get refpte_unmap_unlock()Regarding transparent hugepages, that number shouldn't change, as
MADV_FREE(aka lazyfree) pages arePageAnon()&& !PageSwapBacked() (madvise_free_pte_range()->mark_page_lazyfree()->lru_lazyfree_fn()) thus should reachshrink_page_list()->split_huge_page_to_list()before try_to_unmap[_one](), so it deals with normal pages only.(And in case unlikely/TTU_SPLIT_HUGE_PMD/split_huge_pmd_address() happens, which it should not or be rare, the page refcount is not two, as the head page counts tail pages, and tail pages have zero. That also prevents checking the head
pagethen incorrectly callpage_remove_rmap(subpage)for a tail page, that isn't even in the shrink_page_list()'spage_list(an effect of split huge pmd/pmvw), as it might happen today in this unlikely scenario.)MADV_FREE'd buffers:
===================So, back to the "if
MADV_FREEpages are used as buffers" note. The case is arguable, and subject to multiple interpretations.The madvise(2) manual page on the
MADV_FREEadvice value says:
- 'After a successfulMADV_FREE... data will be lost when the kernel frees the pages.'
- 'the free operation will be canceled if the caller writes into the page' / 'subsequent writes ... will succeed and then [the] kernel cannot free those dirtied pages'
- 'If there is no subsequent write, the kernel can free the pages at any time.'Thoughts, questions, considerations...
- Since the kernel didn't actually free the page (page_ref_freeze()failed), should the data not have been lost? (on userspace read.)
- Should writes performed by the direct IO read be able to cancel the free operation?
- Should the direct IO read be considered as 'the caller' too, as it's been requested by 'the caller'?
- Should the bio technique to dirty pages on return to userspace (bio_check_pages_dirty()is called/used by__blkdev_direct_IO()) be considered in another/special way here?
- Should an upcoming write from a previously requested direct IO read be considered as a subsequent write, so the kernel should not free the pages? (as it's known at the time of page reclaim.)Technically, the last point would seem a reasonable consideration and balance, as the madvise(2) manual page apparently (and fairly) seem to assume that 'writes' are memory access from the userspace process (not explicitly considering writes from the kernel or its corner cases; again, fairly).. plus the kernel fix implementation for the corner case of the largely 'non-atomic write' encompassed by a direct IO read operation, is relatively simple; and it helps.
Reproducer:
==========@
test.c(simplified, but works)#define _GNU_SOURCE #include <fcntl.h> #include <stdio.h> #include <unistd.h> #include <sys/mman.h> int main() { int fd, i; char *buf; fd = open(DEV, O_RDONLY | O_DIRECT); buf = mmap(NULL, BUF_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); for (i = 0; i < BUF_SIZE; i += PAGE_SIZE) buf[i] = 1; // init to non-zero madvise(buf, BUF_SIZE, MADV_FREE); read(fd, buf, BUF_SIZE); for (i = 0; i < BUF_SIZE; i += PAGE_SIZE) printf("%p: 0x%x\n", &buf[i], buf[i]); return 0; }@
block/fops.c(formerlyfs/block_dev.c)+#include <linux/swap.h> ... ... __blkdev_direct_IO[_simple](...) { ... + if (!strcmp(current->comm, "good")) + shrink_all_memory(ULONG_MAX); + ret = bio_iov_iter_get_pages(...); + + if (!strcmp(current->comm, "bad")) + shrink_all_memory(ULONG_MAX); ... }@ shell
# yes | dd of=test.img bs=1k count=16 # DEV=$(losetup -f --show test.img) # gcc -DDEV=\"$DEV\" -DBUF_SIZE=16384 -DPAGE_SIZE=4096 test.c -o test# od -tx1 $DEV 0000000 79 0a 79 0a 79 0a 79 0a 79 0a 79 0a 79 0a 79 0a * 0040000# mv test good # ./good 0x7f1509206000: 0x79 0x7f1509207000: 0x79 0x7f1509208000: 0x79 0x7f1509209000: 0x79# mv good bad # ./bad 0x7fd87272f000: 0x0 0x7fd872730000: 0x0 0x7fd872731000: 0x0 0x7fd872732000: 0x0Ceph/TCMalloc:
=============For documentation purposes, the use case driving the analysis/fix is Ceph on Ubuntu 18.04, as the TCMalloc library there still uses
MADV_FREEto release unused memory to the system from the mmap'ed page heap (might be committed back/used again; it's not munmap'ed.)
-PageHeap::DecommitSpan()->TCMalloc_SystemRelease()->madvise()
-PageHeap::CommitSpan()->TCMalloc_SystemCommit()-> do nothing.Note: TCMalloc switched back to
MADV_DONTNEEDa few commits after the release in Ubuntu 18.04 (google-perftools/gperftools 2.5), so the issue just 'disappeared' on Ceph on later Ubuntu releases but is still present in the kernel, and can be hit by other use cases.The observed issue seems to be the old Ceph bug #22464 [1], where checksum mismatches are observed (and instrumentation with buffer dumps shows zero-pages read from mmap'ed/MADV_FREE'd page ranges).
The issue in Ceph was reasonably deemed a kernel bug (comment #50) and mostly worked around with a retry mechanism, but other parts of Ceph could still hit that (rocksdb). Anyway, it's less likely to be hit again as TCMalloc switched out of
MADV_FREEby default.(Some kernel versions/reports from the Ceph bug, and relation with the
MADV_FREEintroduction/changes; TCMalloc versions not checked.)
- 4.4 good
- 4.5 (madv_free: introduction)
- 4.9 bad
- 4.10 good? maybe a swapless system
- 4.12 (madv_free: no longer free instantly on swapless systems)
- 4.13 bad[1] https://tracker.ceph.com/issues/22464
Thanks:
======Several people contributed to analysis/discussions/tests/reproducers in the first stages when drilling down on ceph/tcmalloc/linux kernel:
- Dan Hill <[email protected]>
- Dan Streetman <[email protected]>
- Dongdong Tao <[email protected]>
- Gavin Guo <[email protected]>
- Gerald Yang <[email protected]>
- Heitor Alves de Siqueira <[email protected]>
- Ioanna Alifieraki <[email protected]>
- Jay Vosburgh <[email protected]>
- Matthew Ruffell <[email protected]>
- Ponnuvel Palaniyappan <[email protected]>v2: check refcount against mapcount rather than a static 2.
Thanks: Minchan Kim <[email protected]>Signed-off-by Mauricio Faria de Oliveira <[email protected]>--- mm/rmap.c | 15 ++++++++++++++- mm/vmscan.c | 2 +- 2 files changed, 15 insertions(+), 2 deletions(-)mm/rmap.c +4
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1586
Quoted 10 lines
mm/rmap.c +10
-0+* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {Thanks. Looks good to me.
Quoted 2 lines
I'd like to invite more folks for better eyes since this could be a rather subtle issue.
Looks good to me too! Please feel free to add my
Best Regards,
Huang, Ying
Quoted 16 lines · Mauricio Faria de Oliveira
mm/rmap.c +7
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* +* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:).
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1589
Quoted 10 lines
mm/rmap.c +7
-0+* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {/* Invalidate as we cleared the pte */ mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );
Out of curiosity, how does it work with COW in terms of reordering? Specifically, it seems to me get_page() and page_dup_rmap() in copy_present_pte() can happen in any order, and if page_dup_rmap() is seen first, and direct io is holding a refcnt, this check can still pass?
Quoted 25 lines · Yu Zhao
Quoted 24 lines · Mauricio Faria de Oliveira
mm/rmap.c +14
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* +* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {/* Invalidate as we cleared the pte */
Quoted 9 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1589
Quoted 2 lines
mm/rmap.c +0
-0mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );Out of curiosity, how does it work with COW in terms of reordering? Specifically, it seems to me
get_page()andpage_dup_rmap()incopy_present_pte()can happen in any order, and ifpage_dup_rmap()is seen first, and direct io is holding a refcnt, this check can still pass?
Hi Yu,
I think you're correct. I think we don't like memory barrier there in page_dup_rmap. Then, how about make gup_fast is aware of FOLL_TOUCH?
FOLL_TOUCH means it's going to write something so the page should be dirty. Currently, get_user_pages works like that. Howver, problem is get_user_pages_fast since it looks like that lockless_pages_from_mm doesn't support FOLL_TOUCH.
So the idea is if param in internal_get_user_pages_fast includes FOLL_TOUCH, gup_{pmd,pte}_range try to make the page dirty under trylock_page(If the lock fails, it goes slow path with __gup_longterm_unlocked and set_dirty_pages for them).
This approach would solve other cases where map userspace pages into kernel space and then write. Since the write didn't go through with the process's page table, we will lose the dirty bit in the page table of the process and it turns out same problem. That's why I'd like to approach this.
If it doesn't work, the other option to fix this specific case is can't we make pages dirty in advance in DIO read-case?
When I look at DIO code, it's already doing in async case. Could't we do the same thing for the other cases? I guess the worst case we will see would be more page writeback since the page becomes dirty unnecessary.
On 1/11/22 10:54, Minchan Kim wrote:
...
Quoted 7 lines
Hi Yu,
I think you're correct. I think we don't like memory barrier there in
page_dup_rmap. Then, how about makegup_fastis aware ofFOLL_TOUCH?
FOLL_TOUCHmeans it's going to write something so the page
Actually, my understanding of FOLL_TOUCH is that it does *not* mean that data will be written to the page. That is what FOLL_WRITE is for. FOLL_TOUCH means: update the "accessed" metadata, without actually writing to the memory that the page represents.
Quoted 7 lines
should be dirty. Currently,
get_user_pagesworks like that. Howver, problem isget_user_pages_fastsince it looks like thatlockless_pages_from_mmdoesn't supportFOLL_TOUCH.So the idea is if param in
internal_get_user_pages_fastincludesFOLL_TOUCH, gup_{pmd,pte}_range try to make the page dirty under trylock_page(If the lock fails, it goes
Marking a page dirty solely because FOLL_TOUCH is specified would be an API-level mistake. That's why it isn't "supported". Or at least, that's how I'm reading things.
Hope that helps!
Quoted 10 lines
slow path with
__gup_longterm_unlockedandset_dirty_pagesfor them).This approach would solve other cases where map userspace pages into kernel space and then write. Since the write didn't go through with the process's page table, we will lose the dirty bit in the page table of the process and it turns out same problem. That's why I'd like to approach this.
Quoted 7 lines
If it doesn't work, the other option to fix this specific case is can't we make pages dirty in advance in DIO read-case?
When I look at DIO code, it's already doing in async case. Could't we do the same thing for the other cases? I guess the worst case we will see would be more page writeback since the page becomes dirty unnecessary.
Marking pages dirty after pinning them is a pre-existing area of problems. See the long-running LWN articles about get_user_pages() [1].
[1] https://lwn.net/Kernel/Index/#Memory_management-get_user_pages
thanks,
Signature · 2 lines
John Hubbard NVIDIA
Quoted 8 lines · John Hubbard
On 1/11/22 10:54, Minchan Kim wrote:
...Quoted 6 lines
Hi Yu,
I think you're correct. I think we don't like memory barrier there in
page_dup_rmap. Then, how about makegup_fastis aware ofFOLL_TOUCH?
Quoted 6 lines
Quoted 1 line
FOLL_TOUCHmeans it's going to write something so the pageActually, my understanding of
FOLL_TOUCHis that it does *not* mean that data will be written to the page. That is whatFOLL_WRITEis for.FOLL_TOUCHmeans: update the "accessed" metadata, without actually writing to the memory that the page represents.
Exactly. I should have mentioned the FOLL_TOUCH with FOLL_WRITE. What I wanted to hit with FOLL_TOUCH was
follow_page_pte:
if (flags & FOLL_TOUCH) {
if ((flags & FOLL_WRITE) &&
!pte_dirty(pte) && !PageDirty(page))
set_page_dirty(page);
mark_page_accessed(page);
}Quoted 29 lines
Quoted 9 lines
should be dirty. Currently,
get_user_pagesworks like that. Howver, problem isget_user_pages_fastsince it looks like thatlockless_pages_from_mmdoesn't supportFOLL_TOUCH.So the idea is if param in
internal_get_user_pages_fastincludesFOLL_TOUCH, gup_{pmd,pte}_range try to make the page dirty under trylock_page(If the lock fails, it goesMarking a page dirty solely because
FOLL_TOUCHis specified would be an API-level mistake. That's why it isn't "supported". Or at least, that's how I'm reading things.Hope that helps!
Quoted 13 lines
slow path with
__gup_longterm_unlockedandset_dirty_pagesfor them).This approach would solve other cases where map userspace pages into kernel space and then write. Since the write didn't go through with the process's page table, we will lose the dirty bit in the page table of the process and it turns out same problem. That's why I'd like to approach this.
If it doesn't work, the other option to fix this specific case is can't we make pages dirty in advance in DIO read-case?
Quoted 7 lines
Quoted 4 lines
When I look at DIO code, it's already doing in async case. Could't we do the same thing for the other cases? I guess the worst case we will see would be more page writeback since the page becomes dirty unnecessary.
Marking pages dirty after pinning them is a pre-existing area of problems. See the long-running LWN articles about
get_user_pages()[1].
Oh, Do you mean marking page dirty in DIO path is already problems? Let me read the pages in the link.
Thanks!
Quoted 9 lines
[1] https://lwn.net/Kernel/Index/#Memory_management-get_user_pages
thanks,
Signature · 2 lines
John Hubbard NVIDIA
On Tue, Jan 11, 2022 at 12:20:13PM -0800, Minchan Kim wrote:
< snip >
Quoted 18 lines
Quoted 18 lines
Quoted 17 lines
slow path with
__gup_longterm_unlockedandset_dirty_pagesfor them).This approach would solve other cases where map userspace pages into kernel space and then write. Since the write didn't go through with the process's page table, we will lose the dirty bit in the page table of the process and it turns out same problem. That's why I'd like to approach this.
If it doesn't work, the other option to fix this specific case is can't we make pages dirty in advance in DIO read-case?
When I look at DIO code, it's already doing in async case. Could't we do the same thing for the other cases? I guess the worst case we will see would be more page writeback since the page becomes dirty unnecessary.
Quoted 4 lines
Quoted 2 lines
Marking pages dirty after pinning them is a pre-existing area of problems. See the long-running LWN articles about
get_user_pages()[1].Oh, Do you mean marking page dirty in DIO path is already problems?
^ marking page dirty too late in DIO path
Typo fix.
Quoted 20 lines · Minchan Kim
On Tue, Jan 11, 2022 at 12:20:13PM -0800, Minchan Kim wrote:
< snip >Quoted 18 lines
Quoted 18 lines
Quoted 17 lines
slow path with
__gup_longterm_unlockedandset_dirty_pagesfor them).This approach would solve other cases where map userspace pages into kernel space and then write. Since the write didn't go through with the process's page table, we will lose the dirty bit in the page table of the process and it turns out same problem. That's why I'd like to approach this.
If it doesn't work, the other option to fix this specific case is can't we make pages dirty in advance in DIO read-case?
When I look at DIO code, it's already doing in async case. Could't we do the same thing for the other cases? I guess the worst case we will see would be more page writeback since the page becomes dirty unnecessary.
Quoted 8 lines
Quoted 4 lines
Quoted 2 lines
Marking pages dirty after pinning them is a pre-existing area of problems. See the long-running LWN articles about
get_user_pages()[1].Oh, Do you mean marking page dirty in DIO path is already problems?
^ marking page dirty too late in DIO path
Typo fix.
I looked though the articles but couldn't find dots to connetct issues with this MADV_FREE issue. However, man page shows a clue why it's fine.
```
O_DIRECT I/Os should never be run concurrently with the fork(2) system call, if the memory buffer is a private map‐
ping (i.e., any mapping created with the mmap(2) MAP_PRIVATE flag; this includes memory allocated on the heap and
statically allocated buffers). Any such I/Os, whether submitted via an asynchronous I/O interface or from another
thread in the process, should be completed before fork(2) is called. Failure to do so can result in data corruption
and undefined behavior in parent and child processes.
```I think it would make the copy_present_pte's page_dup_rmap safe.
On 1/11/22 13:59, Minchan Kim wrote:
...
Quoted 11 lines
Quoted 8 lines
Quoted 4 lines
Quoted 2 lines
Marking pages dirty after pinning them is a pre-existing area of problems. See the long-running LWN articles about
get_user_pages()[1].Oh, Do you mean marking page dirty in DIO path is already problems?
^ marking page dirty too late in DIO path
Typo fix.
I looked though the articles but couldn't find dots to connetct issues with this
MADV_FREEissue. However, man page shows a clue
The area covered in those articles is about the fact that file system and block are not safely interacting with pinned memory. Even today. So I'm trying to make sure you're aware of that before you go too far in that direction.
Quoted 11 lines
why it's fine.
``` O_DIRECT I/Os should never be run concurrently with the fork(2) system call, if the memory buffer is a private map‐ ping (i.e., any mapping created with the mmap(2) MAP_PRIVATE flag; this includes memory allocated on the heap and statically allocated buffers). Any such I/Os, whether submitted via an asynchronous I/O interface or from another thread in the process, should be completed before fork(2) is called. Failure to do so can result in data corruption and undefined behavior in parent and child processes. ```
Quoted 1 line
I think it would make the copy_present_pte's
page_dup_rmapsafe.
I'd have to see this in patch form, because I'm not quite able to visualize it yet.
thanks,
Signature · 2 lines
John Hubbard NVIDIA
Quoted 28 lines · John Hubbard
On 1/11/22 13:59, Minchan Kim wrote:
...Quoted 11 lines
Quoted 8 lines
Quoted 4 lines
Quoted 2 lines
Marking pages dirty after pinning them is a pre-existing area of problems. See the long-running LWN articles about
get_user_pages()[1].Oh, Do you mean marking page dirty in DIO path is already problems?
^ marking page dirty too late in DIO path
Typo fix.
I looked though the articles but couldn't find dots to connetct issues with this
MADV_FREEissue. However, man page shows a clueThe area covered in those articles is about the fact that file system and block are not safely interacting with pinned memory. Even today. So I'm trying to make sure you're aware of that before you go too far in that direction.
Quoted 9 lines
why it's fine.
```
O_DIRECTI/Os should never be run concurrently with the fork(2) system call, if the memory buffer is a private map‐ ping (i.e., any mapping created with the mmap(2)MAP_PRIVATEflag; this includes memory allocated on the heap and statically allocated buffers). Any such I/Os, whether submitted via an asynchronous I/O interface or from another thread in the process, should be completed before fork(2) is called. Failure to do so can result in data corruption and undefined behavior in parent and child processes.
Quoted 5 lines
Quoted 3 lines
```
I think it would make the copy_present_pte's
page_dup_rmapsafe.I'd have to see this in patch form, because I'm not quite able to visualize it yet.
It would be great if you read though the original patch description. Since v2 had a little change to consider mutiple maps among parent and child, it would introduce a little mistmatch with the description but it's still quite good to explain current problem.
https://lore.kernel.org/all/[email protected]/T/#u
Problem is MADV_FREEed anonymous memory is supposed to work based on dirtiness came from the user process's page table bit or PageDirty. Since VM can't see the dirty, it just discards the anonymous memory instead of swappoing out. Thus, the dirtiness is key to work correctly.
However, DIO didn't make the page Dirty yet until IO is completed and at the same time, the store operation didn't go though via user process's page table regardless of DMA or other way. It makes VM could decide just drop the page since it didn't see any dirtiness from the page. So it turns out enduser would be surprised because the read syscall with DIO was completed but the data was zero rather than latest uptodate data.
To prevent the problem, the patch suggested to compare page_mapcount with page_count since it expects any additional reference of the page means someone is doing accessing the memory so in this case, not discarding the page. However, Yu pointed out page_count and page_mapcount could be reordered in copy_page_range, for example. So I am looking for the solution(one would be adding memory barrier right before page_dup_rmap but I'd like to avoid it if we have other idea). And then man page says forking under going DIO would be already prohibited so the concern raised would be void, IIUC.
Hope this helps your understanding.
Thanks!
work
Quoted 25 lines · Yu Zhao
Quoted 24 lines · Mauricio Faria de Oliveira
mm/rmap.c +14
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* +* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {/* Invalidate as we cleared the pte */
Quoted 8 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1589
Quoted 2 lines
mm/rmap.c +0
-0mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );Out of curiosity, how does it work with COW in terms of reordering? Specifically, it seems to me
get_page()andpage_dup_rmap()incopy_present_pte()can happen in any order, and ifpage_dup_rmap()is seen first, and direct io is holding a refcnt, this check can still pass?
I think that you are correct.
After more thoughts, it appears very tricky to compare page count and map count. Even if we have added smp_rmb() between page_ref_count() and page_mapcount(), an interrupt may happen between them. During the interrupt, the page count and map count may be changed, for example, unmapped, or do_swap_page().
Best Regards,
Huang, Ying
Quoted 36 lines · Ying
Quoted 25 lines · Yu Zhao
Quoted 24 lines · Mauricio Faria de Oliveira
mm/rmap.c +14
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* +* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {/* Invalidate as we cleared the pte */ Quoted 8 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1589
Quoted 2 lines
mm/rmap.c +0
-0mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );Out of curiosity, how does it work with COW in terms of reordering? Specifically, it seems to me
get_page()andpage_dup_rmap()incopy_present_pte()can happen in any order, and ifpage_dup_rmap()is seen first, and direct io is holding a refcnt, this check can still pass?
Quoted 7 lines
I think that you are correct.
After more thoughts, it appears very tricky to compare page count and map count. Even if we have added
smp_rmb()betweenpage_ref_count()andpage_mapcount(), an interrupt may happen between them. During the interrupt, the page count and map count may be changed, for example, unmapped, ordo_swap_page().
Yeah, it happens but what specific problem are you concerning from the count change under race? The fork case Yu pointed out was already known for breaking DIO so user should take care not to fork under DIO(Please look at O_DIRECT section in man 2 open). If you could give a specific example, it would be great to think over the issue.
I agree it's little tricky but it seems to be way other place has used for a long time(Please look at write_protect_page in ksm.c). So, here what we missing is tlb flush before the checking.
Something like this.
mm/rmap.c +2 -12
@@ -1599,18 +1599,8 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -int refcount =page_ref_count (page); - -/* -* The only page refs must be from the isolation -* (checked by the caller shrink_page_list() too) -* and the (single) rmap (dropped by discard:). -* -* Check the reference count before dirty flag -* with memory barrier; see __remove_mapping(). -*/ -smp_rmb (); -if (refcount ==2 && !PageDirty (page)) { +if (!PageDirty (page) && +page_mapcount (page) +1 ==page_count (page)) {/* Invalidate as we cleared the pte */ mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );
mm/vmscan.c +3 -0
@@ -1754,6 +1754,9 @@ static unsigned int shrink_page_list(struct list_head *page_list,enum ttu_flags flags =TTU_BATCH_FLUSH ;bool was_swapbacked =PageSwapBacked (page); +if (!was_swapbacked &&PageAnon (page)) + flags &= ~TTU_BATCH_FLUSH ; +if (unlikely (PageTransHuge (page))) flags |=TTU_SPLIT_HUGE_PMD ;
Hi Minchan Kim,
Thanks for handling the hard questions! :)
Quoted 46 lines · Minchan Kim
Quoted 36 lines · Ying
Quoted 25 lines · Yu Zhao
Quoted 24 lines · Mauricio Faria de Oliveira
mm/rmap.c +14
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* +* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {/* Invalidate as we cleared the pte */ Quoted 8 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1606
Quoted 2 lines
mm/rmap.c +0
-0mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );Out of curiosity, how does it work with COW in terms of reordering? Specifically, it seems to me
get_page()andpage_dup_rmap()incopy_present_pte()can happen in any order, and ifpage_dup_rmap()is seen first, and direct io is holding a refcnt, this check can still pass?Quoted 7 lines
I think that you are correct.
After more thoughts, it appears very tricky to compare page count and map count. Even if we have added
smp_rmb()betweenpage_ref_count()andpage_mapcount(), an interrupt may happen between them. During the interrupt, the page count and map count may be changed, for example, unmapped, ordo_swap_page().
Quoted 8 lines
Yeah, it happens but what specific problem are you concerning from the count change under race? The fork case Yu pointed out was already known for breaking DIO so user should take care not to fork under
DIO(Please look at O_DIRECT section in man 2 open). If you could give a specific example, it would be great to think over the issue.I agree it's little tricky but it seems to be way other place has used for a long
time(Please look at write_protect_page in ksm.c).
Ah, that's great to see it's being used elsewhere, for DIO particularly!
Quoted 1 line
So, here what we missing is tlb flush before the checking.
That shouldn't be required for this particular issue/case, IIUIC. One of the things we checked early on was disabling deferred TLB flush (similarly to what you've done), and it didn't help with the issue; also, the issue happens on uniprocessor mode too (thus no remote CPU involved.)
Quoted 15 lines
Something like this.
mm/rmap.c +0
-4@@ -1599,18 +1599,8 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -int refcount =page_ref_count (page); - -/* -* The only page refs must be from the isolation
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1603
Quoted 10 lines
mm/rmap.c +2
-8-* (checked by the caller shrink_page_list() too) -* and the (single) rmap (dropped by discard:). -* -* Check the reference count before dirty flag -* with memory barrier; see __remove_mapping(). -*/ -smp_rmb (); -if (refcount ==2 && !PageDirty (page)) { +if (!PageDirty (page) && +page_mapcount (page) +1 ==page_count (page)) {
In the interest of avoiding a different race/bug, it seemed worth following the suggestion outlined in __remove_mapping(), i.e., checking PageDirty() after the page's reference count, with a memory barrier in between.
I'm not familiar with the details of the original issue behind that code change, but it seemed to be possible here too, particularly as writes from user-space can happen asynchronously / after try_to_unmap_one() checked PTE clean and didn't set PageDirty, and if the page's PTE is present, there's no fault?
Thanks again,
Mauricio
Quoted 22 lines
mm/rmap.c +0
-0/* Invalidate as we cleared the pte */ mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );mm/vmscan.c +3
-0@@ -1754,6 +1754,9 @@ static unsigned int shrink_page_list(struct list_head *page_list,enum ttu_flags flags =TTU_BATCH_FLUSH ;bool was_swapbacked =PageSwapBacked (page); +if (!was_swapbacked &&PageAnon (page)) + flags &= ~TTU_BATCH_FLUSH ; +if (unlikely (PageTransHuge (page))) flags |=TTU_SPLIT_HUGE_PMD ;
Signature · 1 line
Mauricio Faria de Oliveira
Quoted 60 lines · Mauricio Faria de Oliveira
Hi Minchan Kim,
Thanks for handling the hard questions! :)
Quoted 46 lines · Minchan Kim
Quoted 36 lines · Ying
Quoted 25 lines · Yu Zhao
Quoted 24 lines · Mauricio Faria de Oliveira
mm/rmap.c +14
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* +* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {/* Invalidate as we cleared the pte */ Quoted 8 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1606
Quoted 2 lines
mm/rmap.c +0
-0mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );Out of curiosity, how does it work with COW in terms of reordering? Specifically, it seems to me
get_page()andpage_dup_rmap()incopy_present_pte()can happen in any order, and ifpage_dup_rmap()is seen first, and direct io is holding a refcnt, this check can still pass?Quoted 7 lines
I think that you are correct.
After more thoughts, it appears very tricky to compare page count and map count. Even if we have added
smp_rmb()betweenpage_ref_count()andpage_mapcount(), an interrupt may happen between them. During the interrupt, the page count and map count may be changed, for example, unmapped, ordo_swap_page().Quoted 8 lines
Yeah, it happens but what specific problem are you concerning from the count change under race? The fork case Yu pointed out was already known for breaking DIO so user should take care not to fork under
DIO(Please look at O_DIRECT section in man 2 open). If you could give a specific example, it would be great to think over the issue.I agree it's little tricky but it seems to be way other place has used for a long
time(Please look at write_protect_page in ksm.c).
Quoted 8 lines
Ah, that's great to see it's being used elsewhere, for DIO particularly!
Quoted 1 line
So, here what we missing is tlb flush before the checking.
That shouldn't be required for this particular issue/case, IIUIC. One of the things we checked early on was disabling deferred TLB flush (similarly to what you've done), and it didn't help with the issue; also, the issue happens on uniprocessor mode too (thus no remote CPU involved.)
I guess you didn't try it with page_mapcount + 1 == page_count at tha time? Anyway, I agree we don't need TLB flush here like KSM. I think the reason KSM is doing TLB flush before the check it to make sure trap trigger on the write from userprocess in other core. However, this MADV_FREE case, HW already gaurantees the trap. Please see below.
Quoted 23 lines
Quoted 23 lines
Something like this.
mm/rmap.c +0
-10@@ -1599,18 +1599,8 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -int refcount =page_ref_count (page); - -/* -* The only page refs must be from the isolation -* (checked by the caller shrink_page_list() too) -* and the (single) rmap (dropped by discard:). -* -* Check the reference count before dirty flag -* with memory barrier; see __remove_mapping(). -*/
Quoted 8 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1603
Quoted 4 lines
mm/rmap.c +2
-2-smp_rmb (); -if (refcount ==2 && !PageDirty (page)) { +if (!PageDirty (page) && +page_mapcount (page) +1 ==page_count (page)) {In the interest of avoiding a different race/bug, it seemed worth following the suggestion outlined in
__remove_mapping(), i.e., checkingPageDirty()after the page's reference count, with a memory barrier in between.
True so it means your patch as-is is good for me.
Quoted 5 lines
I'm not familiar with the details of the original issue behind that code change, but it seemed to be possible here too, particularly as writes from user-space can happen asynchronously / after
try_to_unmap_one()checked PTE clean and didn't set PageDirty, and if the page's PTE is present, there's no fault?
Yeah, it was discussed.
For clean pte, CPU has to fetch and update the actual pte entry, not TLB so trap triggers for MADV_FREE page.
https://lkml.org/lkml/2015/4/15/565
https://lkml.org/lkml/2015/4/16/136
Quoted 109 lines · Minchan Kim
Quoted 60 lines · Mauricio Faria de Oliveira
Hi Minchan Kim,
Thanks for handling the hard questions! :)
Quoted 46 lines · Minchan Kim
Quoted 36 lines · Ying
Quoted 25 lines · Yu Zhao
Quoted 24 lines · Mauricio Faria de Oliveira
mm/rmap.c +14
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* +* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {/* Invalidate as we cleared the pte */ Quoted 8 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1606
Quoted 2 lines
mm/rmap.c +0
-0mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );Out of curiosity, how does it work with COW in terms of reordering? Specifically, it seems to me
get_page()andpage_dup_rmap()incopy_present_pte()can happen in any order, and ifpage_dup_rmap()is seen first, and direct io is holding a refcnt, this check can still pass?Quoted 7 lines
I think that you are correct.
After more thoughts, it appears very tricky to compare page count and map count. Even if we have added
smp_rmb()betweenpage_ref_count()andpage_mapcount(), an interrupt may happen between them. During the interrupt, the page count and map count may be changed, for example, unmapped, ordo_swap_page().Quoted 8 lines
Yeah, it happens but what specific problem are you concerning from the count change under race? The fork case Yu pointed out was already known for breaking DIO so user should take care not to fork under
DIO(Please look at O_DIRECT section in man 2 open). If you could give a specific example, it would be great to think over the issue.I agree it's little tricky but it seems to be way other place has used for a long
time(Please look at write_protect_page in ksm.c).Quoted 8 lines
Ah, that's great to see it's being used elsewhere, for DIO particularly!
Quoted 1 line
So, here what we missing is tlb flush before the checking.
That shouldn't be required for this particular issue/case, IIUIC. One of the things we checked early on was disabling deferred TLB flush (similarly to what you've done), and it didn't help with the issue; also, the issue happens on uniprocessor mode too (thus no remote CPU involved.)
I guess you didn't try it with
page_mapcount+ 1 ==page_countat tha time? Anyway, I agree we don't need TLB flush here like KSM. I think the reason KSM is doing TLB flush before the check it to make sure trap trigger on the write from userprocess in other core. However, thisMADV_FREEcase, HW already gaurantees the trap. Please see below.Quoted 23 lines
Quoted 23 lines
Something like this.
mm/rmap.c +0
-10@@ -1599,18 +1599,8 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -int refcount =page_ref_count (page); - -/* -* The only page refs must be from the isolation -* (checked by the caller shrink_page_list() too) -* and the (single) rmap (dropped by discard:). -* -* Check the reference count before dirty flag -* with memory barrier; see __remove_mapping(). -*/ Quoted 8 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1603
Quoted 4 lines
mm/rmap.c +2
-2-smp_rmb (); -if (refcount ==2 && !PageDirty (page)) { +if (!PageDirty (page) && +page_mapcount (page) +1 ==page_count (page)) {In the interest of avoiding a different race/bug, it seemed worth following the suggestion outlined in
__remove_mapping(), i.e., checkingPageDirty()after the page's reference count, with a memory barrier in between.
Quoted 1 line
True so it means your patch as-is is good for me.
If my understanding were correct, a shared anonymous page will be mapped read-only. If so, will a private anonymous page be called SetPageDirty() concurrently after direct IO case has been dealt with via comparing page_count()/page_mapcount()?
Best Regards,
Huang, Ying
Quoted 111 lines · Ying
Quoted 109 lines · Minchan Kim
Quoted 60 lines · Mauricio Faria de Oliveira
Hi Minchan Kim,
Thanks for handling the hard questions! :)
Quoted 46 lines · Minchan Kim
Quoted 36 lines · Ying
Quoted 25 lines · Yu Zhao
Quoted 24 lines · Mauricio Faria de Oliveira
mm/rmap.c +14
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* +* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {/* Invalidate as we cleared the pte */ Quoted 8 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1606
Quoted 2 lines
mm/rmap.c +0
-0mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );Out of curiosity, how does it work with COW in terms of reordering? Specifically, it seems to me
get_page()andpage_dup_rmap()incopy_present_pte()can happen in any order, and ifpage_dup_rmap()is seen first, and direct io is holding a refcnt, this check can still pass?Quoted 7 lines
I think that you are correct.
After more thoughts, it appears very tricky to compare page count and map count. Even if we have added
smp_rmb()betweenpage_ref_count()andpage_mapcount(), an interrupt may happen between them. During the interrupt, the page count and map count may be changed, for example, unmapped, ordo_swap_page().Quoted 8 lines
Yeah, it happens but what specific problem are you concerning from the count change under race? The fork case Yu pointed out was already known for breaking DIO so user should take care not to fork under
DIO(Please look at O_DIRECT section in man 2 open). If you could give a specific example, it would be great to think over the issue.I agree it's little tricky but it seems to be way other place has used for a long
time(Please look at write_protect_page in ksm.c).Quoted 8 lines
Ah, that's great to see it's being used elsewhere, for DIO particularly!
Quoted 1 line
So, here what we missing is tlb flush before the checking.
That shouldn't be required for this particular issue/case, IIUIC. One of the things we checked early on was disabling deferred TLB flush (similarly to what you've done), and it didn't help with the issue; also, the issue happens on uniprocessor mode too (thus no remote CPU involved.)
I guess you didn't try it with
page_mapcount+ 1 ==page_countat tha time? Anyway, I agree we don't need TLB flush here like KSM. I think the reason KSM is doing TLB flush before the check it to make sure trap trigger on the write from userprocess in other core. However, thisMADV_FREEcase, HW already gaurantees the trap. Please see below.Quoted 31 lines
Quoted 17 lines
Something like this.
mm/rmap.c +0
-4@@ -1599,18 +1599,8 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -int refcount =page_ref_count (page); - -/* -* The only page refs must be from the isolation mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1603
Quoted 10 lines
mm/rmap.c +2
-8-* (checked by the caller shrink_page_list() too) -* and the (single) rmap (dropped by discard:). -* -* Check the reference count before dirty flag -* with memory barrier; see __remove_mapping(). -*/ -smp_rmb (); -if (refcount ==2 && !PageDirty (page)) { +if (!PageDirty (page) && +page_mapcount (page) +1 ==page_count (page)) {In the interest of avoiding a different race/bug, it seemed worth following the suggestion outlined in
__remove_mapping(), i.e., checkingPageDirty()after the page's reference count, with a memory barrier in between.
Quoted 6 lines
Quoted 1 line
True so it means your patch as-is is good for me.
If my understanding were correct, a shared anonymous page will be mapped read-only. If so, will a private anonymous page be called
SetPageDirty()concurrently after direct IO case has been dealt with via comparing page_count()/page_mapcount()?
Sorry, I found that I am not quite right here. When direct IO read completes, it will call SetPageDirty() and put_page() finally. And MADV_FREE in try_to_unmap_one() needs to deal with that too.
Checking direct IO code, it appears that set_page_dirty_lock() is used to set page dirty, which will use lock_page().
dio_bio_complete
bio_check_pages_dirty
bio_dirty_fn /* through workqueue */
bio_release_pages
set_page_dirty_lock
bio_release_pages
set_page_dirty_lock
So in theory, for direct IO, the memory barrier may be unnecessary. But I don't think it's a good idea to depend on this specific behavior of direct IO. The original code with memory barrier looks more generic and I don't think it will introduce visible overhead.
Best Regards,
Huang, Ying
Quoted 136 lines · Ying
Quoted 111 lines · Ying
Quoted 109 lines · Minchan Kim
Quoted 60 lines · Mauricio Faria de Oliveira
Hi Minchan Kim,
Thanks for handling the hard questions! :)
Quoted 46 lines · Minchan Kim
Quoted 36 lines · Ying
Quoted 25 lines · Yu Zhao
Quoted 24 lines · Mauricio Faria de Oliveira
mm/rmap.c +14
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* +* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {/* Invalidate as we cleared the pte */ Quoted 8 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1606
Quoted 2 lines
mm/rmap.c +0
-0mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );Out of curiosity, how does it work with COW in terms of reordering? Specifically, it seems to me
get_page()andpage_dup_rmap()incopy_present_pte()can happen in any order, and ifpage_dup_rmap()is seen first, and direct io is holding a refcnt, this check can still pass?Quoted 7 lines
I think that you are correct.
After more thoughts, it appears very tricky to compare page count and map count. Even if we have added
smp_rmb()betweenpage_ref_count()andpage_mapcount(), an interrupt may happen between them. During the interrupt, the page count and map count may be changed, for example, unmapped, ordo_swap_page().Quoted 8 lines
Yeah, it happens but what specific problem are you concerning from the count change under race? The fork case Yu pointed out was already known for breaking DIO so user should take care not to fork under
DIO(Please look at O_DIRECT section in man 2 open). If you could give a specific example, it would be great to think over the issue.I agree it's little tricky but it seems to be way other place has used for a long
time(Please look at write_protect_page in ksm.c).Quoted 8 lines
Ah, that's great to see it's being used elsewhere, for DIO particularly!
Quoted 1 line
So, here what we missing is tlb flush before the checking.
That shouldn't be required for this particular issue/case, IIUIC. One of the things we checked early on was disabling deferred TLB flush (similarly to what you've done), and it didn't help with the issue; also, the issue happens on uniprocessor mode too (thus no remote CPU involved.)
I guess you didn't try it with
page_mapcount+ 1 ==page_countat tha time? Anyway, I agree we don't need TLB flush here like KSM. I think the reason KSM is doing TLB flush before the check it to make sure trap trigger on the write from userprocess in other core. However, thisMADV_FREEcase, HW already gaurantees the trap. Please see below.Quoted 31 lines
Quoted 17 lines
Something like this.
mm/rmap.c +0
-4@@ -1599,18 +1599,8 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -int refcount =page_ref_count (page); - -/* -* The only page refs must be from the isolation mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1603
Quoted 10 lines
mm/rmap.c +2
-8-* (checked by the caller shrink_page_list() too) -* and the (single) rmap (dropped by discard:). -* -* Check the reference count before dirty flag -* with memory barrier; see __remove_mapping(). -*/ -smp_rmb (); -if (refcount ==2 && !PageDirty (page)) { +if (!PageDirty (page) && +page_mapcount (page) +1 ==page_count (page)) {In the interest of avoiding a different race/bug, it seemed worth following the suggestion outlined in
__remove_mapping(), i.e., checkingPageDirty()after the page's reference count, with a memory barrier in between.Quoted 6 lines
Quoted 1 line
True so it means your patch as-is is good for me.
If my understanding were correct, a shared anonymous page will be mapped read-only. If so, will a private anonymous page be called
SetPageDirty()concurrently after direct IO case has been dealt with via comparing page_count()/page_mapcount()?Sorry, I found that I am not quite right here. When direct IO read completes, it will call
SetPageDirty()andput_page()finally. AndMADV_FREEintry_to_unmap_one()needs to deal with that too.Checking direct IO code, it appears that
set_page_dirty_lock()is used to set page dirty, which will uselock_page().
dio_bio_complete
bio_check_pages_dirty
bio_dirty_fn/* through workqueue */
bio_release_pages
set_page_dirty_lock
bio_release_pages
set_page_dirty_lock
Quoted 5 lines
So in theory, for direct IO, the memory barrier may be unnecessary. But I don't think it's a good idea to depend on this specific behavior of direct IO. The original code with memory barrier looks more generic and I don't think it will introduce visible overhead.
Thanks for all the considerations/thought process with potential corner cases!
Regarding the overhead, agreed; and this is in memory reclaim which isn't a fast path (and even if it's under direct reclaim, things have slowed down already),
so that would seem to be fine.
cheers,
Quoted 2 lines
Best Regards,
Huang, Ying
Signature · 1 line
Mauricio Faria de Oliveira
Quoted 66 lines · Minchan Kim
Quoted 64 lines · Mauricio Faria de Oliveira
Hi Minchan Kim,
Thanks for handling the hard questions! :)
Quoted 46 lines · Minchan Kim
Quoted 36 lines · Ying
Quoted 25 lines · Yu Zhao
Quoted 24 lines · Mauricio Faria de Oliveira
mm/rmap.c +14
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* +* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {/* Invalidate as we cleared the pte */ Quoted 8 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1606
Quoted 2 lines
mm/rmap.c +0
-0mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );Out of curiosity, how does it work with COW in terms of reordering? Specifically, it seems to me
get_page()andpage_dup_rmap()incopy_present_pte()can happen in any order, and ifpage_dup_rmap()is seen first, and direct io is holding a refcnt, this check can still pass?Quoted 7 lines
I think that you are correct.
After more thoughts, it appears very tricky to compare page count and map count. Even if we have added
smp_rmb()betweenpage_ref_count()andpage_mapcount(), an interrupt may happen between them. During the interrupt, the page count and map count may be changed, for example, unmapped, ordo_swap_page().Quoted 8 lines
Yeah, it happens but what specific problem are you concerning from the count change under race? The fork case Yu pointed out was already known for breaking DIO so user should take care not to fork under
DIO(Please look at O_DIRECT section in man 2 open). If you could give a specific example, it would be great to think over the issue.I agree it's little tricky but it seems to be way other place has used for a long
time(Please look at write_protect_page in ksm.c).Ah, that's great to see it's being used elsewhere, for DIO particularly!
Quoted 1 line
So, here what we missing is tlb flush before the checking.
Quoted 7 lines
Quoted 4 lines
That shouldn't be required for this particular issue/case, IIUIC. One of the things we checked early on was disabling deferred TLB flush (similarly to what you've done), and it didn't help with the issue; also, the issue happens on uniprocessor mode too (thus no remote CPU involved.)
I guess you didn't try it with
page_mapcount+ 1 ==page_countat tha time? Anyway, I agree we don't need TLB flush here like KSM.
Sorry, I fail to understand how the page (map) count and TLB flush would be related.
(I realize you and Yu Zhao already confirmed the TLB flush is not needed/expected
to fix the issue too; but just for my own education, if you have a chance.)
Quoted 3 lines
I think the reason KSM is doing TLB flush before the check it to make sure trap trigger on the write from userprocess in other core. However, this
MADV_FREEcase, HW already gaurantees the trap.
Understood.
Quoted 34 lines
Please see below.
Quoted 23 lines
Quoted 23 lines
Something like this.
mm/rmap.c +0
-10@@ -1599,18 +1599,8 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -int refcount =page_ref_count (page); - -/* -* The only page refs must be from the isolation -* (checked by the caller shrink_page_list() too) -* and the (single) rmap (dropped by discard:). -* -* Check the reference count before dirty flag -* with memory barrier; see __remove_mapping(). -*/ Quoted 8 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1603
Quoted 4 lines
mm/rmap.c +2
-2-smp_rmb (); -if (refcount ==2 && !PageDirty (page)) { +if (!PageDirty (page) && +page_mapcount (page) +1 ==page_count (page)) {In the interest of avoiding a different race/bug, it seemed worth following the suggestion outlined in
__remove_mapping(), i.e., checkingPageDirty()after the page's reference count, with a memory barrier in between.
Quoted 1 line
True so it means your patch as-is is good for me.
That's good news! Thanks for all your help, review, and discussion so far; it's been very educational.
I see Yu Zhao mentioned a possible concern/suggestion with additional memory barriers elsewhere.
I'll try and dig to understand/check that in more detail and follow up.
Quoted 7 lines
Quoted 6 lines
I'm not familiar with the details of the original issue behind that code change, but it seemed to be possible here too, particularly as writes from user-space can happen asynchronously / after
try_to_unmap_one()checked PTE clean and didn't set PageDirty, and if the page's PTE is present, there's no fault?
Quoted 7 lines
Yeah, it was discussed.
For clean pte, CPU has to fetch and update the actual pte entry, not TLB so trap triggers for
MADV_FREEpage.https://lkml.org/lkml/2015/4/15/565
https://lkml.org/lkml/2015/4/16/136
Thanks for the pointers; great reading.
cheers,
Signature · 1 line
Mauricio Faria de Oliveira
Quoted 61 lines · Mauricio Faria de Oliveira
Hi Minchan Kim,
Thanks for handling the hard questions! :)
Quoted 46 lines · Minchan Kim
Quoted 36 lines · Ying
Quoted 25 lines · Yu Zhao
Quoted 24 lines · Mauricio Faria de Oliveira
mm/rmap.c +14
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* +* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {/* Invalidate as we cleared the pte */ Quoted 8 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1606
Quoted 2 lines
mm/rmap.c +0
-0mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );Out of curiosity, how does it work with COW in terms of reordering? Specifically, it seems to me
get_page()andpage_dup_rmap()incopy_present_pte()can happen in any order, and ifpage_dup_rmap()is seen first, and direct io is holding a refcnt, this check can still pass?Quoted 7 lines
I think that you are correct.
After more thoughts, it appears very tricky to compare page count and map count. Even if we have added
smp_rmb()betweenpage_ref_count()andpage_mapcount(), an interrupt may happen between them. During the interrupt, the page count and map count may be changed, for example, unmapped, ordo_swap_page().Quoted 8 lines
Yeah, it happens but what specific problem are you concerning from the count change under race? The fork case Yu pointed out was already known for breaking DIO so user should take care not to fork under
DIO(Please look at O_DIRECT section in man 2 open). If you could give a specific example, it would be great to think over the issue.I agree it's little tricky but it seems to be way other place has used for a long
time(Please look at write_protect_page in ksm.c).
Quoted 8 lines
Ah, that's great to see it's being used elsewhere, for DIO particularly!
Quoted 1 line
So, here what we missing is tlb flush before the checking.
That shouldn't be required for this particular issue/case, IIUIC. One of the things we checked early on was disabling deferred TLB flush (similarly to what you've done), and it didn't help with the issue; also, the issue happens on uniprocessor mode too (thus no remote CPU involved.)
Fast gup doesn't block tlb flush; it only blocks IPI used when freeing page tables. So it's expected that forcing a tlb flush doesn't fix the problem.
But it still seems to me the fix is missing smp_mb(). IIUC, a proper fix would require, on the dio side
inc page refcntsmp_mb()
read pte
and on the rmap side
clear ptesmp_mb()
read page refcnt
try_grab_compound_head() implies smp_mb, but i don't think ptep_get_and_clear() does.
mapcount, as Minchan said, probably is irrelevant given dio is already known to be broken with fork.
I glanced at the thread and thought it might be worth menthing.
Quoted 87 lines · Yu Zhao
Quoted 61 lines · Mauricio Faria de Oliveira
Hi Minchan Kim,
Thanks for handling the hard questions! :)
Quoted 46 lines · Minchan Kim
Quoted 36 lines · Ying
Quoted 25 lines · Yu Zhao
Quoted 24 lines · Mauricio Faria de Oliveira
mm/rmap.c +14
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* +* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {/* Invalidate as we cleared the pte */ Quoted 8 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1606
Quoted 2 lines
mm/rmap.c +0
-0mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );Out of curiosity, how does it work with COW in terms of reordering? Specifically, it seems to me
get_page()andpage_dup_rmap()incopy_present_pte()can happen in any order, and ifpage_dup_rmap()is seen first, and direct io is holding a refcnt, this check can still pass?Quoted 7 lines
I think that you are correct.
After more thoughts, it appears very tricky to compare page count and map count. Even if we have added
smp_rmb()betweenpage_ref_count()andpage_mapcount(), an interrupt may happen between them. During the interrupt, the page count and map count may be changed, for example, unmapped, ordo_swap_page().Quoted 8 lines
Yeah, it happens but what specific problem are you concerning from the count change under race? The fork case Yu pointed out was already known for breaking DIO so user should take care not to fork under
DIO(Please look at O_DIRECT section in man 2 open). If you could give a specific example, it would be great to think over the issue.I agree it's little tricky but it seems to be way other place has used for a long
time(Please look at write_protect_page in ksm.c).Quoted 8 lines
Ah, that's great to see it's being used elsewhere, for DIO particularly!
Quoted 1 line
So, here what we missing is tlb flush before the checking.
That shouldn't be required for this particular issue/case, IIUIC. One of the things we checked early on was disabling deferred TLB flush (similarly to what you've done), and it didn't help with the issue; also, the issue happens on uniprocessor mode too (thus no remote CPU involved.)
Fast gup doesn't block tlb flush; it only blocks IPI used when freeing page tables. So it's expected that forcing a tlb flush doesn't fix the problem.
But it still seems to me the fix is missing
smp_mb(). IIUC, a proper fix would require, on the dio side
inc page refcntsmp_mb()
read pteand on the rmap side
clear ptesmp_mb()
read page refcnt
Quoted 7 lines
try_grab_compound_head()impliessmp_mb, but i don't thinkptep_get_and_clear()does.mapcount, as Minchan said, probably is irrelevant given dio is already known to be broken with fork.
I glanced at the thread and thought it might be worth menthing.
If the madv_freed page is shared among processes, it means the ptes pointing the page are CoW state. If DIO is about to work with the page, gup_fast will fallback to slow path and then break the CoW using faultin_page before the submit bio. Thus, the page is not shared any longer and the pte was alrady marked as dirty on fault handling. Thus, I think there is no race.
Only, problem is race between DIO and reclaim on exclusive private madv_free page. In the case, page_count would be only racy. If ptep_get_and_clear is unordered, yeah, we need barrier there. (Looks like unorder since ARM uses xchg_relaxed).
Quoted 104 lines · Minchan Kim
Quoted 87 lines · Yu Zhao
Quoted 61 lines · Mauricio Faria de Oliveira
Hi Minchan Kim,
Thanks for handling the hard questions! :)
Quoted 46 lines · Minchan Kim
Quoted 36 lines · Ying
Quoted 25 lines · Yu Zhao
Quoted 24 lines · Mauricio Faria de Oliveira
mm/rmap.c +14
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* +* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {/* Invalidate as we cleared the pte */ Quoted 8 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1606
Quoted 2 lines
mm/rmap.c +0
-0mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );Out of curiosity, how does it work with COW in terms of reordering? Specifically, it seems to me
get_page()andpage_dup_rmap()incopy_present_pte()can happen in any order, and ifpage_dup_rmap()is seen first, and direct io is holding a refcnt, this check can still pass?Quoted 7 lines
I think that you are correct.
After more thoughts, it appears very tricky to compare page count and map count. Even if we have added
smp_rmb()betweenpage_ref_count()andpage_mapcount(), an interrupt may happen between them. During the interrupt, the page count and map count may be changed, for example, unmapped, ordo_swap_page().Quoted 8 lines
Yeah, it happens but what specific problem are you concerning from the count change under race? The fork case Yu pointed out was already known for breaking DIO so user should take care not to fork under
DIO(Please look at O_DIRECT section in man 2 open). If you could give a specific example, it would be great to think over the issue.I agree it's little tricky but it seems to be way other place has used for a long
time(Please look at write_protect_page in ksm.c).Quoted 8 lines
Ah, that's great to see it's being used elsewhere, for DIO particularly!
Quoted 1 line
So, here what we missing is tlb flush before the checking.
That shouldn't be required for this particular issue/case, IIUIC. One of the things we checked early on was disabling deferred TLB flush (similarly to what you've done), and it didn't help with the issue; also, the issue happens on uniprocessor mode too (thus no remote CPU involved.)
Fast gup doesn't block tlb flush; it only blocks IPI used when freeing page tables. So it's expected that forcing a tlb flush doesn't fix the problem.
But it still seems to me the fix is missing
smp_mb(). IIUC, a proper fix would require, on the dio side
inc page refcntsmp_mb()
read pteand on the rmap side
clear ptesmp_mb()
read page refcntQuoted 7 lines
try_grab_compound_head()impliessmp_mb, but i don't thinkptep_get_and_clear()does.mapcount, as Minchan said, probably is irrelevant given dio is already known to be broken with fork.
I glanced at the thread and thought it might be worth menthing.
If the
madv_freedpage is shared among processes, it means the ptes pointing the page are CoW state. If DIO is about to work with the page,gup_fastwill fallback to slow path and then break the CoW usingfaultin_pagebefore the submit bio. Thus, the page is not shared any longer and the pte was alrady marked as dirty on fault handling. Thus, I think there is no race.
Quoted 4 lines
Only, problem is race between DIO and reclaim on exclusive private
madv_freepage. In the case,page_countwould be only racy. Ifptep_get_and_clearis unordered, yeah, we need barrier there. (Looks like unorder since ARM usesxchg_relaxed).
Sorry for the long delay in getting back to this.
Thanks to both of you for bringing this up and checking further! Agree; I missed this barrier was needed for the gup() fast path.
Just sent PATCH v3.
Signature · 1 line
Mauricio Faria de Oliveira
Quoted 45 lines · Minchan Kim
Quoted 36 lines · Ying
Quoted 25 lines · Yu Zhao
Quoted 24 lines · Mauricio Faria de Oliveira
mm/rmap.c +14
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* +* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {/* Invalidate as we cleared the pte */ Quoted 8 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1606
Quoted 2 lines
mm/rmap.c +0
-0mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );Out of curiosity, how does it work with COW in terms of reordering? Specifically, it seems to me
get_page()andpage_dup_rmap()incopy_present_pte()can happen in any order, and ifpage_dup_rmap()is seen first, and direct io is holding a refcnt, this check can still pass?Quoted 7 lines
I think that you are correct.
After more thoughts, it appears very tricky to compare page count and map count. Even if we have added
smp_rmb()betweenpage_ref_count()andpage_mapcount(), an interrupt may happen between them. During the interrupt, the page count and map count may be changed, for example, unmapped, ordo_swap_page().
Quoted 5 lines
Yeah, it happens but what specific problem are you concerning from the count change under race? The fork case Yu pointed out was already known for breaking DIO so user should take care not to fork under
DIO(Please look at O_DIRECT section in man 2 open). If you could give a specific example, it would be great to think over the issue.
Whether is the following race possible?
CPU0/Process A CPU1/Process B
-------------- --------------try_to_unmap_one
page_mapcount()
zap_pte_range()
page_remove_rmap()
atomic_add_negative(-1, &page->_mapcount)
tlb_flush_mmu()
...
put_page_testzero() page_count()
Previously I thought that there's similar race in do_swap_page(). But after more thoughts, I found that the page is locked in do_swap_page(). So do_swap_page() is safe. Per my understanding, except during fork() as Yu pointed out, the anonymous page must be locked before increasing its mapcount.
So, if the above race is possible, we need to guarantee to read page_count() before page_mapcount(). That is, something as follows,
count = page_count();
smp_rmb();
mapcount = page_mapcount();
if (!PageDirty(page) && mapcount + 1 == count) {
...
}Best Regards,
Huang, Ying
Quoted 44 lines
I agree it's little tricky but it seems to be way other place has used for a long
time(Please look at write_protect_page in ksm.c). So, here what we missing is tlb flush before the checking.Something like this.
mm/rmap.c +2
-12@@ -1599,18 +1599,8 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -int refcount =page_ref_count (page); - -/* -* The only page refs must be from the isolation -* (checked by the caller shrink_page_list() too) -* and the (single) rmap (dropped by discard:). -* -* Check the reference count before dirty flag -* with memory barrier; see __remove_mapping(). -*/ -smp_rmb (); -if (refcount ==2 && !PageDirty (page)) { +if (!PageDirty (page) && +page_mapcount (page) +1 ==page_count (page)) {/* Invalidate as we cleared the pte */ mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );mm/vmscan.c +3
-0@@ -1754,6 +1754,9 @@ static unsigned int shrink_page_list(struct list_head *page_list,enum ttu_flags flags =TTU_BATCH_FLUSH ;bool was_swapbacked =PageSwapBacked (page); +if (!was_swapbacked &&PageAnon (page)) + flags &= ~TTU_BATCH_FLUSH ; +if (unlikely (PageTransHuge (page))) flags |=TTU_SPLIT_HUGE_PMD ;
Quoted 59 lines · Ying
Quoted 45 lines · Minchan Kim
Quoted 36 lines · Ying
Quoted 25 lines · Yu Zhao
Quoted 24 lines · Mauricio Faria de Oliveira
mm/rmap.c +14
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* +* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {/* Invalidate as we cleared the pte */ Quoted 8 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1606
Quoted 2 lines
mm/rmap.c +0
-0mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );Out of curiosity, how does it work with COW in terms of reordering? Specifically, it seems to me
get_page()andpage_dup_rmap()incopy_present_pte()can happen in any order, and ifpage_dup_rmap()is seen first, and direct io is holding a refcnt, this check can still pass?Quoted 7 lines
I think that you are correct.
After more thoughts, it appears very tricky to compare page count and map count. Even if we have added
smp_rmb()betweenpage_ref_count()andpage_mapcount(), an interrupt may happen between them. During the interrupt, the page count and map count may be changed, for example, unmapped, ordo_swap_page().Quoted 5 lines
Yeah, it happens but what specific problem are you concerning from the count change under race? The fork case Yu pointed out was already known for breaking DIO so user should take care not to fork under
DIO(Please look at O_DIRECT section in man 2 open). If you could give a specific example, it would be great to think over the issue.Whether is the following race possible?
CPU0/Process A CPU1/Process B
-------------- --------------try_to_unmap_one
page_mapcount()
Quoted 8 lines
zap_pte_range() page_remove_rmap() atomic_add_negative(-1, &page->_mapcount) tlb_flush_mmu() ... put_page_testzero()
page_count()
It seems they're under the same page table Lock.
Thanks.
Quoted 65 lines
Previously I thought that there's similar race in
do_swap_page(). But after more thoughts, I found that the page is locked indo_swap_page(). Sodo_swap_page()is safe. Per my understanding, except duringfork()as Yu pointed out, the anonymous page must be locked before increasing its mapcount.So, if the above race is possible, we need to guarantee to read
page_count()beforepage_mapcount(). That is, something as follows,count = page_count(); smp_rmb(); mapcount = page_mapcount(); if (!PageDirty(page) && mapcount + 1 == count) { ... }Best Regards,
Huang, YingQuoted 36 lines
I agree it's little tricky but it seems to be way other place has used for a long
time(Please look at write_protect_page in ksm.c). So, here what we missing is tlb flush before the checking.Something like this.
mm/rmap.c +2
-12@@ -1599,18 +1599,8 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -int refcount =page_ref_count (page); - -/* -* The only page refs must be from the isolation -* (checked by the caller shrink_page_list() too) -* and the (single) rmap (dropped by discard:). -* -* Check the reference count before dirty flag -* with memory barrier; see __remove_mapping(). -*/ -smp_rmb (); -if (refcount ==2 && !PageDirty (page)) { +if (!PageDirty (page) && +page_mapcount (page) +1 ==page_count (page)) {/* Invalidate as we cleared the pte */ mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );mm/vmscan.c +0
-0mm/vmscan.c static unsigned int shrink_page_list(struct list_head *page_list, · line 1761
Quoted 8 lines
mm/vmscan.c +3
-0@@ -1754,6 +1754,9 @@ static unsigned int shrink_page_list(struct list_head *page_list,enum ttu_flags flags =TTU_BATCH_FLUSH ;bool was_swapbacked =PageSwapBacked (page); +if (!was_swapbacked &&PageAnon (page)) + flags &= ~TTU_BATCH_FLUSH ; +if (unlikely (PageTransHuge (page))) flags |=TTU_SPLIT_HUGE_PMD ;.
Quoted 69 lines · Miaohe Lin
Quoted 59 lines · Ying
Quoted 45 lines · Minchan Kim
Quoted 36 lines · Ying
Quoted 25 lines · Yu Zhao
Quoted 24 lines · Mauricio Faria de Oliveira
mm/rmap.c +14
-1@@ -1570,7 +1570,20 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -if (!PageDirty (page)) { +int ref_count =page_ref_count (page); +int map_count =page_mapcount (page); + +/* +* The only page refs must be from the isolation +* (checked by the caller shrink_page_list() too) +* and one or more rmap's (dropped by discard:). +* +* Check the reference count before dirty flag +* with memory barrier; see __remove_mapping(). +*/ +smp_rmb (); +if ((ref_count -1 == map_count) && + !PageDirty (page)) {/* Invalidate as we cleared the pte */ Quoted 8 lines
mm/rmap.c static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma, · line 1606
Quoted 2 lines
mm/rmap.c +0
-0mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );Out of curiosity, how does it work with COW in terms of reordering? Specifically, it seems to me
get_page()andpage_dup_rmap()incopy_present_pte()can happen in any order, and ifpage_dup_rmap()is seen first, and direct io is holding a refcnt, this check can still pass?Quoted 7 lines
I think that you are correct.
After more thoughts, it appears very tricky to compare page count and map count. Even if we have added
smp_rmb()betweenpage_ref_count()andpage_mapcount(), an interrupt may happen between them. During the interrupt, the page count and map count may be changed, for example, unmapped, ordo_swap_page().Quoted 5 lines
Yeah, it happens but what specific problem are you concerning from the count change under race? The fork case Yu pointed out was already known for breaking DIO so user should take care not to fork under
DIO(Please look at O_DIRECT section in man 2 open). If you could give a specific example, it would be great to think over the issue.Whether is the following race possible?
CPU0/Process A CPU1/Process B
-------------- --------------try_to_unmap_one
page_mapcount()Quoted 8 lines
zap_pte_range() page_remove_rmap() atomic_add_negative(-1, &page->_mapcount) tlb_flush_mmu() ... put_page_testzero()
page_count()
Quoted 1 line
It seems they're under the same page table Lock.
This is for a page shared by 2 processes (Process A/B above). But you reminded me that an anonymous page cannot be shared between multiple processes after direct IO. Because direct IO read un-shares the page, and fork() isn't allowed, I guess ksm isn't allowed too.
So the above race isn't possible. Sorry for confusing.
Best Regards,
Huang, Ying
Quoted 67 lines
Thanks.
Quoted 65 lines
Previously I thought that there's similar race in
do_swap_page(). But after more thoughts, I found that the page is locked indo_swap_page(). Sodo_swap_page()is safe. Per my understanding, except duringfork()as Yu pointed out, the anonymous page must be locked before increasing its mapcount.So, if the above race is possible, we need to guarantee to read
page_count()beforepage_mapcount(). That is, something as follows,count = page_count(); smp_rmb(); mapcount = page_mapcount(); if (!PageDirty(page) && mapcount + 1 == count) { ... }Best Regards,
Huang, YingQuoted 36 lines
I agree it's little tricky but it seems to be way other place has used for a long
time(Please look at write_protect_page in ksm.c). So, here what we missing is tlb flush before the checking.Something like this.
mm/rmap.c +2
-12@@ -1599,18 +1599,8 @@ static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,/* MADV_FREE page check */ if (!PageSwapBacked (page)) { -int refcount =page_ref_count (page); - -/* -* The only page refs must be from the isolation -* (checked by the caller shrink_page_list() too) -* and the (single) rmap (dropped by discard:). -* -* Check the reference count before dirty flag -* with memory barrier; see __remove_mapping(). -*/ -smp_rmb (); -if (refcount ==2 && !PageDirty (page)) { +if (!PageDirty (page) && +page_mapcount (page) +1 ==page_count (page)) {/* Invalidate as we cleared the pte */ mmu_notifier_invalidate_range (mm, address, address +PAGE_SIZE );mm/vmscan.c +0
-0mm/vmscan.c static unsigned int shrink_page_list(struct list_head *page_list, · line 1761
Quoted 8 lines
mm/vmscan.c +3
-0@@ -1754,6 +1754,9 @@ static unsigned int shrink_page_list(struct list_head *page_list,enum ttu_flags flags =TTU_BATCH_FLUSH ;bool was_swapbacked =PageSwapBacked (page); +if (!was_swapbacked &&PageAnon (page)) + flags &= ~TTU_BATCH_FLUSH ; +if (unlikely (PageTransHuge (page))) flags |=TTU_SPLIT_HUGE_PMD ;.