Skip to content

Kernel function ordering

This page explains a performance problem found while benchmarking BSDRP 2.4, and the fix: ordering the kernel functions so that the code a router runs for every packet sits together in memory. No line of the kernel's C code changes; only where each function is placed in memory. On the lab machines this made firewalling up to 34% faster than the stock BSDRP 2.4 kernel.

It is written for readers who know what a program, a function and a compiler are, but have not yet studied how a CPU executes code. Every other notion is introduced on the way, and a glossary sits at the end.

Status

BSDRP 2.4 release images ship the stock kernel, without function ordering. The BSDRP development tree enables it for amd64, together with the iflib setting described in Measurements, for the release after 2.4.

The short version

  1. A router runs the same few hundred kernel functions for every packet, millions of times per second.
  2. The CPU keeps a small, fast copy of recently used code: the instruction cache. When the code it needs is not in that cache, it waits.
  3. Where the linker places each function in memory decides how well those functions share the instruction cache. Between BSDRP 2.3 and 2.4, unrelated source changes moved functions around, and the hot ones started to push each other out of the cache.
  4. The fix asks the linker to put the hot functions first, next to each other, in a fixed order. The CPU then fetches about half as many cache lines per packet, and throughput comes back.

Background: how the CPU fetches code

Code is just bytes in memory

When the kernel is compiled, each function becomes a sequence of machine instructions, a few hundred bytes to a few kilobytes long. The linker then glues all these functions one after the other into a single file, the kernel image. When the machine boots, that image is loaded into RAM: every function gets an address, the place in memory where its first instruction lives.

To run a function, the CPU reads its instructions from that address.

RAM is slow, so the CPU keeps a cache

Reading from RAM takes on the order of a hundred CPU cycles. A CPU that waited that long for every instruction would be very slow, so it keeps small copies of recently used memory close to itself, in caches:

flowchart LR
    CPU(("<b>CPU core</b><br/>executes<br/>instructions"))
    L1(("<b>L1 instruction cache</b><br/>32 KB<br/>a few cycles"))
    L2(("<b>L2 cache</b><br/>1-4 MB<br/>tens of cycles"))
    RAM(("<b>RAM</b><br/>gigabytes<br/>~100+ cycles"))

    CPU ---|"<b>hit</b>: fast"| L1
    L1 ---|"<b>miss</b>: wait"| L2
    L2 ---|"<b>miss</b>: wait longer"| RAM

    classDef router fill:#ffe3e3,stroke:#c92a2a,stroke-width:2px,color:#222
    classDef host fill:#e9ecef,stroke:#6c757d,stroke-width:2px,color:#222
    class CPU router
    class L1,L2,RAM host

The figures are orders of magnitude, not exact values for a given CPU. The one that matters here is the L1 instruction cache: on both lab CPUs (Intel Atom C2758 and AMD GX-412TC) it holds only 32 KB of code.

  • If the instruction the CPU needs is in L1, it is a hit: no waiting.
  • If not, it is a miss: the CPU stalls until the code arrives from L2 or RAM.

The cache works in 64-byte lines

The cache does not copy single instructions. It copies fixed blocks of 64 bytes called cache lines. Asking for one instruction brings in the 64 bytes around it.

A 32 KB cache therefore holds 512 lines. Two consequences:

  • Neighbors come for free. If the next function the CPU needs sits right after the current one, it is probably already in the line just loaded.
  • Unused neighbors waste space. If a hot function sits next to code that never runs during packet forwarding (error handling, configuration code), part of every line loaded is wasted.

Each address has only a few possible places in the cache

A cache is not a free-for-all where any line can go anywhere. To be fast, the hardware computes from the address a small group of slots, called a set, and the line can only be stored in one of the few slots of that set. When the set is full, the oldest line in it is thrown out (evicted).

So two functions whose addresses map to the same set compete for the same few slots, even when the rest of the cache is empty. If the CPU alternates between them, each one keeps evicting the other: every access is a miss. These are called conflict misses, and they depend only on where the code is placed, not on how much code there is.

The problem: a router runs the same code millions of times

The per-packet path

Forwarding one packet goes through a chain of kernel functions, always the same ones:

