🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: muc.lists.freebsd.bugs
Article #898

[Bug 301482] mincore(2): a scan restart after a concurrent map change zeroes vector entries already filled, and can fail with EN...

#898
From: bugzilla-noreply
Date: Fri, 04 Dec 2026 05:53
188 lines
9546 bytes
https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=301482

            Bug ID: 301482
           Summary: mincore(2): a scan restart after a concurrent map
                    change zeroes vector entries already filled, and can
                    fail with ENOMEM
           Product: Base System
           Version: 15.1-RELEASE
          Hardware: Any
                OS: Any
            Status: New
          Severity: Affects Some People
          Priority: ---
         Component: kern
          Assignee: bugs@FreeBSD.org
          Reporter: noel.minamino@gmail.com

Created attachment 278178
  --> https://bugs.freebsd.org/bugzilla/attachment.cgi?id=278178&action=edit
patch

Product: Base System   Component: kern   Version: 15.1-RELEASE

Attachments:
  mc3e.c                 reproducer (counts wrong zeros and ENOMEM)
  mc4.c                  shows that repeating the call does not hide it
  mincore-restart.diff   proposed fix, against main (applies to releng/15.1)

------------------------------------------------------------------------

Description

When another thread of the same process changes the memory map (mmap,
munmap) while mincore(2) runs, kern_mincore() restarts its scan. After
the restart it writes 0 into vector entries it had already filled with
correct values. As a result:

- Mapped, resident pages are reported as not resident (vec[i] == 0).
- A one-page call is affected too: a change seen at the final check
  zeroes the whole vector.
- The call can fail with ENOMEM for a range that is fully mapped, when
  the restart position is the end of the range and that address lies in
  a hole.
- Under a steady stream of map changes the call restarts again and
  again and becomes very slow.

The wrong values are always zeros: a mapped page reported as not
resident.

The body of kern_mincore() is identical in main, stable/15, releng/15.1,
stable/14 and releng/14.3; only the line numbers differ.

------------------------------------------------------------------------

Where (sys/vm/vm_mmap.c, line numbers for main / stable/14)

  RestartScan: label, lookup at the current addr     857, 860 / 834, 837
  lastvecindex = -1;                                 870      / 847
  zero-fill of skipped entries                       1005     / 982
  goto RestartScan after subyte()                    1029     / 1006
  zero-fill of the last entries                      1044-1052 / 1021-1029
  final goto RestartScan                             1060     / 1037

The restart resumes at the current addr but resets lastvecindex to -1.
The first subyte() after the restart then zeroes vec[0 .. vecindex-1],
which already held correct values.

A restart detected after the last page (addr == end) looks up the entry
at end:
- if an entry contains end, the scan loop does nothing and the trailing
  zero-fill writes 0 into every entry;
- if no entry contains end (a hole after the range), the call returns
  ENOMEM.

------------------------------------------------------------------------

How to reproduce

mc3e.c maps a 256-page file MAP_SHARED, touches every page, starts
threads that mmap() and munmap() 64 KiB of anonymous memory in a loop,
and calls mincore() over the 256 pages (and once per round on a single
page). It counts calls that report a mapped page as 0, and calls that
fail with ENOMEM.

  cc -O1 -pthread -o mc3e mc3e.c
  ./mc3e /some/dir 300 1        (directory, calls, map-changing threads)

------------------------------------------------------------------------

Results

amd64 VM with 6 vCPUs, vm.mincore_mapped=1 (default). "Unpatched" is
15.1-RELEASE-p6 GENERIC; "patched" is releng/15.1 (15.1-RELEASE-p8)
GENERIC with the attached diff. Same machine, same binaries. One
map-changing thread, 300 calls of 256 pages, unless noted.

                                        unpatched            patched
  UFS: calls with wrong zeros           218 (35,650 entries) 0
  UFS: one-page calls with a zero       23 of 300            0 of 300
  tmpfs: calls with wrong zeros         189 (30,799 entries) 0
  tmpfs: one-page calls with a zero     17 of 300            0 of 300
  tmpfs: calls failing with ENOMEM      2                    0
  UFS, no map-changing thread,
    100,000 calls: wrong zeros          0                    0
  time for 300 calls                    24 s                 26 s
  100,000 calls, one map-changing
    thread                              not done in 600 s    not done in 600 s

Earlier, on 15.1-RELEASE-p7 with ZFS: 252 of 300 calls reported wrong
zeros (35,659 entries).

Without map changes one call takes about 7 us; with one map-changing
thread about 80 ms, with or without the patch.

Repeating the call and ORing the results (mc4.c) reduces the error but
does not remove it. Of 76,800 mapped page entries (300 rounds of 256
pages), the number still reported as 0 after 1, 2, 3, 4 and 8 calls:

  unpatched   31,433 / 15,072 / 8,749 / 5,153 / 1,197
  patched          0 /      0 /     0 /     0 /     0

The libc test lib/libc/sys/mincore_test (kyua) passes 3/3 with both
kernels (run in a bhyve guest).

------------------------------------------------------------------------

Proposed fix (attached as mincore-restart.diff)

