目录
正在加载目录…
正在阅读专栏 OSTEP 操作系统专栏 第 44 篇 · 共 62 篇 · 71%

OSTEP:Free-Space Management

发布于 2026-09-17 21:41 · 最后编辑于 2026-09-17 22:08 · 版本 v2 · 字数 11,138 · 预计阅读 23 分钟 👁 23 次阅读

OSTEP:Free-Space Management

本篇对应 OSTEP Version 1.10 的 Chapter 17 “Free-Space Management”。它暂时离开 paging,讨论 malloc library 或 OS 如何管理由 variable-sized units 组成的 free space。

类型与定位

  • 笔记类型:正文翻译/知识整理
  • 翻译基准:官方 Free-Space Management
  • 术语约定:free list、external/internal fragmentation、split、coalesce、best fit、worst fit、first fit、next fit、buddy 等保留英文或中英并列。
  • 图件说明:原文包含 heap layout 和 free-list 示意图;按原位置用 Mermaid、ASCII 和代码重绘,没有独立 raster image。

TL;DR

variable-sized allocation 的困难在于 external fragmentation:总 free space 足够,但没有一段连续空间满足请求。allocator 通常用 free list,结合 split、coalescing、header 和不同 fit policy,在 throughput、fragmentation 和 metadata overhead 之间取舍。

目录

章节内容
问题与假设malloc/free、heap 与 fragmentation
Low-level mechanismssplit、coalesce、header 与 embedded free list
Growing the heapsbrk 与从 OS 获取空间
Basic strategiesbest/worst/first/next fit
其他组织方式segregated lists、slab 与 buddy
评估 allocatorthroughput 与 utilization
官方 Simulation Homework:malloc.py7 道 simulator 练习

问题与假设

固定大小的 unit 很容易管理:维护一张空闲 unit 表,取出第一个即可。variable-sized unit 则会产生 external fragmentation:

text
free 10 | used 10 | free 10

总共还有 20 bytes free,但请求 15 bytes 仍会失败,因为没有一段连续的 15 bytes。

本章以 malloc/free 为例:

text
void *malloc(size_t size)
void free(void *ptr)

free 只接收 pointer,不接收 size,因此 allocator 必须从 pointer 推导被释放 chunk 的大小。管理区域通常称为 heap,记录 free chunks 的数据结构通常称为 free list。

需要区分:

  • external fragmentation:空闲空间分散在多个位置,无法满足连续分配;
  • internal fragmentation:分配给 client 的 chunk 比请求更大,chunk 内部产生浪费。

本章主要聚焦 external fragmentation,并假设已经返回给 client 的 pointer 不能被 allocator 随意移动,因此不能依靠 compaction 消除碎片。

更具体地说,allocator 管理的是一段 contiguous byte region。user 一旦拿到 malloc() 返回的 pointer,这段 memory 在对应的 free() 之前就归 user 所有,library 不能随意把它移动到其他地址;C pointer 可能被复制到变量、其他数据结构甚至 register 中,allocator 通常无法找到并修正所有这些引用。因此 user-level allocator 不能通过 compaction 消除 external fragmentation。OS 在实现 segmentation 时,有时可以拥有更多信息并执行 compaction,但那是另一个层次的问题。

Low-level mechanisms

Split

若请求小于某个 free chunk,allocator 可以把它拆成两部分:一部分交给 client,剩余部分留在 free list。

text
free chunk: [-------------------- 20 --------------------]
request:                                      5

after split:
allocated: [----- 5 -----] free: [------- 15 -------]

split 提高了空间利用率,但会产生更多小的 free chunks。

Coalesce

释放一个 chunk 后,如果它与相邻 free chunks 连续,allocator 应将它们合并:

text
before free: [free 10][used 10][free 10]
after free:  [------------- free 30 -------------]

如果不 coalesce,即使整个 heap 都已经释放,也可能表现成多个小 chunk,导致较大请求失败。coalescing 通常要求 free list 具有 address ordering,或要求 allocator 能快速找到相邻 chunk。

因为 free(ptr) 没有 size 参数,allocator 常在 client pointer 之前放一个 header:

text
[ header: size, magic ][ memory returned to client ]
                         ^
                         ptr

例如:

text
typedef struct {
    int size;
    int magic;
} header_t;