flowchart LR
    NIC(("<b>NIC</b><br/>packet<br/>arrives"))
    RX(("<b>driver RX</b><br/>iflib, igb, ix<br/>cxgbe"))
    ETH(("<b>Ethernet</b><br/>ether_input<br/>ether_demux"))
    IP(("<b>IP</b><br/>ip_input<br/>ip_tryforward"))
    FW(("<b>firewall</b><br/>pf, ipfw<br/>or ipf"))
    RT(("<b>route lookup</b><br/>fib4_lookup"))
    OUT(("<b>output</b><br/>ether_output<br/>arpresolve"))
    TX(("<b>driver TX</b>"))

    NIC --> RX --> ETH --> IP --> FW --> RT --> OUT --> TX

    classDef router fill:#ffe3e3,stroke:#c92a2a,stroke-width:2px,color:#222
    classDef host fill:#e9ecef,stroke:#6c757d,stroke-width:2px,color:#222
    class RX,ETH,IP,FW,RT,OUT,TX router
    class NIC host

Add memory allocation (m_free, UMA), locks (__mtx_lock_sleep), memcpy and interrupt handling, and a few hundred functions are involved. At 10 Gigabit Ethernet line rate, minimum-size packets arrive at 14.88 million per second. On the 1 GHz AMD CPU of a PC Engines APU2, forwarding one packet costs about 4000 to 5300 CPU cycles in total, so every cycle saved per packet counts.

What changed between BSDRP 2.3 and 2.4

BSDRP 2.4 is built on a newer FreeBSD source tree. Thousands of unrelated changes (new drivers, new features, bug fixes) were added. None of them touched the forwarding code in a way that would make it slower, yet the benchmarks showed ipfw and pf 6 to 16% slower than on 2.3 on an Atom C2758.

The forwarding functions did not change, but their addresses did: every function added or grown elsewhere shifts the functions placed after it. In the stock kernel the hot functions are spread over several megabytes, interleaved with code that never runs while forwarding:

flowchart TB
    subgraph STOCK["Stock kernel: hot functions scattered"]
        direction LR
        A1["ip_input<br/>(hot)"] --- B1["cold code<br/>200 KB"] --- A2["ether_output<br/>(hot)"] --- B2["cold code<br/>1.5 MB"] --- A3["ip_tryforward<br/>(hot)"] --- B3["cold code<br/>..."]
    end
    subgraph ORD["Ordered kernel: hot functions packed first"]
        direction LR
        C1["ip_tryforward"] --- C2["ether_output"] --- C3["ip_input"] --- C4["... 116 more<br/>hot functions"] --- C5["all the<br/>cold code"]
    end

    classDef hot fill:#ffe3e3,stroke:#c92a2a,stroke-width:2px,color:#222
    classDef cold fill:#e9ecef,stroke:#6c757d,stroke-width:2px,color:#222
    class A1,A2,A3,C1,C2,C3,C4 hot
    class B1,B2,B3,C5 cold
    style STOCK fill:#f8f9fa,stroke:#495057,color:#222
    style ORD fill:#f8f9fa,stroke:#495057,color:#222

In the scattered layout, whether two hot functions collide in the same cache set is a matter of luck. In 2.3 the luck was good, in 2.4 it was bad. Any future source change can flip it again.

How we know it is the cache

Guessing is not enough; the CPU can count what happens inside it. Its performance counters count events such as instructions executed, cycles spent and instruction cache misses. On FreeBSD, pmcstat(8) reads them.

On an APU2 forwarding at line rate, comparing the stock 2.4 kernel with the ordered kernel (same source code, only the layout differs), per forwarded packet:

Measurement (inet4 forwarding) Stock 2.4 Ordered Change
Instructions executed 2971 2902 -2%
CPU cycles 5326 3984 -25%
L1 instruction cache misses 100.2 49.8 -50%

Read it like this:

  • The CPU runs almost the same instructions: the work is the same.
  • It suffers half the instruction cache misses: the layout is better.
  • So it needs 25% fewer cycles per packet, which matches the +34% throughput measured for this configuration.

Raw data and scripts are in the netbenches repository, see Measurements.

The fix: tell the linker where to put the functions

Step 1: one section per function

By default, the compiler puts all the functions of a source file into one block called a section (named .text). The linker can move sections, but not what is inside them, so functions from the same file always stay together, in the file's order.

The compiler flag -ffunction-sections changes this: every function gets its own section (.text.ip_input, .text.ether_output, ...). Now the linker can place each function independently.

