Skip to content

Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.

C

APFS in the kernel: the format layer in C, and a read-only driver on top of it

vcvkk773824fb5958
diff --git a/tools/apfs/apfs-tool.c b/tools/apfs/apfs-tool.c
new file mode 100644
index 0000000..6516841
--- /dev/null
+++ b/tools/apfs/apfs-tool.c
@@ -0,0 +1,510 @@
+/*
+ * Run the kernel's APFS reading code on the build machine.
+ *
+ * bsd/miscfs/apfs/apfs_lib.c is built into this program unchanged, so what it says about
+ * an image here is what the driver will see. `census` prints a line per directory entry
+ * that tools/apfs/apfs.py can print too, and run-tests.sh diffs the two: the Python
+ * reader has already been checked against 7-Zip over the whole volume, so agreeing with
+ * it byte for byte is the C code agreeing with the image.
+ *
+ * Built by tools/apfs/build-tool.sh.
+ *
+ * usage: apfs-tool info IMAGE
+ * apfs-tool ls IMAGE [PATH]
+ * apfs-tool stat IMAGE PATH
+ * apfs-tool cat IMAGE PATH
+ * apfs-tool census IMAGE [PATH]
+ */
+
+/* pread(2) */
+#define _DEFAULT_SOURCE
+
+#include <fcntl.h>
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "apfs_lib.h"
+
+/* ---- the image as a device ---- */
+
+static int
+file_read(void *ctx, uint64_t off, void *buf, size_t len)
+{
+ int fd = (int)(intptr_t)ctx;
+ uint8_t *p = buf;
+
+ while (len > 0) {
+ ssize_t n = pread(fd, p, len, (off_t)off);
+
+ if (n <= 0) {
+ return EIO;
+ }
+ p += n;
+ off += (uint64_t)n;
+ len -= (size_t)n;
+ }
+ return 0;
+}
+
+/* The same hash the Python side computes, so contents can be compared without the bytes. */
+static uint64_t
+fnv1a(const uint8_t *p, size_t n, uint64_t h)
+{
+ size_t i;
+
+ for (i = 0; i < n; i++) {
+ h ^= p[i];
+ h *= 0x100000001b3ULL;
+ }
+ return h;
+}
+
+#define FNV_INIT 0xcbf29ce484222325ULL
+
+static int
+open_image(const char *path, struct apfs_nx *nx, struct apfs_vol *vol)
+{
+ struct apfs_dev dev;
+ int fd = open(path, O_RDONLY);
+ uint32_t i;
+ int error;
+
+ if (fd < 0) {
+ perror(path);
+ return 1;
+ }
+ memset(&dev, 0, sizeof(dev));
+ dev.ctx = (void *)(intptr_t)fd;
+ dev.size = (uint64_t)lseek(fd, 0, SEEK_END);
+ dev.read = file_read;
+
+ error = apfs_nx_open(nx, &dev);
+ if (error) {
+ fprintf(stderr, "apfs-tool: cannot read the container: %s\n", strerror(error));
+ return 1;
+ }
+ /* the first volume that has a root directory, like apfs.py picks it */
+ for (i = 0; i < APFS_NX_MAX_FILE_SYSTEMS; i++) {
+ struct apfs_inode ino;
+
+ if (nx->fs_oid[i] == 0) {
+ continue;
+ }
+ if (apfs_vol_open(nx, i, vol) != 0) {
+ continue;
+ }
+ if (apfs_inode_get(vol, APFS_ROOT_DIR_INO_NUM, &ino) == 0) {
+ return 0;
+ }
+ }
+ fprintf(stderr, "apfs-tool: no readable volume with a root directory\n");
+ return 1;
+}
+
+/* ---- info ---- */
+
+static int
+cmd_info(const char *path)
+{
+ struct apfs_nx nx;
+ struct apfs_vol vol;
+ uint32_t i;
+
+ if (open_image(path, &nx, &vol) != 0) {
+ return 1;
+ }
+ printf("%s: APFS container, block size %u, %" PRIu64 " blocks\n", path,
+ nx.block_size, nx.block_count);
+ printf(" newest checkpoint xid %" PRIu64 "\n", nx.xid);
+ printf(" container omap block %" PRIu64 "\n", nx.omap_addr);
+ for (i = 0; i < APFS_NX_MAX_FILE_SYSTEMS; i++) {
+ struct apfs_vol v;
+
+ if (nx.fs_oid[i] == 0 || apfs_vol_open(&nx, i, &v) != 0) {
+ continue;
+ }
+ printf(" [%u] %s role 0x%04x incompatible 0x%" PRIx64 " fs flags 0x%" PRIx64 "\n",
+ i, v.name, v.role, v.incompat, v.fs_flags);
+ printf(" files %" PRIu64 " dirs %" PRIu64 " symlinks %" PRIu64
+ " blocks used %" PRIu64 "\n", v.num_files, v.num_dirs, v.num_symlinks,
+ v.alloc_count);
+ printf(" tree: %" PRIu64 " records in %" PRIu64 " nodes, flags 0x%x\n",
+ v.tree.key_count, v.tree.node_count, v.tree.flags);
+ }
+ printf(" blocks read %" PRIu64 ", cache hits %" PRIu64 "\n", nx.reads, nx.hits);
+ apfs_nx_close(&nx);
+ return 0;
+}
+
+/* ---- ls ---- */
+
+struct ls_ctx {
+ struct apfs_vol *vol;
+};
+
+static const char *
+mode_kind(uint16_t mode)
+{
+ switch (mode & APFS_S_IFMT) {
+ case APFS_S_IFDIR: return "d";
+ case APFS_S_IFLNK: return "l";
+ case APFS_S_IFREG: return "-";
+ case APFS_S_IFIFO: return "p";
+ case APFS_S_IFCHR: return "c";
+ case APFS_S_IFBLK: return "b";
+ case APFS_S_IFSOCK: return "s";
+ default: return "?";
+ }
+}
+
+static int
+ls_cb(void *ctx, const char *name, size_t name_len, uint64_t file_id, uint8_t d_type)
+{
+ struct ls_ctx *lc = ctx;
+ struct apfs_inode ino;
+
+ (void)name_len;
+ (void)d_type;
+ if (apfs_inode_get(lc->vol, file_id, &ino) != 0) {
+ printf("? %20s %s (no inode record)\n", "", name);
+ return 0;
+ }
+ printf("%s %06o %4u:%-4u %12" PRIu64 " %-20" PRIu64 " %s", mode_kind(ino.mode),
+ ino.mode & 07777, ino.owner, ino.group, ino.size, file_id, name);
+ if ((ino.mode & APFS_S_IFMT) == APFS_S_IFLNK) {
+ char target[1024];
+ size_t n = 0;
+
+ if (apfs_readlink(lc->vol, file_id, target, sizeof(target) - 1, &n) == 0) {
+ target[n] = '\0';
+ printf(" -> %s", target);
+ }
+ }
+ printf("\n");
+ return 0;
+}
+
+static int
+cmd_ls(const char *path, const char *where)
+{
+ struct apfs_nx nx;
+ struct apfs_vol vol;
+ struct ls_ctx lc;
+ uint64_t id;
+ uint8_t dt;
+ int error;
+
+ if (open_image(path, &nx, &vol) != 0) {
+ return 1;
+ }
+ error = apfs_path_lookup(&vol, where, &id, &dt);
+ if (error) {
+ fprintf(stderr, "apfs-tool: %s: %s\n", where, strerror(error));
+ return 1;
+ }
+ lc.vol = &vol;
+ if (dt != APFS_DT_DIR) {
+ ls_cb(&lc, where, strlen(where), id, dt);
+ } else {
+ error = apfs_readdir(&vol, id, ls_cb, &lc);
+ if (error) {
+ fprintf(stderr, "apfs-tool: %s\n", strerror(error));
+ return 1;
+ }
+ }
+ apfs_nx_close(&nx);
+ return 0;
+}
+
+/* ---- stat ---- */
+
+static int
+xattr_print_cb(void *ctx, const char *name, size_t name_len, const struct apfs_xattr *xa)
+{
+ (void)ctx;
+ (void)name_len;
+ printf(" xattr %-28s flags 0x%x %u bytes%s\n", name, xa->flags, xa->data_len,
+ (xa->flags & APFS_XATTR_DATA_STREAM) ? " (in a data stream)" : "");
+ return 0;
+}
+
+static int
+cmd_stat(const char *path, const char *where)
+{
+ struct apfs_nx nx;
+ struct apfs_vol vol;
+ struct apfs_inode ino;
+ struct apfs_cfile cf;
+ uint64_t id;
+ uint8_t dt;
+ int error;
+
+ if (open_image(path, &nx, &vol) != 0) {
+ return 1;
+ }
+ error = apfs_path_lookup(&vol, where, &id, &dt);
+ if (error) {
+ fprintf(stderr, "apfs-tool: %s: %s\n", where, strerror(error));
+ return 1;
+ }
+ error = apfs_inode_get(&vol, id, &ino);
+ if (error) {
+ fprintf(stderr, "apfs-tool: inode %" PRIu64 ": %s\n", id, strerror(error));
+ return 1;
+ }
+ printf("path %s\n", where);
+ printf("inode %" PRIu64 " parent %" PRIu64 " private %" PRIu64 "\n",
+ ino.obj_id, ino.parent_id, ino.private_id);
+ printf("mode %06o uid %u gid %u\n", ino.mode, ino.owner, ino.group);
+ printf("size %" PRIu64 " allocated %" PRIu64 "\n", ino.size,
+ ino.alloced_size);
+ printf("flags internal 0x%" PRIx64 " bsd 0x%x%s\n", ino.internal_flags,
+ ino.bsd_flags, ino.is_sparse ? " sparse" : "");
+ if (apfs_cfile_init(&vol, &ino, &cf) == 0 && cf.compressed) {
+ printf("decmpfs type %u uncompressed %" PRIu64 " %s\n", cf.type, cf.size,
+ cf.in_rsrc ? "in the resource fork" : "in the attribute");
+ }
+ apfs_xattr_list(&vol, id, xattr_print_cb, NULL);
+ apfs_nx_close(&nx);
+ return 0;
+}
+
+/* ---- cat ---- */
+
+static int
+cmd_cat(const char *path, const char *where)
+{
+ struct apfs_nx nx;
+ struct apfs_vol vol;
+ struct apfs_inode ino;
+ uint64_t id, off = 0;
+ uint8_t dt;
+ uint8_t *buf;
+ int error;
+
+ if (open_image(path, &nx, &vol) != 0) {
+ return 1;
+ }
+ error = apfs_path_lookup(&vol, where, &id, &dt);
+ if (error == 0) {
+ error = apfs_inode_get(&vol, id, &ino);
+ }
+ if (error) {
+ fprintf(stderr, "apfs-tool: %s: %s\n", where, strerror(error));
+ return 1;
+ }
+ buf = malloc(65536);
+ if (buf == NULL) {
+ return 1;
+ }
+ while (off < ino.size) {
+ size_t got = 0;
+
+ error = apfs_read_file(&vol, &ino, off, buf, 65536, &got);
+ if (error) {
+ fprintf(stderr, "apfs-tool: read at %" PRIu64 ": %s\n", off,
+ strerror(error));
+ free(buf);
+ return 1;
+ }
+ if (got == 0) {
+ break;
+ }
+ if (fwrite(buf, 1, got, stdout) != got) {
+ free(buf);
+ return 1;
+ }
+ off += got;
+ }
+ free(buf);
+ apfs_nx_close(&nx);
+ return 0;
+}
+
+/* ---- census: one line per entry, for diffing against apfs.py ---- */
+
+struct census {
+ struct apfs_vol *vol;
+ char *path; /* the directory being walked, with a trailing / */
+ size_t path_len;
+ size_t path_cap;
+ uint8_t *buf;
+ long max;
+ long seen;
+ int error;
+};
+
+static int census_dir(struct census *cs, uint64_t dir_id);
+
+static uint64_t
+file_hash(struct census *cs, const struct apfs_inode *ino, uint64_t size)
+{
+ uint64_t h = FNV_INIT, off = 0;
+
+ for (;;) {
+ size_t got = 0;
+ int error = apfs_read_file(cs->vol, ino, off, cs->buf, 65536, &got);
+
+ if (error) {
+ fprintf(stderr, "apfs-tool: %s: read at %" PRIu64 ": %s\n", cs->path,
+ off, strerror(error));
+ cs->error = error;
+ return 0;
+ }
+ if (got == 0) {
+ break;
+ }
+ h = fnv1a(cs->buf, got, h);
+ off += got;
+ if (off >= size) {
+ break;
+ }
+ }
+ return h;
+}
+
+static int
+census_cb(void *ctx, const char *name, size_t name_len, uint64_t file_id, uint8_t d_type)
+{
+ struct census *cs = ctx;
+ struct apfs_inode ino;
+ size_t saved = cs->path_len;
+ uint64_t h = 0, size = 0;
+ int error;
+
+ if (cs->max > 0 && cs->seen >= cs->max) {
+ return EEXIST;
+ }
+ /* append "/name" to the path we are at */
+ while (cs->path_len + name_len + 2 > cs->path_cap) {
+ cs->path_cap *= 2;
+ cs->path = realloc(cs->path, cs->path_cap);
+ if (cs->path == NULL) {
+ return ENOMEM;
+ }
+ }
+ cs->path[cs->path_len++] = '/';
+ memcpy(cs->path + cs->path_len, name, name_len);
+ cs->path_len += name_len;
+ cs->path[cs->path_len] = '\0';
+
+ error = apfs_inode_get(cs->vol, file_id, &ino);
+ if (error) {
+ printf("%s\t?\tno-inode\n", cs->path);
+ cs->error = error;
+ goto done;
+ }
+ cs->seen++;
+ if (apfs_inode_size(cs->vol, &ino, &size) != 0) {
+ size = ino.size;
+ }
+ if ((ino.mode & APFS_S_IFMT) == APFS_S_IFREG ||
+ (ino.mode & APFS_S_IFMT) == APFS_S_IFLNK) {
+ h = file_hash(cs, &ino, size);
+ }
+ printf("%s\t%u\t%06o\t%u\t%u\t%" PRIu64 "\t%016" PRIx64 "\n", cs->path, d_type,
+ ino.mode, ino.owner, ino.group, size, h);
+
+ if (d_type == APFS_DT_DIR) {
+ error = census_dir(cs, file_id);
+ if (error) {
+ cs->path_len = saved;
+ cs->path[cs->path_len] = '\0';
+ return error;
+ }
+ }
+done:
+ cs->path_len = saved;
+ cs->path[cs->path_len] = '\0';
+ return 0;
+}
+
+static int
+census_dir(struct census *cs, uint64_t dir_id)
+{
+ return apfs_readdir(cs->vol, dir_id, census_cb, cs);
+}
+
+static int
+cmd_census(const char *path, const char *where)
+{
+ struct apfs_nx nx;
+ struct apfs_vol vol;
+ struct census cs;
+ uint64_t start = APFS_ROOT_DIR_INO_NUM;
+ uint8_t dt = APFS_DT_DIR;
+ int error;
+
+ if (open_image(path, &nx, &vol) != 0) {
+ return 1;
+ }
+ if (where != NULL && apfs_path_lookup(&vol, where, &start, &dt) != 0) {
+ fprintf(stderr, "apfs-tool: %s: not found\n", where);
+ return 1;
+ }
+ memset(&cs, 0, sizeof(cs));
+ cs.vol = &vol;
+ cs.path_cap = 4096;
+ cs.path = malloc(cs.path_cap);
+ cs.buf = malloc(65536);
+ cs.max = 0;
+ if (cs.path == NULL || cs.buf == NULL) {
+ return 1;
+ }
+ cs.path[0] = '\0';
+ if (where != NULL) {
+ size_t n = strlen(where);
+
+ while (n > 0 && where[n - 1] == '/') {
+ n--;
+ }
+ memcpy(cs.path, where, n);
+ cs.path_len = n;
+ cs.path[n] = '\0';
+ }
+ error = census_dir(&cs, start);
+ if (error && error != EEXIST) {
+ fprintf(stderr, "apfs-tool: census: %s\n", strerror(error));
+ return 1;
+ }
+ fprintf(stderr, "apfs-tool: %ld entries, %" PRIu64 " blocks read, %" PRIu64
+ " cache hits\n", cs.seen, nx.reads, nx.hits);
+ free(cs.path);
+ free(cs.buf);
+ apfs_nx_close(&nx);
+ return cs.error ? 1 : 0;
+}
+
+int
+main(int argc, char **argv)
+{
+ if (argc < 3) {
+ fprintf(stderr,
+ "usage: apfs-tool info IMAGE\n"
+ " apfs-tool ls IMAGE [PATH]\n"
+ " apfs-tool stat IMAGE PATH\n"
+ " apfs-tool cat IMAGE PATH\n"
+ " apfs-tool census IMAGE [PATH]\n");
+ return 2;
+ }
+ if (strcmp(argv[1], "info") == 0) {
+ return cmd_info(argv[2]);
+ }
+ if (strcmp(argv[1], "ls") == 0) {
+ return cmd_ls(argv[2], argc > 3 ? argv[3] : "/");
+ }
+ if (strcmp(argv[1], "stat") == 0 && argc > 3) {
+ return cmd_stat(argv[2], argv[3]);
+ }
+ if (strcmp(argv[1], "cat") == 0 && argc > 3) {
+ return cmd_cat(argv[2], argv[3]);
+ }
+ if (strcmp(argv[1], "census") == 0) {
+ return cmd_census(argv[2], argc > 3 ? argv[3] : NULL);
+ }
+ fprintf(stderr, "apfs-tool: unknown command %s\n", argv[1]);
+ return 2;
+}
diff --git a/tools/apfs/build-tool.sh b/tools/apfs/build-tool.sh
new file mode 100755
index 0000000..ff0aad3
--- /dev/null
+++ b/tools/apfs/build-tool.sh
@@ -0,0 +1,22 @@
+#!/bin/bash
+# Build the kernel's APFS reading code as a program for this machine, so it can be run
+# against a real image before it goes anywhere near the kernel. The .c file is taken from
+# the kernel tree unchanged; only apfs_lib.h's few allocation and logging macros differ
+# when KERNEL is not defined.
+#
+# usage: tools/apfs/build-tool.sh [OUT] (default: apfs-work/apfs-tool)
+set -eu
+HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
+ROOT=$(cd "$HERE/../.." && pwd)
+OUT=${1:-$ROOT/apfs-work/apfs-tool}
+
+SRC=""
+for d in "$ROOT/xnu-src/xnu-8796.121.2/bsd/miscfs/apfs" "$ROOT/xnu/files/bsd/miscfs/apfs"; do
+ [ -f "$d/apfs_lib.c" ] && { SRC=$d; break; }
+done
+[ -n "$SRC" ] || { echo "build-tool.sh: apfs_lib.c is in neither the kernel tree nor xnu/files" >&2; exit 1; }
+
+mkdir -p "$(dirname "$OUT")"
+cc -std=c11 -O2 -Wall -Wextra -Wno-unused-parameter -I"$SRC" -I"$HERE" \
+ -o "$OUT" "$HERE/apfs-tool.c" "$SRC/apfs_lib.c" -lz
+echo "build-tool.sh: $OUT (from $SRC)"
diff --git a/tools/apfs/verify.py b/tools/apfs/verify.py
index dc27f00..883141c 100755
--- a/tools/apfs/verify.py
+++ b/tools/apfs/verify.py
@@ -10,9 +10,13 @@
# content ios165/rootfs/ -- the files 7-Zip actually extracted, compared byte for
# byte. This is the one that proves we decompress correctly.
#
+# clines the same lines tools/apfs/apfs-tool prints, so the C code that goes into the
+# kernel can be diffed against this reader over a whole tree.
+#
# usage: verify.py listing IMAGE SLT
# verify.py content IMAGE REFDIR [-n COUNT] [--all]
# verify.py sample IMAGE REFDIR (a few dozen files of every kind)
+# verify.py clines IMAGE [PATH]
import os
import random
@@ -311,6 +315,54 @@ def cmd_content(image, refdir, limit, do_all, stratified):
return 0 if not fails else 1
+FNV_INIT = 0xCBF29CE484222325
+FNV_PRIME = 0x100000001B3
+MASK64 = (1 << 64) - 1
+
+
+def fnv1a(buf, h=FNV_INIT):
+ for b in buf:
+ h = ((h ^ b) * FNV_PRIME) & MASK64
+ return h
+
+
+def cmd_clines(image, where):
+ """
+ One line per directory entry, the same shape apfs-tool's census prints:
+ path, d_type, mode, uid, gid, logical size, FNV-1a of the contents
+ Only regular files and symbolic links get a hash; everything else gets zero.
+ """
+ c, v = open_volume(image)
+ start = apfs.ROOT_DIR_INO_NUM
+ prefix = ""
+ if where:
+ hit = v.lookup(where)
+ if hit is None:
+ print("verify.py: %s: not found" % where, file=sys.stderr)
+ return 1
+ start = hit[0]
+ prefix = "/" + where.strip("/")
+ out = sys.stdout
+ stack = [(start, prefix)]
+ while stack:
+ oid, px = stack.pop()
+ for name, fid, dt in v.dir_entries(oid):
+ p = px + "/" + name
+ ino = v.inode(fid)
+ if ino is None:
+ out.write("%s\t?\tno-inode\n" % p)
+ continue
+ h = 0
+ if ino.is_reg or ino.is_link:
+ h = fnv1a(ino.contents())
+ out.write("%s\t%d\t%06o\t%d\t%d\t%d\t%016x\n"
+ % (p, dt, ino.mode, ino.owner, ino.group, ino.size, h))
+ if dt == 4:
+ stack.append((fid, p))
+ c.close()
+ return 0
+
+
def main(argv):
limit = 200
do_all = False
@@ -328,10 +380,11 @@ def main(argv):
continue
args.append(a)
i += 1
- if len(args) < 3:
+ if len(args) < 2 or (args[0] != "clines" and len(args) < 3):
print("usage: verify.py listing IMAGE SLT\n"
" verify.py content IMAGE REFDIR [-n COUNT] [--all]\n"
- " verify.py sample IMAGE REFDIR", file=sys.stderr)
+ " verify.py sample IMAGE REFDIR\n"
+ " verify.py clines IMAGE [PATH]", file=sys.stderr)
return 2
cmd = args[0]
if cmd == "listing":
@@ -340,6 +393,8 @@ def main(argv):
return cmd_content(args[1], args[2], limit, do_all, False)
if cmd == "sample":
return cmd_content(args[1], args[2], limit, False, True)
+ if cmd == "clines":
+ return cmd_clines(args[1], args[2] if len(args) > 2 else None)
print("verify.py: unknown command %r" % cmd, file=sys.stderr)
return 2
diff --git a/xnu/files/bsd/miscfs/apfs/apfs.h b/xnu/files/bsd/miscfs/apfs/apfs.h
new file mode 100644
index 0000000..ffa9480
--- /dev/null
+++ b/xnu/files/bsd/miscfs/apfs/apfs.h
@@ -0,0 +1,69 @@
+/*
+ * apfs: reading an Apple File System volume from the kernel.
+ *
+ * The format itself is in apfs_lib.{h,c}, which knows nothing of vnodes and is checked
+ * against real images on the build machine (tools/apfs/run-tests.sh). This is the layer
+ * between that and VFS: a mount, a vnode per object, and the vnode operations.
+ *
+ * Read only. Nothing here writes to the device.
+ *
+ * apfs_lib keeps a cache of metadata blocks and hands out pointers into it, and its
+ * cursors are plain structures with no locking of their own, so every call into it is
+ * made with am_lock held. That makes the whole volume one lock wide, which is enough for
+ * a read-only root: the work under the lock is a few block reads, usually from the cache.
+ */
+
+#ifndef _MISCFS_APFS_APFS_H_
+#define _MISCFS_APFS_APFS_H_
+
+#include <sys/param.h>
+#include <sys/mount.h>
+#include <sys/vnode.h>
+#include <kern/locks.h>
+
+#include "apfs_lib.h"
+
+/* Buckets in the table that finds an existing vnode by object identifier. */
+#define APFS_HASH_BUCKETS 1024
+
+struct apfs_node;
+
+struct apfs_mount {
+ mount_t am_mp;
+ vnode_t am_devvp;
+ lck_mtx_t am_lock;
+ struct apfs_nx am_nx;
+ struct apfs_vol am_vol;
+ uint32_t am_devblock;
+ struct apfs_node *am_hash[APFS_HASH_BUCKETS];
+ uint64_t am_root_id;
+};
+
+/* The private part of a vnode: which object it is. */
+struct apfs_node {
+ struct apfs_node *an_next; /* the hash chain */
+ struct apfs_mount *an_mount;
+ vnode_t an_vp;
+ uint64_t an_id; /* the object identifier */
+ uint64_t an_parent;
+ uint16_t an_mode;
+ uint64_t an_size; /* the logical size, as a reader of the file sees it */
+ bool an_attached; /* an_vp is set and the node is in the hash */
+};
+
+#define APFS_MP(mp) ((struct apfs_mount *)vfs_fsprivate(mp))
+#define APFS_VP(vp) ((struct apfs_node *)vnode_fsnode(vp))
+#define APFS_VP_MOUNT(vp) (APFS_VP(vp)->an_mount)
+
+/* apfs_vfsops.c */
+extern struct vfsops apfs_vfsops;
+int apfs_mountroot(mount_t mp, vnode_t devvp, vfs_context_t ctx);
+int apfs_node_vnode(struct apfs_mount *am, uint64_t obj_id, vnode_t dvp,
+ struct componentname *cnp, vnode_t *vpp);
+void apfs_node_detach(struct apfs_node *an);
+
+/* apfs_vnops.c */
+extern const struct vnodeopv_desc apfs_vnodeop_opv_desc;
+extern int (**apfs_vnodeop_p)(void *);
+
+#endif /* _MISCFS_APFS_APFS_H_ */
diff --git a/xnu/files/bsd/miscfs/apfs/apfs_lib.c b/xnu/files/bsd/miscfs/apfs/apfs_lib.c
new file mode 100644
index 0000000..51b8f66
--- /dev/null
+++ b/xnu/files/bsd/miscfs/apfs/apfs_lib.c
@@ -0,0 +1,1846 @@
+/*
+ * Reading the Apple File System. See apfs_lib.h for what this does and does not do, and
+ * apfs_format.h for the layout. Nothing here writes to the device.
+ *
+ * Everything on disk is little-endian and is read with memcpy through the le* helpers, so
+ * none of this depends on the alignment of a field inside a block.
+ *
+ * Validation is the point of most of the code that is not a struct field being copied: a
+ * block that fails its Fletcher-64, an offset that leaves its node, a length that does not
+ * fit the record it came from, a tree deeper than APFS_MAX_LEVELS -- each ends the call
+ * with EIO rather than being followed.
+ */
+
+#include "apfs_lib.h"
+
+#ifdef KERNEL
+#include <libkern/zlib.h>
+#else
+#include <zlib.h>
+#endif
+
+/* The pieces a resource-fork-compressed file is cut into. */
+#define APFS_RSRC_PIECE APFS_DECMPFS_BLOCK_SIZE
+
+/* ------------------------------------------------------------------ bytes */
+
+static inline uint16_t
+le16(const uint8_t *p)
+{
+ uint16_t v;
+ memcpy(&v, p, sizeof(v));
+ return v;
+}
+
+static inline uint32_t
+le32(const uint8_t *p)
+{
+ uint32_t v;
+ memcpy(&v, p, sizeof(v));
+ return v;
+}
+
+static inline uint64_t
+le64(const uint8_t *p)
+{
+ uint64_t v;
+ memcpy(&v, p, sizeof(v));
+ return v;
+}
+
+static inline uint32_t
+be32(const uint8_t *p)
+{
+ return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) |
+ ((uint32_t)p[2] << 8) | (uint32_t)p[3];
+}
+
+/*
+ * Fletcher-64 as APFS uses it: over the block with its own checksum field included, the
+ * result is zero; over the block after the field, the result is what the field holds.
+ */
+uint64_t
+apfs_fletcher64(const uint8_t *data, size_t len)
+{
+ const uint64_t mod = 0xFFFFFFFFULL;
+ uint64_t sum1 = 0, sum2 = 0;
+ size_t i;
+
+ for (i = 0; i + 4 <= len; i += 4) {
+ sum1 = (sum1 + le32(data + i)) % mod;
+ sum2 = (sum2 + sum1) % mod;
+ }
+ {
+ uint64_t c1 = mod - ((sum1 + sum2) % mod);
+ uint64_t c2 = mod - ((sum1 + c1) % mod);
+ return (c2 << 32) | c1;
+ }
+}
+
+bool
+apfs_checksum_ok(const uint8_t *block, uint32_t block_size)
+{
+ if (block_size < 8 || (block_size % 4) != 0) {
+ return false;
+ }
+ return apfs_fletcher64(block + 8, block_size - 8) == le64(block);
+}
+
+uint16_t
+apfs_mode_to_dtype(uint16_t mode)
+{
+ switch (mode & APFS_S_IFMT) {
+ case APFS_S_IFIFO: return APFS_DT_FIFO;
+ case APFS_S_IFCHR: return APFS_DT_CHR;
+ case APFS_S_IFDIR: return APFS_DT_DIR;
+ case APFS_S_IFBLK: return APFS_DT_BLK;
+ case APFS_S_IFREG: return APFS_DT_REG;
+ case APFS_S_IFLNK: return APFS_DT_LNK;
+ case APFS_S_IFSOCK: return APFS_DT_SOCK;
+ default: return APFS_DT_UNKNOWN;
+ }
+}
+
+/* ------------------------------------------------------------------ blocks */
+
+/*
+ * A block of metadata, from the cache or from the device. The returned pointer stays
+ * good until APFS_CACHE_BLOCKS further blocks have been fetched, which is why a B-tree
+ * descent holds block addresses and not pointers.
+ */
+static int
+nx_block(struct apfs_nx *nx, uint64_t addr, const uint8_t **out, bool verify)
+{
+ struct apfs_buf *victim = NULL;
+ uint32_t i, oldest = 0xFFFFFFFFu;
+ int error;
+
+ if (addr == 0 || addr >= nx->block_count) {
+ return EIO;
+ }
+ for (i = 0; i < APFS_CACHE_BLOCKS; i++) {
+ if (nx->cache[i].addr == addr && nx->cache[i].data != NULL) {
+ nx->cache[i].age = ++nx->clock;
+ nx->hits++;
+ *out = nx->cache[i].data;
+ return 0;
+ }
+ }
+ /* not cached: take an unused slot, else the one used longest ago */
+ for (i = 0; i < APFS_CACHE_BLOCKS; i++) {
+ if (nx->cache[i].data == NULL) {
+ nx->cache[i].data = apfs_alloc(nx->block_size);
+ if (nx->cache[i].data == NULL) {
+ return ENOMEM;
+ }
+ victim = &nx->cache[i];
+ break;
+ }
+ if (nx->cache[i].age < oldest) {
+ oldest = nx->cache[i].age;
+ victim = &nx->cache[i];
+ }
+ }
+ if (victim == NULL) {
+ return ENOMEM;
+ }
+ victim->addr = APFS_BUF_EMPTY;
+ error = nx->dev.read(nx->dev.ctx, addr * (uint64_t)nx->block_size, victim->data,
+ nx->block_size);
+ if (error) {
+ return error;
+ }
+ nx->reads++;
+ if (verify && !apfs_checksum_ok(victim->data, nx->block_size)) {
+ apfs_log("block %llu: bad checksum\n", (unsigned long long)addr);
+ return EIO;
+ }
+ victim->addr = addr;
+ victim->age = ++nx->clock;
+ *out = victim->data;
+ return 0;
+}
+
+static uint32_t
+obj_type(const uint8_t *blk)
+{
+ return le32(blk + 24) & APFS_OBJECT_TYPE_MASK;
+}
+
+static apfs_xid_t
+obj_xid(const uint8_t *blk)
+{
+ return le64(blk + 16);
+}
+
+/* ------------------------------------------------------------------ b-tree nodes */
+
+struct node {
+ const uint8_t *blk;
+ uint16_t flags;
+ uint16_t level;
+ uint32_t nkeys;
+ uint32_t toc_off;
+ uint32_t toc_len;
+ uint32_t key_base;
+ uint32_t val_end;
+ bool fixed;
+ bool leaf;
+};
+
+/*
+ * Pick a node block apart and check that every area it describes is inside the block.
+ * A node is: the object header, the table of contents, then keys growing forward from the
+ * end of the table and values growing backwards from the end of the block -- short of the
+ * btree_info that a root node keeps in its last bytes.
+ */
+static int
+node_parse(struct apfs_btree *tree, const uint8_t *blk, struct node *n)
+{
+ uint32_t bs = tree->nx->block_size;
+ uint32_t ts_off, ts_len, ent, need;
+
+ n->blk = blk;
+ n->flags = le16(blk + 32);
+ n->level = le16(blk + 34);
+ n->nkeys = le32(blk + 36);
+ ts_off = le16(blk + 40);
+ ts_len = le16(blk + 42);
+ n->fixed = (n->flags & APFS_BTNODE_FIXED_KV_SIZE) != 0;
+ n->leaf = (n->flags & APFS_BTNODE_LEAF) != 0;
+
+ if (n->level >= APFS_MAX_LEVELS) {
+ return EIO;
+ }
+ n->toc_off = 56 + ts_off;
+ n->toc_len = ts_len;
+ if (n->toc_off < 56 || n->toc_off > bs || n->toc_len > bs - n->toc_off) {
+ return EIO;
+ }
+ n->key_base = n->toc_off + n->toc_len;
+ n->val_end = bs;
+ if (n->flags & APFS_BTNODE_ROOT) {
+ if (bs < 56 + sizeof(struct apfs_btree_info)) {
+ return EIO;
+ }
+ n->val_end = bs - (uint32_t)sizeof(struct apfs_btree_info);
+ }
+ if (n->key_base > n->val_end) {
+ return EIO;
+ }
+ /* the table of contents must hold the entries the header claims */
+ ent = n->fixed ? 4u : 8u;
+ if (n->nkeys > (bs / ent)) {
+ return EIO;
+ }
+ need = n->nkeys * ent;
+ if (need > n->toc_len) {
+ return EIO;
+ }
+ if (n->fixed && n->leaf && tree->key_size == 0) {
+ return EIO; /* fixed layout with no size to use */
+ }
+ return 0;
+}
+
+/*
+ * Entry i of a node. A value offset of 0xffff marks a key with no value ("a ghost"),
+ * which comes back as a zero length rather than an error.
+ */
+static int
+node_entry(struct apfs_btree *tree, const struct node *n, uint32_t i,
+ const uint8_t **kp, uint16_t *klen, const uint8_t **vp, uint16_t *vlen)
+{
+ uint32_t koff, voff, kl, vl;
+
+ if (i >= n->nkeys) {
+ return EIO;
+ }
+ if (n->fixed) {
+ koff = le16(n->blk + n->toc_off + 4 * i);
+ voff = le16(n->blk + n->toc_off + 4 * i + 2);
+ kl = tree->key_size;
+ vl = n->leaf ? tree->val_size : 8;
+ } else {
+ koff = le16(n->blk + n->toc_off + 8 * i);
+ kl = le16(n->blk + n->toc_off + 8 * i + 2);
+ voff = le16(n->blk + n->toc_off + 8 * i + 4);
+ vl = le16(n->blk + n->toc_off + 8 * i + 6);
+ }
+ /* a key lives at key_base + offset and must end before the value area */
+ if (koff > n->val_end - n->key_base || kl > n->val_end - n->key_base - koff) {
+ return EIO;
+ }
+ *kp = n->blk + n->key_base + koff;
+ *klen = (uint16_t)kl;
+
+ if (voff == APFS_BTOFF_INVALID && !n->fixed) {
+ *vp = NULL;
+ *vlen = 0;
+ return 0;
+ }
+ /* a value is measured backwards from the end of the value area */
+ if (voff > n->val_end || vl > voff || n->val_end - voff < n->key_base) {
+ return EIO;
+ }
+ *vp = n->blk + n->val_end - voff;
+ *vlen = (uint16_t)vl;
+ return 0;
+}
+
+/* The identifier of child i of a non-leaf node. */
+static int
+node_child(struct apfs_btree *tree, const struct node *n, uint32_t i, uint64_t *oid)
+{
+ const uint8_t *k, *v;
+ uint16_t kl, vl;
+ int error = node_entry(tree, n, i, &k, &kl, &v, &vl);
+
+ if (error) {
+ return error;
+ }
+ if (v == NULL || vl < 8) {
+ return EIO;
+ }
+ *oid = le64(v);
+ return 0;
+}
+
+/* Where a node identifier actually is: a block address, directly or through a map. */
+static int
+tree_node_addr(struct apfs_btree *tree, uint64_t oid, uint64_t *addr);
+
+static int
+tree_node(struct apfs_btree *tree, uint64_t oid, const uint8_t **blk, struct node *n)
+{
+ uint64_t addr;
+ int error = tree_node_addr(tree, oid, &addr);
+
+ if (error) {
+ return error;
+ }
+ error = nx_block(tree->nx, addr, blk, true);
+ if (error) {
+ return error;
+ }
+ if (obj_type(*blk) != APFS_OBJECT_TYPE_BTREE &&
+ obj_type(*blk) != APFS_OBJECT_TYPE_BTREE_NODE) {
+ return EIO;
+ }
+ return node_parse(tree, *blk, n);
+}
+
+/* ------------------------------------------------------------------ object maps */
+
+static int omap_find(struct apfs_omap *omap, uint64_t oid, apfs_xid_t want_xid,
+ uint64_t *addr);
+
+static int
+tree_node_addr(struct apfs_btree *tree, uint64_t oid, uint64_t *addr)
+{
+ if (tree->omap == NULL || (tree->flags & APFS_BTREE_PHYSICAL)) {
+ *addr = oid;
+ return 0;
+ }
+ return omap_find(tree->omap, oid, tree->nx->xid, addr);
+}
+
+/* Read a tree's root and remember what its btree_info says about the whole tree. */
+static int
+btree_open(struct apfs_nx *nx, struct apfs_omap *omap, uint64_t root_oid,
+ struct apfs_btree *tree)
+{
+ const uint8_t *blk;
+ uint64_t addr;
+ uint32_t bs = nx->block_size;
+ const uint8_t *info;
+ int error;
+
+ memset(tree, 0, sizeof(*tree));
+ tree->nx = nx;
+ tree->omap = omap;
+ /* the root is found the same way as any node, but its flags are not known yet */
+ if (omap == NULL) {
+ addr = root_oid;
+ } else {
+ error = omap_find(omap, root_oid, nx->xid, &addr);
+ if (error) {
+ return error;
+ }
+ }
+ error = nx_block(nx, addr, &blk, true);
+ if (error) {
+ return error;
+ }
+ if (obj_type(blk) != APFS_OBJECT_TYPE_BTREE) {
+ apfs_log("block %llu is not a b-tree root\n", (unsigned long long)addr);
+ return EIO;
+ }
+ if (bs < 56 + sizeof(struct apfs_btree_info)) {
+ return EIO;
+ }
+ info = blk + bs - sizeof(struct apfs_btree_info);
+ tree->root = addr;
+ tree->flags = le32(info);
+ tree->key_size = le32(info + 8);
+ tree->val_size = le32(info + 12);
+ tree->key_count = le64(info + 24);
+ tree->node_count = le64(info + 32);
+ return 0;
+}
+
+static int
+omap_open(struct apfs_nx *nx, uint64_t omap_addr, struct apfs_omap *omap)
+{
+ const uint8_t *blk;
+ uint64_t tree_oid;
+ int error;
+
+ memset(omap, 0, sizeof(*omap));
+ error = nx_block(nx, omap_addr, &blk, true);
+ if (error) {
+ return error;
+ }
+ if (obj_type(blk) != APFS_OBJECT_TYPE_OMAP) {
+ apfs_log("block %llu is not an object map\n", (unsigned long long)omap_addr);
+ return EIO;
+ }
+ tree_oid = le64(blk + 48); /* om_tree_oid, a physical tree */
+ error = btree_open(nx, NULL, tree_oid, &omap->tree);
+ if (error) {
+ return error;
+ }
+ omap->ready = true;
+ return 0;
+}
+
+/*
+ * Where an object lives. The map is keyed by (identifier, transaction) in that order, so
+ * the versions of one object are a run; we want the newest that is not past want_xid.
+ */
+static int
+omap_find(struct apfs_omap *omap, uint64_t oid, apfs_xid_t want_xid, uint64_t *addr)
+{
+ struct apfs_btree *tree = &omap->tree;
+ uint64_t node_oid = tree->root;
+ struct node n;
+ const uint8_t *blk;
+ int level, error;
+
+ if (!omap->ready) {
+ return EIO;
+ }
+ error = nx_block(tree->nx, node_oid, &blk, true);
+ if (error) {
+ return error;
+ }
+ error = node_parse(tree, blk, &n);
+ if (error) {
+ return error;
+ }
+ for (level = 0; level < APFS_MAX_LEVELS; level++) {
+ uint32_t i, best = 0;
+ bool found = false;
+
+ if (n.nkeys == 0) {
+ return ENOENT;
+ }
+ /* the last entry whose key is at or before what we are looking for */
+ for (i = 0; i < n.nkeys; i++) {
+ const uint8_t *k, *v;
+ uint16_t kl, vl;
+ uint64_t o, x;
+
+ error = node_entry(tree, &n, i, &k, &kl, &v, &vl);
+ if (error) {
+ return error;
+ }
+ if (kl < 16) {
+ return EIO;
+ }
+ o = le64(k);
+ x = le64(k + 8);
+ if (o < oid || (o == oid && x <= want_xid)) {
+ best = i;
+ found = true;
+ } else {
+ break;
+ }
+ }
+ if (!found) {
+ return ENOENT;
+ }
+ if (n.leaf) {
+ const uint8_t *k, *v;
+ uint16_t kl, vl;
+
+ error = node_entry(tree, &n, best, &k, &kl, &v, &vl);
+ if (error) {
+ return error;
+ }
+ if (kl < 16 || le64(k) != oid) {
+ return ENOENT;
+ }
+ if (v == NULL || vl < 16) {
+ return EIO;
+ }
+ /* omap_val: flags, size, then the block address */
+ *addr = le64(v + 8);
+ if (*addr == 0 || *addr >= tree->nx->block_count) {
+ return EIO;
+ }
+ return 0;
+ }
+ error = node_child(tree, &n, best, &node_oid);
+ if (error) {
+ return error;
+ }
+ error = nx_block(tree->nx, node_oid, &blk, true);
+ if (error) {
+ return error;
+ }
+ error = node_parse(tree, blk, &n);
+ if (error) {
+ return error;
+ }
+ }
+ return EIO; /* deeper than any real tree: treat as damage */
+}
+
+/* ------------------------------------------------------------------ container */
+
+/* The key of a file-system record: the object id and the kind, packed into eight bytes. */
+static inline uint64_t
+jkey_id(const uint8_t *k)
+{
+ return le64(k) & APFS_OBJ_ID_MASK;
+}
+
+static inline uint8_t
+jkey_type(const uint8_t *k)
+{
+ return (uint8_t)(le64(k) >> APFS_OBJ_TYPE_SHIFT);
+}
+
+int
+apfs_nx_open(struct apfs_nx *nx, const struct apfs_dev *dev)
+{
+ uint8_t *block0;
+ const uint8_t *blk;
+ uint32_t bs, i, desc_blocks;
+ uint64_t desc_base;
+ apfs_xid_t best_xid = 0;
+ uint64_t best_addr = 0;
+ int error;
+
+ memset(nx, 0, sizeof(*nx));
+ nx->dev = *dev;
+ for (i = 0; i < APFS_CACHE_BLOCKS; i++) {
+ nx->cache[i].addr = APFS_BUF_EMPTY;
+ }
+
+ /*
+ * Block zero holds a container superblock, but it can be behind: the live one is
+ * whichever copy in the checkpoint descriptor area has the largest transaction
+ * identifier. Block zero is read only to find that area.
+ */
+ block0 = apfs_alloc(APFS_NX_MINIMUM_BLOCK_SIZE);
+ if (block0 == NULL) {
+ return ENOMEM;
+ }
+ error = nx->dev.read(nx->dev.ctx, 0, block0, APFS_NX_MINIMUM_BLOCK_SIZE);
+ if (error) {
+ goto out;
+ }
+ error = EINVAL;
+ if (le32(block0 + 32) != APFS_NX_MAGIC) {
+ goto out; /* not an APFS container; let the caller try something else */
+ }
+ bs = le32(block0 + 36);
+ if (bs < APFS_NX_MINIMUM_BLOCK_SIZE || bs > APFS_NX_MAXIMUM_BLOCK_SIZE ||
+ (bs & (bs - 1)) != 0) {
+ apfs_log("block size %u makes no sense\n", bs);
+ goto out;
+ }
+ nx->block_size = bs;
+ nx->block_count = le64(block0 + 40);
+ if (nx->block_count < 16) {
+ goto out;
+ }
+ if (nx->dev.size != 0 && nx->block_count * (uint64_t)bs > nx->dev.size) {
+ apfs_log("container claims %llu blocks, the device holds %llu bytes\n",
+ (unsigned long long)nx->block_count, (unsigned long long)nx->dev.size);
+ goto out;
+ }
+ desc_blocks = le32(block0 + 104);
+ desc_base = le64(block0 + 112);
+ error = EIO;
+ if (desc_base == 0 || desc_blocks == 0 || desc_blocks > nx->block_count ||
+ desc_base >= nx->block_count ||
+ desc_base + desc_blocks > nx->block_count) {
+ apfs_log("the checkpoint descriptor area is not inside the container\n");
+ goto out;
+ }
+
+ for (i = 0; i < desc_blocks; i++) {
+ /*
+ * Most of the descriptor area is free or holds older checkpoints, so a block
+ * that fails its checksum here is ordinary and is passed over without a word.
+ */
+ if (nx_block(nx, desc_base + i, &blk, false) != 0) {
+ continue;
+ }
+ if (!apfs_checksum_ok(blk, nx->block_size)) {
+ continue;
+ }
+ if (obj_type(blk) != APFS_OBJECT_TYPE_NX_SUPERBLOCK ||
+ le32(blk + 32) != APFS_NX_MAGIC || le64(blk + 8) != APFS_OID_NX_SUPERBLOCK) {
+ continue;
+ }
+ if (obj_xid(blk) > best_xid) {
+ best_xid = obj_xid(blk);
+ best_addr = desc_base + i;
+ }
+ }
+ if (best_addr == 0) {
+ apfs_log("no usable container superblock in the checkpoint area\n");
+ goto out;
+ }
+ error = nx_block(nx, best_addr, &blk, true);
+ if (error) {
+ goto out;
+ }
+ nx->xid = obj_xid(blk);
+ nx->block_count = le64(blk + 40);
+ memcpy(nx->uuid, blk + 72, sizeof(nx->uuid));
+ nx->omap_addr = le64(blk + 160);
+ {
+ uint32_t maxfs = le32(blk + 180);
+
+ if (maxfs > APFS_NX_MAX_FILE_SYSTEMS) {
+ maxfs = APFS_NX_MAX_FILE_SYSTEMS;
+ }
+ nx->fs_count = 0;
+ for (i = 0; i < maxfs; i++) {
+ uint64_t oid = le64(blk + 184 + 8 * i);
+
+ nx->fs_oid[i] = oid;
+ if (oid != 0) {
+ nx->fs_count = i + 1;
+ }
+ }
+ }
+ error = omap_open(nx, nx->omap_addr, &nx->omap);
+ if (error) {
+ goto out;
+ }
+ error = 0;
+out:
+ apfs_free(block0, APFS_NX_MINIMUM_BLOCK_SIZE);
+ if (error) {
+ apfs_nx_close(nx);
+ }
+ return error;
+}
+
+void
+apfs_nx_close(struct apfs_nx *nx)
+{
+ uint32_t i;
+
+ for (i = 0; i < APFS_CACHE_BLOCKS; i++) {
+ if (nx->cache[i].data != NULL) {
+ apfs_free(nx->cache[i].data, nx->block_size);
+ nx->cache[i].data = NULL;
+ }
+ nx->cache[i].addr = APFS_BUF_EMPTY;
+ }
+}
+
+int
+apfs_vol_open(struct apfs_nx *nx, uint32_t index, struct apfs_vol *vol)
+{
+ const uint8_t *blk;
+ uint64_t addr, omap_oid, root_oid;
+ int error;
+
+ if (index >= APFS_NX_MAX_FILE_SYSTEMS || nx->fs_oid[index] == 0) {
+ return ENOENT;
+ }
+ memset(vol, 0, sizeof(*vol));
+ vol->nx = nx;
+ vol->index = index;
+ vol->oid = nx->fs_oid[index];
+ error = omap_find(&nx->omap, vol->oid, nx->xid, &addr);
+ if (error) {
+ return error;
+ }
+ error = nx_block(nx, addr, &blk, true);
+ if (error) {
+ return error;
+ }
+ if (obj_type(blk) != APFS_OBJECT_TYPE_FS || le32(blk + 32) != APFS_MAGIC_VOL) {
+ apfs_log("volume %u: block %llu is not a volume superblock\n", index,
+ (unsigned long long)addr);
+ return EIO;
+ }
+ vol->incompat = le64(blk + 56);
+ vol->alloc_count = le64(blk + 88);
+ omap_oid = le64(blk + 128);
+ root_oid = le64(blk + 136);
+ vol->num_files = le64(blk + 184);
+ vol->num_dirs = le64(blk + 192);
+ vol->num_symlinks = le64(blk + 200);
+ vol->fs_flags = le64(blk + 264);
+ memcpy(vol->name, blk + 704, APFS_VOLNAME_LEN);
+ vol->name[APFS_VOLNAME_LEN - 1] = '\0';
+ vol->role = le16(blk + 964);
+ vol->hashed_names = (vol->incompat & (APFS_INCOMPAT_CASE_INSENSITIVE |
+ APFS_INCOMPAT_NORMALIZATION_INSENSITIVE)) != 0;
+
+ if (vol->incompat & ~(uint64_t)(APFS_INCOMPAT_CASE_INSENSITIVE |
+ APFS_INCOMPAT_NORMALIZATION_INSENSITIVE | APFS_INCOMPAT_SEALED_VOLUME |
+ APFS_INCOMPAT_DATALESS_SNAPS)) {
+ apfs_log("volume %u: incompatible features 0x%llx are not understood\n",
+ index, (unsigned long long)vol->incompat);
+ return ENOTSUP;
+ }
+ if ((vol->fs_flags & APFS_FS_UNENCRYPTED) == 0) {
+ apfs_log("volume %u (%s) is encrypted\n", index, vol->name);
+ return ENOTSUP;
+ }
+ /* the volume's own map resolves the nodes of its file-system tree */
+ error = omap_open(nx, omap_oid, &vol->omap);
+ if (error) {
+ return error;
+ }
+ return btree_open(nx, &vol->omap, root_oid, &vol->tree);
+}
+
+/* ------------------------------------------------------------------ records */
+
+int
+apfs_seek(struct apfs_btree *tree, uint64_t obj_id, uint8_t type,
+ struct apfs_cursor *cur)
+{
+ const uint8_t *blk;
+ struct node n;
+ uint64_t node_oid = tree->root;
+ int error;
+
+ memset(cur, 0, sizeof(*cur));
+ cur->tree = tree;
+ error = nx_block(tree->nx, node_oid, &blk, true);
+ if (error) {
+ return error;
+ }
+ error = node_parse(tree, blk, &n);
+ if (error) {
+ return error;
+ }
+ cur->depth = 0;
+ for (;;) {
+ uint32_t i, pick = 0;
+
+ if (cur->depth >= APFS_MAX_LEVELS) {
+ return EIO;
+ }
+ cur->node[cur->depth] = node_oid;
+ if (n.nkeys == 0) {
+ cur->done = true;
+ return 0;
+ }
+ if (n.leaf) {
+ /* the first record at or after (obj_id, type) */
+ for (i = 0; i < n.nkeys; i++) {
+ const uint8_t *k, *v;
+ uint16_t kl, vl;
+
+ error = node_entry(tree, &n, i, &k, &kl, &v, &vl);
+ if (error) {
+ return error;
+ }
+ if (kl < 8) {
+ return EIO;
+ }
+ if (jkey_id(k) > obj_id ||
+ (jkey_id(k) == obj_id && jkey_type(k) >= type)) {
+ break;
+ }
+ }
+ cur->index[cur->depth] = i;
+ return 0;
+ }
+ /*
+ * The last child that starts before what we want. A child's key is the
+ * smallest key in it, so going left on a tie cannot skip a record: the walk
+ * forward will reach it.
+ */
+ for (i = 0; i < n.nkeys; i++) {
+ const uint8_t *k, *v;
+ uint16_t kl, vl;
+
+ error = node_entry(tree, &n, i, &k, &kl, &v, &vl);
+ if (error) {
+ return error;
+ }
+ if (kl < 8) {
+ return EIO;
+ }
+ if (jkey_id(k) < obj_id ||
+ (jkey_id(k) == obj_id && jkey_type(k) < type)) {
+ pick = i;
+ } else {
+ break;
+ }
+ }
+ cur->index[cur->depth] = pick;
+ error = node_child(tree, &n, pick, &node_oid);
+ if (error) {
+ return error;
+ }
+ cur->depth++;
+ error = tree_node(tree, node_oid, &blk, &n);
+ if (error) {
+ return error;
+ }
+ }
+}
+
+/*
+ * The record the cursor is on, then step past it. The pointers in `rec` point into a
+ * cached block and stay good only until the next call that touches this container.
+ */
+int
+apfs_cursor_next(struct apfs_cursor *cur, struct apfs_rec *rec)
+{
+ struct apfs_btree *tree = cur->tree;
+ const uint8_t *blk;
+ struct node n;
+ int error;
+
+ if (cur->done) {
+ return ENOENT;
+ }
+ for (;;) {
+ error = tree_node(tree, cur->node[cur->depth], &blk, &n);
+ if (error) {
+ return error;
+ }
+ if (!n.leaf) {
+ return EIO;
+ }
+ if (cur->index[cur->depth] < n.nkeys) {
+ const uint8_t *k, *v;
+ uint16_t kl, vl;
+
+ error = node_entry(tree, &n, cur->index[cur->depth], &k, &kl, &v, &vl);
+ if (error) {
+ return error;
+ }
+ if (kl < 8) {
+ return EIO;
+ }
+ cur->index[cur->depth]++;
+ rec->key = k;
+ rec->key_len = kl;
+ rec->val = v;
+ rec->val_len = vl;
+ rec->obj_id = jkey_id(k);
+ rec->type = jkey_type(k);
+ return 0;
+ }
+ /* this leaf is done: step the path to the next one */
+ for (;;) {
+ if (cur->depth == 0) {
+ cur->done = true;
+ return ENOENT;
+ }
+ cur->depth--;
+ error = tree_node(tree, cur->node[cur->depth], &blk, &n);
+ if (error) {
+ return error;
+ }
+ if (n.leaf) {
+ return EIO;
+ }
+ cur->index[cur->depth]++;
+ if (cur->index[cur->depth] < n.nkeys) {
+ break;
+ }
+ }
+ /* and down the left edge of the subtree we just moved into */
+ for (;;) {
+ uint64_t child;
+
+ error = node_child(tree, &n, cur->index[cur->depth], &child);
+ if (error) {
+ return error;
+ }
+ if (cur->depth + 1 >= APFS_MAX_LEVELS) {
+ return EIO;
+ }
+ cur->depth++;
+ cur->node[cur->depth] = child;
+ cur->index[cur->depth] = 0;
+ error = tree_node(tree, child, &blk, &n);
+ if (error) {
+ return error;
+ }
+ if (n.leaf) {
+ break;
+ }
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ inodes */
+
+/*
+ * Walk the extended fields at the tail of an inode record. The blob is a count and a
+ * used-byte total, then that many descriptors, then the values, each padded out to a
+ * multiple of eight bytes.
+ */
+static int
+xfields_find(const uint8_t *buf, uint16_t len, uint8_t want, const uint8_t **out,
+ uint16_t *out_len)
+{
+ uint16_t num, i, off;
+
+ *out = NULL;
+ *out_len = 0;
+ if (len < 4) {
+ return ENOENT;
+ }
+ num = le16(buf);
+ if ((uint32_t)4 + 4 * (uint32_t)num > len) {
+ return EIO;
+ }
+ off = (uint16_t)(4 + 4 * num);
+ for (i = 0; i < num; i++) {
+ uint8_t xtype = buf[4 + 4 * i];
+ uint16_t xsize = le16(buf + 4 + 4 * i + 2);
+ uint32_t pad = ((uint32_t)xsize + 7u) & ~7u;
+
+ if ((uint32_t)off + xsize > len) {
+ return EIO;
+ }
+ if (xtype == want) {
+ *out = buf + off;
+ *out_len = xsize;
+ return 0;
+ }
+ if ((uint32_t)off + pad > len) {
+ return ENOENT; /* the last field, padding cut short */
+ }
+ off = (uint16_t)(off + pad);
+ }
+ return ENOENT;
+}
+
+int
+apfs_inode_get(struct apfs_vol *vol, uint64_t obj_id, struct apfs_inode *ino)
+{
+ struct apfs_cursor cur;
+ struct apfs_rec rec;
+ const uint8_t *xf;
+ uint16_t xf_len;
+ int error;
+
+ memset(ino, 0, sizeof(*ino));
+ error = apfs_seek(&vol->tree, obj_id, APFS_TYPE_INODE, &cur);
+ if (error) {
+ return error;
+ }
+ error = apfs_cursor_next(&cur, &rec);
+ if (error) {
+ return error;
+ }
+ if (rec.obj_id != obj_id || rec.type != APFS_TYPE_INODE) {
+ return ENOENT;
+ }
+ if (rec.val == NULL || rec.val_len < 92) {
+ return EIO;
+ }
+ ino->obj_id = obj_id;
+ ino->parent_id = le64(rec.val);
+ ino->private_id = le64(rec.val + 8);
+ ino->create_time = le64(rec.val + 16);
+ ino->mod_time = le64(rec.val + 24);
+ ino->change_time = le64(rec.val + 32);
+ ino->access_time = le64(rec.val + 40);
+ ino->internal_flags = le64(rec.val + 48);
+ ino->nchildren = (int32_t)le32(rec.val + 56);
+ ino->bsd_flags = le32(rec.val + 68);
+ ino->owner = le32(rec.val + 72);
+ ino->group = le32(rec.val + 76);
+ ino->mode = le16(rec.val + 80);
+ ino->is_sparse = (ino->internal_flags & APFS_INODE_IS_SPARSE) != 0;
+
+ /* the size of the contents is in an extended field, not in the fixed part */
+ xf = rec.val + 92;
+ xf_len = (uint16_t)(rec.val_len - 92);
+ if (xfields_find(xf, xf_len, APFS_INO_EXT_TYPE_DSTREAM, &xf, &xf_len) == 0 &&
+ xf_len >= 16) {
+ ino->size = le64(xf);
+ ino->alloced_size = le64(xf + 8);
+ ino->has_dstream = true;
+ }
+ xf = rec.val + 92;
+ xf_len = (uint16_t)(rec.val_len - 92);
+ if (xfields_find(xf, xf_len, APFS_INO_EXT_TYPE_RDEV, &xf, &xf_len) == 0 &&
+ xf_len >= 4) {
+ ino->rdev = le32(xf);
+ }
+ return 0;
+}
+
+int
+apfs_inode_size(struct apfs_vol *vol, const struct apfs_inode *ino, uint64_t *size)
+{
+ struct apfs_cfile cf;
+ int error;
+
+ if ((ino->mode & APFS_S_IFMT) == APFS_S_IFLNK) {
+ char target[1024];
+ size_t n = 0;
+
+ error = apfs_readlink(vol, ino->obj_id, target, sizeof(target), &n);
+ if (error) {
+ return error;
+ }
+ *size = n;
+ return 0;
+ }
+ error = apfs_cfile_init(vol, ino, &cf);
+ if (error) {
+ return error;
+ }
+ *size = cf.compressed ? cf.size : ino->size;
+ return 0;
+}
+
+/* ------------------------------------------------------------------ directories */
+
+int
+apfs_readdir(struct apfs_vol *vol, uint64_t dir_id, apfs_dir_cb cb, void *ctx)
+{
+ struct apfs_cursor cur;
+ struct apfs_rec rec;
+ int error;
+
+ error = apfs_seek(&vol->tree, dir_id, APFS_TYPE_DIR_REC, &cur);
+ if (error) {
+ return error;
+ }
+ for (;;) {
+ char name[256];
+ uint32_t name_len;
+ uint64_t file_id;
+ uint8_t d_type;
+
+ error = apfs_cursor_next(&cur, &rec);
+ if (error == ENOENT) {
+ return 0;
+ }
+ if (error) {
+ return error;
+ }
+ if (rec.obj_id != dir_id || rec.type != APFS_TYPE_DIR_REC) {
+ return 0;
+ }
+ /*
+ * iOS uses the hashed key: a word holding the name's length and a hash of it,
+ * then the name. The plain key has a 16-bit length instead; both are handled
+ * so that a volume made elsewhere still reads.
+ */
+ if (vol->hashed_names) {
+ if (rec.key_len < 12) {
+ return EIO;
+ }
+ name_len = le32(rec.key + 8) & APFS_J_DREC_LEN_MASK;
+ if (name_len == 0 || 12 + name_len > rec.key_len) {
+ return EIO;
+ }
+ if (name_len > sizeof(name)) {
+ return EIO;
+ }
+ memcpy(name, rec.key + 12, name_len);
+ } else {
+ if (rec.key_len < 10) {
+ return EIO;
+ }
+ name_len = le16(rec.key + 8);
+ if (name_len == 0 || 10 + name_len > rec.key_len) {
+ return EIO;
+ }
+ if (name_len > sizeof(name)) {
+ return EIO;
+ }
+ memcpy(name, rec.key + 10, name_len);
+ }
+ name_len--; /* the stored length counts the zero byte */
+ name[name_len] = '\0';
+ if (rec.val == NULL || rec.val_len < 18) {
+ return EIO;
+ }
+ file_id = le64(rec.val);
+ d_type = (uint8_t)(le16(rec.val + 16) & APFS_DREC_TYPE_MASK);
+ error = cb(ctx, name, name_len, file_id, d_type);
+ if (error) {
+ return error;
+ }
+ }
+}
+
+struct lookup_ctx {
+ const char *name;
+ size_t name_len;
+ bool fold;
+ uint64_t file_id;
+ uint8_t d_type;
+ bool found;
+};
+
+static int
+ascii_lower(int c)
+{
+ return (c >= 'A' && c <= 'Z') ? c + ('a' - 'A') : c;
+}
+
+static int
+lookup_cb(void *ctx, const char *name, size_t name_len, uint64_t file_id, uint8_t d_type)
+{
+ struct lookup_ctx *lc = ctx;
+ size_t i;
+
+ if (name_len != lc->name_len) {
+ return 0;
+ }
+ for (i = 0; i < name_len; i++) {
+ int a = (unsigned char)name[i], b = (unsigned char)lc->name[i];
+
+ if (lc->fold) {
+ a = ascii_lower(a);
+ b = ascii_lower(b);
+ }
+ if (a != b) {
+ return 0;
+ }
+ }
+ lc->file_id = file_id;
+ lc->d_type = d_type;
+ lc->found = true;
+ return EEXIST; /* stop the walk; not an error */
+}
+
+int
+apfs_lookup(struct apfs_vol *vol, uint64_t dir_id, const char *name, size_t name_len,
+ uint64_t *file_id, uint8_t *d_type)
+{
+ struct lookup_ctx lc;
+ int error;
+
+ memset(&lc, 0, sizeof(lc));
+ lc.name = name;
+ lc.name_len = name_len;
+ lc.fold = (vol->incompat & APFS_INCOMPAT_CASE_INSENSITIVE) != 0;
+ error = apfs_readdir(vol, dir_id, lookup_cb, &lc);
+ if (error && error != EEXIST) {
+ return error;
+ }
+ if (!lc.found) {
+ return ENOENT;
+ }
+ if (file_id != NULL) {
+ *file_id = lc.file_id;
+ }
+ if (d_type != NULL) {
+ *d_type = lc.d_type;
+ }
+ return 0;
+}
+
+int
+apfs_path_lookup(struct apfs_vol *vol, const char *path, uint64_t *file_id,
+ uint8_t *d_type)
+{
+ uint64_t id = APFS_ROOT_DIR_INO_NUM;
+ uint8_t dt = APFS_DT_DIR;
+ const char *p = path;
+
+ while (*p != '\0') {
+ const char *s;
+ size_t n;
+ int error;
+
+ while (*p == '/') {
+ p++;
+ }
+ if (*p == '\0') {
+ break;
+ }
+ s = p;
+ while (*p != '\0' && *p != '/') {
+ p++;
+ }
+ n = (size_t)(p - s);
+ if (n == 1 && s[0] == '.') {
+ continue;
+ }
+ if (dt != APFS_DT_DIR) {
+ return ENOTDIR;
+ }
+ error = apfs_lookup(vol, id, s, n, &id, &dt);
+ if (error) {
+ return error;
+ }
+ }
+ if (file_id != NULL) {
+ *file_id = id;
+ }
+ if (d_type != NULL) {
+ *d_type = dt;
+ }
+ return 0;
+}
+
+/* ------------------------------------------------------------------ attributes */
+
+static int
+xattr_parse(const struct apfs_rec *rec, struct apfs_xattr *xa)
+{
+ uint16_t xdata_len;
+
+ if (rec->val == NULL || rec->val_len < 4) {
+ return EIO;
+ }
+ memset(xa, 0, sizeof(*xa));
+ xa->flags = le16(rec->val);
+ xdata_len = le16(rec->val + 2);
+ if ((uint32_t)4 + xdata_len > rec->val_len) {
+ return EIO;
+ }
+ xa->data = rec->val + 4;
+ xa->data_len = xdata_len;
+ if (xa->flags & APFS_XATTR_DATA_STREAM) {
+ if (xdata_len < 16) {
+ return EIO;
+ }
+ xa->stream_id = le64(xa->data);
+ xa->stream_size = le64(xa->data + 8);
+ }
+ return 0;
+}
+
+int
+apfs_xattr_list(struct apfs_vol *vol, uint64_t obj_id, apfs_xattr_cb cb, void *ctx)
+{
+ struct apfs_cursor cur;
+ struct apfs_rec rec;
+ int error;
+
+ error = apfs_seek(&vol->tree, obj_id, APFS_TYPE_XATTR, &cur);
+ if (error) {
+ return error;
+ }
+ for (;;) {
+ char name[256];
+ uint32_t name_len;
+ struct apfs_xattr xa;
+
+ error = apfs_cursor_next(&cur, &rec);
+ if (error == ENOENT) {
+ return 0;
+ }
+ if (error) {
+ return error;
+ }
+ if (rec.obj_id != obj_id || rec.type != APFS_TYPE_XATTR) {
+ return 0;
+ }
+ if (rec.key_len < 10) {
+ return EIO;
+ }
+ name_len = le16(rec.key + 8);
+ if (name_len == 0 || name_len > sizeof(name) || 10 + name_len > rec.key_len) {
+ return EIO;
+ }
+ memcpy(name, rec.key + 10, name_len);
+ name_len--;
+ name[name_len] = '\0';
+ error = xattr_parse(&rec, &xa);
+ if (error) {
+ return error;
+ }
+ error = cb(ctx, name, name_len, &xa);
+ if (error) {
+ return error;
+ }
+ }
+}
+
+struct xattr_find_ctx {
+ const char *want;
+ size_t want_len;
+ uint8_t *buf; /* NULL when only the metadata is wanted */
+ size_t len;
+ size_t copied;
+ uint16_t flags;
+ uint16_t data_len;
+ uint64_t stream_id;
+ uint64_t stream_size;
+ bool found;
+};
+
+static int
+xattr_find_cb(void *ctx, const char *name, size_t name_len, const struct apfs_xattr *xa)
+{
+ struct xattr_find_ctx *fc = ctx;
+
+ if (name_len != fc->want_len || memcmp(name, fc->want, name_len) != 0) {
+ return 0;
+ }
+ fc->found = true;
+ fc->flags = xa->flags;
+ fc->data_len = xa->data_len;
+ fc->stream_id = xa->stream_id;
+ fc->stream_size = xa->stream_size;
+ /* an embedded value is copied now, while the record is still in a cached block */
+ if ((xa->flags & APFS_XATTR_DATA_EMBEDDED) && fc->buf != NULL) {
+ size_t n = xa->data_len < fc->len ? xa->data_len : fc->len;
+
+ memcpy(fc->buf, xa->data, n);
+ fc->copied = n;
+ }
+ return EEXIST; /* stop the walk; not a failure */
+}
+
+static int
+xattr_find(struct apfs_vol *vol, uint64_t obj_id, const char *name,
+ struct xattr_find_ctx *fc)
+{
+ int error;
+
+ fc->want = name;
+ fc->want_len = strlen(name);
+ error = apfs_xattr_list(vol, obj_id, xattr_find_cb, fc);
+ if (error == EEXIST) {
+ error = 0;
+ }
+ if (error == 0 && !fc->found) {
+ error = ENOENT;
+ }
+ return error;
+}
+
+int
+apfs_xattr_lookup(struct apfs_vol *vol, uint64_t obj_id, const char *name,
+ struct apfs_xattr *xa)
+{
+ struct xattr_find_ctx fc;
+ int error;
+
+ memset(&fc, 0, sizeof(fc));
+ error = xattr_find(vol, obj_id, name, &fc);
+ if (error) {
+ return error;
+ }
+ memset(xa, 0, sizeof(*xa));
+ xa->flags = fc.flags;
+ xa->data = NULL;
+ xa->data_len = fc.data_len;
+ xa->stream_id = fc.stream_id;
+ xa->stream_size = fc.stream_size;
+ return 0;
+}
+
+int
+apfs_xattr_read(struct apfs_vol *vol, uint64_t obj_id, const char *name, void *buf,
+ size_t len, size_t *out)
+{
+ struct xattr_find_ctx fc;
+ int error;
+
+ *out = 0;
+ memset(&fc, 0, sizeof(fc));
+ fc.buf = buf;
+ fc.len = len;
+ error = xattr_find(vol, obj_id, name, &fc);
+ if (error) {
+ return error;
+ }
+ if (fc.flags & APFS_XATTR_DATA_EMBEDDED) {
+ *out = fc.copied;
+ return 0;
+ }
+ if (fc.flags & APFS_XATTR_DATA_STREAM) {
+ return apfs_read_stream(vol, fc.stream_id, fc.stream_size, 0, buf, len, out);
+ }
+ return EIO;
+}
+
+/* ------------------------------------------------------------------ contents */
+
+int
+apfs_read_stream(struct apfs_vol *vol, uint64_t stream_id, uint64_t stream_size,
+ uint64_t off, void *buf, size_t len, size_t *out)
+{
+ struct apfs_cursor cur;
+ struct apfs_rec rec;
+ uint8_t *dst = buf;
+ uint32_t bs = vol->nx->block_size;
+ uint64_t end;
+ int error;
+
+ *out = 0;
+ if (off >= stream_size) {
+ return 0;
+ }
+ if (len > stream_size - off) {
+ len = (size_t)(stream_size - off);
+ }
+ end = off + len;
+ /* holes read as zeros, so start from zeros and fill in what the extents cover */
+ memset(dst, 0, len);
+
+ error = apfs_seek(&vol->tree, stream_id, APFS_TYPE_FILE_EXTENT, &cur);
+ if (error) {
+ return error;
+ }
+ for (;;) {
+ uint64_t logical, length, phys;
+
+ error = apfs_cursor_next(&cur, &rec);
+ if (error == ENOENT) {
+ break;
+ }
+ if (error) {
+ return error;
+ }
+ if (rec.obj_id != stream_id || rec.type != APFS_TYPE_FILE_EXTENT) {
+ break;
+ }
+ if (rec.key_len < 16 || rec.val == NULL || rec.val_len < 24) {
+ return EIO;
+ }
+ logical = le64(rec.key + 8);
+ length = le64(rec.val) & APFS_J_FILE_EXTENT_LEN_MASK;
+ phys = le64(rec.val + 8);
+ if (length == 0 || (length % bs) != 0) {
+ return EIO;
+ }
+ if (logical >= end) {
+ break; /* extents are in order: past what we need */
+ }
+ if (logical + length <= off || phys == 0) {
+ continue; /* before what we need, or a hole */
+ }
+ if (phys >= vol->nx->block_count ||
+ length / bs > vol->nx->block_count - phys) {
+ return EIO;
+ }
+ /* the overlap of [logical, logical+length) with [off, end) */
+ {
+ uint64_t from = logical > off ? logical : off;
+ uint64_t to = (logical + length) < end ? (logical + length) : end;
+ uint64_t inner = from - logical;
+ uint64_t nbytes = to - from;
+ uint64_t addr = phys + inner / bs;
+ uint64_t skew = inner % bs;
+
+ while (nbytes > 0) {
+ const uint8_t *blk;
+ uint64_t n = bs - skew;
+
+ if (n > nbytes) {
+ n = nbytes;
+ }
+ /* file data has no object header and so no checksum */
+ error = nx_block(vol->nx, addr, &blk, false);
+ if (error) {
+ return error;
+ }
+ memcpy(dst + (from - off), blk + skew, (size_t)n);
+ from += n;
+ nbytes -= n;
+ addr++;
+ skew = 0;
+ }
+ }
+ }
+ *out = len;
+ return 0;
+}
+
+int
+apfs_readlink(struct apfs_vol *vol, uint64_t obj_id, char *buf, size_t len, size_t *out)
+{
+ size_t n = 0;
+ int error = apfs_xattr_read(vol, obj_id, APFS_SYMLINK_EA_NAME, buf, len, &n);
+
+ if (error) {
+ return error;
+ }
+ /* the stored target ends with a zero byte that is not part of the name */
+ while (n > 0 && buf[n - 1] == '\0') {
+ n--;
+ }
+ *out = n;
+ return 0;
+}
+
+int
+apfs_cfile_init(struct apfs_vol *vol, const struct apfs_inode *ino,
+ struct apfs_cfile *cf)
+{
+ uint8_t hdr[16];
+ size_t n = 0;
+ int error;
+
+ memset(cf, 0, sizeof(*cf));
+ error = apfs_xattr_read(vol, ino->obj_id, APFS_DECMPFS_XATTR_NAME, hdr, sizeof(hdr),
+ &n);
+ if (error == ENOENT) {
+ return 0; /* not compressed */
+ }
+ if (error) {
+ return error;
+ }
+ if (n < sizeof(hdr) || le32(hdr) != APFS_DECMPFS_MAGIC) {
+ return 0;
+ }
+ cf->compressed = true;
+ cf->type = le32(hdr + 4);
+ cf->size = le64(hdr + 8);
+ switch (cf->type) {
+ case APFS_DECMPFS_TYPE_ZLIB_ATTR:
+ case APFS_DECMPFS_TYPE_RAW_ATTR:
+ cf->in_rsrc = false;
+ return 0;
+ case APFS_DECMPFS_TYPE_ZLIB_RSRC:
+ case APFS_DECMPFS_TYPE_RAW_RSRC:
+ cf->in_rsrc = true;
+ return 0;
+ default:
+ apfs_log("inode %llu: decmpfs type %u is not supported\n",
+ (unsigned long long)ino->obj_id, cf->type);
+ return ENOTSUP;
+ }
+}
+
+/* One zlib stream. A leading 0xff means the piece was stored rather than compressed. */
+static int
+apfs_inflate(const uint8_t *src, size_t src_len, uint8_t *dst, size_t dst_len,
+ size_t *out)
+{
+ z_stream zs;
+ int zerr;
+
+ if (src_len == 0) {
+ return EIO;
+ }
+ if (src[0] == 0xFF) {
+ size_t n = src_len - 1;
+
+ if (n > dst_len) {
+ n = dst_len;
+ }
+ memcpy(dst, src + 1, n);
+ *out = n;
+ return 0;
+ }
+ memset(&zs, 0, sizeof(zs));
+ zs.next_in = (Bytef *)(uintptr_t)src;
+ zs.avail_in = (uInt)src_len;
+ zs.next_out = (Bytef *)dst;
+ zs.avail_out = (uInt)dst_len;
+ if (inflateInit(&zs) != Z_OK) {
+ return ENOMEM;
+ }
+ zerr = inflate(&zs, Z_FINISH);
+ *out = (size_t)zs.total_out;
+ inflateEnd(&zs);
+ if (zerr != Z_STREAM_END && zerr != Z_OK && zerr != Z_BUF_ERROR) {
+ return EIO;
+ }
+ return 0;
+}
+
+/*
+ * A compressed file whose bytes are in the attribute: the whole thing is there, after the
+ * header, with one marker byte in front when it was stored rather than compressed.
+ */
+static int
+read_cfile_attr(struct apfs_vol *vol, const struct apfs_inode *ino,
+ const struct apfs_cfile *cf, uint64_t off, uint8_t *buf, size_t len, size_t *out)
+{
+ struct apfs_xattr xa;
+ uint8_t *attr = NULL;
+ uint8_t *plain = NULL;
+ size_t attr_len = 0, plain_len = 0;
+ size_t alloc = APFS_XATTR_MAX_EMBEDDED_SIZE + 16;
+ int error;
+
+ *out = 0;
+ error = apfs_xattr_lookup(vol, ino->obj_id, APFS_DECMPFS_XATTR_NAME, &xa);
+ if (error) {
+ return error;
+ }
+ if (xa.flags & APFS_XATTR_DATA_STREAM) {
+ if (xa.stream_size > 64u * 1024u * 1024u) {
+ return EIO;
+ }
+ alloc = (size_t)xa.stream_size;
+ }
+ attr = apfs_alloc(alloc);
+ if (attr == NULL) {
+ return ENOMEM;
+ }
+ error = apfs_xattr_read(vol, ino->obj_id, APFS_DECMPFS_XATTR_NAME, attr, alloc,
+ &attr_len);
+ if (error) {
+ goto out;
+ }
+ if (attr_len < 16) {
+ error = EIO;
+ goto out;
+ }
+ if (cf->size > 64u * 1024u * 1024u) {
+ error = EIO;
+ goto out;
+ }
+ plain = apfs_alloc((size_t)cf->size ? (size_t)cf->size : 1);
+ if (plain == NULL) {
+ error = ENOMEM;
+ goto out;
+ }
+ if (cf->type == APFS_DECMPFS_TYPE_RAW_ATTR) {
+ const uint8_t *p = attr + 16;
+ size_t n = attr_len - 16;
+
+ /*
+ * Stored as it is. Every type-9 file in the iOS 16.5 root file system has one
+ * marker byte in front of the contents; a payload that is already exactly the
+ * right length is taken whole.
+ */
+ if (n != cf->size) {
+ if (n == 0) {
+ error = EIO;
+ goto out;
+ }
+ p++;
+ n--;
+ }
+ if (n > cf->size) {
+ n = (size_t)cf->size;
+ }
+ memcpy(plain, p, n);
+ plain_len = n;
+ } else {
+ error = apfs_inflate(attr + 16, attr_len - 16, plain, (size_t)cf->size,
+ &plain_len);
+ if (error) {
+ goto out;
+ }
+ }
+ if (off < plain_len) {
+ size_t n = plain_len - (size_t)off;
+
+ if (n > len) {
+ n = len;
+ }
+ memcpy(buf, plain + off, n);
+ *out = n;
+ }
+out:
+ if (attr != NULL) {
+ apfs_free(attr, alloc);
+ }
+ if (plain != NULL) {
+ apfs_free(plain, (size_t)cf->size ? (size_t)cf->size : 1);
+ }
+ return error;
+}
+
+/*
+ * A compressed file whose bytes are in com.apple.ResourceFork: the contents cut into
+ * 64 KB pieces, each its own zlib stream. The fork is an HFS-Plus resource fork; the
+ * piece table starts four bytes past the data offset in its big-endian header.
+ */
+static int
+read_cfile_rsrc(struct apfs_vol *vol, const struct apfs_inode *ino,
+ const struct apfs_cfile *cf, uint64_t off, uint8_t *buf, size_t len, size_t *out)
+{
+ struct apfs_xattr xa;
+ uint8_t head[16];
+ uint8_t entry[8];
+ uint8_t *piece = NULL, *plain = NULL;
+ size_t piece_cap = 0, got = 0;
+ uint64_t base, nblocks, first, last, i;
+ int error;
+
+ *out = 0;
+ error = apfs_xattr_lookup(vol, ino->obj_id, APFS_RSRC_FORK_XATTR_NAME, &xa);
+ if (error) {
+ return error;
+ }
+ if ((xa.flags & APFS_XATTR_DATA_STREAM) == 0) {
+ return ENOTSUP; /* a resource fork small enough to be embedded */
+ }
+ error = apfs_read_stream(vol, xa.stream_id, xa.stream_size, 0, head, sizeof(head),
+ &got);
+ if (error) {
+ return error;
+ }
+ if (got < sizeof(head)) {
+ return EIO;
+ }
+ base = (uint64_t)be32(head) + 4; /* data offset, then the big-endian length */
+ if (base + 4 > xa.stream_size) {
+ return EIO;
+ }
+ error = apfs_read_stream(vol, xa.stream_id, xa.stream_size, base, entry, 4, &got);
+ if (error) {
+ return error;
+ }
+ if (got < 4) {
+ return EIO;
+ }
+ nblocks = le32(entry);
+ if (nblocks == 0 || nblocks > (cf->size / APFS_RSRC_PIECE) + 1) {
+ return EIO;
+ }
+ if (off >= cf->size) {
+ return 0;
+ }
+ if (len > cf->size - off) {
+ len = (size_t)(cf->size - off);
+ }
+ first = off / APFS_RSRC_PIECE;
+ last = (off + len - 1) / APFS_RSRC_PIECE;
+ if (last >= nblocks) {
+ return EIO;
+ }
+ plain = apfs_alloc(APFS_RSRC_PIECE);
+ if (plain == NULL) {
+ return ENOMEM;
+ }
+ for (i = first; i <= last; i++) {
+ uint64_t ent_off = base + 4 + 8 * i;
+ uint64_t poff, plen;
+ size_t want, copied, from_in_piece, n;
+
+ if (ent_off + 8 > xa.stream_size) {
+ error = EIO;
+ goto out;
+ }
+ error = apfs_read_stream(vol, xa.stream_id, xa.stream_size, ent_off, entry, 8,
+ &got);
+ if (error) {
+ goto out;
+ }
+ if (got < 8) {
+ error = EIO;
+ goto out;
+ }
+ poff = le32(entry);
+ plen = le32(entry + 4);
+ if (plen == 0 || base + poff + plen > xa.stream_size) {
+ error = EIO;
+ goto out;
+ }
+ if (plen > piece_cap) {
+ if (piece != NULL) {
+ apfs_free(piece, piece_cap);
+ }
+ piece_cap = (size_t)plen;
+ piece = apfs_alloc(piece_cap);
+ if (piece == NULL) {
+ error = ENOMEM;
+ goto out;
+ }
+ }
+ error = apfs_read_stream(vol, xa.stream_id, xa.stream_size, base + poff, piece,
+ (size_t)plen, &got);
+ if (error) {
+ goto out;
+ }
+ if (got < plen) {
+ error = EIO;
+ goto out;
+ }
+ /* how much of the file this piece stands for */
+ want = APFS_RSRC_PIECE;
+ if ((i + 1) * APFS_RSRC_PIECE > cf->size) {
+ want = (size_t)(cf->size - i * APFS_RSRC_PIECE);
+ }
+ if (cf->type == APFS_DECMPFS_TYPE_RAW_RSRC) {
+ size_t m = plen < want ? (size_t)plen : want;
+
+ memcpy(plain, piece, m);
+ copied = m;
+ } else {
+ error = apfs_inflate(piece, (size_t)plen, plain, want, &copied);
+ if (error) {
+ goto out;
+ }
+ }
+ if (copied != want) {
+ error = EIO;
+ goto out;
+ }
+ /* the overlap of this piece with what was asked for */
+ from_in_piece = (off > i * APFS_RSRC_PIECE)
+ ? (size_t)(off - i * APFS_RSRC_PIECE) : 0;
+ n = copied - from_in_piece;
+ if (n > len - *out) {
+ n = len - *out;
+ }
+ memcpy(buf + *out, plain + from_in_piece, n);
+ *out += n;
+ }
+out:
+ if (piece != NULL) {
+ apfs_free(piece, piece_cap);
+ }
+ apfs_free(plain, APFS_RSRC_PIECE);
+ return error;
+}
+
+int
+apfs_read_file(struct apfs_vol *vol, const struct apfs_inode *ino, uint64_t off,
+ void *buf, size_t len, size_t *out)
+{
+ struct apfs_cfile cf;
+ int error;
+
+ *out = 0;
+ if ((ino->mode & APFS_S_IFMT) == APFS_S_IFLNK) {
+ size_t n = 0;
+
+ error = apfs_readlink(vol, ino->obj_id, buf, len, &n);
+ if (error) {
+ return error;
+ }
+ *out = (off < n) ? n - (size_t)off : 0;
+ if (off > 0 && *out > 0) {
+ memmove(buf, (uint8_t *)buf + off, *out);
+ }
+ return 0;
+ }
+ error = apfs_cfile_init(vol, ino, &cf);
+ if (error) {
+ return error;
+ }
+ if (!cf.compressed) {
+ if (!ino->has_dstream) {
+ return 0;
+ }
+ return apfs_read_stream(vol, ino->private_id, ino->size, off, buf, len, out);
+ }
+ if (cf.in_rsrc) {
+ return read_cfile_rsrc(vol, ino, &cf, off, buf, len, out);
+ }
+ return read_cfile_attr(vol, ino, &cf, off, buf, len, out);
+}
diff --git a/xnu/files/bsd/miscfs/apfs/apfs_lib.h b/xnu/files/bsd/miscfs/apfs/apfs_lib.h
new file mode 100644
index 0000000..9da14c6
--- /dev/null
+++ b/xnu/files/bsd/miscfs/apfs/apfs_lib.h
@@ -0,0 +1,306 @@
+/*
+ * Reading the Apple File System: the part that knows the format and nothing about vnodes.
+ *
+ * The same file is built into the kernel and, by tools/apfs/build-tool.sh, into a program
+ * on the build machine (tools/apfs/apfs-tool.c) that runs it against a real image and
+ * compares the result with tools/apfs/apfs.py, which is itself checked against 7-Zip.
+ * Nothing goes into the kernel that has not agreed with the image on the computer first.
+ *
+ * The layout being read is in apfs_format.h, written from Apple's reference.
+ *
+ * Where the bytes come from is the caller's business (struct apfs_dev): in the kernel a
+ * block device, in the tool a raw image. Every structure is checked before it is used --
+ * a block's Fletcher-64, every offset and length inside a B-tree node, every record's
+ * length against the fields read out of it -- so a damaged or hostile image comes back as
+ * EIO and never as a wild pointer.
+ *
+ * Read only, and nothing here ever writes to the device.
+ *
+ * What is read: unencrypted volumes, sealed or not; the live tree only (no snapshots);
+ * inodes, directories, symbolic links, hard links, extended attributes (embedded and in
+ * their own data stream), file extents and holes, and files the operating system
+ * compressed (decmpfs: zlib and stored, in the attribute or in the resource fork).
+ * What is not: encryption, snapshots, Fusion, and writing of any kind.
+ */
+
+#ifndef _MISCFS_APFS_APFS_LIB_H_
+#define _MISCFS_APFS_APFS_LIB_H_
+
+#include "apfs_format.h"
+
+#ifdef KERNEL
+#include <sys/param.h>
+#include <sys/errno.h>
+#include <sys/systm.h>
+#include <libkern/libkern.h>
+#include <kern/kalloc.h>
+#define apfs_alloc(n) kalloc_data((vm_size_t)(n), Z_WAITOK | Z_ZERO)
+#define apfs_free(p, n) kfree_data((p), (vm_size_t)(n))
+#define apfs_log(...) printf("apfs: " __VA_ARGS__)
+#else
+#include <errno.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#define apfs_alloc(n) calloc(1, (n))
+#define apfs_free(p, n) ((void)(n), free(p))
+#define apfs_log(...) fprintf(stderr, "apfs: " __VA_ARGS__)
+#endif
+
+/* How many blocks of metadata to keep; a B-tree descent touches one per level. */
+#define APFS_CACHE_BLOCKS 64
+
+/*
+ * The device. read() must fill the whole buffer or return an error; offsets and lengths
+ * are always whole blocks of the container.
+ */
+struct apfs_dev {
+ void *ctx;
+ uint64_t size; /* bytes, 0 if not known */
+ int (*read)(void *ctx, uint64_t off, void *buf, size_t len);
+};
+
+/* One cached block of metadata. */
+struct apfs_buf {
+ uint64_t addr; /* block address, APFS_BUF_EMPTY if unused */
+ uint32_t age;
+ uint8_t *data;
+};
+
+#define APFS_BUF_EMPTY ((uint64_t)~0ULL)
+
+/* A B-tree, ready to be walked. */
+struct apfs_btree {
+ struct apfs_nx *nx;
+ struct apfs_omap *omap; /* NULL for a tree whose node ids are block addresses */
+ uint64_t root; /* block address of the root node */
+ uint32_t flags; /* bt_flags out of the root's btree_info */
+ uint32_t key_size; /* nonzero only for fixed-size keys */
+ uint32_t val_size;
+ uint64_t key_count;
+ uint64_t node_count;
+};
+
+/* An object map: it turns an object identifier into a block address. */
+struct apfs_omap {
+ struct apfs_btree tree;
+ bool ready;
+};
+
+/* A mounted container. */
+struct apfs_nx {
+ struct apfs_dev dev;
+ uint32_t block_size;
+ uint64_t block_count;
+ apfs_xid_t xid; /* the checkpoint we are reading */
+ uint64_t omap_addr;
+ apfs_oid_t fs_oid[APFS_NX_MAX_FILE_SYSTEMS];
+ uint32_t fs_count;
+ uint8_t uuid[16];
+ struct apfs_omap omap; /* resolves volume superblocks */
+ struct apfs_buf cache[APFS_CACHE_BLOCKS];
+ uint32_t clock;
+ uint64_t reads;
+ uint64_t hits;
+};
+
+/* A volume inside the container. */
+struct apfs_vol {
+ struct apfs_nx *nx;
+ uint32_t index;
+ apfs_oid_t oid;
+ uint64_t incompat;
+ uint64_t fs_flags;
+ uint16_t role;
+ /*
+ * Whether directory-entry keys carry a hash of the name. Apple's reference
+ * describes both shapes of the key but never says which a volume uses; the hash it
+ * defines (CRC-32C of the name decomposed and widened) is only of use for looking
+ * a name up without regard to case or normalization, and the iOS 16.5 volume, which
+ * is normalization-insensitive, does carry it. So: hashed when either of those two
+ * features is on. A wrong guess does not go unnoticed -- the name length would not
+ * fit the key and the record is refused.
+ */
+ bool hashed_names;
+ uint64_t num_files;
+ uint64_t num_dirs;
+ uint64_t num_symlinks;
+ uint64_t alloc_count;
+ char name[APFS_VOLNAME_LEN];
+ struct apfs_omap omap; /* resolves the nodes of the tree below */
+ struct apfs_btree tree; /* the file-system tree */
+};
+
+/* One record out of a file-system tree: pointers into a cached block. */
+struct apfs_rec {
+ const uint8_t *key;
+ uint16_t key_len;
+ const uint8_t *val;
+ uint16_t val_len;
+ uint64_t obj_id;
+ uint8_t type;
+};
+
+/*
+ * A walk over the records of a tree. It holds one cached block per level, so a cursor
+ * must not outlive the container and only one may be open at a time per container unless
+ * the cache is larger than the tree is deep.
+ */
+#define APFS_MAX_LEVELS 8
+
+struct apfs_cursor {
+ struct apfs_btree *tree;
+ int depth;
+ uint64_t node[APFS_MAX_LEVELS]; /* block address at each level */
+ uint32_t index[APFS_MAX_LEVELS];
+ bool done;
+};
+
+/* What an inode record says, after the extended fields have been picked apart. */
+struct apfs_inode {
+ uint64_t obj_id;
+ uint64_t parent_id;
+ uint64_t private_id; /* the data stream's id, for a regular file */
+ uint64_t create_time;
+ uint64_t mod_time;
+ uint64_t change_time;
+ uint64_t access_time;
+ uint64_t internal_flags;
+ int32_t nchildren; /* a directory: children; otherwise: links */
+ uint32_t bsd_flags;
+ uint32_t owner;
+ uint32_t group;
+ uint16_t mode;
+ uint64_t size; /* the logical size, what stat reports */
+ uint64_t alloced_size;
+ uint32_t rdev;
+ bool has_dstream;
+ bool is_sparse;
+};
+
+/* One extent of a data stream. */
+struct apfs_extent {
+ uint64_t logical;
+ uint64_t length;
+ uint64_t phys; /* 0 is a hole */
+};
+
+/* An extended attribute, as found in its record. */
+struct apfs_xattr {
+ uint16_t flags;
+ const uint8_t *data; /* embedded value, or an apfs_j_xattr_dstream */
+ uint16_t data_len;
+ uint64_t stream_id; /* when the value is in its own stream */
+ uint64_t stream_size;
+};
+
+/* How a file's contents are stored, once the decmpfs attribute has been read. */
+struct apfs_cfile {
+ bool compressed;
+ uint32_t type; /* decmpfs compression type */
+ uint64_t size; /* uncompressed size */
+ bool in_rsrc; /* the bytes are in com.apple.ResourceFork */
+};
+
+/* ---- container and volumes ---- */
+
+int apfs_nx_open(struct apfs_nx *nx, const struct apfs_dev *dev);
+void apfs_nx_close(struct apfs_nx *nx);
+int apfs_vol_open(struct apfs_nx *nx, uint32_t index, struct apfs_vol *vol);
+
+/* ---- records ---- */
+
+/*
+ * Put a cursor on the first record of (obj_id, type), or on the first record after it if
+ * there is none. A file-system tree sorts by object id first and record type second, so
+ * the records of one object and type are a run; apfs_cursor_next() walks it and the
+ * caller stops when obj_id or type changes.
+ */
+int apfs_seek(struct apfs_btree *tree, uint64_t obj_id, uint8_t type,
+ struct apfs_cursor *cur);
+int apfs_cursor_next(struct apfs_cursor *cur, struct apfs_rec *rec);
+
+/* ---- what the records mean ---- */
+
+/*
+ * Read an inode record. ino->size is the size of the data stream, which for a compressed
+ * file or a symbolic link is not the size a reader of the file sees -- those keep their
+ * contents elsewhere. This stays cheap, touching only the one record; use
+ * apfs_inode_size() where the size reported to a caller has to be right.
+ */
+int apfs_inode_get(struct apfs_vol *vol, uint64_t obj_id, struct apfs_inode *ino);
+
+/*
+ * The logical size of a file: the uncompressed size for a compressed one, the length of
+ * the target for a symbolic link, the data stream's size otherwise. Costs an attribute
+ * lookup for anything that is not a plain file.
+ */
+int apfs_inode_size(struct apfs_vol *vol, const struct apfs_inode *ino, uint64_t *size);
+int apfs_lookup(struct apfs_vol *vol, uint64_t dir_id, const char *name, size_t name_len,
+ uint64_t *file_id, uint8_t *d_type);
+int apfs_path_lookup(struct apfs_vol *vol, const char *path, uint64_t *file_id,
+ uint8_t *d_type);
+
+typedef int (*apfs_dir_cb)(void *ctx, const char *name, size_t name_len,
+ uint64_t file_id, uint8_t d_type);
+int apfs_readdir(struct apfs_vol *vol, uint64_t dir_id, apfs_dir_cb cb, void *ctx);
+
+/*
+ * Find an attribute and report where its value is kept. Only the fields that are values
+ * are filled in -- xa->data is always NULL, because a record's bytes live in a cached
+ * block that the next read may reuse. To get at the value, use apfs_xattr_read().
+ */
+int apfs_xattr_lookup(struct apfs_vol *vol, uint64_t obj_id, const char *name,
+ struct apfs_xattr *xa);
+
+/*
+ * The value of one attribute by name, wherever it is kept: copied straight out of the
+ * record while it is still in hand if it is embedded there, read from its data stream if
+ * it has one. *out is how many bytes were put in buf, which is less than the whole value
+ * if buf is too small.
+ */
+int apfs_xattr_read(struct apfs_vol *vol, uint64_t obj_id, const char *name, void *buf,
+ size_t len, size_t *out);
+
+/*
+ * Every attribute of an object. Inside the callback xa->data points at the value if it
+ * is embedded, and is good only until the callback returns; a callback that wants to keep
+ * it copies it. Returning nonzero from the callback ends the walk with that value.
+ */
+typedef int (*apfs_xattr_cb)(void *ctx, const char *name, size_t name_len,
+ const struct apfs_xattr *xa);
+int apfs_xattr_list(struct apfs_vol *vol, uint64_t obj_id, apfs_xattr_cb cb, void *ctx);
+
+/* The target of a symbolic link, without the trailing zero byte. */
+int apfs_readlink(struct apfs_vol *vol, uint64_t obj_id, char *buf, size_t len,
+ size_t *out);
+
+/* ---- file contents ---- */
+
+/*
+ * Raw bytes of a data stream, holes reading as zeros. `stream_id` is an inode's
+ * private_id for a file, or an attribute's stream id. Short reads only at end of stream.
+ */
+int apfs_read_stream(struct apfs_vol *vol, uint64_t stream_id, uint64_t stream_size,
+ uint64_t off, void *buf, size_t len, size_t *out);
+
+/* Whether a file is compressed, and how. */
+int apfs_cfile_init(struct apfs_vol *vol, const struct apfs_inode *ino,
+ struct apfs_cfile *cf);
+
+/*
+ * The contents of a file as a reader of the file would see them: the data stream for a
+ * plain file, the decompressed bytes for a compressed one.
+ */
+int apfs_read_file(struct apfs_vol *vol, const struct apfs_inode *ino, uint64_t off,
+ void *buf, size_t len, size_t *out);
+
+/* ---- odds and ends worth testing on their own ---- */
+
+uint64_t apfs_fletcher64(const uint8_t *data, size_t len);
+bool apfs_checksum_ok(const uint8_t *block, uint32_t block_size);
+uint16_t apfs_mode_to_dtype(uint16_t mode);
+
+#endif /* _MISCFS_APFS_APFS_LIB_H_ */
diff --git a/xnu/files/bsd/miscfs/apfs/apfs_vfsops.c b/xnu/files/bsd/miscfs/apfs/apfs_vfsops.c
new file mode 100644
index 0000000..d7c1a0c
--- /dev/null
+++ b/xnu/files/bsd/miscfs/apfs/apfs_vfsops.c
@@ -0,0 +1,453 @@
+/*
+ * apfs mount-level operations. See apfs.h; the format is in apfs_lib.c.
+ */
+
+#include <kern/assert.h>
+#include <kern/kalloc.h>
+#include <libkern/libkern.h>
+#include <miscfs/apfs/apfs.h>
+#include <sys/attr.h>
+#include <sys/buf.h>
+#include <sys/disk.h>
+#include <sys/errno.h>
+#include <sys/kauth.h>
+#include <sys/mount_internal.h>
+#include <sys/stat.h>
+#include <sys/systm.h>
+#include <sys/time.h>
+#include <uuid/uuid.h>
+#include <sys/vnode_internal.h>
+
+static LCK_GRP_DECLARE(apfs_lck_grp, "apfs");
+
+/* Blocks are read from the device in pieces of this size. */
+#define APFS_META_CHUNK 4096
+
+/*
+ * The device, as apfs_lib wants it. Offsets and lengths are whole container blocks, and
+ * a container block is a multiple of the device's block size (both are powers of two and
+ * the container's is at least 4096), so every read lines up.
+ */
+struct apfs_devctx {
+ vnode_t dc_devvp;
+ uint32_t dc_devblock;
+};
+
+static int
+apfs_dev_read(void *ctx, uint64_t off, void *buf, size_t len)
+{
+ struct apfs_devctx *dc = ctx;
+ char *out = buf;
+
+ if ((off % dc->dc_devblock) != 0) {
+ return EINVAL;
+ }
+ while (len > 0) {
+ buf_t bp = NULL;
+ size_t chunk = len < APFS_META_CHUNK ? len : APFS_META_CHUNK;
+ int error = (int)buf_meta_bread(dc->dc_devvp,
+ (daddr64_t)(off / dc->dc_devblock), APFS_META_CHUNK, NOCRED, &bp);
+
+ if (error) {
+ if (bp != NULL) {
+ buf_brelse(bp);
+ }
+ return error;
+ }
+ memcpy(out, (const void *)buf_dataptr(bp), chunk);
+ /*
+ * apfs_lib keeps its own cache of what it needs, and a volume this size would
+ * otherwise fill the buffer cache with blocks nobody asks for twice.
+ */
+ buf_markinvalid(bp);
+ buf_brelse(bp);
+
+ out += chunk;
+ off += chunk;
+ len -= chunk;
+ }
+ return 0;
+}
+
+/* ------------------------------------------------------------------ vnodes */
+
+static uint32_t
+apfs_hash_index(uint64_t obj_id)
+{
+ /* the low bits of an identifier are the ones that differ between neighbours */
+ return (uint32_t)((obj_id ^ (obj_id >> 17)) % APFS_HASH_BUCKETS);
+}
+
+/* The vnode for an object, making one if there is not one already. */
+int
+apfs_node_vnode(struct apfs_mount *am, uint64_t obj_id, vnode_t dvp,
+ struct componentname *cnp, vnode_t *vpp)
+{
+ struct vnode_fsparam vfsp;
+ struct apfs_node *an;
+ struct apfs_inode ino;
+ uint32_t b = apfs_hash_index(obj_id);
+ uint64_t size = 0;
+ enum vtype vtype;
+ int error;
+
+ /* already have one? */
+ lck_mtx_lock(&am->am_lock);
+ for (an = am->am_hash[b]; an != NULL; an = an->an_next) {
+ if (an->an_id == obj_id && an->an_attached) {
+ vnode_t vp = an->an_vp;
+ uint32_t vid = vnode_vid(vp);
+
+ lck_mtx_unlock(&am->am_lock);
+ if (vnode_getwithvid(vp, vid) == 0) {
+ *vpp = vp;
+ return 0;
+ }
+ /* it was going away under us: fall through and make a new one */
+ lck_mtx_lock(&am->am_lock);
+ break;
+ }
+ }
+
+ error = apfs_inode_get(&am->am_vol, obj_id, &ino);
+ if (error == 0) {
+ error = apfs_inode_size(&am->am_vol, &ino, &size);
+ if (error) {
+ size = ino.size; /* the stream's size is still better than nothing */
+ error = 0;
+ }
+ }
+ lck_mtx_unlock(&am->am_lock);
+ if (error) {
+ return error;
+ }
+
+ switch (ino.mode & APFS_S_IFMT) {
+ case APFS_S_IFREG: vtype = VREG; break;
+ case APFS_S_IFDIR: vtype = VDIR; break;
+ case APFS_S_IFLNK: vtype = VLNK; break;
+ case APFS_S_IFCHR: vtype = VCHR; break;
+ case APFS_S_IFBLK: vtype = VBLK; break;
+ case APFS_S_IFIFO: vtype = VFIFO; break;
+ case APFS_S_IFSOCK: vtype = VSOCK; break;
+ default:
+ return EIO;
+ }
+
+ an = kalloc_type(struct apfs_node, Z_WAITOK | Z_ZERO);
+ if (an == NULL) {
+ return ENOMEM;
+ }
+ an->an_mount = am;
+ an->an_id = obj_id;
+ an->an_parent = ino.parent_id;
+ an->an_mode = ino.mode;
+ an->an_size = size;
+
+ bzero(&vfsp, sizeof(vfsp));
+ vfsp.vnfs_mp = am->am_mp;
+ vfsp.vnfs_vtype = vtype;
+ vfsp.vnfs_str = "apfs";
+ vfsp.vnfs_dvp = dvp;
+ vfsp.vnfs_fsnode = an;
+ vfsp.vnfs_vops = apfs_vnodeop_p;
+ vfsp.vnfs_markroot = (obj_id == am->am_root_id);
+ vfsp.vnfs_marksystem = 0;
+ vfsp.vnfs_rdev = (vtype == VCHR || vtype == VBLK) ? (dev_t)ino.rdev : 0;
+ vfsp.vnfs_filesize = size;
+ vfsp.vnfs_cnp = cnp;
+ /* let VFS cache the name only when it came from a lookup that has one */
+ vfsp.vnfs_flags = (dvp != NULL && cnp != NULL) ? 0 : VNFS_NOCACHE;
+
+ error = vnode_create(VNCREATE_FLAVOR, VCREATESIZE, &vfsp, &an->an_vp);
+ if (error) {
+ kfree_type(struct apfs_node, an);
+ return error;
+ }
+ vnode_settag(an->an_vp, VT_OTHER);
+
+ lck_mtx_lock(&am->am_lock);
+ an->an_next = am->am_hash[b];
+ am->am_hash[b] = an;
+ an->an_attached = true;
+ lck_mtx_unlock(&am->am_lock);
+
+ *vpp = an->an_vp;
+ return 0;
+}
+
+/* Take a node out of the hash; called from vnop_reclaim. */
+void
+apfs_node_detach(struct apfs_node *an)
+{
+ struct apfs_mount *am = an->an_mount;
+ uint32_t b = apfs_hash_index(an->an_id);
+ struct apfs_node **pp;
+
+ lck_mtx_lock(&am->am_lock);
+ for (pp = &am->am_hash[b]; *pp != NULL; pp = &(*pp)->an_next) {
+ if (*pp == an) {
+ *pp = an->an_next;
+ break;
+ }
+ }
+ an->an_attached = false;
+ lck_mtx_unlock(&am->am_lock);
+}
+
+/* ------------------------------------------------------------------ mount */
+
+static void
+apfs_free_mount(struct apfs_mount *am)
+{
+ apfs_nx_close(&am->am_nx);
+ lck_mtx_destroy(&am->am_lock, &apfs_lck_grp);
+ kfree_type(struct apfs_mount, am);
+}
+
+static int
+apfs_mount_common(mount_t mp, vnode_t devvp, vfs_context_t ctx)
+{
+ struct apfs_mount *am;
+ struct apfs_devctx *dc;
+ struct apfs_dev dev;
+ struct vfsstatfs *sp;
+ uint32_t devblock = 0;
+ uint64_t devblocks = 0;
+ int error;
+
+ if (VNOP_IOCTL(devvp, DKIOCGETBLOCKSIZE, (caddr_t)&devblock, 0, ctx) != 0 ||
+ devblock == 0 || (APFS_META_CHUNK % devblock) != 0) {
+ return EINVAL;
+ }
+ (void)VNOP_IOCTL(devvp, DKIOCGETBLOCKCOUNT, (caddr_t)&devblocks, 0, ctx);
+
+ am = kalloc_type(struct apfs_mount, Z_WAITOK | Z_ZERO);
+ if (am == NULL) {
+ return ENOMEM;
+ }
+ lck_mtx_init(&am->am_lock, &apfs_lck_grp, LCK_ATTR_NULL);
+ am->am_mp = mp;
+ am->am_devvp = devvp;
+ am->am_devblock = devblock;
+
+ dc = kalloc_type(struct apfs_devctx, Z_WAITOK | Z_ZERO);
+ if (dc == NULL) {
+ apfs_free_mount(am);
+ return ENOMEM;
+ }
+ dc->dc_devvp = devvp;
+ dc->dc_devblock = devblock;
+
+ bzero(&dev, sizeof(dev));
+ dev.ctx = dc;
+ dev.size = devblocks * (uint64_t)devblock;
+ dev.read = apfs_dev_read;
+
+ error = apfs_nx_open(&am->am_nx, &dev);
+ if (error) {
+ /*
+ * EINVAL means the magic was not there, so this is not an APFS container at
+ * all: as the root filesystem that lets vfs_mountroot() try the next one
+ * without a word.
+ */
+ if (error != EINVAL) {
+ printf("apfs: cannot read the container: %d\n", error);
+ }
+ kfree_type(struct apfs_devctx, dc);
+ apfs_free_mount(am);
+ return error;
+ }
+
+ /* the first volume that has a root directory */
+ {
+ uint32_t i;
+ bool got = false;
+
+ for (i = 0; i < APFS_NX_MAX_FILE_SYSTEMS && !got; i++) {
+ struct apfs_inode ino;
+
+ if (am->am_nx.fs_oid[i] == 0) {
+ continue;
+ }
+ if (apfs_vol_open(&am->am_nx, i, &am->am_vol) != 0) {
+ continue;
+ }
+ if (apfs_inode_get(&am->am_vol, APFS_ROOT_DIR_INO_NUM, &ino) == 0) {
+ got = true;
+ }
+ }
+ if (!got) {
+ printf("apfs: no readable volume with a root directory\n");
+ kfree_type(struct apfs_devctx, dc);
+ apfs_free_mount(am);
+ return EINVAL;
+ }
+ }
+ am->am_root_id = APFS_ROOT_DIR_INO_NUM;
+
+ vfs_setfsprivate(mp, am);
+ vfs_setflags(mp, MNT_RDONLY | MNT_LOCAL);
+ vfs_setlocklocal(mp);
+
+ sp = vfs_statfs(mp);
+ sp->f_bsize = am->am_nx.block_size;
+ sp->f_iosize = am->am_nx.block_size;
+ sp->f_blocks = am->am_nx.block_count;
+ sp->f_bfree = 0;
+ sp->f_bavail = 0;
+ sp->f_bused = am->am_vol.alloc_count;
+ sp->f_files = am->am_vol.num_files + am->am_vol.num_dirs;
+ sp->f_ffree = 0;
+ sp->f_fsid.val[0] = (int32_t)vnode_specrdev(devvp);
+ sp->f_fsid.val[1] = vfs_typenum(mp);
+ strlcpy(sp->f_fstypename, "apfs", sizeof(sp->f_fstypename));
+
+ printf("apfs: volume \"%s\": %llu files, %llu directories, %llu blocks of %u used\n",
+ am->am_vol.name, (unsigned long long)am->am_vol.num_files,
+ (unsigned long long)am->am_vol.num_dirs,
+ (unsigned long long)am->am_vol.alloc_count, am->am_nx.block_size);
+ return 0;
+}
+
+/* As the root filesystem: EINVAL lets vfs_mountroot() try the next quietly. */
+int
+apfs_mountroot(mount_t mp, vnode_t devvp, vfs_context_t ctx)
+{
+ return apfs_mount_common(mp, devvp, ctx);
+}
+
+static int
+apfs_mount(mount_t mp, vnode_t devvp, __unused user_addr_t data, vfs_context_t ctx)
+{
+ if (vfs_isupdate(mp)) {
+ /* nothing about a mounted volume can change, least of all to read-write */
+ return vfs_iswriteupgrade(mp) ? EROFS : 0;
+ }
+ if (devvp == NULLVP) {
+ return EINVAL;
+ }
+ return apfs_mount_common(mp, devvp, ctx);
+}
+
+static int
+apfs_unmount(mount_t mp, int mntflags, __unused vfs_context_t ctx)
+{
+ struct apfs_mount *am = APFS_MP(mp);
+ int error = vflush(mp, NULLVP, (mntflags & MNT_FORCE) ? FORCECLOSE : 0);
+
+ if (error) {
+ return error;
+ }
+ vfs_setfsprivate(mp, NULL);
+ apfs_free_mount(am);
+ return 0;
+}
+
+static int
+apfs_root(mount_t mp, vnode_t *vpp, __unused vfs_context_t ctx)
+{
+ struct apfs_mount *am = APFS_MP(mp);
+
+ return apfs_node_vnode(am, am->am_root_id, NULLVP, NULL, vpp);
+}
+
+static int
+apfs_vget(mount_t mp, ino64_t ino, vnode_t *vpp, __unused vfs_context_t ctx)
+{
+ return apfs_node_vnode(APFS_MP(mp), (uint64_t)ino, NULLVP, NULL, vpp);
+}
+
+static int
+apfs_vfs_getattr(mount_t mp, struct vfs_attr *fsap, __unused vfs_context_t ctx)
+{
+ struct apfs_mount *am = APFS_MP(mp);
+ uint64_t files = am->am_vol.num_files + am->am_vol.num_dirs;
+
+ VFSATTR_RETURN(fsap, f_objcount, files);
+ VFSATTR_RETURN(fsap, f_bsize, am->am_nx.block_size);
+ VFSATTR_RETURN(fsap, f_iosize, am->am_nx.block_size);
+ VFSATTR_RETURN(fsap, f_blocks, am->am_nx.block_count);
+ VFSATTR_RETURN(fsap, f_bfree, 0);
+ VFSATTR_RETURN(fsap, f_bavail, 0);
+ VFSATTR_RETURN(fsap, f_bused, am->am_vol.alloc_count);
+ VFSATTR_RETURN(fsap, f_files, files);
+ VFSATTR_RETURN(fsap, f_ffree, 0);
+
+ if (VFSATTR_IS_ACTIVE(fsap, f_capabilities)) {
+ vol_capabilities_attr_t *cap = &fsap->f_capabilities;
+ bool nocase = (am->am_vol.incompat & APFS_INCOMPAT_CASE_INSENSITIVE) != 0;
+
+ bzero(cap, sizeof(*cap));
+ /*
+ * An object's identifier never changes and apfs_vget() finds an object by it,
+ * which is what lets fsgetpath(2) and /.vol work for this volume -- see the
+ * note in packfs about what breaks in user space without it.
+ */
+ cap->capabilities[VOL_CAPABILITIES_FORMAT] =
+ VOL_CAP_FMT_PERSISTENTOBJECTIDS |
+ VOL_CAP_FMT_SYMBOLICLINKS |
+ VOL_CAP_FMT_HARDLINKS |
+ VOL_CAP_FMT_SPARSE_FILES |
+ VOL_CAP_FMT_CASE_PRESERVING |
+ VOL_CAP_FMT_FAST_STATFS |
+ VOL_CAP_FMT_2TB_FILESIZE |
+ VOL_CAP_FMT_PATH_FROM_ID |
+ (nocase ? 0 : VOL_CAP_FMT_CASE_SENSITIVE);
+ cap->capabilities[VOL_CAPABILITIES_INTERFACES] =
+ VOL_CAP_INT_ADVLOCK |
+ VOL_CAP_INT_FLOCK |
+ VOL_CAP_INT_EXTENDED_ATTR;
+ cap->valid[VOL_CAPABILITIES_FORMAT] =
+ VOL_CAP_FMT_PERSISTENTOBJECTIDS |
+ VOL_CAP_FMT_SYMBOLICLINKS |
+ VOL_CAP_FMT_HARDLINKS |
+ VOL_CAP_FMT_JOURNAL |
+ VOL_CAP_FMT_JOURNAL_ACTIVE |
+ VOL_CAP_FMT_SPARSE_FILES |
+ VOL_CAP_FMT_ZERO_RUNS |
+ VOL_CAP_FMT_CASE_SENSITIVE |
+ VOL_CAP_FMT_CASE_PRESERVING |
+ VOL_CAP_FMT_FAST_STATFS |
+ VOL_CAP_FMT_2TB_FILESIZE |
+ VOL_CAP_FMT_HIDDEN_FILES |
+ VOL_CAP_FMT_PATH_FROM_ID;
+ cap->valid[VOL_CAPABILITIES_INTERFACES] =
+ VOL_CAP_INT_ADVLOCK |
+ VOL_CAP_INT_FLOCK |
+ VOL_CAP_INT_EXTENDED_ATTR;
+ VFSATTR_SET_SUPPORTED(fsap, f_capabilities);
+ }
+ if (VFSATTR_IS_ACTIVE(fsap, f_vol_name)) {
+ strlcpy(fsap->f_vol_name, am->am_vol.name, MAXPATHLEN);
+ VFSATTR_SET_SUPPORTED(fsap, f_vol_name);
+ }
+ if (VFSATTR_IS_ACTIVE(fsap, f_uuid)) {
+ memcpy(fsap->f_uuid, am->am_nx.uuid, sizeof(fsap->f_uuid));
+ VFSATTR_SET_SUPPORTED(fsap, f_uuid);
+ }
+ return 0;
+}
+
+/* Nothing is ever dirty. */
+static int
+apfs_sync(__unused mount_t mp, __unused int waitfor, __unused vfs_context_t ctx)
+{
+ return 0;
+}
+
+static int
+apfs_init(__unused struct vfsconf *vfsc)
+{
+ return 0;
+}
+
+struct vfsops apfs_vfsops = {
+ .vfs_mount = apfs_mount,
+ .vfs_unmount = apfs_unmount,
+ .vfs_root = apfs_root,
+ .vfs_getattr = apfs_vfs_getattr,
+ .vfs_sync = apfs_sync,
+ .vfs_vget = apfs_vget,
+ .vfs_init = apfs_init,
+};
diff --git a/xnu/files/bsd/miscfs/apfs/apfs_vnops.c b/xnu/files/bsd/miscfs/apfs/apfs_vnops.c
new file mode 100644
index 0000000..1f74996
--- /dev/null
+++ b/xnu/files/bsd/miscfs/apfs/apfs_vnops.c
@@ -0,0 +1,663 @@
+/*
+ * apfs vnode operations. Read only; see apfs.h.
+ *
+ * Every call into apfs_lib is made under the mount's lock, because apfs_lib hands out
+ * pointers into its own block cache and its cursors carry no locking.
+ */
+
+#include <kern/kalloc.h>
+#include <libkern/libkern.h>
+#include <miscfs/apfs/apfs.h>
+#include <sys/attr.h>
+#include <sys/dirent.h>
+#include <sys/errno.h>
+#include <sys/namei.h>
+#include <sys/stat.h>
+#include <sys/systm.h>
+#include <sys/ubc.h>
+#include <sys/uio.h>
+#include <sys/mount_internal.h>
+#include <sys/unistd.h>
+#include <sys/vnode_internal.h>
+#include <sys/xattr.h>
+#include <vfs/vfs_support.h>
+
+/* How much is read out of a file at a time when copying into a uio. */
+#define APFS_IOBUF 65536
+
+static void
+apfs_lock(struct apfs_mount *am)
+{
+ lck_mtx_lock(&am->am_lock);
+}
+
+static void
+apfs_unlock(struct apfs_mount *am)
+{
+ lck_mtx_unlock(&am->am_lock);
+}
+
+/* The inode record of the object a vnode stands for. */
+static int
+apfs_vp_inode(vnode_t vp, struct apfs_inode *ino)
+{
+ struct apfs_node *an = APFS_VP(vp);
+
+ return apfs_inode_get(&an->an_mount->am_vol, an->an_id, ino);
+}
+
+/* ------------------------------------------------------------------ lookup */
+
+static int
+apfs_vnop_lookup(struct vnop_lookup_args *ap)
+{
+ vnode_t dvp = ap->a_dvp;
+ struct componentname *cnp = ap->a_cnp;
+ struct apfs_mount *am = APFS_VP_MOUNT(dvp);
+ struct apfs_node *dn = APFS_VP(dvp);
+ uint64_t id = 0;
+ uint8_t dt = 0;
+ int error;
+
+ *ap->a_vpp = NULLVP;
+ if (!vnode_isdir(dvp)) {
+ return ENOTDIR;
+ }
+ /* read only: anything that would change the directory is refused up front */
+ if (cnp->cn_nameiop != LOOKUP) {
+ return EROFS;
+ }
+ if (cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.') {
+ error = vnode_get(dvp);
+ if (error == 0) {
+ *ap->a_vpp = dvp;
+ }
+ return error;
+ }
+ if (cnp->cn_flags & ISDOTDOT) {
+ return apfs_node_vnode(am, dn->an_parent, NULLVP, NULL, ap->a_vpp);
+ }
+
+ apfs_lock(am);
+ error = apfs_lookup(&am->am_vol, dn->an_id, cnp->cn_nameptr,
+ (size_t)cnp->cn_namelen, &id, &dt);
+ apfs_unlock(am);
+ if (error) {
+ return error;
+ }
+ return apfs_node_vnode(am, id, dvp, cnp, ap->a_vpp);
+}
+
+/* ------------------------------------------------------------------ attributes */
+
+static int
+apfs_vnop_getattr(struct vnop_getattr_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct vnode_attr *vap = ap->a_vap;
+ struct apfs_mount *am = APFS_VP_MOUNT(vp);
+ struct apfs_node *an = APFS_VP(vp);
+ struct apfs_inode ino;
+ uint64_t size = 0;
+ int error;
+
+ apfs_lock(am);
+ error = apfs_vp_inode(vp, &ino);
+ if (error == 0) {
+ error = apfs_inode_size(&am->am_vol, &ino, &size);
+ if (error) {
+ size = ino.size;
+ error = 0;
+ }
+ }
+ apfs_unlock(am);
+ if (error) {
+ return error;
+ }
+ an->an_size = size;
+
+ VATTR_RETURN(vap, va_rdev, (dev_t)ino.rdev);
+ VATTR_RETURN(vap, va_nlink, vnode_isdir(vp) ? 2 : (uint32_t)(ino.nchildren > 0
+ ? ino.nchildren : 1));
+ VATTR_RETURN(vap, va_data_size, size);
+ VATTR_RETURN(vap, va_total_size, size);
+ VATTR_RETURN(vap, va_total_alloc, ino.alloced_size);
+ VATTR_RETURN(vap, va_data_alloc, ino.alloced_size);
+ VATTR_RETURN(vap, va_iosize, am->am_nx.block_size);
+ VATTR_RETURN(vap, va_uid, ino.owner);
+ VATTR_RETURN(vap, va_gid, ino.group);
+ VATTR_RETURN(vap, va_mode, ino.mode & 07777);
+ VATTR_RETURN(vap, va_flags, ino.bsd_flags);
+ VATTR_RETURN(vap, va_fileid, an->an_id);
+ VATTR_RETURN(vap, va_linkid, an->an_id);
+ VATTR_RETURN(vap, va_parentid, ino.parent_id);
+ VATTR_RETURN(vap, va_fsid, (uint32_t)vfs_statfs(am->am_mp)->f_fsid.val[0]);
+ VATTR_RETURN(vap, va_filerev, 0);
+ VATTR_RETURN(vap, va_gen, 0);
+ VATTR_RETURN(vap, va_type, vnode_vtype(vp));
+
+ /* the times are nanoseconds since the Unix epoch */
+ if (VATTR_IS_ACTIVE(vap, va_access_time)) {
+ vap->va_access_time.tv_sec = (long)(ino.access_time / 1000000000ULL);
+ vap->va_access_time.tv_nsec = (long)(ino.access_time % 1000000000ULL);
+ VATTR_SET_SUPPORTED(vap, va_access_time);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_modify_time)) {
+ vap->va_modify_time.tv_sec = (long)(ino.mod_time / 1000000000ULL);
+ vap->va_modify_time.tv_nsec = (long)(ino.mod_time % 1000000000ULL);
+ VATTR_SET_SUPPORTED(vap, va_modify_time);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_change_time)) {
+ vap->va_change_time.tv_sec = (long)(ino.change_time / 1000000000ULL);
+ vap->va_change_time.tv_nsec = (long)(ino.change_time % 1000000000ULL);
+ VATTR_SET_SUPPORTED(vap, va_change_time);
+ }
+ if (VATTR_IS_ACTIVE(vap, va_create_time)) {
+ vap->va_create_time.tv_sec = (long)(ino.create_time / 1000000000ULL);
+ vap->va_create_time.tv_nsec = (long)(ino.create_time % 1000000000ULL);
+ VATTR_SET_SUPPORTED(vap, va_create_time);
+ }
+ return 0;
+}
+
+/* ------------------------------------------------------------------ reading */
+
+static int
+apfs_vnop_read(struct vnop_read_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct uio *uio = ap->a_uio;
+ struct apfs_mount *am = APFS_VP_MOUNT(vp);
+ struct apfs_inode ino;
+ uint8_t *buf;
+ uint64_t size = 0;
+ int error;
+
+ if (vnode_isdir(vp)) {
+ return EISDIR;
+ }
+ if (!vnode_isreg(vp)) {
+ return EINVAL;
+ }
+ if (uio_offset(uio) < 0) {
+ return EINVAL;
+ }
+ apfs_lock(am);
+ error = apfs_vp_inode(vp, &ino);
+ if (error == 0) {
+ error = apfs_inode_size(&am->am_vol, &ino, &size);
+ }
+ apfs_unlock(am);
+ if (error) {
+ return error;
+ }
+ buf = kalloc_data(APFS_IOBUF, Z_WAITOK);
+ if (buf == NULL) {
+ return ENOMEM;
+ }
+ while (uio_resid(uio) > 0 && (uint64_t)uio_offset(uio) < size) {
+ size_t want = (size_t)MIN((user_ssize_t)APFS_IOBUF, uio_resid(uio));
+ size_t got = 0;
+
+ apfs_lock(am);
+ error = apfs_read_file(&am->am_vol, &ino, (uint64_t)uio_offset(uio), buf, want,
+ &got);
+ apfs_unlock(am);
+ if (error) {
+ break;
+ }
+ if (got == 0) {
+ break;
+ }
+ error = uiomove((caddr_t)buf, (int)got, uio);
+ if (error) {
+ break;
+ }
+ }
+ kfree_data(buf, APFS_IOBUF);
+ return error;
+}
+
+/*
+ * Page in. Everything goes through apfs_read_file rather than the cluster layer: a
+ * compressed file has no block mapping at all, and a plain one is read out of the extents
+ * just as cheaply here.
+ */
+static int
+apfs_vnop_pagein(struct vnop_pagein_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct apfs_mount *am = APFS_VP_MOUNT(vp);
+ upl_t upl = ap->a_pl;
+ upl_offset_t upl_offset = ap->a_pl_offset;
+ off_t offset = ap->a_f_offset;
+ struct apfs_inode ino;
+ vm_offset_t address = 0;
+ uint64_t size = 0;
+ off_t at, end;
+ int error = 0;
+
+ if (upl == NULL) {
+ return EINVAL;
+ }
+ if (offset < 0 || (offset & PAGE_MASK_64) || (ap->a_size & PAGE_MASK) ||
+ (upl_offset & PAGE_MASK)) {
+ error = EINVAL;
+ } else {
+ apfs_lock(am);
+ error = apfs_vp_inode(vp, &ino);
+ if (error == 0) {
+ error = apfs_inode_size(&am->am_vol, &ino, &size);
+ }
+ apfs_unlock(am);
+ if (error == 0 && ubc_upl_map(upl, &address) != KERN_SUCCESS) {
+ error = ENOMEM;
+ }
+ }
+ if (error) {
+ if (!(ap->a_flags & UPL_NOCOMMIT)) {
+ ubc_upl_abort_range(upl, upl_offset, (upl_size_t)ap->a_size,
+ UPL_ABORT_FREE_ON_EMPTY | UPL_ABORT_ERROR);
+ }
+ return error;
+ }
+
+ end = offset + (off_t)ap->a_size;
+ for (at = offset; at < end;) {
+ uint8_t *dst = (uint8_t *)address + upl_offset + (at - offset);
+ size_t want, got = 0;
+
+ if ((uint64_t)at >= size) {
+ bzero(dst, (size_t)(end - at)); /* past the end of the file */
+ break;
+ }
+ want = (size_t)MIN(end - at, (off_t)(size - (uint64_t)at));
+ apfs_lock(am);
+ error = apfs_read_file(&am->am_vol, &ino, (uint64_t)at, dst, want, &got);
+ apfs_unlock(am);
+ if (error) {
+ break;
+ }
+ if (got == 0) {
+ bzero(dst, (size_t)(end - at));
+ break;
+ }
+ at += got;
+ /* the last page of the file: zero what lies past its end */
+ if ((uint64_t)at >= size && at < end) {
+ bzero((uint8_t *)address + upl_offset + (at - offset),
+ (size_t)(end - at));
+ break;
+ }
+ }
+
+ ubc_upl_unmap(upl);
+ if (!(ap->a_flags & UPL_NOCOMMIT)) {
+ if (error) {
+ ubc_upl_abort_range(upl, upl_offset, (upl_size_t)ap->a_size,
+ UPL_ABORT_FREE_ON_EMPTY | UPL_ABORT_ERROR);
+ } else {
+ ubc_upl_commit_range(upl, upl_offset, (upl_size_t)ap->a_size,
+ UPL_COMMIT_CLEAR_DIRTY | UPL_COMMIT_FREE_ON_EMPTY);
+ }
+ }
+ return error;
+}
+
+/* ------------------------------------------------------------------ directories */
+
+#define APFS_DIRSIZ(namlen) \
+ ((sizeof(struct dirent) - (MAXNAMLEN + 1)) + (((namlen) + 1 + 3) & ~3))
+
+struct apfs_rd_ctx {
+ struct uio *rd_uio;
+ off_t rd_start; /* where this call is to resume */
+ off_t rd_pos; /* where we are in the stream of entries */
+ int rd_count;
+ bool rd_full;
+ int rd_error;
+};
+
+static int
+apfs_vnop_readdir_one(struct apfs_rd_ctx *rc, const char *name, size_t name_len,
+ uint64_t file_id, uint8_t d_type)
+{
+ struct dirent de;
+
+ if (name_len > MAXNAMLEN) {
+ return 0; /* cannot be named through this interface; skip it */
+ }
+ bzero(&de, sizeof(de));
+ de.d_fileno = (ino_t)file_id;
+ de.d_type = d_type;
+ de.d_namlen = (uint8_t)name_len;
+ de.d_reclen = (uint16_t)APFS_DIRSIZ(name_len);
+
+ if (rc->rd_pos >= rc->rd_start) {
+ if (uio_resid(rc->rd_uio) < (user_ssize_t)de.d_reclen) {
+ rc->rd_full = true;
+ return EEXIST; /* stop the walk: no room for this one */
+ }
+ memcpy(de.d_name, name, name_len);
+ rc->rd_error = uiomove((caddr_t)&de, de.d_reclen, rc->rd_uio);
+ if (rc->rd_error) {
+ return EEXIST;
+ }
+ rc->rd_count++;
+ }
+ rc->rd_pos += de.d_reclen;
+ return 0;
+}
+
+static int
+apfs_readdir_cb(void *ctx, const char *name, size_t name_len, uint64_t file_id,
+ uint8_t d_type)
+{
+ return apfs_vnop_readdir_one(ctx, name, name_len, file_id, d_type);
+}
+
+static int
+apfs_vnop_readdir(struct vnop_readdir_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct apfs_mount *am = APFS_VP_MOUNT(vp);
+ struct apfs_node *an = APFS_VP(vp);
+ struct apfs_rd_ctx rc;
+ int error;
+
+ if (ap->a_flags & (VNODE_READDIR_EXTENDED | VNODE_READDIR_REQSEEKOFF)) {
+ return EINVAL;
+ }
+ if (!vnode_isdir(vp)) {
+ return ENOTDIR;
+ }
+ bzero(&rc, sizeof(rc));
+ rc.rd_uio = ap->a_uio;
+ rc.rd_start = uio_offset(ap->a_uio);
+
+ /*
+ * A directory's entries are a run of records in the tree with no index, so there is
+ * nothing to seek to: the walk starts at the beginning every time and skips what
+ * has already been handed over. "." and ".." come first and are not in the tree.
+ */
+ error = apfs_vnop_readdir_one(&rc, ".", 1, an->an_id, DT_DIR);
+ if (error == 0) {
+ error = apfs_vnop_readdir_one(&rc, "..", 2, an->an_parent, DT_DIR);
+ }
+ if (error == 0) {
+ apfs_lock(am);
+ error = apfs_readdir(&am->am_vol, an->an_id, apfs_readdir_cb, &rc);
+ apfs_unlock(am);
+ }
+ if (error == EEXIST) {
+ error = 0; /* we stopped it ourselves */
+ }
+ if (rc.rd_error != 0) {
+ return rc.rd_error;
+ }
+ if (error != 0) {
+ return error;
+ }
+ uio_setoffset(ap->a_uio, rc.rd_pos);
+ if (ap->a_eofflag != NULL) {
+ *ap->a_eofflag = rc.rd_full ? 0 : 1;
+ }
+ if (ap->a_numdirent != NULL) {
+ *ap->a_numdirent = rc.rd_count;
+ }
+ return 0;
+}
+
+static int
+apfs_vnop_readlink(struct vnop_readlink_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct apfs_mount *am = APFS_VP_MOUNT(vp);
+ struct apfs_node *an = APFS_VP(vp);
+ char *buf;
+ size_t n = 0;
+ int error;
+
+ if (!vnode_islnk(vp)) {
+ return EINVAL;
+ }
+ buf = kalloc_data(MAXPATHLEN, Z_WAITOK);
+ if (buf == NULL) {
+ return ENOMEM;
+ }
+ apfs_lock(am);
+ error = apfs_readlink(&am->am_vol, an->an_id, buf, MAXPATHLEN, &n);
+ apfs_unlock(am);
+ if (error == 0) {
+ error = uiomove(buf, (int)n, ap->a_uio);
+ }
+ kfree_data(buf, MAXPATHLEN);
+ return error;
+}
+
+/* ------------------------------------------------------------------ attributes */
+
+/*
+ * The attributes the operating system keeps for itself are not shown to user space: they
+ * are how a symbolic link and a compressed file are stored, not things a reader should
+ * see.
+ */
+static bool
+apfs_xattr_hidden(const char *name)
+{
+ return strcmp(name, APFS_SYMLINK_EA_NAME) == 0 ||
+ strcmp(name, APFS_DECMPFS_XATTR_NAME) == 0 ||
+ strcmp(name, APFS_RSRC_FORK_XATTR_NAME) == 0;
+}
+
+static int
+apfs_vnop_getxattr(struct vnop_getxattr_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct apfs_mount *am = APFS_VP_MOUNT(vp);
+ struct apfs_node *an = APFS_VP(vp);
+ struct apfs_xattr xa;
+ uint8_t *buf;
+ size_t n = 0, whole;
+ int error;
+
+ if (ap->a_name == NULL) {
+ return EINVAL;
+ }
+ if (apfs_xattr_hidden(ap->a_name)) {
+ return ENOATTR;
+ }
+ apfs_lock(am);
+ error = apfs_xattr_lookup(&am->am_vol, an->an_id, ap->a_name, &xa);
+ apfs_unlock(am);
+ if (error) {
+ return error == ENOENT ? ENOATTR : error;
+ }
+ whole = (xa.flags & APFS_XATTR_DATA_STREAM) ? (size_t)xa.stream_size : xa.data_len;
+ if (ap->a_uio == NULL) {
+ *ap->a_size = whole; /* only the size was asked for */
+ return 0;
+ }
+ if (uio_resid(ap->a_uio) < (user_ssize_t)whole) {
+ return ERANGE;
+ }
+ buf = kalloc_data(whole ? whole : 1, Z_WAITOK);
+ if (buf == NULL) {
+ return ENOMEM;
+ }
+ apfs_lock(am);
+ error = apfs_xattr_read(&am->am_vol, an->an_id, ap->a_name, buf, whole, &n);
+ apfs_unlock(am);
+ if (error == 0) {
+ error = uiomove((caddr_t)buf, (int)n, ap->a_uio);
+ }
+ kfree_data(buf, whole ? whole : 1);
+ return error;
+}
+
+struct apfs_lx_ctx {
+ struct uio *lx_uio;
+ size_t lx_size;
+ int lx_error;
+};
+
+static int
+apfs_listxattr_cb(void *ctx, const char *name, size_t name_len,
+ __unused const struct apfs_xattr *xa)
+{
+ struct apfs_lx_ctx *lc = ctx;
+
+ if (apfs_xattr_hidden(name)) {
+ return 0;
+ }
+ if (lc->lx_uio == NULL) {
+ lc->lx_size += name_len + 1;
+ return 0;
+ }
+ if (uio_resid(lc->lx_uio) < (user_ssize_t)(name_len + 1)) {
+ lc->lx_error = ERANGE;
+ return EEXIST;
+ }
+ lc->lx_error = uiomove((caddr_t)(uintptr_t)name, (int)name_len + 1, lc->lx_uio);
+ return lc->lx_error ? EEXIST : 0;
+}
+
+static int
+apfs_vnop_listxattr(struct vnop_listxattr_args *ap)
+{
+ struct apfs_mount *am = APFS_VP_MOUNT(ap->a_vp);
+ struct apfs_node *an = APFS_VP(ap->a_vp);
+ struct apfs_lx_ctx lc;
+ int error;
+
+ bzero(&lc, sizeof(lc));
+ lc.lx_uio = ap->a_uio;
+ apfs_lock(am);
+ error = apfs_xattr_list(&am->am_vol, an->an_id, apfs_listxattr_cb, &lc);
+ apfs_unlock(am);
+ if (error == EEXIST) {
+ error = 0;
+ }
+ if (error == 0 && lc.lx_error != 0) {
+ return lc.lx_error;
+ }
+ if (error) {
+ return error;
+ }
+ if (ap->a_uio == NULL && ap->a_size != NULL) {
+ *ap->a_size = lc.lx_size;
+ }
+ return 0;
+}
+
+/* ------------------------------------------------------------------ the rest */
+
+static int
+apfs_vnop_open(struct vnop_open_args *ap)
+{
+ if (ap->a_mode & (FWRITE | O_TRUNC | O_CREAT)) {
+ return EROFS;
+ }
+ return 0;
+}
+
+static int
+apfs_vnop_close(__unused struct vnop_close_args *ap)
+{
+ return 0;
+}
+
+static int
+apfs_vnop_mmap(__unused struct vnop_mmap_args *ap)
+{
+ /* the mount is read-only, so VFS has already refused a writable mapping */
+ return 0;
+}
+
+static int
+apfs_vnop_mnomap(__unused struct vnop_mnomap_args *ap)
+{
+ return 0;
+}
+
+static int
+apfs_vnop_inactive(__unused struct vnop_inactive_args *ap)
+{
+ return 0;
+}
+
+static int
+apfs_vnop_reclaim(struct vnop_reclaim_args *ap)
+{
+ vnode_t vp = ap->a_vp;
+ struct apfs_node *an = APFS_VP(vp);
+
+ if (an != NULL) {
+ apfs_node_detach(an);
+ vnode_clearfsnode(vp);
+ kfree_type(struct apfs_node, an);
+ }
+ return 0;
+}
+
+static int
+apfs_vnop_pathconf(struct vnop_pathconf_args *ap)
+{
+ switch (ap->a_name) {
+ case _PC_LINK_MAX:
+ *ap->a_retval = 32767;
+ return 0;
+ case _PC_NAME_MAX:
+ *ap->a_retval = 255;
+ return 0;
+ case _PC_PATH_MAX:
+ *ap->a_retval = PATH_MAX;
+ return 0;
+ case _PC_CHOWN_RESTRICTED:
+ *ap->a_retval = 1;
+ return 0;
+ case _PC_NO_TRUNC:
+ *ap->a_retval = 1;
+ return 0;
+ case _PC_CASE_SENSITIVE:
+ *ap->a_retval = (APFS_VP_MOUNT(ap->a_vp)->am_vol.incompat &
+ APFS_INCOMPAT_CASE_INSENSITIVE) ? 0 : 1;
+ return 0;
+ case _PC_CASE_PRESERVING:
+ *ap->a_retval = 1;
+ return 0;
+ case _PC_XATTR_SIZE_BITS:
+ *ap->a_retval = 32;
+ return 0;
+ default:
+ return EINVAL;
+ }
+}
+
+#define VOPFUNC int (*)(void *)
+
+int(**apfs_vnodeop_p)(void *);
+const struct vnodeopv_entry_desc apfs_vnodeop_entries[] = {
+ { .opve_op = &vnop_default_desc, .opve_impl = (VOPFUNC)vn_default_error },
+ { .opve_op = &vnop_lookup_desc, .opve_impl = (VOPFUNC)apfs_vnop_lookup },
+ { .opve_op = &vnop_open_desc, .opve_impl = (VOPFUNC)apfs_vnop_open },
+ { .opve_op = &vnop_close_desc, .opve_impl = (VOPFUNC)apfs_vnop_close },
+ { .opve_op = &vnop_getattr_desc, .opve_impl = (VOPFUNC)apfs_vnop_getattr },
+ { .opve_op = &vnop_read_desc, .opve_impl = (VOPFUNC)apfs_vnop_read },
+ { .opve_op = &vnop_getxattr_desc, .opve_impl = (VOPFUNC)apfs_vnop_getxattr },
+ { .opve_op = &vnop_listxattr_desc, .opve_impl = (VOPFUNC)apfs_vnop_listxattr },
+ { .opve_op = &vnop_fsync_desc, .opve_impl = (VOPFUNC)nop_fsync },
+ { .opve_op = &vnop_readdir_desc, .opve_impl = (VOPFUNC)apfs_vnop_readdir },
+ { .opve_op = &vnop_readlink_desc, .opve_impl = (VOPFUNC)apfs_vnop_readlink },
+ { .opve_op = &vnop_inactive_desc, .opve_impl = (VOPFUNC)apfs_vnop_inactive },
+ { .opve_op = &vnop_reclaim_desc, .opve_impl = (VOPFUNC)apfs_vnop_reclaim },
+ { .opve_op = &vnop_pathconf_desc, .opve_impl = (VOPFUNC)apfs_vnop_pathconf },
+ { .opve_op = &vnop_mmap_desc, .opve_impl = (VOPFUNC)apfs_vnop_mmap },
+ { .opve_op = &vnop_mnomap_desc, .opve_impl = (VOPFUNC)apfs_vnop_mnomap },
+ { .opve_op = &vnop_pagein_desc, .opve_impl = (VOPFUNC)apfs_vnop_pagein },
+ { .opve_op = (struct vnodeop_desc *)NULL, .opve_impl = (VOPFUNC)NULL }
+};
+const struct vnodeopv_desc apfs_vnodeop_opv_desc = {
+ .opv_desc_vector_p = &apfs_vnodeop_p,
+ .opv_desc_ops = apfs_vnodeop_entries
+};
diff --git a/xnu/redwood.patch b/xnu/redwood.patch
index eada4c3..442b842 100644
--- a/xnu/redwood.patch
+++ b/xnu/redwood.patch
@@ -46,7 +46,7 @@ index 222158a93918..68bb0f3e56bf 100755
######################################################################
# HISTORY
diff --git a/bsd/conf/files b/bsd/conf/files
-index 44274016a4cf..9f1fe3efd685 100644
+index 44274016a4cf..cbbb936699fc 100644
--- a/bsd/conf/files
+++ b/bsd/conf/files
@@ -109,6 +109,31 @@ bsd/dev/munge.c optional config_requires_u32_munging
@@ -81,10 +81,13 @@ index 44274016a4cf..9f1fe3efd685 100644
bsd/dev/dev_perfmon.c optional config_perfmon
bsd/libkern/crc32.c standard
-@@ -155,6 +180,10 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfs
+@@ -155,6 +180,13 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfs
bsd/miscfs/mockfs/mockfs_fsnode.c optional mockfs
bsd/miscfs/mockfs/mockfs_vfsops.c optional mockfs
bsd/miscfs/mockfs/mockfs_vnops.c optional mockfs
++bsd/miscfs/apfs/apfs_lib.c optional apfs
++bsd/miscfs/apfs/apfs_vfsops.c optional apfs
++bsd/miscfs/apfs/apfs_vnops.c optional apfs
+bsd/miscfs/packfs/packfs_vfsops.c optional packfs
+bsd/miscfs/packfs/packfs_vnops.c optional packfs
+bsd/miscfs/packfs/packfs_zstd.c optional packfs
@@ -92,7 +95,7 @@ index 44274016a4cf..9f1fe3efd685 100644
bsd/miscfs/routefs/routefs_ops.c optional routefs
-@@ -361,6 +390,7 @@ bsd/security/audit/audit_syscalls.c standard
+@@ -361,6 +393,7 @@ bsd/security/audit/audit_syscalls.c standard
bsd/security/audit/audit_worker.c optional config_audit
bsd/pthread/pthread_shims.c standard
@@ -100,7 +103,7 @@ index 44274016a4cf..9f1fe3efd685 100644
bsd/pthread/pthread_priority.c standard
bsd/pthread/pthread_workqueue.c standard
-@@ -383,6 +413,7 @@ bsd/kern/kern_debug.c standard
+@@ -383,6 +416,7 @@ bsd/kern/kern_debug.c standard
bsd/kern/kern_symfile.c standard
bsd/kern/kern_descrip.c standard
bsd/kern/kern_guarded.c standard
@@ -921,10 +924,10 @@ index cbaa0b221894..78315a2d54cf 100644
int eofflag;
uint64_t options;
diff --git a/bsd/vfs/vfs_conf.c b/bsd/vfs/vfs_conf.c
-index bae70cda3a96..d0e50606b15e 100644
+index bae70cda3a96..444f414532f5 100644
--- a/bsd/vfs/vfs_conf.c
+++ b/bsd/vfs/vfs_conf.c
-@@ -103,6 +103,15 @@ extern struct vfsops mockfs_vfsops;
+@@ -103,6 +103,20 @@ extern struct vfsops mockfs_vfsops;
extern int mockfs_mountroot(mount_t, vnode_t, vfs_context_t);
#endif /* MOCKFS */
@@ -936,22 +939,28 @@ index bae70cda3a96..d0e50606b15e 100644
+#if RAMFS
+extern struct vfsops ramfs_vfsops;
+#endif /* RAMFS */
++
++#if APFS
++extern struct vfsops apfs_vfsops;
++extern int apfs_mountroot(mount_t, vnode_t, vfs_context_t);
++#endif /* APFS */
+
enum fs_type_num {
FT_NFS = 2,
FT_DEVFS = 19,
-@@ -110,7 +119,9 @@ enum fs_type_num {
+@@ -110,7 +124,10 @@ enum fs_type_num {
FT_ROUTEFS = 21,
FT_NULLFS = 22,
FT_BINDFS = 23,
- FT_MOCKFS = 0x6D6F636B
+ FT_MOCKFS = 0x6D6F636B,
+ FT_PACKFS = 0x7061636B,
-+ FT_RAMFS = 0x72616D66
++ FT_RAMFS = 0x72616D66,
++ FT_APFS = 0x61706673
};
int fstypenumstart = FT_BINDFS + 1;
-@@ -194,6 +205,44 @@ static struct vfstable vfstbllist[] = {
+@@ -194,6 +211,67 @@ static struct vfstable vfstbllist[] = {
},
#endif /* BINDFS */
@@ -974,6 +983,29 @@ index bae70cda3a96..d0e50606b15e 100644
+ },
+#endif /* RAMFS */
+
++#if APFS
++ /*
++ * Apple File System, read only. Before packfs so that a device holding a real
++ * APFS container is recognised as one; a device that is not comes back EINVAL and
++ * vfs_mountroot() goes on to the next.
++ */
++ {
++ .vfc_vfsops = &apfs_vfsops,
++ .vfc_name = "apfs",
++ .vfc_typenum = FT_APFS,
++ .vfc_refcount = 0,
++ .vfc_flags = MNT_LOCAL | MNT_RDONLY,
++ .vfc_mountroot = apfs_mountroot,
++ .vfc_next = NULL,
++ .vfc_reserved1 = 0,
++ .vfc_reserved2 = 0,
++ .vfc_vfsflags = VFC_VFSLOCALARGS | VFC_VFS64BITREADY | VFC_VFSNATIVEXATTR,
++ .vfc_descptr = NULL,
++ .vfc_descsize = 0,
++ .vfc_sysctl = NULL
++ },
++#endif /* APFS */
++
+#if PACKFS
+ /* Read-only boot image; must come before mockfs, which accepts any root device */
+ {
@@ -996,7 +1028,7 @@ index bae70cda3a96..d0e50606b15e 100644
#if MOCKFS
/* If we are configured for it, mockfs should always be the last standard entry (and thus the last FS we attempt mountroot with) */
{
-@@ -298,6 +347,14 @@ extern const struct vnodeopv_desc devfs_fdesc_vnodeop_opv_desc;
+@@ -298,6 +376,18 @@ extern const struct vnodeopv_desc devfs_fdesc_vnodeop_opv_desc;
extern const struct vnodeopv_desc mockfs_vnodeop_opv_desc;
#endif /* MOCKFS */
@@ -1007,11 +1039,15 @@ index bae70cda3a96..d0e50606b15e 100644
+#if RAMFS
+extern const struct vnodeopv_desc ramfs_vnodeop_opv_desc;
+#endif /* RAMFS */
++
++#if APFS
++extern const struct vnodeopv_desc apfs_vnodeop_opv_desc;
++#endif /* APFS */
+
extern const struct vnodeopv_desc nullfs_vnodeop_opv_desc;
extern const struct vnodeopv_desc bindfs_vnodeop_opv_desc;
-@@ -327,5 +384,11 @@ const struct vnodeopv_desc *vfs_opv_descs[] = {
+@@ -327,5 +417,14 @@ const struct vnodeopv_desc *vfs_opv_descs[] = {
#if MOCKFS
&mockfs_vnodeop_opv_desc,
#endif /* MOCKFS */
@@ -1021,6 +1057,9 @@ index bae70cda3a96..d0e50606b15e 100644
+#if RAMFS
+ &ramfs_vnodeop_opv_desc,
+#endif /* RAMFS */
++#if APFS
++ &apfs_vnodeop_opv_desc,
++#endif /* APFS */
NULL
};
diff --git a/bsd/vfs/vfs_lookup.c b/bsd/vfs/vfs_lookup.c
@@ -1197,20 +1236,21 @@ index 5b51e9c46a8d..6872b94631c9 100644
context.vc_thread = current_thread();
context.vc_ucred = cred;
diff --git a/config/MASTER b/config/MASTER
-index 07147cb3188b..a6e1990998c8 100644
+index 07147cb3188b..671fb11422b1 100644
--- a/config/MASTER
+++ b/config/MASTER
-@@ -113,6 +113,8 @@ options CONFIG_WORKLOOP_DEBUG # <config_workloop_debug>
+@@ -113,6 +113,9 @@ options CONFIG_WORKLOOP_DEBUG # <config_workloop_debug>
# 4.4 filesystems
#
options MOCKFS # Boot from an executable # <mockfs>
+options PACKFS # Read-only boot image filesystem # <packfs>
++options APFS # Apple File System, read only # <apfs>
+options RAMFS # Read-write filesystem in memory # <ramfs>
options FIFO # fifo support # <fifo>
options FDESC # fdesc_fs support # <fdesc>
options DEVFS # devfs support # <devfs>
diff --git a/config/MASTER.arm64.bcm2837 b/config/MASTER.arm64.bcm2837
-index 1ed75eea2052..551cfb9d5126 100644
+index 1ed75eea2052..db1bee93f003 100644
--- a/config/MASTER.arm64.bcm2837
+++ b/config/MASTER.arm64.bcm2837
@@ -16,15 +16,15 @@
@@ -1229,7 +1269,7 @@ index 1ed75eea2052..551cfb9d5126 100644
-# FILESYS_BASE = [ devfs fifo fs_compression config_protect config_mnt_rootsnap config_fse routefs namedstreams bindfs]
+# BSD_DEV = [ BSD_BASE config_netboot config_imageboot config_coredump config_vnguard ]
+# BSD_DEBUG = [ BSD_BASE config_netboot config_imageboot config_coredump config_vnguard ]
-+# FILESYS_BASE = [ devfs fifo fs_compression config_protect config_mnt_rootsnap config_fse routefs namedstreams bindfs mockfs packfs ramfs ]
++# FILESYS_BASE = [ devfs fifo fs_compression config_protect config_mnt_rootsnap config_fse routefs namedstreams bindfs mockfs packfs ramfs apfs ]
# FILESYS_RELEASE= [ FILESYS_BASE ]
# FILESYS_DEV = [ FILESYS_BASE config_union_mounts fdesc ]
# FILESYS_DEBUG = [ FILESYS_BASE config_union_mounts fdesc ]