free 时可以通过 pointer arithmetic 回到 header,检查 magic,并根据 size 计算整个待释放区域的大小。header 也会产生 metadata overhead,因此实际 allocator 需要在信息量、检查能力和空间成本之间取舍。

把 free list 放进 free space

allocator 自己不能在每次新增 free-list node 时再调用 malloc,因此可以把 node 直接嵌入当前 free region:

text
typedef struct __node_t {
    int size;
    struct __node_t *next;
} node_t;

初始化 heap 后,free list 只有一个 node;每次 allocation 都从 free region 中切出 header 和 client region,并调整 node 的 size。释放时再把区域放回 free list,并根据地址相邻关系 coalesce。

例如,一个 4KB heap 初始只有一个 free-list node:

c
// mmap() 返回一段可读写的 heap
node_t *head = mmap(NULL, 4096, PROT_READ|PROT_WRITE,
                    MAP_ANON|MAP_PRIVATE, -1, 0);
head->size = 4096 - sizeof(node_t);
head->next = NULL;

若申请 100 bytes,假设 header 为 8 bytes,allocator 实际要从 free chunk 中切出 108 bytes:100 bytes 给 client,8 bytes 存放 size 与 magic;原来的 free node 则从 4088 bytes 缩小为 3980 bytes。连续三次相同申请后,前三个区域各含一个 header 和 100 bytes client data,剩余 free chunk 为 3764 bytes。

若释放中间的 100-byte region,allocator 可以把它作为新 node 插入 free-list head。若随后释放另外两个 region、却不执行 coalescing,heap 明明全部空闲,free list 仍可能是 100 + 100 + 100 + 3764 的多个 chunk;一次 4000-byte request 仍会失败。coalescing 必须扫描并合并相邻地址的 free chunks,才能恢复一个大的连续 region。

Growing the heap

heap 没有足够空间时,allocator 可以:

  1. 直接失败并返回 NULL;
  2. 通过 system call(例如 UNIX 的 sbrk)向 OS 请求更多空间;
  3. OS 找到 free physical pages,把它们映射到 process address space;
  4. allocator 把新增区域加入自己的 free list。

向 OS 申请空间并不等于消除 fragmentation;它只是扩展可管理范围,内部的 allocation policy 仍然决定空间如何分裂。

Basic strategies

理想 allocator 应同时做到高 throughput 和低 fragmentation,但 allocation/free request 由程序决定,任何 policy 都可能在某种 workload 下表现糟糕。

Policy选择规则特征
best fit找能容纳请求的最小 chunk尝试减少单次浪费,但通常要扫描整个 list
worst fit找最大的 chunk保留大块剩余空间,但常导致高 fragmentation
first fit找到第一个足够大的 chunk快;list 开头可能被小块污染
next fit从上次搜索位置继续 first-fit分散搜索位置,性能接近 first fit

Best fit

best fit 遍历 free list,选择 size 最接近请求且足够大的 chunk。它的直觉是减少当前 allocation 的剩余浪费,但 full scan 的成本可能很高。

Worst fit

worst fit 总是从最大 chunk 中分配,希望保留较大的剩余块。研究和实践通常显示它既可能产生更多 fragmentation,又需要较高搜索成本。

First fit

first fit 找到第一块足够大的空间就停止。它通常比 best fit 快;若 free list 按地址排序,coalescing 更容易,fragmentation 也可能得到改善。

Next fit

next fit 保存上一次搜索的位置,使后续搜索从该位置继续。这样可以避免 free list 开头被反复切成小碎片,同时保留 first-fit 的低搜索成本。

一个具体的 fit 例子

假设 free list 按当前顺序包含大小为 10、30、20 的三个 chunks,请求 15 bytes:

策略选择分配后 free list
best fit2010、30、5
worst fit3010、15、20
first fit第一个可用的 3010、15、20

best fit 和 worst fit 都必须查看整个 list 才能确认答案;first fit 找到 30 后即可停止。best fit 看似减少了本次浪费,却容易留下难以利用的小 chunk;worst fit 希望保留大块空间,但通常既要 full scan,又会造成较高 fragmentation。free-list ordering 也会影响结果:按 address 排序有利于 coalescing,按 size 排序则可能改变搜索成本和碎片形态。