Step 2: give the linker an order list

The FreeBSD linker, ld.lld, accepts --symbol-ordering-file=<file>: a text file with one function name per line. The listed functions are placed first, in the listed order; everything else follows as usual.

flowchart LR
    SRC(("<b>C sources</b><br/>ip_input.c<br/>if_ethersubr.c"))
    CC(("<b>clang</b><br/>-ffunction-sections"))
    OBJ(("<b>object files</b><br/>one section<br/>per function"))
    LIST(("<b>order list</b><br/>gen-order.txt"))
    LD(("<b>ld.lld</b><br/>--symbol-ordering-file"))
    KERN(("<b>kernel</b><br/>hot functions<br/>packed first"))

    SRC --> CC --> OBJ --> LD --> KERN
    LIST --> LD

    classDef router fill:#ffe3e3,stroke:#c92a2a,stroke-width:2px,color:#222
    classDef host fill:#e9ecef,stroke:#6c757d,stroke-width:2px,color:#222
    class CC,LD router
    class SRC,OBJ,LIST,KERN host

The generated machine code of each function is unchanged; only the addresses move. This is why function ordering carries little functional risk: no behavior changes, only speed.

The beginning of the list used on the lab machines looks like this:

ip_tryforward
ether_output
lock_delay
ip_input
__mtx_lock_sleep
netisr_dispatch_src
ether_nh_input
arpresolve
bsearch4_lookup
m_free
...

Building the order list

The list was not written by hand. It came from profiles: recordings, made with pmcstat(8) while the router forwards traffic, of how much CPU time each function uses.

A list learned on a single machine works well on that machine but includes its NIC driver and its CPU's quirks. To get one list for all BSDRP users, the generic list (called GEN in the benchmarks) keeps what different routers have in common:

flowchart TB
    P1(("<b>Atom C2758</b><br/>Chelsio T520<br/>profile"))
    P2(("<b>Atom C2758</b><br/>Intel 82599<br/>profile"))
    P3(("<b>APU2</b><br/>Intel i210<br/>profile"))
    COMMON(("<b>1. common hot functions</b><br/>60, sorted by weight"))
    MEM(("<b>2. memcpy family</b><br/>6"))
    V6(("<b>3. IPv6 path</b><br/>16"))
    IFLIB(("<b>4. iflib shared code</b><br/>no NIC driver"))
    GEN(("<b>gen-order.txt</b><br/>119 functions"))

    P1 --> COMMON
    P2 --> COMMON
    P3 --> COMMON
    COMMON --> GEN
    MEM --> GEN
    V6 --> GEN
    IFLIB --> GEN

    classDef router fill:#ffe3e3,stroke:#c92a2a,stroke-width:2px,color:#222
    classDef host fill:#e9ecef,stroke:#6c757d,stroke-width:2px,color:#222
    class P1,P2,P3 host
    class COMMON,MEM,V6,IFLIB,GEN router
  1. Common hot functions: the 60 functions that are hot on all three machines, sorted by their combined share of CPU time. This is the core forwarding path: ip_tryforward, ether_output, ip_input, mbuf and UMA allocation, locks, route lookup, interrupt entry.
  2. The memcpy family (memcpy_erms, memmove_erms, ...).
  3. The IPv6 forwarding path (ip6_tryforward, ip6_input, nd6_resolve, fib6_lookup, ...). The profiles were IPv4-only, so these were added explicitly.
  4. Shared iflib code hot on both Intel machines (iflib, busdma, taskqueue). No function specific to one NIC model is included.

Functions written in assembly cannot be split per function: they move with their whole source file. The ordered block ends up about 87 KB long.

Measurements

All benchmarks: 2000 flows of minimum-size UDP packets at line rate, 5 runs per point with a reboot between each, median value. Seven configurations (plain forwarding, then ipf, ipfw and pf, each stateless and stateful), in IPv4 and IPv6: 14 data points per machine. Each line gives the range over those 14 points.

Machine and NIC Kernel vs stock 2.4 vs 2.3
Atom C2758, Chelsio T520-SO (10G) ordered +0.4% to +21.0% -3.6% to +13.0%
Atom C2758, Intel 82599 (10G) ordered, prefer_mpring=1 +3.8% to +34.0% +0.1% to +20.9%
Atom C2758, Intel 82599 (10G) BSDRP image with both enabled by default +3.6% to +34.2% -0.1% to +22.2%
PC Engines APU2, Intel i210 (1G) ordered -4.5% to +33.7% -34.9% to -9.7%
PC Engines APU2, Intel i210 (1G) ordered, prefer_mpring=1 +25.8% to +68.1% -5.2% to +11.4%

