# When one byte became a page: fixing FreeBSD's Linuxulator `brk()`

Updated 2026-10-27, including the current-main review patches and final
FreeBSD 16.0-CURRENT guest results.

An old Linux application, Red Baron 3.10, was crashing during startup on
FreeBSD. Its memory allocator had asked the operating system to extend its
heap. The request succeeded, but the address returned to the application
was different from the address it had requested.

Here is the bug reduced to two system calls:

```text
brk(0)          -> 0x00403000
brk(0x00403001) -> 0x00404000
```

The second call asks for a break one byte beyond the first address. Linux
should return `0x00403001` when that request succeeds. FreeBSD's Linux
compatibility layer returned the next page boundary instead.

Fixing the return value required more than changing one assignment. The
kernel had to remember the exact address across queries, preserve it across
`fork()`, discard it on `exec()`, and keep low-address queries from unmapping
the application's own data.

The shared `kern_break()` helper predates this work: FreeBSD introduced it
in 2018. This investigation builds on that design and addresses the exact
logical break that Linux applications observe.

The first fix passed 19 regression checks. Review then found four more
bugs: an incomplete lower bound, two races, and a misaligned test stack.
The final fix passes all 28 Linux checks on a patched FreeBSD 16.0-CURRENT
guest, including concurrent calls and 5,000 forks. Both native and Linux
test cases also pass through FreeBSD's test framework. The work is now
packaged for upstream review; it has not been submitted or accepted.

This is the path from the original crash to the corrected implementation,
the tests that exposed its remaining bugs, and the preparation needed for
other FreeBSD developers to review it.

## How a Linux application runs on FreeBSD