其他组织方式

真实 allocator 还会采用更复杂的数据结构和 policy,例如:

  • 按 size class 分组的 segregated lists;
  • 为固定类型对象准备的 slab allocator;
  • 用 buddy system 按 2 的幂次分割和合并;
  • tree、bitmap 或 balanced structure,以改善搜索和合并;
  • 为减少 system-call 成本而批量向 OS 获取大块区域。

这些方式没有消除基本 trade-off,而是利用 workload、size pattern 和对齐约束,降低常见路径上的时间或空间成本。

Segregated lists 与 slab

如果 application 经常申请一种或少数几种固定大小,可以为这些 size class 单独维护 free list。匹配的 request 不必在通用 list 中搜索,因此 allocation/free 很快,fragmentation 也更容易控制;代价是必须决定 specialized pool 与 general pool 各自应该占用多少 memory。

Solaris kernel 中的 slab allocator 是典型例子。kernel boot 时,为 locks、file-system inodes 等常用 kernel objects 建立 object cache;每个 cache 都是某种对象的 segregated free list。当 cache 接近耗尽时,它以 page-size 的倍数向 general allocator 请求新的 slabs;当某个 slab 中对象的 reference count 都归零时,general allocator 又可以回收它。

slab 还会保留 freed object 的 initialized state。对象初始化和销毁本身可能很昂贵,重复利用已经初始化的 object 可以减少每次 allocation 的额外开销。这种优化以额外缓存空间和更复杂的生命周期管理为代价。

Buddy allocation

binary buddy allocator 从一个大小为 2^N 的大块 free space 开始。请求到来后,allocator 递归地把当前 block 对半切分,直到得到能够容纳 request 的最小 power-of-two block。比如在 64KB heap 中申请 7KB,最终通常得到 8KB block,因此会产生 internal fragmentation。

buddy 的优势是 coalescing 很简单:释放一个 block 时,allocator 计算它的 buddy 是否也空闲;若是,就合并成更大的 block,并继续检查上一级 buddy,直到遇到仍在使用的 block 或恢复整个 heap。buddy 的地址只在某一 bit 上不同,该 bit 由 block 在 buddy tree 中的层级决定,所以不需要复杂地搜索所有邻居。

mermaid
flowchart TB
  A[64 KB] --> B[32 KB]
  A --> C[32 KB]
  B --> D[16 KB]
  B --> E[16 KB]
  D --> F[8 KB allocated]
  D --> G[8 KB free]

其他现代 allocator 还会使用 balanced tree、splay tree、partially ordered tree,以及面向 multiprocessor workload 的 per-thread/per-processor 结构;它们以实现复杂度换取更好的搜索、扩展性和并发性能。

评估 allocator

常见指标包括:

  • throughput:单位时间能完成多少 allocation/free;
  • space utilization:已申请空间与实际占用 heap space 的关系;
  • fragmentation:free space 被切碎的程度;
  • metadata overhead:header、pointer 和 free-list structure 的成本;
  • latency distribution:普通请求与最坏请求的延迟差异。

一个只追求最快的 allocator 可能浪费大量空间;一个只追求最小 fragmentation 的 allocator 可能需要昂贵的搜索。应根据 workload 和性能目标选择 policy。

官方 Simulation Homework:malloc.py

官方 malloc.py 将 free-space allocator 的策略变成可观察的 trace。以下按原文 7 道题恢复;每题都应记录 request、返回地址、free-list 状态和最终 fragmentation,而不是只看程序是否结束。

  1. 运行 -n 10 -H 0 -p BEST -s 0,预测每次 alloc()/free() 的返回值和 free-list 状态,并观察 free list 随时间的变化。
  2. 将 policy 改为 -p WORST,比较搜索结果与 BEST fit 的差异。
  3. 将 policy 改为 -p FIRST,说明 first fit 哪一部分搜索工作被省略、什么因此变快。
  4. 使用 -l ADDRSORT、-l SIZESORT+、-l SIZESORT-,观察 free-list ordering 如何与 BEST/WORST/FIRST fit 交互,并比较寻找可用位置的时间。
  5. 将随机 requests 增加到 -n 1000,分别不加和加 -C(coalescing),观察大 allocation request 的成功情况、free-list 大小随时间的变化,以及 ordering 是否影响结果。
  6. 改变 allocated fraction -P:提高到 50% 以上并接近 100%,再接近 0%,观察 allocation 行为如何变化。
  7. 使用 -A 构造高度 fragmented 的 free space,比较不同 fit policy、list ordering 和 coalescing option 对 free-list 形态的影响。