The same kernel file and the same order list were used on all three machines.

The first lines used a kernel built by hand and swapped onto a stock 2.4 image. The last line flashed the full image produced by the BSDRP build, with function ordering and prefer_mpring enabled by default, as a user would install it. On the 82599 it matches the hand-built kernel within 1.3% on 12 of the 14 points; the two other points, ipf-stateful, are 2.2% and 3.4% lower, a configuration whose results vary by 3 to 7% from run to run.

The APU2 lines show that 2.4 had a second, independent regression on Intel NICs: iflib, the framework shared by the Intel drivers, switched its default transmit path. The loader tunable net.iflib.prefer_mpring="1" restores the previous path. Function ordering alone cannot recover that loss, and the tunable alone cannot recover the layout loss; together they bring the APU2 back to the 2.3 level. BSDRP sets this tunable in /boot/loader.conf.local from the release after 2.4.

Firewalls with large code, such as pf, gain less than plain forwarding: their hot code alone is bigger than the 32 KB L1 instruction cache, so a better layout cannot make it fit.

Full results, graphs, raw data and the scripts used:

How BSDRP enables it

The order list ships in the BSDRP sources as BSDRP/kernels/amd64.function-order. The build copies it next to the kernel configuration as function-order.txt, and the amd64 kernel configuration adds two lines:

makeoptions CONF_CFLAGS=-ffunction-sections
makeoptions LDFLAGS=--symbol-ordering-file=${S}/amd64/conf/function-order.txt
  • CONF_CFLAGS=-ffunction-sections is step 1.
  • LDFLAGS=--symbol-ordering-file=... is step 2. ${S} is the kernel build's variable for the sys/ directory of the source tree, so the path stays valid wherever the tree is built.

See Customizing the kernel for where the kernel configuration lives in the BSDRP build. The list used in the benchmarks and its source profiles are in the netbenches repository.

To check that the ordering was applied on a running router, the first functions of the list should have neighboring addresses:

nm -n /boot/kernel/kernel | grep -E ' (ip_tryforward|ether_output|ip_input)$'

Rebuilding in an existing build tree

Changing CONF_CFLAGS does not make an incremental kernel build recompile anything: the old object files, without one section per function, are only relinked. The linker can then move only whole source files, and the ordering is much coarser. Delete the kernel object directory (or run make clean-jail) before the first build with this option. A fresh build is not affected.

Limits

  • The list is tied to a source version. If a function is renamed or removed in a later FreeBSD source tree, it silently drops out of the order, and the gain fades. The list must be checked, and possibly rebuilt from new profiles, when the source tree is updated.
  • Kernel modules are not ordered. pf.ko, ipfw.ko and ipl.ko are separate files loaded at run time; only the main kernel is ordered.
  • amd64 only. The profiles come from amd64 machines; other architectures would need their own.
  • It is tuned for forwarding. The list favors the packet path. A machine doing something else (a file server, for example) would not benefit, and could in theory lose a little.

Glossary

Term Meaning
Address The position of a byte in memory. Each function starts at an address.
Cache line The 64-byte block the cache copies from memory in one go.
Conflict miss A miss caused by two pieces of code whose addresses compete for the same cache set, while other parts of the cache may be free.
Evict Throw a line out of the cache to make room for another.
Hit / miss Whether the code the CPU asks for is already in the cache (hit) or must be fetched from slower memory (miss).
Hot / cold code Code that runs for every packet / code that rarely or never runs during forwarding.
L1 instruction cache The smallest and fastest cache, holding only code. 32 KB on the lab CPUs.
Linker The tool (ld.lld on FreeBSD) that assembles compiled functions into one executable file and decides their addresses.
Mpps Million packets per second, the unit of router throughput.
Performance counter A hardware counter inside the CPU that counts events such as cycles, instructions or cache misses. Read on FreeBSD with pmcstat(8).
Profile A record of where the CPU spends its time, function by function.
Section A named block of an object file that the linker places as a whole.
Set The small group of cache slots in which a given address may be stored.