On a restart, scan the whole range again: set addr = first_addr together
with lastvecindex = -1, so every entry is rewritten with a fresh value.
A restart then no longer returns ENOMEM for a range that was fully
mapped, and a restart after the last page no longer zeroes the vector.

  --- a/sys/vm/vm_mmap.c
  +++ b/sys/vm/vm_mmap.c
  @@ -857,6 +857,14 @@
   RestartScan:
        timestamp = map->timestamp;

  +     /*
  +      * After a restart, scan the whole range again.  lastvecindex is reset
  +      * below, so resuming at the current addr would overwrite the entries
  +      * already written with zeroes, and a restart detected at addr == end
  +      * would zero the whole vector or fail with ENOMEM.
  +      */
  +     addr = first_addr;
  +
        if (!vm_map_lookup_entry(map, addr, &entry)) {
                vm_map_unlock_read(map);
                return (ENOMEM);

The patch fixes the wrong values only. The slowness under heavy map
changes stays as it is (see the timings above). It could be addressed
separately, for example with a bounded number of restarts, or by filling
a kernel buffer under the map lock and copying it out once at the end
instead of calling subyte() page by page with the lock dropped. I have
not tried those.

------------------------------------------------------------------------

Impact

Programs that use mincore() to decide whether touching a page will
fault get wrong "not resident" answers whenever other threads mmap() or
munmap(), for example through a memory allocator.

I found this while developing KariDNS, an authoritative DNS server for
FreeBSD only, which I am writing for research. It serves zones from
memory-mapped files and keeps bitmaps of which pages are resident,
using mincore(). Mapped pages were counted as evicted, which triggered
its page reclaim logic without any real memory pressure.

I found and analysed this with the help of an AI coding assistant. I
checked the source analysis and ran the measurements above myself.

-- 
You are receiving this mail because:
You are the assignee for the bug.

--
Posted automagically by a mail2news gateway at muc.de e.V.
Please direct questions, flames, donations, etc. to news-admin@muc.de
Technical Details
Message-ID: <bug-301482-227@https.bugs.freebsd.org/bugzilla/>
Path: mbox-mo1.pugleaf.net!feed-us-txt.newsdeef.eu!feed-us-mo.newsdeef.eu!srv.newsdeef.eu!weretis.net!feeder8.news.weretis.net!3.eu.feeder.erje.net!feeder.erje.net!news2.arglkargh.de!news.karotte.org!news.muc.de!.POSTED.news.muc.de!not-for-mail

Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!feed-us-txt.newsdeef.eu!feed-us-mo.newsdeef.eu!srv.newsdeef.eu!weretis.net!feeder8.news.weretis.net!3.eu.feeder.erje.net!feeder.erje.net!news2.arglkargh.de!news.karotte.org!news.muc.de!.POSTED.news.muc.de!not-for-mail
From: bugzilla-noreply@freebsd.org
Newsgroups: muc.lists.freebsd.bugs
Subject: [Bug 301482] mincore(2): a scan restart after a concurrent map
 change zeroes vector entries already filled, and can fail with ENOMEM
Date: Fri, 04 Dec 2026 05:53:57 +0000
Organization: Newsgate at muc.de e.V.
Approved: news-admin@muc.de
Distribution: world
Message-ID: <bug-301482-227@https.bugs.freebsd.org/bugzilla/>
MIME-Version: 1.0
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable
Injection-Info: news.muc.de; posting-host="news.muc.de:193.149.48.2";
	logging-data="9165"; mail-complaints-to="news-admin@muc.de"
X-Original-To: bugs@mlmmj.nyi.freebsd.org
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=freebsd.org; s=dkim;
	t=1796363637;
	h=from:from:reply-to:subject:subject:date:date:message-id:message-id:
	 to:to:cc:mime-version:mime-version:content-type:content-type:
	 content-transfer-encoding:content-transfer-encoding;
	bh=fP4YG/jtrUh4RiOf+lHPEZ8aTVk8d3wRhoVDTU/ZMMw=;
	b=aPBcfnr1zDFtCX24mK++eE1vvplTZbrcK/q4XGGHt5xmmQM1FvFeBjIuvGXyIDX1VHM/rp
	l+cl2AGGHxASnlcCviX6oX/3JFaTyr/atC7ciQAXOFIZzKvk6ERK8L7Ia4P3XAq/IUAhth
	cKtkXXUNq+Jx5fiO6SgBrWNc1ivSC384u4N3FKsK5UHmubemkQvPS2BGAXKgotHP/RR8aL
	4nA1ZbYJSTqwQ8uh94LFmxRZN3jYH8eycmmblnKdCZE1y9JTOvpMEtNepcwKhP4cnFVIpK
	KDg1wv2k1lVUUuPNfk2ZBszp6qSwsdlCgB2B9xMGmp9KnT9g6VQ+bTtpw9jb7Q==
X-Authentication-Warning: kenobi.freebsd.org: www set sender to bugzilla-noreply@freebsd.org using -f
Auto-Submitted: auto-generated
Precedence: list
X-Newsgate-Id: f02c70b8849f+
X-No-Archive: Yes