这些实验没有一个对所有 workload 都最优的答案。真正要观察的是:同一 policy 在不同 request stream、free-list ordering 和 coalescing 设置下,会同时改变 throughput、utilization、fragmentation 与大块请求的可满足性。

原文逐段复核补充

本章的范围、假设与 CRUX

本章是对 memory virtualization 主线的一次小幅 detour:free-space management 既出现在 user-level malloc library(管理 process heap 的 pages),也出现在 OS 使用 segmentation 管理 process address space 或 physical memory 的场景。fixed-sized unit(如 paging 中的 page)相对容易,只需维护可用 unit 的集合并返回其中一个;variable-sized unit 才会产生 external fragmentation。

本章的 CRUX 是:面对 variable-sized request,如何管理 free space、用什么 strategy 尽量降低 fragmentation,以及各种方案会带来什么 time/space overhead。正文主要讨论 user-level allocator 的历史与机制,引用 Wilson 等人的 survey;原文还打趣说该 survey 近 80 页,只有真正感兴趣才值得完整阅读。

free(void *ptr) 不接收 size,因此 allocator 必须从 pointer 快速推导 chunk 大小;heap 是这类 library 管理区域的历史名称,而 free list 是追踪 free chunks 的通用数据结构,实际实现未必真的是 linked list。虽然本章主要讨论 external fragmentation,也明确指出:allocator 给出大于 request 的 chunk 时,chunk 内部未使用的部分属于 internal fragmentation。

为了简化分析,原文首先假设 allocator 管理一段固定大小的 contiguous byte region。实际 allocator 可以在空间耗尽时通过 sbrk 等 system call 扩展 heap,但这不等于消除 fragmentation,只是让 managed region 变大。原文还特别说明,C program 拿到 pointer 后,library 通常无法找出并修正所有指向该区域的 references(它们可能存在于其他变量甚至 register 中),所以 user-level allocator 不能依靠 compaction;较强类型且 garbage-collected 的 language 可能拥有更好的 relocation 条件,而 OS 在 segmentation 场景中有时可以做 compaction。

Header 与 free-list 示例的精确边界

header 的最小内容是 allocated region 的 size,也可以包含用于加速 deallocation 的 pointer、用于 integrity checking 的 magic number 和其他 metadata。用户申请 N bytes 时,allocator 实际要寻找能容纳 N + sizeof(header) 的 free chunk;这也是本章 4KB 示例中申请 100 bytes 却消耗 108 bytes 的原因。

在 4096-byte heap 的示例中,free-list node 本身嵌在 free space 内,初始可用 size 为 4096 - sizeof(node_t) = 4088。三次各申请 100 bytes 后,每次都额外消耗 8-byte header,剩余 free chunk 为 3764 bytes。释放中间 chunk 后,如果只把它插到 free-list head,就会得到一个非 coalesced 的小块与大块混合 list;随后即使所有 allocated chunks 都释放,整个 heap 仍可能只是“看起来被切碎”,必须合并相邻地址才能恢复一个完整 free extent。

Policy 不是普适最优解

best fit 和 worst fit 都需要完整扫描 free list;first fit 只需扫描到第一块可用区域,因此更快,但可能污染 list 开头。address-based ordering 不只是影响搜索:它还让相邻 free chunks 更容易被发现和 coalesce,并往往降低 fragmentation。next fit 通过保存上一次搜索位置,把搜索更均匀地分散到 list 中,性能通常接近 first fit。

原文强调,由于 allocation/free stream 由 programmer 决定且可以 arbitrary,不存在对所有 workload 都“最好”的 strategy。真实判断需要结合 request stream、coalescing、list ordering 和 workload measurements,而不能只从某一次 trace 的空间浪费得出结论。

Other approaches 与扩展性