FreeBSD is its own operating system, with its own kernel and system-call
interfaces. A Linux executable expects the Linux interfaces instead.
FreeBSD's **Linuxulator** implements Linux binary compatibility so that
supported Linux executables can run under the FreeBSD kernel. The
[FreeBSD Handbook's Linux compatibility chapter](https://docs.freebsd.org/en/books/handbook/linuxemu/)
is a useful introduction.

The interface a compiled program expects is called an **ABI**, short for
application binary interface. It includes details such as system-call
numbers, argument locations, data structures, and return values. A system
call is a request from an application to the kernel to perform an operation
such as reading a file or changing a memory mapping.

In this investigation, a 32-bit x86 Linux program ran on an amd64 FreeBSD
system. Its instructions ran on the processor; FreeBSD handled its Linux
system calls. There was no Linux kernel involved. Later, a virtual machine
was used to test a modified **FreeBSD** kernel.

That distinction matters: an application can load and execute correctly,
yet fail because one system call returns a subtly incompatible result.

## The heap has a byte address; memory mappings have page boundaries

A process has a virtual address space: the addresses its instructions use
when accessing memory. The kernel maintains mappings that connect ranges
of those addresses to memory and define permissions such as read and write.

One traditional way to obtain memory for an allocator is to grow the
process's data area. Its end is called the **program break**. Moving the
break upward makes room for heap allocations; moving it downward can
release memory. Allocators can also use mechanisms such as `mmap()`, so
`brk()` is only one part of the memory-allocation story.

The kernel manages these mappings in pages. The test environment used
4 KiB pages: 4,096 bytes, or `0x1000` in hexadecimal. Allocator bookkeeping,
however, can use byte addresses.

These are two different values:

| Request | Logical break visible to Linux | Page boundary needed for the mapping |
|---|---|---|
| Initial query | `0x00403000` | `0x00403000` |
| Grow by one byte | `0x00403001` | `0x00404000` |
| Grow farther within that page | `0x00403100` | `0x00404000` |
| Grow into the following page | `0x00404001` | `0x00405000` |

The mapped range can extend beyond the logical break because it covers
whole pages. The logical break is still an exact byte address, marking the
end of the requested data area.

The raw Linux `brk` system call returns the requested break on successful
movement, or the current break when it cannot make the change. A zero
argument is conventionally used to query the current break. This differs
from the C library's `brk()` function, whose usual interface returns zero
on success and minus one on failure. The library implements that interface
around the underlying system call. The distinction is documented in the
[Linux `brk(2)` manual's library/kernel notes](https://man7.org/linux/man-pages/man2/brk.2.html).

The bug was in the raw system-call result seen by the Linux program.

## Why the original application rejected successful growth

The saved application trace showed the same pattern at a different address:

```text
CALL  linux_brk(0x082ee290)
RET   linux_brk 137293824/0x082ef000
PSIG  SIGSEGV SIG_DFL code=SEGV_MAPERR
```

`0x082ef000` is `0x082ee290` rounded up to a 4 KiB boundary.

Red Baron used an old Linux C library, `libc.so.5.3.12`. Disassembly of that
library showed its `__sbrk` path issuing Linux system call 45, then comparing
the returned break with the requested address. A mismatch took its error
path and set `errno` to `ENOMEM`, the error normally associated with an
unsatisfied memory request.

The allocator consequently returned a null pointer. The application's
startup code then used that pointer as the destination of a string copy
without checking it. Accessing address zero produced **SIGSEGV**, the
segmentation-fault signal.

There were two faults in that chain: an incompatible kernel return value
and an application that did not handle allocation failure. The latter
explained the crash; it did not excuse the former. The
[original investigation](LINUXULATOR_BRK.md) records the trace and disassembly
in more detail.

An existing `LD_PRELOAD` workaround replaced the application's allocator
with one using `mmap()`. Preloading makes a dynamic linker resolve selected
library calls to replacement functions. That let the application avoid the
broken heap-growth path, but it left the kernel's `brk` behavior unchanged.

## Removing the application from the experiment

To establish the kernel bug independently, the investigation used a tiny
Linux executable with no C library. The
[minimal assembly probe](brk-test/brk-probe.S) queried the break, requested
one byte more, and wrote three addresses: initial, requested, and returned.

For the Linux/i386 ABI, `brk` is system call 45. The system-call number goes
in register `%eax`, the requested address goes in `%ebx`, and the result
comes back in `%eax`. The instruction `int $0x80` enters the kernel.
The central operation looks like this:

```asm
movl $45, %eax
xorl %ebx, %ebx
int $0x80               /* Query the current break. */

leal 1(%eax), %ebx      /* Request one byte more. */
movl $45, %eax
int $0x80               /* Result should equal the request in %ebx. */
```

The probe produced:

```text
initial     requested   returned
00403000    00403001    00404000
```

It exited with status 1 to indicate the mismatch. This reproduction needed
neither Red Baron nor its old libraries, window system, or allocator.
The register convention above is specifically for 32-bit Linux x86;
other ABIs use different system-call conventions.

## What FreeBSD changed in 2018

On June 27, 2018, Ed Maste committed
[r335702, now Git commit `e8a1ec3e0590`](https://github.com/freebsd/freebsd-src/commit/e8a1ec3e059000c939e42cc3c22036fad0474ac5),
with the work discussed in [review D16019](https://reviews.freebsd.org/D16019?id=44526).

Previously, `linux_brk()` called FreeBSD's native `sys_break()` system-call
handler directly. The 2018 change extracted the VM implementation into
`kern_break()`, which both handlers could call. The aim was to share the
VM work through an internal helper, allowing each system-call handler to
manage its own entry and return behavior.

The author also described a return-address bug fix: Linuxulator would
return the “actual (rounded up) break address” instead of the requested
value. Before that change, Linuxulator passed the request in a separate
argument structure and retained its local requested address. Afterward,
it passed `&new` to the helper, which replaced `new` with the rounded
address. The Linux handler returned that modified value.

The [committed diff](https://github.com/freebsd/freebsd-src/commit/e8a1ec3e059000c939e42cc3c22036fad0474ac5)
therefore shows how the successful return changed. That rounded address
describes the mapping end; Linux's raw `brk` contract requires the exact
logical break. The earlier query/failure path already used page-based
accounting, so returning to the pre-2018 code would not establish complete
Linux compatibility. No before-and-after boot test of those historical
kernels was performed here.

The present fix retains the shared helper and its mapping, resource-limit
and accounting work. It adds byte-precise state to the VM space and returns
a locked snapshot of that state to Linux callers. Native FreeBSD callers
keep their rounded result. Queries, refused requests, fork and exec must
preserve the appropriate logical value as well. These are the additional
requirements investigated and tested below.

## Where the requested address was lost

The relevant FreeBSD code lives in two places under `/usr/src/sys`:

- `compat/linux/linux_misc.c` contains `linux_brk()`, the Linux system-call handler.
- `vm/vm_unix.c` contains `kern_break()`, the shared kernel helper that changes data-area mappings.

At the start of this investigation, the post-2018 handler passed the
address of a local variable to the helper:

```c
new = (uintptr_t)args->dsend;
if ((caddr_t)new > vm->vm_daddr && !kern_break(td, &new))
    td->td_retval[0] = (register_t)new;
```

In C, `&new` means the address of `new`. It lets the called function replace
that variable's contents. `kern_break()` did exactly that. Its mapping
calculations used the page-rounded request, and its successful return path
wrote that rounded address back through the pointer:

```c
new = round_page(*addr);
/* Resource checks and mapping changes occur here. */
if (error == 0)
    *addr = new;
```

The Linux handler then returned the modified variable to the application.
`td->td_retval[0]` is the kernel's saved system-call return-value slot; the
system-call machinery transfers it to the appropriate user register.

There are two return channels here. The C return value of `kern_break()`
is an error code, where zero means success. The pointer argument carries
an address back to its caller. Confusing those roles makes this code much
harder to follow.

The 2018 extraction remains useful: both callers share the VM work. The
incompatibility is exposing its page-rounded mapping end as the Linux
logical break.

## Keeping the exact break in the address space

Returning the original request would fix the immediate success result, but
a later `brk(0)` still needs to recover the same exact value. The existing
data-size accounting used a page count and could not retain the byte offset.

The completed fix adds two fields to FreeBSD's `struct vmspace`:

```c
vm_offset_t vm_brk;      /* logical break, protected by the map lock */
vm_offset_t vm_brk_min;  /* initial break, protected by the map lock */
```

Both start at zero. `vm_brk` remembers the current byte address;
`vm_brk_min` remembers the lowest address Linux may accept as a new break.

A VM space represents a process's virtual-memory environment. Keeping the
break there ties it to the address space whose mappings it describes.

`vmspace_alloc()` initializes both fields to zero. On first use,
`kern_break()` initializes them from the existing mapped data end. It keeps
two values while handling a request:

```c
logical = *addr;
new = round_page(logical);
```

`logical` is the byte address to remember; `new` is the boundary used for
mapping and accounting. The helper retains its existing resource-limit
checks and mapping operations. Once a resize succeeds, it updates the
saved logical value, including when the request stays within an already
mapped page. A failed resize leaves an established logical break intact.

These updates occur while the VM map lock is held. A lock prevents other
users of that map from changing its mapping state during the protected
operation. This places the bookkeeping beside the operation that makes it
valid, rather than recording success before memory work has finished.

The Linux handler returns a local copy of `vm_brk` captured by the helper
while holding the map lock. Its final call is:

```c
new = (uintptr_t)args->dsend;
(void)kern_break(td, &new, true);
td->td_retval[0] = (register_t)new;
```

The third argument selects Linux semantics: enforce the initial break
floor and return the logical address, including when growth is refused.
The native FreeBSD caller passes `false` and retains the rounded success
address and native error handling. The local copy matters when another
process shares the same address space, as the later review demonstrated.

### Queries must remain queries

`kern_break()` also has a low-address query path. If a rounded request is
below its data-area base, it returns the old mapped end without changing
the mappings. A query must also leave the saved logical break unchanged.

The implementation therefore tracks an explicit `query` flag. Its final
bookkeeping is:

```c
if (error == 0 && !query)
    vm->vm_brk = (logical <= base) ? new : logical;
```

Here, `base` means the rounded **start of the data segment**. It is not
necessarily the initial program break, which is at the segment's end.
The conditional also accommodates the native helper's boundary behavior.
A successful resize and a successful query both return error code zero;
the flag preserves the distinction when updating the extra state.

### Fork copies the break; exec clears it

`fork()` creates a child process with its own copied address space. The
child must initially see the same logical break as its parent, so
`vmspace_fork()` copies both break fields while holding the parent's map
lock. The copied values therefore match the mappings copied into the child.
Subsequent child heap growth must leave the parent's break unchanged.

`exec()` replaces the running program. Its new image needs a fresh initial
break. Resetting the fields only in `vmspace_alloc()` is insufficient:
FreeBSD can empty and reuse an existing VM-space structure during exec.

The fix explicitly clears both saved values in `exec_new_vmspace()` after
selecting the new or reused address space:

```c
vmspace->vm_brk = 0;
vmspace->vm_brk_min = 0;
```

The first later break operation initializes both fields from the new
image's data layout. Copying on fork and clearing on exec are different
requirements, even though both operations are involved in starting programs.

## The regression test exposed an unmapping bug

The first version of the modified handler called `kern_break()`
unconditionally. That removed an important part of the old Linux handler:
its check against `vm_daddr`, the start of the data segment.

The verbose suite passed checks 1 through 13, then crashed during check 14,
which requested one page below the initial break. For that test binary,
the addresses were:

```text
Data-segment start:     0x00403000
Initial program break: 0x00404000
Check 14 request:      0x00403000
```

The request equalled the data-segment start. The helper's query condition
was strictly `new < base`; equality could proceed as a shrink. It therefore
unmapped the data page containing the program's own state. Subsequent
access to that state caused SIGSEGV.

This was a bug introduced while implementing the fix. It also explains why
a program can crash after earlier heap writes have worked: a later operation
can remove memory that was previously valid. The early, sparse output did
not establish which check crashed. Numbered results located it at check 14.

The first repair, preserved in patch 0003, translated requests at or below
the data-segment start into a zero-address query before calling the shared
helper:

```c
new = (uintptr_t)args->dsend;
if (new <= (uintptr_t)vm->vm_daddr)
    new = 0;
(void)kern_break(td, &new);
td->td_retval[0] = (register_t)vm->vm_brk;
```

That repair restored the old protection and made all 19 original checks
pass. It was still incomplete: the data segment can contain several pages,
and its start is lower than the initial break. Patch 0004 replaces this
historical handler with the locked helper call shown above.

## Review found four gaps behind a passing suite

A passing suite establishes the cases it actually exercises. The original
19 checks covered a low request at one particular boundary and used one
caller at a time. Broader probes exposed four problems.

### The minimum break is the data end, not its start

With an initial break of `0x00404000`, asking for `0x00403fff` incorrectly
changed the saved logical break. Both addresses round to the same page
boundary, so a page-level check missed the invalid byte-level shrink.
A separate probe with 16 KiB of initialized data requested an address inside
that data and then crashed when reading its last byte: whole data pages
had been unmapped.

The fix records the initial mapped data end in `vm_brk_min`. Under the map
lock, the Linux path treats every request below that floor as a query.
It returns the current logical break without shrinking mappings. The floor
survives fork and resets on exec, just like the current logical value.
This also preserves an unaligned current break after a rejected low request.
Native FreeBSD callers keep their existing lower-bound policy.

### A correct shared value can still be the wrong return value

The earlier handler read `vm_brk` after `kern_break()` released the map lock.
Suppose process A requests `base + 0x111`, and process B shares its address
space and requests `base + 0x222`. A can successfully complete its resize,
release the lock, and then read B's new value as its own result.

The probes used Linux's `clone()` system call with `CLONE_VM` to create a
separate process sharing its parent's address space. That worker can move
the same heap break while the parent is completing a call. Two virtual CPUs
allow those operations to run simultaneously.

This is a race: the result depends on how the processor schedules the two
callers. A two-CPU probe observed 13 wrong parent returns in 500,000 calls
and nine wrong worker returns. Both addresses were in the same heap page,
so no page allocation was needed to trigger the mistake.

The helper now copies the logical result through its pointer argument
before releasing the lock. Each handler returns that local snapshot.
Another caller may move the break immediately afterward; it cannot change
the already captured result of this call. Refused growth follows the same
rule and returns the exact current break under the lock.

### Fork must copy bookkeeping and mappings at the same moment

The first patch copied `vm_brk` near fields that do not change during a
program's lifetime, before acquiring the parent map lock. The logical break
is mutable. A shared-address-space worker could resize the heap between
that copy and the later mapping copy.

A probe found two failures among 500 forks: a child queried its inherited
break, wrote the byte immediately below it, and crashed. Its saved break
and mappings had come from different states of the parent.

Moving both break-field copies under the parent map lock makes them part
of the same protected snapshot as the mappings. The child can subsequently
resize its separate address space without affecting the parent.

### The test program also has an ABI to obey

Our freestanding program has a small assembly `_start` routine instead of
a C library startup. It aligns the stack to 16 bytes, then pushes three
four-byte arguments before calling C. Those pushes broke the alignment
expected at the call site.

This stayed hidden until a small C probe used a stack-local vector. Clang
emitted an aligned `movaps` instruction, and the old startup crashed with
SIGBUS. Reserving four padding bytes before the three arguments restores
the required alignment. The same probe exits successfully with the fixed
startup. The suite now contains a vector-stack check, and its new worker
trampoline also aligns the child stack before calling C.

[The review record](REVIEW_BRK.md) gives the individual reproductions,
regression check numbers, and measured results.

## Testing a different kernel requires a different kernel

A FreeBSD **jail** isolates processes and their environment while sharing
the host kernel. Building a new kernel inside a jail does not make programs
in that jail use it. Running the suite there normally would still exercise
the unpatched host.

A virtual machine provides a separate kernel to boot. For this experiment,
a small FreeBSD guest named `BRKVM` ran under **bhyve**, FreeBSD's hypervisor.
VMM access was initially unavailable in the build jail; after the jail was
enabled for VMs, the guest could be booted there.

The host ran `15.1-RELEASE-p1`. The first test kernels were built from
`15.1-RELEASE-p6` sources; the upstream preparation later moved to a pinned
FreeBSD `main` revision and a `16.0-CURRENT` guest. Each guest's Linuxulator
modules were built together with its kernel. Adding a field to
`struct vmspace` changes its layout, and module code can contain compiled
offsets into that structure. Loading these
experimental modules into the running host would not test the intended
kernel/module combination.

The guest configuration starts from FreeBSD's `MINIMAL` configuration and
adds the prerequisites for this image: the FFS/UFS filesystem implementation,
firmware support, and the compatibility facilities needed by the Linux
modules. It keeps serial-console and virtio block-device support.
**Virtio** is the interface through which the guest accesses its virtual disk.

For the original 15.1 reproduction, the kernel build command, run from the
project root, was:

```sh
env MAKEOBJDIRPREFIX="$PWD/obj" \
    make -C /usr/src buildkernel \
    KERNCONF=BRKVM \
    MODULES_OVERRIDE="linux linux_common" \
    -j"$(sysctl -n hw.ncpu)"
```

`MAKEOBJDIRPREFIX` keeps build products under the project's `obj` directory.
`KERNCONF` chooses the guest kernel configuration. `MODULES_OVERRIDE`
restricts module building to the two needed Linuxulator modules, and `-j`
allows parallel build jobs.

For that 15.1 reproduction, a clean matching source tree needs the
`BRKVM` configuration and all four historical patches applied in order.
Those patches are already applied to this environment's `/usr/src`.
The [README](README.md) records that workflow. The separate main-branch
review series and its build commands are in [UPSTREAM.md](UPSTREAM.md).
Use the patch set intended for the chosen source tree.

Both workflows build a guest image. No test kernel or module was installed
into the running host, and its 15.0 boot loader, Lua scripts and defaults
were retained in the guest image.

## A tiny guest with a clear answer

The [regression suite](brk-test/brk-suite.c) is a freestanding Linux/i386
executable: it issues its own system calls and needs no Linux C library.
FreeBSD's compiler can build it for that target. The `brandelf -t Linux`
step marks its ELF header so FreeBSD selects the Linux execution interface.
ELF is the executable-file format used here.

The guest disk contains a 128 MiB UFS root filesystem in a GPT partitioned
image, plus boot files, the test kernel, its modules, the suite, and a static
FreeBSD init program. UFS is a FreeBSD filesystem; GPT describes the disk's
partitions. The guest sees its root partition as `/dev/vtbd0p2` and mounts it
using `ufs:/dev/vtbd0p2`.

`init` is the first user process started by the kernel. This custom version
mounts devfs, opens the serial console, loads `linux_common.ko` followed by
`linux.ko`, runs the suite, prints its result, and powers off. Devfs supplies
the device-file tree under `/dev`; the `.ko` files are loadable kernel
modules.

Two mistakes in the initial harness made its output misleading. Devfs
needed the `nmount()` interface rather than the older `mount()` call used
there. Also, `kldload()` returns a nonnegative module ID on success, not
necessarily zero. Testing for equality with zero incorrectly treated positive
IDs as failure and printed a stale `errno`, producing the message
`Bad file descriptor` even after a successful load. Both harness bugs were
corrected, and setup failures now stop the test run.

For the regression results, the suite sends one pass/fail byte per completed
check through an inherited pipe to init. A pipe is a kernel-managed stream
between processes. Because init survives a crash in its child, it can still
print the number of completed checks and the terminating signal.

The suite now has 28 numbered checks. The original 19 cover queries,
byte-precise growth, page crossings, heap writes, shrink operations, a low
request, fork inheritance and isolation, and exec reset. Nine added checks
cover stack alignment, the full initial-break floor, initialized data,
concurrent returns, fork snapshots, and refused growth. A passing result
requires both correct returned addresses and usable mapped memory.

The results show why the intermediate passes were useful but insufficient:

| Kernel and suite | Completed | Passed | Failed assertions | Outcome |
|---|---:|---:|---:|---|
| Unpatched host, original suite | 19 | 11 | 8 | `FAILED 8` |
| Intermediate 15.1 test kernel | 13 | 13 | 0 | SIGSEGV during check 14 |
| First three patches, original suite | 19 | 19 | 0 | `PASS 19` |
| All four historical patches, expanded suite | 28 | 28 | 0 | `PASS 28` |
| Consolidated fix on pinned main, expanded suite | 28 | 28 | 0 | `PASS 28` |

Zero failed assertions in the second row did not mean success: six checks
were incomplete and the process crashed. The third row also missed the
boundary and concurrency bugs discovered in review. Those required new
checks, rather than another run of the unchanged 19-check suite.

After rebuilding the kernel and image, the guest was started with:

```sh
sudo ./brk-test/run-bhyve.sh
```

The launcher recreates a test VM named `brkvm`; that name must not identify
another VM you want to keep running. It starts two virtual CPUs so
shared-address-space operations can run in parallel.

## From a local fix to an upstream review

The initial development happened against release sources. To prepare a
change for FreeBSD itself, the final implementation was rebased onto
FreeBSD `main`, the development branch also called **FreeBSD-CURRENT**.
The tested base was commit
[`61c70dc16a79efcb9db732d37706cd311f555d9a`](https://github.com/freebsd/freebsd-src/commit/61c70dc16a79efcb9db732d37706cd311f555d9a),
dated 2026-10-26. Pinning the revision makes the source used for testing
identifiable even as the development branch continues to change.

The four historical kernel patches record the investigation, including
repairs to earlier attempts. They were consolidated into a complete kernel
fix, followed by a separate regression-test patch:

1. [Preserve the logical break](upstream/0001-linuxulator-logical-brk.patch):
   add the two VM-space fields, apply the initial floor, capture Linux
   results under the map lock, handle fork and exec, and mark the kernel
   interface change.
2. [Integrate regression tests](upstream/0002-linuxulator-brk-tests.patch):
   add the Linux helper and native FreeBSD checks to the normal test build
   and installation hierarchy.

Reviewers can assess the complete implementation without applying commits
that temporarily introduce an unmapping bug or a race. The historical
series remains under `brk-test/`; the review series is under `upstream/`.
They are alternative patch sets and must not be applied together.

### The handbooks and coding rules

FreeBSD's [Developers' Handbook](https://docs.freebsd.org/en/books/developers-handbook/)
covers development tools, testing and source-tree policies. Its
[style guidelines](https://docs.freebsd.org/en/books/developers-handbook/policies/)
point contributors to [`style(9)`](https://man.freebsd.org/cgi/man.cgi?query=style&sektion=9)
for C and [`style.Makefile(5)`](https://man.freebsd.org/cgi/man.cgi?query=style.Makefile&sektion=5)
for build files. These conventions are often called **Kernel Normal Form**.
The [Architecture Handbook](https://docs.freebsd.org/en/books/arch-handbook/book/)
provides background on locking, virtual memory and other kernel mechanisms.
The current source remains necessary when checking the exact implementation.

For this change, following those rules meant documenting the helper's
native and Linux behavior, marking which lock protects each field, using
a `bool` query flag, and putting assembly-callable C prototypes in a header.
The new test sources carry `SPDX-License-Identifier: BSD-2-Clause`.
The test helper also builds with the normal warnings enabled and `-Werror`,
which makes compiler warnings fail the build. An exec argument now uses
a writable character array instead of casting away a string literal's
`const` qualifier.

Both review patches were checked with FreeBSD's
`tools/build/checkstyle9.pl`: **zero errors and zero warnings**. Both also
applied to the pinned source without offsets or fuzz, meaning their context
matched directly. Reversing and reapplying them reproduced the tested files
byte for byte. These checks help a reviewer reproduce the change; correctness
still depends on the implementation and its tests.

### A structure change is also a kernel interface change

The new break fields sit immediately before `struct vmspace`'s final
`vm_pmap` member. That placement preserves the offsets of the existing
preceding fields and keeps `vm_pmap` last, as required by the structure's
existing comment. The structure still grows, and `vm_pmap` moves.

This matters because compiled module code can access a field using a fixed
number of bytes from the structure's start. Rebuilding the kernel with a
new layout while retaining an old module can make that module read the
wrong memory. Changing `kern_break()` from two arguments to three also
changes an interface used by the Linuxulator modules.

These are changes to the **kernel binary interface**, or **KBI**: the
interfaces between compiled kernel components. That is distinct from the
Linux application ABI whose behavior the fix restores.

The patch therefore proposes advancing `__FreeBSD_version` from the pinned
tree's `1600029` to `1600030` and adds an `UPDATING` notice requiring the
kernel and modules to be rebuilt together. The number is a proposal for
this patch, not an assigned upstream version. At landing time, a committer
must confirm the available number and record the final source commit and
date in the Porter's Handbook version table. This preparation targets
`main`; backporting it to a release branch would require its own KBI review.

## Putting the tests in FreeBSD's normal framework

The minimal guest answers whether the custom kernel passes our helper.
Upstream reviewers also need to run the checks using the ordinary FreeBSD
test workflow. The second patch adds `tests/sys/kern/linux` to the amd64
and i386 test build.

**ATF**, the Automated Testing Framework, supplies the test-case interfaces.
**Kyua** runs those cases and records their results. The new directory has
two cases. One runs the 28-check Linux helper. The other checks native
FreeBSD `break(2)` behavior, because the fix changes their shared VM helper.

The Linux test requires the matching i386 Linuxulator to be loaded already.
It checks for the `linuxelf` module and reports a skip if it is unavailable.
It does not load modules from the test runner. Once available, the test
requires a successful helper exit and its final pass line; a crash cannot
become a passing test.

The native case verifies page-rounded results, writing into the newly
allocated page, `ENOMEM` on refused growth, an unchanged break after that
refusal, and shrinking back to the initial break. It uses FreeBSD's
`__syscall()` interface, whose return type can carry a pointer. FreeBSD's
`syscall()` returns an `int`; using it for an amd64 break query would
truncate the address and test the wrong request.

Integration included the installation details. `etc/mtree/BSD.tests.dist`
describes the test directory hierarchy; it needs an entry for the new
`sys/kern/linux` directory. The helper's build rule also needs source paths
that work when object files live outside the source directory. Both the
separate-object-directory build and installation into an unprivileged
staging root were verified.

The ordinary minimal image still runs the Linux helper through its static
init. To run Kyua as well, a temporary extended image included the installed
Kyua and ATF runtime, their shared libraries, and writable storage for
results. It used the same final BRKVM kernel and matching modules. The
committed init was unchanged.

## The final results

The final amd64 **BRKVM**, **GENERIC**, and **LINT** kernel builds all passed
with the proposed version bump. BRKVM is the small guest configuration used
here; GENERIC is FreeBSD's standard configuration; LINT exercises a much
broader collection of kernel options. Building those configurations checks
more combinations than the minimal guest alone can cover.

The `linux`, `linux_common`, and `linux64` modules were built together with
BRKVM. The guest loaded `linux_common.ko` and `linux.ko` to exercise the
Linux/i386 ABI. Building `linux64.ko` checked compilation of that module;
Linux/amd64 runtime behavior remains outside this verification.

On the final two-CPU FreeBSD 16.0-CURRENT guest with 256 MiB RAM, Kyua
reported:

```text
brk_test:logical_break  ->  passed
native_brk_test:native_break  ->  passed
2/2 passed (0 broken, 0 failed, 0 skipped)
UPSTREAM KYUA RESULT: PASS (status=0)
```

Kyua counts two test cases: the Linux case wraps 28 numbered helper checks,
and the native case makes separate assertions about FreeBSD's own interface.
The Linux helper was then run directly in the same guest and reported:

```text
Concurrent return mismatches: parent=0 worker=0; worker calls=435479
Fork snapshot failures: 0; children=5000; worker resize cycles=146353
Completed: 28/28; passed: 28; failed: 0
PASS 28

============================================================
BRK TEST RESULT: PASS -- ALL 28 CHECKS PASSED
Completed: 28 / 28 checks
Passed: 28    Failed: 0    Not completed: 0
============================================================
```

The concurrent-return test made **500,000 parent calls** while the worker
made **435,479 calls**, with no incorrect results from either process.
The fork test created **5,000 children** while its worker completed
**146,353 grow/shrink cycles**, with no snapshot failures. Earlier 15.1
runs also passed, with different worker counts because scheduling varies.
The current generated console log is `brk-test/bhyve.log`.

Negative controls checked that the tests detect the conditions they target.
On the unpatched host, the Linux ATF case failed on incorrect break behavior,
while the native case passed. Simulating an unavailable module through a
`kldstat` PATH stub produced a skip; no host module was unloaded. The
standalone vector probe failed with SIGBUS using the old startup and passed
with the corrected alignment. The ten native init tests also passed,
including setup failures, child crashes and incomplete or invalid reports.

Bhyve itself returns exit status 1 when the guest powers off. That status
describes the VM's termination. Init reports a pass only when the suite
exits successfully and all 28 result records indicate success.

## What is verified, and what remains

The recorded guest runs verify the Linux/i386 checks on the original
15.1-RELEASE-p6 implementation and on the consolidated fix against the
pinned main revision. The final main guest also verifies the native
FreeBSD/amd64 case. Returned addresses, mapped memory, refusal behavior,
fork inheritance, exec reset, concurrent returns and fork snapshots were
all exercised.

The stress samples do not exhaust every possible scheduling interleaving.
Other kernel architectures, Linux/amd64 runtime, physical-memory exhaustion
and a full world build were not checked. The refusal tests exercise
address/resource limits. Red Baron itself still needs to be retested
without its allocator workaround on the corrected kernel.

The [contribution guidance checked for this work](https://github.com/freebsd/freebsd-src/blob/61c70dc16a79efcb9db732d37706cd311f555d9a/CONTRIBUTING.md)
requires substantial human review and validation of AI-assisted changes.
This work was AI-assisted. A human contributor must review it and supply
their own author details and any required DCO sign-off before submitting it.
The patches also need review from the VM and Linuxulator developers. No
upstream submission or acceptance has occurred.

The two [review patches](upstream/) and their build, application and test
instructions are collected in the [upstream preparation notes](UPSTREAM.md).


## Comparing with a real Linux kernel

A later comparison boots a small Alpine Linux guest under bhyve and runs
exactly the same Linux/i386 executable. It uses Alpine 3.24.3's unmodified
6.18.58 virtual kernel, two CPUs and 256 MiB RAM. BusyBox, its loader, the
init script and the test program fit in an approximately 896 KiB compressed
RAM filesystem. No Linux installation, network or persistent disk is needed.
The build and launcher are documented in [linux-test/README.md](linux-test/README.md).

This exposed an assumption in check 19: the initial heap address can change
on exec because Linux randomizes heap placement. The check now verifies
fresh aligned break state and exact byte-sized growth without comparing
addresses across exec. Address randomization remains enabled. The updated
suite still passes all 28 checks in the patched FreeBSD guest.

The real Linux result is **27 passed, one failed**, with all 28 completed.
The failure is check 25, which forks during concurrent heap growth and
shrink: some children terminate on a signal when writing below their
reported break. Ordinary fork inheritance, exec reset, concurrent return
values and the byte-precision checks all pass. Source inspection suggests
that Linux's separate break-state and mapping copies may explain this
stress result, but that diagnosis has not been independently established.
The comparison keeps the failure visible and does not claim a fully
passing Linux baseline or include a Linux kernel fix.