segregated lists 的收益是为常见 size 单独提供 pool,减少 search 与 fragmentation;代价是决定 specialized pool 和 general pool 的 memory 分配。Solaris kernel 的 slab allocator 以 lock、file-system inode 等高频 kernel object 建立 object cache;cache 缺空间时按 page-size 的倍数申请 slab,所有 object 的 reference count 归零后,VM system 可以回收 slab。slab 还把 freed object 保持在 pre-initialized state,避免反复执行昂贵的 initialization/destruction。

原文用 Jeff Bonwick 既实现 slab、又主导 ZFS 的经历说明“great engineers”旁注,并以“100x”工程师和“找这样的人合作”的玩笑收束;这里保留其语义定位,但不把旁注当作 allocator correctness 的条件。

buddy allocator 的关键不只是 power-of-two allocation 带来的 internal fragmentation,更在于 coalescing 简单:每个 buddy pair 的地址只在由 tree level 决定的一个 bit 上不同,因此可以快速计算 buddy,不必扫描全部 free list。更复杂的 allocator 还会使用 balanced binary tree、splay tree 或 partially-ordered tree;multiprocessor workload 则催生 Hoard、jemalloc 等面向扩展性的设计。复杂度换来的不是理论上消灭 fragmentation,而是在真实 workload 上改善 search、concurrency 和 scalability。

原文总结

allocator 广泛存在于每个 C program 所链接的 library 中,也存在于为自身 data structures 管理 memory 的 OS 中。构建一个同时 fast、space-efficient、scalable,并能适应广泛 workload 的 allocator,至今仍是持续的 systems challenge;对 workload 了解越多,就越能针对性地调优 allocator。

源文档核验记录

  • 源文档:OSTEP Version 1.10 官方 vm-freespace.pdf。
  • 页数:18 页(含正文与 References)。
  • 章节范围:17.1 Assumptions、17.2 Low-level Mechanisms、17.3 Basic Strategies,以及 Segregated Lists、Slab、Buddy 与其他 allocator approaches、Evaluation、Simulation Homework 和 Summary。
  • 图件核对:Figure 17.1–17.7 的 heap/header/free-list 示意已在对应语义位置用 ASCII、Mermaid、表格和代码块重绘;原 PDF 没有需要另存的独立 raster 图片。
  • 内容核对:已覆盖 external/internal fragmentation、不可 relocation 与 compaction 边界、split/coalescing、header、embedded free list、4KB/100-byte 示例、sbrk、best/worst/first/next fit、list ordering、segregated lists、Solaris slab、buddy allocator、throughput/utilization、malloc.py 7 道实验题、原文 Summary 与完整 References。

原文 References

  • [B+00] Emery D. Berger、Kathryn S. McKinley、Robert D. Blumofe、Paul R. Wilson,《Hoard: A Scalable Memory Allocator for Multithreaded Applications》,ASPLOS-IX,2000。
  • [B94] Jeff Bonwick,《The Slab Allocator: An Object-Caching Kernel Memory Allocator》,USENIX,1994。
  • [E06] Jason Evans,《A Scalable Concurrent malloc(3) Implementation for FreeBSD》,2006;介绍 jemalloc 的设计。
  • [K65] Kenneth C. Knowlton,《A Fast Storage Allocator》,Communications of the ACM,Vol. 8,No. 10,1965;buddy allocation 的经典引用。
  • [S15] Sploitfun,《Understanding glibc malloc》,2015。
  • [W+95] Paul R. Wilson、Mark S. Johnstone、Michael Neely、David Boles,《Dynamic Storage Allocation: A Survey and Critical Review》,International Workshop on Memory Management,1995。

关键结论

  • variable-sized allocation 的核心难点是 external fragmentation。
  • split 让大 free chunk 服务小请求;coalescing 把相邻 free chunks 合并。
  • header 让 free(ptr) 能恢复 chunk 大小,但会产生 metadata overhead。
  • best fit、worst fit、first fit、next fit 没有对所有 workload 都最优的方案。
  • address ordering、segregated lists、slab 和 buddy system 是组织 free space 的不同工程选择。
  • allocator 的评价必须同时考虑 throughput、utilization、fragmentation 和 worst-case behavior。

与已有笔记的关系

参考资料

← 返回列表
← 上一篇 OSTEP:Distributed System Security 下一篇 → OSTEP:Sun's Network File System(NFS)

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论