diff --git a/bin/Makefile b/bin/Makefile
index 0ccbf5f3d175..324251299d75 100644
--- a/bin/Makefile
+++ b/bin/Makefile
@@ -52,6 +52,7 @@ SUBDIR.${MK_CHERI}+=	cheri_pthreads
 SUBDIR.${MK_CHERI}+=	helloworld
 SUBDIR.${MK_CHERI}+=	helloworld_cxx
 SUBDIR.${MK_CHERI}+=	helloworld_static
+SUBDIR.${MK_CHERI}+=	cheri_bench_malloc
 
 # Consumers of libhelloworld
 SUBDIR.${MK_LIBCHERI}+=	cheri_helloworld
diff --git a/bin/cheri_bench_malloc/Makefile b/bin/cheri_bench_malloc/Makefile
new file mode 100644
index 000000000000..3049aafbb298
--- /dev/null
+++ b/bin/cheri_bench_malloc/Makefile
@@ -0,0 +1,15 @@
+# $FreeBSD$
+
+.include <src.opts.mk>
+
+NEED_CHERI=pure
+LIBADD+=pthread
+LIBADD+=cheri_caprevoke
+
+PROG=  cheri_bench_malloc
+MAN=
+SRCS=  main.c \
+       capdirty.c \
+       malloc_comb.c
+
+.include <bsd.prog.mk>
diff --git a/bin/cheri_bench_malloc/capdirty.c b/bin/cheri_bench_malloc/capdirty.c
new file mode 100644
index 000000000000..8290540f02b3
--- /dev/null
+++ b/bin/cheri_bench_malloc/capdirty.c
@@ -0,0 +1,121 @@
+/*
+ * A benchmark for stressing the capdirty tracking.
+ *
+ * Optional arguments:
+ *
+ *   flavor: specify as OR of:
+ *     0x01 - read from each page
+ *     0x02 - write data to each page
+ *     0x04 - write capabilities to each page
+ *
+ *   npgs: arena size, in pages
+ *
+ *   iters: number of rounds of resetting the arena
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <sys/mman.h>
+#include <machine/param.h>
+
+#include "cheri_bench_malloc.h"
+
+int
+bench_capdirty_overhead(FILE *out, int argc, char **argv)
+{
+	int iters = 32;
+	int npgs = 512;
+  int flavor = 0x7;
+	char *arena = NULL;
+
+  if (argc > 1)
+  {
+    flavor = atoi(argv[1]);
+    argc--; argv++;
+  }
+
+  if (argc > 1)
+  {
+    npgs = atoi(argv[1]);
+    argc--; argv++;
+  }
+
+  if (argc > 1)
+  {
+    iters = atoi(argv[1]);
+    argc--; argv++;
+  }
+
+  fprintf(out, "# capdirty_overhead: flavor=0x%x npgs=%d iters=%d\n",
+          flavor, npgs, iters);
+
+	arena = mmap(arena, PAGE_SIZE*npgs, PROT_READ|PROT_WRITE,
+               MAP_ANON|MAP_PRIVATE, -1, 0);
+  if (arena == MAP_FAILED)
+  {
+    fprintf(out, "bail - initial mmap failed\n");
+    return -1;
+  }
+
+	for (int i = 0; i < iters; i++)
+  {
+		char *pagep;
+		void * __capability c = &pagep;
+		int sum = 0;
+
+		arena = mmap(arena, PAGE_SIZE*npgs,
+				PROT_READ|PROT_WRITE,
+				MAP_ANON|MAP_PRIVATE|MAP_FIXED, -1, 0);
+    if (arena == MAP_FAILED)
+    {
+      fprintf(out, "bail - remap failed\n");
+      return -2;
+    }
+
+		if (flavor & 0x1)
+    {
+			/* Read every page */
+			pagep = arena;
+			for (int j = 0; j < npgs; j++, pagep += PAGE_SIZE)
+      {
+				sum += *(int *)__builtin_assume_aligned(pagep, sizeof(int));
+			}
+      if (sum != 0)
+      {
+        fprintf(out, "bail - nonzero zero\n");
+        return -3;
+      }
+		}
+
+		if (flavor & 0x2)
+    {	
+			/* Write every page */
+			pagep = arena;
+			for (int j = 0; j < npgs; j++, pagep += PAGE_SIZE)
+      {
+				*(long *)__builtin_assume_aligned(pagep, sizeof(int))
+					= 1;
+			}
+		}
+
+		if (flavor & 0x4)
+    {
+			/* Capability-write every page */
+			pagep = arena;
+			for (int j = 0; j < npgs; j++, pagep += PAGE_SIZE)
+      {
+				*(void * __capability *)
+					__builtin_assume_aligned(pagep,
+						sizeof(void * __capability))
+					= c;
+			}
+		}
+	}
+
+	munmap(arena, PAGE_SIZE*npgs);
+  return 0;
+}
+
+
diff --git a/bin/cheri_bench_malloc/cheri_bench_malloc.h b/bin/cheri_bench_malloc/cheri_bench_malloc.h
new file mode 100644
index 000000000000..813c25778857
--- /dev/null
+++ b/bin/cheri_bench_malloc/cheri_bench_malloc.h
@@ -0,0 +1,14 @@
+#ifndef _CHERI_BENCH_MALLOC_H_
+#define _CHERI_BENCH_MALLOC_H_
+
+#include <stdio.h>
+
+typedef int (*benchfn_t)(FILE *, int, char **);
+
+/* capdirty.c */
+int bench_capdirty_overhead(FILE *, int, char **);
+
+/* malloc_comb.c */
+int bench_malloc_comb(FILE *, int, char **);
+
+#endif
diff --git a/bin/cheri_bench_malloc/main.c b/bin/cheri_bench_malloc/main.c
new file mode 100644
index 000000000000..d5d32e937c2d
--- /dev/null
+++ b/bin/cheri_bench_malloc/main.c
@@ -0,0 +1,67 @@
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "cheri_bench_malloc.h"
+
+typedef struct {
+  const char *name;
+  benchfn_t benchfn;
+} benchdesc_t;
+
+static const benchdesc_t benches[] = {
+  { "capdirty_overhead", bench_capdirty_overhead },
+  { "malloc_comb", bench_malloc_comb },
+  { NULL, NULL },
+};
+
+static void
+help(FILE *out)
+{
+  const benchdesc_t *b;
+  fprintf(out, "Possible benchmarks:\n");
+  for (b = benches; b->name != NULL; b++)
+  {
+    fprintf(out, "  %s\n", b->name);
+  }
+}
+
+int
+main(int argc, char **argv)
+{
+  int opt;
+  FILE *benchout = stdout;
+
+  while ((opt = getopt(argc, argv, "+h")) != -1)
+  {
+    switch(opt)
+    {
+    case 'h':
+      help(stdout);
+      return 0;
+    }
+  }
+
+  if (optind >= argc)
+  {
+    fprintf(stderr, "Specify benchmark\n");
+    help(stderr);
+    return 1;
+  }
+
+  const benchdesc_t *b;
+  for (b = benches; b->name != NULL; b++)
+  {
+    if (strcmp(b->name, argv[optind]) == 0)
+    {
+      break;
+    }
+  }
+  if (b == NULL)
+  {
+    fprintf(stderr, "Unknown benchmark %s\n", argv[optind]);
+    help(stderr);
+  }
+
+  return b->benchfn(benchout, argc-optind, &argv[optind]);
+}
diff --git a/bin/cheri_bench_malloc/malloc_comb.c b/bin/cheri_bench_malloc/malloc_comb.c
new file mode 100644
index 000000000000..857bccfa6146
--- /dev/null
+++ b/bin/cheri_bench_malloc/malloc_comb.c
@@ -0,0 +1,40 @@
+/*
+ * Hammer malloc with short-lived objects of a comb of sizes
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "cheri_bench_malloc.h"
+
+static const int comb_sizes[] = { 32, 512, 8192, 131072, 2097152, 33554432 };
+static const int comb_count[] = { 32,  16,    8,      4,       2,        1 };
+
+_Static_assert(sizeof(comb_sizes) == sizeof(comb_count), "bad comb sizes");
+
+int
+bench_malloc_comb(FILE *out, int argc, char **argv)
+{
+  int iters = 1024;
+
+  (void)out;
+  (void)argc;
+  (void)argv;
+
+  for(; iters > 0; iters--)
+  {
+    for(size_t cpos = 0;
+        cpos < sizeof(comb_sizes)/sizeof(comb_sizes[0]);
+        cpos++)
+    {
+      for (int op = comb_count[cpos]; op > 0; op--)
+      {
+        char *p = malloc(comb_sizes[cpos]);
+        p[0] = 1;
+        free(p);
+      }
+    }
+  }
+
+  return 0;
+}
diff --git a/bin/cheritest/Makefile b/bin/cheritest/Makefile
index 781703145272..0d7854180a77 100644
--- a/bin/cheritest/Makefile
+++ b/bin/cheritest/Makefile
@@ -31,6 +31,7 @@ CHERITEST_DIR:=	${.PARSEDIR}
 .ifdef CHERIABI_TESTS
 SRCS+=	cheritest_cheriabi.c
 SRCS+=	cheritest_cheriabi_open.c
+LIBADD+=	cheri_caprevoke
 CFLAGS+=	-DCHERIABI_TESTS
 .endif
 
@@ -82,7 +83,7 @@ WANT_CHERI=	pure
 .else
 .error Unknown cheritest variant ${PROG}
 .endif
-LIBADD= 	z
+LIBADD+= 	z
 
 LIBADD+=	xo util
 
diff --git a/bin/cheritest/cheritest.c b/bin/cheritest/cheritest.c
index af055cd6d1b2..e9c974d3e61d 100644
--- a/bin/cheritest/cheritest.c
+++ b/bin/cheritest/cheritest.c
@@ -288,6 +288,13 @@ static const struct cheri_test cheri_tests[] = {
 	  .ct_mips_exccode = T_C2E,
 	  .ct_cp2_exccode = CHERI_EXCCODE_SYSTEM_REGS },
 
+	{ .ct_name = "test_fault_cloadtags_misaligned",
+	  .ct_desc = "CLoadTags on not-cacheline-aligned address",
+	  .ct_func = test_fault_cloadtags_misaligned,
+	  .ct_flags = CT_FLAG_SIGNAL | CT_FLAG_MIPS_EXCCODE,
+	  .ct_signum = SIGBUS,
+	  .ct_mips_exccode = T_ADDR_ERR_LD, },
+
 	/*
 	 * Tests on the kernel-provided sealing capability (sealcap).
 	 */
@@ -1035,6 +1042,35 @@ static const struct cheri_test cheri_tests[] = {
 	  .ct_func = cheritest_vm_swap,
 	  .ct_check_xfail = xfail_swap_required},
 
+	{ .ct_name = "test_fault_cloadtags_mapped",
+	  .ct_desc = "CLoadTags on mapped address",
+	  .ct_func = test_cloadtags_mapped, },
+
+	{ .ct_name = "test_fault_cloadtags_unmapped",
+	  .ct_desc = "CLoadTags on unmapped address",
+	  .ct_func = test_fault_cloadtags_unmapped,
+	  .ct_flags = CT_FLAG_SIGNAL | CT_FLAG_MIPS_EXCCODE,
+	  .ct_signum = SIGSEGV,
+	  .ct_mips_exccode = T_TLB_LD_MISS, },
+
+#ifdef CHERIABI_TESTS
+	{ .ct_name = "test_caprevoke_lightly",
+	  .ct_desc = "A gentle test of capability revocation",
+	  .ct_func = test_caprevoke_lightly, },
+
+	{ .ct_name = "test_caprevoke_capdirty",
+	  .ct_desc = "Probe the interaction of revocation and capdirty",
+	  .ct_func = test_caprevoke_capdirty, },
+
+	{ .ct_name = "test_caprevoke_lib",
+	  .ct_desc = "Test libcheri_caprevoke internals",
+	  .ct_func = test_caprevoke_lib, },
+
+	{ .ct_name = "test_caprevoke_lib_fork",
+	  .ct_desc = "Test libcheri_caprevoke with fork",
+	  .ct_func = test_caprevoke_lib_fork, },
+#endif
+
 #ifdef CHERI_LIBCHERI_TESTS
 #if 0
 	/*
@@ -1157,6 +1193,10 @@ static const struct cheri_test cheri_tests[] = {
 	  .ct_desc = "Test basic handling of ptrace functionality",
 	  .ct_func = test_ptrace_basic, },
 
+	{ .ct_name = "test_aio_sival",
+	  .ct_desc = "Test pointer passing through AIO signals",
+	  .ct_func = test_aio_sival, },
+
 #ifdef CHERI_LIBCHERI_TESTS
 	/*
 	 * Test libcheri sandboxing -- and kernel sandbox unwind.
diff --git a/bin/cheritest/cheritest.h b/bin/cheritest/cheritest.h
index 6c1668b37212..b8c93e9bec9a 100644
--- a/bin/cheritest/cheritest.h
+++ b/bin/cheritest/cheritest.h
@@ -327,6 +327,7 @@ DECLARE_CHERI_TEST(test_fault_read_kr2c);
 DECLARE_CHERI_TEST(test_fault_read_kcc);
 DECLARE_CHERI_TEST(test_fault_read_kdc);
 DECLARE_CHERI_TEST(test_fault_read_epcc);
+DECLARE_CHERI_TEST(test_fault_cloadtags_misaligned);
 DECLARE_CHERI_TEST(test_nofault_ccheck_user_pass);
 
 /* cheritest_fd.c */
@@ -456,6 +457,7 @@ DECLARE_CHERI_TEST(test_sandbox_syscall);
 DECLARE_CHERI_TEST(test_sig_dfl_neq_ign);
 DECLARE_CHERI_TEST(test_sig_dfl_ign);
 DECLARE_CHERI_TEST(test_ptrace_basic);
+DECLARE_CHERI_TEST(test_aio_sival);
 
 /* cheritest_registers.c */
 DECLARE_CHERI_TEST(test_initregs_default);
@@ -493,6 +495,14 @@ DECLARE_CHERI_TEST(cheritest_vm_tag_tmpfile_private);
 DECLARE_CHERI_TEST(cheritest_vm_tag_tmpfile_private_prefault);
 DECLARE_CHERI_TEST(cheritest_vm_cow_read);
 DECLARE_CHERI_TEST(cheritest_vm_cow_write);
+#ifdef CHERIABI_TESTS
+DECLARE_CHERI_TEST(test_caprevoke_lightly);
+DECLARE_CHERI_TEST(test_caprevoke_capdirty);
+DECLARE_CHERI_TEST(test_caprevoke_lib);
+DECLARE_CHERI_TEST(test_caprevoke_lib_fork);
+#endif
+DECLARE_CHERI_TEST(test_cloadtags_mapped);
+DECLARE_CHERI_TEST(test_fault_cloadtags_unmapped);
 const char	*xfail_need_writable_tmp(const char *name);
 const char	*xfail_need_writable_non_tmpfs_tmp(const char *name);
 
diff --git a/bin/cheritest/cheritest_fault.c b/bin/cheritest/cheritest_fault.c
index e8e624cc0f2d..ec37c9fa423f 100644
--- a/bin/cheritest/cheritest_fault.c
+++ b/bin/cheritest/cheritest_fault.c
@@ -254,3 +254,15 @@ test_fault_read_epcc(const struct cheri_test *ctp __unused)
 
 	CHERI_CAP_PRINT(cheri_getepcc());
 }
+
+void
+test_fault_cloadtags_misaligned(const struct cheri_test *ctp __unused)
+{
+	uint64_t tags = 0xDEADFEED;
+	void * __capability p[20] __attribute__((aligned(512))) = { 0 } ;
+	void * __capability c = &p[1];
+
+	asm volatile ( "cloadtags %[tags], %[ptr]" : [tags]"+r"(tags) : [ptr]"r"(c) );
+
+	cheritest_success();
+}
diff --git a/bin/cheritest/cheritest_syscall.c b/bin/cheritest/cheritest_syscall.c
index de43b83c5b3a..9cdfa9acb10e 100644
--- a/bin/cheritest/cheritest_syscall.c
+++ b/bin/cheritest/cheritest_syscall.c
@@ -35,7 +35,9 @@
 #endif
 
 #include <sys/types.h>
+#include <sys/aio.h>
 #include <sys/signal.h>
+#include <sys/socket.h>
 #include <sys/sysctl.h>
 #include <sys/wait.h>
 #include <sys/time.h>
@@ -233,3 +235,54 @@ test_ptrace_basic(const struct cheri_test *ctp __unused)
 		exit(23);
 	}
 }
+
+static void
+test_aio_sival_handler(int sig __unused, siginfo_t *si, void *uc __unused)
+{
+	CHERITEST_VERIFY2(si->si_code == SI_ASYNCIO,
+		"Signal not asyncio?  code=%d\n", si->si_code);
+	CHERITEST_VERIFY2(si->si_value.sival_ptr == test_aio_sival_handler,
+		"Bad si_value; expected=%p got=%p\n",
+		test_aio_sival_handler, si->si_value.sival_ptr);
+	cheritest_success();
+}
+
+void
+test_aio_sival(const struct cheri_test *cpt __unused)
+{
+	char buf[128];
+	int pfd[2];
+	int res;
+	sigset_t sigset, osigset;
+	struct aiocb aiocb;
+	struct sigaction sa;
+
+	sa.sa_flags = SA_SIGINFO;
+	sa.sa_sigaction = &test_aio_sival_handler;
+	res = sigaction(SIGUSR1, &sa, NULL);
+	CHERITEST_VERIFY2(res == 0, "Could not install signal handler; errno=%d", errno);
+
+	res = socketpair(AF_UNIX, SOCK_STREAM, 0, pfd);
+	CHERITEST_VERIFY2(res == 0, "Could not create socketpair; errno=%d", errno);
+
+	aiocb.aio_fildes = pfd[0];
+	aiocb.aio_buf = buf;
+	aiocb.aio_nbytes = sizeof buf;
+	aiocb.aio_lio_opcode = LIO_READ;
+
+	aiocb.aio_sigevent.sigev_notify = SIGEV_SIGNAL;
+	aiocb.aio_sigevent.sigev_signo = SIGUSR1;
+	aiocb.aio_sigevent.sigev_value.sival_ptr = test_aio_sival_handler;
+
+	res = aio_read(&aiocb);
+	CHERITEST_VERIFY2(res == 0, "Could not register aio; errno=%d", errno);
+
+	sigemptyset(&sigset);
+	sigaddset(&sigset, SIGUSR1);
+	sigprocmask(SIG_BLOCK, &sigset, &osigset);
+	close(pfd[1]);
+	sigsuspend(&osigset);
+	close(pfd[0]);
+
+	cheritest_failure_errx("Test not terminated by signal handler\n");
+}
diff --git a/bin/cheritest/cheritest_vm.c b/bin/cheritest/cheritest_vm.c
index cc0ae78385b5..60775d04477f 100644
--- a/bin/cheritest/cheritest_vm.c
+++ b/bin/cheritest/cheritest_vm.c
@@ -47,6 +47,7 @@
 #include <sys/ucontext.h>
 #include <sys/wait.h>
 
+#include <sys/caprevoke.h>
 #include <sys/event.h>
 
 #include <machine/cpuregs.h>
@@ -165,7 +166,7 @@ cheritest_vm_shm_open_anon_unix_surprise(const struct cheri_test *ctp __unused)
 
 	if (pid == 0) {
 		void * __capability * map;
-		void * __capability c;
+		void * __capability crx;
 		int fd, tag;
 		struct msghdr msg = { 0 };
 		struct cmsghdr * cmsg;
@@ -192,13 +193,11 @@ cheritest_vm_shm_open_anon_unix_surprise(const struct cheri_test *ctp __unused)
 		map = CHERITEST_CHECK_SYSCALL(mmap(NULL, getpagesize(),
 						PROT_READ, MAP_SHARED, fd,
 						0));
-		c = *map;
+		crx = *map;
 
-		fprintf(stderr, "rx cap: v:%lu b:%016jx l:%016zx o:%jx\n",
-			(unsigned long)cheri_gettag(c), cheri_getbase(c),
-			cheri_getlen(c), cheri_getoffset(c));
+		CHERI_FPRINT_PTR(stderr, crx);
 
-		tag = cheri_gettag(c);
+		tag = cheri_gettag(crx);
 		CHERITEST_VERIFY2(tag == 0, "tag read");
 
 		CHERITEST_CHECK_SYSCALL(munmap(map, getpagesize()));
@@ -208,7 +207,7 @@ cheritest_vm_shm_open_anon_unix_surprise(const struct cheri_test *ctp __unused)
 		exit(tag);
 	} else {
 		void * __capability * map;
-		void * __capability c;
+		void * __capability ctx;
 		int fd, res;
 		struct msghdr msg = { 0 };
 		struct cmsghdr * cmsg;
@@ -227,12 +226,10 @@ cheritest_vm_shm_open_anon_unix_surprise(const struct cheri_test *ctp __unused)
 
 		/* Just some pointer */
 		*map = &fd;
-		c = *map;
-		CHERITEST_VERIFY2(cheri_gettag(c) != 0, "tag written");
+		ctx = *map;
+		CHERITEST_VERIFY2(cheri_gettag(ctx) != 0, "tag written");
 
-		fprintf(stderr, "tx cap: v:%lu b:%016jx l:%016zx o:%jx\n",
-			(unsigned long)cheri_gettag(c), cheri_getbase(c),
-			cheri_getlen(c), cheri_getoffset(c));
+		CHERI_FPRINT_PTR(stderr, ctx);
 
 		CHERITEST_CHECK_SYSCALL(munmap(map, getpagesize()));
 
@@ -597,3 +594,553 @@ cheritest_vm_cow_write(const struct cheri_test *ctp __unused)
 	CHERITEST_CHECK_SYSCALL(close(fd));
 	cheritest_success();
 }
+
+/*
+ * Test a mapped and unmapped invocation of cloadtags
+ */
+
+void
+test_cloadtags_mapped(const struct cheri_test *ctp __unused)
+{
+	uint64_t tags = 0;
+	void * __capability * __capability c;
+	void * __capability * p;
+
+	p = CHERITEST_CHECK_SYSCALL(mmap(0, PAGE_SIZE, PROT_READ | PROT_WRITE,
+						MAP_ANON, -1, 0));
+	c = (__cheri_tocap void * __capability * __capability) p;
+
+	CHERITEST_VERIFY2(cheri_gettag(c) != 0, "initial cap not constructed");
+
+	p[1] = c;
+	p[2] = c;
+
+	asm volatile ( "cloadtags %[tags], %[ptr]" : [tags]"+r"(tags) : [ptr]"r"(c) );
+
+	CHERITEST_VERIFY2(tags == 0x6, "incorrect result from cloadtags");
+
+	munmap(p, PAGE_SIZE);
+	cheritest_success();
+}
+
+void
+test_fault_cloadtags_unmapped(const struct cheri_test *ctp __unused)
+{
+	uint64_t tags = 0;
+	void * __capability c;
+	void * p;
+
+	p = CHERITEST_CHECK_SYSCALL(mmap(0, PAGE_SIZE, PROT_READ | PROT_WRITE,
+						MAP_ANON, -1, 0));
+	munmap(p, PAGE_SIZE);
+	c = (__cheri_tocap void * __capability) p;
+	asm volatile ( "cloadtags %[tags], %[ptr]" : [tags]"+r"(tags) : [ptr]"r"(c) );
+}
+
+/*
+ * Revocation tests
+ */
+
+#ifdef CHERIABI_TESTS
+
+static int
+check_revoked(void * __capability r)
+{
+	return ((cheri_gettag(r) == 1)
+		&& (cheri_gettype(r) == (int64_t)(-1))
+		&& (cheri_getperm(r) == 0));
+}
+
+static void
+install_kqueue_cap(int kq, void * __capability revme)
+{
+	struct kevent ike;
+
+	EV_SET(&ike, 0x2BAD, EVFILT_USER, EV_ADD|EV_ONESHOT|EV_DISABLE,
+		NOTE_FFNOP, 0, revme);
+	CHERITEST_CHECK_SYSCALL(kevent(kq, &ike, 1, NULL, 0, NULL));
+	EV_SET(&ike, 0x2BAD, EVFILT_USER, EV_KEEPUDATA,
+		NOTE_FFNOP|NOTE_TRIGGER, 0, NULL);
+	CHERITEST_CHECK_SYSCALL(kevent(kq, &ike, 1, NULL, 0, NULL));
+}
+
+static void
+check_kqueue_cap(int kq, unsigned int valid)
+{
+	struct kevent ike, oke = { 0 };
+
+	EV_SET(&ike, 0x2BAD, EVFILT_USER, EV_ENABLE|EV_KEEPUDATA,
+		NOTE_FFNOP, 0, NULL);
+	CHERITEST_CHECK_SYSCALL(kevent(kq, &ike, 1, NULL, 0, NULL));
+	CHERITEST_CHECK_SYSCALL(kevent(kq, NULL, 0, &oke, 1, NULL));
+	CHERITEST_VERIFY2(oke.ident == 0x2BAD, "Bad identifier from kqueue");
+	CHERITEST_VERIFY2(oke.filter == EVFILT_USER, "Bad filter from kqueue");
+	CHERITEST_VERIFY2(check_revoked(oke.udata) == !valid,
+				"kqueue-held cap not as expected");
+}
+
+static void
+fprintf_caprevoke_stats(FILE *f, struct caprevoke_stats crst, uint32_t cycsum)
+{
+	fprintf(f, "revoke:"
+		" einit=%" PRIu64
+		" efini=%" PRIu64
+		" psro=%" PRIu32
+		" psrw=%" PRIu32
+		" scanc=%" PRIu64
+		" psk=%" PRIu32
+		" pskf=%" PRIu32
+		" pfro=%" PRIu32
+		" pfrw=%" PRIu32
+		" prty=%" PRIu32
+		" caps=%" PRIu32
+		" crevd=%" PRIu32
+		" cnuke=%" PRIu32
+		" totc=%" PRIu32 "\n",
+		crst.epoch_init,
+		crst.epoch_fini,
+		crst.pages_scan_ro,
+		crst.pages_scan_rw,
+		crst.page_scan_cycles,
+		crst.pages_skip,
+		crst.pages_skip_fast,
+		crst.pages_faulted_ro,
+		crst.pages_faulted_rw,
+		crst.pages_retried,
+		crst.caps_found,
+		crst.caps_found_revoked,
+		crst.caps_cleared,
+		cycsum);
+}
+
+void
+test_caprevoke_lightly(const struct cheri_test *ctp __unused)
+{
+	void * __capability * __capability mb;
+	void * __capability sh;
+	const volatile struct caprevoke_info * __capability cri;
+	void * __capability revme;
+	struct caprevoke_stats crst;
+	int kq;
+	uint32_t cyc_start, cyc_end;
+
+	kq = CHERITEST_CHECK_SYSCALL(kqueue());
+	mb = CHERITEST_CHECK_SYSCALL(mmap(0, PAGE_SIZE, PROT_READ | PROT_WRITE,
+					  MAP_ANON, -1, 0));
+	CHERITEST_CHECK_SYSCALL(caprevoke_shadow(CAPREVOKE_SHADOW_NOVMMAP,
+						 mb, &sh));
+
+	CHERITEST_CHECK_SYSCALL(
+		caprevoke_shadow(CAPREVOKE_SHADOW_INFO_STRUCT, NULL,
+				 __DEQUALIFY_CAP(void * __capability *,&cri)));
+
+	/*
+	 * OK, armed with the shadow mapping... generate a capability to
+	 * the 0th granule of the map, spill it to the 1st granule,
+	 * stash it in the kqueue, and mark it as revoked in the shadow.
+	 */
+	revme = cheri_andperm(mb, ~CHERI_PERM_CHERIABI_VMMAP);
+	((void * __capability *)mb)[1] = revme;
+	install_kqueue_cap(kq, revme);
+
+	((uint8_t * __capability) sh)[0] = 1;
+
+	/*
+	 * First, let's see if we can shoot down just the hoarders and not
+	 * the VM.  We'll put the thing back and do a full pass momentarily.
+	 */
+	CHERITEST_CHECK_SYSCALL(caprevoke(CAPREVOKE_JUST_HOARDERS, 0, &crst));
+
+	check_kqueue_cap(kq, 0);
+	CHERITEST_VERIFY2(!check_revoked(mb[1]), "JUST cleared memory tag");
+
+	/* OK, full pass */
+	install_kqueue_cap(kq, revme);
+
+	cyc_start = cheri_get_cyclecount();
+	CHERITEST_CHECK_SYSCALL(caprevoke(CAPREVOKE_LAST_PASS|CAPREVOKE_IGNORE_START, 0, &crst));
+	cyc_end = cheri_get_cyclecount();
+
+	fprintf_caprevoke_stats(stderr, crst, cyc_end - cyc_start);
+
+	CHERITEST_VERIFY2(cri->epoch_dequeue == crst.epoch_fini, "Bad shared clock");
+
+	CHERITEST_VERIFY2(check_revoked(mb[1]), "Memory tag persists");
+	check_kqueue_cap(kq, 0);
+
+	/* Clear the revocation bit and do that again */
+	((uint8_t * __capability) sh)[0] = 0;
+
+	/*
+	 * We don't derive exactly the same thing, to prevent CSE from
+	 * firing.  More specifically, we adjust the offset first, taking
+	 * the path through the commutation diagram that doesn't share an
+	 * edge with the derivation above.
+	 */
+	revme = cheri_andperm(mb+1, ~CHERI_PERM_CHERIABI_VMMAP);
+	CHERITEST_VERIFY2(!check_revoked(revme), "Tag clear on 2nd revme?");
+	((void * __capability *)mb)[1] = revme;
+	install_kqueue_cap(kq, revme);
+
+	cyc_start = cheri_get_cyclecount();
+	CHERITEST_CHECK_SYSCALL(caprevoke(CAPREVOKE_IGNORE_START, 0, &crst));
+	cyc_end = cheri_get_cyclecount();
+
+	CHERITEST_VERIFY2(crst.epoch_fini >= crst.epoch_init + 1, "Bad epoch clock state");
+	fprintf_caprevoke_stats(stderr, crst, cyc_end - cyc_start);
+
+	CHERITEST_VERIFY2(cri->epoch_dequeue == crst.epoch_fini, "Bad shared clock");
+
+	cyc_start = cheri_get_cyclecount();
+	CHERITEST_CHECK_SYSCALL(caprevoke(CAPREVOKE_LAST_PASS, crst.epoch_init, &crst));
+	cyc_end = cheri_get_cyclecount();
+
+	fprintf_caprevoke_stats(stderr, crst, cyc_end - cyc_start);
+
+	CHERITEST_VERIFY2(cri->epoch_dequeue == crst.epoch_fini, "Bad shared clock");
+
+	CHERITEST_VERIFY2(!check_revoked(mb[1]), "Memory tag cleared");
+
+	check_kqueue_cap(kq, 1);
+
+	munmap(mb, PAGE_SIZE);
+	close(kq);
+
+	cheritest_success();
+}
+
+void
+test_caprevoke_capdirty(const struct cheri_test *ctp __unused)
+{
+	void * __capability * __capability mb;
+	void * __capability sh;
+	const volatile struct caprevoke_info * __capability cri;
+	void * __capability revme;
+	struct caprevoke_stats crst;
+	uint32_t cyc_start, cyc_end;
+
+	mb = CHERITEST_CHECK_SYSCALL(mmap(0, PAGE_SIZE, PROT_READ | PROT_WRITE,
+					  MAP_ANON, -1, 0));
+	CHERITEST_CHECK_SYSCALL(caprevoke_shadow(CAPREVOKE_SHADOW_NOVMMAP,
+						 mb, &sh));
+
+	CHERITEST_CHECK_SYSCALL(
+		caprevoke_shadow(CAPREVOKE_SHADOW_INFO_STRUCT, NULL,
+				 __DEQUALIFY_CAP(void * __capability *,&cri)));
+
+	revme = cheri_andperm(cheri_csetbounds(mb, 0x10),
+			      ~CHERI_PERM_CHERIABI_VMMAP);
+	mb[0] = revme;
+
+	/* Mark the start of the arena as subject to revocation */
+	((uint8_t * __capability) sh)[0] = 1;
+
+	cyc_start = cheri_get_cyclecount();
+	CHERITEST_CHECK_SYSCALL(caprevoke(CAPREVOKE_IGNORE_START, 0, &crst));
+	cyc_end = cheri_get_cyclecount();
+	fprintf_caprevoke_stats(stderr, crst, cyc_end - cyc_start);
+
+	CHERITEST_VERIFY2(cri->epoch_dequeue == crst.epoch_fini, "Bad shared clock");
+
+	CHERI_FPRINT_PTR(stderr, revme);
+	CHERI_FPRINT_PTR(stderr, mb[0]);
+
+	/* Between revocation sweeps, derive another cap and store */
+	revme = cheri_andperm(cheri_csetbounds(mb, 0x11),
+			      ~CHERI_PERM_CHERIABI_VMMAP);
+	mb[1] = revme;
+
+	cyc_start = cheri_get_cyclecount();
+	CHERITEST_CHECK_SYSCALL(caprevoke(CAPREVOKE_IGNORE_START, 0, &crst));
+	cyc_end = cheri_get_cyclecount();
+	fprintf_caprevoke_stats(stderr, crst, cyc_end - cyc_start);
+
+	CHERITEST_VERIFY2(cri->epoch_dequeue == crst.epoch_fini, "Bad shared clock");
+
+	CHERI_FPRINT_PTR(stderr, revme);
+	CHERI_FPRINT_PTR(stderr, mb[0]);
+	CHERI_FPRINT_PTR(stderr, mb[1]);
+
+	/* Between revocation sweeps, derive another cap and store */
+	revme = cheri_andperm(cheri_csetbounds(mb, 0x12),
+			      ~CHERI_PERM_CHERIABI_VMMAP);
+	mb[2] = revme;
+
+	cyc_start = cheri_get_cyclecount();
+	CHERITEST_CHECK_SYSCALL(caprevoke(CAPREVOKE_LAST_PASS|CAPREVOKE_IGNORE_START, 0, &crst));
+	cyc_end = cheri_get_cyclecount();
+	fprintf_caprevoke_stats(stderr, crst, cyc_end - cyc_start);
+
+	CHERITEST_VERIFY2(cri->epoch_dequeue == crst.epoch_fini, "Bad shared clock");
+
+	CHERI_FPRINT_PTR(stderr, revme);
+	CHERI_FPRINT_PTR(stderr, mb[0]);
+	CHERI_FPRINT_PTR(stderr, mb[1]);
+	CHERI_FPRINT_PTR(stderr, mb[2]);
+
+	CHERITEST_VERIFY2(!check_revoked(mb), "Arena revoked");
+	CHERITEST_VERIFY2(check_revoked(revme), "Register tag cleared");
+	CHERITEST_VERIFY2(check_revoked(mb[0]), "Memory tag 0 cleared");
+	CHERITEST_VERIFY2(check_revoked(mb[1]), "Memory tag 1 cleared");
+	CHERITEST_VERIFY2(check_revoked(mb[2]), "Memory tag 2 cleared");
+
+	munmap(mb, PAGE_SIZE);
+
+	cheritest_success();
+}
+
+/*
+ * Repeatedly invoke libcheri_caprevoke logic.
+ * Using a bump the pointer allocator, repeatedly grab rand()-omly sized
+ * objects and fill them with capabilities to themselves, mark them for
+ * revocation, revoke, and validate.
+ *
+ */
+
+#include <cheri/caprevoke.h>
+
+/* Just for debugging printouts */
+#ifndef CPU_CHERI
+#define CPU_CHERI
+#include <machine/pte.h>
+#include <machine/vmparam.h>
+#undef CPU_CHERI
+#else
+#include <machine/pte.h>
+#include <machine/vmparam.h>
+#endif
+
+static void
+test_caprevoke_lib_init(
+	size_t bigblock_caps,
+	void * __capability * __capability * obigblock,
+	void * __capability * oshadow,
+	const volatile struct caprevoke_info * __capability * ocri
+)
+{
+	void * __capability * __capability bigblock;
+
+	bigblock = CHERITEST_CHECK_SYSCALL(
+			mmap(0, bigblock_caps * sizeof(void * __capability),
+				PROT_READ | PROT_WRITE,
+				MAP_ANON, -1, 0));
+
+	for (size_t ix = 0; ix < bigblock_caps; ix++) {
+		/* Create self-referential VMMAP-free capabilities */
+
+		bigblock[ix] = cheri_andperm(
+				cheri_csetbounds(&bigblock[ix], 16),
+				~CHERI_PERM_CHERIABI_VMMAP);
+	}
+	*obigblock = bigblock;
+
+	CHERITEST_CHECK_SYSCALL(
+		caprevoke_shadow(CAPREVOKE_SHADOW_NOVMMAP, bigblock, oshadow));
+
+	CHERITEST_CHECK_SYSCALL(
+		caprevoke_shadow(CAPREVOKE_SHADOW_INFO_STRUCT, NULL,
+			__DEQUALIFY_CAP(void * __capability *,ocri)));
+}
+
+static void
+test_caprevoke_lib_run(
+	int verbose,
+	int paranoia,
+	size_t bigblock_caps,
+	void * __capability * __capability bigblock,
+	void * __capability shadow,
+	const volatile struct caprevoke_info * __capability cri
+)
+{
+	size_t bigblock_offset = 0;
+
+	while (bigblock_offset < bigblock_caps) {
+		struct caprevoke_stats crst;
+		uint32_t cyc_start, cyc_end;
+
+		size_t csz = rand() % 1024 + 1;
+		csz = MIN(csz, bigblock_caps - bigblock_offset);
+
+		if (verbose > 1) {
+			fprintf(stderr, "left=%zd csz=%zd\n",
+					bigblock_caps - bigblock_offset,
+					csz);
+		}
+
+		void * __capability * __capability chunk =
+			cheri_csetbounds(bigblock + bigblock_offset,
+					 csz * sizeof(void * __capability));
+
+		if (verbose > 1) {
+			CHERI_FPRINT_PTR(stderr, chunk);
+		}
+
+		size_t chunk_offset = bigblock_offset;
+		bigblock_offset += csz;
+
+		if (verbose > 3) {
+			ptrdiff_t fwo, lwo;
+			caprev_shadow_nomap_offsets((vaddr_t)chunk,
+				csz * sizeof(void * __capability), &fwo, &lwo);
+
+			fprintf(stderr,
+				"premrk fwo=%lx lwo=%lx fw=%p "
+				"*fw=%016lx *lw=%016lx\n",
+				fwo, lwo,
+				cheri_setaddress(shadow,
+					VM_CAPREVOKE_BM_MEM_NOMAP + fwo),
+				*(uint64_t *)(cheri_setaddress(shadow,
+					VM_CAPREVOKE_BM_MEM_NOMAP + fwo)),
+				*(uint64_t *)(cheri_setaddress(shadow,
+					VM_CAPREVOKE_BM_MEM_NOMAP + lwo)));
+		}
+
+		/* Mark the chunk for revocation */
+		CHERITEST_VERIFY2(caprev_shadow_nomap_set(shadow, chunk, chunk)
+				  == 0, "Shadow update collision");
+
+		__atomic_thread_fence(__ATOMIC_RELEASE);
+
+		if (verbose > 3) {
+			ptrdiff_t fwo, lwo;
+			caprev_shadow_nomap_offsets((vaddr_t)chunk,
+				csz * sizeof(void * __capability), &fwo, &lwo);
+
+			fprintf(stderr,
+				"marked fwo=%lx lwo=%lx fw=%p "
+				"*fw=%016lx *lw=%016lx\n",
+				fwo, lwo,
+				cheri_setaddress(shadow,
+					VM_CAPREVOKE_BM_MEM_NOMAP + fwo),
+				*(uint64_t *)(cheri_setaddress(shadow,
+					VM_CAPREVOKE_BM_MEM_NOMAP + fwo)),
+				*(uint64_t *)(cheri_setaddress(shadow,
+					VM_CAPREVOKE_BM_MEM_NOMAP + lwo)));
+		}
+
+		cyc_start = cheri_get_cyclecount();
+		CHERITEST_CHECK_SYSCALL(
+			caprevoke(CAPREVOKE_LAST_PASS|CAPREVOKE_IGNORE_START,
+					0, &crst));
+		cyc_end = cheri_get_cyclecount();
+		if (verbose > 2) {
+			fprintf_caprevoke_stats(stderr, crst, cyc_end - cyc_start);
+		}
+		CHERITEST_VERIFY2(cri->epoch_dequeue == crst.epoch_fini, "Bad shared clock");
+
+		/* Check the surroundings */
+		if (paranoia > 1) {
+			for (size_t ix = 0; ix < chunk_offset; ix++) {
+				CHERITEST_VERIFY2(!check_revoked(bigblock[ix]),
+						"Revoked cap incorrectly below object, at ix=%zd\n", ix);
+			}
+			for (size_t ix = chunk_offset + csz; ix < bigblock_caps; ix++) {
+				CHERITEST_VERIFY2(!check_revoked(bigblock[ix]),
+						"Revoked cap incorrectly above object, at ix=%zd\n", ix);
+			}
+		}
+
+		for (size_t ix = 0; ix < csz; ix++) {
+			if (paranoia > 0) {
+				if (!check_revoked(chunk[ix])) {
+					CHERI_FPRINT_PTR(stderr, chunk[ix]);
+					cheritest_failure_errx("Unrevoked at ix=%zd after revoke\n", ix);
+				}
+			}
+
+			/* Put it back */
+			chunk[ix] = cheri_andperm(
+					cheri_csetbounds(&chunk[ix], 16),
+					~CHERI_PERM_CHERIABI_VMMAP);
+		}
+
+		caprev_shadow_nomap_clear(shadow, chunk);
+
+		__atomic_thread_fence(__ATOMIC_RELEASE);
+
+	}
+}
+
+void
+test_caprevoke_lib(const struct cheri_test *ctp __unused)
+{
+		/* If debugging the revoker, some verbosity can help. 0 - 4. */
+	static const int verbose = 0;
+
+		/*
+		 * Tweaking paranoia can turn this test into more of a
+		 * benchmark than a correctness test.  At 0, no checks
+		 * will be performed; at 1, only the revoked object is
+		 * investigated, and at 2, the entire allocaton arena
+		 * is tested.
+		 */
+	static const int paranoia = 2;
+
+	static const size_t bigblock_caps = 4096;
+
+	void * __capability * __capability bigblock;
+	void * __capability shadow;
+	const volatile struct caprevoke_info * __capability cri;
+
+	srand(1337);
+
+	test_caprevoke_lib_init(bigblock_caps, &bigblock, &shadow, &cri);
+
+	if (verbose > 0) {
+		CHERI_FPRINT_PTR(stderr, bigblock);
+		CHERI_FPRINT_PTR(stderr, shadow);
+	}
+
+	test_caprevoke_lib_run(verbose, paranoia, bigblock_caps,
+		bigblock, shadow, cri);
+
+	munmap(bigblock, bigblock_caps * sizeof(void * __capability));
+
+	cheritest_success();
+}
+
+void
+test_caprevoke_lib_fork(const struct cheri_test *ctp __unused)
+{
+	static const int verbose = 0;
+	static const int paranoia = 2;
+
+	static const size_t bigblock_caps = 4096;
+
+	void * __capability * __capability bigblock;
+	void * __capability shadow;
+	const volatile struct caprevoke_info * __capability cri;
+
+	int pid;
+
+	srand(1337);
+
+	test_caprevoke_lib_init(bigblock_caps, &bigblock, &shadow, &cri);
+
+	if (verbose > 0) {
+		CHERI_FPRINT_PTR(stderr, bigblock);
+		CHERI_FPRINT_PTR(stderr, shadow);
+	}
+
+	pid = fork();
+	if (pid == 0) {
+		test_caprevoke_lib_run(verbose, paranoia, bigblock_caps,
+			bigblock, shadow, cri);
+	} else {
+		int res;
+
+		CHERITEST_VERIFY2(pid > 0, "fork failed");
+		waitpid(pid, &res, 0);
+		if (res == 0) {
+			cheritest_success();
+		} else {
+			cheritest_failure_errx("Bad child process exit");
+		}
+	}
+
+	munmap(bigblock, bigblock_caps * sizeof(void * __capability));
+
+	cheritest_success();
+}
+
+#endif
diff --git a/contrib/dlmalloc/.gitrepo b/contrib/dlmalloc/.gitrepo
new file mode 100644
index 000000000000..33f898a231f6
--- /dev/null
+++ b/contrib/dlmalloc/.gitrepo
@@ -0,0 +1,12 @@
+; DO NOT EDIT (unless you know what you are doing)
+;
+; This subdirectory is a git "subrepo", and this file is maintained by the
+; git-subrepo command. See https://github.com/git-commands/git-subrepo#readme
+;
+[subrepo]
+	remote = https://github.com/CTSRD-CHERI/dlmalloc_nonreuse.git
+	branch = newscheme
+	commit = 463ca9523011699be2515bff29f06b04ada02ad1
+	parent = 0927107d26123a8d5e28d5f424d42aaacc8beca0
+	method = merge
+	cmdver = 0.4.0
diff --git a/contrib/dlmalloc/Makefile b/contrib/dlmalloc/Makefile
new file mode 100644
index 000000000000..738a65cb2768
--- /dev/null
+++ b/contrib/dlmalloc/Makefile
@@ -0,0 +1,61 @@
+SDKBIN?=/home/bed22/git/llvm-project-cheri/Build/bin
+SDKROOT?=/home/bed22/bsdtools/cheribsd-root/cheribsd128
+CC=${SDKBIN}/clang -target cheri-unknown-freebsd --sysroot=${SDKROOT}
+LD=${CC} -fuse-ld=lld -B ${SDKBIN}
+DEBUG?=1
+
+CFLAGS=-Wall -Werror
+CFLAGS+=-mabi=purecap -msoft-float
+CFLAGS+=-std=c11
+CFLAGS+=-Wno-error=unused-function
+
+CFLAGS+=-DCAPREVOKE -DCHERI_SET_BOUNDS
+LDFLAGS+=-lcheri_caprevoke
+
+CFLAGS+=-DSAFE_FREEBUF
+
+ifeq ($(DEBUG),1)
+CFLAGS+=-O0
+CFLAGS+=-ggdb
+CFLAGS+=-DDEBUG=1 -DABORT_ON_ASSERT_FAILURE=1 -DVERBOSE=1
+else # DEBUG
+CFLAGS+=-O3
+CFLAGS+=-g0
+CFLAGS+=-fomit-frame-pointer
+CFLAGS+=-fno-stack-protector
+CFLAGS+=-DINSECURE=1
+
+ifneq (,$(findstring clang,$(CC)))
+ifneq (,$(findstring lld,$(LD)))
+# Use link-time optimizations if clang/lld.
+CFLAGS+=-flto
+LDFLAGS+=-O3
+LDFLAGS+=--lto-O3
+endif
+endif
+
+endif # DEBUG
+
+ifeq ($(DEBUG),1)
+libdlmalloc_nonreuse.so: dlmalloc_nonreuse.o
+	$(LD) $(CFLAGS) $(LDFLAGS) -shared -o $@ $^
+else
+libdlmalloc_nonreuse.so: dlmalloc_nonreuse.o
+	$(LD) $(CFLAGS) $(LDFLAGS) -shared $^ -o $@
+	strip $@
+endif
+
+dlmalloc_nonreuse.o: dlmalloc_nonreuse.c dlmalloc_nonreuse.h
+	$(CC) $(CFLAGS) -fPIC -c $< -o $@
+
+dlmalloc_nonreuse-dlprefix.o: dlmalloc_nonreuse.c dlmalloc_nonreuse.h
+	$(CC) $(CFLAGS) -DUSE_DL_PREFIX -c $< -o $@
+
+dlmalloc_test.o: dlmalloc_test.c
+	$(CC) $(CFLAGS) -DUSE_DL_PREFIX -c $< -o $@
+
+dlmalloc_test: dlmalloc_nonreuse-dlprefix.o dlmalloc_test.o
+	$(LD) $(CFLAGS) $(LDFLAGS) -static dlmalloc_nonreuse-dlprefix.o dlmalloc_test.o -o $@
+
+clean:
+	rm -f dlmalloc_test *.o *.so
diff --git a/contrib/dlmalloc/Makefile.cheribuild b/contrib/dlmalloc/Makefile.cheribuild
new file mode 100644
index 000000000000..1335c17bd8db
--- /dev/null
+++ b/contrib/dlmalloc/Makefile.cheribuild
@@ -0,0 +1,24 @@
+# A minimal makefile, designed to be piloted externally rather than set
+# preferences here.
+
+SRCDIR?=.
+CPPFLAGS+=-I$(SRCDIR)
+
+CFLAGS+=-g
+ifeq ($(DEBUG),1)
+# -O2 can't be debugged and -O0 is quite slow so default to -O1
+CFLAGS+=-DDEBUG=1 -DABORT_ON_ASSERT_FAILURE=1 -ggdb -DVERBOSE=1 -DINSECURE=0 -O1
+else
+# XXX NWF?
+CFLAGS+= -DINSECURE=1
+endif
+
+ifeq ($(CAPREVOKE),1)
+CFLAGS+=-DCAPREVOKE
+LDFLAGS+=-lcheri_caprevoke
+endif
+
+all: libdlmalloc_nonreuse.so
+
+libdlmalloc_nonreuse.so: $(SRCDIR)/dlmalloc_nonreuse.c $(SRCDIR)/dlmalloc_nonreuse.h
+	$(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -shared -o $@ $<
diff --git a/contrib/dlmalloc/README.md b/contrib/dlmalloc/README.md
new file mode 100644
index 000000000000..6da26eb0527d
--- /dev/null
+++ b/contrib/dlmalloc/README.md
@@ -0,0 +1,62 @@
+dlmalloc\_nonreuse
+==================
+
+This is a modified version of dlmalloc which delays the reuse of freed chunks
+and consolidate just-freed chunks before eventually returning them back to the 
+free pool. This allocator is intended to be used in conjunction with CHERI to
+perform capability revocation.
+
+Simply type make and link the final shared library "libdlmalloc\_nonreuse.so".
+Do it like this:
+
+`CC=clang LD=ld.lld DEBUG=0 gmake`
+
+`DEBUG=1` enables debugging assertions which slows down the allocator quite a
+bit. Only enable it in debugging.
+
+Global compile-time variables
+-----------------------------
+
+The following compile-time #defines are the interesting bits to change or tweak.
+They live in the header file.
+
+```
+USE_LOCKS
+USE_SPIN_LOCKS
+USE_RECURSIVE_LOCKS
+HAVE_MMAP
+MAX_RELEASE_CHECK_RATE
+FREEBUF_MODE
+DEFAULT_FREEBUF_PERCENT
+DEFAULT_SWEEP_SIZE
+SWEEP_STATS
+MALLOC_UTRACE
+```
+
+`USE_LOCKS` should be 1 for thread safety.
+
+`USE_SPIN_LOCKS` is 0 to use pthreads, but pthreads on many platforms depend on
+malloc, so define it to 1 to use simple spin locks with C11 atomics.
+
+`USE_RECURSIVE_LOCKS` should just be 0.
+
+`MAX_RELEASE_RATE` indicates how many frees there are before traversing all
+segments to release unused ones. The default value is reasonable enough.
+
+`FREEBUF_MODE` enables the delaying of freed chunks, putting them inside a
+free-buffer pool for consolidation and revocation before returning them to free
+lists. Defining it to 0 turns it into just the original dlmalloc.
+
+`DEFAULT_FREEBUF_PERCENT` is the ratio of the size of the free-buffer pool to
+that of the normal heap, default being 25%.
+
+`DEFAULT_SWEEP_SIZE` is for CHERI revocation, indicating how many chunks you
+want to sweep per sweeping pass.
+
+`SWEEP_STATS` registers the printing of statistics via `atexit()`. On some
+platforms it has to be 0 because `atexit()` may depend on malloc.
+
+`MALLOC_UTRACE` inject utrace entries for tracing. Define it to enable it. To
+collect traces, run the application with `ktrace -tu cmd args...` which
+generates a ktrace.out. Process it with `kdump -tu > trace.log` to parse the
+binary format into human readable entries.
diff --git a/contrib/dlmalloc/dlmalloc_nonreuse.c b/contrib/dlmalloc/dlmalloc_nonreuse.c
new file mode 100644
index 000000000000..c3365aceadcb
--- /dev/null
+++ b/contrib/dlmalloc/dlmalloc_nonreuse.c
@@ -0,0 +1,4079 @@
+/*-
+ * Copyright (c) 2018-2019 Hongyan Xia
+ * All rights reserved.
+ *
+ * This software was developed by SRI International and the University of
+ * Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-10-C-0237)
+ * ("CTSRD"), as part of the DARPA CRASH research programme.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * The original license header is as follows:
+ *
+ * This is a version (aka dlmalloc) of malloc/free/realloc written by
+ * Doug Lea and released to the public domain, as explained at
+ * http://creativecommons.org/publicdomain/zero/1.0/ Send questions,
+ * comments, complaints, performance data, etc to dl@cs.oswego.edu
+
+ * Version 2.8.6 Wed Aug 29 06:57:58 2012  Doug Lea
+ * Note: There may be an updated version of this malloc obtainable at
+ *       ftp://gee.cs.oswego.edu/pub/misc/malloc.c. Check before installing!
+ */
+
+#include "dlmalloc_nonreuse.h"
+
+/*------------------------------ internal #includes ---------------------- */
+
+#ifdef CAPREVOKE
+#ifndef CHERI_SET_BOUNDS
+#error "CHERI_SET_BOUNDS required for CAPREVOKE"
+#endif
+#endif
+
+#if !NO_MALLOC_STATS
+#include <stdio.h>       /* for printing in malloc_stats */
+#endif /* NO_MALLOC_STATS */
+#ifndef LACKS_ERRNO_H
+#include <errno.h>       /* for MALLOC_FAILURE_ACTION */
+#endif /* LACKS_ERRNO_H */
+#ifdef DEBUG
+#if ABORT_ON_ASSERT_FAILURE
+#undef assert
+#define assert(x) if(!(x)) ABORT
+#else /* ABORT_ON_ASSERT_FAILURE */
+#include <assert.h>
+#endif /* ABORT_ON_ASSERT_FAILURE */
+#else  /* DEBUG */
+#ifndef assert
+#define assert(x)
+#endif
+#define DEBUG 0
+#endif /* DEBUG */
+#ifdef __CHERI_PURE_CAPABILITY__
+#include <machine/cherireg.h>
+#ifdef CAPREVOKE
+#include <sys/caprevoke.h>
+#include <cheri/caprevoke.h>
+#endif /* CAPREVOKE */
+#endif /* __CHERI_PURE_CAPABILITY__ */
+#if !defined(LACKS_TIME_H)
+#include <time.h>        /* for magic initialization */
+#endif /* LACKS_TIME_H */
+#ifndef LACKS_STDLIB_H
+#include <stdlib.h>      /* for abort() */
+#endif /* LACKS_STDLIB_H */
+#ifndef LACKS_STRING_H
+#include <string.h>      /* for memset etc */
+#endif  /* LACKS_STRING_H */
+#if USE_BUILTIN_FFS
+#ifndef LACKS_STRINGS_H
+#include <strings.h>     /* for ffs */
+#endif /* LACKS_STRINGS_H */
+#endif /* USE_BUILTIN_FFS */
+#if HAVE_MMAP
+#ifndef LACKS_SYS_MMAN_H
+// On some versions of linux, __USE_MISC must be set for MAP_ANONYMOUS.
+#include<sys/mman.h> // for mmap
+#endif /* LACKS_SYS_MMAN_H */
+#ifndef LACKS_FCNTL_H
+#include <fcntl.h>
+#endif /* LACKS_FCNTL_H */
+#endif /* HAVE_MMAP */
+#ifndef LACKS_UNISTD_H
+#include <unistd.h>     /* for sysconf */
+#endif /* LACKS_UNISTD_H */
+
+/* Declarations for locking */
+#if USE_LOCKS
+#if defined (__SVR4) && defined (__sun)  /* solaris */
+#include <thread.h>
+#elif !defined(LACKS_SCHED_H)
+#include <sched.h>
+#endif /* solaris or LACKS_SCHED_H */
+#if (defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0) || !USE_SPIN_LOCKS
+#include <pthread.h>
+#endif /* USE_RECURSIVE_LOCKS ... */
+#endif /* USE_LOCKS */
+
+#ifndef LOCK_AT_FORK
+#define LOCK_AT_FORK 0
+#endif
+
+#ifndef malloc_getpagesize
+#  ifdef _SC_PAGESIZE         /* some SVR4 systems omit an underscore */
+#    ifndef _SC_PAGE_SIZE
+#      define _SC_PAGE_SIZE _SC_PAGESIZE
+#    endif
+#  endif
+#  ifdef _SC_PAGE_SIZE
+#    define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
+#  else
+#    if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
+       extern size_t getpagesize();
+#      define malloc_getpagesize getpagesize()
+#    else
+#        ifndef LACKS_SYS_PARAM_H
+#          include <sys/param.h>
+#        endif
+#        ifdef EXEC_PAGESIZE
+#          define malloc_getpagesize EXEC_PAGESIZE
+#        else
+#          ifdef NBPG
+#            ifndef CLSIZE
+#              define malloc_getpagesize NBPG
+#            else
+#              define malloc_getpagesize (NBPG * CLSIZE)
+#            endif
+#          else
+#            ifdef NBPC
+#              define malloc_getpagesize NBPC
+#            else
+#              ifdef PAGESIZE
+#                define malloc_getpagesize PAGESIZE
+#              else /* just guess */
+#                define malloc_getpagesize ((size_t)4096U)
+#              endif
+#            endif
+#          endif
+#        endif
+#    endif
+#  endif
+#endif
+
+#ifdef MALLOC_UTRACE
+#include<sys/param.h>
+#include<sys/uio.h>
+#include<sys/ktrace.h>
+static int malloc_utrace = 1;
+static int malloc_utrace_suspend = 0;
+
+typedef struct {
+  void *p;
+  size_t s;
+  void *r;
+} malloc_utrace_t;
+
+#define	UTRACE(a, b, c)\
+  if(malloc_utrace && malloc_utrace_suspend == 0) {\
+    malloc_utrace_t ut = {a, b, c};\
+    utrace(&ut, sizeof(ut));\
+  }
+#else
+#define UTRACE(a, b, c)
+#endif
+
+/* ------------------- size_t and alignment properties -------------------- */
+
+/* The byte and bit size of a size_t */
+#define SIZE_T_SIZE         (sizeof(size_t))
+#define SIZE_T_BITSIZE      (sizeof(size_t) << 3)
+
+/* Some constants coerced to size_t */
+/* Annoying but necessary to avoid errors on some platforms */
+#define SIZE_T_ZERO         ((size_t)0)
+#define SIZE_T_ONE          ((size_t)1)
+#define SIZE_T_TWO          ((size_t)2)
+#define SIZE_T_FOUR         ((size_t)4)
+#define SIZE_T_EIGHT        ((size_t)8)
+#define SIZE_T_SIXTEEN      ((size_t)16)
+#define TWO_SIZE_T_SIZES    (SIZE_T_SIZE<<1)
+#define FOUR_SIZE_T_SIZES   (SIZE_T_SIZE<<2)
+#define SIX_SIZE_T_SIZES    (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES)
+#define HALF_MAX_SIZE_T     (MAX_SIZE_T / 2U)
+
+/* The bit mask value corresponding to MALLOC_ALIGNMENT */
+#define CHUNK_ALIGN_MASK    (MALLOC_ALIGNMENT - SIZE_T_ONE)
+
+/* True if address a has acceptable alignment */
+#define is_aligned(A)       __builtin_is_aligned((A), MALLOC_ALIGNMENT)
+
+/* the number of bytes to offset an address to align it */
+#define align_offset(A)\
+  (__builtin_align_up((A), MALLOC_ALIGNMENT) - (A))
+
+/* -------------------------- MMAP preliminaries ------------------------- */
+
+/*
+   If HAVE_MMAP is false, we just define calls and
+   checks to fail so compiler optimizer can delete code rather than
+   using so many "#if"s.
+*/
+
+/* MMAP must return MFAIL on failure */
+#define MFAIL                ((void*)(MAX_SIZE_T))
+#define CMFAIL               ((char*)(MFAIL)) /* defined for convenience */
+
+#if HAVE_MMAP
+
+#define MUNMAP_DEFAULT(a, s)  munmap((a), (s))
+#define MUNMAP_SHADOW(a, s)  munmap((void*)((size_t)(a)>>MALLOC_ALIGN_BITSHIFT), (s)>>MALLOC_ALIGN_BITSHIFT)
+#define MMAP_PROT            (PROT_READ|PROT_WRITE)
+
+#if !defined(MAP_ANONYMOUS) && !defined(MAP_ANON)
+#error "Anonymous mapping must be provided. #define __USE_MISC for linux?"
+#elif !defined(MAP_ANONYMOUS)
+#define MAP_ANONYMOUS        MAP_ANON
+#endif // !defined(MAP_ANONYMOUS) && !defined(MAP_ANON)
+
+#define MMAP_FLAGS           (MAP_PRIVATE|MAP_ANONYMOUS|MAP_ALIGNED(PAGE_SHIFT+MALLOC_ALIGN_BITSHIFT))
+#define MMAP_DEFAULT(s)       mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0)
+
+#define MMAP_SHADOW_FLAGS    (MAP_PRIVATE|MAP_ANONYMOUS|MAP_32BIT|MAP_FIXED)
+#define MMAP_SHADOW(addr, s)       mmap((void*)((size_t)(addr)>>MALLOC_ALIGN_BITSHIFT), (s)>>MALLOC_ALIGN_BITSHIFT, MMAP_PROT, MMAP_SHADOW_FLAGS, -1, 0)
+
+#define DIRECT_MMAP_DEFAULT(s) MMAP_DEFAULT(s)
+#endif /* HAVE_MMAP */
+
+/**
+ * Define CALL_MMAP/CALL_MUNMAP/CALL_DIRECT_MMAP
+ */
+#if HAVE_MMAP
+    #define USE_MMAP_BIT            (SIZE_T_ONE)
+
+    #ifdef MMAP
+        #define CALL_MMAP(s)        MMAP(s)
+    #else /* MMAP */
+        #define CALL_MMAP(s)        MMAP_DEFAULT(s)
+    #endif /* MMAP */
+    #ifdef MUNMAP
+        #define CALL_MUNMAP(a, s)   MUNMAP((a), (s))
+    #else /* MUNMAP */
+        #define CALL_MUNMAP(a, s)   MUNMAP_DEFAULT((a), (s))
+    #endif /* MUNMAP */
+    #ifdef DIRECT_MMAP
+        #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s)
+    #else /* DIRECT_MMAP */
+        #define CALL_DIRECT_MMAP(s) DIRECT_MMAP_DEFAULT(s)
+    #endif /* DIRECT_MMAP */
+#else  /* HAVE_MMAP */
+    #define USE_MMAP_BIT            (SIZE_T_ZERO)
+
+    #define MMAP(s)                 MFAIL
+    #define MUNMAP(a, s)            (-1)
+    #define DIRECT_MMAP(s)          MFAIL
+    #define CALL_DIRECT_MMAP(s)     DIRECT_MMAP(s)
+    #define CALL_MMAP(s)            MMAP(s)
+    #define CALL_MUNMAP(a, s)       MUNMAP((a), (s))
+#endif /* HAVE_MMAP */
+
+#define CALL_MREMAP(addr, osz, nsz, mv)     MFAIL
+
+/* mstate bit set if continguous morecore disabled or failed */
+#define USE_NONCONTIGUOUS_BIT (4U)
+
+/* segment bit set in create_mspace_with_base */
+#define EXTERN_BIT            (8U)
+
+
+/* --------------------------- Lock preliminaries ------------------------ */
+
+/*
+  When locks are defined, there is one global lock, plus
+  one per-mspace lock.
+
+  The global lock_ensures that mparams.magic and other unique
+  mparams values are initialized only once.
+
+  Per-mspace locks surround calls to malloc, free, etc.
+  By default, locks are simple non-reentrant mutexes.
+
+  Because lock-protected regions generally have bounded times, it is
+  OK to use the supplied simple spinlocks. Spinlocks are likely to
+  improve performance for lightly contended applications, but worsen
+  performance under heavy contention.
+
+  If USE_LOCKS is > 1, the definitions of lock routines here are
+  bypassed, in which case you will need to define the type MLOCK_T,
+  and at least INITIAL_LOCK, DESTROY_LOCK, ACQUIRE_LOCK, RELEASE_LOCK
+  and TRY_LOCK.  You must also declare a
+    static MLOCK_T malloc_global_mutex = { initialization values };.
+
+*/
+
+#if !USE_LOCKS
+#define USE_LOCK_BIT               (0U)
+#define INITIAL_LOCK(l)            (0)
+#define DESTROY_LOCK(l)            (0)
+#define ACQUIRE_MALLOC_GLOBAL_LOCK()
+#define RELEASE_MALLOC_GLOBAL_LOCK()
+
+#else
+#if USE_LOCKS > 1
+/* -----------------------  User-defined locks ------------------------ */
+/* Define your own lock implementation here */
+/* #define INITIAL_LOCK(lk)  ... */
+/* #define DESTROY_LOCK(lk)  ... */
+/* #define ACQUIRE_LOCK(lk)  ... */
+/* #define RELEASE_LOCK(lk)  ... */
+/* #define TRY_LOCK(lk) ... */
+/* static MLOCK_T malloc_global_mutex = ... */
+
+#elif USE_SPIN_LOCKS
+
+// First, define CAS_LOCK and CLEAR_LOCK on atomic_flag.
+// Note CAS_LOCK defined to return 0 on success.
+// Use C11 atomics for portability.
+
+#include<stdatomic.h>
+
+#define CAS_LOCK(sl)     atomic_flag_test_and_set(sl)
+#define CLEAR_LOCK(sl)   atomic_flag_clear(sl)
+
+/* How to yield for a spin lock */
+#define SPINS_PER_YIELD       63
+#if defined (__SVR4) && defined (__sun) /* solaris */
+#define SPIN_LOCK_YIELD   thr_yield();
+#elif !defined(LACKS_SCHED_H)
+#define SPIN_LOCK_YIELD   sched_yield();
+#else
+#define SPIN_LOCK_YIELD
+#endif /* ... yield ... */
+
+#if !defined(USE_RECURSIVE_LOCKS) || USE_RECURSIVE_LOCKS == 0
+static size_t lockContended;
+/* Plain spin locks use single word (embedded in malloc_states) */
+static int
+spin_acquire_lock(atomic_flag* sl) {
+  lockContended++;
+  int spins = 0;
+  while(CAS_LOCK(sl)) {
+    if((++spins & SPINS_PER_YIELD) == 0) {
+      SPIN_LOCK_YIELD;
+    }
+  }
+  return 0;
+}
+
+#define MLOCK_T               atomic_flag
+#define TRY_LOCK(sl)          !CAS_LOCK(sl)
+#define RELEASE_LOCK(sl)      CLEAR_LOCK(sl)
+#define ACQUIRE_LOCK(sl)      (CAS_LOCK(sl)? spin_acquire_lock(sl) : 0)
+#define INITIAL_LOCK(sl)      (atomic_flag_clear(sl))
+#define DESTROY_LOCK(sl)      (0)
+static MLOCK_T malloc_global_mutex = ATOMIC_FLAG_INIT;
+
+#else /* USE_RECURSIVE_LOCKS */
+/* types for lock owners */
+
+/*
+  Note: the following assume that pthread_t is a type that can be
+  initialized to (casted) zero. If this is not the case, you will need to
+  somehow redefine these or not use spin locks.
+*/
+#define THREAD_ID_T           pthread_t
+#define CURRENT_THREAD        pthread_self()
+#define EQ_OWNER(X,Y)         pthread_equal(X, Y)
+
+struct malloc_recursive_lock {
+  atomic_flag sl;
+  unsigned int c;
+  THREAD_ID_T threadid;
+};
+
+#define MLOCK_T  struct malloc_recursive_lock
+static MLOCK_T malloc_global_mutex = { ATOMIC_FLAG_INIT, 0, (THREAD_ID_T)0};
+
+static FORCEINLINE void recursive_release_lock(MLOCK_T *lk) {
+  if (--lk->c == 0) {
+    CLEAR_LOCK(&lk->sl);
+  }
+}
+
+static FORCEINLINE int recursive_acquire_lock(MLOCK_T *lk) {
+  THREAD_ID_T mythreadid = CURRENT_THREAD;
+  int spins = 0;
+  for (;;) {
+    if (*((volatile int *)(&lk->sl)) == 0) {
+      if (!CAS_LOCK(&lk->sl)) {
+        lk->threadid = mythreadid;
+        lk->c = 1;
+        return 0;
+      }
+    }
+    else if (EQ_OWNER(lk->threadid, mythreadid)) {
+      ++lk->c;
+      return 0;
+    }
+    if ((++spins & SPINS_PER_YIELD) == 0) {
+      SPIN_LOCK_YIELD;
+    }
+  }
+}
+
+static FORCEINLINE int recursive_try_lock(MLOCK_T *lk) {
+  THREAD_ID_T mythreadid = CURRENT_THREAD;
+  if (*((volatile int *)(&lk->sl)) == 0) {
+    if (!CAS_LOCK(&lk->sl)) {
+      lk->threadid = mythreadid;
+      lk->c = 1;
+      return 1;
+    }
+  }
+  else if (EQ_OWNER(lk->threadid, mythreadid)) {
+    ++lk->c;
+    return 1;
+  }
+  return 0;
+}
+
+#define RELEASE_LOCK(lk)      recursive_release_lock(lk)
+#define TRY_LOCK(lk)          recursive_try_lock(lk)
+#define ACQUIRE_LOCK(lk)      recursive_acquire_lock(lk)
+#define INITIAL_LOCK(lk)      ((lk)->threadid = (THREAD_ID_T)0, atomic_flag_clear(&(lk)->sl), (lk)->c = 0)
+#define DESTROY_LOCK(lk)      (0)
+#endif /* USE_RECURSIVE_LOCKS */
+
+#else /* pthreads-based locks */
+#define MLOCK_T               pthread_mutex_t
+#define ACQUIRE_LOCK(lk)      pthread_mutex_lock(lk)
+#define RELEASE_LOCK(lk)      pthread_mutex_unlock(lk)
+#define TRY_LOCK(lk)          (!pthread_mutex_trylock(lk))
+#define INITIAL_LOCK(lk)      pthread_init_lock(lk)
+#define DESTROY_LOCK(lk)      pthread_mutex_destroy(lk)
+
+static MLOCK_T malloc_global_mutex = PTHREAD_MUTEX_INITIALIZER;
+
+static int pthread_init_lock (MLOCK_T *lk) {
+  pthread_mutexattr_t attr;
+  if (pthread_mutexattr_init(&attr)) return 1;
+#if defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0
+  if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) return 1;
+#endif
+  if (pthread_mutex_init(lk, &attr)) return 1;
+  if (pthread_mutexattr_destroy(&attr)) return 1;
+  return 0;
+}
+
+#endif /* ... lock types ... */
+
+/* Common code for all lock types */
+#define USE_LOCK_BIT               (2U)
+
+#ifndef ACQUIRE_MALLOC_GLOBAL_LOCK
+#define ACQUIRE_MALLOC_GLOBAL_LOCK()  ACQUIRE_LOCK(&malloc_global_mutex);
+#endif
+
+#ifndef RELEASE_MALLOC_GLOBAL_LOCK
+#define RELEASE_MALLOC_GLOBAL_LOCK()  RELEASE_LOCK(&malloc_global_mutex);
+#endif
+
+#endif /* USE_LOCKS */
+
+/* -----------------------  Chunk representations ------------------------ */
+
+/*
+  (The following includes lightly edited explanations by Colin Plumb.)
+
+  The malloc_chunk declaration below is misleading (but accurate and
+  necessary).  It declares a "view" into memory allowing access to
+  necessary fields at known offsets from a given base.
+
+  Chunks of memory are maintained using a `boundary tag' method as
+  originally described by Knuth.  (See the paper by Paul Wilson
+  ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such
+  techniques.)  Sizes of free chunks are stored both in the front of
+  each chunk and at the end.  This makes consolidating fragmented
+  chunks into bigger chunks fast.  The head fields also hold bits
+  representing whether chunks are free or in use.
+
+  Here are some pictures to make it clearer.  They are "exploded" to
+  show that the state of a chunk can be thought of as extending from
+  the high 31 bits of the head field of its header through the
+  prev_foot and PINUSE_BIT bit of the following chunk header.
+
+  A chunk that's in use looks like:
+
+   chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+           | Size of previous chunk (if P = 0)                             |
+           +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
+         | Size of this chunk                                         1| +-+
+   mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+         |                                                               |
+         +-                                                             -+
+         |                                                               |
+         +-                                                             -+
+         |                                                               :
+         +-      size - sizeof(size_t) available payload bytes          -+
+         :                                                               |
+ chunk-> +-                                                             -+
+         |                                                               |
+         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1|
+       | Size of next chunk (may or may not be in use)               | +-+
+ mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+
+    And if it's free, it looks like this:
+
+   chunk-> +-                                                             -+
+           | User payload (must be in use, or we would have merged!)       |
+           +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
+         | Size of this chunk                                         0| +-+
+   mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+         | Next pointer                                                  |
+         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+         | Prev pointer                                                  |
+         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+         |                                                               :
+         +-      size - sizeof(struct chunk) unused bytes               -+
+         :                                                               |
+ chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+         | Size of this chunk                                            |
+         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|
+       | Size of next chunk (must be in use, or we would have merged)| +-+
+ mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+       |                                                               :
+       +- User payload                                                -+
+       :                                                               |
+       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+                                                                     |0|
+                                                                     +-+
+  Note that since we always merge adjacent free chunks, the chunks
+  adjacent to a free chunk must be in use.
+
+  Given a pointer to a chunk (which can be derived trivially from the
+  payload pointer) we can, in O(1) time, find out whether the adjacent
+  chunks are free, and if so, unlink them from the lists that they
+  are on and merge them with the current chunk.
+
+  Chunks always begin on even word boundaries, so the mem portion
+  (which is returned to the user) is also on an even word boundary, and
+  thus at least double-word aligned.
+
+  The P (PINUSE_BIT) bit, stored in the unused low-order bit of the
+  chunk size (which is always a multiple of two words), is an in-use
+  bit for the *previous* chunk.  If that bit is *clear*, then the
+  word before the current chunk size contains the previous chunk
+  size, and can be used to find the front of the previous chunk.
+  The very first chunk allocated always has this bit set, preventing
+  access to non-existent (or non-owned) memory. If pinuse is set for
+  any given chunk, then you CANNOT determine the size of the
+  previous chunk, and might even get a memory addressing fault when
+  trying to do so.
+
+  The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of
+  the chunk size redundantly records whether the current chunk is
+  inuse (unless the chunk is mmapped). This redundancy enables usage
+  checks within free and realloc, and reduces indirection when freeing
+  and consolidating chunks.
+
+  Each freshly allocated chunk must have both cinuse and pinuse set.
+  That is, each allocated chunk borders either a previously allocated
+  and still in-use chunk, or the base of its memory arena. This is
+  ensured by making all allocations from the `lowest' part of any
+  found chunk.  Further, no free chunk physically borders another one,
+  so each free chunk is known to be preceded and followed by either
+  inuse chunks or the ends of memory.
+
+  Note that the `foot' of the current chunk is actually represented
+  as the prev_foot of the NEXT chunk. This makes it easier to
+  deal with alignments etc but can be very confusing when trying
+  to extend or adapt this code.
+
+  The exceptions to all this are
+
+     1. The special chunk `top' is the top-most available chunk (i.e.,
+        the one bordering the end of available memory). It is treated
+        specially.  Top is never included in any bin, is used only if
+        no other chunk is available, and is released back to the
+        system if it is very large (see M_TRIM_THRESHOLD).  In effect,
+        the top chunk is treated as larger (and thus less well
+        fitting) than any other available chunk.  The top chunk
+        doesn't update its trailing size field since there is no next
+        contiguous chunk that would have to index off it. However,
+        space is still allocated for it (TOP_FOOT_SIZE) to enable
+        separation or merging when space is extended.
+
+     3. Chunks allocated via mmap, have both cinuse and pinuse bits
+        cleared in their head fields.  Because they are allocated
+        one-by-one, each must carry its own prev_foot field, which is
+        also used to hold the offset this chunk has within its mmapped
+        region, which is needed to preserve alignment. Each mmapped
+        chunk is trailed by the first two fields of a fake next-chunk
+        for sake of usage checks.
+
+*/
+
+struct malloc_chunk {
+  size_t               prev_foot;  /* Size of previous chunk (if free).  */
+  size_t               head;       /* Size and inuse bits. */
+#ifdef __CHERI_PURE_CAPABILITY__
+  /*
+   * It is a documented requirement that struct malloc_chunk be a power
+   * of two in size.
+   * On 256-bit, there will be 16-bytes of padding before pad.
+   */
+  void* pad;
+#endif
+  struct malloc_chunk* fd;         /* double links -- used only if free. */
+  struct malloc_chunk* bk;
+};
+
+typedef struct malloc_chunk  mchunk;
+typedef struct malloc_chunk* mchunkptr;
+typedef struct malloc_chunk* sbinptr;  /* The type of bins of chunks */
+typedef unsigned int bindex_t;         /* Described below */
+typedef unsigned int binmap_t;         /* Described below */
+typedef unsigned int flag_t;           /* The type of various bit flag sets */
+
+/* ------------------- Chunks sizes and alignments ----------------------- */
+
+#define MCHUNK_SIZE         (sizeof(mchunk))
+
+#ifdef SAFE_FREEBUF
+#define	CHUNK_HEADER_OFFSET	sizeof(struct malloc_chunk)
+#else
+#define	CHUNK_HEADER_OFFSET	__offsetof(struct malloc_chunk, fd)
+#endif
+
+#define CHUNK_OVERHEAD      (CHUNK_HEADER_OFFSET)
+
+/* MMapped chunks need a second word of overhead ... */
+#define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
+/* ... and additional padding for fake next-chunk at foot */
+#define MMAP_FOOT_PAD       (FOUR_SIZE_T_SIZES)
+
+/* The smallest size we can malloc is an aligned minimal chunk */
+#ifdef SAFE_FREEBUF
+#define MIN_CHUNK_SIZE \
+  (((2 * MCHUNK_SIZE) + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
+#else
+#define MIN_CHUNK_SIZE\
+  ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
+#endif
+
+/* conversion from malloc headers to user pointers, and back */
+#define chunk2mem(p)        ((void*)((char*)(p)       + CHUNK_HEADER_OFFSET))
+#define mem2chunk(mem)      ((mchunkptr)((char*)(mem) - CHUNK_HEADER_OFFSET))
+/* chunk associated with aligned address A */
+#define align_as_chunk(A)   (mchunkptr)((A) + align_offset(chunk2mem(A)))
+
+/* Bounds on request (not chunk) sizes. */
+#define MAX_REQUEST         ((-MIN_CHUNK_SIZE) << 2)
+#define MIN_REQUEST         (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE)
+
+/* pad request bytes into a usable size */
+#define pad_request(req) \
+   (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
+
+/* pad request, checking for minimum (but not maximum) */
+#define request2size(req) \
+  (((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req))
+
+
+/* ------------------ Operations on head and foot fields ----------------- */
+
+/*
+  The head field of a chunk is or'ed with PINUSE_BIT when previous
+  adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in
+  use, unless mmapped, in which case both bits are cleared.
+
+  CDIRTY_BIT indicates whether this freed chunk is dirty (not swept) or not.
+  PDIRTY_BIT indicates whether the previous chunk is in dirty.
+  CUNMAPPED_BIT indicates that the part aligned portion of the (dirty)
+                chunk are unmapped.
+*/
+
+#define PINUSE_BIT          (SIZE_T_ONE)
+#define CINUSE_BIT          (SIZE_T_TWO)
+#define PDIRTY_BIT          (SIZE_T_FOUR)
+#define CDIRTY_BIT          (SIZE_T_EIGHT)
+#define CUNMAPPED_BIT       (SIZE_T_SIXTEEN)
+#define INUSE_BITS          (PINUSE_BIT|CINUSE_BIT)
+#define DIRTY_BITS          (PDIRTY_BIT|CDIRTY_BIT)
+#define FLAG_BITS           (PINUSE_BIT|CINUSE_BIT|CDIRTY_BIT|PDIRTY_BIT|CUNMAPPED_BIT)
+
+/* Head value for fenceposts */
+#define FENCEPOST_HEAD      (INUSE_BITS)
+
+/* extraction of fields from head words */
+#define cinuse(p)           ((p)->head & CINUSE_BIT)
+#define pinuse(p)           ((p)->head & PINUSE_BIT)
+#define cdirty(p)           ((p)->head & CDIRTY_BIT)
+#define pdirty(p)           ((p)->head & PDIRTY_BIT)
+#define cunmapped(p)        ((p)->head & CUNMAPPED_BIT)
+#define dirtybits(p)        ((p)->head & (PDIRTY_BIT|CDIRTY_BIT))
+#define inusebits(p)        ((p)->head & (PINUSE_BIT|CINUSE_BIT|CUNMAPPED_BIT))
+#define is_inuse(p)         ((((p)->head & INUSE_BITS) != PINUSE_BIT))
+#define is_mmapped(p)       (((p)->head & INUSE_BITS) == 0)
+
+#define chunksize(p)        ((p)->head & ~(FLAG_BITS))
+
+#define clear_pinuse(p)     ((p)->head &= ~PINUSE_BIT)
+#define clear_cinuse(p)     ((p)->head &= ~CINUSE_BIT)
+#define set_cdirty(p)       ((p)->head |= CDIRTY_BIT)
+#define clear_cdirty(p)     ((p)->head &= ~CDIRTY_BIT)
+#define set_pdirty(p)       ((p)->head |= PDIRTY_BIT)
+#define clear_pdirty(p)     ((p)->head &= ~PDIRTY_BIT)
+#define set_cunmapped(p)       ((p)->head |= CUNMAPPED_BIT)
+#define clear_cunmapped(p)     ((p)->head &= ~CUNMAPPED_BIT)
+
+/* Treat space at ptr +/- offset as a chunk */
+#define chunk_plus_offset(p, s)  ((mchunkptr)(((char*)(p)) + (s)))
+#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s)))
+
+/* Ptr to next or previous physical malloc_chunk. */
+#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + chunksize(p) ))
+#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) ))
+
+/* extract next chunk's pinuse bit */
+#define next_pinuse(p)  ((next_chunk(p)->head) & PINUSE_BIT)
+
+/* Get/set size at footer */
+#define get_foot(p, s)  (((mchunkptr)((char*)(p) + (s)))->prev_foot)
+#define set_foot(p, s)  (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s))
+
+#define set_size_and_clear_pdirty_of_dirty_chunk(p, s)\
+  ((p)->head = (inusebits(p)|s|CDIRTY_BIT), set_foot(p, s))
+
+/* Set size, pinuse bit, and foot */
+#define set_size_and_pinuse_of_free_chunk(p, s)\
+  ((p)->head = (pdirty(p)|s|PINUSE_BIT), set_foot(p, s))
+
+/* Set size, pinuse bit, foot, and clear next pinuse */
+#define set_free_with_pinuse(p, s, n)\
+  (clear_pinuse(n), clear_pdirty(n), set_size_and_pinuse_of_free_chunk(p, s))
+
+/* Get the internal overhead associated with chunk p */
+#define overhead_for(p)\
+ (is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD)
+
+/* Return true if malloced space is not necessarily cleared */
+#if MMAP_CLEARS
+#define calloc_must_clear(p) (!is_mmapped(p))
+#else /* MMAP_CLEARS */
+#define calloc_must_clear(p) (1)
+#endif /* MMAP_CLEARS */
+
+/* ---------------------- Overlaid data structures ----------------------- */
+
+/*
+  When chunks are not in use, they are treated as nodes of either
+  lists or trees.
+
+  "Small"  chunks are stored in circular doubly-linked lists, and look
+  like this:
+
+    chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Size of previous chunk                            |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+    `head:' |             Size of chunk, in bytes                         |P|
+      mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Forward pointer to next chunk in list             |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Back pointer to previous chunk in list            |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Unused space (may be 0 bytes long)                .
+            .                                                               .
+            .                                                               |
+nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+    `foot:' |             Size of chunk, in bytes                           |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+
+  Larger chunks are kept in a form of bitwise digital trees (aka
+  tries) keyed on chunksizes.  Because malloc_tree_chunks are only for
+  free chunks greater than 256 bytes, their size doesn't impose any
+  constraints on user chunk sizes.  Each node looks like:
+
+    chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Size of previous chunk                            |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+    `head:' |             Size of chunk, in bytes                         |P|
+      mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Forward pointer to next chunk of same size        |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Back pointer to previous chunk of same size       |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Pointer to left child (child[0])                  |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Pointer to right child (child[1])                 |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Pointer to parent                                 |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             bin index of this chunk                           |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            |             Unused space                                      .
+            .                                                               |
+nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+    `foot:' |             Size of chunk, in bytes                           |
+            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+
+  Each tree holding treenodes is a tree of unique chunk sizes.  Chunks
+  of the same size are arranged in a circularly-linked list, with only
+  the oldest chunk (the next to be used, in our FIFO ordering)
+  actually in the tree.  (Tree members are distinguished by a non-null
+  parent pointer.)  If a chunk with the same size an an existing node
+  is inserted, it is linked off the existing node using pointers that
+  work in the same way as fd/bk pointers of small chunks.
+
+  Each tree contains a power of 2 sized range of chunk sizes (the
+  smallest is 0x100 <= x < 0x180), which is is divided in half at each
+  tree level, with the chunks in the smaller half of the range (0x100
+  <= x < 0x140 for the top nose) in the left subtree and the larger
+  half (0x140 <= x < 0x180) in the right subtree.  This is, of course,
+  done by inspecting individual bits.
+
+  Using these rules, each node's left subtree contains all smaller
+  sizes than its right subtree.  However, the node at the root of each
+  subtree has no particular ordering relationship to either.  (The
+  dividing line between the subtree sizes is based on trie relation.)
+  If we remove the last chunk of a given size from the interior of the
+  tree, we need to replace it with a leaf node.  The tree ordering
+  rules permit a node to be replaced by any leaf below it.
+
+  The smallest chunk in a tree (a common operation in a best-fit
+  allocator) can be found by walking a path to the leftmost leaf in
+  the tree.  Unlike a usual binary tree, where we follow left child
+  pointers until we reach a null, here we follow the right child
+  pointer any time the left one is null, until we reach a leaf with
+  both child pointers null. The smallest chunk in the tree will be
+  somewhere along that path.
+
+  The worst case number of steps to add, find, or remove a node is
+  bounded by the number of bits differentiating chunks within
+  bins. Under current bin calculations, this ranges from 6 up to 21
+  (for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case
+  is of course much better.
+*/
+
+struct malloc_tree_chunk {
+  /* The first four(five for CHERI) fields must be compatible with malloc_chunk */
+  size_t                    prev_foot;
+  size_t                    head;
+#ifdef __CHERI_PURE_CAPABILITY__
+  /*
+   * It is a documented requirement that struct malloc_chunk be a power
+   * of two in size.
+   * On 256-bit, there will be 16-bytes of padding before pad.
+   */
+  void* pad;
+#endif
+  struct malloc_tree_chunk* fd;
+  struct malloc_tree_chunk* bk;
+
+  struct malloc_tree_chunk* child[2];
+  struct malloc_tree_chunk* parent;
+  bindex_t                  index;
+};
+
+typedef struct malloc_tree_chunk  tchunk;
+typedef struct malloc_tree_chunk* tchunkptr;
+typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */
+
+/* A little helper macro for trees */
+#define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1])
+
+/* ----------------------------- Segments -------------------------------- */
+
+/*
+  Each malloc space may include non-contiguous segments, held in a
+  list headed by an embedded malloc_segment record representing the
+  top-most space. Segments also include flags holding properties of
+  the space. Large chunks that are directly allocated by mmap are not
+  included in this list. They are instead independently created and
+  destroyed without otherwise keeping track of them.
+
+  Segment management mainly comes into play for spaces allocated by
+  MMAP.  Any call to MMAP might or might not return memory that is
+  adjacent to an existing segment.
+  When allocating using MMAP, we don't use any of the
+  hinting mechanisms (inconsistently) supported in various
+  implementations of unix mmap, or distinguish reserving from
+  committing memory. Instead, we just ask for space, and exploit
+  contiguity when we get it.  It is probably possible to do
+  better than this on some systems, but no general scheme seems
+  to be significantly better.
+
+  Management entails a simpler variant of the consolidation scheme
+  used for chunks to reduce fragmentation -- new adjacent memory is
+  normally prepended or appended to an existing segment. However,
+  there are limitations compared to chunk consolidation that mostly
+  reflect the fact that segment processing is relatively infrequent
+  (occurring only when getting memory from system) and that we
+  don't expect to have huge numbers of segments:
+
+  * Segments are not indexed, so traversal requires linear scans.  (It
+    would be possible to index these, but is not worth the extra
+    overhead and complexity for most programs on most platforms.)
+  * New segments are only appended to old ones when holding top-most
+    memory; if they cannot be prepended to others, they are held in
+    different segments.
+
+  Except for the top-most segment of an mstate, each segment record
+  is kept at the tail of its segment. Segments are added by pushing
+  segment records onto the list headed by &mstate.seg for the
+  containing mstate.
+
+  Segment flags control allocation/merge/deallocation policies:
+  * If EXTERN_BIT set, then we did not allocate this segment,
+    and so should not try to deallocate or merge with others.
+    (This currently holds only for the initial segment passed
+    into create_mspace_with_base.)
+  * If USE_MMAP_BIT set, the segment may be merged with
+    other surrounding mmapped segments and trimmed/de-allocated
+    using munmap.
+*/
+
+struct malloc_segment {
+  char*        base;             /* base address */
+  size_t       size;             /* allocated size */
+  struct malloc_segment* next;   /* ptr to next segment */
+  flag_t       sflags;           /* mmap and extern flag */
+#ifdef CAPREVOKE
+  void*        shadow;
+#endif
+};
+
+#define is_mmapped_segment(S)  ((S)->sflags & USE_MMAP_BIT)
+#define is_extern_segment(S)   ((S)->sflags & EXTERN_BIT)
+
+typedef struct malloc_segment  msegment;
+typedef struct malloc_segment* msegmentptr;
+
+/* ---------------------------- malloc_state ----------------------------- */
+
+/*
+   A malloc_state holds all of the bookkeeping for a space.
+   The main fields are:
+
+  Top
+    The topmost chunk of the currently active segment. Its size is
+    cached in topsize.  The actual size of topmost space is
+    topsize+TOP_FOOT_SIZE, which includes space reserved for adding
+    fenceposts and segment records if necessary when getting more
+    space from the system.  The size at which to autotrim top is
+    cached from mparams in trim_check, except that it is disabled if
+    an autotrim fails.
+
+  Designated victim (dv)
+    This is the preferred chunk for servicing small requests that
+    don't have exact fits.  It is normally the chunk split off most
+    recently to service another small request.  Its size is cached in
+    dvsize. The link fields of this chunk are not maintained since it
+    is not kept in a bin.
+
+  SmallBins
+    An array of bin headers for free chunks.  These bins hold chunks
+    with sizes less than MIN_LARGE_SIZE bytes. Each bin contains
+    chunks of all the same size, spaced 8 bytes apart.  To simplify
+    use in double-linked lists, each bin header acts as a malloc_chunk
+    pointing to the real first node, if it exists (else pointing to
+    itself).  This avoids special-casing for headers.  But to avoid
+    waste, we allocate only the fd/bk pointers of bins, and then use
+    repositioning tricks to treat these as the fields of a chunk.
+
+  TreeBins
+    Treebins are pointers to the roots of trees holding a range of
+    sizes. There are 2 equally spaced treebins for each power of two
+    from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything
+    larger.
+
+  Bin maps
+    There is one bit map for small bins ("smallmap") and one for
+    treebins ("treemap).  Each bin sets its bit when non-empty, and
+    clears the bit when empty.  Bit operations are then used to avoid
+    bin-by-bin searching -- nearly all "search" is done without ever
+    looking at bins that won't be selected.  The bit maps
+    conservatively use 32 bits per map word, even if on 64bit system.
+    For a good description of some of the bit-based techniques used
+    here, see Henry S. Warren Jr's book "Hacker's Delight" (and
+    supplement at http://hackersdelight.org/). Many of these are
+    intended to reduce the branchiness of paths through malloc etc, as
+    well as to reduce the number of memory locations read or written.
+
+  Segments
+    A list of segments headed by an embedded malloc_segment record
+    representing the initial space.
+
+  Address check support
+    The least_addr field is the least address ever obtained from
+    MMAP. Attempted frees and reallocs of any address less
+    than this are trapped (unless INSECURE is defined).
+
+  Magic tag
+    A cross-check field that should always hold same value as mparams.magic.
+
+  Max allowed footprint
+    The maximum allowed bytes to allocate from system (zero means no limit)
+
+  Flags
+    Bits recording whether to use MMAP, locks
+
+  Statistics
+    Each space keeps track of current and maximum system memory
+    obtained via MMAP.
+
+  Trim support
+    Fields holding the amount of unused topmost memory that should trigger
+    trimming, and a counter to force periodic scanning to release unused
+    non-topmost segments.
+
+  Locking
+    If USE_LOCKS is defined, the "mutex" lock is acquired and released
+    around every public call using this mspace.
+
+  Extension support
+    A void* pointer and a size_t field that can be used to help implement
+    extensions to this malloc.
+*/
+
+/* Bin types, widths and sizes */
+#define NSMALLBINS        (32U)
+#define NTREEBINS         (32U)
+#define SMALLBIN_SHIFT    (3U)
+#define SMALLBIN_WIDTH    (SIZE_T_ONE << SMALLBIN_SHIFT)
+#define TREEBIN_SHIFT     (8U)
+#define MIN_LARGE_SIZE    (SIZE_T_ONE << TREEBIN_SHIFT)
+#define MAX_SMALL_SIZE    (MIN_LARGE_SIZE - SIZE_T_ONE)
+#define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD)
+
+struct malloc_state {
+  binmap_t   smallmap;
+  binmap_t   treemap;
+  size_t     freebufbytes;
+  size_t     freebufsize;
+  size_t     dvsize;
+  size_t     topsize;
+  char*      least_addr;
+  mchunkptr  dv;
+  mchunkptr  top;
+  size_t     trim_check;
+  size_t     release_checks;
+  size_t     magic;
+  mchunkptr  smallbins[(NSMALLBINS+1)*2];
+  tbinptr    treebins[NTREEBINS];
+  mchunk     freebufbin;
+  size_t     footprint;
+  size_t     max_footprint;
+  size_t     footprint_limit; /* zero means no limit */
+  size_t     allocated;
+  size_t     max_allocated;
+#if SWEEP_STATS
+  size_t     sweepTimes;
+  size_t     sweptBytes;
+  size_t     freeTimes;
+  size_t     freeBytes;
+  size_t     bitsPainted;
+  size_t     bitsCleared;
+#endif // SWEEP_STATS
+  flag_t     mflags;
+#if USE_LOCKS
+  MLOCK_T    mutex;     /* locate lock among fields that rarely change */
+#endif /* USE_LOCKS */
+  msegment   seg;
+  void*      extp;      /* Unused but available for extensions */
+  size_t     exts;
+};
+
+typedef struct malloc_state*    mstate;
+
+/* ------------- Global malloc_state and malloc_params ------------------- */
+
+/*
+  malloc_params holds global properties, including those that can be
+  dynamically set using mallopt. There is a single instance, mparams,
+  initialized in init_mparams. Note that the non-zeroness of "magic"
+  also serves as an initialization flag.
+*/
+
+struct malloc_params {
+  size_t magic;
+  size_t page_size;;
+  size_t granularity;
+  size_t mmap_threshold;
+  size_t trim_threshold;
+  size_t min_freebufbytes;
+  size_t max_freebufbytes;
+  double max_freebuf_percent;
+#if SUPPORT_UNMAP
+  size_t unmap_threshold;
+#endif
+  flag_t default_mflags;
+};
+
+static struct malloc_params mparams;
+
+/* Ensure mparams initialized */
+#define ensure_initialization() (void)(mparams.magic != 0 || init_mparams())
+
+/* The global malloc_state used for all non-"mspace" calls */
+static struct malloc_state _gm_;
+#define gm                 (&_gm_)
+#define is_global(M)       ((M) == &_gm_)
+
+#define is_initialized(M)  ((M)->top != 0)
+
+/* -------------------------- system alloc setup ------------------------- */
+
+/* Operations on mflags */
+
+#define use_lock(M)           ((M)->mflags &   USE_LOCK_BIT)
+#define enable_lock(M)        ((M)->mflags |=  USE_LOCK_BIT)
+#if USE_LOCKS
+#define disable_lock(M)       ((M)->mflags &= ~USE_LOCK_BIT)
+#else
+#define disable_lock(M)
+#endif
+
+#define use_mmap(M)           ((M)->mflags &   USE_MMAP_BIT)
+#define enable_mmap(M)        ((M)->mflags |=  USE_MMAP_BIT)
+#if HAVE_MMAP
+#define disable_mmap(M)       ((M)->mflags &= ~USE_MMAP_BIT)
+#else
+#define disable_mmap(M)
+#endif
+
+#define use_noncontiguous(M)  ((M)->mflags &   USE_NONCONTIGUOUS_BIT)
+#define disable_contiguous(M) ((M)->mflags |=  USE_NONCONTIGUOUS_BIT)
+
+#define set_lock(M,L)\
+ ((M)->mflags = (L)?\
+  ((M)->mflags | USE_LOCK_BIT) :\
+  ((M)->mflags & ~USE_LOCK_BIT))
+
+/* page-align a size */
+#define page_align(S)\
+  __builtin_align_up((S), mparams.page_size)
+
+/* granularity-align a size */
+#ifndef __CHERI_PURE_CAPABILITY__
+#define granularity_align(S)\
+  __builtin_align_up((S), mparams.granularity)
+#else
+#define granularity_align(S) \
+  __builtin_cheri_round_representable_length(__builtin_align_up((S), \
+					     mparams.granularity))
+#endif
+
+#define mmap_align(S) page_align(S)
+
+/* For sys_alloc, enough padding to ensure can malloc request on success */
+#define SYS_ALLOC_PADDING (TOP_FOOT_SIZE + MALLOC_ALIGNMENT)
+
+#define is_page_aligned(S)\
+  __builtin_is_aligned((S), mparams.page_size)
+#define is_granularity_aligned(S)\
+  __builtin_is_aligned((S), mparams.granularity)
+
+/*  True if segment S holds address A */
+#define segment_holds(S, A)\
+  ((char*)(A) >= S->base && (char*)(A) < S->base + S->size)
+
+/* Return segment holding given address */
+static msegmentptr segment_holding(mstate m, char* addr) {
+  msegmentptr sp = &m->seg;
+  for (;;) {
+    if (addr >= sp->base && addr < sp->base + sp->size)
+      return sp;
+    if ((sp = sp->next) == 0)
+      return 0;
+  }
+}
+
+/* Return true if segment contains a segment link */
+static int has_segment_link(mstate m, msegmentptr ss) {
+  msegmentptr sp = &m->seg;
+  for (;;) {
+    if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size)
+      return 1;
+    if ((sp = sp->next) == 0)
+      return 0;
+  }
+}
+
+#define should_trim(M,s)  ((s) > (M)->trim_check)
+
+/*
+  TOP_FOOT_SIZE is padding at the end of a segment, including space
+  that may be needed to place segment records and fenceposts when new
+  noncontiguous segments are added.
+*/
+#define TOP_FOOT_SIZE\
+  (align_offset(CHUNK_HEADER_OFFSET)+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE)
+
+
+/* -------------------------------  Hooks -------------------------------- */
+
+/*
+  PREACTION should be defined to return 0 on success, and nonzero on
+  failure. If you are not using locking, you can redefine these to do
+  anything you like.
+*/
+
+#if USE_LOCKS
+#define PREACTION(M)  ((use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0)
+#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); }
+#else /* USE_LOCKS */
+
+#ifndef PREACTION
+#define PREACTION(M) (0)
+#endif  /* PREACTION */
+
+#ifndef POSTACTION
+#define POSTACTION(M)
+#endif  /* POSTACTION */
+
+#endif /* USE_LOCKS */
+
+/*
+  CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses.
+  USAGE_ERROR_ACTION is triggered on detected bad frees and
+  reallocs. The argument p is an address that might have triggered the
+  fault. It is ignored by the two predefined actions, but might be
+  useful in custom actions that try to help diagnose errors.
+*/
+
+// Hopefully snprintf() won't call malloc().
+#define malloc_printf(...) do { \
+    char buf[1024]; \
+    snprintf(buf, sizeof(buf), __VA_ARGS__); \
+    write(STDERR_FILENO, buf, strlen(buf)); \
+} while(0);
+
+__attribute((optnone))
+static inline void usage_error(mstate m, void *mem) {
+    malloc_printf("USAGE ERROR: mstate=%p, mem=%#p\n", m, mem);
+    abort();
+}
+
+__attribute((optnone))
+static inline void corruption_error(mstate m) {
+    malloc_printf("CORRUPTION ERROR: mstate=%#p\n", m);
+    abort();
+}
+
+#ifndef CORRUPTION_ERROR_ACTION
+#define CORRUPTION_ERROR_ACTION(m) corruption_error(m)
+#endif /* CORRUPTION_ERROR_ACTION */
+
+#ifndef USAGE_ERROR_ACTION
+#define USAGE_ERROR_ACTION(m,p) usage_error(m, p)
+#endif /* USAGE_ERROR_ACTION */
+
+/* --------------------------- CHERI support ----------------------------- */
+
+/*
+ * Bound a memory allocation and remove unneeded permissions.
+ */
+#ifndef __CHERI_PURE_CAPABILITY__
+#define	bound_ptr(mem, bytes)	(mem)
+#else
+static inline void *bound_ptr(void *mem, size_t bytes)
+{
+	void* ptr;
+
+#ifdef CHERI_SET_BOUNDS
+	ptr = __builtin_cheri_bounds_set(mem, bytes);
+#else
+	ptr = mem;
+#endif
+	ptr = __builtin_cheri_perms_and(ptr,
+	    CHERI_PERMS_USERSPACE_DATA & ~CHERI_PERM_CHERIABI_VMMAP);
+	mem2chunk(mem)->pad = mem;
+	return ptr;
+}
+#endif
+
+/*
+ * Given a memory allocation, return a pointer to it bounded to the
+ * segment it was allocated from.
+ */
+#ifndef __CHERI_PURE_CAPABILITY__
+#define	unbound_ptr(m, spp, mem)	(mem)
+#else
+static inline void *unbound_ptr(mstate m, msegmentptr *spp, void *mem)
+{
+	void* ptr;
+#ifdef CHERI_SET_BOUNDS
+	msegmentptr sp;
+
+	if (__builtin_cheri_tag_get(mem) != 1 ||
+	    __builtin_cheri_offset_get(mem) != 0)
+		USAGE_ERROR_ACTION(m, mem);
+	sp = segment_holding(m, mem);
+	if (sp == NULL)
+		USAGE_ERROR_ACTION(m, mem);
+	if (spp != NULL)
+		*spp = sp;
+	ptr = sp->base + ((char *)mem - (char *)sp->base);
+#else
+	if (__builtin_cheri_tag_get(mem) != 1)
+		USAGE_ERROR_ACTION(m, mem);
+	ptr = mem;
+#endif
+	if (ptr != mem2chunk(ptr)->pad ||
+	    (__builtin_cheri_perms_get(mem2chunk(ptr)->pad) &
+	     CHERI_PERM_CHERIABI_VMMAP) == 0)
+		USAGE_ERROR_ACTION(m, mem);
+	return ptr;
+}
+#endif
+
+/* -------------------------- Debugging setup ---------------------------- */
+
+#if ! DEBUG
+
+#define check_free_chunk(M,P)
+#define check_inuse_chunk(M,P)
+#define check_malloced_chunk(M,P,N)
+#define check_mmapped_chunk(M,P)
+#define check_malloc_state(M)
+#define check_top_chunk(M,P)
+#define check_freebuf_corrupt(M,P)
+
+#else /* DEBUG */
+#define check_free_chunk(M,P)       do_check_free_chunk(M,P)
+#define check_inuse_chunk(M,P)      do_check_inuse_chunk(M,P)
+#define check_top_chunk(M,P)        do_check_top_chunk(M,P)
+#define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N)
+#define check_mmapped_chunk(M,P)    do_check_mmapped_chunk(M,P)
+#define check_malloc_state(M)       do_check_malloc_state(M)
+#define check_freebuf_corrupt(M,P)  do_check_freebuf_corrupt(M,P)
+
+static void   do_check_any_chunk(mstate m, mchunkptr p);
+static void   do_check_top_chunk(mstate m, mchunkptr p);
+static void   do_check_mmapped_chunk(mstate m, mchunkptr p);
+static void   do_check_inuse_chunk(mstate m, mchunkptr p);
+static void   do_check_free_chunk(mstate m, mchunkptr p);
+static void   do_check_malloced_chunk(mstate m, void* mem, size_t s);
+static void   do_check_tree(mstate m, tchunkptr t);
+static void   do_check_treebin(mstate m, bindex_t i);
+static void   do_check_smallbin(mstate m, bindex_t i);
+static void   do_check_malloc_state(mstate m);
+static int    bin_find(mstate m, mchunkptr x);
+static size_t traverse_and_check(mstate m);
+#endif /* DEBUG */
+
+/* ---------------------------- Indexing Bins ---------------------------- */
+
+#define is_small(s)         (((s) >> SMALLBIN_SHIFT) < NSMALLBINS)
+#define small_index(s)      (bindex_t)((s)  >> SMALLBIN_SHIFT)
+#define small_index2size(i) ((i)  << SMALLBIN_SHIFT)
+#define MIN_SMALL_INDEX     (small_index(MIN_CHUNK_SIZE))
+
+/* addressing by index. See above about smallbin repositioning */
+#define smallbin_at(M, i)   ((sbinptr)((char*)&((M)->smallbins[(i)<<1])))
+#define treebin_at(M,i)     (&((M)->treebins[i]))
+
+/* assign tree index for size S to variable I. Use x86 asm if possible  */
+#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
+#define compute_tree_index(S, I)\
+{\
+  unsigned int X = S >> TREEBIN_SHIFT;\
+  if (X == 0)\
+    I = 0;\
+  else if (X > 0xFFFF)\
+    I = NTREEBINS-1;\
+  else {\
+    unsigned int K = (unsigned) sizeof(X)*__CHAR_BIT__ - 1 - (unsigned) __builtin_clz(X); \
+    I =  (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
+  }\
+}
+
+#elif defined (__INTEL_COMPILER)
+#define compute_tree_index(S, I)\
+{\
+  size_t X = S >> TREEBIN_SHIFT;\
+  if (X == 0)\
+    I = 0;\
+  else if (X > 0xFFFF)\
+    I = NTREEBINS-1;\
+  else {\
+    unsigned int K = _bit_scan_reverse (X); \
+    I =  (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
+  }\
+}
+
+#else /* GNUC */
+#define compute_tree_index(S, I)\
+{\
+  size_t X = S >> TREEBIN_SHIFT;\
+  if (X == 0)\
+    I = 0;\
+  else if (X > 0xFFFF)\
+    I = NTREEBINS-1;\
+  else {\
+    unsigned int Y = (unsigned int)X;\
+    unsigned int N = ((Y - 0x100) >> 16) & 8;\
+    unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\
+    N += K;\
+    N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\
+    K = 14 - N + ((Y <<= K) >> 15);\
+    I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\
+  }\
+}
+#endif /* GNUC */
+
+/* Bit representing maximum resolved size in a treebin at i */
+#define bit_for_tree_index(i) \
+   (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2)
+
+/* Shift placing maximum resolved bit in a treebin at i as sign bit */
+#define leftshift_for_tree_index(i) \
+   ((i == NTREEBINS-1)? 0 : \
+    ((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2)))
+
+/* The size of the smallest chunk held in bin with index i */
+#define minsize_for_tree_index(i) \
+   ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) |  \
+   (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1)))
+
+
+/* ------------------------ Operations on bin maps ----------------------- */
+
+/* bit corresponding to given index */
+#define idx2bit(i)              ((binmap_t)(1) << (i))
+
+/* Mark/Clear bits with given index */
+#define mark_smallmap(M,i)      ((M)->smallmap |=  idx2bit(i))
+#define clear_smallmap(M,i)     ((M)->smallmap &= ~idx2bit(i))
+#define smallmap_is_marked(M,i) ((M)->smallmap &   idx2bit(i))
+
+#define mark_treemap(M,i)       ((M)->treemap  |=  idx2bit(i))
+#define clear_treemap(M,i)      ((M)->treemap  &= ~idx2bit(i))
+#define treemap_is_marked(M,i)  ((M)->treemap  &   idx2bit(i))
+
+/* isolate the least set bit of a bitmap */
+#define least_bit(x)         ((x) & -(x))
+
+/* mask with all bits to left of least bit of x on */
+#define left_bits(x)         ((x<<1) | -(x<<1))
+
+/* mask with all bits to left of or equal to least bit of x on */
+#define same_or_left_bits(x) ((x) | -(x))
+
+/* index corresponding to given bit. Use x86 asm if possible */
+
+#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
+#define compute_bit2idx(X, I)\
+{\
+  unsigned int J;\
+  J = __builtin_ctz(X); \
+  I = (bindex_t)J;\
+}
+
+#elif defined (__INTEL_COMPILER)
+#define compute_bit2idx(X, I)\
+{\
+  unsigned int J;\
+  J = _bit_scan_forward (X); \
+  I = (bindex_t)J;\
+}
+
+#elif USE_BUILTIN_FFS
+#define compute_bit2idx(X, I) I = ffs(X)-1
+
+#else
+#define compute_bit2idx(X, I)\
+{\
+  unsigned int Y = X - 1;\
+  unsigned int K = Y >> (16-4) & 16;\
+  unsigned int N = K;        Y >>= K;\
+  N += K = Y >> (8-3) &  8;  Y >>= K;\
+  N += K = Y >> (4-2) &  4;  Y >>= K;\
+  N += K = Y >> (2-1) &  2;  Y >>= K;\
+  N += K = Y >> (1-0) &  1;  Y >>= K;\
+  I = (bindex_t)(N + Y);\
+}
+#endif /* GNUC */
+
+
+/* ----------------------- Runtime Check Support ------------------------- */
+
+/*
+  For security, the main invariant is that malloc/free/etc never
+  writes to a static address other than malloc_state, unless static
+  malloc_state itself has been corrupted, which cannot occur via
+  malloc (because of these checks). In essence this means that we
+  believe all pointers, sizes, maps etc held in malloc_state, but
+  check all of those linked or offsetted from other embedded data
+  structures.  These checks are interspersed with main code in a way
+  that tends to minimize their run-time cost.
+
+  When FOOTERS is defined, in addition to range checking, we also
+  verify footer fields of inuse chunks, which can be used guarantee
+  that the mstate controlling malloc/free is intact.  This is a
+  streamlined version of the approach described by William Robertson
+  et al in "Run-time Detection of Heap-based Overflows" LISA'03
+  http://www.usenix.org/events/lisa03/tech/robertson.html The footer
+  of an inuse chunk holds the xor of its mstate and a random seed,
+  that is checked upon calls to free() and realloc().  This is
+  (probabalistically) unguessable from outside the program, but can be
+  computed by any code successfully malloc'ing any chunk, so does not
+  itself provide protection against code that has already broken
+  security through some other means.  Unlike Robertson et al, we
+  always dynamically check addresses of all offset chunks (previous,
+  next, etc). This turns out to be cheaper than relying on hashes.
+*/
+
+#if !INSECURE
+/* Check if address a is at least as high as any from MMAP */
+#define ok_address(M, a) ((char*)(a) >= (M)->least_addr)
+/* Check if address of next chunk n is higher than base chunk p */
+#define ok_next(p, n)    ((char*)(p) < (char*)(n))
+/* Check if p has inuse status */
+#define ok_inuse(p)     is_inuse(p)
+/* Check if p has its pinuse bit on */
+#define ok_pinuse(p)     pinuse(p)
+
+#else /* !INSECURE */
+#define ok_address(M, a) (1)
+#define ok_next(b, n)    (1)
+#define ok_inuse(p)      (1)
+#define ok_pinuse(p)     (1)
+#endif /* !INSECURE */
+
+#define ok_magic(M)      (1)
+
+/* In gcc, use __builtin_expect to minimize impact of checks */
+#if !INSECURE
+#if defined(__GNUC__) && __GNUC__ >= 3
+#define RTCHECK(e)  __builtin_expect(e, 1)
+#else /* GNUC */
+#define RTCHECK(e)  (e)
+#endif /* GNUC */
+#else /* !INSECURE */
+#define RTCHECK(e)  (1)
+#endif /* !INSECURE */
+
+/* macros to set up inuse chunks with or without footers */
+
+
+#define mark_inuse_foot(M,p,s)
+
+/* Macros for setting head/foot of non-mmapped chunks */
+
+/* Set cinuse bit and pinuse bit of next chunk */
+#define set_inuse(M,p,s)\
+  ((p)->head = (pdirty(p)|((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
+  ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT, clear_pdirty((mchunkptr)(((char*)(p)) + (s))))
+
+/* Set cinuse and pinuse of this chunk and pinuse of next chunk */
+#define set_inuse_and_pinuse(M,p,s)\
+  ((p)->head = (pdirty(p)|s|PINUSE_BIT|CINUSE_BIT),\
+  ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT, clear_pdirty((mchunkptr)(((char*)(p)) + (s))))
+
+/* Set size, cinuse and pinuse bit of this chunk */
+#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
+  ((p)->head = (pdirty(p)|s|PINUSE_BIT|CINUSE_BIT))
+
+
+/* ---------------------------- setting mparams -------------------------- */
+
+#if LOCK_AT_FORK
+static void pre_fork(void)         { ACQUIRE_LOCK(&(gm)->mutex); }
+static void post_fork_parent(void) { RELEASE_LOCK(&(gm)->mutex); }
+static void post_fork_child(void)  { INITIAL_LOCK(&(gm)->mutex); }
+#endif /* LOCK_AT_FORK */
+
+/* Initialize mparams */
+static int init_mparams(void) {
+  const char *valuestr;
+  char *endp;
+  ssize_t value;
+
+  ACQUIRE_MALLOC_GLOBAL_LOCK();
+  if (mparams.magic == 0) {
+    size_t magic;
+    size_t psize;
+    size_t gsize;
+
+    UTRACE(0, 0, 0);
+
+    psize = malloc_getpagesize;
+    gsize = ((DEFAULT_GRANULARITY != 0)? DEFAULT_GRANULARITY : psize);
+
+    /* Sanity-check configuration:
+       ints must be at least 4 bytes.
+       alignment must be at least 8.
+       Alignment, min chunk size, and page size must all be powers of 2.
+    */
+    if ((MAX_SIZE_T < MIN_CHUNK_SIZE)  ||
+        (sizeof(int) < 4)  ||
+        (MALLOC_ALIGNMENT < (size_t)8U) ||
+        ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) ||
+        ((MCHUNK_SIZE      & (MCHUNK_SIZE-SIZE_T_ONE))      != 0) ||
+        ((gsize            & (gsize-SIZE_T_ONE))            != 0) ||
+        ((psize            & (psize-SIZE_T_ONE))            != 0))
+      ABORT;
+    mparams.granularity = gsize;
+    mparams.page_size = psize;
+    mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD;
+    mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD;
+    mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT;
+
+    if ((valuestr = getenv("MALLOC_MAX_FREEBUF_BYTES")) != NULL) {
+      value = strtol(valuestr, &endp, 0);
+      if (value == 0 && *endp != '\0')
+        value = DEFAULT_MAX_FREEBUFBYTES;
+      if (value < 0)
+        value = MAX_SIZE_T;
+      mparams.max_freebufbytes = value;
+    } else
+      mparams.max_freebufbytes = DEFAULT_MAX_FREEBUFBYTES;
+
+    if ((valuestr = getenv("MALLOC_MIN_FREEBUF_BYTES")) != NULL) {
+      value = strtol(valuestr, &endp, 0);
+      if (value == 0 && *endp != '\0')
+        value = DEFAULT_MIN_FREEBUFBYTES;
+      if (value < 0)
+        value = MAX_SIZE_T;
+      mparams.min_freebufbytes = value;
+    } else
+      mparams.min_freebufbytes = DEFAULT_MIN_FREEBUFBYTES;
+
+    if ((valuestr = getenv("MALLOC_MAX_FREEBUF_PERCENT")) != NULL) {
+      value = strtol(valuestr, &endp, 0);
+      if (value == 0 && *endp != '\0')
+	value = DEFAULT_FREEBUF_PERCENT;
+      if (value < 0)
+	value = MAX_SIZE_T;
+      mparams.max_freebuf_percent = (double)value / 100.0;
+    } else
+      mparams.max_freebuf_percent = DEFAULT_FREEBUF_PERCENT;
+
+#if SUPPORT_UNMAP
+    if ((valuestr = getenv("MALLOC_UNMAP_THRESHOLD")) != NULL) {
+      value = strtol(valuestr, &endp, 0);
+      if (value == 0 && *endp != '\0')
+	value = DEFAULT_UNMAP_THRESHOLD;
+      if (value < 0 || value > MAX_UNMAP_THRESHOLD)
+	value = MAX_UNMAP_THRESHOLD;
+      mparams.unmap_threshold = psize * value;
+    } else
+      mparams.unmap_threshold = psize * DEFAULT_UNMAP_THRESHOLD;
+#endif
+
+    /* Set up lock for main malloc area */
+    gm->mflags = mparams.default_mflags;
+    (void)INITIAL_LOCK(&gm->mutex);
+#if LOCK_AT_FORK
+    pthread_atfork(&pre_fork, &post_fork_parent, &post_fork_child);
+#endif
+
+    {
+#if USE_DEV_RANDOM
+      int fd;
+      unsigned char buf[sizeof(size_t)];
+      /* Try to use /dev/urandom, else fall back on using time */
+      if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 &&
+          read(fd, buf, sizeof(buf)) == sizeof(buf)) {
+        magic = *((size_t *) buf);
+        close(fd);
+      }
+      else
+#endif /* USE_DEV_RANDOM */
+#if defined(LACKS_TIME_H)
+      magic = (size_t)&magic ^ (size_t)0x55555555U;
+#else
+      magic = (size_t)(time(0) ^ (size_t)0x55555555U);
+#endif
+      magic |= (size_t)8U;    /* ensure nonzero */
+      magic &= ~(size_t)7U;   /* improve chances of fault for bad values */
+      /* Until memory modes commonly available, use volatile-write */
+      (*(volatile size_t *)(&(mparams.magic))) = magic;
+    }
+  }
+
+  RELEASE_MALLOC_GLOBAL_LOCK();
+  return 1;
+}
+
+/* support for mallopt */
+static int change_mparam(int param_number, ssize_t value) {
+  size_t val;
+  ensure_initialization();
+  val = (value == -1)? MAX_SIZE_T : (size_t)value;
+  switch(param_number) {
+  case M_TRIM_THRESHOLD:
+    mparams.trim_threshold = val;
+    return 1;
+  case M_GRANULARITY:
+    if (val >= mparams.page_size && ((val & (val-1)) == 0)) {
+      mparams.granularity = val;
+      return 1;
+    }
+    else
+      return 0;
+  case M_MMAP_THRESHOLD:
+    mparams.mmap_threshold = val;
+    return 1;
+  case M_MIN_FREEBUFBYTES:
+    mparams.min_freebufbytes = val;
+    return 1;
+  case M_MAX_FREEBUFBYTES:
+    mparams.max_freebufbytes = val;
+    return 1;
+  case M_MAX_FREEBUF_PERCENT:
+    /* Values over 100 are all infinity */
+    mparams.max_freebuf_percent = val / 100.0;
+    return 1;
+#ifdef SUPPORT_UNMAP
+  case M_UNMAP_THRESHOLD:
+    mparams.unmap_threshold = value < 0 || value > MAX_UNMAP_THRESHOLD ?
+	MAX_UNMAP_THRESHOLD : (size_t)value;
+#endif
+  default:
+    return 0;
+  }
+}
+
+#if DEBUG
+/* ------------------------- Debugging Support --------------------------- */
+
+static void
+do_check_freebuf_corrupt(mstate m, mchunkptr p) {
+  mchunkptr freebinptr = &m->freebufbin;
+  /*
+   * XXX: before anything has been free'd, first freebin entry points to
+   * NULL.  Perhaps more initilization is required...
+   */
+  if (freebinptr->fd->fd == NULL)
+    return;
+  for(mchunkptr iter=freebinptr->fd; iter!=freebinptr; iter=iter->fd) {
+    assert(p != iter);
+  }
+}
+
+/* Check properties of any chunk, whether free, inuse, mmapped etc  */
+static void do_check_any_chunk(mstate m, mchunkptr p) {
+  assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
+  assert(ok_address(m, p));
+}
+
+/* Check properties of top chunk */
+static void do_check_top_chunk(mstate m, mchunkptr p) {
+  msegmentptr sp = segment_holding(m, (char*)p);
+  size_t  sz = p->head & ~FLAG_BITS; /* third-lowest bit can be set! */
+  assert(sp != 0);
+  assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
+  assert(ok_address(m, p));
+  assert(sz == m->topsize);
+  assert(sz > 0);
+  assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE);
+  assert(pinuse(p));
+  assert(!pinuse(chunk_plus_offset(p, sz)));
+}
+
+/* Check properties of (inuse) mmapped chunks */
+static void do_check_mmapped_chunk(mstate m, mchunkptr p) {
+  size_t  sz = chunksize(p);
+  size_t len = (sz + (p->prev_foot) + MMAP_FOOT_PAD);
+  assert(is_mmapped(p));
+  assert(use_mmap(m));
+  assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
+  assert(ok_address(m, p));
+  assert(!is_small(sz));
+  assert((len & (mparams.page_size-SIZE_T_ONE)) == 0);
+  assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD);
+  assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0);
+}
+
+/* Check properties of inuse chunks */
+static void do_check_inuse_chunk(mstate m, mchunkptr p) {
+  do_check_any_chunk(m, p);
+  assert(is_inuse(p));
+  assert(next_pinuse(p));
+  /* If not pinuse and not mmapped, previous chunk has OK offset */
+  assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p);
+  if (is_mmapped(p))
+    do_check_mmapped_chunk(m, p);
+}
+
+/* Check properties of free chunks */
+static void do_check_free_chunk(mstate m, mchunkptr p) {
+  size_t sz = chunksize(p);
+  mchunkptr next = chunk_plus_offset(p, sz);
+  do_check_any_chunk(m, p);
+  assert(!is_inuse(p));
+  assert(!next_pinuse(p));
+  assert (!is_mmapped(p));
+  if (p != m->dv && p != m->top) {
+    if (sz >= MIN_CHUNK_SIZE) {
+      assert((sz & CHUNK_ALIGN_MASK) == 0);
+      assert(is_aligned(chunk2mem(p)));
+      assert(next->prev_foot == sz);
+      assert(pinuse(p));
+      assert (next == m->top || is_inuse(next));
+      assert(p->fd->bk == p);
+      assert(p->bk->fd == p);
+    }
+    else  /* markers are always of size SIZE_T_SIZE */
+      assert(sz == SIZE_T_SIZE);
+  }
+}
+
+/* Check properties of malloced chunks at the point they are malloced */
+static void do_check_malloced_chunk(mstate m, void* mem, size_t s) {
+  if (mem != 0) {
+    mchunkptr p = mem2chunk(mem);
+    size_t sz = p->head & ~FLAG_BITS;
+    do_check_inuse_chunk(m, p);
+    assert((sz & CHUNK_ALIGN_MASK) == 0);
+    assert(sz >= MIN_CHUNK_SIZE);
+    assert(sz >= s);
+    /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */
+    assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE));
+  }
+}
+
+/* Check a tree and its subtrees.  */
+static void do_check_tree(mstate m, tchunkptr t) {
+  tchunkptr head = 0;
+  tchunkptr u = t;
+  bindex_t tindex = t->index;
+  size_t tsize = chunksize(t);
+  bindex_t idx;
+  compute_tree_index(tsize, idx);
+  assert(tindex == idx);
+  assert(tsize >= MIN_LARGE_SIZE);
+  assert(tsize >= minsize_for_tree_index(idx));
+  assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1))));
+
+  do { /* traverse through chain of same-sized nodes */
+    do_check_any_chunk(m, ((mchunkptr)u));
+    assert(u->index == tindex);
+    assert(chunksize(u) == tsize);
+    assert(!is_inuse(u));
+    assert(!next_pinuse(u));
+    assert(u->fd->bk == u);
+    assert(u->bk->fd == u);
+    if (u->parent == 0) {
+      assert(u->child[0] == 0);
+      assert(u->child[1] == 0);
+    }
+    else {
+      assert(head == 0); /* only one node on chain has parent */
+      head = u;
+      assert(u->parent != u);
+      assert (u->parent->child[0] == u ||
+              u->parent->child[1] == u ||
+              *((tbinptr*)(u->parent)) == u);
+      if (u->child[0] != 0) {
+        assert(u->child[0]->parent == u);
+        assert(u->child[0] != u);
+        do_check_tree(m, u->child[0]);
+      }
+      if (u->child[1] != 0) {
+        assert(u->child[1]->parent == u);
+        assert(u->child[1] != u);
+        do_check_tree(m, u->child[1]);
+      }
+      if (u->child[0] != 0 && u->child[1] != 0) {
+        assert(chunksize(u->child[0]) < chunksize(u->child[1]));
+      }
+    }
+    u = u->fd;
+  } while (u != t);
+  assert(head != 0);
+}
+
+/*  Check all the chunks in a treebin.  */
+static void do_check_treebin(mstate m, bindex_t i) {
+  tbinptr* tb = treebin_at(m, i);
+  tchunkptr t = *tb;
+  int empty = (m->treemap & (1U << i)) == 0;
+  if (t == 0)
+    assert(empty);
+  if (!empty)
+    do_check_tree(m, t);
+}
+
+/*  Check all the chunks in a smallbin.  */
+static void do_check_smallbin(mstate m, bindex_t i) {
+  sbinptr b = smallbin_at(m, i);
+  mchunkptr p = b->bk;
+  unsigned int empty = (m->smallmap & (1U << i)) == 0;
+  if (p == b)
+    assert(empty);
+  if (!empty) {
+    for (; p != b; p = p->bk) {
+      size_t size = chunksize(p);
+      mchunkptr q;
+      /* each chunk claims to be free */
+      do_check_free_chunk(m, p);
+      /* chunk belongs in bin */
+      assert(small_index(size) == i);
+      assert(p->bk == b || chunksize(p->bk) == chunksize(p));
+      /* chunk is followed by an inuse chunk */
+      q = next_chunk(p);
+      if (q->head != FENCEPOST_HEAD)
+        do_check_inuse_chunk(m, q);
+    }
+  }
+}
+
+/* Find x in a bin. Used in other check functions. */
+static int bin_find(mstate m, mchunkptr x) {
+  size_t size = chunksize(x);
+  if (is_small(size)) {
+    bindex_t sidx = small_index(size);
+    sbinptr b = smallbin_at(m, sidx);
+    if (smallmap_is_marked(m, sidx)) {
+      mchunkptr p = b;
+      do {
+        if (p == x)
+          return 1;
+      } while ((p = p->fd) != b);
+    }
+  }
+  else {
+    bindex_t tidx;
+    compute_tree_index(size, tidx);
+    if (treemap_is_marked(m, tidx)) {
+      tchunkptr t = *treebin_at(m, tidx);
+      size_t sizebits = size << leftshift_for_tree_index(tidx);
+      while (t != 0 && chunksize(t) != size) {
+        t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
+        sizebits <<= 1;
+      }
+      if (t != 0) {
+        tchunkptr u = t;
+        do {
+          if (u == (tchunkptr)x)
+            return 1;
+        } while ((u = u->fd) != t);
+      }
+    }
+  }
+  return 0;
+}
+
+/* Traverse each chunk and check it; return total */
+static size_t traverse_and_check(mstate m) {
+  size_t sum = 0;
+  if (is_initialized(m)) {
+    msegmentptr s = &m->seg;
+    sum += m->topsize + TOP_FOOT_SIZE;
+    while (s != 0) {
+      mchunkptr q = align_as_chunk(s->base);
+      mchunkptr lastq = 0;
+      assert(pinuse(q));
+      while (segment_holds(s, q) &&
+             q != m->top && q->head != FENCEPOST_HEAD) {
+        sum += chunksize(q);
+        if (is_inuse(q)) {
+          assert(!bin_find(m, q));
+          do_check_inuse_chunk(m, q);
+        }
+        else {
+          assert(q == m->dv || bin_find(m, q));
+          assert(lastq == 0 || is_inuse(lastq)); /* Not 2 consecutive free */
+          do_check_free_chunk(m, q);
+        }
+        lastq = q;
+        q = next_chunk(q);
+      }
+      s = s->next;
+    }
+  }
+  return sum;
+}
+
+
+/* Check all properties of malloc_state. */
+static void do_check_malloc_state(mstate m) {
+  bindex_t i;
+  size_t total;
+  /* check bins */
+  for (i = 0; i < NSMALLBINS; ++i)
+    do_check_smallbin(m, i);
+  for (i = 0; i < NTREEBINS; ++i)
+    do_check_treebin(m, i);
+
+  if (m->dvsize != 0) { /* check dv chunk */
+    do_check_any_chunk(m, m->dv);
+    assert(m->dvsize == chunksize(m->dv));
+    assert(m->dvsize >= MIN_CHUNK_SIZE);
+    assert(bin_find(m, m->dv) == 0);
+  }
+
+  if (m->top != 0) {   /* check top chunk */
+    do_check_top_chunk(m, m->top);
+    /*assert(m->topsize == chunksize(m->top)); redundant */
+    assert(m->topsize > 0);
+    assert(bin_find(m, m->top) == 0);
+  }
+
+  total = traverse_and_check(m);
+  assert(total <= m->footprint);
+  assert(m->footprint <= m->max_footprint);
+}
+#endif /* DEBUG */
+
+/* ----------------------------- statistics ------------------------------ */
+
+#if !NO_MALLINFO
+static struct mallinfo internal_mallinfo(mstate m) {
+  struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+  ensure_initialization();
+  if (!PREACTION(m)) {
+    check_malloc_state(m);
+    if (is_initialized(m)) {
+      size_t nfree = SIZE_T_ONE; /* top always free */
+      size_t mfree = m->topsize + TOP_FOOT_SIZE;
+      size_t sum = mfree;
+      msegmentptr s = &m->seg;
+      while (s != 0) {
+        mchunkptr q = align_as_chunk(s->base);
+        while (segment_holds(s, q) &&
+               q != m->top && q->head != FENCEPOST_HEAD) {
+          size_t sz = chunksize(q);
+          sum += sz;
+          if (!is_inuse(q)) {
+            mfree += sz;
+            ++nfree;
+          }
+          q = next_chunk(q);
+        }
+        s = s->next;
+      }
+
+      nm.arena    = sum;
+      nm.ordblks  = nfree;
+      nm.hblkhd   = m->footprint - sum;
+      nm.usmblks  = m->max_footprint;
+      nm.uordblks = m->footprint - mfree;
+      nm.fordblks = mfree;
+      nm.keepcost = m->topsize;
+    }
+
+    POSTACTION(m);
+  }
+  return nm;
+}
+#endif /* !NO_MALLINFO */
+
+#if !NO_MALLOC_STATS
+static void internal_malloc_stats(mstate m) {
+  ensure_initialization();
+  if (!PREACTION(m)) {
+    size_t allocated = 0;
+    size_t max_allocated = 0;
+    size_t maxfp = 0;
+    size_t fp = 0;
+    size_t used = 0;
+    check_malloc_state(m);
+    if (is_initialized(m)) {
+      msegmentptr s = &m->seg;
+      maxfp = m->max_footprint;
+      allocated = m->allocated;
+      max_allocated = m->max_allocated;
+      fp = m->footprint;
+      used = fp - (m->topsize + TOP_FOOT_SIZE);
+
+      while (s != 0) {
+        mchunkptr q = align_as_chunk(s->base);
+        while (segment_holds(s, q) &&
+               q != m->top && q->head != FENCEPOST_HEAD) {
+          if (!is_inuse(q))
+            used -= chunksize(q);
+          mchunkptr next = next_chunk(q);
+          // FIXME: work around infinite loop
+          if (next == q) {
+            malloc_printf("ERROR: Infinite loop in %s: q=%#p, head=0x%zx, m->top=%#p\n",
+                          __func__, q, q->head, m->top);
+            break;
+          }
+          q = next;
+        }
+        s = s->next;
+      }
+    }
+    POSTACTION(m); /* drop lock */
+    malloc_printf("max system bytes      = %10zu\n", maxfp);
+    malloc_printf("system bytes          = %10zu\n", fp);
+    malloc_printf("in use bytes          = %10zu\n", used);
+    malloc_printf("allocated bytes       = %10zu\n", allocated);
+    malloc_printf("max allocated bytes   = %10zu\n", max_allocated);
+#if USE_LOCKS && USE_SPIN_LOCKS && (!defined(USE_RECURSIVE_LOCKS) || USE_RECURSIVE_LOCKS==0)
+    malloc_printf("global lock contended = %10zu\n", lockContended);
+#endif // USE_LOCKS
+  }
+}
+#endif /* NO_MALLOC_STATS */
+
+/* ----------------------- Operations on smallbins ----------------------- */
+
+/*
+  Various forms of linking and unlinking are defined as macros.  Even
+  the ones for trees, which are very long but have very short typical
+  paths.  This is ugly but reduces reliance on inlining support of
+  compilers.
+*/
+
+// Link a free chunk into a freebufbin.
+#define insert_freebuf_chunk(M, P) {\
+  mchunkptr B = &M->freebufbin;\
+  mchunkptr L = B;\
+  if(RTCHECK(ok_address(M, B->bk) || B->bk==&M->freebufbin))\
+    L = B->bk;\
+  else {\
+    CORRUPTION_ERROR_ACTION(M);\
+  }\
+  B->bk = P;\
+  L->fd = P;\
+  P->bk = L;\
+  P->fd = B;\
+  M->freebufbytes += chunksize(P);\
+  M->freebufsize++;\
+}
+
+// Unlink a chunk from freebufbin.
+#define unlink_freebuf_chunk(M, P) {\
+  mchunkptr F = P->fd;\
+  mchunkptr B = P->bk;\
+  assert(P != B);\
+  assert(P != F);\
+  if(RTCHECK((ok_address(M, F) || F==&M->freebufbin) && F->bk == P)) { \
+    if(RTCHECK((ok_address(M, B) || B==&M->freebufbin) && B->fd == P)) {\
+      F->bk = B;\
+      B->fd = F;\
+      M->freebufbytes -= chunksize(P);\
+      M->freebufsize--;\
+    } else {\
+      CORRUPTION_ERROR_ACTION(M);\
+    }\
+  } else {\
+    CORRUPTION_ERROR_ACTION(M);\
+  }\
+}
+
+// Unlink the first chunk from freebufbin.
+#define unlink_first_freebuf_chunk(M, B, P) {\
+  mchunkptr F = P->fd;\
+  assert(P != B);\
+  assert(P != F);\
+  if(RTCHECK((ok_address(M, F) || F==&M->freebufbin) && F->bk == P)) {\
+    F->bk = B;\
+    B->fd = F;\
+    M->freebufbytes -= chunksize(P);\
+    M->freebufsize--;\
+  } else {\
+    CORRUPTION_ERROR_ACTION(M);\
+  }\
+}
+
+/* Link a free chunk into a smallbin  */
+static void insert_small_chunk(mstate M, mchunkptr P, size_t S) {
+  bindex_t I  = small_index(S);
+  mchunkptr B = smallbin_at(M, I);
+  mchunkptr F = B;
+  assert(S >= MIN_CHUNK_SIZE);
+  if (!smallmap_is_marked(M, I))
+    mark_smallmap(M, I);
+  else if (RTCHECK(ok_address(M, B->fd)))
+    F = B->fd;
+  else {
+    CORRUPTION_ERROR_ACTION(M);
+  }
+  B->fd = P;
+  F->bk = P;
+  P->fd = F;
+  P->bk = B;
+}
+
+/* Unlink a chunk from a smallbin  */
+static void unlink_small_chunk(mstate M, mchunkptr P, size_t S) {
+  mchunkptr F = P->fd;
+  mchunkptr B = P->bk;
+  bindex_t I = small_index(S);
+  assert(P != B);
+  assert(P != F);
+  assert(chunksize(P) == small_index2size(I));
+  if (RTCHECK(F == smallbin_at(M,I) || (ok_address(M, F) && F->bk == P))) { 
+    if (B == F) {
+      clear_smallmap(M, I);
+    }
+    else if (RTCHECK(B == smallbin_at(M,I) ||
+                     (ok_address(M, B) && B->fd == P))) {
+      F->bk = B;
+      B->fd = F;
+    }
+    else {
+      CORRUPTION_ERROR_ACTION(M);
+    }
+  }
+  else {
+    CORRUPTION_ERROR_ACTION(M);
+  }
+}
+
+/* Unlink the first chunk from a smallbin */
+static void unlink_first_small_chunk(mstate M, mchunkptr B, mchunkptr P,
+    bindex_t I) {
+  mchunkptr F = P->fd;
+  assert(P != B);
+  assert(P != F);
+  assert(chunksize(P) == small_index2size(I));
+  if (B == F) {
+    clear_smallmap(M, I);
+  }
+  else if (RTCHECK(ok_address(M, F) && F->bk == P)) {
+    F->bk = B;
+    B->fd = F;
+  }
+  else {
+    CORRUPTION_ERROR_ACTION(M);
+  }
+}
+
+/* Replace dv node, binning the old one */
+/* Used only when dvsize known to be small */
+#define replace_dv(M, P, S) {\
+  size_t DVS = M->dvsize;\
+  assert(is_small(DVS));\
+  if (DVS != 0) {\
+    mchunkptr DV = M->dv;\
+    insert_small_chunk(M, DV, DVS);\
+  }\
+  M->dvsize = S;\
+  M->dv = P;\
+}
+
+/* ------------------------- Operations on trees ------------------------- */
+
+/* Insert chunk into tree */
+static void insert_large_chunk(mstate M, tchunkptr X, size_t S) {
+  tbinptr* H;
+  bindex_t I;
+  compute_tree_index(S, I);
+  H = treebin_at(M, I);
+  X->index = I;
+  X->child[0] = X->child[1] = 0;
+  if (!treemap_is_marked(M, I)) {
+    mark_treemap(M, I);
+    *H = X;
+    X->parent = (tchunkptr)H;
+    X->fd = X->bk = X;
+  }
+  else {
+    tchunkptr T = *H;
+    size_t K = S << leftshift_for_tree_index(I);
+    for (;;) {
+      if (chunksize(T) != S) {
+        tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);
+        K <<= 1;
+        if (*C != 0)
+          T = *C;
+        else if (RTCHECK(ok_address(M, C))) {
+          *C = X;
+          X->parent = T;
+          X->fd = X->bk = X;
+          break;
+        }
+        else {
+          CORRUPTION_ERROR_ACTION(M);
+          break;
+        }
+      }
+      else {
+        tchunkptr F = T->fd;
+        if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {
+          T->fd = F->bk = X;
+          X->fd = F;
+          X->bk = T;
+          X->parent = 0;
+          break;
+        }
+        else {
+          CORRUPTION_ERROR_ACTION(M);
+          break;
+        }
+      }
+    }
+  }
+}
+
+/*
+  Unlink steps:
+
+  1. If x is a chained node, unlink it from its same-sized fd/bk links
+     and choose its bk node as its replacement.
+  2. If x was the last node of its size, but not a leaf node, it must
+     be replaced with a leaf node (not merely one with an open left or
+     right), to make sure that lefts and rights of descendents
+     correspond properly to bit masks.  We use the rightmost descendent
+     of x.  We could use any other leaf, but this is easy to locate and
+     tends to counteract removal of leftmosts elsewhere, and so keeps
+     paths shorter than minimally guaranteed.  This doesn't loop much
+     because on average a node in a tree is near the bottom.
+  3. If x is the base of a chain (i.e., has parent links) relink
+     x's parent and children to x's replacement (or null if none).
+*/
+
+static void unlink_large_chunk(mstate M, tchunkptr X) {
+  tchunkptr XP = X->parent;
+  tchunkptr R;
+  if (X->bk != X) {
+    tchunkptr F = X->fd;
+    R = X->bk;
+    if (RTCHECK(ok_address(M, F) && F->bk == X && R->fd == X)) {
+      F->bk = R;
+      R->fd = F;
+    }
+    else {
+      CORRUPTION_ERROR_ACTION(M);
+    }
+  }
+  else {
+    tchunkptr* RP;
+    if (((R = *(RP = &(X->child[1]))) != 0) ||
+        ((R = *(RP = &(X->child[0]))) != 0)) {
+      tchunkptr* CP;
+      while ((*(CP = &(R->child[1])) != 0) ||
+             (*(CP = &(R->child[0])) != 0)) {
+        R = *(RP = CP);
+      }
+      if (RTCHECK(ok_address(M, RP)))
+        *RP = 0;
+      else {
+        CORRUPTION_ERROR_ACTION(M);
+      }
+    }
+  }
+  if (XP != 0) {
+    tbinptr* H = treebin_at(M, X->index);
+    if (X == *H) {
+      if ((*H = R) == 0) 
+        clear_treemap(M, X->index);
+    }
+    else if (RTCHECK(ok_address(M, XP))) {
+      if (XP->child[0] == X) 
+        XP->child[0] = R;
+      else 
+        XP->child[1] = R;
+    }
+    else
+      CORRUPTION_ERROR_ACTION(M);
+    if (R != 0) {
+      if (RTCHECK(ok_address(M, R))) {
+        tchunkptr C0, C1;
+        R->parent = XP;
+        if ((C0 = X->child[0]) != 0) {
+          if (RTCHECK(ok_address(M, C0))) {
+            R->child[0] = C0;
+            C0->parent = R;
+          }
+          else
+            CORRUPTION_ERROR_ACTION(M);
+        }
+        if ((C1 = X->child[1]) != 0) {
+          if (RTCHECK(ok_address(M, C1))) {
+            R->child[1] = C1;
+            C1->parent = R;
+          }
+          else
+            CORRUPTION_ERROR_ACTION(M);
+        }
+      }
+      else
+        CORRUPTION_ERROR_ACTION(M);
+    }
+  }
+}
+
+/* Relays to large vs small bin operations */
+
+#define insert_chunk(M, P, S)\
+  if (is_small(S)) insert_small_chunk(M, P, S);\
+  else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); }
+
+#define unlink_chunk(M, P, S)\
+  if (is_small(S)) unlink_small_chunk(M, P, S);\
+  else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); }
+
+
+/* Relays to internal calls to malloc/free from realloc, memalign etc */
+
+#define internal_free(m, mem) dlfree(mem)
+
+/* -----------------------  Direct-mmapping chunks ----------------------- */
+
+/*
+  Directly mmapped chunks are set up with an offset to the start of
+  the mmapped region stored in the prev_foot field of the chunk. This
+  allows reconstruction of the required argument to MUNMAP when freed,
+  and also allows adjustment of the returned chunk to meet alignment
+  requirements (especially in memalign).
+*/
+
+/* Malloc using mmap */
+static void* mmap_alloc(mstate m, size_t nb) {
+#ifdef __CHERI_PURE_CAPABILITY__
+  /* Should never be called */
+  ABORT;
+#endif
+  size_t mmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
+  if (m->footprint_limit != 0) {
+    size_t fp = m->footprint + mmsize;
+    if (fp <= m->footprint || fp > m->footprint_limit)
+      return 0;
+  }
+  if (mmsize > nb) {     /* Check for wrap around 0 */
+    char* mm = (char*)(CALL_DIRECT_MMAP(mmsize));
+    if (mm != CMFAIL) {
+#ifndef __CHERI_PURE_CAPABILITY__
+      if(MMAP_SHADOW(mm, mmsize) != (void*)((size_t)mm>>MALLOC_ALIGN_BITSHIFT)) {
+        ABORT;
+      }
+#endif
+      size_t offset = align_offset(chunk2mem(mm));
+      size_t psize = mmsize - offset - MMAP_FOOT_PAD;
+      mchunkptr p = (mchunkptr)(mm + offset);
+      p->prev_foot = offset;
+      p->head = psize;
+      mark_inuse_foot(m, p, psize);
+      chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD;
+      chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0;
+
+      if (m->least_addr == 0 || mm < m->least_addr)
+        m->least_addr = mm;
+      if ((m->footprint += mmsize) > m->max_footprint)
+        m->max_footprint = m->footprint;
+      assert(is_aligned(chunk2mem(p)));
+      check_mmapped_chunk(m, p);
+      return chunk2mem(p);
+    }
+  }
+  return 0;
+}
+
+/* Realloc using mmap */
+static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb) {
+  size_t oldsize = chunksize(oldp);
+  if (is_small(nb)) /* Can't shrink mmap regions below small size */
+    return 0;
+  /* Keep old chunk if big enough but not too big */
+  if (oldsize >= nb + SIZE_T_SIZE &&
+      (oldsize - nb) <= (mparams.granularity << 1))
+    return oldp;
+  else {
+    return 0;
+  }
+}
+
+
+/* -------------------------- mspace management -------------------------- */
+
+/* Initialize top chunk and its size */
+static void init_top(mstate m, mchunkptr p, size_t psize) {
+  /* Ensure alignment */
+  size_t offset = align_offset(chunk2mem(p));
+  p = (mchunkptr)((char*)p + offset);
+  psize -= offset;
+
+  m->top = p;
+  m->topsize = psize;
+  p->head = dirtybits(p) | psize | PINUSE_BIT;
+  /* set size of fake trailing chunk holding overhead space only once */
+  chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE;
+  m->trim_check = mparams.trim_threshold; /* reset on each update */
+}
+
+/* Initialize bins for a new mstate that is otherwise zeroed out */
+static void init_bins(mstate m) {
+  /* Establish circular links for smallbins */
+  bindex_t i;
+  for (i = 0; i < NSMALLBINS; ++i) {
+    sbinptr bin = smallbin_at(m,i);
+    bin->fd = bin->bk = bin;
+  }
+  mchunkptr freebin = &m->freebufbin;
+  freebin->fd = freebin->bk = freebin;
+}
+
+#ifndef __CHERI_PURE_CAPABILITY__
+/* Allocate chunk and prepend remainder with chunk in successor base. */
+static void* prepend_alloc(mstate m, char* newbase, char* oldbase,
+                           size_t nb) {
+  mchunkptr p = align_as_chunk(newbase);
+  mchunkptr oldfirst = align_as_chunk(oldbase);
+  size_t psize = (char*)oldfirst - (char*)p;
+  mchunkptr q = chunk_plus_offset(p, nb);
+  size_t qsize = psize - nb;
+  set_size_and_pinuse_of_inuse_chunk(m, p, nb);
+
+  assert((char*)oldfirst > (char*)q);
+  assert(pinuse(oldfirst));
+  assert(qsize >= MIN_CHUNK_SIZE);
+
+  /* consolidate remainder with first chunk of old base */
+  if (oldfirst == m->top) {
+    size_t tsize = m->topsize += qsize;
+    m->top = q;
+    q->head = tsize | PINUSE_BIT;
+    check_top_chunk(m, q);
+  }
+  else if (oldfirst == m->dv) {
+    size_t dsize = m->dvsize += qsize;
+    m->dv = q;
+    set_size_and_pinuse_of_free_chunk(q, dsize);
+  }
+  else {
+    if (!is_inuse(oldfirst)) {
+      size_t nsize = chunksize(oldfirst);
+      unlink_chunk(m, oldfirst, nsize);
+      oldfirst = chunk_plus_offset(oldfirst, nsize);
+      qsize += nsize;
+    }
+    set_free_with_pinuse(q, qsize, oldfirst);
+    insert_chunk(m, q, qsize);
+    check_free_chunk(m, q);
+  }
+
+  check_malloced_chunk(m, chunk2mem(p), nb);
+  return chunk2mem(p);
+}
+#endif /* !__CHERI_PURE_CAPABILITY__ */
+
+/* Add a segment to hold a new noncontiguous region */
+static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) {
+  /* Determine locations and sizes of segment, fenceposts, old top */
+  char* old_top = (char*)m->top;
+  msegmentptr oldsp = segment_holding(m, old_top);
+  char* old_end = oldsp->base + oldsp->size;
+  size_t ssize = pad_request(sizeof(struct malloc_segment));
+  char* rawsp = old_end - (ssize + CHUNK_HEADER_OFFSET + TWO_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
+  size_t offset = align_offset(chunk2mem(rawsp));
+  char* asp = rawsp + offset;
+  char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp;
+  mchunkptr sp = (mchunkptr)csp;
+  msegmentptr ss = (msegmentptr)(chunk2mem(sp));
+  mchunkptr tnext = chunk_plus_offset(ss, ssize);
+  mchunkptr p = tnext;
+  int nfences = 0;
+
+  /* reset top to new space */
+  init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
+
+  /* Set up segment record */
+  assert(is_aligned(ss));
+  set_size_and_pinuse_of_inuse_chunk(m, sp, ssize);
+  *ss = m->seg; /* Push current record */
+  m->seg.base = tbase;
+  m->seg.size = tsize;
+  m->seg.sflags = mmapped;
+  m->seg.next = ss;
+#ifdef CAPREVOKE
+  if (caprevoke_shadow(CAPREVOKE_SHADOW_NOVMMAP, tbase, &m->seg.shadow) != 0)
+    ABORT;
+#endif
+
+  /* Insert trailing fenceposts */
+  for (;;) {
+    mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE);
+    p->head = FENCEPOST_HEAD;
+    ++nfences;
+    if ((char*)(&(nextp->head)) < old_end)
+      p = nextp;
+    else
+      break;
+  }
+  assert(nfences >= 2);
+
+  /* Insert the rest of old top into a bin as an ordinary free chunk */
+  if (csp != old_top) {
+    mchunkptr q = (mchunkptr)old_top;
+    size_t psize = csp - old_top;
+    mchunkptr tn = chunk_plus_offset(q, psize);
+    set_free_with_pinuse(q, psize, tn);
+    insert_chunk(m, q, psize);
+  }
+
+  check_top_chunk(m, m->top);
+}
+
+#if SWEEP_STATS
+// atexit() calls malloc, try using __attribute__((destructor)) instead.
+__attribute__((destructor))
+static void
+print_sweep_stats() {
+  malloc_printf("Sweeps: %zd.\n", gm->sweepTimes);
+  malloc_printf("Swept bytes: %zd.\n", gm->sweptBytes);
+  malloc_printf("Frees: %zd.\n", gm->freeTimes);
+  malloc_printf("Free bytes: %zd.\n", gm->freeBytes);
+  malloc_printf("Bits painted: %zd.\n", gm->bitsPainted);
+  malloc_printf("Bits cleared: %zd.\n", gm->bitsCleared);
+  dlmalloc_stats();
+}
+#endif // SWEEP_STATS
+
+/* -------------------------- System allocation -------------------------- */
+
+/* Get memory from system using MMAP */
+static void* sys_alloc(mstate m, size_t nb) {
+  char* tbase = CMFAIL;
+  size_t tsize = 0;
+  flag_t mmap_flag = 0;
+  size_t asize; /* allocation size */
+
+  ensure_initialization();
+
+  /* Directly map large chunks, but only if already initialized */
+  if (use_mmap(m) && nb >= mparams.mmap_threshold && m->topsize != 0) {
+    void* mem = mmap_alloc(m, nb);
+    if (mem != 0)
+      return mem;
+  }
+
+  asize = granularity_align(nb + SYS_ALLOC_PADDING);
+  if (asize <= nb)
+    return 0; /* wraparound */
+  if (m->footprint_limit != 0) {
+    size_t fp = m->footprint + asize;
+    if (fp <= m->footprint || fp > m->footprint_limit)
+      return 0;
+  }
+
+  /*
+    Try getting memory in any of three ways (in most-preferred to
+    least-preferred order):
+    2. A call to MMAP new space (disabled if not HAVE_MMAP).
+
+   In all cases, we need to request enough bytes from system to ensure
+   we can malloc nb bytes upon success, so pad with enough space for
+   top_foot, plus alignment-pad to make sure we don't lose bytes if
+   not on boundary, and round this up to a granularity unit.
+  */
+
+  if (HAVE_MMAP && tbase == CMFAIL) {  /* Try MMAP */
+    char* mp = (char*)(CALL_MMAP(asize));
+#ifndef __CHERI_PURE_CAPABILITY__
+    if(MMAP_SHADOW(mp, asize) != (void*)((size_t)mp>>MALLOC_ALIGN_BITSHIFT)) {
+      ABORT;
+    }
+#endif
+    if (mp != CMFAIL) {
+      tbase = mp;
+      tsize = asize;
+      mmap_flag = USE_MMAP_BIT;
+    }
+  }
+
+  if (tbase != CMFAIL) {
+
+    if ((m->footprint += tsize) > m->max_footprint)
+      m->max_footprint = m->footprint;
+
+    if (!is_initialized(m)) { /* first-time initialization */
+      if (m->least_addr == 0 || tbase < m->least_addr)
+        m->least_addr = tbase;
+      m->seg.base = tbase;
+      m->seg.size = tsize;
+      m->seg.sflags = mmap_flag;
+#ifdef CAPREVOKE
+      if (caprevoke_shadow(CAPREVOKE_SHADOW_NOVMMAP, tbase, &m->seg.shadow) != 0)
+        ABORT;
+#endif
+      m->magic = mparams.magic;
+      m->release_checks = MAX_RELEASE_CHECK_RATE;
+      init_bins(m);
+      if (is_global(m))
+        init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
+      else
+      {
+        /* Offset top by embedded malloc_state */
+        mchunkptr mn = next_chunk(mem2chunk(m));
+        init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE);
+      }
+    }
+
+    else {
+#ifndef __CHERI_PURE_CAPABILITY__
+      /* Try to merge with an existing segment */
+      msegmentptr sp = &m->seg;
+      /* Only consider most recent segment if traversal suppressed */
+      while (sp != 0 && tbase != sp->base + sp->size)
+        sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next;
+      if (sp != 0 &&
+          !is_extern_segment(sp) &&
+          (sp->sflags & USE_MMAP_BIT) == mmap_flag &&
+          segment_holds(sp, m->top)) { /* append */
+        sp->size += tsize;
+        init_top(m, m->top, m->topsize + tsize);
+      }
+      else {
+        if (tbase < m->least_addr)
+          m->least_addr = tbase;
+        sp = &m->seg;
+        while (sp != 0 && sp->base != tbase + tsize)
+          sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next;
+        if (sp != 0 &&
+            !is_extern_segment(sp) &&
+            (sp->sflags & USE_MMAP_BIT) == mmap_flag) {
+          char* oldbase = sp->base;
+          sp->base = tbase;
+          sp->size += tsize;
+          return prepend_alloc(m, tbase, oldbase, nb);
+        }
+        else
+#endif /* !__CHERI_PURE_CAPABILITY__ */
+          add_segment(m, tbase, tsize, mmap_flag);
+#ifndef __CHERI_PURE_CAPABILITY__
+      }
+#endif /* !__CHERI_PURE_CAPABILITY__ */
+    }
+
+    if (nb < m->topsize) { /* Allocate from new or extended top space */
+      size_t rsize = m->topsize -= nb;
+      mchunkptr p = m->top;
+      mchunkptr r = m->top = chunk_plus_offset(p, nb);
+      r->head = rsize | PINUSE_BIT;
+      set_size_and_pinuse_of_inuse_chunk(m, p, nb);
+      check_top_chunk(m, m->top);
+      check_malloced_chunk(m, chunk2mem(p), nb);
+      return chunk2mem(p);
+    }
+  }
+
+  MALLOC_FAILURE_ACTION;
+  return 0;
+}
+
+/* -----------------------  system deallocation -------------------------- */
+
+/* Unmap and unlink any mmapped segments that don't contain used chunks */
+static size_t release_unused_segments(mstate m) {
+  size_t released = 0;
+  int nsegs = 0;
+  msegmentptr pred = &m->seg;
+  msegmentptr sp = pred->next;
+  while (sp != 0) {
+    char* base = sp->base;
+    size_t size = sp->size;
+    msegmentptr next = sp->next;
+    ++nsegs;
+    if (is_mmapped_segment(sp) && !is_extern_segment(sp)) {
+      mchunkptr p = align_as_chunk(base);
+      size_t psize = chunksize(p);
+      /* Can unmap if first chunk holds entire segment and not pinned */
+      if (!is_inuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) {
+        tchunkptr tp = (tchunkptr)p;
+        assert(segment_holds(sp, (char*)sp));
+        if (p == m->dv) {
+          m->dv = 0;
+          m->dvsize = 0;
+        }
+        else {
+          unlink_large_chunk(m, tp);
+        }
+        if (CALL_MUNMAP(base, size) == 0) {
+#ifndef __CHERI_PURE_CAPABILITY__
+          MUNMAP_SHADOW(base, size);
+#endif
+          released += size;
+          m->footprint -= size;
+          /* unlink obsoleted record */
+          sp = pred;
+          sp->next = next;
+        }
+        else { /* back out if cannot unmap */
+          insert_large_chunk(m, tp, psize);
+        }
+      }
+    }
+    if (NO_SEGMENT_TRAVERSAL) /* scan only first segment */
+      break;
+    pred = sp;
+    sp = next;
+  }
+  /* Reset check counter */
+  m->release_checks = (((size_t) nsegs > (size_t) MAX_RELEASE_CHECK_RATE)?
+                       (size_t) nsegs : (size_t) MAX_RELEASE_CHECK_RATE);
+  return released;
+}
+
+static int sys_trim(mstate m, size_t pad) {
+  size_t released = 0;
+  ensure_initialization();
+  if (pad < MAX_REQUEST && is_initialized(m)) {
+    pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */
+
+    if (m->topsize > pad) {
+      /* Shrink top space in granularity-size units, keeping at least one */
+      size_t unit = mparams.granularity;
+      size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit -
+                      SIZE_T_ONE) * unit;
+      msegmentptr sp = segment_holding(m, (char*)m->top);
+
+      if (!is_extern_segment(sp)) {
+        if (is_mmapped_segment(sp)) {
+          if (HAVE_MMAP &&
+              sp->size >= extra &&
+              !has_segment_link(m, sp)) { /* can't shrink if pinned */
+            size_t newsize = sp->size - extra;
+            (void)newsize; /* placate people compiling -Wunused-variable */
+            /* Prefer mremap, fall back to munmap */
+            if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) ||
+                (CALL_MUNMAP(sp->base + newsize, extra) == 0)) {
+#ifndef __CHERI_PURE_CAPABILITY__
+              MUNMAP_SHADOW(sp->base+newsize, extra);
+#endif
+              released = extra;
+            }
+          }
+        }
+      }
+
+      if (released != 0) {
+        sp->size -= released;
+        m->footprint -= released;
+        init_top(m, m->top, m->topsize - released);
+        check_top_chunk(m, m->top);
+      }
+    }
+
+    /* Unmap any unused mmapped segments */
+    if (HAVE_MMAP)
+      released += release_unused_segments(m);
+
+    /* On failure, disable autotrim to avoid repeated failed future calls */
+    if (released == 0 && m->topsize > m->trim_check)
+      m->trim_check = MAX_SIZE_T;
+  }
+
+  return (released != 0)? 1 : 0;
+}
+
+/* Consolidate and bin a chunk. Differs from exported versions
+   of free mainly in that the chunk need not be marked as inuse.
+*/
+static void dispose_chunk(mstate m, mchunkptr p, size_t psize) {
+  mchunkptr next = chunk_plus_offset(p, psize);
+  if (!pinuse(p)) {
+    mchunkptr prev;
+    size_t prevsize = p->prev_foot;
+    if (is_mmapped(p)) {
+      psize += prevsize + MMAP_FOOT_PAD;
+      if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) {
+#ifndef __CHERI_PURE_CAPABILITY__
+        MUNMAP_SHADOW((char*)p - prevsize, psize);
+#endif
+        m->footprint -= psize;
+      }
+      return;
+    }
+    prev = chunk_minus_offset(p, prevsize);
+    check_freebuf_corrupt(m, prev);
+    psize += prevsize;
+    p = prev;
+    if (RTCHECK(ok_address(m, prev))) { /* consolidate backward */
+      if (p != m->dv) {
+        unlink_chunk(m, p, prevsize);
+      }
+      else if ((next->head & INUSE_BITS) == INUSE_BITS) {
+        m->dvsize = psize;
+        set_free_with_pinuse(p, psize, next);
+        return;
+      }
+    }
+    else {
+      CORRUPTION_ERROR_ACTION(m);
+      return;
+    }
+  }
+  if (RTCHECK(ok_address(m, next))) {
+    // Only consolidate forward if the next is free and not dirty.
+    if(!cinuse(next)) {
+      check_freebuf_corrupt(m, next);
+      if (next == m->top) {
+        size_t tsize = m->topsize += psize;
+        m->top = p;
+        p->head = tsize | PINUSE_BIT;
+        if (p == m->dv) {
+          m->dv = 0;
+          m->dvsize = 0;
+        }
+        return;
+      }
+      else if (next == m->dv) {
+        size_t dsize = m->dvsize += psize;
+        m->dv = p;
+        set_size_and_pinuse_of_free_chunk(p, dsize);
+        return;
+      }
+      else {
+        size_t nsize = chunksize(next);
+        psize += nsize;
+        unlink_chunk(m, next, nsize);
+        set_size_and_pinuse_of_free_chunk(p, psize);
+        if (p == m->dv) {
+          m->dvsize = psize;
+          return;
+        }
+      }
+    }
+    else {
+      set_free_with_pinuse(p, psize, next);
+    }
+    insert_chunk(m, p, psize);
+  }
+  else {
+    CORRUPTION_ERROR_ACTION(m);
+  }
+}
+
+/* ---------------------------- malloc --------------------------- */
+
+/* allocate a large request from the best fitting chunk in a treebin */
+static void* tmalloc_large(mstate m, size_t nb) {
+  tchunkptr v = 0;
+  size_t rsize = -nb; /* Unsigned negation */
+  tchunkptr t;
+  bindex_t idx;
+  compute_tree_index(nb, idx);
+  if ((t = *treebin_at(m, idx)) != 0) {
+    /* Traverse tree for this bin looking for node with size == nb */
+    size_t sizebits = nb << leftshift_for_tree_index(idx);
+    tchunkptr rst = 0;  /* The deepest untaken right subtree */
+    for (;;) {
+      tchunkptr rt;
+      size_t trem = chunksize(t) - nb;
+      if (trem < rsize) {
+        v = t;
+        if ((rsize = trem) == 0)
+          break;
+      }
+      rt = t->child[1];
+      t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
+      if (rt != 0 && rt != t)
+        rst = rt;
+      if (t == 0) {
+        t = rst; /* set t to least subtree holding sizes > nb */
+        break;
+      }
+      sizebits <<= 1;
+    }
+  }
+  if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */
+    binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap;
+    if (leftbits != 0) {
+      bindex_t i;
+      binmap_t leastbit = least_bit(leftbits);
+      compute_bit2idx(leastbit, i);
+      t = *treebin_at(m, i);
+    }
+  }
+
+  while (t != 0) { /* find smallest of tree or subtree */
+    size_t trem = chunksize(t) - nb;
+    if (trem < rsize) {
+      rsize = trem;
+      v = t;
+    }
+    t = leftmost_child(t);
+  }
+
+  /*  If dv is a better fit, return 0 so malloc will use it */
+  if (v != 0 && rsize < (size_t)(m->dvsize - nb)) {
+    if (RTCHECK(ok_address(m, v))) { /* split */
+      mchunkptr r = chunk_plus_offset(v, nb);
+      assert(chunksize(v) == rsize + nb);
+      if (RTCHECK(ok_next(v, r))) {
+        unlink_large_chunk(m, v);
+        if (rsize < MIN_CHUNK_SIZE)
+          set_inuse_and_pinuse(m, v, (rsize + nb));
+        else {
+          set_size_and_pinuse_of_inuse_chunk(m, v, nb);
+          set_size_and_pinuse_of_free_chunk(r, rsize);
+          insert_chunk(m, r, rsize);
+        }
+        return chunk2mem(v);
+      }
+    }
+    CORRUPTION_ERROR_ACTION(m);
+  }
+  return 0;
+}
+
+/* allocate a small request from the best fitting chunk in a treebin */
+static void* tmalloc_small(mstate m, size_t nb) {
+  tchunkptr t, v;
+  size_t rsize;
+  bindex_t i;
+  binmap_t leastbit = least_bit(m->treemap);
+  compute_bit2idx(leastbit, i);
+  v = t = *treebin_at(m, i);
+  rsize = chunksize(t) - nb;
+
+  while ((t = leftmost_child(t)) != 0) {
+    size_t trem = chunksize(t) - nb;
+    if (trem < rsize) {
+      rsize = trem;
+      v = t;
+    }
+  }
+
+  if (RTCHECK(ok_address(m, v))) {
+    mchunkptr r = chunk_plus_offset(v, nb);
+    assert(chunksize(v) == rsize + nb);
+    if (RTCHECK(ok_next(v, r))) {
+      unlink_large_chunk(m, v);
+      if (rsize < MIN_CHUNK_SIZE)
+        set_inuse_and_pinuse(m, v, (rsize + nb));
+      else {
+        set_size_and_pinuse_of_inuse_chunk(m, v, nb);
+        set_size_and_pinuse_of_free_chunk(r, rsize);
+        replace_dv(m, r, rsize);
+      }
+      return chunk2mem(v);
+    }
+  }
+
+  CORRUPTION_ERROR_ACTION(m);
+  return 0;
+}
+
+static void* internal_memalign(mstate m, size_t alignment, size_t bytes);
+
+static void* internal_malloc(mstate m, size_t bytes) {
+  /*
+     Basic algorithm:
+     If a small request (< 256 bytes minus per-chunk overhead):
+       1. If one exists, use a remainderless chunk in associated smallbin.
+          (Remainderless means that there are too few excess bytes to
+          represent as a chunk.)
+       2. If it is big enough, use the dv chunk, which is normally the
+          chunk adjacent to the one used for the most recent small request.
+       3. If one exists, split the smallest available chunk in a bin,
+          saving remainder in dv.
+       4. If it is big enough, use the top chunk.
+       5. If available, get memory from system and use it
+     Otherwise, for a large request:
+       1. Find the smallest available binned chunk that fits, and use it
+          if it is better fitting than dv chunk, splitting if necessary.
+       2. If better fitting than any binned chunk, use the dv chunk.
+       3. If it is big enough, use the top chunk.
+       4. If request size >= mmap threshold, try to directly mmap this chunk.
+       5. If available, get memory from system and use it
+
+     The ugly goto's here ensure that postaction occurs along all paths.
+  */
+
+#if USE_LOCKS
+  ensure_initialization(); /* initialize in sys_alloc if not using locks */
+#endif
+
+  if (!PREACTION(m)) {
+    void* mem;
+    size_t nb;
+    if (bytes <= MAX_SMALL_REQUEST) {
+      bindex_t idx;
+      binmap_t smallbits;
+      nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
+      idx = small_index(nb);
+      smallbits = m->smallmap >> idx;
+
+      if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
+        mchunkptr b, p;
+        idx += ~smallbits & 1;       /* Uses next bin if idx empty */
+        b = smallbin_at(m, idx);
+        p = b->fd;
+        assert(chunksize(p) == small_index2size(idx));
+        unlink_first_small_chunk(m, b, p, idx);
+        set_inuse_and_pinuse(m, p, small_index2size(idx));
+        mem = chunk2mem(p);
+        check_malloced_chunk(m, mem, nb);
+        goto postaction;
+      }
+
+      else if (nb > m->dvsize) {
+        if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
+          mchunkptr b, p, r;
+          size_t rsize;
+          bindex_t i;
+          binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
+          binmap_t leastbit = least_bit(leftbits);
+          compute_bit2idx(leastbit, i);
+          b = smallbin_at(m, i);
+          p = b->fd;
+          assert(chunksize(p) == small_index2size(i));
+          unlink_first_small_chunk(m, b, p, i);
+          rsize = small_index2size(i) - nb;
+          /* Fit here cannot be remainderless if 4byte sizes */
+          if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
+            set_inuse_and_pinuse(m, p, small_index2size(i));
+          else {
+            set_size_and_pinuse_of_inuse_chunk(m, p, nb);
+            r = chunk_plus_offset(p, nb);
+            set_size_and_pinuse_of_free_chunk(r, rsize);
+            replace_dv(m, r, rsize);
+          }
+          mem = chunk2mem(p);
+          check_malloced_chunk(m, mem, nb);
+          goto postaction;
+        }
+
+        else if (m->treemap != 0 && (mem = tmalloc_small(m, nb)) != 0) {
+          check_malloced_chunk(m, mem, nb);
+          goto postaction;
+        }
+      }
+    }
+    else if (bytes >= MAX_REQUEST)
+      nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
+    else {
+      nb = pad_request(bytes);
+      if (m->treemap != 0 && (mem = tmalloc_large(m, nb)) != 0) {
+        check_malloced_chunk(m, mem, nb);
+        goto postaction;
+      }
+    }
+
+    if (nb <= m->dvsize) {
+      size_t rsize = m->dvsize - nb;
+      mchunkptr p = m->dv;
+      if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
+        mchunkptr r = m->dv = chunk_plus_offset(p, nb);
+        m->dvsize = rsize;
+        set_size_and_pinuse_of_free_chunk(r, rsize);
+        set_size_and_pinuse_of_inuse_chunk(m, p, nb);
+      }
+      else { /* exhaust dv */
+        size_t dvs = m->dvsize;
+        m->dvsize = 0;
+        m->dv = 0;
+        set_inuse_and_pinuse(m, p, dvs);
+      }
+      mem = chunk2mem(p);
+      check_malloced_chunk(m, mem, nb);
+      goto postaction;
+    }
+
+    else if (nb < m->topsize) { /* Split top */
+      size_t rsize = m->topsize -= nb;
+      mchunkptr p = m->top;
+      mchunkptr r = m->top = chunk_plus_offset(p, nb);
+      r->head = rsize | PINUSE_BIT;
+      set_size_and_pinuse_of_inuse_chunk(m, p, nb);
+      mem = chunk2mem(p);
+      check_top_chunk(m, m->top);
+      check_malloced_chunk(m, mem, nb);
+      goto postaction;
+    }
+
+    mem = sys_alloc(m, nb);
+
+  postaction:
+    ;
+    mchunkptr ret = mem2chunk(mem);
+    if(!is_mmapped(ret)) {
+      size_t theSize = chunksize(ret);
+      mchunkptr theNext = chunk_plus_offset(ret, theSize);
+      // Clear these two bits to be safe.
+      clear_cdirty(ret);
+      clear_pdirty(theNext);
+    }
+    POSTACTION(m);
+    UTRACE(0, bytes, mem);
+    m->allocated += chunksize(mem2chunk(mem));
+    if (m->allocated > m->max_allocated)
+      m->max_allocated = m->allocated;
+    return mem;
+  }
+
+  return 0;
+}
+
+static void* dlmalloc_internal_unbounded(size_t bytes) {
+  void *mem;
+#ifdef __CHERI_PURE_CAPABILITY__
+  bytes = __builtin_cheri_round_representable_length(bytes);
+  size_t mask = __builtin_cheri_representable_alignment_mask(bytes);
+  size_t align = 1 + ~mask;
+
+  if (mask != MAX_SIZE_T && align > MALLOC_ALIGNMENT) {
+    mem = internal_memalign(gm, align, bytes);
+  } else
+#endif
+    mem = internal_malloc(gm, bytes);
+
+  assert(chunksize(mem2chunk(mem)) >= bytes + CHUNK_HEADER_OFFSET);
+
+  return mem;
+}
+
+void* dlmalloc(size_t bytes) {
+    return bound_ptr(dlmalloc_internal_unbounded(bytes), bytes);
+}
+
+/* ---------------------------- free --------------------------- */
+
+static void
+dlfree_internal(void* mem) {
+  /*
+     Consolidate freed chunks with preceeding or succeeding bordering
+     free chunks, if they exist, and then place in a bin.  Intermixed
+     with special cases for top, dv, mmapped chunks, and usage errors.
+  */
+
+  if (mem != 0) {
+    mchunkptr p  = mem2chunk(mem);
+#ifdef __CHERI_PURE_CAPABILITY__
+    p->pad = NULL;
+#endif
+#define fm gm
+
+#if SUPPORT_UNMAP
+    char *remap_base = NULL, *remap_end = NULL;
+    if (cunmapped(p)) {
+      remap_base = __builtin_align_up(chunk2mem(p), mparams.page_size);
+      remap_end = __builtin_align_down((char *)p + chunksize(p),
+				       mparams.page_size);
+      ptrdiff_t remap_len = remap_end - remap_base;
+      assert(remap_len > 0 && remap_len % mparams.page_size == 0);
+#ifdef VERBOSE
+      malloc_printf("%s: remapping %ti from %#p\n", __func__, remap_len, remap_base);
+#endif
+      if (mmap(remap_base, remap_len, PROT_READ|PROT_WRITE,
+	       MAP_FIXED | MAP_ANON | MAP_CHERI_NOSETBOUNDS, -1, 0) ==
+          MAP_FAILED)
+        ABORT;
+    }
+#endif /* SUPPORT_UNMAP */
+
+#if ZERO_MEMORY
+  /*
+   * Zero the memory to ensure we don't leak pointers to other parts
+   * of the allocation graph to a consumer.
+   *
+   * XXX: There are optimization opportunities here including:
+   *  - MPROT_QUARANTINE doing clearing.
+   *  - An efficent, ranged tag clearing instruction.
+   */
+#if SUPPORT_UNMAP
+    if (cunmapped(p)) {
+      assert(remap_base && remap_end);
+      size_t leading_size = remap_base - (char *)mem;
+      // XXXAR: I'm not sure I understand this code correctly but it seems we
+      // need to subtract CHUNK_HEADER_OFFSET to avoid zeroing the next chunk
+      size_t trailing_size = (char *)mem + chunksize(p) - remap_end - CHUNK_HEADER_OFFSET;
+#ifdef VERBOSE
+      malloc_printf("%s: cunmapped: zeroing %ti from %#p\n", __func__, leading_size, mem);
+      malloc_printf("%s: cunmapped: zeroing %ti from %#p\n", __func__, trailing_size, remap_end);
+#endif
+      memset(mem, 0, leading_size);
+      memset(remap_end, 0, trailing_size);
+    } else
+#endif /* SUPPORT_UNMAP */
+    {
+#ifdef VERBOSE
+      malloc_printf("%s: zeroing %ti from %#p\n", __func__, chunksize(p) - CHUNK_HEADER_OFFSET, mem);
+#endif
+      memset(mem, 0, chunksize(p) - CHUNK_HEADER_OFFSET);
+    }
+#endif /* ZERO_MEMORY */
+
+#if SUPPORT_UNMAP
+    if (cunmapped(p)) {
+      clear_cunmapped(p);
+    }
+#endif
+
+    if (1) {
+      check_inuse_chunk(fm, p);
+      if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) {
+        size_t psize = chunksize(p);
+        mchunkptr next = chunk_plus_offset(p, psize);
+        if (!pinuse(p)) {
+          size_t prevsize = p->prev_foot;
+          if (is_mmapped(p)) {
+            psize += prevsize + MMAP_FOOT_PAD;
+            if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) {
+#ifndef __CHERI_PURE_CAPABILITY__
+              MUNMAP_SHADOW((char*)p - prevsize, psize);
+#endif
+              fm->footprint -= psize;
+            }
+            goto postaction;
+          }
+          else {
+            mchunkptr prev = chunk_minus_offset(p, prevsize);
+            check_freebuf_corrupt(fm, prev);
+            psize += prevsize;
+	    /* Don't leak freebuf pointers */
+	    memset(p, 0, CHUNK_HEADER_OFFSET);
+            p = prev;
+            if (RTCHECK(ok_address(fm, prev))) {
+              if (p != fm->dv) {
+                unlink_chunk(fm, p, prevsize);
+              }
+              else if ((next->head & INUSE_BITS) == INUSE_BITS) {
+                fm->dvsize = psize;
+                set_free_with_pinuse(p, psize, next);
+                goto postaction;
+              }
+            }
+            else {
+              malloc_printf("fail: (%#p) >= (M)->least_addr(%#p)\n", prev, fm->least_addr);
+              goto erroraction;
+            }
+          }
+        }
+
+        if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
+          // Consolidate forward only with a non-dirty chunk.
+          if(!cinuse(next)) {
+            check_freebuf_corrupt(fm, next);
+            if (next == fm->top) {
+	      /* Don't leek allocator pointers */
+	      memset(next, 0, sizeof(tchunk));
+              size_t tsize = fm->topsize += psize;
+              fm->top = p;
+              p->head = dirtybits(p) | tsize | PINUSE_BIT;
+              if (p == fm->dv) {
+                fm->dv = 0;
+                fm->dvsize = 0;
+              }
+              if (should_trim(fm, tsize))
+                sys_trim(fm, 0);
+              goto postaction;
+            }
+            else if (next == fm->dv) {
+	      /* Don't leek allocator pointers */
+	      memset(next, 0, sizeof(tchunk));
+              size_t dsize = fm->dvsize += psize;
+              fm->dv = p;
+              set_size_and_pinuse_of_free_chunk(p, dsize);
+              goto postaction;
+            }
+            else {
+              size_t nsize = chunksize(next);
+              psize += nsize;
+              unlink_chunk(fm, next, nsize);
+	      /* Don't leek allocator pointers */
+	      memset(next, 0, sizeof(tchunk));
+              set_size_and_pinuse_of_free_chunk(p, psize);
+              if (p == fm->dv) {
+                fm->dvsize = psize;
+                goto postaction;
+              }
+            }
+          }
+          else
+            set_free_with_pinuse(p, psize, next);
+
+          if (is_small(psize)) {
+            insert_small_chunk(fm, p, psize);
+            check_free_chunk(fm, p);
+          }
+          else {
+            tchunkptr tp = (tchunkptr)p;
+            insert_large_chunk(fm, tp, psize);
+            check_free_chunk(fm, p);
+            if (--fm->release_checks == 0)
+              release_unused_segments(fm);
+          }
+          goto postaction;
+        }
+      }
+    erroraction:
+      USAGE_ERROR_ACTION(fm, p);
+    postaction:
+      ;
+    }
+  }
+#undef fm
+}
+
+#ifndef __CHERI_PURE_CAPABILITY__
+// The following two functions assume 8 bits in a byte.
+static void
+shadow_paint(void* start, size_t size) {
+  size_t realStart = (size_t)start>>MALLOC_ALIGN_BYTESHIFT;
+  size_t realEnd = (((size_t)start+size)>>MALLOC_ALIGN_BYTESHIFT);
+  char* firstByte = (char*)(realStart>>3);
+  char* lastByte = (char*)(realEnd>>3);
+  if(firstByte == lastByte) { // All the paint bits are within a single byte.
+    for(size_t bitoff=(realStart&BYTE_ALIGN_MASK); bitoff<(realEnd&BYTE_ALIGN_MASK); bitoff++) {
+      *firstByte |= 1<<bitoff;
+#if SWEEP_STATS
+      gm->bitsPainted++;
+#endif
+    }
+  } else {
+    char* nextByte = firstByte+1;
+    for(size_t bitoff=(realStart&BYTE_ALIGN_MASK); bitoff<8; bitoff++) {
+      *firstByte |= 1<<bitoff;
+#if SWEEP_STATS
+      gm->bitsPainted++;
+#endif
+    }
+    memset(nextByte, 0xff, lastByte-nextByte);
+#if SWEEP_STATS
+    gm->bitsPainted += 8*(lastByte-nextByte);
+#endif
+    for(size_t bitoff=0; bitoff<(realEnd&BYTE_ALIGN_MASK); bitoff++) {
+      *lastByte |= 1<<bitoff;
+#if SWEEP_STATS
+      gm->bitsPainted++;
+#endif
+    }
+  }
+}
+
+static void
+shadow_clear(void* start, size_t size) {
+  size_t realStart = (size_t)start>>MALLOC_ALIGN_BYTESHIFT;
+  size_t realEnd = (((size_t)start+size)>>MALLOC_ALIGN_BYTESHIFT);
+  char* firstByte = (char*)(realStart>>3);
+  char* lastByte = (char*)(realEnd>>3);
+  if(firstByte == lastByte) { // All the paint bits are within a single byte.
+    for(size_t bitoff=(realStart&BYTE_ALIGN_MASK); bitoff<(realEnd&BYTE_ALIGN_MASK); bitoff++) {
+      *firstByte &= ~(1<<bitoff);
+#if SWEEP_STATS
+      gm->bitsCleared++;
+#endif
+    }
+  } else {
+    char* nextByte = firstByte+1;
+    for(size_t bitoff=(realStart&BYTE_ALIGN_MASK); bitoff<8; bitoff++) {
+      *firstByte &= ~(1<<bitoff);
+#if SWEEP_STATS
+      gm->bitsCleared++;
+#endif
+    }
+    memset(nextByte, 0, lastByte-nextByte);
+#if SWEEP_STATS
+    gm->bitsCleared += 8*(lastByte-nextByte);
+#endif
+    for(size_t bitoff=0; bitoff<(realEnd&BYTE_ALIGN_MASK); bitoff++) {
+      *lastByte &= ~(1<<bitoff);
+#if SWEEP_STATS
+      gm->bitsCleared++;
+#endif
+    }
+  }
+}
+#endif
+
+static void malloc_revoke_internal(const char *cause);
+
+void
+dlfree(void* mem) {
+  if(mem != 0) {
+    msegmentptr sp;
+    mchunkptr p  = mem2chunk(unbound_ptr(gm, &sp, mem));
+    gm->allocated -= chunksize(p);
+#if SUPPORT_UNMAP
+    void *unmap_base = NULL;
+    void *unmap_end = NULL;
+#endif
+
+#define fm gm
+#ifdef __CHERI_PURE_CAPABILITY__
+    /*
+     * Replace the pointer to the allocation.  This allows us to catch
+     * double-free()s in unbound_ptr().  In the CAPREVOKE case, it also
+     * allows us to cache the shadow pointer for later use.
+     */
+#ifdef CAPREVOKE
+    p->pad = sp->shadow;
+#else
+    p->pad = NULL;
+#endif
+#endif /* __CHERI_PURE_CAPABILITY__ */
+    UTRACE(mem, 0, 0);
+    if(!PREACTION(fm)) {
+      check_inuse_chunk(fm, p);
+#if SWEEP_STATS
+      fm->freeTimes++;
+      fm->freeBytes += chunksize(p);
+#endif // SWEEP_STATS
+      check_freebuf_corrupt(fm, p);
+#if CONSOLIDATE_ON_FREE == 1
+      if(!is_mmapped(p)) {
+        if(RTCHECK(ok_address(fm, p) && ok_inuse(p))) {
+          size_t psize = chunksize(p);
+          if(pdirty(p)) {
+            size_t prevsize = p->prev_foot;
+            mchunkptr prev = chunk_minus_offset(p, prevsize);
+            psize += prevsize;
+#if SUPPORT_UNMAP
+	    if (cunmapped(prev)) {
+	      /*
+	       * The previous chunk is unmapped up to the page contining our
+	       * chunk header.  We must unmap that page if we can to
+	       * join the unmapped region.
+	       */
+              unmap_base = __builtin_align_down(p, mparams.page_size);
+	    }
+#endif
+            p = prev;
+            if(RTCHECK(ok_address(fm, prev))) {
+              unlink_freebuf_chunk(fm, p);
+            } else
+              CORRUPTION_ERROR_ACTION(fm);
+          }
+
+          mchunkptr next = chunk_plus_offset(p, psize);
+          if(RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
+            // Consolidate forward only with a non-dirty chunk.
+            if(cdirty(next)) {
+              size_t nsize = chunksize(next);
+              psize += nsize;
+              unlink_freebuf_chunk(fm, next);
+              set_size_and_clear_pdirty_of_dirty_chunk(p, psize);
+#if SUPPORT_UNMAP
+	      if (cunmapped(next)) {
+		/*
+		 * The page after our allocation is unmapped and we
+		 * must join it if we can and consume remainder of the
+		 * next chunk.
+		 */
+		set_cunmapped(p);
+		unmap_end = __builtin_align_up(next, mparams.page_size);
+	      }
+#endif
+            }
+            else {
+              set_size_and_clear_pdirty_of_dirty_chunk(p, psize);
+              set_pdirty(next);
+            }
+          } else
+            CORRUPTION_ERROR_ACTION(fm);
+        } else
+          USAGE_ERROR_ACTION(fm, p);
+      }
+#endif /* CONSOLIDATE_ON_FREE == 1 */
+      insert_freebuf_chunk(fm, p);
+
+#if SUPPORT_UNMAP
+      if (unmap_base == NULL)
+        unmap_base = __builtin_align_up(chunk2mem(p), mparams.page_size);
+      if (unmap_end == NULL)
+        unmap_end = __builtin_align_down((char *)p + chunksize(p), mparams.page_size);
+      ptrdiff_t unmap_len = (char *)unmap_end - (char *)unmap_base;
+      if (unmap_len > 0 && (size_t)unmap_len >= mparams.unmap_threshold) {
+	set_cunmapped(p);
+      }
+      if (cunmapped(p) && unmap_end > unmap_base) {
+#ifdef VERBOSE
+	malloc_printf("%s: unmapping %ti from %#p\n", __func__, unmap_len, unmap_base);
+#endif
+	/*
+	 * We'd like to unmap the memory, but that could lead to reuse.
+	 * Instead, map it MAP_GUARD.
+	 */
+        if (mmap(unmap_base, unmap_len, PROT_NONE,
+	         MAP_FIXED | MAP_GUARD | MAP_CHERI_NOSETBOUNDS, -1, 0) ==
+            MAP_FAILED)
+          CORRUPTION_ERROR_ACTION(fm);
+      }
+#endif
+
+      if (fm->freebufbytes > mparams.max_freebufbytes) {
+        malloc_revoke_internal("mparams.max_freebufbytes exceeded");
+      } else if (fm->freebufbytes > mparams.min_freebufbytes &&
+	         fm->freebufbytes >
+                 (size_t)(fm->footprint * mparams.max_freebuf_percent)) {
+        malloc_revoke_internal("mparams.max_freebuf_percent and "
+	                       "mparams.min_freebufbytes exceeded");
+      }
+      POSTACTION(fm);
+    }
+  }
+}
+
+static void
+malloc_revoke_internal(const char *reason) {
+#ifdef VERBOSE
+  malloc_printf("%s: %s\n", __func__, reason);
+#endif
+#if SWEEP_STATS
+  gm->sweepTimes++;
+  gm->sweptBytes += gm->footprint;
+#endif // SWEEP_STATS
+  mchunkptr freebin = &gm->freebufbin;
+  for (mchunkptr thePtr = freebin->fd; thePtr != freebin; thePtr = thePtr->fd) {
+#ifndef __CHERI_PURE_CAPABILITY__
+    shadow_paint(thePtr, chunksize(thePtr));
+#else
+#ifdef CAPREVOKE
+    vaddr_t addr = __builtin_cheri_address_get(chunk2mem(thePtr));
+    caprev_shadow_nomap_set_raw(thePtr->pad, addr, addr + chunksize(thePtr));
+#endif
+#endif
+  }
+
+#ifdef CAPREVOKE
+  struct caprevoke_stats crst;
+  uint64_t start_epoch;
+  caprevoke(CAPREVOKE_LAST_PASS|CAPREVOKE_IGNORE_START|CAPREVOKE_NO_WAIT_OK,
+	    0, &crst);
+  start_epoch = crst.epoch_init;
+  while (!caprevoke_epoch_clears(crst.epoch_fini, start_epoch)) {
+    caprevoke(CAPREVOKE_LAST_PASS, start_epoch, &crst);
+  }
+#endif
+
+  for (mchunkptr thePtr = freebin->fd; thePtr != freebin; thePtr = freebin->fd) {
+    unlink_first_freebuf_chunk(gm, freebin, thePtr);
+#if CONSOLIDATE_ON_FREE == 1 || !defined(__CHERI_PURE_CAPABILITY__)
+    size_t theSize = chunksize(thePtr);
+#endif
+#ifndef __CHERI_PURE_CAPABILITY__
+    shadow_clear(thePtr, theSize);
+#else
+#ifdef CAPREVOKE
+    vaddr_t addr = __builtin_cheri_address_get(chunk2mem(thePtr));
+    caprev_shadow_nomap_clear_raw(thePtr->pad, addr, addr + chunksize(thePtr));
+#endif
+#endif
+#if CONSOLIDATE_ON_FREE == 1
+    mchunkptr theNext = chunk_plus_offset(thePtr, theSize);
+    if(!is_mmapped(thePtr)) {
+      assert(cdirty(thePtr));
+      assert(pdirty(theNext));
+      clear_cdirty(thePtr);
+      clear_pdirty(theNext);
+    }
+#endif /* CONSOLIDATE_ON_FREE == 1 */
+
+    // Have to do free_internal after unlinking, otherwise the circular
+    // list of freebufbin will get corrupted.
+    dlfree_internal(chunk2mem(thePtr));
+  }
+}
+
+void
+dlmalloc_revoke(void) {
+  PREACTION(gm);
+  malloc_revoke_internal(__func__);
+  POSTACTION(gm);
+}
+
+void* dlcalloc(size_t n_elements, size_t elem_size) {
+  void* mem;
+  size_t req = 0;
+  if (n_elements != 0) {
+    req = n_elements * elem_size;
+    if (((n_elements | elem_size) & ~(size_t)0xffff) &&
+        (req / n_elements != elem_size))
+      req = MAX_SIZE_T; /* force downstream failure on overflow */
+  }
+  mem = dlmalloc_internal_unbounded(req);
+#ifndef CAPREVOKE
+  if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
+    memset(mem, 0, req);
+#endif
+  return bound_ptr(mem, req);
+}
+
+/* ------------ Internal support for realloc, memalign, etc -------------- */
+
+/* Try to realloc; only in-place unless can_move true */
+static mchunkptr try_realloc_chunk(mstate m, mchunkptr p, size_t nb) {
+  mchunkptr newp = 0;
+  size_t oldsize = chunksize(p);
+  mchunkptr next = chunk_plus_offset(p, oldsize);
+  if (RTCHECK(ok_address(m, p) && ok_inuse(p) &&
+              ok_next(p, next) && ok_pinuse(next))) {
+    if (is_mmapped(p)) {
+      newp = mmap_resize(m, p, nb);
+    }
+    else if (oldsize >= nb) {             /* already big enough */
+#if 0
+      /*
+       * If already big enough, we do not shrink.
+       * We CANNOT shrink, because this chunk might have already been used to
+       * create a chunk that spans across below and above the new upper bound,
+       * which is not a subset of either the remainder or the shrinked chunk.
+       */
+      size_t rsize = oldsize - nb;
+      if (rsize >= MIN_CHUNK_SIZE) {      // Split off remainder.
+        mchunkptr r = chunk_plus_offset(p, nb);
+        set_inuse(m, p, nb);
+        set_inuse(m, r, rsize);
+        dispose_chunk(m, r, rsize);
+      }
+#else
+      newp = p;
+#endif
+    }
+    else if (next == m->top) {  /* extend into top */
+      if (oldsize + m->topsize > nb) {
+        size_t newsize = oldsize + m->topsize;
+        size_t newtopsize = newsize - nb;
+        mchunkptr newtop = chunk_plus_offset(p, nb);
+        set_inuse(m, p, nb);
+        newtop->head = newtopsize |PINUSE_BIT;
+        m->top = newtop;
+        m->topsize = newtopsize;
+        newp = p;
+      }
+    }
+    else if (next == m->dv) { /* extend into dv */
+      size_t dvs = m->dvsize;
+      if (oldsize + dvs >= nb) {
+        size_t dsize = oldsize + dvs - nb;
+        if (dsize >= MIN_CHUNK_SIZE) {
+          mchunkptr r = chunk_plus_offset(p, nb);
+          mchunkptr n = chunk_plus_offset(r, dsize);
+          set_inuse(m, p, nb);
+          set_size_and_pinuse_of_free_chunk(r, dsize);
+          clear_pinuse(n);
+          m->dvsize = dsize;
+          m->dv = r;
+        }
+        else { /* exhaust dv */
+          size_t newsize = oldsize + dvs;
+          set_inuse(m, p, newsize);
+          m->dvsize = 0;
+          m->dv = 0;
+        }
+        newp = p;
+      }
+    }
+    else if(!cinuse(next)) {
+      size_t nextsize = chunksize(next);
+      if (oldsize + nextsize >= nb) {
+        size_t rsize = oldsize + nextsize - nb;
+        unlink_chunk(m, next, nextsize);
+        if (rsize < MIN_CHUNK_SIZE) {
+          size_t newsize = oldsize + nextsize;
+          set_inuse(m, p, newsize);
+        }
+        else {
+          mchunkptr r = chunk_plus_offset(p, nb);
+          set_inuse(m, p, nb);
+          set_inuse(m, r, rsize);
+          dispose_chunk(m, r, rsize);
+        }
+        newp = p;
+      }
+    }
+  }
+  else {
+    USAGE_ERROR_ACTION(m, chunk2mem(p));
+  }
+  return newp;
+}
+
+static void* internal_memalign(mstate m, size_t alignment, size_t bytes) {
+  void* mem = 0;
+  if (alignment <  MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */
+    alignment = MIN_CHUNK_SIZE;
+  if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */
+    size_t a = MALLOC_ALIGNMENT << 1;
+    while (a < alignment) a <<= 1;
+    alignment = a;
+  }
+  if (bytes >= MAX_REQUEST - alignment) {
+    if (m != 0)  { /* Test isn't needed but avoids compiler warning */
+      MALLOC_FAILURE_ACTION;
+    }
+  }
+  else {
+    size_t nb = request2size(bytes);
+    size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD;
+    mem = internal_malloc(m, req);
+    if (mem != 0) {
+      mchunkptr p = mem2chunk(mem);
+      if (PREACTION(m))
+        return 0;
+      if (!__builtin_is_aligned(mem, alignment)) { /* misaligned */
+        /*
+          Find an aligned spot inside chunk.  Since we need to give
+          back leading space in a chunk of at least MIN_CHUNK_SIZE, if
+          the first calculation places us at a spot with less than
+          MIN_CHUNK_SIZE leader, we can move to the next aligned spot.
+          We've allocated enough total room so that this is always
+          possible.
+        */
+        char* br = (char*)mem2chunk(__builtin_align_up(mem, alignment));
+        char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)?
+          br : br+alignment;
+        mchunkptr newp = (mchunkptr)pos;
+        size_t leadsize = pos - (char*)(p);
+        size_t newsize = chunksize(p) - leadsize;
+
+        if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */
+          newp->prev_foot = p->prev_foot + leadsize;
+          newp->head = newsize;
+        }
+        else { /* Otherwise, give back leader, use the rest */
+          set_inuse(m, newp, newsize);
+          set_inuse(m, p, leadsize);
+          dispose_chunk(m, p, leadsize);
+        }
+        p = newp;
+      }
+
+      /* Give back spare room at the end */
+      if (!is_mmapped(p)) {
+        size_t size = chunksize(p);
+        if (size > nb + MIN_CHUNK_SIZE) {
+          size_t remainder_size = size - nb;
+          mchunkptr remainder = chunk_plus_offset(p, nb);
+          set_inuse(m, p, nb);
+          set_inuse(m, remainder, remainder_size);
+          dispose_chunk(m, remainder, remainder_size);
+        }
+      }
+
+      mem = chunk2mem(p);
+      assert (chunksize(p) >= nb);
+      assert(__builtin_is_aligned(mem, alignment));
+      check_inuse_chunk(m, p);
+      POSTACTION(m);
+    }
+  }
+  m->allocated += chunksize(mem2chunk(mem));
+  if (m->allocated > m->max_allocated)
+    m->max_allocated = m->allocated;
+  return mem;
+}
+
+/* Traversal */
+#if MALLOC_INSPECT_ALL
+static void internal_inspect_all(mstate m,
+                                 void(*handler)(void *start,
+                                                void *end,
+                                                size_t used_bytes,
+                                                void* callback_arg),
+                                 void* arg) {
+  if (is_initialized(m)) {
+    mchunkptr top = m->top;
+    msegmentptr s;
+    for (s = &m->seg; s != 0; s = s->next) {
+      mchunkptr q = align_as_chunk(s->base);
+      while (segment_holds(s, q) && q->head != FENCEPOST_HEAD) {
+        mchunkptr next = next_chunk(q);
+        size_t sz = chunksize(q);
+        size_t used;
+        void* start;
+        if (is_inuse(q)) {
+          used = sz - CHUNK_OVERHEAD; /* must not be mmapped */
+          start = chunk2mem(q);
+        }
+        else {
+          used = 0;
+          if (is_small(sz)) {     /* offset by possible bookkeeping */
+            start = (void*)((char*)q + sizeof(struct malloc_chunk));
+          }
+          else {
+            start = (void*)((char*)q + sizeof(struct malloc_tree_chunk));
+          }
+        }
+        if (start < (void*)next)  /* skip if all space is bookkeeping */
+          handler(start, next, used, arg);
+        if (q == top)
+          break;
+        q = next;
+      }
+    }
+  }
+}
+#endif /* MALLOC_INSPECT_ALL */
+
+/* ------------------ Exported realloc, memalign, etc -------------------- */
+
+void* dlrealloc(void* oldmem, size_t bytes) {
+  void* mem = 0;
+#ifdef __CHERI_PURE_CAPABILITY__
+  bytes = __builtin_cheri_round_representable_length(bytes);
+  size_t mask = __builtin_cheri_representable_alignment_mask(bytes);
+#endif
+  if (oldmem == 0) {
+    return dlmalloc(bytes);
+  }
+  else if (bytes >= MAX_REQUEST) {
+    MALLOC_FAILURE_ACTION;
+  }
+#ifdef REALLOC_ZERO_BYTES_FREES
+  else if (bytes == 0) {
+    dlfree(oldmem);
+    return 0;
+  }
+#endif /* REALLOC_ZERO_BYTES_FREES */
+  else {
+    size_t nb = request2size(bytes);
+    mchunkptr oldp = mem2chunk(unbound_ptr(gm, NULL, oldmem));
+    mstate m = gm;
+#ifdef MALLOC_UTRACE
+    malloc_utrace_suspend++;
+#endif
+    if (!PREACTION(m)) {
+      mchunkptr newp = 0;
+#ifdef __CHERI_PURE_CAPABILITY__
+      /*
+       * Don't try to expand in place if the extended pointer won't be
+       * sufficently aligned.
+       */
+      if ((__builtin_cheri_base_get(oldmem) & ~mask) == 0)
+#endif
+        newp = try_realloc_chunk(m, oldp, nb);
+      POSTACTION(m);
+      if (newp != 0) {
+        check_inuse_chunk(m, newp);
+        mem = chunk2mem(newp);
+        if(!is_mmapped(newp))
+          clear_pdirty(next_chunk(newp));
+      }
+      else {
+#ifdef __CHERI_PURE_CAPABILITY__
+        size_t align = 1 + ~mask;
+
+        if (mask != MAX_SIZE_T && align > MALLOC_ALIGNMENT) {
+          size_t align = 1 + ~mask;
+          mem = internal_memalign(gm, align, bytes);
+        } else
+#endif
+          mem = internal_malloc(m, bytes);
+        if (mem != 0) {
+          size_t oc = chunksize(oldp) - overhead_for(oldp);
+	  /*
+	   * CHERI: Use chunk2mem(oldp) as the source because oc might be
+	   * longer than the length of oldmem.
+	   */
+          memcpy(mem, chunk2mem(oldp), (oc < bytes)? oc : bytes);
+          internal_free(m, oldmem);
+        }
+      }
+    }
+#ifdef MALLOC_UTRACE
+    malloc_utrace_suspend--;
+#endif
+    UTRACE(oldmem, bytes, mem);
+  }
+  return bound_ptr(mem, bytes);
+}
+
+int dlposix_memalign(void** pp, size_t alignment, size_t bytes) {
+  void* mem = 0;
+#ifdef __CHERI_PURE_CAPABILITY__
+  bytes = __builtin_cheri_round_representable_length(bytes);
+#endif
+  if (alignment == MALLOC_ALIGNMENT)
+    mem = dlmalloc_internal_unbounded(bytes);
+  else {
+    size_t d = alignment / sizeof(void*);
+    size_t r = alignment % sizeof(void*);
+    if (r != 0 || d == 0 || (d & (d-SIZE_T_ONE)) != 0)
+      return EINVAL;
+    else if (bytes <= MAX_REQUEST - alignment) {
+      if (alignment <  MIN_CHUNK_SIZE)
+        alignment = MIN_CHUNK_SIZE;
+      mem = internal_memalign(gm, alignment, bytes);
+    }
+  }
+  if (mem == 0)
+    return ENOMEM;
+  else {
+    *pp = bound_ptr(mem, bytes);
+    return 0;
+  }
+}
+
+void *
+dlalloc_aligned(size_t alignment, size_t size) {
+  int error;
+  void *mem;
+
+  error = dlposix_memalign(&mem, alignment, size);
+  if (error != 0) {
+    errno = error;
+    return 0;
+  }
+  return mem;
+}
+
+#if MALLOC_INSPECT_ALL
+void dlmalloc_inspect_all(void(*handler)(void *start,
+                                         void *end,
+                                         size_t used_bytes,
+                                         void* callback_arg),
+                          void* arg) {
+  ensure_initialization();
+  if (!PREACTION(gm)) {
+    internal_inspect_all(gm, handler, arg);
+    POSTACTION(gm);
+  }
+}
+#endif /* MALLOC_INSPECT_ALL */
+
+int dlmalloc_trim(size_t pad) {
+  int result = 0;
+  ensure_initialization();
+  if (!PREACTION(gm)) {
+    result = sys_trim(gm, pad);
+    POSTACTION(gm);
+  }
+  return result;
+}
+
+size_t dlmalloc_footprint(void) {
+  return gm->footprint;
+}
+
+size_t dlmalloc_max_footprint(void) {
+  return gm->max_footprint;
+}
+
+size_t dlmalloc_footprint_limit(void) {
+  size_t maf = gm->footprint_limit;
+  return maf == 0 ? MAX_SIZE_T : maf;
+}
+
+size_t dlmalloc_set_footprint_limit(size_t bytes) {
+  size_t result;  /* invert sense of 0 */
+  if (bytes == 0)
+    result = granularity_align(1); /* Use minimal size */
+  if (bytes == MAX_SIZE_T)
+    result = 0;                    /* disable */
+  else
+    result = granularity_align(bytes);
+  return gm->footprint_limit = result;
+}
+
+#if !NO_MALLINFO
+struct mallinfo dlmallinfo(void) {
+  return internal_mallinfo(gm);
+}
+#endif /* NO_MALLINFO */
+
+#if !NO_MALLOC_STATS
+void dlmalloc_stats(void) {
+  internal_malloc_stats(gm);
+}
+#endif /* NO_MALLOC_STATS */
+
+int dlmallopt(int param_number, int value) {
+  return change_mparam(param_number, value);
+}
+
+size_t dlmalloc_usable_size(void* mem) {
+#ifndef __CHERI_PURE_CAPABILITY__
+  if (mem != 0) {
+    mchunkptr p = mem2chunk(mem);
+    if (is_inuse(p))
+      return chunksize(p) - overhead_for(p);
+  }
+  return 0;
+#else
+  return __builtin_cheri_length_get(mem);
+#endif
+}
diff --git a/contrib/dlmalloc/dlmalloc_nonreuse.h b/contrib/dlmalloc/dlmalloc_nonreuse.h
new file mode 100644
index 000000000000..a582c039722a
--- /dev/null
+++ b/contrib/dlmalloc/dlmalloc_nonreuse.h
@@ -0,0 +1,1006 @@
+/*-
+ * Copyright (c) 2018-2019 Hongyan Xia
+ * All rights reserved.
+ *
+ * This software was developed by SRI International and the University of
+ * Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-10-C-0237)
+ * ("CTSRD"), as part of the DARPA CRASH research programme.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * The original license header is as follows:
+ *
+ * This is a version (aka dlmalloc) of malloc/free/realloc written by
+ * Doug Lea and released to the public domain, as explained at
+ * http://creativecommons.org/publicdomain/zero/1.0/ Send questions,
+ * comments, complaints, performance data, etc to dl@cs.oswego.edu
+
+ * Version 2.8.6 Wed Aug 29 06:57:58 2012  Doug Lea
+ * Note: There may be an updated version of this malloc obtainable at
+ *       ftp://gee.cs.oswego.edu/pub/misc/malloc.c. Check before installing!
+ *
+
+* Quickstart
+
+  This library is all in one file to simplify the most common usage:
+  ftp it, compile it (-O3), and link it into another program. All of
+  the compile-time options default to reasonable values for use on
+  most platforms.  You might later want to step through various
+  compile-time and dynamic tuning options.
+
+  For convenience, an include file for code using this malloc is at:
+     ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.6.h
+  You don't really need this .h file unless you call functions not
+  defined in your system include files.  The .h file contains only the
+  excerpts from this file needed for using this malloc on ANSI C/C++
+  systems, so long as you haven't changed compile-time options about
+  naming and tuning parameters.  If you do, then you can create your
+  own malloc.h that does include all settings by cutting at the point
+  indicated below. Note that you may already by default be using a C
+  library containing a malloc that is based on some version of this
+  malloc (for example in linux). You might still want to use the one
+  in this file to customize settings or to avoid overheads associated
+  with library versions.
+
+* Vital statistics:
+
+  Supported pointer/size_t representation:       4 or 8 bytes
+       size_t MUST be an unsigned type of the same width as
+       pointers. (If you are using an ancient system that declares
+       size_t as a signed type, or need it to be a different width
+       than pointers, you can use a previous release of this malloc
+       (e.g. 2.7.2) supporting these.)
+
+  Alignment:                                     8 bytes (minimum)
+       This suffices for nearly all current machines and C compilers.
+       However, you can define MALLOC_ALIGNMENT to be wider than this
+       if necessary (up to 128bytes), at the expense of using more space.
+
+  Minimum overhead per allocated chunk:   4 or  8 bytes (if 4byte sizes)
+                                          8 or 16 bytes (if 8byte sizes)
+       Each malloced chunk has a hidden word of overhead holding size
+       and status information.
+
+  Minimum allocated size: 4-byte ptrs:  16 bytes    (including overhead)
+                          8-byte ptrs:  32 bytes    (including overhead)
+
+       Even a request for zero bytes (i.e., malloc(0)) returns a
+       pointer to something of the minimum allocatable size.
+       The maximum overhead wastage (i.e., number of extra bytes
+       allocated than were requested in malloc) is less than or equal
+       to the minimum size, except for requests >= mmap_threshold that
+       are serviced via mmap(), where the worst case wastage is about
+       32 bytes plus the remainder from a system page (the minimal
+       mmap unit); typically 4096 or 8192 bytes.
+
+  Security: static-safe; optionally more or less
+       The "security" of malloc refers to the ability of malicious
+       code to accentuate the effects of errors (for example, freeing
+       space that is not currently malloc'ed or overwriting past the
+       ends of chunks) in code that calls malloc.  This malloc
+       guarantees not to modify any memory locations below the base of
+       heap, i.e., static variables, even in the presence of usage
+       errors.  The routines additionally detect most improper frees
+       and reallocs.  All this holds as long as the static bookkeeping
+       for malloc itself is not corrupted by some other means.  This
+       is only one aspect of security -- these checks do not, and
+       cannot, detect all possible programming errors.
+
+       By default detected errors cause the program to abort (calling
+       "abort()"). You can override this to instead proceed past
+       errors by defining PROCEED_ON_ERROR.  In this case, a bad free
+       has no effect, and a malloc that encounters a bad address
+       caused by user overwrites will ignore the bad address by
+       dropping pointers and indices to all known memory. This may
+       be appropriate for programs that should continue if at all
+       possible in the face of programming errors, although they may
+       run out of memory because dropped memory is never reclaimed.
+
+       If you don't like either of these options, you can define
+       CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything
+       else. And if if you are sure that your program using malloc has
+       no errors or vulnerabilities, you can define INSECURE to 1,
+       which might (or might not) provide a small performance improvement.
+
+       It is also possible to limit the maximum total allocatable
+       space, using malloc_set_footprint_limit. This is not
+       designed as a security feature in itself (calls to set limits
+       are not screened or privileged), but may be useful as one
+       aspect of a secure implementation.
+
+  Thread-safety: NOT thread-safe unless USE_LOCKS defined non-zero
+       When USE_LOCKS is defined, each public call to malloc, free,
+       etc is surrounded with a lock. By default, this uses a plain
+       pthread mutex, win32 critical section, or a spin-lock if if
+       available for the platform and not disabled by setting
+       USE_SPIN_LOCKS=0.  However, if USE_RECURSIVE_LOCKS is defined,
+       recursive versions are used instead (which are not required for
+       base functionality but may be needed in layered extensions).
+       Using a global lock is not especially fast, and can be a major
+       bottleneck.  It is designed only to provide minimal protection
+       in concurrent environments, and to provide a basis for
+       extensions.  If you are using malloc in a concurrent program,
+       consider instead using nedmalloc
+       (http://www.nedprod.com/programs/portable/nedmalloc/) or
+       ptmalloc (See http://www.malloc.de), which are derived from
+       versions of this malloc.
+
+  System requirements: MMAP/MUNMAP
+
+  Compliance: I believe it is compliant with the Single Unix Specification
+       (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably
+       others as well.
+
+* Overview of algorithms
+
+  This is not the fastest, most space-conserving, most portable, or
+  most tunable malloc ever written. However it is among the fastest
+  while also being among the most space-conserving, portable and
+  tunable.  Consistent balance across these factors results in a good
+  general-purpose allocator for malloc-intensive programs.
+
+  In most ways, this malloc is a best-fit allocator. Generally, it
+  chooses the best-fitting existing chunk for a request, with ties
+  broken in approximately least-recently-used order. (This strategy
+  normally maintains low fragmentation.) However, for requests less
+  than 256bytes, it deviates from best-fit when there is not an
+  exactly fitting available chunk by preferring to use space adjacent
+  to that used for the previous small request, as well as by breaking
+  ties in approximately most-recently-used order. (These enhance
+  locality of series of small allocations.)  And for very large requests
+  (>= 256Kb by default), it relies on system memory mapping
+  facilities, if supported.  (This helps avoid carrying around and
+  possibly fragmenting memory used only for large chunks.)
+
+  All operations (except malloc_stats and mallinfo) have execution
+  times that are bounded by a constant factor of the number of bits in
+  a size_t, not counting any clearing in calloc or copying in realloc,
+  or actions surrounding MMAP that have times
+  proportional to the number of non-contiguous regions returned by
+  system allocation routines, which is often just 1. In real-time
+  applications, you can optionally suppress segment traversals using
+  NO_SEGMENT_TRAVERSAL, which assures bounded execution even when
+  system allocators return non-contiguous spaces, at the typical
+  expense of carrying around more memory and increased fragmentation.
+
+  The implementation is not very modular and seriously overuses
+  macros. Perhaps someday all C compilers will do as good a job
+  inlining modular code as can now be done by brute-force expansion,
+  but now, enough of them seem not to.
+
+  Some compilers issue a lot of warnings about code that is
+  dead/unreachable only on some platforms, and also about intentional
+  uses of negation on unsigned types. All known cases of each can be
+  ignored.
+
+  For a longer but out of date high-level description, see
+     http://gee.cs.oswego.edu/dl/html/malloc.html
+
+ -------------------------  Compile-time options ---------------------------
+
+Be careful in setting #define values for numerical constants of type
+size_t. On some systems, literal values are not automatically extended
+to size_t precision unless they are explicitly casted. You can also
+use the symbolic values MAX_SIZE_T, SIZE_T_ONE, etc below.
+
+DLMALLOC_EXPORT       default: extern
+  Defines how public APIs are declared. If you want to export via a
+  Windows DLL, you might define this as
+    #define DLMALLOC_EXPORT extern  __declspec(dllexport)
+  If you want a POSIX ELF shared object, you might use
+    #define DLMALLOC_EXPORT extern __attribute__((visibility("default")))
+
+MALLOC_ALIGNMENT         default: (size_t)(2 * sizeof(void *))
+  Controls the minimum alignment for malloc'ed chunks.  It must be a
+  power of two and at least 8, even on machines for which smaller
+  alignments would suffice. It may be defined as larger than this
+  though. Note however that code and data structures are optimized for
+  the case of 8-byte alignment.
+
+USE_LOCKS                default: 0 (false)
+  Causes each call to each public routine to be surrounded with
+  pthread or mutex lock/unlock. (If set true, this can be
+  overridden on a per-mspace basis for mspace versions.) If set to a
+  non-zero value other than 1, locks are used, but their
+  implementation is left out, so lock functions must be supplied manually,
+  as described below.
+
+USE_SPIN_LOCKS           default: 1 iff USE_LOCKS and spin locks available
+  If true, uses custom spin locks for locking. This is currently
+  supported only gcc >= 4.1, older gccs on x86 platforms, and recent
+  MS compilers.  Otherwise, posix locks or win32 critical sections are
+  used.
+
+USE_RECURSIVE_LOCKS      default: not defined
+  If defined nonzero, uses recursive (aka reentrant) locks, otherwise
+  uses plain mutexes. This is not required for malloc proper, but may
+  be needed for layered allocators such as nedmalloc.
+
+LOCK_AT_FORK            default: not defined
+  If defined nonzero, performs pthread_atfork upon initialization
+  to initialize child lock while holding parent lock. The implementation
+  assumes that pthread locks (not custom locks) are being used. In other
+  cases, you may need to customize the implementation.
+
+INSECURE                 default: 0
+  If true, omit checks for usage errors and heap space overwrites.
+
+USE_DL_PREFIX            default: NOT defined
+  Causes compiler to prefix all public routines with the string 'dl'.
+  This can be useful when you only want to use this malloc in one part
+  of a program, using your regular system malloc elsewhere.
+
+MALLOC_INSPECT_ALL       default: NOT defined
+  If defined, compiles malloc_inspect_all and mspace_inspect_all, that
+  perform traversal of all heap space.  Unless access to these
+  functions is otherwise restricted, you probably do not want to
+  include them in secure implementations.
+
+ABORT                    default: defined as abort()
+  Defines how to abort on failed checks.  On most systems, a failed
+  check cannot die with an "assert" or even print an informative
+  message, because the underlying print routines in turn call malloc,
+  which will fail again.  Generally, the best policy is to simply call
+  abort(). It's not very useful to do more than this because many
+  errors due to overwriting will show up as address faults (null, odd
+  addresses etc) rather than malloc-triggered checks, so will also
+  abort.  Also, most compilers know that abort() does not return, so
+  can better optimize code conditionally calling it.
+
+PROCEED_ON_ERROR           default: defined as 0 (false)
+  Controls whether detected bad addresses cause them to bypassed
+  rather than aborting. If set, detected bad arguments to free and
+  realloc are ignored. And all bookkeeping information is zeroed out
+  upon a detected overwrite of freed heap space, thus losing the
+  ability to ever return it from malloc again, but enabling the
+  application to proceed. If PROCEED_ON_ERROR is defined, the
+  static variable malloc_corruption_error_count is compiled in
+  and can be examined to see if errors have occurred. This option
+  generates slower code than the default abort policy.
+
+DEBUG                    default: NOT defined
+  The DEBUG setting is mainly intended for people trying to modify
+  this code or diagnose problems when porting to new platforms.
+  However, it may also be able to better isolate user errors than just
+  using runtime checks.  The assertions in the check routines spell
+  out in more detail the assumptions and invariants underlying the
+  algorithms.  The checking is fairly extensive, and will slow down
+  execution noticeably. Calling malloc_stats or mallinfo with DEBUG
+  set will attempt to check every non-mmapped allocated and free chunk
+  in the course of computing the summaries.
+
+ABORT_ON_ASSERT_FAILURE   default: defined as 1 (true)
+  Debugging assertion failures can be nearly impossible if your
+  version of the assert macro causes malloc to be called, which will
+  lead to a cascade of further failures, blowing the runtime stack.
+  ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(),
+  which will usually make debugging easier.
+
+MALLOC_FAILURE_ACTION     default: sets errno to ENOMEM, or no-op on win32
+  The action to take before "return 0" when malloc fails to be able to
+  return memory because there is none available.
+
+NO_SEGMENT_TRAVERSAL       default: 0
+  If non-zero, suppresses traversals of memory segments
+  returned by CALL_MMAP. This disables
+  merging of segments that are contiguous, and selectively
+  releasing them to the OS if unused, but bounds execution times.
+
+HAVE_MMAP                 default: 1 (true)
+  True if this system supports mmap or an emulation of it.
+  Note: A single call to MUNMAP is assumed to be
+  able to unmap memory that may have be allocated using multiple calls
+  to MMAP, so long as they are adjacent.
+
+MMAP_CLEARS               default: 1 except on WINCE.
+  True if mmap clears memory so calloc doesn't need to. This is true
+  for standard unix mmap using /dev/zero.
+
+USE_BUILTIN_FFS            default: 0 (i.e., not used)
+  Causes malloc to use the builtin ffs() function to compute indices.
+  Some compilers may recognize and intrinsify ffs to be faster than the
+  supplied C version. Also, the case of x86 using gcc is special-cased
+  to an asm instruction, so is already as fast as it can be, and so
+  this setting has no effect. Similarly for Win32 under recent MS compilers.
+  (On most x86s, the asm version is only slightly faster than the C version.)
+
+malloc_getpagesize         default: derive from system includes, or 4096.
+  The system page size. To the extent possible, this malloc manages
+  memory from the system in page-size units.  This may be (and
+  usually is) a function rather than a constant.
+
+USE_DEV_RANDOM             default: 0 (i.e., not used)
+  Causes malloc to use /dev/random to initialize secure magic seed for
+  stamping footers. Otherwise, the current time is used.
+
+NO_MALLINFO                default: 0
+  If defined, don't compile "mallinfo". This can be a simple way
+  of dealing with mismatches between system declarations and
+  those in this file.
+
+MALLINFO_FIELD_TYPE        default: size_t
+  The type of the fields in the mallinfo struct. This was originally
+  defined as "int" in SVID etc, but is more usefully defined as
+  size_t. The value is used only if  HAVE_USR_INCLUDE_MALLOC_H is not set
+
+NO_MALLOC_STATS            default: 0
+  If defined, don't compile "malloc_stats". This avoids calls to
+  fprintf and bringing in stdio dependencies you might not want.
+
+REALLOC_ZERO_BYTES_FREES    default: not defined
+  This should be set if a call to realloc with zero bytes should
+  be the same as a call to free. Some people think it should. Otherwise,
+  since this malloc returns a unique pointer for malloc(0), so does
+  realloc(p, 0).
+
+LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H
+LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H,  LACKS_ERRNO_H
+LACKS_STDLIB_H LACKS_SCHED_H LACKS_TIME_H  default: NOT defined
+  Define these if your system does not have these header files.
+  You might need to manually insert some of the declarations they provide.
+
+DEFAULT_GRANULARITY        default: 64K.
+      Also settable using mallopt(M_GRANULARITY, x)
+  The unit for allocating and deallocating memory from the system.
+  However, systems with MMAP tend to
+  either require or encourage larger granularities.  You can increase
+  this value to prevent system allocation functions to be called so
+  often, especially if they are slow.  The value must be at least one
+  page and must be a power of two.  Setting to 0 causes initialization
+  to either page size or win32 region size.  (Note: In previous
+  versions of malloc, the equivalent of this option was called
+  "TOP_PAD")
+
+DEFAULT_TRIM_THRESHOLD    default: 2MB
+      Also settable using mallopt(M_TRIM_THRESHOLD, x)
+  The maximum amount of unused top-most memory to keep before
+  releasing via malloc_trim in free(). Because
+  trimming via sbrk can be slow on some systems, and can sometimes be
+  wasteful (in cases where programs immediately afterward allocate
+  more large chunks) the value should be high enough so that your
+  overall system performance would improve by releasing this much
+  memory.  As a rough guide, you might set to a value close to the
+  average size of a process (program) running on your system.
+  Releasing this much memory would allow such a process to run in
+  memory.  Generally, it is worth tuning trim thresholds when a
+  program undergoes phases where several large chunks are allocated
+  and released in ways that can reuse each other's storage, perhaps
+  mixed with phases where there are no such chunks at all. The trim
+  value must be greater than page size to have any useful effect.  To
+  disable trimming completely, you can set to MAX_SIZE_T. Note that the trick
+  some people use of mallocing a huge space and then freeing it at
+  program startup, in an attempt to reserve system memory, doesn't
+  have the intended effect under automatic trimming, since that memory
+  will immediately be returned to the system.
+
+DEFAULT_MMAP_THRESHOLD       default: 256K
+      Also settable using mallopt(M_MMAP_THRESHOLD, x)
+  The request size threshold for using MMAP to directly service a
+  request. Requests of at least this size that cannot be allocated
+  using already-existing space will be serviced via mmap.  (If enough
+  normal freed space already exists it is used instead.)  Using mmap
+  segregates relatively large chunks of memory so that they can be
+  individually obtained and released from the host system. A request
+  serviced through mmap is never reused by any other request (at least
+  not directly; the system may just so happen to remap successive
+  requests to the same locations).  Segregating space in this way has
+  the benefits that: Mmapped space can always be individually released
+  back to the system, which helps keep the system level memory demands
+  of a long-lived program low.  Also, mapped memory doesn't become
+  `locked' between other chunks, as can happen with normally allocated
+  chunks, which means that even trimming via malloc_trim would not
+  release them.  However, it has the disadvantage that the space
+  cannot be reclaimed, consolidated, and then used to service later
+  requests, as happens with normal chunks.  The advantages of mmap
+  nearly always outweigh disadvantages for "large" chunks, but the
+  value of "large" may vary across systems.  The default is an
+  empirically derived value that works well in most systems. You can
+  disable mmap by setting to MAX_SIZE_T.
+
+MAX_RELEASE_CHECK_RATE   default: 4095 unless not HAVE_MMAP
+  The number of consolidated frees between checks to release
+  unused segments when freeing. When using non-contiguous segments,
+  especially with multiple mspaces, checking only for topmost space
+  doesn't always suffice to trigger trimming. To compensate for this,
+  free() will, with a period of MAX_RELEASE_CHECK_RATE (or the
+  current number of segments, if greater) try to release unused
+  segments to the OS when freeing chunks that result in
+  consolidation. The best value for this parameter is a compromise
+  between slowing down frees with relatively costly checks that
+  rarely trigger versus holding on to unused memory. To effectively
+  disable, set to MAX_SIZE_T. This may lead to a very slight speed
+  improvement at the expense of carrying around more memory.
+
+DEFAULT_UNMAP_THRESHOLD	default: MAX_SIZE_T / PAGESIZE
+  Minimum number of adjacent pages required to unmap the middle of a
+  quanintined chunk.  Smaller unmaps may be performed when collessing
+  a smaller chunk into a large chunk which is already unmapped to
+  maintain the invariant that an unmapped chunk has all interior pages
+  unmapped.
+*/
+
+// Override default dlmalloc compile-time parameters here.
+#define USE_LOCKS 1
+#define USE_SPIN_LOCKS 1
+#define USE_RECURSIVE_LOCKS 0
+#define HAVE_MMAP 1
+#define MAX_RELEASE_CHECK_RATE 4095
+//#define MALLOC_UTRACE
+
+// FIXME: These are partially hardcoded values.
+#define BYTE_ALIGN_MASK (7U)
+#define PAGE_SHIFT (12U)
+#define MALLOC_ALIGN_BYTESHIFT (4U)
+#define MALLOC_ALIGN_BITSHIFT (MALLOC_ALIGN_BYTESHIFT+3U)
+
+#define DEFAULT_GRANULARITY (16 * 1024 * 1024)
+//#define DEFAULT_GRANULARITY ((size_t)1U<<(PAGE_SHIFT+MALLOC_ALIGN_BITSHIFT))
+#define DEFAULT_MMAP_THRESHOLD (DEFAULT_GRANULARITY<<2U)
+
+#ifndef DEFAULT_FREEBUF_PERCENT
+#define DEFAULT_FREEBUF_PERCENT ((double)0.2)
+#endif
+#ifndef DEFAULT_MAX_FREEBUFBYTES
+#define DEFAULT_MAX_FREEBUFBYTES MAX_SIZE_T
+#endif
+#ifndef DEFAULT_MIN_FREEBUFBYTES
+#define DEFAULT_MIN_FREEBUFBYTES (2 * 1024 * 1024)
+#endif
+
+#define MAX_UNMAP_THRESHOLD (MAX_SIZE_T >> PAGE_SHIFT)
+#ifndef DEFAULT_UNMAP_THRESHOLD
+#define DEFAULT_UNMAP_THRESHOLD MAX_UNMAP_THRESHOLD
+#endif
+
+#ifndef CONSOLIDATE_ON_FREE
+#ifdef CAPREVOKE
+#define CONSOLIDATE_ON_FREE 1
+#else
+#define CONSOLIDATE_ON_FREE 0
+#endif
+#endif
+
+#ifndef SUPPORT_UNMAP
+#define SUPPORT_UNMAP 1
+#endif
+
+#ifndef ZERO_MEMORY
+#ifdef CAPREVOKE
+#define ZERO_MEMORY 1
+#else
+#define ZERO_MEMORY 0
+#endif
+#endif
+
+//-----------------------------------------------------------------------------
+
+// Enable the report of sweeping statistics.
+#ifndef SWEEP_STATS
+// Some platforms depend on malloc when doing atexit, so disable it by default.
+#define SWEEP_STATS 0
+#endif // SWEEP_STATS
+
+/* Version identifier to allow people to support multiple versions */
+#ifndef DLMALLOC_VERSION
+#define DLMALLOC_VERSION 20806
+#endif /* DLMALLOC_VERSION */
+
+#ifndef DLMALLOC_EXPORT
+#define DLMALLOC_EXPORT extern
+#endif
+
+#if defined(DARWIN) || defined(_DARWIN)
+/* Mac OSX docs advise not to use sbrk; it seems better to use mmap */
+#define HAVE_MMAP 1
+/* OSX allocators provide 16 byte alignment */
+#ifndef MALLOC_ALIGNMENT
+#define MALLOC_ALIGNMENT ((size_t)16U)
+#endif
+#endif  /* DARWIN */
+
+#ifndef LACKS_SYS_TYPES_H
+#include <sys/types.h>  /* For size_t */
+#endif  /* LACKS_SYS_TYPES_H */
+#include <stddef.h>	/* For ptrdiff_t */
+
+/* The maximum possible size_t value has all bits set */
+#define MAX_SIZE_T           (~(size_t)0)
+
+#ifndef USE_LOCKS /* ensure true if spin or recursive locks set */
+#define USE_LOCKS  ((defined(USE_SPIN_LOCKS) && USE_SPIN_LOCKS != 0) || \
+                    (defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0))
+#endif /* USE_LOCKS */
+
+#if USE_LOCKS /* Spin locks for gcc >= 4.1, older gcc on x86 */
+#if (defined(__GNUC__) &&                                              \
+      ((__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) ||      \
+       defined(__i386__) || defined(__x86_64__)))
+#ifndef USE_SPIN_LOCKS
+#define USE_SPIN_LOCKS 1
+#endif /* USE_SPIN_LOCKS */
+#elif USE_SPIN_LOCKS
+#error "USE_SPIN_LOCKS defined without implementation"
+#endif /* ... locks available... */
+#elif !defined(USE_SPIN_LOCKS)
+#define USE_SPIN_LOCKS 0
+#endif /* USE_LOCKS */
+
+#ifndef MALLOC_ALIGNMENT
+#define MALLOC_ALIGNMENT ((size_t)(2 * sizeof(void *)))
+#endif  /* MALLOC_ALIGNMENT */
+#ifndef ABORT
+#define ABORT  abort()
+#endif  /* ABORT */
+#ifndef ABORT_ON_ASSERT_FAILURE
+#define ABORT_ON_ASSERT_FAILURE 1
+#endif  /* ABORT_ON_ASSERT_FAILURE */
+
+#ifndef INSECURE
+#define INSECURE 0
+#endif  /* INSECURE */
+#ifndef MALLOC_INSPECT_ALL
+#define MALLOC_INSPECT_ALL 0
+#endif  /* MALLOC_INSPECT_ALL */
+#ifndef HAVE_MMAP
+#define HAVE_MMAP 1
+#endif  /* HAVE_MMAP */
+#ifndef MMAP_CLEARS
+#define MMAP_CLEARS 1
+#endif  /* MMAP_CLEARS */
+#ifndef MALLOC_FAILURE_ACTION
+#define MALLOC_FAILURE_ACTION  errno = ENOMEM;
+#endif  /* MALLOC_FAILURE_ACTION */
+#ifndef DEFAULT_GRANULARITY
+#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U)
+#endif  /* DEFAULT_GRANULARITY */
+
+#ifndef DEFAULT_TRIM_THRESHOLD
+#define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U)
+#endif  /* DEFAULT_TRIM_THRESHOLD */
+#ifndef __CHERI_PURE_CAPABILITY__
+#ifndef DEFAULT_MMAP_THRESHOLD
+#if HAVE_MMAP
+#define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U)
+#else   /* HAVE_MMAP */
+#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T
+#endif  /* HAVE_MMAP */
+#endif  /* DEFAULT_MMAP_THRESHOLD */
+#else	/* __CHERI_PURE_CAPABILITY__ */
+#undef DEFAULT_MMAP_THRESHOLD
+/*
+ * We need a containing structure for all allocations so we can locate
+ * them in the free() path and so we have somewhere to hang the shadow
+ * capability.
+ */
+#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T
+#endif	/* __CHERI_PURE_CAPABILITY__ */
+#ifndef MAX_RELEASE_CHECK_RATE
+#if HAVE_MMAP
+#define MAX_RELEASE_CHECK_RATE 4095
+#else
+#define MAX_RELEASE_CHECK_RATE MAX_SIZE_T
+#endif /* HAVE_MMAP */
+#endif /* MAX_RELEASE_CHECK_RATE */
+#ifndef USE_BUILTIN_FFS
+#define USE_BUILTIN_FFS 0
+#endif  /* USE_BUILTIN_FFS */
+#ifndef USE_DEV_RANDOM
+#define USE_DEV_RANDOM 0
+#endif  /* USE_DEV_RANDOM */
+#ifndef NO_MALLINFO
+#define NO_MALLINFO 0
+#endif  /* NO_MALLINFO */
+#ifndef MALLINFO_FIELD_TYPE
+#define MALLINFO_FIELD_TYPE size_t
+#endif  /* MALLINFO_FIELD_TYPE */
+#ifndef NO_MALLOC_STATS
+#define NO_MALLOC_STATS 0
+#endif  /* NO_MALLOC_STATS */
+#ifndef NO_SEGMENT_TRAVERSAL
+#define NO_SEGMENT_TRAVERSAL 0
+#endif /* NO_SEGMENT_TRAVERSAL */
+
+/*
+  mallopt tuning options.  SVID/XPG defines four standard parameter
+  numbers for mallopt, normally defined in malloc.h.  None of these
+  are used in this malloc, so setting them has no effect. But this
+  malloc does support the following options.
+*/
+
+#define M_TRIM_THRESHOLD     (-1)
+#define M_GRANULARITY        (-2)
+#define M_MMAP_THRESHOLD     (-3)
+#define M_MIN_FREEBUFBYTES   (-4)
+#define M_MAX_FREEBUFBYTES   (-5)
+#define M_MAX_FREEBUF_PERCENT (-6)
+#define M_UNMAP_THRESHOLD    (-7)
+
+/* ------------------------ Mallinfo declarations ------------------------ */
+
+#if !NO_MALLINFO
+/*
+  This version of malloc supports the standard SVID/XPG mallinfo
+  routine that returns a struct containing usage properties and
+  statistics. It should work on any system that has a
+  /usr/include/malloc.h defining struct mallinfo.  The main
+  declaration needed is the mallinfo struct that is returned (by-copy)
+  by mallinfo().  The malloinfo struct contains a bunch of fields that
+  are not even meaningful in this version of malloc.  These fields are
+  are instead filled by mallinfo() with other numbers that might be of
+  interest.
+
+  HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
+  /usr/include/malloc.h file that includes a declaration of struct
+  mallinfo.  If so, it is included; else a compliant version is
+  declared below.  These must be precisely the same for mallinfo() to
+  work.  The original SVID version of this struct, defined on most
+  systems with mallinfo, declares all fields as ints. But some others
+  define as unsigned long. If your system defines the fields using a
+  type of different width than listed here, you MUST #include your
+  system version and #define HAVE_USR_INCLUDE_MALLOC_H.
+*/
+
+/* #define HAVE_USR_INCLUDE_MALLOC_H */
+
+#ifdef HAVE_USR_INCLUDE_MALLOC_H
+#include "/usr/include/malloc.h"
+#else /* HAVE_USR_INCLUDE_MALLOC_H */
+#ifndef STRUCT_MALLINFO_DECLARED
+/* HP-UX (and others?) redefines mallinfo unless _STRUCT_MALLINFO is defined */
+#define _STRUCT_MALLINFO
+#define STRUCT_MALLINFO_DECLARED 1
+struct mallinfo {
+  MALLINFO_FIELD_TYPE arena;    /* non-mmapped space allocated from system */
+  MALLINFO_FIELD_TYPE ordblks;  /* number of free chunks */
+  MALLINFO_FIELD_TYPE smblks;   /* always 0 */
+  MALLINFO_FIELD_TYPE hblks;    /* always 0 */
+  MALLINFO_FIELD_TYPE hblkhd;   /* space in mmapped regions */
+  MALLINFO_FIELD_TYPE usmblks;  /* maximum total allocated space */
+  MALLINFO_FIELD_TYPE fsmblks;  /* always 0 */
+  MALLINFO_FIELD_TYPE uordblks; /* total allocated space */
+  MALLINFO_FIELD_TYPE fordblks; /* total free space */
+  MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */
+};
+#endif /* STRUCT_MALLINFO_DECLARED */
+#endif /* HAVE_USR_INCLUDE_MALLOC_H */
+#endif /* NO_MALLINFO */
+
+/*
+  Try to persuade compilers to inline. The most critical functions for
+  inlining are defined as macros, so these aren't used for them.
+*/
+
+#ifndef FORCEINLINE
+  #if defined(__GNUC__)
+#define FORCEINLINE __inline __attribute__ ((always_inline))
+  #endif
+#endif
+#ifndef NOINLINE
+  #if defined(__GNUC__)
+    #define NOINLINE __attribute__ ((noinline))
+  #else
+    #define NOINLINE
+  #endif
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#ifndef FORCEINLINE
+ #define FORCEINLINE inline
+#endif
+#endif /* __cplusplus */
+#ifndef FORCEINLINE
+ #define FORCEINLINE
+#endif
+
+/* ------------------- Declarations of public routines ------------------- */
+
+#ifndef USE_DL_PREFIX
+#define dlcalloc               calloc
+#define dlfree                 free
+#define dlmalloc               malloc
+#define dlposix_memalign       posix_memalign
+#define dlaligned_alloc        aligned_alloc
+#define dlrealloc              realloc
+#define dlmallinfo             mallinfo
+#define dlmallopt              mallopt
+#define dlmalloc_trim          malloc_trim
+#define dlmalloc_stats         malloc_stats
+#define dlmalloc_usable_size   malloc_usable_size
+#define dlmalloc_footprint     malloc_footprint
+#define dlmalloc_max_footprint malloc_max_footprint
+#define dlmalloc_footprint_limit malloc_footprint_limit
+#define dlmalloc_set_footprint_limit malloc_set_footprint_limit
+#define dlmalloc_inspect_all   malloc_inspect_all
+#define dlmalloc_revoke        malloc_revoke
+#endif /* USE_DL_PREFIX */
+
+/*
+  malloc(size_t n)
+  Returns a pointer to a newly allocated chunk of at least n bytes, or
+  null if no space is available, in which case errno is set to ENOMEM
+  on ANSI C systems.
+
+  If n is zero, malloc returns a minimum-sized chunk. (The minimum
+  size is 16 bytes on most 32bit systems, and 32 bytes on 64bit
+  systems.)  Note that size_t is an unsigned type, so calls with
+  arguments that would be negative if signed are interpreted as
+  requests for huge amounts of space, which will often fail. The
+  maximum supported value of n differs across systems, but is in all
+  cases less than the maximum representable value of a size_t.
+*/
+DLMALLOC_EXPORT void* dlmalloc(size_t);
+
+/*
+  free(void* p)
+  Releases the chunk of memory pointed to by p, that had been previously
+  allocated using malloc or a related routine such as realloc.
+  It has no effect if p is null. If p was not malloced or already
+  freed, free(p) will by default cause the current program to abort.
+*/
+DLMALLOC_EXPORT void  dlfree(void*);
+
+/*
+  calloc(size_t n_elements, size_t element_size);
+  Returns a pointer to n_elements * element_size bytes, with all locations
+  set to zero.
+*/
+DLMALLOC_EXPORT void* dlcalloc(size_t, size_t);
+
+/*
+  realloc(void* p, size_t n)
+  Returns a pointer to a chunk of size n that contains the same data
+  as does chunk p up to the minimum of (n, p's size) bytes, or null
+  if no space is available.
+
+  The returned pointer may or may not be the same as p. The algorithm
+  prefers extending p in most cases when possible, otherwise it
+  employs the equivalent of a malloc-copy-free sequence.
+
+  If p is null, realloc is equivalent to malloc.
+
+  If space is not available, realloc returns null, errno is set (if on
+  ANSI) and p is NOT freed.
+
+  if n is for fewer bytes than already held by p, the newly unused
+  space is lopped off and freed if possible.  realloc with a size
+  argument of zero (re)allocates a minimum-sized chunk.
+
+  The old unix realloc convention of allowing the last-free'd chunk
+  to be used as an argument to realloc is not supported.
+*/
+DLMALLOC_EXPORT void* dlrealloc(void*, size_t);
+
+/*
+  int posix_memalign(void** pp, size_t alignment, size_t n);
+  Allocates a chunk of n bytes, aligned in accord with the alignment
+  argument. Differs from memalign only in that it (1) assigns the
+  allocated memory to *pp rather than returning it, (2) fails and
+  returns EINVAL if the alignment is not a power of two (3) fails and
+  returns ENOMEM if memory cannot be allocated.
+*/
+DLMALLOC_EXPORT int dlposix_memalign(void**, size_t, size_t);
+
+/*
+  void *aligned_alloc(size_t alignment, size_t size);
+  C11 interface to allocate aligned memory.
+*/
+DLMALLOC_EXPORT void *aligned_alloc(size_t, size_t);
+
+/*
+  mallopt(int parameter_number, int parameter_value)
+  Sets tunable parameters The format is to provide a
+  (parameter-number, parameter-value) pair.  mallopt then sets the
+  corresponding parameter to the argument value if it can (i.e., so
+  long as the value is meaningful), and returns 1 if successful else
+  0.  To workaround the fact that mallopt is specified to use int,
+  not size_t parameters, the value -1 is specially treated as the
+  maximum unsigned size_t value.
+
+  SVID/XPG/ANSI defines four standard param numbers for mallopt,
+  normally defined in malloc.h.  None of these are use in this malloc,
+  so setting them has no effect. But this malloc also supports other
+  options in mallopt. See below for details.  Briefly, supported
+  parameters are as follows (listed defaults are for "typical"
+  configurations).
+
+  Symbol            param #  default    allowed param values
+  M_TRIM_THRESHOLD     -1   2*1024*1024   any   (-1 disables)
+  M_GRANULARITY        -2     page size   any power of 2 >= page size
+  M_MMAP_THRESHOLD     -3      256*1024   any   (or 0 if no MMAP support)
+*/
+DLMALLOC_EXPORT int dlmallopt(int, int);
+
+/*
+  malloc_footprint();
+  Returns the number of bytes obtained from the system.  The total
+  number of bytes allocated by malloc, realloc etc., is less than this
+  value. Unlike mallinfo, this function returns only a precomputed
+  result, so can be called frequently to monitor memory consumption.
+  Even if locks are otherwise defined, this function does not use them,
+  so results might not be up to date.
+*/
+DLMALLOC_EXPORT size_t dlmalloc_footprint(void);
+
+/*
+  malloc_max_footprint();
+  Returns the maximum number of bytes obtained from the system. This
+  value will be greater than current footprint if deallocated space
+  has been reclaimed by the system. The peak number of bytes allocated
+  by malloc, realloc etc., is less than this value. Unlike mallinfo,
+  this function returns only a precomputed result, so can be called
+  frequently to monitor memory consumption.  Even if locks are
+  otherwise defined, this function does not use them, so results might
+  not be up to date.
+*/
+DLMALLOC_EXPORT size_t dlmalloc_max_footprint(void);
+
+/*
+  malloc_footprint_limit();
+  Returns the number of bytes that the heap is allowed to obtain from
+  the system, returning the last value returned by
+  malloc_set_footprint_limit, or the maximum size_t value if
+  never set. The returned value reflects a permission. There is no
+  guarantee that this number of bytes can actually be obtained from
+  the system.
+*/
+DLMALLOC_EXPORT size_t dlmalloc_footprint_limit();
+
+/*
+  malloc_set_footprint_limit();
+  Sets the maximum number of bytes to obtain from the system, causing
+  failure returns from malloc and related functions upon attempts to
+  exceed this value. The argument value may be subject to page
+  rounding to an enforceable limit; this actual value is returned.
+  Using an argument of the maximum possible size_t effectively
+  disables checks. If the argument is less than or equal to the
+  current malloc_footprint, then all future allocations that require
+  additional system memory will fail. However, invocation cannot
+  retroactively deallocate existing used memory.
+*/
+DLMALLOC_EXPORT size_t dlmalloc_set_footprint_limit(size_t bytes);
+
+#if MALLOC_INSPECT_ALL
+/*
+  malloc_inspect_all(void(*handler)(void *start,
+                                    void *end,
+                                    size_t used_bytes,
+                                    void* callback_arg),
+                      void* arg);
+  Traverses the heap and calls the given handler for each managed
+  region, skipping all bytes that are (or may be) used for bookkeeping
+  purposes.  Traversal does not include include chunks that have been
+  directly memory mapped. Each reported region begins at the start
+  address, and continues up to but not including the end address.  The
+  first used_bytes of the region contain allocated data. If
+  used_bytes is zero, the region is unallocated. The handler is
+  invoked with the given callback argument. If locks are defined, they
+  are held during the entire traversal. It is a bad idea to invoke
+  other malloc functions from within the handler.
+
+  For example, to count the number of in-use chunks with size greater
+  than 1000, you could write:
+  static int count = 0;
+  void count_chunks(void* start, void* end, size_t used, void* arg) {
+    if (used >= 1000) ++count;
+  }
+  then:
+    malloc_inspect_all(count_chunks, NULL);
+
+  malloc_inspect_all is compiled only if MALLOC_INSPECT_ALL is defined.
+*/
+DLMALLOC_EXPORT void dlmalloc_inspect_all(void(*handler)(void*, void *, size_t, void*),
+                           void* arg);
+
+#endif /* MALLOC_INSPECT_ALL */
+
+#if !NO_MALLINFO
+/*
+  mallinfo()
+  Returns (by copy) a struct containing various summary statistics:
+
+  arena:     current total non-mmapped bytes allocated from system
+  ordblks:   the number of free chunks
+  smblks:    always zero.
+  hblks:     current number of mmapped regions
+  hblkhd:    total bytes held in mmapped regions
+  usmblks:   the maximum total allocated space. This will be greater
+                than current total if trimming has occurred.
+  fsmblks:   always zero
+  uordblks:  current total allocated space (normal or mmapped)
+  fordblks:  total free space
+  keepcost:  the maximum number of bytes that could ideally be released
+               back to system via malloc_trim. ("ideally" means that
+               it ignores page restrictions etc.)
+
+  Because these fields are ints, but internal bookkeeping may
+  be kept as longs, the reported values may wrap around zero and
+  thus be inaccurate.
+*/
+DLMALLOC_EXPORT struct mallinfo dlmallinfo(void);
+#endif /* NO_MALLINFO */
+
+/*
+  malloc_trim(size_t pad);
+
+  If possible, gives memory back to the system (via negative arguments
+  to sbrk) if there is unused memory at the `high' end of the malloc
+  pool or in unused MMAP segments. You can call this after freeing
+  large blocks of memory to potentially reduce the system-level memory
+  requirements of a program. However, it cannot guarantee to reduce
+  memory. Under some allocation patterns, some large free blocks of
+  memory will be locked between two used chunks, so they cannot be
+  given back to the system.
+
+  The `pad' argument to malloc_trim represents the amount of free
+  trailing space to leave untrimmed. If this argument is zero, only
+  the minimum amount of memory to maintain internal data structures
+  will be left. Non-zero arguments can be supplied to maintain enough
+  trailing space to service future expected allocations without having
+  to re-obtain memory from the system.
+
+  Malloc_trim returns 1 if it actually released any memory, else 0.
+*/
+DLMALLOC_EXPORT int  dlmalloc_trim(size_t);
+
+/*
+  malloc_stats();
+  Prints on stderr the amount of space obtained from the system (both
+  via sbrk and mmap), the maximum amount (which may be more than
+  current if malloc_trim and/or munmap got called), and the current
+  number of bytes allocated via malloc (or realloc, etc) but not yet
+  freed. Note that this is the number of bytes allocated, not the
+  number requested. It will be larger than the number requested
+  because of alignment and bookkeeping overhead. Because it includes
+  alignment wastage as being in use, this figure may be greater than
+  zero even when no user-level chunks are allocated.
+
+  The reported current and maximum system memory can be inaccurate if
+  a program makes other calls to system memory allocation functions
+  (normally sbrk) outside of malloc.
+
+  malloc_stats prints only the most commonly interesting statistics.
+  More information can be obtained by calling mallinfo.
+*/
+DLMALLOC_EXPORT void  dlmalloc_stats(void);
+
+/*
+  malloc_usable_size(void* p);
+
+  Returns the number of bytes you can actually use in
+  an allocated chunk, which may be more than you requested (although
+  often not) due to alignment and minimum size constraints.
+  You can use this many bytes without worrying about
+  overwriting other allocated objects. This is not a particularly great
+  programming practice. malloc_usable_size can be more useful in
+  debugging and assertions, for example:
+
+  p = malloc(n);
+  assert(malloc_usable_size(p) >= 256);
+*/
+size_t dlmalloc_usable_size(void*);
+
+DLMALLOC_EXPORT void  dlmalloc_revoke(void);
+
+#ifdef __cplusplus
+}  /* end of extern "C" */
+#endif /* __cplusplus */
diff --git a/contrib/dlmalloc/dlmalloc_test.c b/contrib/dlmalloc/dlmalloc_test.c
new file mode 100644
index 000000000000..a66d0971d5ef
--- /dev/null
+++ b/contrib/dlmalloc/dlmalloc_test.c
@@ -0,0 +1,186 @@
+#include <stdarg.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <cheri/cheric.h>
+#include "dlmalloc_nonreuse.h"
+
+#ifndef nitems
+#define nitems(x)	(sizeof((x)) / sizeof((x)[0]))
+#endif
+
+const size_t sizes[] = {
+	1,
+	2,
+	3, 4, 5,
+	7, 8, 9,
+	15, 16, 17,
+	31, 32, 33,
+	63, 64, 65,
+	127, 128, 129,
+	255, 256, 257,
+	511, 512, 513,
+	1023, 1024, 1025,
+	2047, 2048, 2049,
+	4095, 4096, 4097,
+	1024 * 1024 - 1, 1024 * 1024, 1024 * 1024 + 1
+};
+
+#define bad_ptr(ptr, fmt, ...)	\
+    _bad_ptr((ptr), __FILE__, __LINE__, (fmt), ##__VA_ARGS__)
+
+void
+_bad_ptr(void *ptr, const char *file, int line, const char *fmt, ...)
+{
+	va_list ap;
+
+	printf("%s:%d: bad pointer %#p\n", file, line, ptr);
+	va_start(ap, fmt);
+	vprintf(fmt, ap);
+	va_end(ap);
+	if (fmt[strlen(fmt) - 1] != '\n')
+		printf("\n");
+	abort();
+}
+
+static void *
+malloc_checked(size_t bytes)
+{
+	void *ptr;
+
+	ptr = dlmalloc(bytes);
+	if (bytes == 0 && ptr == NULL)
+		return (ptr);
+	if (!cheri_gettag(ptr))
+		bad_ptr(ptr, "missing tag");
+	if (cheri_getlen(ptr) < bytes)
+		bad_ptr(ptr, "length is less than %zu", bytes);
+#ifdef CHERI_SET_BOUNDS
+	if (cheri_getoffset(ptr) != 0)
+		bad_ptr(ptr, "pointer has non-zero offset");
+#endif
+	return (ptr);
+}
+
+static void *
+calloc_checked(size_t number, size_t size)
+{
+	void *ptr;
+
+	ptr = dlcalloc(number, size);
+	if (number * size == 0 && ptr == NULL)
+		return (ptr);
+	if (!cheri_gettag(ptr))
+		bad_ptr(ptr, "missing tag");
+	if (cheri_getlen(ptr) < number * size)
+		bad_ptr(ptr, "length is less than %zu", number * size);
+#ifdef CHERI_SET_BOUNDS
+	if (cheri_getoffset(ptr) != 0)
+		bad_ptr(ptr, "pointer has non-zero offset");
+#endif
+	return (ptr);
+}
+
+static void *
+realloc_checked(void *optr, size_t bytes)
+{
+	void *ptr;
+
+	ptr = dlrealloc(optr, bytes);
+	if (bytes == 0 && ptr == NULL)
+		return (ptr);
+	if (!cheri_gettag(ptr))
+		bad_ptr(ptr, "missing tag");
+	if (cheri_getlen(ptr) < bytes)
+		bad_ptr(ptr, "length is less than %zu", bytes);
+#ifdef CHERI_SET_BOUNDS
+	if (cheri_getoffset(ptr) != 0)
+		bad_ptr(ptr, "pointer has non-zero offset");
+#endif
+	return (ptr);
+}
+
+int
+main(int argc, char **argv)
+{
+	void *ptrs[nitems(sizes)];
+	int i;
+
+	/* ----- malloc tests ----- */
+	for (i = 0; i < nitems(sizes); i++)
+		ptrs[i] = malloc_checked(sizes[i]);
+#ifdef CAPREVOKE
+	dlmalloc_revoke();
+	for (i = 0; i < nitems(sizes); i++)
+		if (cheri_getperm(ptrs[i]) == 0)
+			bad_ptr(ptrs[i],
+			    "ptrs[%d] is revoked before being freed", i);
+#endif
+	/* Free even pointers */
+	for (i = 0; i < nitems(sizes); i += 2)
+		dlfree(ptrs[i]);
+#ifdef CAPREVOKE
+	dlmalloc_revoke();
+	/*
+	 * Check that even pointers were revoked and odd ones were not,
+	 * freeing odd ones.
+	 */
+	for (i = 0; i < nitems(sizes); i += 2)
+		if (cheri_getperm(ptrs[i]) != 0)
+			bad_ptr(ptrs[i], "ptrs[%d] was not revoked", i);
+	for (i = 1; i < nitems(sizes); i += 2)
+		if (cheri_getperm(ptrs[i]) == 0)
+			bad_ptr(ptrs[i],
+			    "ptrs[%d] is revoked before being freed", i);
+	dlmalloc_revoke();
+#endif
+	/* Free odd pointers */
+	for (i = 1; i < nitems(sizes); i += 2)
+		dlfree(ptrs[i]);
+
+	/* ----- calloc tests ----- */
+	for (i = 0; i < nitems(sizes); i++)
+		ptrs[i] = calloc_checked(1, sizes[i]);
+#ifdef CAPREVOKE
+	dlmalloc_revoke();
+	for (i = 0; i < nitems(sizes); i++)
+		if (cheri_getperm(ptrs[i]) == 0)
+			bad_ptr(ptrs[i],
+			    "ptrs[%d] is revoked before being freed", i);
+#endif
+	/* Free even pointers */
+	for (i = 0; i < nitems(sizes); i += 2)
+		dlfree(ptrs[i]);
+#ifdef CAPREVOKE
+	dlmalloc_revoke();
+	/*
+	 * Check that even pointers were revoked and odd ones were not,
+	 * freeing odd ones.
+	 */
+	for (i = 0; i < nitems(sizes); i += 2)
+		if (cheri_getperm(ptrs[i]) != 0)
+			bad_ptr(ptrs[i], "ptrs[%d] was not revoked", i);
+	for (i = 1; i < nitems(sizes); i += 2)
+		if (cheri_getperm(ptrs[i]) == 0)
+			bad_ptr(ptrs[i],
+			    "ptrs[%d] is revoked before being freed", i);
+	dlmalloc_revoke();
+#endif
+	/* Free odd pointers */
+	for (i = 1; i < nitems(sizes); i += 2)
+		dlfree(ptrs[i]);
+
+	/* ----- realloc tests ----- */
+	ptrs[0] = realloc_checked(NULL, sizes[0]);
+	for (i = 1; i < nitems(sizes); i++)
+		ptrs[i] = realloc_checked(ptrs[i - 1], sizes[i]);
+	dlfree(ptrs[nitems(sizes) - 1]);
+#ifdef CAPREVOKE
+	dlmalloc_revoke();
+	for (i = 0; i < nitems(sizes); i++)
+		if (cheri_getperm(ptrs[i]) != 0)
+			bad_ptr(ptrs[i], "ptrs[%d] was not revoked", i);
+#endif
+
+	return (0);
+}
diff --git a/contrib/subrepo-cheri-libunwind/src/DwarfParser.hpp b/contrib/subrepo-cheri-libunwind/src/DwarfParser.hpp
index af0ab293f02c..af42c368cf6d 100644
--- a/contrib/subrepo-cheri-libunwind/src/DwarfParser.hpp
+++ b/contrib/subrepo-cheri-libunwind/src/DwarfParser.hpp
@@ -153,7 +153,6 @@ const char *CFI_Parser<A>::decodeFDE(A &addressSpace, pc_t pc, pint_t fdeStart,
       addressSpace.getEncodedP(p, nextCFI, cieInfo->pointerEncoding);
 #ifdef __CHERI_PURE_CAPABILITY__
   // This should not be a valid pointer:
-  assert(!__builtin_cheri_tag_get((void*)_pcStart));
   addr_t pcStart = __builtin_cheri_address_get((void*)_pcStart);
 #else
   addr_t pcStart = (addr_t)_pcStart;
@@ -161,7 +160,6 @@ const char *CFI_Parser<A>::decodeFDE(A &addressSpace, pc_t pc, pint_t fdeStart,
   pint_t _pcRange = addressSpace.getEncodedP(
       p, nextCFI, cieInfo->pointerEncoding & 0x0F);
 #ifdef __CHERI_PURE_CAPABILITY__
-  assert(!__builtin_cheri_tag_get((void*)_pcRange));
   addr_t pcRange = __builtin_cheri_address_get((void*)_pcRange);
 #else
   addr_t pcRange = (addr_t)_pcRange;
diff --git a/lib/Makefile b/lib/Makefile
index 42bd4b7a17b5..9fcb3e2ac599 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -151,6 +151,7 @@ SUBDIR.${MK_BSNMP}+=	libbsnmp
 
 SUBDIR.${MK_LIBCHERI}+=	libhelloworld
 SUBDIR.${MK_CHERI}+=	libsyscalls
+SUBDIR.${MK_CHERI}+=	libcheri_caprevoke
 
 .if ${MK_LIBCHERI} == "yes" && ${MACHINE_ARCH} != "mips"
 _libc_cheri=	libc_cheri
@@ -271,4 +272,5 @@ SUBDIR.${MK_LIBCHERI}+=	libcheri_syscalls
 SUBDIR.${MK_LIBCHERI}+=	libcheri_support
 .endif
 
+
 .include <bsd.subdir.mk>
diff --git a/lib/libc/Makefile b/lib/libc/Makefile
index e6269884e055..22f569aa8e47 100644
--- a/lib/libc/Makefile
+++ b/lib/libc/Makefile
@@ -108,7 +108,11 @@ NOASM=
 .include "${LIBC_SRCTOP}/resolv/Makefile.inc"
 .include "${LIBC_SRCTOP}/stdio/Makefile.inc"
 .include "${LIBC_SRCTOP}/stdlib/Makefile.inc"
+.if ${MK_DLMALLOC} == "no" || !defined(LIBCHERI)
 .include "${LIBC_SRCTOP}/stdlib/jemalloc/Makefile.inc"
+.else
+.include "${LIBC_SRCTOP}/stdlib/dlmalloc/Makefile.inc"
+.endif
 .include "${LIBC_SRCTOP}/stdtime/Makefile.inc"
 .include "${LIBC_SRCTOP}/string/Makefile.inc"
 .if !defined(NO_SYSCALLS)
diff --git a/lib/libc/gen/Makefile.inc b/lib/libc/gen/Makefile.inc
index db45832e010d..d609c043412c 100644
--- a/lib/libc/gen/Makefile.inc
+++ b/lib/libc/gen/Makefile.inc
@@ -176,6 +176,12 @@ SRCS+=	devname-compat11.c \
 	unvis-compat.c
 .endif
 
+.if ${MACHINE_ARCH:Mmips*c*} && ${MK_CHERI_CAPREVOKE}
+CFLAGS.tls_malloc.c+=	-DCAPREVOKE
+.PATH:	${SRCTOP}/lib/libcheri_caprevoke
+SRCS+=	libcheri_caprevoke.c
+.endif
+
 CFLAGS.arc4random.c= -I${SRCTOP}/sys -I${SRCTOP}/sys/crypto/chacha20
 
 .PATH: ${SRCTOP}/contrib/libc-pwcache
diff --git a/lib/libc/gen/tls_malloc.c b/lib/libc/gen/tls_malloc.c
index 200c7bb3e996..5a9945bed0a4 100644
--- a/lib/libc/gen/tls_malloc.c
+++ b/lib/libc/gen/tls_malloc.c
@@ -60,6 +60,11 @@
 
 #ifdef __CHERI_PURE_CAPABILITY__
 #include <cheri/cheric.h>
+#ifdef CAPREVOKE
+#include <sys/caprevoke.h>
+#include <sys/stdatomic.h>
+#include <cheri/caprevoke.h>
+#endif
 #endif
 
 #include <assert.h>
@@ -92,7 +97,9 @@ static void *__tls_malloc_aligned(size_t size, size_t align);
  * byte is set to MAGIC, and the second byte is the size index.
  */
 union	overhead {
+	struct {
 	union	overhead *ov_next;	/* when free */
+	};
 	struct {
 		u_char	ovu_magic;	/* magic number */
 		u_char	ovu_index;	/* bucket # */
@@ -101,6 +108,19 @@ union	overhead {
 #define	ov_index	ovu.ovu_index
 };
 
+struct pagepool_header {
+	size_t			 ph_size;
+#ifdef __CHERI_PURE_CAPABILITY__
+	size_t			 ph_pad1;
+	/* XXXBD: more padding on 256-bit... */
+#endif
+	struct pagepool_header	*ph_next;
+#ifdef CAPREVOKE
+	void			*ph_shadow;
+	void			*ph_pad2; /* Align strongly */
+#endif
+};
+
 #define	MALLOC_ALIGNMENT	sizeof(union overhead)
 
 #define	MAGIC		0xef		/* magic # on accounting info */
@@ -110,44 +130,44 @@ union	overhead {
  * (FIRST_BUCKET_SIZE << i).  The overhead information precedes the
  * data area returned to the user.
  */
-#define	FIRST_BUCKET_SIZE	32
+#define	FIRST_BUCKET_SHIFT	5
+#define	FIRST_BUCKET_SIZE	(1 << FIRST_BUCKET_SHIFT)
 #define	NBUCKETS 30
 static	union overhead *nextf[NBUCKETS];
 
+#ifdef CAPREVOKE
+/*
+ * In the CAPREVOKE case, we encode the bucket in the next pointer's low
+ * bit in the quarantine pool.  The static assert ensures that remains
+ * possible.
+ */
+_Static_assert(NBUCKETS < FIRST_BUCKET_SIZE,
+    "Not enough alignment to encode bucket in pointer bits");
+#define	MAX_QUARANTINE	(1024 * 1024)
+static union overhead *quarantine_bufs[NBUCKETS];
+static size_t quarantine_size;
+#endif
+
 static const size_t pagesz = PAGE_SIZE;			/* page size */
 
 #define	NPOOLPAGES	(32*1024/pagesz)
 
 static caddr_t	pagepool_start, pagepool_end;
-static size_t	n_pagepools, max_pagepools;
-static char	**pagepool_list;
+static struct pagepool_header	*curpp;
 
-static void
-__morepools(void)
-{
-	size_t osize, nsize;
-	char **new_pagepool_list;
-
-	osize = max_pagepools * sizeof(char *);
-	if (max_pagepools == 0)
-		max_pagepools = pagesz / (sizeof(char *) * 2);
-	max_pagepools *= 2;
-	nsize = max_pagepools * sizeof(char *);
-	if ((new_pagepool_list = mmap(0, nsize, PROT_READ|PROT_WRITE,
-	    MAP_ANON, -1, 0)) == MAP_FAILED)
-		abort();
-	memcpy(new_pagepool_list, pagepool_list, osize);
-	if (pagepool_list != NULL) {
-		if (munmap(pagepool_list, osize) != 0)
-			abort();
-	}
-	pagepool_list = new_pagepool_list;
-}
+#ifdef CAPREVOKE
+volatile const struct caprevoke_info *cri;
+
+static void paint_shadow(void *mem, size_t size);
+static void clear_shadow(void *mem, size_t size);
+static void do_revoke();
+#endif
 
 static int
 __morepages(int n)
 {
 	size_t	size;
+	struct pagepool_header *newpp;
 
 	n += NPOOLPAGES;	/* round up allocation. */
 	size = n * pagesz;
@@ -155,9 +175,6 @@ __morepages(int n)
 	size = CHERI_REPRESENTABLE_LENGTH(size);
 #endif
 
-	if (n_pagepools >= max_pagepools)
-		__morepools();
-
 	if (pagepool_end - pagepool_start > (ssize_t)pagesz) {
 		caddr_t extra_start = __builtin_align_up(pagepool_start,
 		    pagesz);
@@ -181,12 +198,15 @@ __morepages(int n)
 #endif
 	}
 
-	if ((pagepool_start = mmap(0, size, PROT_READ|PROT_WRITE,
-	    MAP_ANON, -1, 0)) == MAP_FAILED)
+	if ((newpp = mmap(0, size, PROT_READ|PROT_WRITE, MAP_ANON, -1,
+	    0)) == MAP_FAILED)
 		return (0);
 
-	pagepool_end = pagepool_start + size;
-	pagepool_list[n_pagepools++] = pagepool_start;
+	newpp->ph_next = curpp;
+	newpp->ph_size = size;
+	curpp = newpp;
+	pagepool_start = (char *)(newpp + 1);
+	pagepool_end = pagepool_start + (size - sizeof(*newpp));
 
 	return (size / pagesz);
 }
@@ -197,17 +217,23 @@ __rederive_pointer(void *ptr)
 #ifndef __CHERI_PURE_CAPABILITY__
 	return (ptr);
 #else
-	size_t i;
+	struct pagepool_header *pp;
 	vm_offset_t addr;
 
 	addr = cheri_getaddress(ptr);
 	TLS_MALLOC_LOCK;
-	for (i = 0; i < n_pagepools; i++) {
-		char *pool = pagepool_list[i];
+	/*
+	 * It's OK if more pools are added, they can't contain our pointer
+	 * and we never mutate the list except when adding to the front.
+	 */
+	pp = curpp;
+	TLS_MALLOC_UNLOCK;
+	while (pp != NULL) {
+		char *pool = (char *)pp;
 		if (cheri_is_address_inbounds(pool, addr))
 			return (cheri_setaddress(pool, addr));
+		pp = pp->ph_next;
 	}
-	TLS_MALLOC_UNLOCK;
 
 	return (NULL);
 #endif
@@ -224,6 +250,49 @@ bound_ptr(void *mem, size_t nbytes)
 	return (ptr);
 }
 
+#ifdef CAPREVOKE
+static void
+try_revoke(int target_bucket)
+{
+	int bucket;
+	union overhead *op, *next_op;
+
+	/*
+	 * Don't revoke unless there is enough in quarantine and some of
+	 * it would be returned to the bucket we want to refill.
+	 */
+	 if (quarantine_bufs[target_bucket] == NULL ||
+	     quarantine_size < MAX_QUARANTINE)
+	     return;
+
+	for (bucket = 0; bucket < NBUCKETS; bucket++) {
+		for (op = quarantine_bufs[bucket]; op != NULL;
+		    op = op->ov_next)
+			paint_shadow(op, FIRST_BUCKET_SIZE << bucket);
+	}
+	atomic_thread_fence(memory_order_acq_rel);
+
+	do_revoke();
+
+	 for (bucket = 0; bucket < NBUCKETS; bucket++) {
+		for (op = quarantine_bufs[bucket]; op != NULL;
+		    op = op->ov_next)
+			clear_shadow(op, FIRST_BUCKET_SIZE << bucket);
+	}
+	atomic_thread_fence(memory_order_acq_rel);
+
+	for (bucket = 0; bucket < NBUCKETS; bucket++) {
+		op = quarantine_bufs[bucket];
+		while (op != NULL) {
+			next_op = op->ov_next;
+			op->ov_next = nextf[bucket];
+			nextf[bucket] = op;
+		}
+	}
+	quarantine_size = 0;
+}
+#endif
+
 static void *
 __tls_malloc(size_t nbytes)
 {
@@ -251,6 +320,10 @@ __tls_malloc(size_t nbytes)
 	 * request more memory from the system.
 	 */
 	TLS_MALLOC_LOCK;
+#ifdef CAPREVOKE
+	if ((op = nextf[bucket]) == NULL)
+		try_revoke(bucket);
+#endif
 	if ((op = nextf[bucket]) == NULL) {
 		morecore(bucket);
 		if ((op = nextf[bucket]) == NULL)
@@ -398,6 +471,53 @@ nextf_insert(void *mem, size_t size, int xbucket)
 	nextf[bucket] = op;
 }
 
+#ifdef CAPREVOKE
+static void
+paint_shadow(void *mem, size_t size)
+{
+	struct pagepool_header *pp;
+
+	pp = cheri_setoffset(pp, 0);
+	/*
+	 * Defer initializing ph_shadow since odds are good we'll never
+	 * need it.
+	 */
+	if (pp->ph_shadow == NULL)
+		if (caprevoke_shadow(CAPREVOKE_SHADOW_NOVMMAP, pp,
+		    &pp->ph_shadow) != 0)
+			abort();
+	caprev_shadow_nomap_set_raw(pp->ph_shadow, (vaddr_t)mem, size);
+}
+
+static void
+clear_shadow(void *mem, size_t size)
+{
+	struct pagepool_header *pp;
+
+	pp = cheri_setoffset(pp, 0);
+	caprev_shadow_nomap_clear_raw(pp->ph_shadow, (vaddr_t)mem, size);
+}
+
+static void
+do_revoke(void)
+{
+	int error;
+
+	if (cri == NULL) {
+		error = caprevoke_shadow(CAPREVOKE_SHADOW_INFO_STRUCT, NULL,
+		    (void **)&cri);
+		assert(error == 0);
+	}
+
+	caprevoke_epoch start_epoch = cri->epoch_enqueue;
+	while (!caprevoke_epoch_clears(cri->epoch_dequeue, start_epoch)) {
+		struct caprevoke_stats crst;
+		error = caprevoke(CAPREVOKE_LAST_PASS, start_epoch, &crst);
+		assert(error == 0);
+	}
+}
+#endif /* CAPREVOKE */
+
 void
 tls_free(void *cp)
 {
@@ -413,7 +533,13 @@ tls_free(void *cp)
 	bucket = op->ov_index;
 	if (bucket < NBUCKETS)
 		abort();
+#ifdef CAPREVOKE
+	op->ov_next = quarantine_bufs[bucket];
+	quarantine_bufs[bucket] = op;
+	quarantine_size += FIRST_BUCKET_SIZE << bucket;
+#else
 	nextf_insert(op, FIRST_BUCKET_SIZE << bucket, bucket);
+#endif
 	TLS_MALLOC_UNLOCK;
 }
 
diff --git a/lib/libc/stdlib/dlmalloc/Makefile.inc b/lib/libc/stdlib/dlmalloc/Makefile.inc
new file mode 100644
index 000000000000..43e7567f2aac
--- /dev/null
+++ b/lib/libc/stdlib/dlmalloc/Makefile.inc
@@ -0,0 +1,23 @@
+# $FreeBSD$
+
+.PATH: ${LIBC_SRCTOP}/stdlib/dlmalloc
+.PATH: ${SRCTOP}/contrib/dlmalloc
+
+DLMALLOCSRCS:= dlmalloc_nonreuse.c dlmalloc_libc_stubs.c
+
+SYM_MAPS+=${LIBC_SRCTOP}/stdlib/dlmalloc/Symbol.map
+
+CFLAGS+=-I${SRCTOP}/contrib/dlmalloc
+
+.if ${MK_CHERI_CAPREVOKE} == "yes"
+.PATH: ${SRCTOP}/lib/libcheri_caprevoke
+DLMALLOCSRCS+=		libcheri_caprevoke.c
+DLMALLOC_CFLAGS+=	-DCHERI_SET_BOUNDS -DSAFE_FREEBUF
+DLMALLOC_CFLAGS+=	-DCAPREVOKE -DDEFAULT_MAX_FREEBUFBYTES=8388608
+DLMALLOC_CFLAGS+=	-DDCONSOLIDATE_ON_FREE=1
+DLMALLOC_CFLAGS+=	-DZERO_MEMORY=0
+DLMALLOC_CFLAGS+=	-DSUPPORT_UNMAP=1
+.endif
+CFLAGS.dlmalloc_nonreuse.c+=	${DLMALLOC_CFLAGS}
+
+SRCS+=	${DLMALLOCSRCS}
diff --git a/lib/libc/stdlib/dlmalloc/Symbol.map b/lib/libc/stdlib/dlmalloc/Symbol.map
new file mode 100644
index 000000000000..614dd6605890
--- /dev/null
+++ b/lib/libc/stdlib/dlmalloc/Symbol.map
@@ -0,0 +1,20 @@
+/*
+ * $FreeBSD$
+ */
+
+FBSD_1.0 {
+	aligned_alloc;
+	malloc;
+	posix_memalign;
+	calloc;
+	realloc;
+	free;
+	malloc_usable_size;
+};
+
+FBSDprivate_1.0 {
+	_malloc_thread_cleanup;
+	_malloc_prefork;
+	_malloc_postfork;
+	_malloc_first_thread;
+};
diff --git a/lib/libc/stdlib/dlmalloc/dlmalloc_libc_stubs.c b/lib/libc/stdlib/dlmalloc/dlmalloc_libc_stubs.c
new file mode 100644
index 000000000000..a1489995ff93
--- /dev/null
+++ b/lib/libc/stdlib/dlmalloc/dlmalloc_libc_stubs.c
@@ -0,0 +1,51 @@
+/*-
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2019 SRI interntional
+ *
+ * This software was developed by SRI International and the University of
+ * Cambridge Computer Laboratory (Department of Computer Science and
+ * Technology) under DARPA contract HR0011-18-C-0016 ("ECATS"), as part of the
+ * DARPA SSITH research programme.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+void
+_malloc_thread_cleanup(void)
+{
+}
+
+void
+_malloc_prefork(void)
+{
+}
+
+void
+_malloc_postfork(void)
+{
+}
+
+void
+_malloc_first_thread(void)
+{
+}
diff --git a/lib/libc/sys/Symbol.map b/lib/libc/sys/Symbol.map
index a807b45ab77f..d65fabc56779 100644
--- a/lib/libc/sys/Symbol.map
+++ b/lib/libc/sys/Symbol.map
@@ -380,6 +380,9 @@ FBSD_1.4 {
 };
 
 FBSD_1.5 {
+	caprevoke;
+	caprevoke_shadow;
+	caprevoke_entire_shadow_cap;
 	clock_nanosleep;
 	fdatasync;
 	fhstat;
diff --git a/lib/libc/tests/stdlib/Makefile b/lib/libc/tests/stdlib/Makefile
index e0386890c9da..01a2fef59bdf 100644
--- a/lib/libc/tests/stdlib/Makefile
+++ b/lib/libc/tests/stdlib/Makefile
@@ -36,7 +36,9 @@ NETBSD_ATF_TESTS_C+=	div_test
 NETBSD_ATF_TESTS_C+=	getenv_test
 NETBSD_ATF_TESTS_C+=	exit_test
 NETBSD_ATF_TESTS_C+=	hsearch_test
+.if ${MK_DLMALLOC} == no || !defined(LIBCHERI)
 NETBSD_ATF_TESTS_C+=	posix_memalign_test
+.endif
 NETBSD_ATF_TESTS_C+=	random_test
 NETBSD_ATF_TESTS_C+=	strtod_test
 NETBSD_ATF_TESTS_C+=	strtol_test
diff --git a/lib/libcheri_caprevoke/Makefile b/lib/libcheri_caprevoke/Makefile
new file mode 100644
index 000000000000..a303993343f0
--- /dev/null
+++ b/lib/libcheri_caprevoke/Makefile
@@ -0,0 +1,17 @@
+SRCS= libcheri_caprevoke.c
+
+INCS= caprevoke.h
+INCSDIR=	${INCLUDEDIR}/cheri
+
+CFLAGS+= -I${.CURDIR}
+CFLAGS+= -I${.CURDIR}/${MACHINE_ARCH}
+
+LIB=cheri_caprevoke
+SHLIB= cheri_caprevoke
+SHLIB_MAJOR= 1
+
+NO_WERROR=
+WANT_CHERI=yes
+
+.include "../Makefile.inc"
+.include <bsd.lib.mk>
diff --git a/lib/libcheri_caprevoke/caprevoke.h b/lib/libcheri_caprevoke/caprevoke.h
new file mode 100644
index 000000000000..6404a270b597
--- /dev/null
+++ b/lib/libcheri_caprevoke/caprevoke.h
@@ -0,0 +1,47 @@
+#ifndef LIBCHERI_CAPREVOKE_H
+#define LIBCHERI_CAPREVOKE_H
+
+#include <stddef.h>
+#include <sys/caprevoke.h>
+
+/*
+ * The per-object interface protects against concurrent mutation and both
+ * intra- and inter-epoch double-frees.
+ */
+int caprev_shadow_nomap_set_len(uint64_t * __capability sb,
+                                vaddr_t ob,
+                                size_t len,
+                                void * __capability user_obj);
+
+void caprev_shadow_nomap_clear_len(uint64_t * __capability sb,
+                                   vaddr_t ob,
+                                   size_t len);
+
+int caprev_shadow_nomap_set(uint64_t * __capability sb,
+                            void * __capability priv_obj,
+                            void * __capability user_obj);
+
+void caprev_shadow_nomap_clear(uint64_t * __capability sb,
+                               void * __capability obj);
+
+/*
+ * For already interlocked allocators where these protections are not
+ * necessary, we also export a "raw" interface, which is especially useful
+ * when objects can coalesce in quarantine prior to being staged for
+ * revocation, as fewer bitmap writes are necessary.
+ */
+
+void caprev_shadow_nomap_set_raw(uint64_t * __capability sb,
+                                 vaddr_t heap_start, vaddr_t heap_end);
+
+void caprev_shadow_nomap_clear_raw(uint64_t * __capability sb,
+                                   vaddr_t heap_start, vaddr_t heap_end);
+
+/* Utility functions for testing */
+void caprev_shadow_nomap_offsets(vaddr_t ob, size_t len,
+                                 ptrdiff_t *fwo, ptrdiff_t *lwo);
+
+void caprev_shadow_nomap_masks(vaddr_t ob, size_t len,
+                               uint64_t *fwm, uint64_t *lwm);
+
+#endif
diff --git a/lib/libcheri_caprevoke/libcheri_caprevoke.c b/lib/libcheri_caprevoke/libcheri_caprevoke.c
new file mode 100644
index 000000000000..775e31be07a0
--- /dev/null
+++ b/lib/libcheri_caprevoke/libcheri_caprevoke.c
@@ -0,0 +1,486 @@
+/*
+ * Revocation bitmap manipulation operations.
+ */
+
+// XXX This can't possibly be right.  Should vmparam.h be checking for
+// something else?
+#ifndef CPU_CHERI
+#define CPU_CHERI
+#endif
+
+#include <assert.h>
+#include <inttypes.h>
+#include <stdbool.h>
+#include <stdatomic.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#include <cheri/cheric.h>
+
+#include <sys/param.h>
+#include <sys/caprevoke.h>
+#include <machine/cherireg.h>
+#include <machine/pte.h>
+#include <machine/vmparam.h>
+#include "caprevoke.h"
+
+static ptrdiff_t caprev_shadow_nomap_first_word_offset(vaddr_t base);
+static ptrdiff_t caprev_shadow_nomap_last_word_offset(vaddr_t base, size_t len);
+static uint64_t  caprev_shadow_nomap_first_word_mask(vaddr_t base, size_t len);
+static uint64_t  caprev_shadow_nomap_last_word_mask(vaddr_t base, size_t len);
+
+  /*
+   * Given a capability to an object, derive the offset relative to the base of
+   * the fine-grained bitmap where the first word would be located.
+   */
+
+static ptrdiff_t
+caprev_shadow_nomap_first_word_offset(vaddr_t base)
+{
+  return (ptrdiff_t)(base / VM_CAPREVOKE_GSZ_MEM_NOMAP
+                          / 8
+                          / sizeof(uint64_t)) * sizeof(uint64_t);
+}
+
+static ptrdiff_t
+caprev_shadow_nomap_last_word_offset(vaddr_t base, size_t len)
+{
+  if (len == 0)
+    return caprev_shadow_nomap_first_word_offset(base);
+
+  return (ptrdiff_t)((base + len - 1)
+                          / VM_CAPREVOKE_GSZ_MEM_NOMAP
+                          / 8
+                          / sizeof(uint64_t)) * sizeof(uint64_t);
+}
+
+  /*
+   * Derive the mask to be or'd in to the first word to mark the object's
+   * bottom granules as revoked.
+   */
+
+static uint64_t
+caprev_shadow_nomap_first_word_mask(vaddr_t base, size_t len)
+{
+  uint64_t res;
+
+  /* What's the least significant bit's position within the word? */
+  int lsb = (base / VM_CAPREVOKE_GSZ_MEM_NOMAP) % (8 * sizeof(uint64_t));
+
+  if (caprev_shadow_nomap_first_word_offset(base) ==
+      caprev_shadow_nomap_last_word_offset(base, len)) {
+    /* The object occupies only some bits in the first word */
+
+    int setwidth = len / VM_CAPREVOKE_GSZ_MEM_NOMAP;
+
+    if (lsb + setwidth == 64) {
+      /* Object fills this word completely, but does not spill to the next */
+
+      res = ~(((uint64_t)1 << lsb) - 1);
+    } else {
+      res = (   ~(((uint64_t)1 << (lsb + setwidth)) - 1)
+             ^ (~(((uint64_t)1 << lsb             ) - 1)));
+    }
+  } else {
+    /* The object runs off the end of this word. */
+
+    res = ~(((uint64_t)1 << lsb) - 1);
+  }
+
+#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
+  return __builtin_bswap64(res);
+#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+  return res;
+#else
+# error
+#endif
+}
+
+static uint64_t
+caprev_shadow_nomap_last_word_mask(vaddr_t base, size_t len)
+{
+  uint64_t res;
+
+  if (caprev_shadow_nomap_first_word_offset(base) ==
+      caprev_shadow_nomap_last_word_offset(base, len)) {
+
+    /*
+     * There are no more bits to set that haven't been taken care of by the the
+     * first word, so just return 0.
+     */
+
+    return 0;
+  }
+
+  int msb = ((base + len - 1) / VM_CAPREVOKE_GSZ_MEM_NOMAP) % (8 * sizeof(uint64_t));
+
+  if (msb == 63) {
+    /* This object runs to the end of its last word */
+
+    return ~(uint64_t)0;
+  }
+
+  res = ((uint64_t)1 << (msb+1)) - 1;
+
+#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
+  return __builtin_bswap64(res);
+#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+  return res;
+#else
+# error
+#endif
+}
+
+  /*
+   * Exposed for testing, but hopefully inlined into the actual update
+   * functions below.
+   *
+   * XXX Slightly less polluting of the external namespace than having all four
+   * functions available, maybe?
+   */
+
+void
+caprev_shadow_nomap_offsets(vaddr_t ob, size_t len, ptrdiff_t *fwo, ptrdiff_t *lwo)
+{
+  *fwo = caprev_shadow_nomap_first_word_offset(ob);
+  *lwo = caprev_shadow_nomap_last_word_offset(ob, len);
+}
+
+void
+caprev_shadow_nomap_masks(vaddr_t ob, size_t len, uint64_t *fwm, uint64_t *lwm)
+{
+  *fwm = caprev_shadow_nomap_first_word_mask(ob, len);
+  *lwm = caprev_shadow_nomap_last_word_mask(ob, len);
+}
+
+  /*
+   * A helper function for some things both setting and clearing shadow masks
+   * need up front.
+   */
+
+static inline void
+caprev_shadow_nomap_common_pfx(uint64_t * __capability sb,
+             vaddr_t ob, size_t len, ptrdiff_t *fwo, ptrdiff_t *lwo,
+             uint64_t * __capability *fw
+            )
+{
+  caprev_shadow_nomap_offsets(ob, len, fwo, lwo);
+
+  *fw = cheri_setaddress(sb, VM_CAPREVOKE_BM_MEM_NOMAP + *fwo);
+}
+
+  /*
+   * Mark an object for revocation using the indicated capability to the
+   * correct fragment of the shadow bitmap.
+   *
+   * The region of memory whose corresponding shadow space will be set is given
+   * by a base vaddr ob and a length len. The "user" object capability is
+   * expected to govern a subset of this region and, importantly, must be
+   * subject to revocation; it is used to guard against double-frees. The two
+   * are provided separately because the bounds of the "user" capability may
+   * have been shrunk so that they do not cover the entire underlying allocation.
+   *
+   * The masks here are additive: they're going to be OR'd with the shadow.
+   *
+   * Returns 0 on success or 1 if the calling free() should skip this
+   * capability, as it has either become de-tagged or is at least partially
+   * already marked in the bitmap (as might happen, for example, with a
+   * racing second call to free on the same pointer).
+   */
+
+int
+caprev_shadow_nomap_set_len(uint64_t * __capability sb,
+                            vaddr_t ob,
+                            size_t len,
+                            void * __capability user_obj)
+{
+  ptrdiff_t fwo, lwo;
+  uint64_t * __capability fw;
+
+  caprev_shadow_nomap_common_pfx(sb, ob, len, &fwo, &lwo, &fw);
+
+  uint64_t fwm = caprev_shadow_nomap_first_word_mask(ob, len);
+
+  uint64_t asmres = 0;
+
+  /*
+   * The first word is tricky to handle, since we use it to gate frees,
+   * ensuring that double-frees are idempotent.  There are three reasons we
+   * might bail out:
+   *
+   *   - another thread has quarantined this object (bits already set)
+   *
+   *   - this object is detagged
+   *
+   *   - this object has been revoked while we held a pointer to it in
+   *   free() (and so its permissions have been stripped; see cheri_revoke)
+   *
+   * We have to check the permissions inside the ll/sc we use to update the
+   * shadow bitmask so that we interlock against the stop-the-world (and
+   * maybe read-side) phases of revocation.
+   *
+   * It's possible the SC fails for neither of the above reasons, of course,
+   * not the least of which is that a concurrent thread might be mutating
+   * the shadow.  In that case, just go around again.
+   *
+   * We're going to do this dance with some inline assembler (sigh), because
+   * it's a little much to expect C to understand!
+   */
+#ifdef __mips__
+
+  // t0: the local, manipulated copy of the shadow
+  // t1: temp value
+
+  // XXX Why is someone inserting nops in my carefully-written assembler? :(
+
+  __asm__ __volatile__ (
+      "1:\n\t"
+      "clld $t0, %[fw]\n\t"             // Load linked the first word
+
+      "and $t1, $t0, %[fwm]\n\t"        // Jump out if shadow set
+      "bnez $t1, 2f\n\t"
+      "nop\n\t"                         // [delay]
+
+      "cbtu %[obj], 2f\n\t"             // Jump out if object detagged
+	// no delay slot OK
+
+      "cgetperm $t1, %[obj]\n\t"        // Jump out if zero perms
+      "beqz $t1, 2f\n\t"
+      "nop\n\t"                         // [delay]
+
+      "or $t0, $t0, %[fwm]\n\t"         // bitwise or in the mask [delay]
+
+      "cscd %[asmres], $t0, %[fw]\n\t"  // SC the updated mask
+      "bnez %[asmres], 2f\n\t"          // Jump out on success
+      "nop\n\t"                         // [delay]
+
+      "j 1b\n\t"                        // Go again if SC failed
+      "nop\n\t"
+
+      "2:\n\t"
+    : // output operands
+      [asmres] "+r" (asmres)
+    : // input operands
+      [obj]    "C"  (user_obj),
+      [fw]     "C"  (fw),
+      [fwm]    "r"  (fwm)
+     : // clobbers
+       "t0", "t1", "memory"
+  );
+#else
+#  error Unable to mark bitmaps on this architecture
+#endif
+
+  /*
+   * In the "Jump out" cases above, %[asmres] will hold the value 0, either
+   * from initialization or because a cscd instruction was unsuccessful on a
+   * prior iteration.  Only if we don't jump out and successfully exit the loop
+   * will asmres be 1.
+   */
+  if (asmres == 0) {
+    return 1;
+  }
+
+  if (lwo != fwo) {
+
+    /*
+     * If this object straddles a word boundary, the first and last word offets
+     * will not be equal; the last word might also need special handling.
+     */
+
+    uint64_t * __capability lw = cheri_setaddress(sb,
+                                    VM_CAPREVOKE_BM_MEM_NOMAP + lwo);
+    uint64_t lwm = caprev_shadow_nomap_last_word_mask(ob, len);
+
+    /*
+     * We might overlap a concurrent object's attempt to mutate bits in the
+     * last word, so do the OR atomically unless we're setting the whole word,
+     * in which case, the write cannot possibly race.
+     */
+
+    if (lwm != ~(uint64_t)0) {
+      atomic_fetch_or_explicit((_Atomic(uint64_t) * __capability)lw, lwm,
+                               memory_order_relaxed);
+    } else {
+      *lw = ~(uint64_t)0;
+    }
+
+    /*
+     * Any words between the first and last we can just set all at once;
+     * there's nothing else to see here.
+     */
+
+    ptrdiff_t wo = fwo + sizeof(uint64_t);
+    uint64_t * __capability sbo = fw + 1;
+    for (; wo < lwo; wo += sizeof(uint64_t), sbo++) {
+      *sbo = ~(uint64_t)0;
+    }
+  }
+
+  /*
+   * There is no need to store-barrier or any such here; we can enforce store
+   * order before grabbing the epoch clock for this *chunk* of the quarantine.
+   * By ensuring that we make all cores aware of our bits before looking at the
+   * clock, we guarantee that the revocation epoch(s) upon which we are waiting
+   * will be done with at least our stores visible.
+   */
+
+  return 0;
+}
+
+  /*
+   * Mark an object for revocation using the indicated capability to the
+   * correct fragment of the shadow bitmap.
+   *
+   * The "privileged" object capability is expected to point to the full,
+   * actual bounds of the allocation and may (or may not) be subject to
+   * revocation; this capability determines which bits of the bitmap are in
+   * scope for changes.  The "user" object capability is expected to be a
+   * subset of the privileged object capability and, importantly, must be
+   * subject to revocation; this capability is used to guard against
+   * double-frees.  The two are provided separately to remove from the
+   * allocator the need to construct the priveleged capability while
+   * respecting (concurrently mutable!) taggedness of the user capability.
+   *
+   * The masks here are additive: they're going to be OR'd with the shadow.
+   *
+   * Returns 0 on success or 1 if the calling free() should skip this
+   * capability, as it has either become de-tagged or is at least partially
+   * already marked in the bitmap (as might happen, for example, with a
+   * racing second call to free on the same pointer).
+   */
+
+int
+caprev_shadow_nomap_set(uint64_t * __capability sb,
+                        void * __capability priv_obj,
+                        void * __capability user_obj)
+{
+  return caprev_shadow_nomap_set_len(sb, (__cheri_addr vaddr_t)priv_obj, cheri_getlen(priv_obj), user_obj);
+}
+
+  /*
+   * Clear a region from the shadow bitmap.
+   *
+   * The masks here are subtractive: they're going to be AND'd with the shadow.
+   */
+
+void
+caprev_shadow_nomap_clear_len(uint64_t * __capability sb, vaddr_t ob, size_t len)
+{
+  ptrdiff_t fwo, lwo;
+  uint64_t * __capability fw;
+
+  caprev_shadow_nomap_common_pfx(sb, ob, len, &fwo, &lwo, &fw);
+
+  uint64_t fwm = ~caprev_shadow_nomap_first_word_mask(ob, len);
+
+  /*
+   * The first word must be handled atomically, so that it interlocks
+   * with the atomic manipulation in caprev_shadow_nomap_set.
+   */
+  atomic_fetch_and_explicit((_Atomic(uint64_t) * __capability)fw, fwm,
+                            memory_order_relaxed);
+
+  if (lwo != fwo) {
+
+    uint64_t * __capability lw = cheri_setaddress(sb,
+                                    VM_CAPREVOKE_BM_MEM_NOMAP + lwo);
+    uint64_t lwm = ~caprev_shadow_nomap_last_word_mask(ob, len);
+
+    /*
+     * The last word may also need to be handled atomically.
+     */
+
+    if (lwm != 0) {
+      atomic_fetch_and_explicit((_Atomic(uint64_t) * __capability)lw, lwm,
+                                memory_order_relaxed);
+    } else {
+      *lw = 0;
+    }
+
+    /*
+     * Any words between the first and last we can just clear all at once.
+     */
+
+    ptrdiff_t wo = fwo + sizeof(uint64_t);
+    uint64_t * __capability sbo = fw + 1;
+    for (; wo < lwo; wo += sizeof(uint64_t), sbo++) {
+      *sbo = (uint64_t)0;
+    }
+  }
+
+  /*
+   * There is no need to store-barrier or any such here either.  It suffices to
+   * store-barrier at the end of whatever set of objects is being cleared from
+   * the shadow, before those objects may be released to the application.
+   */
+}
+
+  /*
+   * Clear an object from the shadow bitmap.
+   *
+   * The masks here are subtractive: they're going to be AND'd with the shadow.
+   */
+
+void
+caprev_shadow_nomap_clear(uint64_t * __capability sb, void * __capability obj)
+{
+  return caprev_shadow_nomap_clear_len(sb, (__cheri_addr vaddr_t)obj, cheri_getlen(obj));
+}
+
+/*
+ * The "raw" interfaces presume that all interlocking has already been
+ * managed by the caller and so contain no atomics or such!
+ */
+
+void
+caprev_shadow_nomap_set_raw(uint64_t * __capability sb,
+                            vaddr_t heap_start, vaddr_t heap_end)
+{
+  ptrdiff_t fwo, lwo;
+  uint64_t * __capability fw;
+  size_t len = heap_end - heap_start;
+
+  caprev_shadow_nomap_offsets(heap_start, len, &fwo, &lwo);
+
+  fw = cheri_setaddress(sb, VM_CAPREVOKE_BM_MEM_NOMAP + fwo);
+  *fw |= caprev_shadow_nomap_first_word_mask(heap_start, len);
+
+  if (lwo != fwo) {
+    uint64_t * __capability w = fw + 1;
+    ptrdiff_t wo = fwo + sizeof(uint64_t);
+    w = fw + 1;
+    for (; wo < lwo; wo += sizeof(uint64_t), w++) {
+		*w = ~(uint64_t)0;
+	}
+
+    w = cheri_setaddress(sb, VM_CAPREVOKE_BM_MEM_NOMAP + lwo);
+    *w |= caprev_shadow_nomap_last_word_mask(heap_start, len);
+  }
+}
+
+void
+caprev_shadow_nomap_clear_raw(uint64_t * __capability sb,
+                              vaddr_t heap_start, vaddr_t heap_end)
+{
+  ptrdiff_t fwo, lwo;
+  uint64_t * __capability fw;
+  size_t len = heap_end - heap_start;
+
+  caprev_shadow_nomap_offsets(heap_start, len, &fwo, &lwo);
+
+  fw = cheri_setaddress(sb, VM_CAPREVOKE_BM_MEM_NOMAP + fwo);
+  *fw &= ~caprev_shadow_nomap_first_word_mask(heap_start, len);
+
+  if (lwo != fwo) {
+    uint64_t * __capability w = fw + 1;
+    ptrdiff_t wo = fwo + sizeof(uint64_t);
+    w = fw + 1;
+    for (; wo < lwo; wo += sizeof(uint64_t), w++) {
+		*w = 0;
+	}
+
+    w = cheri_setaddress(sb, VM_CAPREVOKE_BM_MEM_NOMAP + lwo);
+    *w &= ~caprev_shadow_nomap_last_word_mask(heap_start, len);
+  }
+}
diff --git a/lib/libmalloc_simple/Makefile b/lib/libmalloc_simple/Makefile
index 7a19330aeb7e..4651c6f6fb9c 100644
--- a/lib/libmalloc_simple/Makefile
+++ b/lib/libmalloc_simple/Makefile
@@ -1,8 +1,14 @@
 # $FreeBSD$
 
+.include <src.opts.mk>
+
 LIB=	malloc_simple
 SHLIB_MAJOR=	1
 
 SRCS=	heap.c malloc.c
 
+.if ${MACHINE_ARCH:Mmips*c*} && ${MK_CHERI_CAPREVOKE}
+CFLAGS+=	-DCAPREVOKE
+.endif
+
 .include <bsd.lib.mk>
diff --git a/lib/libmalloc_simple/heap.c b/lib/libmalloc_simple/heap.c
index 5910dd57351e..bc2c94505486 100644
--- a/lib/libmalloc_simple/heap.c
+++ b/lib/libmalloc_simple/heap.c
@@ -46,8 +46,17 @@ static char *rcsid = "$FreeBSD$";
 
 #include <sys/param.h>
 #include <sys/types.h>
+#ifdef CAPREVOKE
+#include <sys/caprevoke.h>
+#endif
 #include <sys/mman.h>
+#ifdef CAPREVOKE
+#include <sys/stdatomic.h>
+#endif
 
+#ifdef CAPREVOKE
+#include <cheri/caprevoke.h>
+#endif
 #include <cheri/cheri.h>
 #include <cheri/cheric.h>
 
@@ -68,19 +77,36 @@ static char *rcsid = "$FreeBSD$";
 #define	error_printf(...)	fprintf(stderr, __VA_ARGS__)
 #endif
 
+struct pagepool_header {
+	size_t			ph_size;
+#ifdef __CHERI_PURE_CAPABILITY__
+	size_t			ph_pad1;
+	/* XXXBD: more padding on 256-bit... */
+#endif
+	struct pagepool_header	*ph_next;
+#ifdef CAPREVOKE
+	void			*ph_shadow;
+#else
+	void			*ph_pad2;
+#endif
+};
+
 #define	NPOOLPAGES	(32*1024/_pagesz)
 
 caddr_t		pagepool_start, pagepool_end;
+static struct pagepool_header	*curpp;
 
-static size_t n_pagepools, max_pagepools;
-static char **pagepool_list;
 static size_t _pagesz;
 
+#ifdef CAPREVOKE
+static volatile const struct caprevoke_info *cri;
+#endif
+
 int
 __morepages(int n)
 {
 	size_t	size;
-	char **new_pagepool_list;
+	struct pagepool_header *newpp;
 
 	n += NPOOLPAGES;	/* round up allocation. */
 	size = n * _pagesz;
@@ -88,30 +114,6 @@ __morepages(int n)
 	size = CHERI_REPRESENTABLE_LENGTH(size);
 #endif
 
-	if (n_pagepools >= max_pagepools) {
-		if (max_pagepools == 0)
-			max_pagepools = _pagesz / (sizeof(char *) * 2);
-
-		max_pagepools *= 2;
-		if ((new_pagepool_list = mmap(0,
-		    max_pagepools * sizeof(char *), PROT_READ|PROT_WRITE,
-		    MAP_ANON, -1, 0)) == MAP_FAILED) {
-			error_printf("%s: Can not map pagepool_list\n", __func__);
-			return (0);
-		}
-		memcpy(new_pagepool_list, pagepool_list,
-		    sizeof(char *) * n_pagepools);
-		if (pagepool_list != NULL) {
-			if (munmap(pagepool_list,
-			    max_pagepools * sizeof(char *) / 2) != 0) {
-				error_printf("%s: failed to unmap pagepool_list\n",
-				    __func__);
-				/* XXX: leak the region */
-			}
-		}
-		pagepool_list = new_pagepool_list;
-	}
-
 	if (pagepool_end - pagepool_start > (ssize_t)_pagesz) {
 		caddr_t extra_start = __builtin_align_up(pagepool_start,
 		    _pagesz);
@@ -138,13 +140,16 @@ __morepages(int n)
 #endif
 	}
 
-	if ((pagepool_start = mmap(0, size, PROT_READ|PROT_WRITE,
-	    MAP_ANON, -1, 0)) == MAP_FAILED) {
+	if ((newpp = mmap(0, size, PROT_READ|PROT_WRITE, MAP_ANON, -1,
+	    0)) == MAP_FAILED) {
 		error_printf("%s: mmap of pagepool failed\n", __func__);
 		return (0);
 	}
-	pagepool_end = pagepool_start + size;
-	pagepool_list[n_pagepools++] = pagepool_start;
+	newpp->ph_next = curpp;
+	newpp->ph_size = size;
+	curpp = newpp;
+	pagepool_start = (char *)(newpp + 1);
+	pagepool_end = pagepool_start + (size - sizeof(*newpp));
 
 	return (size / _pagesz);
 }
@@ -159,16 +164,66 @@ __init_heap(size_t pagesz)
 void *
 __rederive_pointer(void *ptr)
 {
-	size_t i;
+	struct pagepool_header *pp;
 	vm_offset_t addr;
 
 	addr = cheri_getaddress(ptr);
-	for (i = 0; i < n_pagepools; i++) {
-		char *pool = pagepool_list[i];
-
+	pp = curpp;
+	while (pp != NULL) {
+		char *pool = (char *)pp;
 		if (cheri_is_address_inbounds(pool, addr))
 			return (cheri_setaddress(pool, addr));
+		pp = pp->ph_next;
 	}
 
 	return (NULL);
 }
+
+
+#ifdef CAPREVOKE
+void
+__paint_shadow(void *mem, size_t size)
+{
+	struct pagepool_header *pp;
+
+	pp = cheri_setoffset(pp, 0);
+	/*
+	 * Defer initializing ph_shadow since odds are good we'll never
+	 * need it.
+	 */
+	if (pp->ph_shadow == NULL)
+		if (caprevoke_shadow(CAPREVOKE_SHADOW_NOVMMAP, pp,
+		    &pp->ph_shadow) != 0)
+			abort();
+	caprev_shadow_nomap_set_raw(pp->ph_shadow, (vaddr_t)mem, size);
+}
+
+void
+__clear_shadow(void *mem, size_t size)
+{
+	struct pagepool_header *pp;
+
+	pp = cheri_setoffset(pp, 0);
+	caprev_shadow_nomap_clear_raw(pp->ph_shadow, (vaddr_t)mem, size);
+}
+
+void
+__do_revoke(void)
+{
+	int error;
+
+	if (cri == NULL) {
+		error = caprevoke_shadow(CAPREVOKE_SHADOW_INFO_STRUCT, NULL,
+		    __DECONST(void **, &cri));
+		assert(error == 0);
+	}
+
+	caprevoke_epoch start_epoch = cri->epoch_enqueue;
+	while (!caprevoke_epoch_clears(cri->epoch_dequeue, start_epoch)) {
+		struct caprevoke_stats crst;
+		error = caprevoke(CAPREVOKE_LAST_PASS, start_epoch, &crst);
+		assert(error == 0);
+	}
+}
+
+#endif /* CAPREVOKE */
diff --git a/lib/libmalloc_simple/malloc.c b/lib/libmalloc_simple/malloc.c
index a48a9f0cfe0e..d04f098e59e4 100644
--- a/lib/libmalloc_simple/malloc.c
+++ b/lib/libmalloc_simple/malloc.c
@@ -45,8 +45,15 @@ static char *rcsid = "$FreeBSD$";
  */
 
 #include <sys/param.h>
+#ifdef CAPREVOKE
+#include <sys/caprevoke.h>
+#include <sys/stdatomic.h>
+#endif
 #include <sys/types.h>
 
+#ifdef CAPREVOKE
+#include <cheri/caprevoke.h>
+#endif
 #include <cheri/cheri.h>
 #include <cheri/cheric.h>
 
@@ -98,10 +105,28 @@ union	overhead {
  * (FIRST_BUCKET_SIZE << i).  The overhead information precedes the
  * data area returned to the user.
  */
-#define	FIRST_BUCKET_SIZE	32
+#define	FIRST_BUCKET_SHIFT	5
+#define	FIRST_BUCKET_SIZE	(1 << FIRST_BUCKET_SHIFT)
 #define	NBUCKETS 30
 static	union overhead *nextf[NBUCKETS];
 
+#ifdef CAPREVOKE
+/*
+ * In the CAPREVOKE case, we encode the bucket in the next pointer's low
+ * bit in the quarantine pool.  The static assert ensures that remains
+ * possible.
+ */
+_Static_assert(NBUCKETS < FIRST_BUCKET_SIZE,
+    "Not enough alignment to encode bucket in pointer bits");
+#define	MAX_QUARANTINE	(1024 * 1024)
+#define	MAX_PAINTED	(4 * MAX_QUARANTINE)
+static	union overhead *quarantine_bufs[NBUCKETS];
+static	union overhead *painted_bufs[NBUCKETS];
+static	size_t quarantine_size, painted_size;
+static	volatile const struct caprevoke_info *cri;
+static	caprevoke_epoch painted_epoch;
+#endif
+
 static	size_t pagesz;			/* page size */
 
 
@@ -131,6 +156,92 @@ bound_ptr(void *mem, size_t nbytes)
 	return (ptr);
 }
 
+#ifdef CAPREVOKE
+static void
+free_painted(void)
+{
+	int bucket;
+	union overhead *op, *next_op;;
+
+	for (bucket = 0; bucket < NBUCKETS; bucket++)
+		for (op = painted_bufs[bucket]; op != NULL; op = op->ov_next)
+			__clear_shadow(op, FIRST_BUCKET_SIZE << bucket);
+
+	/* XXX: how do we know that no thread is revoking? */
+	atomic_thread_fence(memory_order_acq_rel);
+
+	for (bucket = 0; bucket < NBUCKETS; bucket++) {
+		op = painted_bufs[bucket];
+		while (op != NULL) {
+			next_op = op->ov_next;
+			op->ov_next = nextf[bucket];
+			nextf[bucket] = op;
+			op = next_op;
+		}
+	}
+	painted_size = 0;
+}
+
+static void
+try_revoke(int target_bucket)
+{
+	int bucket, error;
+	union overhead *op, *next_op;
+
+	/* See if prior painting has resulted in revoked pointers. */
+	/*
+	 * NB: despite the NULL check below, cri is always non-NULL if
+	 * used here.  We defer initilization as long as possible to
+	 * avoid the extra syscall in the common case.
+	 */
+	if (painted_size > 0 &&
+	    caprevoke_epoch_clears(cri->epoch_dequeue, painted_epoch))
+		free_painted();
+
+	if (quarantine_size < MAX_QUARANTINE && painted_size < MAX_PAINTED)
+		return;
+
+	if (cri == NULL) {
+		error = caprevoke_shadow(CAPREVOKE_SHADOW_INFO_STRUCT, NULL,
+		    __DECONST(void **, &cri));
+		assert(error == 0);
+	}
+
+	/* Paint all buffers in quarantine */
+	for (bucket = 0; bucket < NBUCKETS; bucket++) {
+		op = quarantine_bufs[bucket];
+		while (op != NULL) {
+			next_op = op->ov_next;
+			__paint_shadow(op, FIRST_BUCKET_SIZE << bucket);
+			op->ov_next = painted_bufs[bucket];
+			painted_bufs[bucket] = op;
+			op = next_op;
+		}
+	}
+	painted_size += quarantine_size;
+	quarantine_size = 0;
+	atomic_thread_fence(memory_order_acq_rel);
+	painted_epoch = cri->epoch_enqueue;
+
+	/*
+	 * Don't force revocation unless we've exceeded MAX_PAINTED and
+	 * it would return memory we actually want.  Otherwise, just
+	 * hope the base malloc does the job for us.
+	 */
+	if (painted_size < MAX_PAINTED || painted_bufs[target_bucket] == NULL)
+		return;
+
+	while (!caprevoke_epoch_clears(cri->epoch_dequeue, painted_epoch)) {
+		struct caprevoke_stats crst;
+		error = caprevoke(CAPREVOKE_LAST_PASS, painted_epoch, &crst);
+		assert(error == 0);
+	}
+
+	free_painted();
+
+}
+#endif
+
 static void *
 __simple_malloc_unaligned(size_t nbytes)
 {
@@ -166,6 +277,10 @@ __simple_malloc_unaligned(size_t nbytes)
 	 * If nothing in hash bucket right now,
 	 * request more memory from the system.
 	 */
+#ifdef CAPREVOKE
+	if ((op = nextf[bucket]) == NULL)
+		try_revoke(bucket);
+#endif
 	if ((op = nextf[bucket]) == NULL) {
 		morecore(bucket);
 		if ((op = nextf[bucket]) == NULL)
@@ -340,8 +455,14 @@ __simple_free(void *cp)
 		return;
 	bucket = op->ov_index;
 	ASSERT(bucket < NBUCKETS);
+#ifdef CAPREVOKE
+	op->ov_next = quarantine_bufs[bucket];
+	quarantine_bufs[bucket] = op;
+	quarantine_size += FIRST_BUCKET_SIZE << bucket;
+#else
 	op->ov_next = nextf[bucket];	/* also clobbers ov_magic */
 	nextf[bucket] = op;
+#endif
 }
 
 static void *
diff --git a/lib/libmalloc_simple/malloc_heap.h b/lib/libmalloc_simple/malloc_heap.h
index c924aeb9cbe3..3efb856769d9 100644
--- a/lib/libmalloc_simple/malloc_heap.h
+++ b/lib/libmalloc_simple/malloc_heap.h
@@ -39,5 +39,8 @@ extern caddr_t pagepool_end __hidden;
 int	__morepages(int n) __hidden;
 void	__init_heap(size_t pagesz) __hidden;
 void	*__rederive_pointer(void *ptr) __hidden;
+void	__paint_shadow(void *mem, size_t size) __hidden;
+void	__clear_shadow(void *mem, size_t size) __hidden;
+void	__do_revoke(void);
 
 #endif /* __MALLOC_HEAP_H__ */
diff --git a/share/mk/bsd.libnames.mk b/share/mk/bsd.libnames.mk
index 16d95804e70a..9b78743ebc3c 100644
--- a/share/mk/bsd.libnames.mk
+++ b/share/mk/bsd.libnames.mk
@@ -170,6 +170,7 @@ LIBZPOOL?=	${LIBDESTDIR}${LIBDIR_BASE}/libzpool.a
 
 LIBC_NOSYSCALLS?=	${DESTDIR}${LIBDIR_BASE}/libc_nosyscalls.a
 LIBCHERI?=	${DESTDIR}${LIBDIR_BASE}/libcheri.a
+LIBCHERI_CAPREVOKE?=	${DESTDIR}${LIBDIR_BASE}/libcheri_caprevoke.a
 LIBCHERI_SUPPORT?=	${DESTDIR}${LIBDIR_BASE}/libcheri_support.a
 LIBCHERI_SYSCALLS?=	${DESTDIR}${LIBDIR_BASE}/libcheri_syscalls.a
 LIBC_CHERI?=	${DESTDIR}${LIBDIR_BASE}/libc_cheri.a
diff --git a/share/mk/bsd.opts.mk b/share/mk/bsd.opts.mk
index c4c83d7d6bfc..27cd51dd9e04 100644
--- a/share/mk/bsd.opts.mk
+++ b/share/mk/bsd.opts.mk
@@ -79,10 +79,12 @@ __DEFAULT_NO_OPTIONS = \
     STALE_STAGED
 
 __DEFAULT_NO_OPTIONS+= \
+    CHERI_CAPREVOKE \
     CHERI_PURE \
     CHERI128 \
     CHERI256 \
     CHERIBSDBOX \
+    DLMALLOC \
     DEMO_VULNERABILITIES
 
 __DEFAULT_DEPENDENT_OPTIONS = \
diff --git a/share/mk/src.libnames.mk b/share/mk/src.libnames.mk
index 713fae68f4f9..3de9850a16c5 100644
--- a/share/mk/src.libnames.mk
+++ b/share/mk/src.libnames.mk
@@ -90,6 +90,7 @@ _LIBRARIES=	\
 		cam \
 		casper \
 		cheri \
+		cheri_caprevoke \
 		cheri_support \
 		cheri_syscalls \
 		cap_dns \
diff --git a/sys/cheri/cheri_otype.c b/sys/cheri/cheri_otype.c
index 51be5b2f9040..55f75dd9329e 100644
--- a/sys/cheri/cheri_otype.c
+++ b/sys/cheri/cheri_otype.c
@@ -42,6 +42,11 @@ __FBSDID("$FreeBSD$");
 
 #include <machine/cherireg.h>
 
+#ifdef CHERI_CAPREVOKE
+#include <sys/caprevoke.h>
+#include <vm/vm_caprevoke.h>
+#endif
+
 static struct mtx cheri_otype_lock;
 static struct unrhdr *cheri_otypes;
 /* Initialized in _start() */
@@ -82,3 +87,18 @@ cheri_otype_free(otype_t cap)
 	type = cheri_getbase(cap);
 	free_unr(cheri_otypes, type);
 }
+
+#ifdef CHERI_CAPREVOKE
+#ifndef CHERI_CAPREVOKE_CLEARTAGS
+
+/* If this changes, make the comment in sys/sys/caprevoke.h match! */
+void * __capability
+cheri_revoke_sealed(void * __capability c)
+{
+	c = cheri_unseal(c, kernel_sealcap);
+	c = cheri_andperm(c, 0);
+	return c;
+}
+
+#endif
+#endif
diff --git a/sys/compat/cheriabi/cheriabi_caprevoke.c b/sys/compat/cheriabi/cheriabi_caprevoke.c
new file mode 100644
index 000000000000..29de2245e6d5
--- /dev/null
+++ b/sys/compat/cheriabi/cheriabi_caprevoke.c
@@ -0,0 +1,629 @@
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#include "opt_compat.h"
+
+#define	EXPLICIT_USER_ACCESS
+
+#include <sys/param.h>
+#include <sys/systm.h>
+#include <sys/signal.h>
+#include <sys/user.h>
+
+#include <compat/cheriabi/cheriabi.h>
+#include <compat/cheriabi/cheriabi_util.h>
+#include <compat/cheriabi/cheriabi_proto.h>
+#include <compat/cheriabi/cheriabi_syscall.h>
+
+#include <sys/caprevoke.h>
+
+#ifdef CHERI_CAPREVOKE
+
+#include <sys/lock.h>
+#include <sys/mutex.h>
+#include <sys/proc.h>
+
+#include <vm/vm.h>
+#include <vm/vm_extern.h>
+#include <vm/vm_param.h>
+#include <vm/pmap.h>
+#include <vm/vm_map.h>
+
+#include <cheri/cheric.h>
+
+#include <sys/file.h>
+#include <sys/filedesc.h>
+#include <vm/vm_caprevoke.h>
+
+/*
+ * When revoking capabilities, we have to visit several kernel hoarders.
+ *
+ * XXX This gets exciting when these resources are shared.  For the moment,
+ * we consider only the case where these are in 1:1 correspondence with
+ * address spaces, but that's not going to be true in general (e.g., shared
+ * file descriptor tables) even today, nevermind when we start doing things
+ * like colocated processes.  Anyway, can we handwave away some of it and
+ * say that "enough" of the world must be stopped?
+ *
+ * Since some stashes allow aliasing (e.g. dup2() for filedescs), we must
+ * hold some locks for uncomfortably long.
+ */
+static void
+caprevoke_hoarders(struct proc *p, struct vm_caprevoke_cookie *crc)
+{
+	/* kqueue */
+	{
+		int fd;
+		struct filedesc *fdp = p->p_fd;
+		FILEDESC_SLOCK(fdp);
+		for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
+			struct file * fp = fdp->fd_ofiles[fd].fde_file;
+			if ((fp != NULL) && (fp->f_type == DTYPE_KQUEUE)) {
+
+				/*
+				 * We ignore errors from this function; they
+				 * indicate either that the kq has yet to be
+				 * born or that it's dying, and in either
+				 * case, that should be fine.
+				 */
+				kqueue_caprevoke(fp, crc);
+			}
+		}
+		FILEDESC_SUNLOCK(fdp);
+	}
+
+	/* aio */
+	aio_caprevoke(p, crc);
+
+	/* timers */
+	ktimer_caprevoke(p, crc);
+}
+
+static int
+cheriabi_caprevoke_fini(struct thread *td, struct cheriabi_caprevoke_args *uap,
+			int res, struct caprevoke_stats *crst)
+{
+	int res2 = copyout(crst, uap->statout, sizeof (*crst));
+	if (res != 0)
+		return res;
+	return res2;
+}
+
+static void
+cheriabi_caprevoke_just(struct thread *td, struct vm_caprevoke_cookie *vmcrc,
+			struct caprevoke_stats *stats,
+			struct cheriabi_caprevoke_args *uap)
+{
+	/*
+	 * Unlocked access is fine; this is advisory and, when it is
+	 * relevant to userland, we expect that userland has already
+	 * arranged for the bitmasks to carry the state it wants and
+	 * wants to *now* wait for the clock to advance to be sure
+	 * that time has elapsed.
+	 *
+	 * XXX But on ALPHA, we might need to explicitly add a read
+	 * barrier, unless we've already done something that's
+	 * implied a suitable one on syscall entry, which seems
+	 * unlikely.
+	 */
+	stats->epoch_init =
+		vmcrc->map->vm_caprev_st >> CAPREVST_EPOCH_SHIFT;
+
+	if (uap->flags & CAPREVOKE_JUST_MY_REGS) {
+		caprevoke_td_frame(td, vmcrc);
+	}
+	if (uap->flags & CAPREVOKE_JUST_MY_STACK) {
+		vm_caprevoke_one(vmcrc, 0,
+			(vm_offset_t)(__cheri_fromcap void *)
+				(td->td_frame->csp));
+	}
+	if (uap->flags & CAPREVOKE_JUST_HOARDERS) {
+		caprevoke_hoarders(td->td_proc, vmcrc);
+	}
+
+	/* XXX unlocked read OK? */
+	stats->epoch_fini =
+		vmcrc->map->vm_caprev_st >> CAPREVST_EPOCH_SHIFT;
+}
+
+#define SET_ST(vp, e, st) \
+	(vp)->vm_caprev_st = (((e) << CAPREVST_EPOCH_SHIFT) | (st))
+
+int
+cheriabi_caprevoke(struct thread *td, struct cheriabi_caprevoke_args *uap)
+{
+	int res;
+	caprevoke_epoch epoch;
+	enum caprevoke_state entryst, myst;
+	struct caprevoke_info cri;
+	struct caprevoke_stats stat = { 0 };
+	struct vmspace *vm;
+	vm_map_t vmm;
+	struct vm_caprevoke_cookie vmcrc;
+
+	vm = vmspace_acquire_ref(td->td_proc);
+	res = vm_caprevoke_cookie_init(&vm->vm_map, &stat, &vmcrc);
+	if (res != KERN_SUCCESS) {
+		vmspace_free(vm);
+		return cheriabi_caprevoke_fini(td, uap, vm_mmap_to_errno(res),
+					       &stat);
+	}
+	if ((uap->flags & CAPREVOKE_JUST_MASK) != 0) {
+		cheriabi_caprevoke_just(td, &vmcrc, &stat, uap);
+		vm_caprevoke_cookie_rele(&vmcrc);
+		vmspace_free(vm);
+		return cheriabi_caprevoke_fini(td, uap, 0, &stat);
+	}
+	/* Engaging the full state machine; here we go! */
+
+	vmm = vmcrc.map;
+
+	/*
+	 * We need some value that's more or less "now", but we don't have
+	 * to be too picky about it.  This value is not reported to
+	 * userland, just used to guide the interlocking below.
+	 */
+	if ((uap->flags & CAPREVOKE_IGNORE_START) != 0) {
+		uap->start_epoch = vmm->vm_caprev_st >> CAPREVST_EPOCH_SHIFT;
+	}
+
+	/*
+	 * XXX We don't support late phases anyway, except as a placeholder,
+	 * so act like the user asked us not to do one.
+	 */
+	uap->flags |= CAPREVOKE_LAST_NO_LATE;
+
+	/* Serialize and figure out what we're supposed to do */
+	vm_map_lock(vmm);
+	{
+		static const int fast_out_flags = CAPREVOKE_NO_WAIT_OK
+						| CAPREVOKE_IGNORE_START
+						| CAPREVOKE_LAST_NO_EARLY;
+		int ires = 0;
+		caprevoke_epoch first_epoch;
+
+		epoch = vmm->vm_caprev_st >> CAPREVST_EPOCH_SHIFT;
+		first_epoch = epoch;
+
+		/*
+		 * Be optimistic about the outcome of any worker currently
+		 * in progress.  We cannot truly claim that all writes to
+		 * the revocation bitmap began prior to the epoch clock's
+		 * current value if that value is in the process of being
+		 * advanced by another thread: the writes may have happened
+		 * after that thread began its work.  Therefore, bump the
+		 * counter reported to userland appropriately.
+		 *
+		 * If the current epoch already clears the given
+		 * start_epoch, this may result in epoch_init > epoch_fini!
+		 *
+		 * Similarly, if the thread advancing the clock fails to do
+		 * so, we may find that our reported epoch_init is greater
+		 * than the epoch clock and so we may end up attempting to
+		 * advance only up to this report.  This is compensated for
+		 * below, when we wake up from sleep and notice that the
+		 * epoch has not advanced.
+		 */
+
+		switch(vmm->vm_caprev_st & CAPREVST_ST_MASK) {
+		case CAPREVST_INIT_PASS:
+			/*
+			 * A revoker intends to open, but not close, this
+			 * epoch.
+			 */
+			stat.epoch_init = epoch + 1;
+			break;
+		case CAPREVST_LAST_PASS:
+			/*
+			 * A revoker intends to close an epoch, which may
+			 * be the one now open or the next one.  In either
+			 * case, the resulting epoch is closed and advanced
+			 * from its present value.
+			 */
+			stat.epoch_init = (epoch & ~1) + 2;
+			break;
+		case CAPREVST_NONE:
+		case CAPREVST_INIT_DONE:
+			/*
+			 * There is no active worker; the epoch clock is
+			 * a true reflection of the time.
+			 */
+			stat.epoch_init = epoch;
+			break;
+		}
+
+		if ((uap->flags & (fast_out_flags|CAPREVOKE_LAST_PASS))
+		    == fast_out_flags) {
+			/* Apparently they really just wanted the time. */
+			goto fast_out;
+		}
+
+reentry:
+		if (caprevoke_epoch_clears(epoch, uap->start_epoch)) {
+			/*
+			 * An entire epoch has come and gone since the
+			 * starting point of this request.  It is safe to
+			 * return to userland with the request satiated.
+			 *
+			 * In case we queued, tho', go ahead and wake up the
+			 * next would-be revoker first.
+			 */
+fast_out:
+			vm_map_unlock(vmm);
+			cv_signal(&vmm->vm_caprev_cv);
+			vm_caprevoke_cookie_rele(&vmcrc);
+			vmspace_free(vm);
+			stat.epoch_fini = epoch;
+			return cheriabi_caprevoke_fini(td, uap, ires, &stat);
+		}
+
+		/*
+		 * OK, the initial epoch clock isn't in the past.  Let's see
+		 * what state we're in and what we can accomplish.
+		 */
+		entryst = vmm->vm_caprev_st & CAPREVST_ST_MASK;
+		switch(entryst) {
+		case CAPREVST_NONE:
+			/*
+			 * Begin, non-incremental; advance clock.  We might
+			 * also be ending the epoch at the same time.
+			 */
+			if (uap->flags & CAPREVOKE_LAST_PASS) {
+				myst = CAPREVST_LAST_PASS;
+			} else {
+				myst = CAPREVST_INIT_PASS;
+			}
+			KASSERT((epoch & 1) == 0, ("Odd epoch NONE"));
+			break;
+		case CAPREVST_INIT_DONE:
+			/* We could either be finishing up or doing another pass */
+			if (uap->flags & CAPREVOKE_LAST_PASS) {
+				myst = CAPREVST_LAST_PASS;
+			} else {
+				myst = CAPREVST_INIT_PASS;
+			}
+			KASSERT((epoch & 1) == 1, ("Even epoch INIT"));
+			break;
+		case CAPREVST_LAST_PASS:
+			if ((uap->flags & CAPREVOKE_ONLY_IF_OPEN) != 0) {
+				goto fast_out;
+			}
+			/* FALLTHROUGH */
+		case CAPREVST_INIT_PASS:
+			if ((uap->flags & CAPREVOKE_NO_WAIT_OK) != 0) {
+				goto fast_out;
+			}
+
+			/* There is another revoker in progress.  Wait. */
+			KASSERT(vmm->system_map == 0, ("System map?"));
+			ires = cv_wait_sig(&vmm->vm_caprev_cv, &vmm->lock);
+			if (ires != 0) {
+				goto fast_out;
+			}
+
+			epoch = vmm->vm_caprev_st
+				>> CAPREVST_EPOCH_SHIFT;
+			if (epoch == first_epoch) {
+				stat.epoch_init = epoch;
+			}
+			goto reentry;
+		}
+
+		KASSERT((entryst == CAPREVST_NONE)
+			 || (entryst == CAPREVST_INIT_DONE),
+			("Beginning revocation with bad entry state"));
+		KASSERT((myst == CAPREVST_INIT_PASS)
+			 || (myst == CAPREVST_LAST_PASS),
+			("Beginning revocation with bad current state"));
+
+		if (((uap->flags & CAPREVOKE_ONLY_IF_OPEN) != 0)
+		    && ((epoch & 1) == 0)) {
+			/*
+			 * If we're requesting work only if an epoch is open
+			 * and one isn't, then there's only one thing to do!
+			 */
+			goto fast_out;
+		}
+
+		/*
+		 * Don't bump the epoch count here, just the state!  Wait
+		 * until we're certain it's actually open, which we can only
+		 * do below.
+		 */
+		SET_ST(vmm, epoch, myst);
+	}
+	vm_map_unlock(vmm);
+
+	/*
+	 * I am the revoker; expose an incremented epoch to userland
+	 * for its enqueue side.  Use a store fence to ensure that this
+	 * is visible before any of our subsequent loads (we can't use
+	 * vm map lock to do this, because copyout might need the map).
+	 */
+	if ((entryst == CAPREVST_NONE) && (myst == CAPREVST_LAST_PASS)) {
+		cri.epoch_enqueue = epoch + 2;
+	} else {
+		cri.epoch_enqueue = epoch + 1;
+	}
+	cri.epoch_dequeue = epoch;
+	vm_caprevoke_publish(&vmcrc, &cri);
+	wmb();
+
+	/* Walk the VM unless told not to */
+	if ((uap->flags & CAPREVOKE_LAST_NO_EARLY) == 0) {
+		res = vm_caprevoke(&vmcrc,
+			/* Userspace can ask us to avoid an IPI here */
+		   (((uap->flags & CAPREVOKE_EARLY_SYNC) != 0)
+			? VM_CAPREVOKE_PMAP_SYNC : 0)
+			/* If not first pass, only recently capdirty pages */
+		   | ((entryst == CAPREVST_INIT_DONE)
+			? VM_CAPREVOKE_INCREMENTAL : 0));
+
+		if (res == KERN_SUCCESS) {
+			/*
+			 * That worked; the epoch is certainly open; when we
+			 * set the state below, it's fine to advance the
+			 * clock rather than revert it, even if something
+			 * else goes wrong.
+			 *
+			 * Note that this is a purely local change even so;
+			 * threads interlocking against us will not see it
+			 * until we next publish the state below.
+			 */
+			if (entryst == CAPREVST_NONE) {
+				epoch++;
+				entryst = CAPREVST_INIT_DONE;
+			}
+		} else {
+			goto skip_last_pass;
+		}
+	}
+
+	/*
+	 * If we are beginning the last pass, single-thread the world and
+	 * expunge state that we want to ensure does not become visible
+	 * during the body of the last pass.
+	 */
+	if (myst == CAPREVST_LAST_PASS) {
+		struct thread *ptd;
+
+		PROC_LOCK(td->td_proc);
+		if ((td->td_proc->p_flag & P_HADTHREADS) != 0) {
+			if (thread_single(td->td_proc, SINGLE_BOUNDARY)) {
+				PROC_UNLOCK(td->td_proc);
+
+				vm_map_lock(vmm);
+				SET_ST(vmm, epoch, entryst);
+				vm_map_unlock(vmm);
+
+				/* XXX Don't signal other would-be revokers? */
+
+				vm_caprevoke_cookie_rele(&vmcrc);
+				vmspace_free(vm);
+
+				/* XXX Don't copy out the stat structure? */
+
+				return ERESTART;
+			}
+		}
+
+		/* Register file */
+		FOREACH_THREAD_IN_PROC(td->td_proc, ptd) {
+			caprevoke_td_frame(ptd, &vmcrc);
+			sigaltstack_caprevoke(td, &vmcrc);
+		}
+		PROC_UNLOCK(td->td_proc);
+
+		/* Kernel hoarders */
+		caprevoke_hoarders(td->td_proc, &vmcrc);
+
+		/*
+		 * The world is stopped; do another pass through the VM.
+		 *
+		 * This pass can be incremental if we had previously done an
+		 * init pass, either just now or earlier.  In either case,
+		 * we'll have entryst == CAPREVST_INIT_DONE; there's no need
+		 * to look at CAPREVOKE_LAST_NO_EARLY.
+		 */
+		res = vm_caprevoke(&vmcrc,
+			((entryst == CAPREVST_INIT_DONE)
+				? VM_CAPREVOKE_INCREMENTAL : 0)
+			| VM_CAPREVOKE_LAST_INIT
+			| VM_CAPREVOKE_PMAP_SYNC
+			| (((uap->flags & CAPREVOKE_LAST_NO_LATE) != 0)
+				? VM_CAPREVOKE_LAST_FINI : 0));
+
+		PROC_LOCK(td->td_proc);
+		if ((td->td_proc->p_flag & P_HADTHREADS) != 0) {
+			/* Un-single-thread the world */
+			thread_single_end(td->td_proc, SINGLE_BOUNDARY);
+		}
+
+		if (res != KERN_SUCCESS) {
+			PROC_UNLOCK(td->td_proc);
+
+			vm_map_lock(vmm);
+			SET_ST(vmm, epoch, entryst);
+			vm_map_unlock(vmm);
+
+			cv_signal(&vmm->vm_caprev_cv);
+
+			vm_caprevoke_cookie_rele(&vmcrc);
+			vmspace_free(vm);
+
+			stat.epoch_fini = epoch;
+			return cheriabi_caprevoke_fini(td, uap, 0, &stat);
+		}
+		PROC_UNLOCK(td->td_proc);
+
+		if (entryst == CAPREVST_NONE) {
+			/* That counts as our initial pass */
+			epoch++;
+			entryst = CAPREVST_INIT_DONE;
+		}
+
+		if ((uap->flags & CAPREVOKE_LAST_NO_LATE) == 0) {
+			/*
+			 * Walk the VM again, now with the world running;
+			 * as we must have done a pass before here, this is
+			 * certain to be an incremental pass.
+			 */
+			res = vm_caprevoke(&vmcrc,
+				VM_CAPREVOKE_INCREMENTAL
+				| VM_CAPREVOKE_LAST_FINI);
+		}
+	}
+
+skip_last_pass:
+	/* OK, that's that.  Where do we stand now? */
+	{
+		if ((res == KERN_SUCCESS) && (myst == CAPREVST_LAST_PASS)) {
+			/* Signal the end of this revocation epoch */
+			epoch++;
+			cri.epoch_dequeue = epoch;
+			vm_caprevoke_publish(&vmcrc, &cri);
+			vm_map_lock(vmm);
+			SET_ST(vmm, epoch, CAPREVST_NONE);
+			vm_map_unlock(vmm);
+		} else {
+			/*
+			 * Put the state back how we found it, modulo
+			 * having perhaps finished the first pass.
+			 */
+			cri.epoch_dequeue = epoch;
+			vm_caprevoke_publish(&vmcrc, &cri);
+			vm_map_lock(vmm);
+			SET_ST(vmm, epoch, entryst);
+			vm_map_unlock(vmm);
+		}
+	}
+
+	/* Broadcast here: some sleepers may be able to take the fast out */
+	cv_broadcast(&vmm->vm_caprev_cv);
+
+	vm_caprevoke_cookie_rele(&vmcrc);
+	vmspace_free(vm);
+
+	/*
+	 * Return the epoch as it was at the end of the run above,
+	 * not necessarily as it is now.  This value is useful only
+	 * for retroactive comparisons, i.e., to answer if
+	 * particular epochs are in the past.
+	 */
+	stat.epoch_fini = epoch;
+
+	return cheriabi_caprevoke_fini(td, uap, 0, &stat);
+}
+
+int
+cheriabi_caprevoke_shadow(struct thread *td,
+			    struct cheriabi_caprevoke_shadow_args *uap)
+{
+	int arena_perms, error;
+	void * __capability cres;
+	vm_offset_t base, size;
+	int sel = uap->flags & CAPREVOKE_SHADOW_SPACE_MASK;
+
+	if (!SV_CURPROC_FLAG(SV_CHERI))
+		return ENOSYS;
+
+	switch (sel) {
+	case CAPREVOKE_SHADOW_NOVMMAP:
+
+		if (cheri_gettag(uap->arena) == 0)
+			return EINVAL;
+
+		arena_perms = cheri_getperm(uap->arena);
+
+		if ((arena_perms & CHERI_PERM_CHERIABI_VMMAP) == 0)
+			return EPERM;
+
+		base = cheri_getbase(uap->arena);
+		size = cheri_getlen(uap->arena);
+
+		cres = vm_caprevoke_shadow_cap(sel, base, size, arena_perms);
+
+		break;
+
+	case CAPREVOKE_SHADOW_OTYPE: {
+		int reqperms;
+
+		if (cheri_gettag(uap->arena) == 0)
+			return EINVAL;
+
+		/* XXX Require all of VMMAP, SEAL, and UNSEAL permissions? */
+		reqperms = CHERI_PERM_SEAL | CHERI_PERM_UNSEAL
+			     | CHERI_PERM_CHERIABI_VMMAP;
+		arena_perms = cheri_getperm(uap->arena);
+		if ((arena_perms & reqperms) != reqperms)
+			return EPERM;
+
+		base = cheri_getbase(uap->arena);
+		size = cheri_getlen(uap->arena);
+
+		cres = vm_caprevoke_shadow_cap(sel, base, size, 0);
+
+		}
+		break;
+
+	case CAPREVOKE_SHADOW_INFO_STRUCT: {
+		/* Anyone's allowed to ask, I guess; ->arena ignored. */
+		cres = vm_caprevoke_shadow_cap(sel, 0, 0, 0);
+
+		break;
+	}
+	default:
+		return EINVAL;
+	}
+
+	if (cheri_gettag(cres))
+		error = copyoutcap(&cres, uap->shadow, sizeof(cres));
+	else
+		error = (__cheri_addr uintptr_t)cres;
+
+	return error;
+}
+
+extern void * __capability caprev_shadow_cap;
+int
+cheriabi_caprevoke_entire_shadow_cap(struct thread *td,
+			    struct cheriabi_caprevoke_entire_shadow_cap_args *uap)
+{
+	return copyoutcap(&caprev_shadow_cap, uap->shadow, sizeof(caprev_shadow_cap));
+}
+
+#else /* CHERI_CAPREVOKE */
+
+int
+cheriabi_caprevoke(struct thread *td, struct cheriabi_caprevoke_args *uap)
+{
+	struct caprevoke_stats stat = { 0 };
+
+	copyout(&stat, uap->statout, sizeof (stat));
+
+	return ENOSYS;
+}
+
+int
+cheriabi_caprevoke_shadow(struct thread *td,
+			    struct cheriabi_caprevoke_shadow_args *uap)
+{
+	void * __capability cres = NULL;
+
+	copyoutcap(&cres, uap->shadow, sizeof(cres));
+
+	return ENOSYS;
+}
+
+int
+cheriabi_caprevoke_entire_shadow_cap(struct thread *td,
+			    struct cheriabi_caprevoke_entire_shadow_cap_args *uap)
+{
+	void * __capability cres = NULL;
+
+	copyoutcap(&cres, uap->shadow, sizeof(cres));
+
+	return ENOSYS;
+}
+
+#endif /* CHERI_CAPREVOKE */
diff --git a/sys/compat/cheriabi/cheriabi_proto.h b/sys/compat/cheriabi/cheriabi_proto.h
index b23eedc8c1d2..f01777ba5500 100644
--- a/sys/compat/cheriabi/cheriabi_proto.h
+++ b/sys/compat/cheriabi/cheriabi_proto.h
@@ -514,6 +514,19 @@ struct cheriabi_kbounce_args {
 	char len_l_[PADL_(size_t)]; size_t len; char len_r_[PADR_(size_t)];
 	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
 };
+struct cheriabi_caprevoke_shadow_args {
+	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
+	char arena_l_[PADL_(void * __capability)]; void * __capability arena; char arena_r_[PADR_(void * __capability)];
+	char shadow_l_[PADL_(void * __capability)]; void * __capability shadow; char shadow_r_[PADR_(void * __capability)];
+};
+struct cheriabi_caprevoke_args {
+	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
+	char start_epoch_l_[PADL_(uint64_t)]; uint64_t start_epoch; char start_epoch_r_[PADR_(uint64_t)];
+	char statout_l_[PADL_(struct caprevoke_stats * __capability)]; struct caprevoke_stats * __capability statout; char statout_r_[PADR_(struct caprevoke_stats * __capability)];
+};
+struct cheriabi_caprevoke_entire_shadow_cap_args {
+	char shadow_l_[PADL_(void * __capability)]; void * __capability shadow; char shadow_r_[PADR_(void * __capability)];
+};
 struct cheriabi_lchmod_args {
 	char path_l_[PADL_(const char * __capability)]; const char * __capability path; char path_r_[PADR_(const char * __capability)];
 	char mode_l_[PADL_(mode_t)]; mode_t mode; char mode_r_[PADR_(mode_t)];
@@ -1567,6 +1580,9 @@ int	cheriabi_aio_read(struct thread *, struct cheriabi_aio_read_args *);
 int	cheriabi_aio_write(struct thread *, struct cheriabi_aio_write_args *);
 int	cheriabi_lio_listio(struct thread *, struct cheriabi_lio_listio_args *);
 int	cheriabi_kbounce(struct thread *, struct cheriabi_kbounce_args *);
+int	cheriabi_caprevoke_shadow(struct thread *, struct cheriabi_caprevoke_shadow_args *);
+int	cheriabi_caprevoke(struct thread *, struct cheriabi_caprevoke_args *);
+int	cheriabi_caprevoke_entire_shadow_cap(struct thread *, struct cheriabi_caprevoke_entire_shadow_cap_args *);
 int	cheriabi_lchmod(struct thread *, struct cheriabi_lchmod_args *);
 int	cheriabi_lutimes(struct thread *, struct cheriabi_lutimes_args *);
 int	cheriabi_preadv(struct thread *, struct cheriabi_preadv_args *);
@@ -1902,6 +1918,9 @@ int	cheriabi_shm_rename(struct thread *, struct cheriabi_shm_rename_args *);
 #define	CHERIABI_SYS_AUE_cheriabi_aio_write	AUE_AIO_WRITE
 #define	CHERIABI_SYS_AUE_cheriabi_lio_listio	AUE_LIO_LISTIO
 #define	CHERIABI_SYS_AUE_cheriabi_kbounce	AUE_NULL
+#define	CHERIABI_SYS_AUE_cheriabi_caprevoke_shadow	AUE_NULL
+#define	CHERIABI_SYS_AUE_cheriabi_caprevoke	AUE_NULL
+#define	CHERIABI_SYS_AUE_cheriabi_caprevoke_entire_shadow_cap	AUE_NULL
 #define	CHERIABI_SYS_AUE_cheriabi_lchmod	AUE_LCHMOD
 #define	CHERIABI_SYS_AUE_cheriabi_lutimes	AUE_LUTIMES
 #define	CHERIABI_SYS_AUE_cheriabi_preadv	AUE_PREADV
diff --git a/sys/compat/cheriabi/cheriabi_sysargmap.h b/sys/compat/cheriabi/cheriabi_sysargmap.h
index 9f3b72f7a916..3445d98b04e3 100644
--- a/sys/compat/cheriabi/cheriabi_sysargmap.h
+++ b/sys/compat/cheriabi/cheriabi_sysargmap.h
@@ -145,6 +145,9 @@ int cheriabi_sysargmask[] = {
  [CHERIABI_SYS_cheriabi_aio_write] = (0x0 | 0x1),
  [CHERIABI_SYS_cheriabi_lio_listio] = (0x0 | 0x2 | 0x8),
  [CHERIABI_SYS_cheriabi_kbounce] = (0x0 | 0x1 | 0x2),
+ [CHERIABI_SYS_cheriabi_caprevoke_shadow] = (0x0 | 0x2 | 0x4),
+ [CHERIABI_SYS_cheriabi_caprevoke] = (0x0 | 0x4),
+ [CHERIABI_SYS_cheriabi_caprevoke_entire_shadow_cap] = (0x0 | 0x1),
  [CHERIABI_SYS_cheriabi_lchmod] = (0x0 | 0x1),
  [CHERIABI_SYS_cheriabi_lutimes] = (0x0 | 0x1 | 0x2),
  [CHERIABI_SYS_cheriabi_preadv] = (0x0 | 0x2),
diff --git a/sys/compat/cheriabi/cheriabi_syscall.h b/sys/compat/cheriabi/cheriabi_syscall.h
index 87b8a03b82d5..2531cb2216c2 100644
--- a/sys/compat/cheriabi/cheriabi_syscall.h
+++ b/sys/compat/cheriabi/cheriabi_syscall.h
@@ -235,6 +235,9 @@
 #define	CHERIABI_SYS_cheriabi_aio_write	256
 #define	CHERIABI_SYS_cheriabi_lio_listio	257
 #define	CHERIABI_SYS_cheriabi_kbounce	258
+#define	CHERIABI_SYS_cheriabi_caprevoke_shadow	259
+#define	CHERIABI_SYS_cheriabi_caprevoke	260
+#define	CHERIABI_SYS_cheriabi_caprevoke_entire_shadow_cap	261
 				/* 272 is obsolete freebsd11_getdents */
 #define	CHERIABI_SYS_cheriabi_lchmod	274
 				/* 275 is obsolete netbsd_lchown */
diff --git a/sys/compat/cheriabi/cheriabi_syscall.mk b/sys/compat/cheriabi/cheriabi_syscall.mk
index 38358061d3f6..6b3705f74830 100644
--- a/sys/compat/cheriabi/cheriabi_syscall.mk
+++ b/sys/compat/cheriabi/cheriabi_syscall.mk
@@ -153,6 +153,9 @@ MIASM =  \
 	cheriabi_aio_write.o \
 	cheriabi_lio_listio.o \
 	cheriabi_kbounce.o \
+	cheriabi_caprevoke_shadow.o \
+	cheriabi_caprevoke.o \
+	cheriabi_caprevoke_entire_shadow_cap.o \
 	cheriabi_lchmod.o \
 	cheriabi_lutimes.o \
 	cheriabi_preadv.o \
diff --git a/sys/compat/cheriabi/cheriabi_syscalls.c b/sys/compat/cheriabi/cheriabi_syscalls.c
index bf14725468cc..6c650d9ebe54 100644
--- a/sys/compat/cheriabi/cheriabi_syscalls.c
+++ b/sys/compat/cheriabi/cheriabi_syscalls.c
@@ -265,9 +265,9 @@ const char *cheriabi_syscallnames[] = {
 	"cheriabi_aio_write",			/* 256 = cheriabi_aio_write */
 	"cheriabi_lio_listio",			/* 257 = cheriabi_lio_listio */
 	"cheriabi_kbounce",			/* 258 = cheriabi_kbounce */
-	"#259",			/* 259 = nosys */
-	"#260",			/* 260 = nosys */
-	"#261",			/* 261 = nosys */
+	"cheriabi_caprevoke_shadow",			/* 259 = cheriabi_caprevoke_shadow */
+	"cheriabi_caprevoke",			/* 260 = cheriabi_caprevoke */
+	"cheriabi_caprevoke_entire_shadow_cap",			/* 261 = cheriabi_caprevoke_entire_shadow_cap */
 	"#262",			/* 262 = nosys */
 	"#263",			/* 263 = nosys */
 	"#264",			/* 264 = nosys */
diff --git a/sys/compat/cheriabi/cheriabi_sysent.c b/sys/compat/cheriabi/cheriabi_sysent.c
index 5d13f4e8c126..fc230f9ac621 100644
--- a/sys/compat/cheriabi/cheriabi_sysent.c
+++ b/sys/compat/cheriabi/cheriabi_sysent.c
@@ -273,9 +273,9 @@ struct sysent cheriabi_sysent[] = {
 	{ AS(cheriabi_aio_write_args), (sy_call_t *)cheriabi_aio_write, AUE_AIO_WRITE, NULL, 0, 0, SYF_CAPENABLED, SY_THR_STATIC },	/* 256 = cheriabi_aio_write */
 	{ AS(cheriabi_lio_listio_args), (sy_call_t *)cheriabi_lio_listio, AUE_LIO_LISTIO, NULL, 0, 0, SYF_CAPENABLED, SY_THR_STATIC },	/* 257 = cheriabi_lio_listio */
 	{ AS(cheriabi_kbounce_args), (sy_call_t *)cheriabi_kbounce, AUE_NULL, NULL, 0, 0, 0, SY_THR_STATIC },	/* 258 = cheriabi_kbounce */
-	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 259 = nosys */
-	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 260 = nosys */
-	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 261 = nosys */
+	{ AS(cheriabi_caprevoke_shadow_args), (sy_call_t *)cheriabi_caprevoke_shadow, AUE_NULL, NULL, 0, 0, SYF_CAPENABLED, SY_THR_STATIC },	/* 259 = cheriabi_caprevoke_shadow */
+	{ AS(cheriabi_caprevoke_args), (sy_call_t *)cheriabi_caprevoke, AUE_NULL, NULL, 0, 0, SYF_CAPENABLED, SY_THR_STATIC },	/* 260 = cheriabi_caprevoke */
+	{ AS(cheriabi_caprevoke_entire_shadow_cap_args), (sy_call_t *)cheriabi_caprevoke_entire_shadow_cap, AUE_NULL, NULL, 0, 0, SYF_CAPENABLED, SY_THR_STATIC },	/* 261 = cheriabi_caprevoke_entire_shadow_cap */
 	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 262 = nosys */
 	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 263 = nosys */
 	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 264 = nosys */
diff --git a/sys/compat/cheriabi/cheriabi_sysstubs.h b/sys/compat/cheriabi/cheriabi_sysstubs.h
index 310f4b654e8f..64d0f415da97 100644
--- a/sys/compat/cheriabi/cheriabi_sysstubs.h
+++ b/sys/compat/cheriabi/cheriabi_sysstubs.h
@@ -15,12 +15,11 @@
 #include <sys/wait.h>
 
 #include <compat/cheriabi/cheriabi_signal.h>
-struct __ucontext;
-struct __wrusage;
 struct acl;
 struct aiocb;
-struct auditinfo_addr;
 struct auditinfo;
+struct auditinfo_addr;
+struct caprevoke_stats;
 struct ffclock_estimate;
 struct fhandle;
 struct freebsd11_stat;
@@ -30,15 +29,15 @@ struct iovec;
 struct itimerspec;
 struct itimerval;
 struct jail;
-struct kevent_freebsd11;
 struct kevent;
+struct kevent_freebsd11;
 struct kld_file_stat;
 struct mac;
 struct module_stat;
 struct mq_attr;
 struct msghdr;
-struct msqid_ds_old;
 struct msqid_ds;
+struct msqid_ds_old;
 struct nstat;
 struct ntptimeval;
 struct oaiocb;
@@ -57,8 +56,8 @@ struct sched_param;
 struct sctp_sndrcvinfo;
 struct sembuf;
 struct sf_hdtr;
-struct shmid_ds_old;
 struct shmid_ds;
+struct shmid_ds_old;
 struct sigaction;
 struct sigaltstack;
 struct sigevent;
@@ -73,10 +72,12 @@ struct timespec;
 struct timeval;
 struct timex;
 struct timezone;
+struct __ucontext;
 struct utsname;
 struct uuid;
-union semun_old;
+struct __wrusage;
 union semun;
+union semun_old;
 SYS_STUB(2, int, fork,
     /* _protoargs */ (void),
     /* _protoargs_chk */ (int *retp , int * __capability stub_errno),
@@ -1518,6 +1519,36 @@ SYS_STUB(258, int, kbounce,
     /* _localcheck */ {if (!(cheri_getperm(src) & CHERI_PERM_GLOBAL)) {errno = EPROT; return ((int)-1);} if (!(cheri_getperm(dst) & CHERI_PERM_GLOBAL)) {errno = EPROT; return ((int)-1);} }
 )
 
+SYS_STUB(259, int, caprevoke_shadow,
+    /* _protoargs */ (int flags, void *  arena, void *  shadow),
+    /* _protoargs_chk */ (int *retp , int * __capability stub_errno, int flags, void * __capability   arena, void * __capability   shadow),
+    /* _protoargs_err */ (int * __capability stub_errno, int flags, void * __capability   arena, void * __capability   shadow),
+    /* _callargs */ (flags, (__cheri_fromcap void * )arena, (__cheri_fromcap void * )shadow),
+    /* _callargs_chk */ (&ret, stub_errno, flags, arena, shadow),
+    /* _callargs_err */ (&errno, flags, (void * )arena, (void * )shadow),
+    /* _localcheck */ {if (!(cheri_getperm(arena) & CHERI_PERM_GLOBAL)) {errno = EPROT; return ((int)-1);} if (!(cheri_getperm(shadow) & CHERI_PERM_GLOBAL)) {errno = EPROT; return ((int)-1);} }
+)
+
+SYS_STUB(260, void*, caprevoke,
+    /* _protoargs */ (int flags, uint64_t start_epoch, struct caprevoke_stats *  statout),
+    /* _protoargs_chk */ (void* *retp , int * __capability stub_errno, int flags, uint64_t start_epoch, struct caprevoke_stats * __capability   statout),
+    /* _protoargs_err */ (int * __capability stub_errno, int flags, uint64_t start_epoch, struct caprevoke_stats * __capability   statout),
+    /* _callargs */ (flags, start_epoch, (__cheri_fromcap struct caprevoke_stats * )statout),
+    /* _callargs_chk */ (&ret, stub_errno, flags, start_epoch, statout),
+    /* _callargs_err */ (&errno, flags, start_epoch, (struct caprevoke_stats * )statout),
+    /* _localcheck */ {if (!(cheri_getperm(statout) & CHERI_PERM_GLOBAL)) {errno = EPROT; return ((void*)-1);} }
+)
+
+SYS_STUB(261, void*, caprevoke_entire_shadow_cap,
+    /* _protoargs */ (void *  shadow),
+    /* _protoargs_chk */ (void* *retp , int * __capability stub_errno, void * __capability   shadow),
+    /* _protoargs_err */ (int * __capability stub_errno, void * __capability   shadow),
+    /* _callargs */ ((__cheri_fromcap void * )shadow),
+    /* _callargs_chk */ (&ret, stub_errno, shadow),
+    /* _callargs_err */ (&errno, (void * )shadow),
+    /* _localcheck */ {if (!(cheri_getperm(shadow) & CHERI_PERM_GLOBAL)) {errno = EPROT; return ((void*)-1);} }
+)
+
 SYS_STUB(274, int, lchmod,
     /* _protoargs */ (const char *  path, mode_t mode),
     /* _protoargs_chk */ (int *retp , int * __capability stub_errno, const char * __capability   path, mode_t mode),
diff --git a/sys/compat/cheriabi/cheriabi_systrace_args.c b/sys/compat/cheriabi/cheriabi_systrace_args.c
index 9689122bd3c1..3ba1214336c3 100644
--- a/sys/compat/cheriabi/cheriabi_systrace_args.c
+++ b/sys/compat/cheriabi/cheriabi_systrace_args.c
@@ -1276,6 +1276,31 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
 		*n_args = 4;
 		break;
 	}
+	/* cheriabi_caprevoke_shadow */
+	case 259: {
+		struct cheriabi_caprevoke_shadow_args *p = params;
+		iarg[0] = p->flags; /* int */
+		uarg[1] = (__cheri_addr intptr_t) p->arena; /* void * __capability */
+		uarg[2] = (__cheri_addr intptr_t) p->shadow; /* void * __capability */
+		*n_args = 3;
+		break;
+	}
+	/* cheriabi_caprevoke */
+	case 260: {
+		struct cheriabi_caprevoke_args *p = params;
+		iarg[0] = p->flags; /* int */
+		uarg[1] = p->start_epoch; /* uint64_t */
+		uarg[2] = (__cheri_addr intptr_t) p->statout; /* struct caprevoke_stats * __capability */
+		*n_args = 3;
+		break;
+	}
+	/* cheriabi_caprevoke_entire_shadow_cap */
+	case 261: {
+		struct cheriabi_caprevoke_entire_shadow_cap_args *p = params;
+		uarg[0] = (__cheri_addr intptr_t) p->shadow; /* void * __capability */
+		*n_args = 1;
+		break;
+	}
 	/* cheriabi_lchmod */
 	case 274: {
 		struct cheriabi_lchmod_args *p = params;
@@ -5312,6 +5337,48 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
 			break;
 		};
 		break;
+	/* cheriabi_caprevoke_shadow */
+	case 259:
+		switch(ndx) {
+		case 0:
+			p = "int";
+			break;
+		case 1:
+			p = "userland void * __capability";
+			break;
+		case 2:
+			p = "userland void * __capability";
+			break;
+		default:
+			break;
+		};
+		break;
+	/* cheriabi_caprevoke */
+	case 260:
+		switch(ndx) {
+		case 0:
+			p = "int";
+			break;
+		case 1:
+			p = "uint64_t";
+			break;
+		case 2:
+			p = "userland struct caprevoke_stats * __capability";
+			break;
+		default:
+			break;
+		};
+		break;
+	/* cheriabi_caprevoke_entire_shadow_cap */
+	case 261:
+		switch(ndx) {
+		case 0:
+			p = "userland void * __capability";
+			break;
+		default:
+			break;
+		};
+		break;
 	/* cheriabi_lchmod */
 	case 274:
 		switch(ndx) {
@@ -9566,6 +9633,21 @@ systrace_return_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
 		if (ndx == 0 || ndx == 1)
 			p = "int";
 		break;
+	/* cheriabi_caprevoke_shadow */
+	case 259:
+		if (ndx == 0 || ndx == 1)
+			p = "int";
+		break;
+	/* cheriabi_caprevoke */
+	case 260:
+		if (ndx == 0 || ndx == 1)
+			p = "void *";
+		break;
+	/* cheriabi_caprevoke_entire_shadow_cap */
+	case 261:
+		if (ndx == 0 || ndx == 1)
+			p = "void *";
+		break;
 	/* cheriabi_lchmod */
 	case 274:
 		if (ndx == 0 || ndx == 1)
diff --git a/sys/conf/files b/sys/conf/files
index af12d2dd7548..314e2130340b 100644
--- a/sys/conf/files
+++ b/sys/conf/files
@@ -313,6 +313,7 @@ cheri/cheri_asserts.c			optional cpu_cheri
 cheri/cheri_sysctl.c			optional cpu_cheri
 cheri/cheri_otype.c			optional cpu_cheri
 compat/cheriabi/cheriabi_abort2.c	optional compat_cheriabi
+compat/cheriabi/cheriabi_caprevoke.c	optional compat_cheriabi
 compat/cheriabi/cheriabi_generic.c	optional compat_cheriabi
 compat/cheriabi/cheriabi_mac.c		optional compat_cheriabi
 compat/cheriabi/cheriabi_mmap.c		optional compat_cheriabi
@@ -323,6 +324,7 @@ compat/cheriabi/cheriabi_sysent.c	optional compat_cheriabi
 compat/cheriabi/cheriabi_time.c		optional compat_cheriabi
 compat/cheriabi/cheriabi_uipc.c		optional compat_cheriabi
 compat/cheriabi/cheriabi_vfs.c		optional compat_cheriabi
+vm/vm_caprevoke.c			optional cpu_cheri cheri_caprevoke
 
 # dtrace specific
 cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c	optional dtrace compile-with "${DTRACE_C}" \
diff --git a/sys/conf/files.mips b/sys/conf/files.mips
index 12b5b5740e6d..cf6e2f52c80c 100644
--- a/sys/conf/files.mips
+++ b/sys/conf/files.mips
@@ -58,6 +58,9 @@ mips/mips/trap.c			standard
 mips/mips/uio_machdep.c			standard
 mips/mips/uma_machdep.c			standard
 mips/mips/vm_machdep.c			standard
+mips/mips/vm_machdep_caprevoke.c	optional	cpu_cheri cheri_caprevoke
+mips/mips/vm_machdep_caprevoke_tests.c	optional	cpu_cheri cheri_caprevoke \
+	compile-with "${NORMAL_C} -fomit-frame-pointer"
 
 # misc opt-in bits
 kern/kern_clocksource.c			standard
diff --git a/sys/conf/options.mips b/sys/conf/options.mips
index 131ee47b5985..27204a168ce1 100644
--- a/sys/conf/options.mips
+++ b/sys/conf/options.mips
@@ -143,6 +143,14 @@ CPU_CHERI128			opt_global.h
 #
 CPU_CHERI_NO_SYSCALL_AUTHORIZE opt_global.h
 
+#
+# Capability revocation
+#
+CHERI_CAPREVOKE			opt_global.h
+CHERI_CAPREVOKE_CLOADTAGS	opt_global.h
+CHERI_CAPREVOKE_STATS		opt_global.h
+CHERI_CAPREVOKE_CLEARTAGS	opt_global.h
+
 #
 # Options that control the NetFPGA-10G Embedded CPU Ethernet Core.
 #
diff --git a/sys/kern/capabilities.conf b/sys/kern/capabilities.conf
index 897c64145514..4a788704249a 100644
--- a/sys/kern/capabilities.conf
+++ b/sys/kern/capabilities.conf
@@ -425,6 +425,9 @@ mprotect
 ##
 ## Allow simple VM operations on the current process.
 ##
+caprevoke
+caprevoke_shadow
+caprevoke_entire_shadow_cap
 msync
 munlock
 munlockall
diff --git a/sys/kern/imgact_elf.c b/sys/kern/imgact_elf.c
index 33c440db27f9..c29df14b7204 100644
--- a/sys/kern/imgact_elf.c
+++ b/sys/kern/imgact_elf.c
@@ -2600,7 +2600,7 @@ note_procstat_vmmap(void *arg, struct sbuf *sb, size_t *sizep)
 		sbuf_set_drain(sb, sbuf_count_drain, &size);
 		sbuf_bcat(sb, &structsize, sizeof(structsize));
 		PROC_LOCK(p);
-		kern_proc_vmmap_out(p, sb, -1, vmmap_flags);
+		kern_proc_vmmap_out(p, sb, -1, 0, 0, vmmap_flags);
 		sbuf_finish(sb);
 		sbuf_delete(sb);
 		*sizep = size;
@@ -2608,7 +2608,7 @@ note_procstat_vmmap(void *arg, struct sbuf *sb, size_t *sizep)
 		sbuf_bcat(sb, &structsize, sizeof(structsize));
 		PROC_LOCK(p);
 		kern_proc_vmmap_out(p, sb, *sizep - sizeof(structsize),
-		    vmmap_flags);
+		    0, 0, vmmap_flags);
 	}
 }
 
diff --git a/sys/kern/init_sysent.c b/sys/kern/init_sysent.c
index 794ce9553d04..2b4706469448 100644
--- a/sys/kern/init_sysent.c
+++ b/sys/kern/init_sysent.c
@@ -315,9 +315,9 @@ struct sysent sysent[] = {
 	{ AS(aio_write_args), (sy_call_t *)sys_aio_write, AUE_AIO_WRITE, NULL, 0, 0, SYF_CAPENABLED, SY_THR_STATIC },	/* 256 = aio_write */
 	{ AS(lio_listio_args), (sy_call_t *)sys_lio_listio, AUE_LIO_LISTIO, NULL, 0, 0, SYF_CAPENABLED, SY_THR_STATIC },	/* 257 = lio_listio */
 	{ AS(kbounce_args), (sy_call_t *)sys_kbounce, AUE_NULL, NULL, 0, 0, 0, SY_THR_STATIC },	/* 258 = kbounce */
-	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 259 = nosys */
-	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 260 = nosys */
-	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 261 = nosys */
+	{ AS(caprevoke_shadow_args), (sy_call_t *)sys_caprevoke_shadow, AUE_NULL, NULL, 0, 0, SYF_CAPENABLED, SY_THR_STATIC },	/* 259 = caprevoke_shadow */
+	{ AS(caprevoke_args), (sy_call_t *)sys_caprevoke, AUE_NULL, NULL, 0, 0, SYF_CAPENABLED, SY_THR_STATIC },	/* 260 = caprevoke */
+	{ AS(caprevoke_entire_shadow_cap_args), (sy_call_t *)sys_caprevoke_entire_shadow_cap, AUE_NULL, NULL, 0, 0, SYF_CAPENABLED, SY_THR_STATIC },	/* 261 = caprevoke_entire_shadow_cap */
 	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 262 = nosys */
 	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 263 = nosys */
 	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 264 = nosys */
diff --git a/sys/kern/kern_event.c b/sys/kern/kern_event.c
index 008880057cea..8a2b58ac1f64 100644
--- a/sys/kern/kern_event.c
+++ b/sys/kern/kern_event.c
@@ -81,6 +81,14 @@ __FBSDID("$FreeBSD$");
 #include <machine/atomic.h>
 
 #include <vm/uma.h>
+#include <vm/vm_extern.h>
+
+
+#ifdef CHERI_CAPREVOKE
+#include <cheri/cheric.h>
+#include <sys/caprevoke.h>
+#include <vm/vm_caprevoke.h>
+#endif
 
 MALLOC_DEFINE(M_KQUEUE, "kqueue", "memory for kqueue system");
 
@@ -2734,6 +2742,55 @@ kqfd_register(int fd, struct kevent *kev, struct thread *td, int mflag)
 	fdrop(fp, td);
 	return (error);
 }
+
+#ifdef CHERI_CAPREVOKE
+
+int
+kqueue_caprevoke(struct file *fp, const struct vm_caprevoke_cookie *crc)
+{
+	struct kqueue *kq;
+	struct knote *kn;
+	int error, ix;
+	CAPREVOKE_STATS_FOR(crst, crc);
+
+	error = kqueue_acquire(fp, &kq);
+	if (error != 0)
+		return (error);
+
+	KQ_LOCK(kq);
+	for (ix = 0; ix < kq->kq_knlistsize; ix++) {
+		SLIST_FOREACH(kn, &kq->kq_knlist[ix], kn_link) {
+			void * __capability ud = kn->kn_kevent.udata;
+			if (!cheri_gettag(ud))
+				continue;
+	                CAPREVOKE_STATS_BUMP(crst, caps_found);
+			if (vm_caprevoke_test(crc, ud)) {
+				kn->kn_kevent.udata = cheri_revoke(ud);
+	                        CAPREVOKE_STATS_BUMP(crst, caps_cleared);
+			}
+		}
+	}
+	for (ix = 0; ix <= kq->kq_knhashmask; ix++) {
+		SLIST_FOREACH(kn, &kq->kq_knhash[ix], kn_link) {
+			void * __capability ud = kn->kn_kevent.udata;
+			if (!cheri_gettag(ud))
+				continue;
+	                CAPREVOKE_STATS_BUMP(crst, caps_found);
+			if (vm_caprevoke_test(crc, ud)) {
+				kn->kn_kevent.udata = cheri_revoke(ud);
+	                        CAPREVOKE_STATS_BUMP(crst, caps_cleared);
+			}
+		}
+	}
+
+	kqueue_release(kq, 1);
+	KQ_UNLOCK(kq);
+
+	return 0;
+}
+
+#endif
+
 // CHERI CHANGES START
 // {
 //   "updated": 20181203,
diff --git a/sys/kern/kern_exec.c b/sys/kern/kern_exec.c
index d9a025cec725..757736a7d4dd 100644
--- a/sys/kern/kern_exec.c
+++ b/sys/kern/kern_exec.c
@@ -84,6 +84,11 @@ __FBSDID("$FreeBSD$");
 #include <vm/vm_object.h>
 #include <vm/vm_pager.h>
 
+#ifdef CHERI_CAPREVOKE
+#include <cheri/cheric.h>
+#include <vm/vm_caprevoke.h>
+#endif
+
 #ifdef	HWPMC_HOOKS
 #include <sys/pmckern.h>
 #endif
@@ -1073,6 +1078,11 @@ exec_new_vmspace(struct image_params *imgp, struct sysentvec *sv)
 	    cpu_exec_vmspace_reuse(p, map)) {
 		shmexit(vmspace);
 		pmap_remove_pages(vmspace_pmap(vmspace));
+
+#ifdef CHERI_CAPREVOKE
+		map->vm_caprev_sh = NULL;
+#endif
+
 		vm_map_remove(map, vm_map_min(map), vm_map_max(map));
 		/*
 		 * An exec terminates mlockall(MCL_FUTURE), ASLR state
@@ -1143,6 +1153,22 @@ exec_new_vmspace(struct image_params *imgp, struct sysentvec *sv)
 	if (error != KERN_SUCCESS)
 		return (vm_mmap_to_errno(error));
 
+#ifdef CHERI_CAPREVOKE
+	/*
+	 * For CheriABI, create an anonymous, CoW mapping for the revocation
+	 * bitmaps.
+	 *
+	 * XXX This almost surely belongs elsewhere, but I don't immediately
+	 * see a per-sv hook here.
+	 */
+	if (sv->sv_flags & SV_CHERI) {
+		error = vm_map_install_caprevoke_shadow(map);
+
+		if (error != KERN_SUCCESS)
+			return (vm_mmap_to_errno(error));
+	}
+#endif
+
 	/*
 	 * vm_ssize and vm_maxsaddr are somewhat antiquated concepts, but they
 	 * are still used to enforce the stack rlimit on the process stack.
diff --git a/sys/kern/kern_proc.c b/sys/kern/kern_proc.c
index 3b07793bf6f8..d3cf417dad10 100644
--- a/sys/kern/kern_proc.c
+++ b/sys/kern/kern_proc.c
@@ -2651,7 +2651,8 @@ next:;
  * Must be called with the process locked and will return unlocked.
  */
 int
-kern_proc_vmmap_out(struct proc *p, struct sbuf *sb, ssize_t maxlen, int flags)
+kern_proc_vmmap_out(struct proc *p, struct sbuf *sb, ssize_t maxlen,
+	vm_offset_t startaddr, size_t n, int flags)
 {
 	vm_map_entry_t entry, tmp_entry;
 	struct vattr va;
@@ -2666,6 +2667,7 @@ kern_proc_vmmap_out(struct proc *p, struct sbuf *sb, ssize_t maxlen, int flags)
 	unsigned int last_timestamp;
 	int error;
 	bool super;
+	size_t pathlen, i;
 
 	PROC_LOCK_ASSERT(p, MA_OWNED);
 
@@ -2681,10 +2683,29 @@ kern_proc_vmmap_out(struct proc *p, struct sbuf *sb, ssize_t maxlen, int flags)
 	error = 0;
 	map = &vm->vm_map;
 	vm_map_lock_read(map);
-	VM_MAP_ENTRY_FOREACH(entry, map) {
+
+	/* XXX I really wish this could be 0, not 1. But...
+	 *
+	 * Someone is too damn smart and sees NULL for the new ptr and
+	 * zorches the new length, causing the kernel to do a full sweep
+	 * at first.  Pass 1 instead of 0 for the first query base.
+	 */
+	if (startaddr <= 1) {
+		entry = vm_map_entry_first(map);
+	} else {
+		boolean_t in = vm_map_lookup_entry(map, startaddr, &entry);
+		if (!in) {
+			entry = vm_map_entry_succ(entry);
+		}
+	}
+
+	for (i = 0; (entry != &map->header) && (n == 0 || i < n);
+	     entry = vm_map_entry_succ(entry)) {
 		if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
 			continue;
 
+		i++;
+
 		addr = entry->end;
 		bzero(kve, sizeof(*kve));
 		obj = entry->object.vm_object;
@@ -2722,6 +2743,13 @@ kern_proc_vmmap_out(struct proc *p, struct sbuf *sb, ssize_t maxlen, int flags)
 		if (entry->protection & VM_PROT_EXECUTE)
 			kve->kve_protection |= KVME_PROT_EXEC;
 
+		if (entry->max_protection & VM_PROT_READ)
+			kve->kve_max_protection |= KVME_PROT_READ;
+		if (entry->max_protection & VM_PROT_WRITE)
+			kve->kve_max_protection |= KVME_PROT_WRITE;
+		if (entry->max_protection & VM_PROT_EXECUTE)
+			kve->kve_max_protection |= KVME_PROT_EXEC;
+
 		if (entry->eflags & MAP_ENTRY_COW)
 			kve->kve_flags |= KVME_FLAG_COW;
 		if (entry->eflags & MAP_ENTRY_NEEDS_COPY)
@@ -2746,6 +2774,18 @@ kern_proc_vmmap_out(struct proc *p, struct sbuf *sb, ssize_t maxlen, int flags)
 				vref(vp);
 			if (lobj != obj)
 				VM_OBJECT_RUNLOCK(lobj);
+#ifdef OBJ_NOSTORETAGS
+			if ((obj->flags & OBJ_NOSTORETAGS) == 0) {
+				kve->kve_protection |= KVME_PROT_WRITECAPS;
+				kve->kve_max_protection |= KVME_PROT_WRITECAPS;
+			}
+#endif
+#ifdef OBJ_NOLOADTAGS
+			if ((obj->flags & OBJ_NOLOADTAGS) == 0) {
+				kve->kve_protection |= KVME_PROT_READCAPS;
+				kve->kve_max_protection |= KVME_PROT_READCAPS;
+			}
+#endif
 
 			kve->kve_ref_count = obj->ref_count;
 			kve->kve_shadow_count = obj->shadow_count;
@@ -2775,18 +2815,37 @@ kern_proc_vmmap_out(struct proc *p, struct sbuf *sb, ssize_t maxlen, int flags)
 			kve->kve_type = KVME_TYPE_NONE;
 			kve->kve_ref_count = 0;
 			kve->kve_shadow_count = 0;
+
+			/* Anonymous memory is presumed able to have tags */
+			kve->kve_protection |= KVME_PROT_READCAPS
+					       | KVME_PROT_WRITECAPS;
+
+			kve->kve_max_protection |= KVME_PROT_READCAPS
+						   | KVME_PROT_WRITECAPS;
 		}
 
-		strlcpy(kve->kve_path, fullpath, sizeof(kve->kve_path));
+		if ((kve->kve_protection & KVME_PROT_READ) == 0)
+			kve->kve_protection &= ~KVME_PROT_READCAPS;
+		if ((kve->kve_protection & KVME_PROT_WRITE) == 0)
+			kve->kve_protection &= ~KVME_PROT_WRITECAPS;
+		if ((kve->kve_max_protection & KVME_PROT_READ) == 0)
+			kve->kve_max_protection &= ~KVME_PROT_READCAPS;
+		if ((kve->kve_max_protection & KVME_PROT_WRITE) == 0)
+			kve->kve_max_protection &= ~KVME_PROT_WRITECAPS;
+
+		pathlen = strlcpy(kve->kve_path, fullpath, sizeof(kve->kve_path));
 		if (freepath != NULL)
 			free(freepath, M_TEMP);
 
 		/* Pack record size down */
-		if ((flags & KERN_VMMAP_PACK_KINFO) != 0)
+		if ((flags & KERN_VMMAP_PACK_KINFO) != 0) {
+			if (pathlen > sizeof(kve->kve_path))
+				pathlen = sizeof(kve->kve_path);
+
 			kve->kve_structsize =
 			    offsetof(struct kinfo_vmentry, kve_path) +
-			    strlen(kve->kve_path) + 1;
-		else
+			    pathlen + 1;
+		} else
 			kve->kve_structsize = sizeof(*kve);
 		kve->kve_structsize = roundup(kve->kve_structsize,
 		    sizeof(uint64_t));
@@ -2794,25 +2853,29 @@ kern_proc_vmmap_out(struct proc *p, struct sbuf *sb, ssize_t maxlen, int flags)
 		/* Halt filling and truncate rather than exceeding maxlen */
 		if (maxlen != -1 && maxlen < kve->kve_structsize) {
 			error = 0;
-			vm_map_lock_read(map);
-			break;
+			goto out_nolock;
 		} else if (maxlen != -1)
 			maxlen -= kve->kve_structsize;
 
 		if (sbuf_bcat(sb, kve, kve->kve_structsize) != 0)
 			error = ENOMEM;
-		vm_map_lock_read(map);
 		if (error != 0)
-			break;
+			goto out_nolock;
+		vm_map_lock_read(map);
 		if (last_timestamp != map->timestamp) {
 			vm_map_lookup_entry(map, addr - 1, &tmp_entry);
 			entry = tmp_entry;
 		}
 	}
 	vm_map_unlock_read(map);
+out_nolock:
 	vmspace_free(vm);
 	PRELE(p);
 	free(kve, M_TEMP);
+
+	if (i == 0)
+		error = ENOENT;
+
 	return (error);
 }
 
@@ -2822,8 +2885,17 @@ sysctl_kern_proc_vmmap(SYSCTL_HANDLER_ARGS)
 	struct proc *p;
 	struct sbuf sb;
 	int error, error2, *name;
+	vm_offset_t base;
+	size_t n;
 
 	name = (int *)arg1;
+
+	base = (__cheri_addr vm_offset_t)(req->newptr);
+	req->newptr = NULL;
+
+	n = req->newlen;
+	req->newlen = 0;
+
 	sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_vmentry), req);
 	sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
 	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
@@ -2831,7 +2903,8 @@ sysctl_kern_proc_vmmap(SYSCTL_HANDLER_ARGS)
 		sbuf_delete(&sb);
 		return (error);
 	}
-	error = kern_proc_vmmap_out(p, &sb, -1, KERN_VMMAP_PACK_KINFO);
+	error = kern_proc_vmmap_out(p, &sb, -1, base, n,
+		KERN_VMMAP_PACK_KINFO);
 	error2 = sbuf_finish(&sb);
 	sbuf_delete(&sb);
 	return (error != 0 ? error : error2);
@@ -3545,8 +3618,10 @@ static SYSCTL_NODE(_kern_proc, KERN_PROC_OVMMAP, ovmmap, CTLFLAG_RD |
 	CTLFLAG_MPSAFE, sysctl_kern_proc_ovmmap, "Old Process vm map entries");
 #endif
 
-static SYSCTL_NODE(_kern_proc, KERN_PROC_VMMAP, vmmap, CTLFLAG_RD |
-	CTLFLAG_MPSAFE, sysctl_kern_proc_vmmap, "Process vm map entries");
+/* XXXNWF CTLFLAG_RW is a hack to sneak a parameter in! */
+static SYSCTL_NODE(_kern_proc, KERN_PROC_VMMAP, vmmap, CTLFLAG_RW |
+	CTLFLAG_MPSAFE, sysctl_kern_proc_vmmap,
+	"Process vm map entries");
 
 #if defined(STACK) || defined(DDB)
 static SYSCTL_NODE(_kern_proc, KERN_PROC_KSTACK, kstack, CTLFLAG_RD |
diff --git a/sys/kern/kern_sig.c b/sys/kern/kern_sig.c
index b68df88e5f28..ae50c3b3330d 100644
--- a/sys/kern/kern_sig.c
+++ b/sys/kern/kern_sig.c
@@ -99,6 +99,10 @@ __FBSDID("$FreeBSD$");
  */
 #include <cheri/cheri.h>
 #include <cheri/cheric.h>
+#ifdef CHERI_CAPREVOKE
+#include <vm/vm_caprevoke.h>
+#include <sys/caprevoke.h>
+#endif
 #endif
 
 #include <machine/cpu.h>
@@ -1744,6 +1748,24 @@ kern_sigaltstack(struct thread *td, stack_t *ss, stack_t *oss)
 	return (0);
 }
 
+#ifdef CHERI_CAPREVOKE
+void
+sigaltstack_caprevoke(struct thread *td, const struct vm_caprevoke_cookie *crc)
+{
+	CAPREVOKE_STATS_FOR(crst, crc);
+
+	void * __capability sp = td->td_sigstk.ss_sp;
+
+	if (cheri_gettag(sp)) {
+		CAPREVOKE_STATS_BUMP(crst, caps_found);
+		if (vm_caprevoke_test(crc, sp)) {
+			CAPREVOKE_STATS_BUMP(crst, caps_cleared);
+			td->td_sigstk.ss_sp = cheri_revoke(sp);
+		}
+	}
+}
+#endif
+
 struct killpg1_ctx {
 	struct thread *td;
 	ksiginfo_t *ksi;
diff --git a/sys/kern/kern_time.c b/sys/kern/kern_time.c
index 5c1a244287c1..8dee2b0106c4 100644
--- a/sys/kern/kern_time.c
+++ b/sys/kern/kern_time.c
@@ -67,6 +67,12 @@ __FBSDID("$FreeBSD$");
 #include <vm/vm.h>
 #include <vm/vm_extern.h>
 
+#ifdef CHERI_CAPREVOKE
+#include <cheri/cheric.h>
+#include <sys/caprevoke.h>
+#include <vm/vm_caprevoke.h>
+#endif
+
 #define MAX_CLOCKS 	(CLOCK_MONOTONIC+1)
 #define CPUCLOCK_BIT		0x80000000
 #define CPUCLOCK_PROCESS_BIT	0x40000000
@@ -1383,6 +1389,40 @@ kern_ktimer_delete(struct thread *td, int timerid)
 	return (0);
 }
 
+#ifdef CHERI_CAPREVOKE
+
+void
+ktimer_caprevoke(struct proc *p, const struct vm_caprevoke_cookie *crc)
+{
+	int i;
+
+	CAPREVOKE_STATS_FOR(crst, crc);
+
+	if (p->p_itimers == NULL)
+		return;
+
+	PROC_LOCK(p);
+	for (i = 0; i < TIMER_MAX; i++) {
+		struct itimer *it = p->p_itimers->its_timers[i];
+		if (it == NULL)
+			continue;
+
+		void * __capability v = it->it_sigev.sigev_value.sival_ptr;
+
+		if (!cheri_gettag(v))
+			continue;
+
+		CAPREVOKE_STATS_BUMP(crst, caps_found);
+		if (vm_caprevoke_test(crc, v)) {
+			it->it_sigev.sigev_value.sival_ptr = cheri_revoke(v);
+			CAPREVOKE_STATS_BUMP(crst, caps_cleared);
+		}
+	}
+	PROC_UNLOCK(p);
+}
+
+#endif
+
 #ifndef _SYS_SYSPROTO_H_
 struct ktimer_settime_args {
 	int timerid;
diff --git a/sys/kern/makesyscalls.sh b/sys/kern/makesyscalls.sh
index 9f4a442c45a4..9800d7cbe33e 100644
--- a/sys/kern/makesyscalls.sh
+++ b/sys/kern/makesyscalls.sh
@@ -77,6 +77,7 @@ fi
 
 if [ -n "$capenabled" ]; then
 	# do nothing
+	:
 elif [ -r $capabilities_conf ]; then
 	capenabled=`egrep -v '^#|^$' $capabilities_conf`
 	capenabled=`echo $capenabled | sed 's/ /,/g'`
diff --git a/sys/kern/syscalls.c b/sys/kern/syscalls.c
index dc011385d615..b22348f595f8 100644
--- a/sys/kern/syscalls.c
+++ b/sys/kern/syscalls.c
@@ -265,9 +265,9 @@ const char *syscallnames[] = {
 	"aio_write",			/* 256 = aio_write */
 	"lio_listio",			/* 257 = lio_listio */
 	"kbounce",			/* 258 = kbounce */
-	"#259",			/* 259 = nosys */
-	"#260",			/* 260 = nosys */
-	"#261",			/* 261 = nosys */
+	"caprevoke_shadow",			/* 259 = caprevoke_shadow */
+	"caprevoke",			/* 260 = caprevoke */
+	"caprevoke_entire_shadow_cap",			/* 261 = caprevoke_entire_shadow_cap */
 	"#262",			/* 262 = nosys */
 	"#263",			/* 263 = nosys */
 	"#264",			/* 264 = nosys */
diff --git a/sys/kern/syscalls.master b/sys/kern/syscalls.master
index ada2c61212a5..842e30e66bbb 100644
--- a/sys/kern/syscalls.master
+++ b/sys/kern/syscalls.master
@@ -1481,7 +1481,24 @@
 		    int flags
 		);
 	}
-259-271	AUE_NULL	UNIMPL	nosys
+259	AUE_NULL	STD	{
+		int caprevoke_shadow(
+			int flags,
+			_In_ void *arena,
+			_Out_ void *shadow,
+		);
+	}
+260	AUE_NULL	STD	{
+		void *caprevoke(
+		    int flags,
+		    uint64_t start_epoch,
+		    _Out_ struct caprevoke_stats *statout,
+		);
+	}
+	261	AUE_NULL	STD {
+		void *caprevoke_entire_shadow_cap(_Out_ void *shadow);
+	}
+262-271	AUE_NULL	UNIMPL	nosys
 272	AUE_O_GETDENTS	COMPAT11 {
 		int getdents(
 		    int fd,
diff --git a/sys/kern/systrace_args.c b/sys/kern/systrace_args.c
index 61343c0b539c..51f2e9989299 100644
--- a/sys/kern/systrace_args.c
+++ b/sys/kern/systrace_args.c
@@ -1330,6 +1330,31 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
 		*n_args = 4;
 		break;
 	}
+	/* caprevoke_shadow */
+	case 259: {
+		struct caprevoke_shadow_args *p = params;
+		iarg[0] = p->flags; /* int */
+		uarg[1] = (intptr_t) p->arena; /* void * __capability */
+		uarg[2] = (intptr_t) p->shadow; /* void * __capability */
+		*n_args = 3;
+		break;
+	}
+	/* caprevoke */
+	case 260: {
+		struct caprevoke_args *p = params;
+		iarg[0] = p->flags; /* int */
+		uarg[1] = p->start_epoch; /* uint64_t */
+		uarg[2] = (intptr_t) p->statout; /* struct caprevoke_stats * __capability */
+		*n_args = 3;
+		break;
+	}
+	/* caprevoke_entire_shadow_cap */
+	case 261: {
+		struct caprevoke_entire_shadow_cap_args *p = params;
+		uarg[0] = (intptr_t) p->shadow; /* void * __capability */
+		*n_args = 1;
+		break;
+	}
 	/* lchmod */
 	case 274: {
 		struct lchmod_args *p = params;
@@ -5462,6 +5487,48 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
 			break;
 		};
 		break;
+	/* caprevoke_shadow */
+	case 259:
+		switch(ndx) {
+		case 0:
+			p = "int";
+			break;
+		case 1:
+			p = "userland void * __capability";
+			break;
+		case 2:
+			p = "userland void * __capability";
+			break;
+		default:
+			break;
+		};
+		break;
+	/* caprevoke */
+	case 260:
+		switch(ndx) {
+		case 0:
+			p = "int";
+			break;
+		case 1:
+			p = "uint64_t";
+			break;
+		case 2:
+			p = "userland struct caprevoke_stats * __capability";
+			break;
+		default:
+			break;
+		};
+		break;
+	/* caprevoke_entire_shadow_cap */
+	case 261:
+		switch(ndx) {
+		case 0:
+			p = "userland void * __capability";
+			break;
+		default:
+			break;
+		};
+		break;
 	/* lchmod */
 	case 274:
 		switch(ndx) {
@@ -9746,6 +9813,21 @@ systrace_return_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
 		if (ndx == 0 || ndx == 1)
 			p = "int";
 		break;
+	/* caprevoke_shadow */
+	case 259:
+		if (ndx == 0 || ndx == 1)
+			p = "int";
+		break;
+	/* caprevoke */
+	case 260:
+		if (ndx == 0 || ndx == 1)
+			p = "void *";
+		break;
+	/* caprevoke_entire_shadow_cap */
+	case 261:
+		if (ndx == 0 || ndx == 1)
+			p = "void *";
+		break;
 	/* lchmod */
 	case 274:
 		if (ndx == 0 || ndx == 1)
diff --git a/sys/kern/uipc_shm.c b/sys/kern/uipc_shm.c
index 223ae1ce93dc..753290b96d19 100644
--- a/sys/kern/uipc_shm.c
+++ b/sys/kern/uipc_shm.c
@@ -735,6 +735,10 @@ shm_remove(char *path, Fnv32_t fnv, struct ucred *ucred)
 	return (ENOENT);
 }
 
+#if __has_feature(capabilities)
+#define SHM_ANON_N	1
+#endif
+
 int
 kern_shm_open2(struct thread *td, const char * __capability userpath,
     int flags, mode_t mode, int shmflags, struct filecaps *fcaps,
@@ -756,6 +760,11 @@ kern_shm_open2(struct thread *td, const char * __capability userpath,
 	if ((shmflags & SHM_ALLOW_SEALING) != 0)
 		initial_seals &= ~F_SEAL_SEAL;
 
+#if __has_feature(capabilities)
+	if ((__cheri_addr uintptr_t) userpath == SHM_ANON_N)
+		userpath = SHM_ANON;
+#endif
+
 #ifdef CAPABILITY_MODE
 	/*
 	 * shm_open(2) is only allowed for anonymous objects.
diff --git a/sys/kern/vfs_aio.c b/sys/kern/vfs_aio.c
index 574d17c0b3bf..b65d7b3849df 100644
--- a/sys/kern/vfs_aio.c
+++ b/sys/kern/vfs_aio.c
@@ -76,10 +76,16 @@ __FBSDID("$FreeBSD$");
 #include <vm/uma.h>
 #include <sys/aio.h>
 
+#include <cheri/cheric.h>
 #ifdef COMPAT_CHERIABI
 #include <compat/cheriabi/cheriabi_util.h>
 #endif
 
+#ifdef CHERI_CAPREVOKE
+#include <sys/caprevoke.h>
+#include <vm/vm_caprevoke.h>
+#endif
+
 /*
  * Counter for allocating reference ids to new jobs.  Wrapped to 1 on
  * overflow. (XXX will be removed soon.)
@@ -2671,6 +2677,67 @@ filt_lio(struct knote *kn, long hint)
 	return (lj->lioj_flags & LIOJ_KEVENT_POSTED);
 }
 
+#ifdef CHERI_CAPREVOKE
+
+void
+aio_caprevoke(struct proc *p, const struct vm_caprevoke_cookie *crc)
+{
+	struct kaioinfo *ki;
+	struct kaiocb *job, *jobn;
+
+	/*
+	 * XXX Does not yet count caps into stats
+	 */
+
+	ki = p->p_aioinfo;
+	if (ki == NULL)
+		return;
+
+	AIO_LOCK(ki);
+
+restart:
+	/* Visit all pending jobs. */
+	TAILQ_FOREACH_SAFE(job, &ki->kaio_jobqueue, plist, jobn) {
+		void * __capability uc =
+			job->uaiocb.aio_sigevent.sigev_value.sival_ptr;
+
+		/* Zorch user pointers being revoked.
+		 *
+		 * The analog in userland (i.e. job->ujob's
+		 * aio_sigevent.sigev_value.sival_ptr) we assume will be
+		 * scrubbed by userland.
+		 */
+		if (vm_caprevoke_test(crc, uc)) {
+			job->uaiocb.aio_sigevent.sigev_value.sival_ptr =
+				cheri_revoke(uc);
+		}
+
+		/* Cancel and finish jobs whose userland metadata
+		 * structure is being revoked, so that all writes take
+		 * place before we return to userland.  Same if the
+		 * buffer itself is in the region being revoked or
+		 * the mysterious "kernelinfo" capability.
+		 */
+		if (   vm_caprevoke_test(crc, job->ujob)
+		    || vm_caprevoke_test(crc,
+					 __DEQUALIFY_CAP(void * __capability,
+					 job->uaiocb.aio_buf))
+		    || vm_caprevoke_test(crc,
+					 job->uaiocb._aiocb_private.kernelinfo)
+		   ) {
+			aio_cancel_job(p, ki, job);
+			ki->kaio_flags |= KAIO_WAKEUP;
+			msleep(&p->p_aioinfo, AIO_MTX(ki), PRIBIO,
+				"aioprn", hz);
+			goto restart;
+		}
+	}
+
+	AIO_UNLOCK(ki);
+}
+
+#endif
+
 #ifdef COMPAT_FREEBSD32
 #include <sys/mount.h>
 #include <sys/socket.h>
diff --git a/sys/mips/cheri/cheriabi_machdep.c b/sys/mips/cheri/cheriabi_machdep.c
index 180daa5910ad..723d56a43c03 100644
--- a/sys/mips/cheri/cheriabi_machdep.c
+++ b/sys/mips/cheri/cheriabi_machdep.c
@@ -596,8 +596,7 @@ cheriabi_sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
 		/* fill siginfo structure */
 		sf.sf_si.si_signo = sig;
 		sf.sf_si.si_code = ksi->ksi_code;
-		sf.sf_si.si_value.sival_int =
-		    ksi->ksi_info.si_value.sival_int;
+		sf.sf_si.si_value.sival_ptr = ksi->ksi_info.si_value.sival_ptr;
 		/*
 		 * Write out badvaddr, but don't create a valid capability
 		 * since that might allow privilege amplification.
diff --git a/sys/mips/conf/std.BENCHMARK b/sys/mips/conf/std.BENCHMARK
index 4184b039b115..2caae39fc172 100644
--- a/sys/mips/conf/std.BENCHMARK
+++ b/sys/mips/conf/std.BENCHMARK
@@ -5,3 +5,5 @@ nooptions	INVARIANTS
 nooptions	INVARIANTS_SUPPORT
 nooptions	KTRACE
 nooptions	WITNESS
+
+nooptions	CHERI_CAPREVOKE_STATS
diff --git a/sys/mips/conf/std.CHERI b/sys/mips/conf/std.CHERI
index 6874ba22cd5e..dfdbf4ecb981 100644
--- a/sys/mips/conf/std.CHERI
+++ b/sys/mips/conf/std.CHERI
@@ -11,4 +11,8 @@ options 	COMPAT_CHERIABI
 options 	COMPAT_FREEBSD64
 #options 	CHERI_IMPLICIT_USER_DDC
 
+options	CHERI_CAPREVOKE
+options	CHERI_CAPREVOKE_CLOADTAGS
+options	CHERI_CAPREVOKE_STATS
+
 options 	TMPFS
diff --git a/sys/mips/include/cherireg.h b/sys/mips/include/cherireg.h
index 68ec76c8e52e..907cb152df2f 100644
--- a/sys/mips/include/cherireg.h
+++ b/sys/mips/include/cherireg.h
@@ -165,6 +165,22 @@
 	CHERI_PERM_SEAL | CHERI_PERM_CCALL | CHERI_PERM_UNSEAL |	\
 	CHERI_PERM_SYSTEM_REGS | CHERI_PERM_SET_CID)
 
+/*
+ * Hardware defines a kind of tripartite taxonomy: memory, type, and CID.
+ * They're all squished together in the permission bits, so define masks
+ * that give us a kind of "kind" for capabilities.  A capability may belong
+ * to zero, one, or more than one of these.
+ */
+
+#define CHERI_PERMS_HWALL_MEMORY                                        \
+	(CHERI_PERM_EXECUTE | CHERI_PERM_LOAD | CHERI_PERM_LOAD_CAP |   \
+		CHERI_PERM_STORE | CHERI_PERM_STORE_CAP |               \
+		CHERI_PERM_STORE_LOCAL_CAP | CHERI_PERM_CCALL)
+
+#define CHERI_PERMS_HWALL_OTYPE	(CHERI_PERM_SEAL | CHERI_PERM_UNSEAL)
+
+// TODO #define CHERI_PERMS_HWALL_CID	(CHERI_PERM_SETCID)
+
 /*
  * Root "object-type" capability for the kernel.  This can be used neither as
  * a data nor code capability.
@@ -247,7 +263,7 @@
 /*
  * When performing a userspace-to-userspace CCall, capability flow-control
  * checks normally prevent local capabilities from being delegated.  This can
- * be disabled on call (but not return) by using an object type with the 22nd
+ * be disabled on call (but not return) by using an object type with the 16th
  * bit set -- combined with a suitable selector on the CCall instruction to
  * ensure that this behaviour is intended.
  */
diff --git a/sys/mips/include/pmap.h b/sys/mips/include/pmap.h
index 336d1725153d..1aec9c46ba82 100644
--- a/sys/mips/include/pmap.h
+++ b/sys/mips/include/pmap.h
@@ -181,6 +181,9 @@ void *pmap_kenter_temporary(vm_paddr_t pa, int i);
 void pmap_kenter_temporary_free(vm_paddr_t pa);
 void pmap_flush_pvcache(vm_page_t m);
 int pmap_emulate_modified(pmap_t pmap, vm_offset_t va);
+#ifdef CPU_CHERI
+int pmap_emulate_capdirty(pmap_t pmap, vm_offset_t va);
+#endif
 void pmap_page_set_memattr(vm_page_t, vm_memattr_t);
 int pmap_change_attr(vm_offset_t, vm_size_t, vm_memattr_t);
 
diff --git a/sys/mips/include/pte.h b/sys/mips/include/pte.h
index 51f51ee3758e..c670e50c55cf 100644
--- a/sys/mips/include/pte.h
+++ b/sys/mips/include/pte.h
@@ -105,7 +105,7 @@ typedef uint64_t pd_entry_t;
 #define	TLBLO_SWBITS_CLEAR_SHIFT	(11)	/* XXXSS: Was 9. */
 #define	TLBLO_PFN_MASK		0x3FFFFFC0ULL
 #define	TLB_1M_SUPERPAGE_SHIFT	(PDRSHIFT)
-#define	TLBLO_SWBITS_MASK	((pt_entry_t)0x7F << TLBLO_SWBITS_SHIFT)
+#define	TLBLO_SWBITS_MASK	((pt_entry_t)0xFF << TLBLO_SWBITS_SHIFT)
 #else
 #define	TLBLO_SWBITS_SHIFT	(29)
 #define	TLBLO_SWBITS_CLEAR_SHIFT	(3)
@@ -194,10 +194,10 @@ typedef uint64_t pd_entry_t;
  *
  * Upper bits of a 64 bit PTE:
  *
- *   63-62   61-60  59   58 -- 56    55   54   53
- *   ---------------------------------------------
- *  |  RG  |      | SV | PG SZ IDX | MN | W  | RO |
- *   ---------------------------------------------
+ *   63-62   61  60    59   58 -- 56    55   54   53
+ *   ------------------------------------------------
+ *  |  RG  |   | CRO | SV | PG SZ IDX | MN | W  | RO |
+ *   ------------------------------------------------
  *
  * VM flags managed in software:
  *
@@ -226,6 +226,9 @@ typedef uint64_t pd_entry_t;
  *
  *  W:  Wired.  ???
  *
+ *  CRO: CHERI-only.  Capability read only.  Never clear PTE_SC on this
+ *       entry, and fail attempts to store capabilities to it.
+ *
  *  RO: Read only.  Never set PTE_D on this page, and don't
  *      listen to requests to write to it.
  *
@@ -244,6 +247,7 @@ typedef uint64_t pd_entry_t;
 #define	PTE_PS_16M		((pt_entry_t)0x30 << TLBLO_SWBITS_SHIFT)
 #define	PTE_PS_64M		((pt_entry_t)0x38 << TLBLO_SWBITS_SHIFT)
 #define	PTE_PS_IDX_MASK		((pt_entry_t)0x38 << TLBLO_SWBITS_SHIFT)
+#define	PTE_CRO			(((pt_entry_t)0x80) << TLBLO_SWBITS_SHIFT)
 #endif
 
 #ifdef CPU_CHERI
diff --git a/sys/mips/include/vmparam.h b/sys/mips/include/vmparam.h
index edc8f37294aa..45fc8eebdf41 100644
--- a/sys/mips/include/vmparam.h
+++ b/sys/mips/include/vmparam.h
@@ -83,15 +83,64 @@
 
 #ifdef __mips_n64
 #define	VM_MAXUSER_ADDRESS	(VM_MINUSER_ADDRESS + (NPDEPG * NBSEG))
-#define	VM_MIN_KERNEL_ADDRESS	((vm_offset_t)0xc000000000000000)
-#define	VM_MAX_KERNEL_ADDRESS	(VM_MIN_KERNEL_ADDRESS + (NPDEPG * NBSEG))
-#else
-#define	VM_MAXUSER_ADDRESS	((vm_offset_t)0x80000000)
-#define	VM_MIN_KERNEL_ADDRESS	((vm_offset_t)0xC0000000)
-#define	VM_MAX_KERNEL_ADDRESS	((vm_offset_t)0xFFFFC000)
-#endif
+#ifdef CPU_CHERI
 
-#define	KERNBASE		((vm_offset_t)(intptr_t)(int32_t)0x80000000)
+/*
+ * Lay out some bitmaps for us, ranging from VM_CAPREVOKE_BM_BASE
+ * to VM_CAPREVOKE_BM_TOP:
+ *
+ * TOP:
+ * 	- shared page for per-process information (_INFO_PAGE)
+ * 	- one bit per otype (BM_OTYPE)
+ * 	- one bit per page, checked for VMMAP-bearing caps (BM_MEM_MAP)
+ * 	- one bit per cap, checked for non-VMMAP-bearing caps (BM_MEM_NOMAP)
+ * BASE:
+ *
+ * The granularities of these bitmaps are specified in the _GSZ_ constants.
+ * For the present settings, a *byte* of these bitmaps spans....
+ * 	- 8 otypes
+ * 	- 8 pages (32KiB of memory)
+ * 	- 128 bytes of memory (on CC and CHERI-128; 256 bytes on CHERI-256)
+ * Requests to access the shadow space must, therefore, be at least that
+ * aligned!
+ *
+ */
+
+#define VM_CAPREVOKE_GSZ_OTYPE		((vm_offset_t)1)
+#define VM_CAPREVOKE_GSZ_MEM_MAP	((vm_offset_t)PAGE_SIZE)
+#define VM_CAPREVOKE_GSZ_MEM_NOMAP	((vm_offset_t)sizeof (void * __capability))
+
+#define VM_CAPREVOKE_BSZ_MEM_NOMAP	(NPDEPG * NBSEG  / VM_CAPREVOKE_GSZ_MEM_NOMAP / 8)
+#define VM_CAPREVOKE_BSZ_MEM_MAP	(NPDEPG * NBSEG  / VM_CAPREVOKE_GSZ_MEM_MAP   / 8)
+#define VM_CAPREVOKE_BSZ_OTYPE		((1 << CHERI_OTYPE_BITS) / VM_CAPREVOKE_GSZ_OTYPE     / 8)
+/* XXX TODO SetCID revocation? */
+
+#define VM_CAPREVOKE_BM_TOP	VM_MAXUSER_ADDRESS
+#define VM_CAPREVOKE_BM_BASE	( VM_CAPREVOKE_BM_TOP \
+					- VM_CAPREVOKE_BSZ_MEM_NOMAP \
+					- VM_CAPREVOKE_BSZ_MEM_MAP \
+					- VM_CAPREVOKE_BSZ_OTYPE \
+					- PAGE_SIZE )
+#define VM_CAPREVOKE_BM_MEM_NOMAP	VM_CAPREVOKE_BM_BASE
+#define VM_CAPREVOKE_BM_MEM_MAP		( VM_CAPREVOKE_BM_MEM_NOMAP  \
+					+ VM_CAPREVOKE_BSZ_MEM_NOMAP )
+#define VM_CAPREVOKE_BM_OTYPE		( VM_CAPREVOKE_BM_MEM_MAP  \
+					+ VM_CAPREVOKE_BSZ_MEM_MAP )
+#define VM_CAPREVOKE_INFO_PAGE		( VM_CAPREVOKE_BM_OTYPE  \
+					+ VM_CAPREVOKE_BSZ_OTYPE )
+
+#define	SHAREDPAGE		(VM_CAPREVOKE_BM_BASE - PAGE_SIZE)
+/*
+ * To ensure that the stack base address that is sufficiently aligned, we
+ * jump down quite a bit.
+ *
+ * XXX The idea of "the" USRSTACK top/base really should go away; as
+ * rlimits are changed, our alignment requirements change as well, so
+ * there's no one right answer.
+ */
+#define	USRSTACK		(SHAREDPAGE & ~0xFFFFFFF)
+
+#else
 /*
  * USRSTACK needs to start a little below 0x8000000 because the R8000
  * and some QED CPUs perform some virtual address checks before the
@@ -103,6 +152,19 @@
  * a bounded capability we must round down by 16 pages to get to 0x7ffbff0000.
  */
 #define	USRSTACK		(SHAREDPAGE - (15 * PAGE_SIZE))
+#endif
+
+#define	VM_MIN_KERNEL_ADDRESS	((vm_offset_t)0xc000000000000000)
+#define	VM_MAX_KERNEL_ADDRESS	(VM_MIN_KERNEL_ADDRESS + (NPDEPG * NBSEG))
+#else
+#define	VM_MAXUSER_ADDRESS	((vm_offset_t)0x80000000)
+#define	VM_MIN_KERNEL_ADDRESS	((vm_offset_t)0xC0000000)
+#define	VM_MAX_KERNEL_ADDRESS	((vm_offset_t)0xFFFFC000)
+#define	SHAREDPAGE		(VM_MAXUSER_ADDRESS - PAGE_SIZE)
+#define	USRSTACK		SHAREDPAGE
+#endif
+
+#define	KERNBASE		((vm_offset_t)(intptr_t)(int32_t)0x80000000)
 #ifdef __mips_n64
 #define	FREEBSD32_SHAREDPAGE	(((vm_offset_t)0x80000000) - PAGE_SIZE)
 #define	FREEBSD32_USRSTACK	FREEBSD32_SHAREDPAGE
diff --git a/sys/mips/mips/genassym.c b/sys/mips/mips/genassym.c
index 35b2064e3ae4..658ccc83aa96 100644
--- a/sys/mips/mips/genassym.c
+++ b/sys/mips/mips/genassym.c
@@ -130,6 +130,8 @@ ASSYM(MIPS_XKSEG_START, MIPS_XKSEG_START);
 
 #ifdef	CPU_CHERI
 ASSYM(U_PCB_CHERIKFRAME, offsetof(struct pcb, pcb_cherikframe));
+ASSYM(VM_CAPREVOKE_BM_BASE, VM_CAPREVOKE_BM_BASE);
+ASSYM(VM_CAPREVOKE_BM_TOP, VM_CAPREVOKE_BM_TOP);
 #endif
 
 #ifdef	CPU_CNMIPS
diff --git a/sys/mips/mips/locore.S b/sys/mips/mips/locore.S
index a2bf2e92c722..59adbb8a835b 100644
--- a/sys/mips/mips/locore.S
+++ b/sys/mips/mips/locore.S
@@ -199,6 +199,21 @@ VECTOR(_locore, unknown)
 	PTR_LA	t0, _C_LABEL(user_sealcap)
 	csc	CHERI_REG_C27, t0, 0($ddc)
 
+#ifdef CHERI_CAPREVOKE
+	/*
+	 * And one more, this time for access to the caprev shadow space
+	 */
+	cmove		CHERI_REG_C27, CHERI_REG_C28
+	REG_LI	t0, VM_CAPREVOKE_BM_BASE
+	csetoffset	CHERI_REG_C27, CHERI_REG_C27, t0
+	REG_LI	t0, (VM_CAPREVOKE_BM_TOP - VM_CAPREVOKE_BM_BASE)
+	csetbounds	CHERI_REG_C27, CHERI_REG_C27, t0
+	REG_LI	t0, (CHERI_PERM_LOAD | CHERI_PERM_STORE)
+	candperm	CHERI_REG_C27, CHERI_REG_C27, t0
+	PTR_LA	t0, _C_LABEL(caprev_shadow_cap)
+	csc	CHERI_REG_C27, t0, 0($ddc)
+#endif
+
 	/*
 	 * Store the omnipotent capability to allow swap to be restored.
 	 */
diff --git a/sys/mips/mips/mp_machdep.c b/sys/mips/mips/mp_machdep.c
index f49dd7553d33..9d51614573a2 100644
--- a/sys/mips/mips/mp_machdep.c
+++ b/sys/mips/mips/mp_machdep.c
@@ -286,6 +286,12 @@ smp_init_secondary(u_int32_t cpuid)
 		mips_wr_hwrena(mips_rd_hwrena() | MIPS_HWRENA_UL);
 
 	/* TLB */
+#ifdef BERI_LARGE_TLB
+	/* If extended TLB entries is implemented then enable it. */
+#define	BERI_CP5_LTLB_SUPPORTED	0x1
+	if (mips_rd_config5() & BERI_CP5_LTLB_SUPPORTED)
+		mips_wr_config6(mips_rd_config6() | 0x4);
+#endif
 	mips_wr_wired(0);
 	tlb_invalidate_all();
 	mips_wr_wired(VMWIRED_ENTRIES);
diff --git a/sys/mips/mips/pm_machdep.c b/sys/mips/mips/pm_machdep.c
index 7b2a52abd953..edb8f0d9d473 100644
--- a/sys/mips/mips/pm_machdep.c
+++ b/sys/mips/mips/pm_machdep.c
@@ -81,6 +81,10 @@ __FBSDID("$FreeBSD$");
 #include <cheri/cheri.h>
 #include <cheri/cheric.h>
 #include <machine/cheri_machdep.h>
+#ifdef CHERI_CAPREVOKE
+#include <sys/caprevoke.h>
+#include <vm/vm_caprevoke.h>
+#endif
 #endif
 
 #include <ddb/ddb.h>
@@ -960,6 +964,59 @@ ptrace_clear_single_step(struct thread *td)
 	td->td_md.md_ss_addr = 0;
 	return 0;
 }
+
+#ifdef CHERI_CAPREVOKE
+
+void
+caprevoke_td_frame(struct thread *td, const struct vm_caprevoke_cookie *crc)
+{
+	CAPREVOKE_STATS_FOR(crst, crc);
+
+#define CAPREV_REG(r) \
+	do { if (cheri_gettag(r)) { \
+		CAPREVOKE_STATS_BUMP(crst, caps_found); \
+		if (vm_caprevoke_test(crc, r)) { \
+			r = cheri_revoke(r); \
+			CAPREVOKE_STATS_BUMP(crst, caps_cleared); \
+		} \
+	    }} while(0)
+
+	CAPREV_REG(td->td_frame->ddc);
+	CAPREV_REG(td->td_frame->c1);
+	CAPREV_REG(td->td_frame->c2);
+	CAPREV_REG(td->td_frame->c3);
+	CAPREV_REG(td->td_frame->c4);
+	CAPREV_REG(td->td_frame->c5);
+	CAPREV_REG(td->td_frame->c6);
+	CAPREV_REG(td->td_frame->c7);
+	CAPREV_REG(td->td_frame->c8);
+	CAPREV_REG(td->td_frame->c9);
+	CAPREV_REG(td->td_frame->c10);
+	CAPREV_REG(td->td_frame->csp);
+	CAPREV_REG(td->td_frame->c12);
+	CAPREV_REG(td->td_frame->c13);
+	CAPREV_REG(td->td_frame->c14);
+	CAPREV_REG(td->td_frame->c15);
+	CAPREV_REG(td->td_frame->c16);
+	CAPREV_REG(td->td_frame->c17);
+	CAPREV_REG(td->td_frame->c18);
+	CAPREV_REG(td->td_frame->c19);
+	CAPREV_REG(td->td_frame->c20);
+	CAPREV_REG(td->td_frame->c21);
+	CAPREV_REG(td->td_frame->c22);
+	CAPREV_REG(td->td_frame->c23);
+	CAPREV_REG(td->td_frame->c24);
+	CAPREV_REG(td->td_frame->c25);
+	CAPREV_REG(td->td_frame->idc);
+	CAPREV_REG(td->td_frame->pcc); /* This could be real exciting! */
+
+#undef CAPREV_REG
+
+	return;
+}
+
+#endif
+
 // CHERI CHANGES START
 // {
 //   "updated": 20181114,
diff --git a/sys/mips/mips/pmap.c b/sys/mips/mips/pmap.c
index 9f890b0ddf4d..04b5c8d4a14a 100644
--- a/sys/mips/mips/pmap.c
+++ b/sys/mips/mips/pmap.c
@@ -1490,6 +1490,10 @@ pmap_pv_reclaim(pmap_t locked_pmap)
 				m = PHYS_TO_VM_PAGE(TLBLO_PTE_TO_PA(oldpte));
 				if (pte_test(&oldpte, PTE_D))
 					vm_page_dirty(m);
+#ifdef PTE_SC
+				if (pte_test(&oldpte, PTE_SC) == 0)
+					vm_page_capdirty(m);
+#endif
 				if (m->md.pv_flags & PV_TABLE_REF)
 					vm_page_aflag_set(m, PGA_REFERENCED);
 				m->md.pv_flags &= ~PV_TABLE_REF;
@@ -1763,6 +1767,10 @@ pmap_remove_pte(struct pmap *pmap, pt_entry_t *ptq, vm_offset_t va,
 			    __func__, (void *)va, (uintmax_t)oldpte));
 			vm_page_dirty(m);
 		}
+#ifdef PTE_SC
+		if (pte_test(&oldpte, PTE_SC) == 0)
+			vm_page_capdirty(m);
+#endif
 		if (m->md.pv_flags & PV_TABLE_REF)
 			vm_page_aflag_set(m, PGA_REFERENCED);
 		m->md.pv_flags &= ~PV_TABLE_REF;
@@ -1942,6 +1950,10 @@ pmap_remove_all(vm_page_t m)
 			    __func__, (void *)pv->pv_va, (uintmax_t)tpte));
 			vm_page_dirty(m);
 		}
+#ifdef PTE_SC
+		if (pte_test(&tpte, PTE_SC) == 0)
+			vm_page_capdirty(m);
+#endif
 		pmap_invalidate_page(pmap, pv->pv_va);
 
 		TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
@@ -2035,6 +2047,16 @@ pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
 					va = va_next;
 				}
 			}
+#ifdef PTE_SC
+			if (pte_test(&pbits, PTE_SC) == 0) {
+				pte_set(&pbits, PTE_SC);
+				if (pte_test(&pbits, PTE_MANAGED)) {
+					pa = TLBLO_PTE_TO_PA(pbits);
+					m = PHYS_TO_VM_PAGE(pa);
+					vm_page_capdirty(m);
+				}
+			}
+#endif
 			*pte = pbits;
 		}
 		if (va != va_next)
@@ -2082,8 +2104,26 @@ pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
 #ifdef CPU_CHERI
 	if ((flags & PMAP_ENTER_NOLOADTAGS) != 0)
 		newpte |= PTE_LC;
-	if ((flags & PMAP_ENTER_NOSTORETAGS) != 0)
+	/*
+	 * If this page is unmanaged, don't try to track its capdirty status
+	 * (so determine PTE_SC entirely from NOSTORETAGS).  On the other
+	 * hand, if it's already capdirty, avoid the overhead of faulting,
+	 * since all we'd do is set the bit again (eventually, in
+	 * pmap_emulate_capdirty).
+	 *
+	 * Transfer NOSTORETAGS to PTE_CRO.
+	 *
+	 * XXX NWF: I would like, eventually, to track capdirty in the
+	 * kernel as well, but for the moment, doing this trips a panic in
+	 * pmap_emulate_capdirty because it can't find the PTE in question.
+	 * I am sure I am just holding something wrong.
+	 */
+	if ((((m->oflags & VPO_UNMANAGED) == 0)
+		&& ((m->a.flags & PGA_CAPSTORED) == 0))
+	    || ((flags & PMAP_ENTER_NOSTORETAGS) != 0))
 		newpte |= PTE_SC;
+	if ((flags & PMAP_ENTER_NOSTORETAGS) != 0)
+		newpte |= PTE_CRO;
 #endif
 	if ((m->oflags & VPO_UNMANAGED) == 0)
 		newpte |= PTE_MANAGED;
@@ -2121,6 +2161,11 @@ pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
 	KASSERT(!pte_test(&origpte, PTE_D | PTE_RO | PTE_V),
 	    ("pmap_enter: modified page not writable: va: %p, pte: %#jx",
 	    (void *)va, (uintmax_t)origpte));
+#ifdef PTE_SC
+	KASSERT(!pte_test(&origpte, PTE_CRO | PTE_V) || pte_test(&origpte, PTE_SC),
+	    ("pmap_enter: capdirty with CRO set: va: %p, pte: %#jx",
+	    (void *)va, (uintmax_t)origpte));
+#endif
 	opa = TLBLO_PTE_TO_PA(origpte);
 
 	/*
@@ -2170,6 +2215,10 @@ pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
 			om = PHYS_TO_VM_PAGE(opa);
 			if (pte_test(&origpte, PTE_D))
 				vm_page_dirty(om);
+#ifdef PTE_SC
+			if (pte_test(&origpte, PTE_SC) == 0)
+				vm_page_capdirty(m);
+#endif
 			if ((om->md.pv_flags & PV_TABLE_REF) != 0) {
 				om->md.pv_flags &= ~PV_TABLE_REF;
 				vm_page_aflag_set(om, PGA_REFERENCED);
@@ -2235,6 +2284,11 @@ pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
 				if (pte_test(&origpte, PTE_MANAGED))
 					vm_page_dirty(m);
 			}
+#ifdef PTE_SC
+			if ((pte_test(&origpte, PTE_SC) == 0)
+			    && pte_test(&origpte, PTE_MANAGED))
+				vm_page_capdirty(m);
+#endif
 			pmap_update_page(pmap, va, newpte);
 		}
 	}
@@ -2619,10 +2673,21 @@ pmap_copy_page_internal(vm_page_t src, vm_page_t dst, int flags)
 		va_src = MIPS_PHYS_TO_DIRECT(phys_src);
 		va_dst = MIPS_PHYS_TO_DIRECT(phys_dst);
 #ifdef CPU_CHERI
-		if (flags & PMAP_COPY_TAGS)
+		if (flags & PMAP_COPY_TAGS) {
 			cheri_bcopy((caddr_t)va_src, (caddr_t)va_dst,
 			    PAGE_SIZE);
-		else
+
+			/*
+			 * If we're copying tags, consider the target page
+			 * capdirty, even if tere might not be tags on the
+			 * page.  We can't accurately get the PTE's capdirty
+			 * bit, at this point, so err on the side of safety.
+			 *
+			 * XXX Can we do better?
+			 */
+	
+			vm_page_capdirty(dst);
+		} else
 #endif
 			bcopy((caddr_t)va_src, (caddr_t)va_dst, PAGE_SIZE);
 		mips_dcache_wbinv_range(va_dst, PAGE_SIZE);
@@ -2679,6 +2744,7 @@ pmap_copy_pages_internal(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
 		cnt = min(cnt, PAGE_SIZE - b_pg_offset);
 		b_m = mb[b_offset >> PAGE_SHIFT];
 		b_phys = VM_PAGE_TO_PHYS(b_m);
+
 		if (MIPS_DIRECT_MAPPABLE(a_phys) &&
 		    MIPS_DIRECT_MAPPABLE(b_phys)) {
 			pmap_flush_pvcache(a_m);
@@ -2689,9 +2755,21 @@ pmap_copy_pages_internal(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
 			b_cp = (char *)MIPS_PHYS_TO_DIRECT(b_phys) +
 			    b_pg_offset;
 #ifdef CPU_CHERI
-			if (flags & PMAP_COPY_TAGS)
+			if (flags & PMAP_COPY_TAGS) {
 				cheri_bcopy(a_cp, b_cp, cnt);
-			else
+
+				/*
+				 * If we're copying tags, consider the
+				 * target page capdirty, even if tere might
+				 * not be tags on the page.  We can't
+				 * accurately get the PTE's capdirty bit, at
+				 * this point, so err on the side of safety.
+				 *
+				 * XXX Can we do better?
+				 */
+
+				vm_page_capdirty(b_m);
+			} else
 #endif
 				bcopy(a_cp, b_cp, cnt);
 			mips_dcache_wbinv_range((vm_offset_t)b_cp, cnt);
@@ -2898,6 +2976,10 @@ pmap_remove_pages(pmap_t pmap)
 				 */
 				if (pte_test(&tpte, PTE_D))
 					vm_page_dirty(m);
+#ifdef PTE_SC
+				if (pte_test(&tpte, PTE_SC) == 0)
+					vm_page_capdirty(m);
+#endif
 
 				/* Mark free */
 				PV_STAT(pv_entry_frees++);
@@ -2925,7 +3007,7 @@ pmap_remove_pages(pmap_t pmap)
  * pmap_testbit tests bits in pte's
  */
 static boolean_t
-pmap_testbit(vm_page_t m, int bit)
+pmap_testbit(vm_page_t m, pt_entry_t bit)
 {
 	pv_entry_t pv;
 	pmap_t pmap;
@@ -3006,6 +3088,12 @@ pmap_remove_write(vm_page_t m)
 			pte_clear(&pbits, PTE_D);
 			vm_page_dirty(m);
 		}
+#ifdef PTE_SC
+		if (pte_test(&pbits, PTE_SC) == 0) {
+			pte_set(&pbits, PTE_SC);
+			vm_page_capdirty(m);
+		}
+#endif
 		pte_set(&pbits, PTE_RO);
 		if (pbits != *pte) {
 			*pte = pbits;
@@ -3170,6 +3258,12 @@ pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
 					va = va_next;
 				}
 			}
+#ifdef PTE_SC
+			if (pte_test(pte, PTE_SC) == 0) {
+				pte_set(pte, PTE_SC);
+				vm_page_capdirty(m);
+			}
+#endif
 		}
 		if (va != va_next)
 			pmap_invalidate_range(pmap, va, sva);
@@ -3311,6 +3405,10 @@ pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
 	val = MINCORE_INCORE;
 	if (pte_test(&pte, PTE_D))
 		val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
+#ifdef PTE_SC
+	if (pte_test(&pte, PTE_SC) == 0)
+		val |= MINCORE_MAYHAVECAP;
+#endif
 	pa = TLBLO_PTE_TO_PA(pte);
 	if (pte_test(&pte, PTE_MANAGED)) {
 		/*
@@ -3547,6 +3645,175 @@ pmap_emulate_modified(pmap_t pmap, vm_offset_t va)
 	return (0);
 }
 
+#if __has_feature(capabilities)
+
+/*
+ * For every mapping of this page, collect and clear its capdirty PTE
+ * entries, promoting them to the page's PGA_CAPSTORED bit.
+ *
+ * XXX This is now only used by mincore; perhaps a more gentle approach
+ * could be taken?
+ *
+ * XREF pmap_clear_modify and pmap_is_modified
+ */
+boolean_t
+pmap_tc_capdirty(vm_page_t m)
+{
+	pv_entry_t pv;
+	boolean_t found;
+
+	/*
+	 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
+	 * concurrently set while the object is locked.  Thus, if PGA_WRITEABLE
+	 * is clear, no PTEs can have PTE_SC clear.
+	 */
+	VM_OBJECT_ASSERT_LOCKED(m->object);
+
+	found = (m->a.flags & PGA_CAPSTORED) != 0;
+
+	rw_wlock(&pvh_global_lock);
+	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
+		pmap_t pmap;
+		pt_entry_t *pte;
+
+		pmap = PV_PMAP(pv);
+		PMAP_LOCK(pmap);
+		pte = pmap_pte(pmap, pv->pv_va);
+		if (pte_test(pte, PTE_SC) == 0) {
+			if (!found)
+				vm_page_capdirty(m);
+			found = 1;
+			pte_set(pte, PTE_SC);
+			pmap_update_page(pmap, pv->pv_va, *pte);
+		}
+		PMAP_UNLOCK(pmap);
+
+	}
+	rw_wunlock(&pvh_global_lock);
+
+	return found;
+}
+
+/*
+ * Atomically push all the in-PTE, MD capdirty bits up to the MI layer.
+ *
+ * While this is a fairly long-running operation under the current pmap
+ * lock, it's going to be called only from single-threaded context, so there
+ * should be minimal contention (perhaps from the page daemon or updates to
+ * shared mappings) as no other cores are going to have this pmap active.
+ *
+ * XREF pmap_remove_pages
+ */
+
+void
+pmap_sync_capdirty(pmap_t pmap)
+{
+	struct pv_chunk *pc, *npc;
+
+	PMAP_LOCK(pmap);
+
+	/*
+	 * While we expect that no other cores have us active right now,
+	 * because we're thread_single'd, other TLBs may still have cached
+	 * entries with PTE_SC clear!  We'd best get those out of the way.
+	 *
+	 * Doing this before clearing the bits means that even if we're
+	 * wrong about being single-threaded, those other cores will park
+	 * behind us when they go to update their TLBs.
+	 *
+	 * XXX Is it worth only invalidating the capdirty ones?
+	 */
+	tlb_invalidate_all_user(pmap);
+
+	TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
+		int field;
+
+		for (field = 0; field < _NPCM; field++) {
+			u_long inuse;
+
+			inuse = ~pc->pc_map[field] & pc_freemask[field];
+			while (inuse != 0) {
+				pd_entry_t *pde;
+				pt_entry_t *pte, tpte;
+				pv_entry_t pv;
+				u_long bitmask;
+				int bit, idx;
+
+				bit = ffsl(inuse) - 1;
+				bitmask = 1UL << bit;
+				idx = field * sizeof(inuse) * NBBY + bit;
+				pv = &pc->pc_pventry[idx];
+				inuse &= ~bitmask;
+
+				pde = pmap_pde(pmap, pv->pv_va);
+				KASSERT(pde != NULL && *pde != 0,
+				    ("pmap_sync_capdirty: pde"));
+				pte = pmap_pde_to_pte(pde, pv->pv_va);
+				if (!pte_test(pte, PTE_V))
+					panic("pmap_sync_capdirty: bad pte");
+				tpte = *pte;
+
+				if (pte_test(&tpte, PTE_MANAGED) == 0)
+					continue;
+
+				if (pte_test(&tpte, PTE_SC) == 0) {
+					vm_page_t m;
+
+					m = PHYS_TO_VM_PAGE(
+					      TLBLO_PTE_TO_PA(tpte));
+					KASSERT(m != NULL,
+					  ("pmap_sync_capdirty: bad tpte %#jx",
+					   (uintmax_t)(tpte)));
+
+					KASSERT(pte_test(&tpte, PTE_CRO) == 0,
+					 ("cap-read-only without inhibit?"));
+
+					vm_page_capdirty(m);
+					pte_set(pte, PTE_SC);
+				}
+			}
+		}
+	}
+
+	PMAP_UNLOCK(pmap);
+}
+
+/* XREF pmap_emulate_modified */
+int
+pmap_emulate_capdirty(pmap_t pmap, vm_offset_t va)
+{
+	pt_entry_t *pte;
+
+	PMAP_LOCK(pmap);
+	pte = pmap_pte(pmap, va);
+	if (pte == NULL)
+		panic("pmap_emulate_capdirty: can't find PTE");
+#ifdef SMP
+	/* It is possible that some other CPU changed m-bit */
+	if (!pte_test(pte, PTE_V) || !pte_test(pte, PTE_SC)) {
+		tlb_update(pmap, va, *pte);
+		PMAP_UNLOCK(pmap);
+		return (0);
+	}
+#else
+	if (!pte_test(pte, PTE_V) || !pte_test(pte, PTE_SC))
+		panic("pmap_emulate_capdirty: invalid pte");
+#endif
+	if (pte_test(pte, PTE_RO) || pte_test(pte, PTE_CRO)) {
+		PMAP_UNLOCK(pmap);
+		return (1);
+	}
+
+	pte_clear(pte, PTE_SC);
+	tlb_update(pmap, va, *pte);
+	if (!pte_test(pte, PTE_MANAGED))
+		panic("pmap_emulate_capdirty: unmanaged page");
+	PMAP_UNLOCK(pmap);
+	return 0;
+}
+
+#endif
+
 /*
  *	Routine:	pmap_kextract
  *	Function:
diff --git a/sys/mips/mips/trap.c b/sys/mips/mips/trap.c
index b6ed3254cda8..bcd30e0a2cde 100644
--- a/sys/mips/mips/trap.c
+++ b/sys/mips/mips/trap.c
@@ -677,6 +677,36 @@ cpu_fetch_syscall_args(struct thread *td)
 #define __FBSDID(x)
 #include "../../kern/subr_syscall.c"
 
+#ifdef CPU_CHERI
+static inline int
+try_emulate_capdirty(struct trapframe *trapframe, pmap_t kpmap, pmap_t upmap)
+{
+	register_t cause = trapframe->capcause;
+
+	cause &= CHERI_CAPCAUSE_EXCCODE_MASK;
+	cause >>= CHERI_CAPCAUSE_EXCCODE_SHIFT;
+
+	if (cause == CHERI_EXCCODE_TLBSTORE) {
+		/*
+		 * This could just need capdirty emulation; we cannot get
+		 * here unless the TLB entry is permitted to store, just not
+		 * store capabilities.  That is, all CoW will have already
+		 * been handled for us, thank goodness.
+		 */
+
+		vm_offset_t va = trapframe->badvaddr;
+
+		if (KERNLAND(va)) {
+			if (kpmap) {
+				return pmap_emulate_capdirty(kpmap, va);
+			}
+		} else {
+			return pmap_emulate_capdirty(upmap, va);
+		}
+	}
+	return 1;
+}
+#endif
 
 /*
  * Handle an exception.
@@ -1137,6 +1167,11 @@ trap(struct trapframe *trapframe)
 		break;
 #ifdef CPU_CHERI
 	case T_C2E:
+		if(try_emulate_capdirty(trapframe, kernel_pmap,
+					&p->p_vmspace->vm_pmap) == 0) {
+			return trapframe->pc;
+		}
+
 		if (td->td_pcb->pcb_onfault != NULL) {
 			pc = trapf_pc_from_kernel_code_ptr(td->td_pcb->pcb_onfault);
 			td->td_pcb->pcb_onfault = NULL;
@@ -1156,6 +1191,15 @@ trap(struct trapframe *trapframe)
 		if (KTRPOINT(td, KTR_CEXCEPTION))
 			ktrcexception(trapframe);
 #endif
+
+		if (try_emulate_capdirty(trapframe, NULL,
+					 &p->p_vmspace->vm_pmap) == 0) {
+			if (!usermode) {
+				return (trapframe->pc);
+			}
+			goto out;
+		}
+
 		fetch_bad_instr(trapframe);
 		log_c2e_exception(msg, trapframe, type);
 		i = SIGPROT;
diff --git a/sys/mips/mips/vm_machdep.c b/sys/mips/mips/vm_machdep.c
index 18259feae769..637cd46cd286 100644
--- a/sys/mips/mips/vm_machdep.c
+++ b/sys/mips/mips/vm_machdep.c
@@ -60,6 +60,7 @@ __FBSDID("$FreeBSD$");
 #include <sys/unistd.h>
 #include <sys/vmem.h>
 
+#include <machine/_inttypes.h>
 #include <machine/abi.h>
 #include <machine/cache.h>
 #include <machine/clock.h>
@@ -87,6 +88,7 @@ __FBSDID("$FreeBSD$");
 #include <vm/uma.h>
 #include <vm/uma_int.h>
 
+#include <sys/stdatomic.h>
 #include <sys/user.h>
 #include <sys/mbuf.h>
 
diff --git a/sys/mips/mips/vm_machdep_caprevoke.c b/sys/mips/mips/vm_machdep_caprevoke.c
new file mode 100644
index 000000000000..a4e1e0c20616
--- /dev/null
+++ b/sys/mips/mips/vm_machdep_caprevoke.c
@@ -0,0 +1,540 @@
+/*-
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2019 Nathaniel Filardo
+ *
+ * This software was developed by SRI International and the University of
+ * Cambridge Computer Laboratory (Department of Computer Science and
+ * Technology) under DARPA contract HR0011-18-C-0016 ("ECATS"), as part of the
+ * DARPA SSITH research programme.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#include <sys/param.h>
+#include <sys/systm.h>
+#include <sys/kernel.h>
+#include <sys/unistd.h>
+#include <sys/proc.h>
+#include <sys/caprevoke.h>
+
+#include <machine/_inttypes.h>
+#include <cheri/cheri.h>
+#include <cheri/cheric.h>
+#include <machine/pcb.h>
+
+#include <vm/vm.h>
+#include <vm/vm_extern.h>
+#include <vm/pmap.h>
+#include <vm/vm_kern.h>
+#include <vm/vm_map.h>
+#include <vm/vm_object.h>
+#include <vm/vm_page.h>
+#include <vm/vm_param.h>
+#include <vm/vm_caprevoke.h>
+
+/*
+ * Here's a wildly dangerous thing to do: we know the shadow is inside a
+ * completely valid map... so even if this faults, the usual ZFOD handling
+ * will kick in.
+ *
+ * We can therefore install this somewhat dubious function as the fault
+ * handler before we sweep a page, which we do physically, so that we can
+ * access the virtual pages of the shadow bitmap.  YIKES!
+ *
+ * Why do this?  Because it beats installing and uninstalling the
+ * ->pcb_onfault for every capability we find in the page.
+ *
+ * Why only for each page?  Because a large amount of kernel code runs
+ * between each page scanned and while, in principle, none of that should be
+ * accessing user maps... I would much rather a performance hit than
+ * accidentally leave an onfault handler registered when we went back to
+ * userland!
+ */
+static void
+vm_caprevoke_tlb_fault(void)
+{
+	panic(__FUNCTION__);
+}
+
+
+/*
+ * The Capability Under Test Pointer needs to be a capability because we
+ * don't have a LLC instruction, just a CLLC one.
+ */
+static int
+vm_do_caprevoke(int *res,
+		const struct vm_caprevoke_cookie *crc,
+		const uint8_t * __capability crshadow,
+		vm_caprevoke_test_fn ctp,
+		void * __capability * __capability cutp,
+		void * __capability cut)
+{
+	int perms = cheri_getperm(cut);
+	CAPREVOKE_STATS_FOR(crst, crc);
+
+	if (perms == 0) {
+		/* For revoked or permissionless caps, do nothing. */
+
+		/*
+		 * XXX technically, a sealed permissionless thing is a
+		 * bearer token, but that's not really something we use.  We
+		 * should probably insist that people don't; keep one sw bit
+		 * set or something.
+		 */
+
+		CAPREVOKE_STATS_BUMP(crst, caps_found_revoked);
+	} else if (cheri_gettag(cut) && ctp(crshadow, cut, perms)) {
+		void * __capability cscratch;
+		int ok;
+
+		void * __capability cutr = cheri_revoke(cut);
+
+		CAPREVOKE_STATS_BUMP(crst, caps_found);
+
+		/*
+		 * Load-link the position under test; verify that it matches
+		 * our previous load; store conditionally the revoked
+		 * version back.  If the verification fails, don't try
+		 * anything fancy, just modify the return value to flag the
+		 * page as dirty.
+		 *
+		 * It's possible that this CAS will fail because the pointer
+		 * has changed during our test.  That's fine, if this is not
+		 * a stop-the-world scan; we'll catch it in the next go
+		 * around.  However, because CAS can fail for reasons other
+		 * than an actual data failure, return an indicator that the
+		 * page should not be considered clean.
+		 *
+		 * Because revoked capabilities are still tagged, one might
+		 * worry that this would reset the capdirty bits.  That's
+		 * not true, tho', because we're storing via the direct
+		 * mapping of physical memory.
+		 */
+		__asm__ __volatile__ (
+			"cllc %[cscratch], %[cutp]\n\t"
+			"cexeq %[ok], %[cscratch], %[cut]\n\t"
+			"beqz %[ok], 1f\n\t"
+			"nop\n\t"
+			"cscc %[ok], %[cutr], %[cutp]\n\t"
+			"1:\n\t"
+		  : [ok] "=r" (ok), [cscratch] "=&C" (cscratch)
+		  : [cut] "C" (cut), [cutp] "C" (cutp), [cutr] "C" (cutr)
+		  : "memory");
+
+		if (__builtin_expect(ok,1)) {
+			CAPREVOKE_STATS_BUMP(crst, caps_cleared);
+			/* Don't count a revoked cap as HASCAPS */
+		} else {
+			*res |= VM_CAPREVOKE_PAGE_DIRTY
+				| VM_CAPREVOKE_PAGE_HASCAPS ;
+		}
+	} else {
+		CAPREVOKE_STATS_BUMP(crst, caps_found);
+
+		/*
+		 * Even though it might actually be un-tagged, that's a very
+		 * narrow race and this a very common case, so don't bother
+		 * testing.  We'll find it clear next time, maybe.
+		 */
+		*res |= VM_CAPREVOKE_PAGE_HASCAPS;
+	}
+
+	return 0;
+}
+
+#ifdef CHERI_CAPREVOKE_CLOADTAGS
+uint8_t cloadtags_stride;
+SYSCTL_U8(_vm, OID_AUTO, cloadtags_stride, 0, &cloadtags_stride, 0, "XXX");
+
+static void
+measure_cloadtags_stride(void *ignored)
+{
+	(void)ignored;
+
+	void * __capability buf[64] __attribute__((aligned(PAGE_SIZE)));
+	int i;
+	
+	/* Fill with capabilities */
+	for (i = 0; i < 64; i++) {
+	        buf[i] = cheri_getkdc();
+	}
+
+	uint64_t tags = __builtin_cheri_cap_load_tags(buf);
+	switch(tags) {
+	case 0x0001:  cloadtags_stride = 1;  break;
+	case 0x0003:  cloadtags_stride = 2;  break;
+	case 0x000F:  cloadtags_stride = 4;  break;
+	case 0x00FF:  cloadtags_stride = 8;  break;
+	case 0xFFFF:  cloadtags_stride = 16; break;
+	default:
+		panic("Bad cloadtags result 0x%" PRIx64, tags);
+	}
+}
+SYSINIT(cloadtags_stride, SI_SUB_VM, SI_ORDER_ANY,
+        measure_cloadtags_stride, NULL);
+#endif
+
+#define CPREFETCH(c) \
+	__asm__ __volatile__ ("pref 4, 0(%[addr])\n\t" \
+		: /* no out */ \
+		: [addr] "r" (cheri_getaddress(c)) \
+		: /* no clobber */)
+
+
+static inline int
+vm_caprevoke_page_iter(const struct vm_caprevoke_cookie *crc,
+		       int (*cb)(int *, const struct vm_caprevoke_cookie *,
+				 const uint8_t * __capability,
+				 vm_caprevoke_test_fn,
+				 void * __capability * __capability,
+				 void * __capability),
+		       void * __capability * __capability mvu,
+		       vm_offset_t mve)
+{
+	CAPREVOKE_STATS_FOR(crst, crc);
+
+	int res = 0;
+	uint64_t tags, nexttags;
+
+	CPREFETCH(mvu);
+
+	/* Load once up front, which is almost as good as const */
+	uint8_t _cloadtags_stride = cloadtags_stride;
+	vm_caprevoke_test_fn ctp = crc->caprevoke_test_int;
+	const uint8_t * __capability crshadow = crc->crshadow;
+
+	mve -= _cloadtags_stride * sizeof(void * __capability);
+
+	curthread->td_pcb->pcb_onfault = vm_caprevoke_tlb_fault;
+
+#ifdef CHERI_CAPREVOKE_CLOADTAGS
+	tags = __builtin_cheri_cap_load_tags(mvu);
+
+#ifdef CHERI_CAPREVOKE_STATS
+	if (tags) {
+		CAPREVOKE_STATS_BUMP(crst, lines_scan);
+	}
+#endif
+
+	for( ; cheri_getaddress(mvu) < mve; mvu += _cloadtags_stride ) {
+		void * __capability * __capability mvt = mvu;
+
+		nexttags = __builtin_cheri_cap_load_tags(mvu + _cloadtags_stride);
+		if (nexttags != 0) {
+			CPREFETCH(mvu + _cloadtags_stride);
+			CAPREVOKE_STATS_BUMP(crst, lines_scan);
+		}
+
+		for(; tags != 0; (tags >>= 1), mvt += 1) {
+			if (!(tags & 1))
+				continue;
+
+			if (cb(&res, crc, crshadow, ctp, mvt, *mvt))
+				goto out;
+		}
+
+		tags = nexttags;
+	}
+
+	/* And the last line */
+	{
+		void * __capability * __capability mvt = mvu;
+		for(; tags != 0; (tags >>= 1), mvt += 1) {
+			if (!(tags & 1))
+				continue;
+
+			if (cb(&res, crc, crshadow, ctp, mvt, *mvt))
+				goto out;
+		}
+	}
+#else
+	for( ; cheri_getaddress(mvu) < mve; mvu += 8) {
+#ifdef CHERI_CAPREVOKE_STATS
+		int seentag = 0;
+#endif
+		for (int i = 0; i < 8; i++) {
+			void * __capability cut = *mvu;
+			if (cheri_gettag(cut)) {
+#ifdef CHERI_CAPREVOKE_STATS
+				seentag++;
+#endif
+				if (cb(&res, crc, crshadow, ctp, mvt, *mvt))
+					goto out;
+			}
+		}
+#ifdef CHERI_CAPREVOKE_STATS
+		if (seentag) {
+			CAPREVOKE_STATS_BUMP(crst, lines_scan);
+		}
+#endif
+	}
+#endif
+
+out:
+	curthread->td_pcb->pcb_onfault = NULL;
+	return res;
+}
+
+int
+vm_caprevoke_test(const struct vm_caprevoke_cookie *crc,
+		      const void * __capability cut)
+{
+	if (cheri_gettag(cut)) {
+		int res;
+		curthread->td_pcb->pcb_onfault = vm_caprevoke_tlb_fault;
+		res = crc->caprevoke_test_int(crc->crshadow, cut, cheri_getperm(cut));
+		curthread->td_pcb->pcb_onfault = NULL;
+		return res;
+	}
+
+	return 0;
+}
+
+int
+vm_caprevoke_page(const struct vm_caprevoke_cookie *crc, vm_page_t m)
+{
+#ifdef CHERI_CAPREVOKE_STATS
+	CAPREVOKE_STATS_FOR(crst, crc);
+	uint32_t cyc_start = cheri_get_cyclecount();
+#endif
+
+	vm_paddr_t mpa = VM_PAGE_TO_PHYS(m);
+	vm_offset_t mva;
+	vm_offset_t mve;
+	void * __capability * __capability mvu;
+	/* XXX NWF Is this what we want? */
+	void * __capability kdc = cheri_getkdc();
+	int res = 0;
+
+	/*
+	 * XXX NWF
+	 * Hopefully m being xbusy'd means it's not about to go away on us.
+	 * I don't yet understand all the interlocks in the vm subsystem.
+	 */
+	KASSERT(MIPS_DIRECT_MAPPABLE(mpa),
+		("Revoke not directly map swept page?"));
+	mva = MIPS_PHYS_TO_DIRECT(mpa);
+	mve = mva + pagesizes[m->psind];
+
+	mvu = cheri_csetbounds(cheri_setaddress(kdc, mva), pagesizes[m->psind]);
+
+	res = vm_caprevoke_page_iter(crc, vm_do_caprevoke, mvu, mve);
+
+#ifdef CHERI_CAPREVOKE_STATS
+	uint32_t cyc_end = cheri_get_cyclecount();
+	CAPREVOKE_STATS_INC(crst, page_scan_cycles, cyc_end - cyc_start);
+#endif
+
+	return res;
+}
+
+static inline int
+vm_caprevoke_page_ro_adapt(int *res,
+			   const struct vm_caprevoke_cookie *vmcrc,
+		           const uint8_t * __capability crshadow,
+			   vm_caprevoke_test_fn ctp,
+			   void * __capability * __capability cutp,
+			   void * __capability cut)
+{
+	(void)cutp;
+
+	/*
+	 * Being untagged would imply mutation, but we're visiting this page
+	 * under the assumption that it's read-only.
+	 */
+	KASSERT(cheri_gettag(cut), ("vm_caprevoke_page_ro_adapt untagged"));
+
+	/* If the thing has no permissions, we don't need to scan it later */
+	if (cheri_getperm(cut) == 0)
+		return 0;
+
+	*res |= VM_CAPREVOKE_PAGE_HASCAPS;
+
+	if (ctp(crshadow, cut, cheri_getperm(cut))) {
+		*res |= VM_CAPREVOKE_PAGE_DIRTY;
+
+		/* One dirty answer is as good as any other; stop eary */
+		return 1;
+	}
+
+	return 0;
+}
+
+/*
+ * Like vm_caprevoke_page, but does not write to the page in question
+ *
+ * VM_CAPREVOKE_PAGE_DIRTY in the result means that we would like to store
+ * back, but can't, rather than that we lost a LL/SC race.  We will return
+ * early if this becomes set: there's no reason to continue probing once we
+ * know the answer.
+ *
+ * VM_CAPREVOKE_PAGE_HASCAPS continues to mean what it meant before: we
+ * saw at least one, permission-bearing capability on this page.
+ */
+int
+vm_caprevoke_page_ro(const struct vm_caprevoke_cookie *crc, vm_page_t m)
+{
+#ifdef CHERI_CAPREVOKE_STATS
+	uint32_t cyc_start = cheri_get_cyclecount();
+	CAPREVOKE_STATS_FOR(crst, crc);
+#endif
+
+	vm_paddr_t mpa = VM_PAGE_TO_PHYS(m);
+	vm_offset_t mva;
+	vm_offset_t mve;
+	void * __capability * __capability mvu;
+	void * __capability kdc = cheri_getkdc();
+	int res = 0;
+
+	KASSERT(MIPS_DIRECT_MAPPABLE(mpa),
+		("Revoke not directly map swept page?"));
+	mva = MIPS_PHYS_TO_DIRECT(mpa);
+	mve = mva + pagesizes[m->psind];
+
+	mvu = cheri_csetbounds(cheri_setaddress(kdc, mva), pagesizes[m->psind]);
+
+	res = vm_caprevoke_page_iter(crc, vm_caprevoke_page_ro_adapt, mvu, mve);
+
+#ifdef CHERI_CAPREVOKE_STATS
+	uint32_t cyc_end = cheri_get_cyclecount();
+	crst->page_scan_cycles += cyc_end - cyc_start;
+#endif
+
+	return res;
+}
+
+/*
+ * Map a capability revocation shadow
+ */
+int
+vm_map_install_caprevoke_shadow(vm_map_t map)
+{
+	int error = KERN_SUCCESS;
+	vm_object_t vmo;
+	vm_offset_t start = VM_CAPREVOKE_BM_BASE;
+	vm_offset_t end = VM_CAPREVOKE_BM_TOP;
+
+	vmo = vm_object_allocate(OBJT_DEFAULT, end - start);
+	vmo->flags |= OBJ_NOLOADTAGS | OBJ_NOSTORETAGS;
+
+	vm_map_lock(map);
+
+	if (map->vm_caprev_sh != NULL) {
+		error = KERN_PROTECTION_FAILURE;
+		goto out;
+	}
+
+	error = vm_map_insert(map, vmo, 0, start, end,
+				VM_PROT_READ | VM_PROT_WRITE,
+				VM_PROT_READ | VM_PROT_WRITE,
+				0);
+
+	if (error != KERN_SUCCESS) {
+		goto out;
+	}
+
+	map->vm_caprev_sh = vmo;
+	map->vm_caprev_shva = start;
+
+out:
+	vm_map_unlock(map);
+
+	if (error) {
+		vm_object_deallocate(vmo);
+	}
+	return error;
+}
+
+#define ERRNO_CAP(v) ((void * __capability)(__intptr_t)(v))
+
+/*
+ * Grant access to a capability shadow
+ */
+void * __capability
+vm_caprevoke_shadow_cap(int sel, vm_offset_t base, vm_offset_t size, int pmask)
+{
+	switch(sel) {
+	/* Accessible to userspace */
+	case CAPREVOKE_SHADOW_NOVMMAP: {
+		vm_offset_t shadow_base, shadow_size;
+
+		/* Require at least byte granularity in the shadow space */
+		if ((base & ((VM_CAPREVOKE_GSZ_MEM_NOMAP * 8) - 1)) != 0)
+			return ERRNO_CAP(EINVAL);
+		if ((size & ((VM_CAPREVOKE_GSZ_MEM_NOMAP * 8) - 1)) != 0)
+			return ERRNO_CAP(EINVAL);
+
+		shadow_base = VM_CAPREVOKE_BM_MEM_NOMAP
+		            + (base / VM_CAPREVOKE_GSZ_MEM_NOMAP / 8);
+		shadow_size = size / VM_CAPREVOKE_GSZ_MEM_NOMAP / 8;
+
+		return cheri_capability_build_user_data(
+		    (pmask & (CHERI_PERM_LOAD | CHERI_PERM_STORE)) |
+			CHERI_PERM_GLOBAL,
+		    shadow_base, shadow_size, 0);
+	}	
+	case CAPREVOKE_SHADOW_OTYPE: {
+		vm_offset_t shadow_base, shadow_size;
+
+		shadow_base = VM_CAPREVOKE_BM_OTYPE
+		            + (base / VM_CAPREVOKE_GSZ_OTYPE / 8);
+		shadow_size = size / VM_CAPREVOKE_GSZ_OTYPE / 8;
+
+		/* Require at least byte granularity in the shadow space */
+		if ((base & ((VM_CAPREVOKE_GSZ_OTYPE * 8) - 1)) != 0)
+			return ERRNO_CAP(EINVAL);
+		if ((size & ((VM_CAPREVOKE_GSZ_OTYPE * 8) - 1)) != 0)
+			return ERRNO_CAP(EINVAL);
+
+		return cheri_capability_build_user_data(
+			CHERI_PERM_LOAD | CHERI_PERM_STORE | CHERI_PERM_GLOBAL,
+			shadow_base, shadow_size, 0);
+	}
+	case CAPREVOKE_SHADOW_INFO_STRUCT: {
+		return cheri_capability_build_user_data(
+			CHERI_PERM_LOAD
+			| CHERI_PERM_LOAD_CAP
+			| CHERI_PERM_GLOBAL,
+			VM_CAPREVOKE_INFO_PAGE,
+			sizeof(struct caprevoke_info),
+			0);
+	}
+	/* Kernel-only */
+	// XXX CAPREVOKE_SHADOW_MAP:
+	//
+	default:
+		return ERRNO_CAP(EINVAL);
+	}
+}
+
+void
+vm_caprevoke_publish(const struct vm_caprevoke_cookie *vmcrc,
+			 const struct caprevoke_info *ip)
+{
+	int res = copyout_c(ip, &vmcrc->info_page->pub, sizeof(*ip));
+	KASSERT(res == 0, ("vm_caprevoke_publish: bad copyout %d\n", res));
+	(void)res;
+}
diff --git a/sys/mips/mips/vm_machdep_caprevoke_tests.c b/sys/mips/mips/vm_machdep_caprevoke_tests.c
new file mode 100644
index 000000000000..1d1d33e69525
--- /dev/null
+++ b/sys/mips/mips/vm_machdep_caprevoke_tests.c
@@ -0,0 +1,166 @@
+/*-
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2019 Nathaniel Filardo
+ *
+ * This software was developed by SRI International and the University of
+ * Cambridge Computer Laboratory (Department of Computer Science and
+ * Technology) under DARPA contract HR0011-18-C-0016 ("ECATS"), as part of the
+ * DARPA SSITH research programme.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#include <sys/param.h>
+#include <sys/systm.h>
+
+#include <machine/_inttypes.h>
+#include <cheri/cheri.h>
+#include <cheri/cheric.h>
+
+#include <vm/vm.h>
+#include <vm/vm_param.h>
+#include <vm/vm_caprevoke.h>
+
+/* Check the coarse-grained MAP bitmap */
+static inline unsigned long
+vm_caprevoke_test_mem_map(const uint8_t * __capability crshadow,
+			  const void * __capability cut)
+{
+	uint8_t bmbits;
+	const uint8_t * __capability bmloc;
+
+	vaddr_t va = cheri_getbase(cut);
+
+	bmloc = crshadow
+		+ (VM_CAPREVOKE_BM_MEM_MAP - VM_CAPREVOKE_BM_BASE)
+		+ (va / VM_CAPREVOKE_GSZ_MEM_MAP / 8);
+
+	/*
+	 * Load it (see the comments on vm_caprevoke_tlb_fault above
+	 * before *you* panic, dear reader).
+	 */
+
+	bmbits = *bmloc;
+
+	/* Fast path: often these are all zeros */
+
+	if (bmbits == 0) {
+		return 0;
+	}
+
+	return bmbits & (1 << ((va / VM_CAPREVOKE_GSZ_MEM_MAP) % 8));
+}
+
+/* Check the fine-grained NOMAP bitmap */
+static inline unsigned long
+vm_caprevoke_test_mem_nomap(const uint8_t * __capability crshadow,
+			    const void * __capability cut)
+{
+	uint8_t bmbits;
+	const uint8_t * __capability bmloc;
+
+	vaddr_t va = cheri_getbase(cut);
+
+	bmloc = crshadow
+		+ (VM_CAPREVOKE_BM_MEM_NOMAP - VM_CAPREVOKE_BM_BASE)
+		+ (va / VM_CAPREVOKE_GSZ_MEM_NOMAP / 8);
+
+	bmbits = *bmloc;
+
+	if (bmbits == 0) {
+		return 0;
+	}
+
+	return bmbits & (1 << ((va / VM_CAPREVOKE_GSZ_MEM_NOMAP) % 8));
+}
+
+// TODO: if ((perms & CHERI_PERMS_HWALL_OTYPE) != 0)
+// TODO: if ((perms & CHERI_PERMS_HWALL_CID) != 0)
+
+static unsigned long
+vm_caprevoke_test_just_mem(const uint8_t * __capability crshadow,
+		      const void * __capability cut, unsigned long perms)
+{
+	if ((perms & (CHERI_PERMS_HWALL_MEMORY
+		     | CHERI_PERM_CHERIABI_VMMAP)) != 0) {
+		if (vm_caprevoke_test_mem_map(crshadow, cut))
+			return 1;
+
+		if ((perms & CHERI_PERM_CHERIABI_VMMAP) == 0) {
+			return vm_caprevoke_test_mem_nomap(crshadow, cut);
+		}
+	}
+	return 0;
+}
+
+static unsigned long
+vm_caprevoke_test_just_mem_fine(const uint8_t * __capability crshadow,
+		      const void * __capability cut, unsigned long perms)
+{
+	/*
+	 * Most capabilities are memory capabilities, most are unrevoked,
+	 * and comparatively few are VMMAP-bearing.... so do the load
+	 * first and only then do the permissions checks.
+	 */
+
+	if (vm_caprevoke_test_mem_nomap(crshadow, cut)) {
+		if (__builtin_expect(perms & CHERI_PERM_CHERIABI_VMMAP,0)) {
+			return 0;
+		}
+
+		return (perms & CHERI_PERMS_HWALL_MEMORY) != 0;
+	}
+
+	return 0;
+}
+
+/*
+ *
+ */
+void
+vm_caprevoke_set_test(struct vm_caprevoke_cookie *crc, int flags)
+{
+	switch(flags) {
+	case VM_CAPREVOKE_CF_NO_COARSE_MEM
+		| VM_CAPREVOKE_CF_NO_OTYPES
+		| VM_CAPREVOKE_CF_NO_CIDS :
+
+		crc->caprevoke_test_int = vm_caprevoke_test_just_mem_fine;
+		break;
+
+	case VM_CAPREVOKE_CF_NO_OTYPES
+		| VM_CAPREVOKE_CF_NO_CIDS :
+
+		crc->caprevoke_test_int = vm_caprevoke_test_just_mem;
+		break;
+
+	default:
+		panic("Bad caprevoke cookie flags 0x%x\n", flags);
+	}
+}
+
+
diff --git a/sys/sys/caprevoke.h b/sys/sys/caprevoke.h
new file mode 100644
index 000000000000..5d97a4a2776a
--- /dev/null
+++ b/sys/sys/caprevoke.h
@@ -0,0 +1,342 @@
+/*-
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2018 SRI International
+ * All rights reserved.
+ *
+ * This software was developed by SRI International and the University of
+ * Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
+ * ("CTSRD"), as part of the DARPA CRASH research programme.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef __SYS_CAPREVOKE_H__
+#define	__SYS_CAPREVOKE_H__
+
+/*
+ * The outermost capability revocation state machine.
+ *
+ *   We begin with no revocation in progress (CAPREVST_NONE).  Userland can
+ *   request that we steal the calling thread to carry out an initial pass,
+ *   which will begin the next epoch and visit all cap-dirty pages in the
+ *   address space, moving us to CAPREVST_INIT_PASS for the duration and to
+ *   CAPREVST_INIT_DONE upon completion, before returning to userland.
+ *
+ *   We are now in the store-side steady state for this epoch: we need only
+ *   look at *recently* capdirty pages, kernel hoarders, and register files
+ *   to find should-be-revoked pages.  Userland can request additional
+ *   passes, which will be *incremental* passes, visiting only capdirty
+ *   pages (and keeping us in CAPREVST_STORE_DONE).
+ *
+ *   Alternatively, userland can request that we finish this epoch,
+ *   transitioning us into CAPREVST_LAST_PASS for the duration.  This pass
+ *   visits all recently capdirty pages, kernel hoarders, and thread
+ *   register files.  It implies at least some brief window of
+ *   thread_single'd life.  When this pass finishes, it again increments
+ *   the epoch counter, signaling the end of this epoch.
+ *
+ *     XXX The thread_single window can be reduced by using the "load-side"
+ *     strategy, in which we temporarily remove read access to all
+ *     recently-capdirty pages and then un-thread_single.  We would continue
+ *     to use the calling thread to sweep pages "in the background", but would
+ *     also clean pages when taking vm faults.  The epoch must not end
+ *     before all pages have been cleaned!
+ *
+ *   Userland might cause us to jump directly from CAPREVST_NONE to
+ *   CAPREVST_LAST_PASS.  This case is *almost* like the above, except that
+ *   we have to consider *all* capdirty pages, not just recently-capdirty.
+ *
+ * The state and epoch counter are stored in the same per-process word,
+ * vm_caprev_st.  There is, at present, at most one thread actively engaged
+ * in revocation per process.
+ */
+
+enum caprevoke_state {
+	CAPREVST_NONE      = 0,	/* No revocation is in progress */
+	CAPREVST_INIT_PASS = 1,	/* Currently executing a "store-side" pass */
+	CAPREVST_INIT_DONE = 2,	/* > 0 store-sides done, no pass running */
+	CAPREVST_LAST_PASS = 3,	/* Last, "load-side"/STW pass running */
+};
+
+#define CAPREVST_ST_MASK	0x3
+#define CAPREVST_EPOCH_SHIFT	2
+#define CAPREVST_EPOCH_WIDTH	62
+
+typedef uint64_t caprevoke_epoch;
+
+/*
+ * Epoch greater than orderings: a > b, a >= b.
+ *
+ * We use RFC1982 serial number arithmetic to deal with wrap-around.  We
+ * assume that there will never be any reason to ask about epochs so far
+ * apart that this is problematic.
+ *
+ * We could probably get away without wraparound handling, given the current
+ * value of CAPREVST_EPOCH_WIDTH, but on the chance that it becomes
+ * significantly shorter, it doesn't hurt to have this abstracted.
+ *
+ * XXX this almost surely belongs somewhere else.
+ */
+
+static inline int caprevoke_epoch_gt(caprevoke_epoch a, caprevoke_epoch b) {
+	return ((a < b) && ((b - a) > (1ULL << (CAPREVST_EPOCH_WIDTH-1))))
+	    || ((a > b) && ((a - b) < (1ULL << (CAPREVST_EPOCH_WIDTH-1))));
+}
+static inline int caprevoke_epoch_ge(caprevoke_epoch a, caprevoke_epoch b) {
+	return (a == b) || caprevoke_epoch_gt(a, b);
+}
+
+static inline int caprevoke_epoch_clears(caprevoke_epoch now,
+                                         caprevoke_epoch then) {
+	return caprevoke_epoch_ge(now, then + (then & 1) + 2);
+}
+
+	/*
+	 * Finish the current revocation epoch this pass.
+	 * If there is no current revocation epoch, start one and then
+	 * finish it.
+	 *
+	 * If this flag is not given, then either start an epoch by doing
+	 * the first (full) pass or continue an epoch by doing an
+	 * incremental pass.
+	 */
+#define CAPREVOKE_LAST_PASS	0x001
+
+	/*
+	 * If this bit is set, the kernel is free to return without making
+	 * progress.
+	 *
+	 * The returned statistics describe any transitions that take place
+	 * as a result of this request, but not any that result due to
+	 * backgrounded work.
+	 *
+	 * If set without CAPREVOKE_IGNORE_START, the kernel may treat this
+	 * as a hint that background revocation may be useful (XXX but we
+	 * don't implement that yet).
+	 *
+	 */
+#define	CAPREVOKE_NO_WAIT_OK	0x002
+
+	/*
+	 * Ignore the given epoch argument and always attempt to advance the
+	 * epoch clock relative to its value "at the time of the call".
+	 */
+#define CAPREVOKE_IGNORE_START	0x004
+
+	/*
+	 * Do a pass only if an epoch is open after synchronization.  This
+	 * is most useful when we want to get to the end of an epoch as
+	 * quickly as possible; if we're already past the end, then we
+	 * should just stay there.
+	 */
+#define CAPREVOKE_ONLY_IF_OPEN	0x008
+
+	/*
+	 * Ordinarily, caprevoke with CAPREVOKE_LAST_PASS attempts to
+	 * minimize the amount of work it does with the world held in
+	 * single-threaded state.  It will do up to three passes:
+	 *
+	 *   * an opening/incremental pass with the world running
+	 *
+	 *   * a pass with the world stopped, which visits kernel hoarders
+	 *     and recently-dirty pages (since the above pass)
+	 *
+	 *   * another pass with the world resumed, again visiting
+	 *     recently-dirty pages.  (XXX Not yet!)
+	 *
+	 * The first and/or last of these may be disabled by passing
+	 * CAPREVOKE_LAST_NO_EARLY and/or CAPREVOKE_LAST_NO_LATE flags,
+	 * causing more work to be pushed into the world-stopped phase.
+	 *
+	 * Setting CAPREVOKE_LAST_NO_EARLY when not setting
+	 * CAPREVOKE_LAST_PASS will cause no passes to be performed.
+	 *
+	 * XXX CAPREVOKE_LAST_NO_LATE is currently implied because our VM
+	 * does not actually take advantage of the split.  This is
+	 * post-ASPLOS work at the earliest.
+	 */
+#define CAPREVOKE_LAST_NO_EARLY	0x010
+#define CAPREVOKE_LAST_NO_LATE	0x020
+
+	/*
+	 * Force a synchronization with the PMAP before doing a non-LAST
+	 * pass (including the EARLY part of a LAST call).  This should let
+	 * us measure the impact of lazily synchronizing with the PMAP
+	 * capdirty bits.
+	 *
+	 * This may also be useful if one were to do intermediate (i.e.,
+	 * neither opening nor closing) passes, but at present we do not.
+	 *
+	 * Meaningless if CAPREVOKE_LAST_NO_EARLY also set.
+	 */
+#define CAPREVOKE_EARLY_SYNC	0x040
+
+	/*
+	 * Some flags indicate that we are to engage in a blocking
+	 * capability revocation sweep on a subset of the entire address
+	 * space.  If any of these are set, we bypass the above state
+	 * machine and visit only the indicated locations.  This is an
+	 * expermental feature to see if this kind of mitigation, while
+	 * unsound, is still a useful thing to do.
+	 *
+	 */
+/* CAPREVOKE_JUST_THE_TIME was 0x100; it is removed for being unsafe */
+#define CAPREVOKE_JUST_MY_REGS  0x200	/* Calling thread register file */
+#define CAPREVOKE_JUST_MY_STACK	0x400	/* Calling thread stack */
+#define CAPREVOKE_JUST_HOARDERS 0x800	/* Kernel hoarders */
+#define CAPREVOKE_JUST_MASK	0xF00
+
+	/*
+	 * XXX In a colocated proc model, just the current proc?  Is this a
+	 * thing we want?  If so, how do we make it fit with our story?
+	 * Does it not alter the epoch clock?  Is there a second clock?
+	 */
+// #define CAPREVOKE_COLO_JUST_ME		0x1000
+
+/*
+ * Information conveyed to userland about a given caprevoke scan.
+ */
+struct caprevoke_stats {
+
+		/*
+		 * The synchronized time at the start of the call.  This
+		 * value is useful for *enqueueing* objects to quarantine:
+		 * all bitmap writes prior to the system call certainly
+		 * happened in or before epoch_init, and so waiting for the
+		 * epoch to advance sufficiently far relative to epoch_init
+		 * will ensure that those objects have been revoked.
+		 */
+	caprevoke_epoch	epoch_init;
+
+		/*
+		 * The synchronized time at the end of the call.  This value
+		 * is useful for *dequeueing* objects from quarantine: if
+		 * this value clears the recorded epoch_init, then those
+		 * objects have been revoked.
+		 *
+		 * It may be the case that epoch_fini < epoch_init.  This
+		 * implies that an epoch transition is in progress but that
+		 * the requested "start_epoch" given to caprevoke() has been
+		 * cleared by the reported value of epoch_fini, and so there
+		 * is no reason to wait for the transition to finish.
+		 */
+	caprevoke_epoch	epoch_fini;
+
+		/*
+		 * The remainder of the fields of this structure are purely
+		 * informative; they may be of slight interest to policies,
+		 * but shouldn't influence correctness.
+		 */
+
+	uint64_t	page_scan_cycles;
+
+	uint32_t	pages_retried;
+	uint32_t	pages_scan_ro;
+	uint32_t	pages_scan_rw;
+
+	uint32_t	pages_faulted_ro;
+	uint32_t	pages_faulted_rw;
+
+	uint32_t	pages_skip_fast;
+	uint32_t	pages_skip;
+
+	uint32_t	caps_found;
+	uint32_t	caps_found_revoked;
+
+	uint32_t	caps_cleared;
+
+	uint32_t	lines_scan;
+	uint32_t	pages_mark_clean;
+
+	uint32_t	__spare[2];
+};
+
+struct caprevoke_info {
+	caprevoke_epoch epoch_enqueue;	/* Label on entry to quarantine */
+	caprevoke_epoch epoch_dequeue;	/* Gates removal from quarantine */
+};
+
+/* Returns 1 if cap is revoked, 0 otherwise. */
+static inline int caprevoke_is_revoked(void * __capability cap) {
+	return (__builtin_cheri_perms_get(cap) == 0);
+}
+
+#ifdef _KERNEL
+struct caprevoke_info_page {
+		/* Userland will come to hold RO caps to this bit */
+	struct caprevoke_info pub;
+
+		/*
+		 * The kernel is free to use the rest of this page for
+		 * private data that is quite naturally associated with
+		 * this VM space.
+		 */
+};
+#endif
+
+#define	CAPREVOKE_SHADOW_NOVMMAP	0x00	/* The ordinary shadow space */
+#define CAPREVOKE_SHADOW_OTYPE		0x01	/* The otype shadow space */
+/*
+ * It is not possible to ask for the _MEM_MAP bitmask, as we intend that one
+ * to be used by the kernel internally for munmap().  Maybe that's wrong?
+ *
+ * XXX Do we want a madvise mode to allow userspace to request revocation
+ * of vm objects that we aren't deleting?  They *can* use the NOVMMAP
+ * bitmask, but it's 256 times as many bits to flip.
+ */
+#define CAPREVOKE_SHADOW_INFO_STRUCT	0x03	/* R/O access to shared state */
+#define CAPREVOKE_SHADOW_SPACE_MASK	0x03	/* Flag bits for shadow index */
+
+#ifndef _KERNEL
+
+	/*
+	 * Drive the revocation state machine.
+	 *
+	 * If the current epoch clock is sufficient to caprvoke_epoch_clears
+	 * start_epoch, this call returns immediately, populating
+	 * statout->epoch_{init,fini} with the current clock's value.
+	 *
+	 * XXX if caprevoke_epoch becomes more complex than a scalar type,
+	 * this prototype will need to change or we'll need to be more
+	 * explicit about it being a hint or something.
+	 */
+int caprevoke(int flags, caprevoke_epoch start_epoch,
+		struct caprevoke_stats *statout);
+
+	/*
+	 * Request a capability to the shadow bitmap state for the given
+	 * arena.  Flags determine which space is requested; the arena cap
+	 * must have appropriate privileges.
+	 *
+	 * This call must fail if the resulting capability would not be
+	 * representable due to alignment constraints.
+	 */
+int caprevoke_shadow(int flags,
+	void * __capability arena,
+	void * __capability * shadow);
+
+/* Set *shadow to a capability granting access to the entire shadow space. */
+int caprevoke_entire_shadow_cap(void * __capability *shadow);
+#endif
+
+#endif /* !__SYS_CAPREVOKE_H__ */
diff --git a/sys/sys/mman.h b/sys/sys/mman.h
index ccda37212bfa..e0a4051e02c5 100644
--- a/sys/sys/mman.h
+++ b/sys/sys/mman.h
@@ -197,14 +197,18 @@
 #define	MINCORE_REFERENCED_OTHER 0x8 /* Page has been referenced */
 #define	MINCORE_MODIFIED_OTHER	0x10 /* Page has been modified */
 #define	MINCORE_SUPER		0x20 /* Page is a "super" page */
+#if __has_feature(capabilities)
+#define MINCORE_MAYHAVECAP	0x40 /* Page may contain capabilities */
+#endif
 
 /*
  * Anonymous object constant for shm_open().
  */
-#ifndef _KERNEL
-#define	SHM_ANON		((char *)1)
+#if __has_feature(capabilities) && \
+	(defined(_KERNEL) || defined(__CHERI_PURE_CAPABILITY__))
+#define	SHM_ANON		((char * __capability)(__intcap_t)1)
 #else
-#define	SHM_ANON		((char * __capability)(intcap_t)1)
+#define	SHM_ANON		((char *)(__intptr_t)1)
 #endif
 
 /*
diff --git a/sys/sys/sysargmap.h b/sys/sys/sysargmap.h
index d61904d2140f..cc1acce54da7 100644
--- a/sys/sys/sysargmap.h
+++ b/sys/sys/sysargmap.h
@@ -165,6 +165,9 @@ static int sysargmask[] = {
 	[SYS_aio_write] = (0x0 | 0x1),
 	[SYS_lio_listio] = (0x0 | 0x2 | 0x8),
 	[SYS_kbounce] = (0x0 | 0x1 | 0x2),
+	[SYS_caprevoke_shadow] = (0x0 | 0x2 | 0x4),
+	[SYS_caprevoke] = (0x0 | 0x4),
+	[SYS_caprevoke_entire_shadow_cap] = (0x0 | 0x1),
 	[SYS_lchmod] = (0x0 | 0x1),
 	[SYS_lutimes] = (0x0 | 0x1 | 0x2),
 	[SYS_preadv] = (0x0 | 0x2),
diff --git a/sys/sys/syscall.h b/sys/sys/syscall.h
index d7586a9cb404..d1143af9ddda 100644
--- a/sys/sys/syscall.h
+++ b/sys/sys/syscall.h
@@ -235,6 +235,9 @@
 #define	SYS_aio_write	256
 #define	SYS_lio_listio	257
 #define	SYS_kbounce	258
+#define	SYS_caprevoke_shadow	259
+#define	SYS_caprevoke	260
+#define	SYS_caprevoke_entire_shadow_cap	261
 #define	SYS_freebsd11_getdents	272
 #define	SYS_lchmod	274
 				/* 275 is obsolete netbsd_lchown */
diff --git a/sys/sys/syscall.mk b/sys/sys/syscall.mk
index 577f1724dc70..94c706c5cc0c 100644
--- a/sys/sys/syscall.mk
+++ b/sys/sys/syscall.mk
@@ -169,6 +169,9 @@ MIASM =  \
 	aio_write.o \
 	lio_listio.o \
 	kbounce.o \
+	caprevoke_shadow.o \
+	caprevoke.o \
+	caprevoke_entire_shadow_cap.o \
 	freebsd11_getdents.o \
 	lchmod.o \
 	lutimes.o \
diff --git a/sys/sys/sysproto.h b/sys/sys/sysproto.h
index e717ec4145a4..cc9a8be8da18 100644
--- a/sys/sys/sysproto.h
+++ b/sys/sys/sysproto.h
@@ -729,6 +729,19 @@ struct kbounce_args {
 	char len_l_[PADL_(size_t)]; size_t len; char len_r_[PADR_(size_t)];
 	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
 };
+struct caprevoke_shadow_args {
+	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
+	char arena_l_[PADL_(void * __capability)]; void * __capability arena; char arena_r_[PADR_(void * __capability)];
+	char shadow_l_[PADL_(void * __capability)]; void * __capability shadow; char shadow_r_[PADR_(void * __capability)];
+};
+struct caprevoke_args {
+	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
+	char start_epoch_l_[PADL_(uint64_t)]; uint64_t start_epoch; char start_epoch_r_[PADR_(uint64_t)];
+	char statout_l_[PADL_(struct caprevoke_stats * __capability)]; struct caprevoke_stats * __capability statout; char statout_r_[PADR_(struct caprevoke_stats * __capability)];
+};
+struct caprevoke_entire_shadow_cap_args {
+	char shadow_l_[PADL_(void * __capability)]; void * __capability shadow; char shadow_r_[PADR_(void * __capability)];
+};
 struct lchmod_args {
 	char path_l_[PADL_(const char * __capability)]; const char * __capability path; char path_r_[PADR_(const char * __capability)];
 	char mode_l_[PADL_(mode_t)]; mode_t mode; char mode_r_[PADR_(mode_t)];
@@ -1990,6 +2003,9 @@ int	sys_aio_read(struct thread *, struct aio_read_args *);
 int	sys_aio_write(struct thread *, struct aio_write_args *);
 int	sys_lio_listio(struct thread *, struct lio_listio_args *);
 int	sys_kbounce(struct thread *, struct kbounce_args *);
+int	sys_caprevoke_shadow(struct thread *, struct caprevoke_shadow_args *);
+int	sys_caprevoke(struct thread *, struct caprevoke_args *);
+int	sys_caprevoke_entire_shadow_cap(struct thread *, struct caprevoke_entire_shadow_cap_args *);
 int	sys_lchmod(struct thread *, struct lchmod_args *);
 int	sys_lutimes(struct thread *, struct lutimes_args *);
 int	sys_preadv(struct thread *, struct preadv_args *);
@@ -2894,6 +2910,9 @@ int	freebsd12_shm_open(struct thread *, struct freebsd12_shm_open_args *);
 #define	SYS_AUE_aio_write	AUE_AIO_WRITE
 #define	SYS_AUE_lio_listio	AUE_LIO_LISTIO
 #define	SYS_AUE_kbounce	AUE_NULL
+#define	SYS_AUE_caprevoke_shadow	AUE_NULL
+#define	SYS_AUE_caprevoke	AUE_NULL
+#define	SYS_AUE_caprevoke_entire_shadow_cap	AUE_NULL
 #define	SYS_AUE_freebsd11_getdents	AUE_O_GETDENTS
 #define	SYS_AUE_lchmod	AUE_LCHMOD
 #define	SYS_AUE_lutimes	AUE_LUTIMES
diff --git a/sys/sys/timers.h b/sys/sys/timers.h
index c80d7568c95c..0baedfa40cfa 100644
--- a/sys/sys/timers.h
+++ b/sys/sys/timers.h
@@ -115,6 +115,7 @@ struct	kclock {
 #define	ITIMER_EV_EXIT	1
 
 int	itimer_accept(struct proc *p, int tid, ksiginfo_t *ksi);
+
 #endif
 #endif /* !_SYS_TIMERS_H_ */
 // CHERI CHANGES START
diff --git a/sys/sys/user.h b/sys/sys/user.h
index b9b71b381e36..a1324d8f9962 100644
--- a/sys/sys/user.h
+++ b/sys/sys/user.h
@@ -464,6 +464,8 @@ struct kinfo_file {
 #define	KVME_PROT_READ		0x00000001
 #define	KVME_PROT_WRITE		0x00000002
 #define	KVME_PROT_EXEC		0x00000004
+#define	KVME_PROT_READCAPS	0x00000100
+#define	KVME_PROT_WRITECAPS	0x00000200
 
 #define	KVME_FLAG_COW		0x00000001
 #define	KVME_FLAG_NEEDS_COPY	0x00000002
@@ -524,7 +526,8 @@ struct kinfo_vmentry {
 	uint16_t kve_status;			/* Status flags. */
 	uint64_t kve_vn_fsid;			/* dev_t of vnode location */
 	uint64_t kve_vn_rdev;			/* Device id if device. */
-	int	 _kve_ispare[8];		/* Space for more stuff. */
+	int      kve_max_protection;		/* Maximum protection bitmask */
+	int	 _kve_ispare[7];		/* Space for more stuff. */
 	/* Truncated before copyout in sysctl */
 	char	 kve_path[PATH_MAX];		/* Path to VM obj, if any. */
 };
@@ -606,7 +609,7 @@ int	kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen,
 int	kern_proc_cwd_out(struct proc *p, struct sbuf *sb, ssize_t maxlen);
 int	kern_proc_out(struct proc *p, struct sbuf *sb, int flags);
 int	kern_proc_vmmap_out(struct proc *p, struct sbuf *sb, ssize_t maxlen,
-	int flags);
+	vm_offset_t startaddr, size_t max, int flags);
 
 int	vntype_to_kinfo(int vtype);
 void	pack_kinfo(struct kinfo_file *kif);
diff --git a/sys/vm/pmap.h b/sys/vm/pmap.h
index 04d54ece852a..b89202608d1b 100644
--- a/sys/vm/pmap.h
+++ b/sys/vm/pmap.h
@@ -174,6 +174,10 @@ void		 pmap_remove_all(vm_page_t m);
 void		 pmap_remove_pages(pmap_t);
 void		 pmap_remove_write(vm_page_t m);
 void		 pmap_sync_icache(pmap_t, vm_offset_t, vm_size_t);
+#if __has_feature(capabilities)
+boolean_t	 pmap_tc_capdirty(vm_page_t m);
+void		 pmap_sync_capdirty(pmap_t);
+#endif
 int		 pmap_ts_referenced(vm_page_t m);
 void		 pmap_unwire(pmap_t pmap, vm_offset_t start, vm_offset_t end);
 void		 pmap_zero_page(vm_page_t);
diff --git a/sys/vm/swap_pager.c b/sys/vm/swap_pager.c
index a6c2e104ccd5..72e6426ade63 100644
--- a/sys/vm/swap_pager.c
+++ b/sys/vm/swap_pager.c
@@ -2187,6 +2187,7 @@ swp_pager_meta_cheri_get_tags(vm_page_t page)
 	void * __capability *p;
 	struct swblk *sb;
 	vm_pindex_t swidx;
+	int mark_capdirty = 0;
 
 	swidx = rounddown(page->pindex, SWAP_META_PAGES);
 	scan = (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(page));
@@ -2196,18 +2197,33 @@ swp_pager_meta_cheri_get_tags(vm_page_t page)
 	    i < (swidx + 1) * BITS_PER_TAGS_PER_PAGE; i++) {
 		p = scan;
 		for (t = sb->swb_tags[i]; t != 0; t >>= j) {
+			mark_capdirty = 1;
 			j = ffsl((long)t);
 			cheri_restore_tag(p + j - 1);
 			p += j;
 		}
 		scan += 8 * sizeof(uint64_t);
 	}
+
+	/*
+	 * Because we stored through the direct region we will have bypassed
+	 * the TLB and all implicit capdirty tracking.  If we stored a
+	 * capability, mark the page as recently dirtied.
+	 *
+	 * This has to be recent (PGA_CAPSTORED) and not just dirty
+	 * (VPO_PASTCAPSTORE) so that incremental scans of the address space
+	 * still consider it.
+	 */
+	if (mark_capdirty)
+		vm_page_aflag_set(page, PGA_CAPSTORED);
 }
 
 /*
  *	swp_pager_meta_cheri_put_tags:
  *
  *	Save the capability tags of a page to its swap metadata structure.
+ *
+ *	XXX Make this use CLoadTags eventually
  */
 static void
 swp_pager_meta_cheri_put_tags(vm_page_t page)
diff --git a/sys/vm/vm_caprevoke.c b/sys/vm/vm_caprevoke.c
new file mode 100644
index 000000000000..73f8fd993796
--- /dev/null
+++ b/sys/vm/vm_caprevoke.c
@@ -0,0 +1,710 @@
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#include "opt_vm.h"
+#include <sys/param.h>
+#include <sys/systm.h>
+#include <sys/lock.h>
+#include <sys/mutex.h>
+#include <sys/proc.h>
+#include <sys/rwlock.h>
+
+#include <vm/vm.h>
+#include <vm/vm_param.h>
+#include <vm/pmap.h>
+#include <vm/vm_map.h>
+#include <vm/vm_object.h>
+#include <vm/vm_extern.h>
+#include <vm/vm_page.h>
+
+#include <cheri/cheric.h>
+#include <sys/caprevoke.h>
+#include <vm/vm_caprevoke.h>
+
+// XXX This is very much a work in progress!
+
+static bool caprevoke_avoid_faults = 1;
+SYSCTL_BOOL(_vm, OID_AUTO, caprevoke_avoid_faults, CTLFLAG_RW,
+    &caprevoke_avoid_faults, 0,
+    "XXX");
+
+static bool caprevoke_last_redirty = 1;
+SYSCTL_BOOL(_vm, OID_AUTO, caprevoke_last_redirty, CTLFLAG_RW,
+    &caprevoke_last_redirty, 0,
+    "XXX");
+
+static inline int
+vm_caprevoke_should_visit_page(vm_page_t m, int flags)
+{
+	/*
+	 * If a page is capdirty, visit this page.  On incremental passes,
+	 * this should catch a superset of the pages we need to visit.
+	 */
+	if (m->a.flags & PGA_CAPSTORED)
+		return 1;
+
+	/*
+	 * If this is an incremental scan, we only care about
+	 * recently-capdirty pages, so can stop here.
+	 */
+	if (flags & VM_CAPREVOKE_INCREMENTAL)
+		return 0;
+
+	/*
+	 * On the other hand, for full scans, we want to visit all pages
+	 * that may have had capabilities, not just recently.
+	 */
+	if (m->oflags & VPO_PASTCAPSTORE)
+		return 1;
+
+	return 0;
+}
+
+enum vm_cro_visit {
+	VM_CAPREVOKE_VIS_DONE  = 0,
+	VM_CAPREVOKE_VIS_DIRTY = 1,
+	VM_CAPREVOKE_VIS_BUSY  = 2
+};
+
+/*
+ * Given a writable, wired page in a wlocked object, visit it.
+ */
+static int
+vm_caprevoke_visit_rw(const struct vm_caprevoke_cookie *crc, int flags,
+		      vm_page_t m)
+{
+	int hascaps;
+	CAPREVOKE_STATS_FOR(crst, crc);
+
+	if (!vm_page_tryxbusy(m))
+		return VM_CAPREVOKE_VIS_BUSY;
+	VM_OBJECT_WUNLOCK(m->object);
+
+retry:
+	CAPREVOKE_STATS_BUMP(crst, pages_scan_rw);
+	hascaps = vm_caprevoke_page(crc, m);
+
+	/* CAS failures cause us to revisit */
+	if (hascaps & VM_CAPREVOKE_PAGE_DIRTY) {
+		/* If the world is stopped, do that now */
+		if (flags & VM_CAPREVOKE_LAST_FINI) {
+			CAPREVOKE_STATS_BUMP(crst, pages_retried);
+			goto retry;
+		}
+		vm_page_capdirty(m);
+	}
+
+	VM_OBJECT_WLOCK(m->object);
+	vm_page_xunbusy(m);
+
+	/*
+	 * Update VPO_PASTCAPSTORE to record the results of
+	 * this sweep.  Even though we cleared PGA_CAPSTORED before
+	 * calling this function, it's entirely possible that it
+	 * has become set again in the interim.
+	 */
+	if (hascaps & VM_CAPREVOKE_PAGE_HASCAPS) {
+		m->oflags |= VPO_PASTCAPSTORE;
+	} else {
+		m->oflags &= ~VPO_PASTCAPSTORE;
+		CAPREVOKE_STATS_BUMP(crst, pages_mark_clean);
+	}
+
+	return VM_CAPREVOKE_VIS_DONE;
+}
+
+/*
+ * The same thing, but for a *readable*, wired page.
+ *
+ * Returns 1 if the page must be visited read-write, 0 if it is clear to
+ * advance and carry on.
+ */
+static int
+vm_caprevoke_visit_ro(const struct vm_caprevoke_cookie *crc, int flags,
+		      vm_page_t m)
+{
+	CAPREVOKE_STATS_FOR(crst, crc);
+	int hascaps;
+
+	if (!vm_page_tryxbusy(m))
+		return VM_CAPREVOKE_VIS_BUSY;
+	VM_OBJECT_WUNLOCK(m->object);
+
+	CAPREVOKE_STATS_BUMP(crst, pages_scan_ro);
+	hascaps = vm_caprevoke_page_ro(crc, m);
+
+	KASSERT(!(hascaps & VM_CAPREVOKE_PAGE_HASCAPS)
+		|| ((m->oflags & VPO_PASTCAPSTORE)
+		    || (m->a.flags & PGA_CAPSTORED)),
+		("cap-bearing RO page without h/r capdirty?"
+			" hc=%x m=%p, m->of=%x, m->af=%x",
+			hascaps, m, m->oflags, m->a.flags));
+
+	VM_OBJECT_WLOCK(m->object);
+	vm_page_xunbusy(m);
+
+	if ((hascaps & VM_CAPREVOKE_PAGE_HASCAPS) == 0) {
+		/*
+		 * This can only be true if we scanned the entire page and
+		 * found no tagged, permission-bearing things.  In that case,
+		 * even though the page is possibly shared, it's safe to mark
+		 * it as clean for subsequent revocation passes!
+		 */
+		vm_page_aflag_clear(m, PGA_CAPSTORED);
+		m->oflags &= ~VPO_PASTCAPSTORE;
+
+		CAPREVOKE_STATS_BUMP(crst, pages_mark_clean);
+	} else if (m->a.flags & PGA_CAPSTORED) {
+		/*
+		 * Even if we have capabilities here, it's sufficient to
+		 * visit only in the opening pass.  While RW pages would
+		 * rely on PGA_CAPSTORED to be revisited, for RO pages,
+		 * VIS_DIRTY causes us to upgrade to RW now, so this is
+		 * a fine shuffling of capdirty bits.
+		 */
+		vm_page_aflag_clear(m, PGA_CAPSTORED);
+		m->oflags |= VPO_PASTCAPSTORE;
+	}
+
+	if (hascaps & VM_CAPREVOKE_PAGE_DIRTY) {
+		return VM_CAPREVOKE_VIS_DIRTY;
+	}
+
+	return VM_CAPREVOKE_VIS_DONE;
+}
+
+static void
+vm_caprevoke_unwire_in_situ(vm_page_t m)
+{
+	bool active;
+
+	vm_page_lock(m);
+	active = vm_page_active(m);
+	vm_page_unlock(m);
+	vm_page_unwire(m, active ? PQ_ACTIVE : PQ_INACTIVE);
+}
+
+enum vm_cro_at {
+	VM_CAPREVOKE_AT_OK    = 0,
+	VM_CAPREVOKE_AT_TICK  = 1,
+	VM_CAPREVOKE_AT_VMERR = 2
+};
+
+/*
+ * Given a map, map entry, and page index within that entry, visit that page
+ * for revocation.  The entry must have an object.
+ *
+ * The map must be read-locked on entry and will be read-locked on return,
+ * but this lock may be dropped in the interim.
+ *
+ * The entry's object must be wlocked on entry and will be returned
+ * wlocked on success and unlocked on failure.  Even on success, the lock
+ * may have been dropped and reacquired.
+ *
+ * On success, *ooff will be updated to the next offset to probe (which may
+ * be past the end of the object; the caller should test).  This next offset
+ * may equal ioff if the world has shifted; this is probably fine as the
+ * caller should just repeat the call.  On failure, *ooff will not be modified.
+ */
+static enum vm_cro_at
+vm_caprevoke_object_at(const struct vm_caprevoke_cookie *crc, int flags,
+			vm_map_entry_t entry, vm_offset_t ioff,
+			vm_offset_t *ooff, int *vmres)
+{
+	CAPREVOKE_STATS_FOR(crst, crc);
+	vm_map_t    map = crc->map;
+	vm_object_t obj = entry->object.vm_object;
+	vm_pindex_t ipi = OFF_TO_IDX(ioff);
+
+	vm_page_t m = vm_page_lookup(obj, ipi);
+
+	KASSERT((m == NULL) || (m->valid == VM_PAGE_BITS_ALL),
+		("Revocation invalid page"));
+
+	if (m == NULL) {
+		vm_offset_t addr = ioff - entry->offset + entry->start;
+
+		if (flags & VM_CAPREVOKE_QUICK_SUCCESSOR) {
+			/* Look forward in the object map */
+			vm_page_t obj_next_pg = vm_page_find_least(obj, ipi);
+
+			vm_offset_t lastoff = entry->end - entry->start + entry->offset;
+
+			if ((obj_next_pg == NULL)
+			    || (obj_next_pg->pindex >= OFF_TO_IDX(lastoff))) {
+				CAPREVOKE_STATS_INC(crst, pages_skip_fast,
+					(entry->end - addr) >> PAGE_SHIFT);
+				*ooff = lastoff;
+			} else {
+
+				KASSERT(obj_next_pg->object == obj,
+					("Fast find page in bad object?"));
+
+				*ooff = IDX_TO_OFF(obj_next_pg->pindex);
+				CAPREVOKE_STATS_INC(crst, pages_skip_fast,
+					obj_next_pg->pindex - ipi);
+			}
+			return VM_CAPREVOKE_AT_OK;
+		}
+
+		CAPREVOKE_STATS_BUMP(crst, pages_faulted_ro);
+
+		int res;
+		unsigned int last_timestamp = map->timestamp;
+
+		VM_OBJECT_WUNLOCK(obj);
+
+		vm_map_unlock_read(map);
+		res = vm_fault(map, addr, VM_PROT_READ, VM_FAULT_NORMAL,
+				    &m);
+		vm_map_lock_read(map);
+
+		if (res != KERN_SUCCESS) {
+			*vmres = res;
+			return VM_CAPREVOKE_AT_VMERR;
+		}
+		if (last_timestamp != map->timestamp) {
+			/*
+			 * The map has changed out from under us; bail and
+			 * the caller will look up the new map entry.
+			 * First, though, it's important to release the page
+			 * we're holding!
+			 *
+			 * If we're the sole wiring holder, consider this
+			 * page active because we're most likely about to
+			 * come right back.
+			 */
+			vm_page_unwire(m, PQ_ACTIVE);
+			return VM_CAPREVOKE_AT_TICK;
+		}
+
+		VM_OBJECT_WLOCK(m->object);
+		vm_caprevoke_unwire_in_situ(m);
+	} else {
+		KASSERT(m->object == obj, ("Page lookup bad object?"));
+	}
+
+	VM_OBJECT_ASSERT_WLOCKED(m->object);
+
+	if (pmap_page_is_write_mapped(m)) {
+		if (!vm_caprevoke_should_visit_page(m, flags)) {
+			CAPREVOKE_STATS_BUMP(crst, pages_skip);
+			goto visit_rw_ok;
+		}
+
+		if (m->object == obj) {
+			/* Go visit the page RW in place */
+			goto visit_rw;
+		}
+
+		/*
+		 * XXX I don't quite understand how this is
+		 * possible, but something seems fishy about
+		 * this situation.  Just go force a RW fault
+		 * to copy up the page
+		 */
+		goto visit_rw_fault;
+	}
+
+	if (!vm_caprevoke_should_visit_page(m, flags)) {
+		*ooff = ioff + pagesizes[m->psind];
+		CAPREVOKE_STATS_BUMP(crst, pages_skip);
+		if (m->object != obj) {
+			VM_OBJECT_WUNLOCK(m->object);
+			VM_OBJECT_WLOCK(obj);
+		}
+		return VM_CAPREVOKE_AT_OK;
+	}
+
+	switch(vm_caprevoke_visit_ro(crc, flags, m))
+	{
+	case VM_CAPREVOKE_VIS_DONE:
+		/* We were able to conclude that the page was clean */
+		*ooff = ioff + pagesizes[m->psind];
+		if (m->object != obj) {
+			VM_OBJECT_WUNLOCK(m->object);
+			VM_OBJECT_WLOCK(obj);
+		}
+		return VM_CAPREVOKE_AT_OK;
+	case VM_CAPREVOKE_VIS_BUSY:
+		/*
+		 * This is kind of awkward; the page is busy and it's
+		 * not clear by whom.  But whoever it is needs our
+		 * object lock to unbusy.  So handle this like the
+		 * map stepping forward.
+		 */
+		if (m->object != obj) {
+			VM_OBJECT_WUNLOCK(m->object);
+		}
+		VM_OBJECT_ASSERT_UNLOCKED(obj);
+		return VM_CAPREVOKE_AT_TICK;
+	case VM_CAPREVOKE_VIS_DIRTY:
+		/* Dirty here means we need to upgrade to RW now */
+		break;
+	default:
+		panic("bad result from vm_caprevoke_visit_ro");
+	}
+
+visit_rw_fault:
+	CAPREVOKE_STATS_BUMP(crst, pages_faulted_rw);
+
+	int res;
+	unsigned int last_timestamp = map->timestamp;
+
+	vm_offset_t addr = ioff - entry->offset + entry->start;
+
+	VM_OBJECT_WUNLOCK(m->object);
+	vm_map_unlock_read(map);
+	res = vm_fault(map, addr, VM_PROT_WRITE, VM_FAULT_NORMAL, &m);
+	vm_map_lock_read(map);
+	if (res != KERN_SUCCESS) {
+		*vmres = res;
+		VM_OBJECT_ASSERT_UNLOCKED(obj);
+		return VM_CAPREVOKE_AT_VMERR;
+	}
+	if (last_timestamp != map->timestamp) {
+		vm_page_unwire(m, PQ_ACTIVE);
+		VM_OBJECT_ASSERT_UNLOCKED(obj);
+		return VM_CAPREVOKE_AT_TICK;
+	}
+
+	KASSERT(m->object == obj, ("Bad page object after FAULT WRITE"));
+
+	VM_OBJECT_WLOCK(m->object);
+	vm_caprevoke_unwire_in_situ(m);
+
+visit_rw:
+	vm_page_aflag_clear(m, PGA_CAPSTORED);
+	switch(vm_caprevoke_visit_rw(crc, flags, m))
+	{
+	case VM_CAPREVOKE_VIS_DONE:
+visit_rw_ok:
+
+		KASSERT(((m->a.flags & PGA_CAPSTORED) == 0)
+			|| !(flags & VM_CAPREVOKE_LAST_INIT),
+			("Capdirty page after visit with world stopped?"));
+
+		/*
+		 * When we are closing a revocation epoch, we transfer
+		 * VPO_PASTCAPSTORED to PGA_CAPSTORED so that we don't take
+		 * as many faults in the inter-epoch period.  We know that
+		 * we're going to visit all the VPO_PASTCAPSTORED-bearing
+		 * pages when we open the next epoch anyway, so there's no
+		 * point in lazily setting their PGA_CAPSTORED flags.
+		 */
+		if (caprevoke_last_redirty
+		    && (flags & VM_CAPREVOKE_LAST_INIT)) {
+			if (m->oflags & VPO_PASTCAPSTORE) {
+				vm_page_capdirty(m);
+			}
+		}
+
+		*ooff = ioff + pagesizes[m->psind];
+		if (m->object != obj) {
+			VM_OBJECT_WUNLOCK(m->object);
+			VM_OBJECT_WLOCK(obj);
+		}
+		return VM_CAPREVOKE_AT_OK;
+	case VM_CAPREVOKE_VIS_BUSY:
+		VM_OBJECT_WUNLOCK(m->object);
+		VM_OBJECT_ASSERT_UNLOCKED(obj);
+		return VM_CAPREVOKE_AT_TICK;
+	default:
+		panic("bad result from vm_caprevoke_visit_rw");
+	}
+}
+
+/*
+ * Do a sweep through a given map entry, starting at a given va.  Update the
+ * va with how far we got.
+ *
+ * The map must be read-locked on entry and will be read-locked on exit, but
+ * the lock may be dropped internally.  The map must, therefore, also be
+ * held across invocation.
+ */
+static int
+vm_caprevoke_map_entry(const struct vm_caprevoke_cookie *crc, int flags,
+		       vm_map_entry_t entry, vm_offset_t *addr)
+{
+	int res;
+	vm_offset_t ooffset;
+	vm_object_t obj;
+	bool obj_has_backing_caps;
+
+	// XXX NWF ?
+	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
+		goto fini;
+
+	obj = entry->object.vm_object;
+
+	/* No backing object?  Just a bunch of zeros, so skip it */
+	if (!obj)
+		goto fini;
+
+	/* Skip entire objects that cannot store tags */
+	if ((obj->flags & (OBJ_NOLOADTAGS | OBJ_NOSTORETAGS)) ==
+	    (OBJ_NOLOADTAGS | OBJ_NOSTORETAGS))
+		goto fini;
+
+	VM_OBJECT_WLOCK(obj);
+
+	if (caprevoke_avoid_faults) {
+		/*
+		 * Look to see if this object's backing stores are not tag-capable.
+		 * If so, this allows us to immediately advance to the next page
+		 * in this object whenever we find something unmapped.
+		 *
+		 * XXX There is an intermediate "faster" path we haven't yet
+		 * explored, which is to have a "next possible tag-capable pindex"
+		 * operation on the stack of vm objects that we might find we need.
+		 *
+		 * XXX Do we really have to look recursively like this or is
+		 * it enough to just glance at the immediate backing object?
+		 */
+
+		vm_object_t tobj;
+
+		obj_has_backing_caps = false;
+
+		for (tobj = obj->backing_object; tobj != NULL;
+		    tobj = tobj->backing_object) {
+			if ((tobj->flags & OBJ_NOLOADTAGS) == 0 ||
+			    (tobj->flags & OBJ_NOSTORETAGS) == 0) {
+				obj_has_backing_caps = true;
+				break;
+			}
+		}
+	} else {
+		obj_has_backing_caps = true;
+	}
+	if (!obj_has_backing_caps)
+		flags |= VM_CAPREVOKE_QUICK_SUCCESSOR;
+
+	while (*addr < entry->end) {
+		int vmres;
+
+		/* Find ourselves in this object */
+		ooffset = *addr      - entry->start + entry->offset;
+
+		res = vm_caprevoke_object_at(crc, flags, entry, ooffset,
+					     &ooffset, &vmres);
+
+		/* How far did we get? */
+		*addr = ooffset - entry->offset + entry->start;
+		KASSERT(*addr <= entry->end, ("vm_caprevoke post past entry end"));
+
+		switch (res) {
+		case VM_CAPREVOKE_AT_VMERR:
+			return vmres;
+		case VM_CAPREVOKE_AT_TICK:
+			/* Have the caller retranslate the map */
+			return KERN_SUCCESS;
+		case VM_CAPREVOKE_AT_OK:
+			break;
+		}
+
+	}
+
+	VM_OBJECT_WUNLOCK(obj);
+
+fini:
+	*addr = entry->end;
+	return KERN_SUCCESS;
+}
+
+/*
+ * Do a sweep through all mapped objects, hunting for revoked capabilities,
+ * as defined by the machdep vm_caprevoke_page.
+ *
+ * For simplicity, the proc must be held on entry and will be held
+ * throughout.  XXX Would we rather do something else?
+ *
+ * XXX Right now, CAPREVOKE_LAST_INIT and _FINI are probably not correctly
+ * used.  We should, instead, take the flags to imply...
+ *
+ *   LAST_INIT by itself: enter into the load-side story
+ *   LAST_FINI by itself: clean pages in the background
+ *   both: as now, a world-stopped cleaning pass
+ */
+int
+vm_caprevoke(const struct vm_caprevoke_cookie *crc, int flags)
+{
+	int res = KERN_SUCCESS;
+	const vm_map_t map = crc->map;
+	vm_map_entry_t entry;
+	vm_offset_t addr;
+
+	if ((flags & (VM_CAPREVOKE_LAST_INIT|VM_CAPREVOKE_LAST_FINI))
+	    == VM_CAPREVOKE_LAST_FINI) {
+		/*
+		 * XXX We don't do the load-side story; instead, we do all our work
+		 * in LAST_INIT.  There's nothing to do in this second pass.
+		 */
+		return KERN_SUCCESS;
+	}
+
+	addr = 0;
+
+	/* Acquire the address space map write-locked and not busy */
+	vm_map_lock(map);
+	if(map->busy)
+		vm_map_wait_busy(map);
+
+	if (flags & VM_CAPREVOKE_PMAP_SYNC) {
+		/* Flush out all the MD capdirty bits to the MI layer. */
+		pmap_sync_capdirty(map->pmap);
+	}
+
+	/*
+	 * Downgrade VM map locks to read-locked but busy to guard against
+	 * a racing fork (see vmspace_fork).
+	 */
+	vm_map_busy(map);
+	vm_map_lock_downgrade(map);
+
+	entry = vm_map_entry_first(map);
+
+	if (entry != &map->header)
+		addr = entry->start;
+
+	while (entry != &map->header) {
+		/*
+		 * XXX Somewhere around here we should be resetting
+		 * MPROT_QUARANTINE'd map entries to be usable again, yes?
+		 */
+
+		res = vm_caprevoke_map_entry(crc, flags, entry, &addr);
+
+		/*
+		 * We might be bailing out because a page fault failed for
+		 * catastrophic reasons (or polite ones like ptrace()).
+		 */
+		if (res != KERN_SUCCESS)
+			goto out;
+
+		if (!vm_map_lookup_entry(map, addr, &entry)) {
+			entry = vm_map_entry_succ(entry);
+			if (entry != &map->header)
+				addr = entry->start;
+		}
+	}
+
+out:
+	vm_map_unlock_read(map);
+	vm_map_lock(map);
+	vm_map_unbusy(map);
+	vm_map_unlock(map);
+
+	return res;
+}
+
+/*
+ * Do a sweep across the single map entry containing the given address.
+ */
+int
+vm_caprevoke_one(const struct vm_caprevoke_cookie *crc, int flags,
+		 vm_offset_t oneaddr)
+{
+	int res = KERN_SUCCESS;
+	const vm_map_t map = crc->map;
+	vm_map_entry_t entry;
+	vm_offset_t addr;
+
+	KASSERT(!!(flags & VM_CAPREVOKE_LAST_INIT)
+		 == !!(flags & VM_CAPREVOKE_LAST_FINI),
+			("vm_caprevoke_one bad LAST flags"));
+
+	vm_map_lock_read(map);
+
+	if (!vm_map_lookup_entry(map, oneaddr, &entry))
+		goto out;
+
+	addr = entry->start;
+	while (addr < entry->end) {
+		res = vm_caprevoke_map_entry(crc, flags, entry, &addr);
+
+		if (res != KERN_SUCCESS)
+			goto out;
+
+		if (!vm_map_lookup_entry(map, addr, &entry))
+			break;
+		if (oneaddr < entry->start)
+			break;
+	}
+
+out:
+	vm_map_unlock_read(map);
+	return res;
+}
+
+/*
+ * XXX Constructed for us by the MD layer
+ *
+ * We ought to do the construction ourselves, but we can't use
+ * cheri_capability_build_user_data because the shadow space isn't
+ * sufficiently padded.  We can fix that and go from there, but this is a
+ * convenient workaround since we already had it.
+ */
+void * __capability caprev_shadow_cap = (void * __capability)(intcap_t) -1;
+
+int
+vm_caprevoke_cookie_init(vm_map_t map,
+			 struct caprevoke_stats *stats,
+			 struct vm_caprevoke_cookie *crc)
+{
+	KASSERT(map == &curproc->p_vmspace->vm_map,
+		("caprev does not support foreign maps (yet)"));
+	KASSERT(map->vm_caprev_shva == cheri_getaddress(caprev_shadow_cap),
+		("caprev shadow does not match capability"));
+	KASSERT(map->vm_caprev_shva == VM_CAPREVOKE_BM_BASE,
+		("caprev shadow does not match definition"));
+
+	if (map->vm_caprev_sh == NULL)
+		return KERN_INVALID_ARGUMENT;
+
+	crc->map = map;
+#ifdef CHERI_CAPREVOKE_STATS
+	crc->stats = stats;
+#endif
+
+	/*
+	 * XXX Right now, we know that there are no coarse-grain bits
+	 * getting set, nor otypes nor anything else, since we don't do
+	 * MPROT_QUARANTINE or anything of that sort.
+	 *
+	 * In the future, we should count the number of pages held in
+	 * MPROT_QUARANTINE or munmap()'s quarantine or other such to decide
+	 * whether to set _NO_COARSE.  Similary for the others.
+	 */
+	vm_caprevoke_set_test(crc,
+		VM_CAPREVOKE_CF_NO_COARSE_MEM
+		| VM_CAPREVOKE_CF_NO_OTYPES
+		| VM_CAPREVOKE_CF_NO_CIDS);
+
+	/*
+	 * For foreign maps, we should take advantage of map->vm_caprev_sh
+	 * and construct a mapping in the local address space to manipulate
+	 * the remote one!
+	 */
+	crc->crshadow = caprev_shadow_cap;
+
+	/* XXX This is awfully MD for a MI file like this one... */
+	crc->info_page = cheri_capability_build_user_data(
+		CHERI_PERM_LOAD
+		| CHERI_PERM_LOAD_CAP
+		| CHERI_PERM_STORE
+		| CHERI_PERM_STORE_CAP
+		| CHERI_PERM_GLOBAL,
+		VM_CAPREVOKE_INFO_PAGE,
+		PAGE_SIZE,
+		0);
+
+	return KERN_SUCCESS;
+}
+
+void
+vm_caprevoke_cookie_rele(struct vm_caprevoke_cookie *crc)
+{
+	(void)crc;
+	return;
+}
diff --git a/sys/vm/vm_caprevoke.h b/sys/vm/vm_caprevoke.h
new file mode 100644
index 000000000000..ce1fed65df0e
--- /dev/null
+++ b/sys/vm/vm_caprevoke.h
@@ -0,0 +1,187 @@
+/*-
+ * SPDX-License-Identifier: BSD-2-Clause
+ *
+ * Copyright (c) 2019 Nathaniel Filardo
+ * All rights reserved.
+ *
+ * This software was developed by SRI International and the University of
+ * Cambridge Computer Laboratory (Department of Computer Science and
+ * Technology) under DARPA contract HR0011-18-C-0016 ("ECATS"), as part of the
+ * DARPA SSITH research programme.
+* 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef	_VM_CAPREVOKE_
+#define _VM_CAPREVOKE_
+#ifdef CHERI_CAPREVOKE
+
+/**************************** FORWARD DECLARATIONS ***************************/
+
+struct caprevoke_info;
+struct caprevoke_info_page;
+struct caprevoke_stats;
+struct file;
+struct vm_caprevoke_cookie;
+struct vm_map;
+struct vm_page;
+
+/***************************** REVOCATION ITSELF *****************************/
+
+  /* sys/.../cheri/cheri_otype.c */
+void * __capability cheri_revoke_sealed(void * __capability r);
+
+/*
+ * The revoked image of a capability is a *tagged* quantity with zero
+ * permissions.
+ *
+ * If the input is sealed, the revoked image is, at present, the unsealed,
+ * zero-permission variant, so that software that uses sealing types for
+ * tokens will notice the type mismatch and architectural usage will fail.
+ * This is almost certainly a sufficiently subtle point that this is not
+ * entirely the right answer, though I hope it's not entirely wrong, either.
+ */
+static __always_inline inline void * __capability
+cheri_revoke(void * __capability c)
+{
+#ifndef CHERI_CAPREVOKE_CLEARTAGS
+	if (__builtin_expect(cheri_gettype(c) == -1, 1)) {
+		return cheri_andperm(c, 0);
+	}
+	return cheri_revoke_sealed(c);
+#else
+	/* No need to handle sealed things specially */
+	return cheri_cleartag(c);
+#endif
+}
+
+/***************************** KERNEL MI LAYER ******************************/
+
+	/*
+	 * To support optimization as to which bitmap(s) we look at,
+	 * given revocation runs may use different predicates on
+	 * capabilities under test.
+	 *
+	 * Takes cutperm = cheri_getperm(cut) as an argument for
+	 * optimization reasons.
+	 *
+	 * Returns any nonzero value to indicate revocation required.
+	 */
+typedef unsigned long (*vm_caprevoke_test_fn)(
+			const uint8_t * __capability shadow,
+			const void * __capability cut,
+			unsigned long cutperm);
+
+struct vm_caprevoke_cookie {
+	struct vm_map * map;			/* The map itself */
+	const uint8_t * __capability crshadow;	/* Access to the shadow space */
+	struct caprevoke_info_page * __capability info_page;
+#ifdef CHERI_CAPREVOKE_STATS
+	struct caprevoke_stats *stats;		/* Statistics */
+#endif
+
+	vm_caprevoke_test_fn caprevoke_test_int;
+};
+
+int vm_caprevoke_cookie_init(struct vm_map * map,
+			     struct caprevoke_stats * stats,
+			     struct vm_caprevoke_cookie *baked);
+void vm_caprevoke_cookie_rele(struct vm_caprevoke_cookie *cookie);
+
+enum {
+	/* Set externally */
+	VM_CAPREVOKE_INCREMENTAL=0x01,
+	VM_CAPREVOKE_LAST_INIT=0x02,
+	VM_CAPREVOKE_LAST_FINI=0x04,
+	VM_CAPREVOKE_PMAP_SYNC=0x08,
+
+	/* Set internally */
+	VM_CAPREVOKE_QUICK_SUCCESSOR=0x10,
+};
+
+int vm_caprevoke(const struct vm_caprevoke_cookie *, int);
+int vm_caprevoke_one(const struct vm_caprevoke_cookie *, int, vm_offset_t);
+
+/***************************** KERNEL MD LAYER ******************************/
+
+int vm_caprevoke_test(const struct vm_caprevoke_cookie *,
+		      const void * __capability);
+
+
+enum {
+	/* If no coarse bits set, VMMAP-bearing caps are imune */
+	VM_CAPREVOKE_CF_NO_COARSE_MEM = 0x01,
+
+	/* If no otype bits set, Permit_Seal and _Unseal are imune */
+	VM_CAPREVOKE_CF_NO_OTYPES = 0x02,
+	VM_CAPREVOKE_CF_NO_CIDS   = 0x04,
+};
+void vm_caprevoke_set_test(struct vm_caprevoke_cookie *, int flags);
+
+/*  Shadow region installation into vm map */
+int vm_map_install_caprevoke_shadow (struct vm_map * map);
+
+/*  Shadow map capability constructor */
+void * __capability vm_caprevoke_shadow_cap(int sel, vm_offset_t base,
+					    vm_offset_t size, int perm_mask);
+/*  Publish state to shared page */
+void vm_caprevoke_publish(const struct vm_caprevoke_cookie *,
+			  const struct caprevoke_info *);
+
+/*  Walking a particular page */
+#define VM_CAPREVOKE_PAGE_HASCAPS	0x01
+#define VM_CAPREVOKE_PAGE_DIRTY		0x02
+int vm_caprevoke_page(const struct vm_caprevoke_cookie * c,
+		      struct vm_page * m);
+int vm_caprevoke_page_ro(const struct vm_caprevoke_cookie * c,
+		      struct vm_page * m);
+
+/***************************** HOARDER CALLBACKS ******************************/
+
+/*  sys/kern/vfs_aio.c */
+void aio_caprevoke(struct proc *, const struct vm_caprevoke_cookie *);
+
+/*  sys/kern/kern_event.c */
+int kqueue_caprevoke(struct file *fp, const struct vm_caprevoke_cookie *);
+
+/*  sys/kern/kern_sig.c */
+void sigaltstack_caprevoke(struct thread *, const struct vm_caprevoke_cookie *);
+
+/*  sys/kern/kern_time.c */
+void ktimer_caprevoke(struct proc *, const struct vm_caprevoke_cookie *);
+
+/*  MD */
+void caprevoke_td_frame(struct thread *td, const struct vm_caprevoke_cookie *);
+
+/**************************** STATISTICS COUNTING *****************************/
+
+#ifdef CHERI_CAPREVOKE_STATS
+#define CAPREVOKE_STATS_FOR(st, crc)	struct caprevoke_stats *st = crc->stats
+#define CAPREVOKE_STATS_INC(st, ctr, d)	do { (st)->ctr += (d); } while(0)
+#else
+#define CAPREVOKE_STATS_FOR(st, crc)	do { } while(0)
+#define CAPREVOKE_STATS_INC(st, ctr, d)	do { } while(0)
+#endif
+#define CAPREVOKE_STATS_BUMP(st, ctr)	CAPREVOKE_STATS_INC(st, ctr, 1)
+
+#endif
+#endif
diff --git a/sys/vm/vm_extern.h b/sys/vm/vm_extern.h
index 149dc6193648..aeb056601fdd 100644
--- a/sys/vm/vm_extern.h
+++ b/sys/vm/vm_extern.h
@@ -131,6 +131,7 @@ u_int vm_active_count(void);
 u_int vm_inactive_count(void);
 u_int vm_laundry_count(void);
 u_int vm_wait_count(void);
+
 #endif				/* _KERNEL */
 #endif				/* !_VM_EXTERN_H_ */
 // CHERI CHANGES START
diff --git a/sys/vm/vm_map.c b/sys/vm/vm_map.c
index 890fd147bf48..bd3bcf397261 100644
--- a/sys/vm/vm_map.c
+++ b/sys/vm/vm_map.c
@@ -100,6 +100,10 @@ __FBSDID("$FreeBSD$");
 #include <vm/swap_pager.h>
 #include <vm/uma.h>
 
+#ifdef CHERI_CAPREVOKE
+#include <sys/caprevoke.h>
+#endif
+
 /*
  *	Virtual memory maps provide for the mapping, protection,
  *	and sharing of virtual memory objects.  In addition,
@@ -135,6 +139,7 @@ static int vm_map_zinit(void *mem, int ize, int flags);
 static void _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min,
     vm_offset_t max);
 static void vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map);
+static void vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry);
 static void vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry);
 static void vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry);
 static int vm_map_growstack(vm_map_t map, vm_offset_t addr,
@@ -150,6 +155,7 @@ static int vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos,
     int cow);
 static void vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
     vm_offset_t failed_addr);
+static vm_map_entry_t vm_map_entry_create(vm_map_t map);
 
 #define	ENTRY_CHARGED(e) ((e)->cred != NULL || \
     ((e)->object.vm_object != NULL && (e)->object.vm_object->cred != NULL && \
@@ -275,6 +281,9 @@ vm_map_zinit(void *mem, int size, int flags)
 	memset(map, 0, sizeof(*map));
 	mtx_init(&map->system_mtx, "vm map (system)", NULL, MTX_DEF | MTX_DUPOK);
 	sx_init(&map->lock, "vm map (user)");
+#ifdef CHERI_CAPREVOKE
+	cv_init(&map->vm_caprev_cv, "vmcaprev");
+#endif
 	return (0);
 }
 
@@ -361,6 +370,11 @@ vmspace_dofree(struct vmspace *vm)
 	 */
 	shmexit(vm);
 
+#ifdef CHERI_CAPREVOKE
+	/* Drop our explicit handle to the caprevoke shadow object */
+	vm->vm_map.vm_caprev_sh = NULL;
+#endif
+
 	/*
 	 * Lock the map, to wait out all other references to it.
 	 * Delete all of the mappings and pages they hold, then call
@@ -401,6 +415,86 @@ vmspace_exitfree(struct proc *p)
 	vmspace_free(vm);
 }
 
+static int coexecve_cleanup_margin_up = 0x10000;
+SYSCTL_INT(_debug, OID_AUTO, coexecve_cleanup_margin_up, CTLFLAG_RWTUN,
+    &coexecve_cleanup_margin_up, 0,
+    "Maximum hole size for segments growing up when cleaning up after colocated processes");
+static int coexecve_cleanup_margin_down = MAXSSIZ;
+SYSCTL_INT(_debug, OID_AUTO, coexecve_cleanup_margin_down, CTLFLAG_RWTUN,
+    &coexecve_cleanup_margin_down, 0,
+    "Maximum hole size for segments growing down when cleaning up after colocated processes");
+
+static void
+vm_map_entry_abandon(vm_map_t map, vm_map_entry_t old_entry)
+{
+	vm_map_entry_t entry, prev, next;
+	vm_offset_t start, end;
+	boolean_t found, grown_down;
+	int rv;
+
+	start = old_entry->start;
+
+	if (start != 0)
+		vm_map_lookup_entry(map, start-1, &prev);
+	else
+		prev = &map->header;
+	next = vm_map_entry_succ(old_entry);
+
+	end = old_entry->end;
+	grown_down = old_entry->eflags & MAP_ENTRY_GROWS_DOWN;
+	vm_map_entry_delete(map, old_entry);
+
+	/*
+	 * Try to cover the "holes" between abandoned entries, so that
+	 * vm_map_try_merge_entries() can coalesce them.  Use much larger
+	 * threshold for stacks.
+	 */
+	if (prev != &map->header && prev->object.vm_object == NULL &&
+	    prev->protection == PROT_NONE &&
+	    start > prev->end && start - prev->end <=
+	    ((grown_down != 0) ?
+	    coexecve_cleanup_margin_down : coexecve_cleanup_margin_up)) {
+		start = prev->end;
+	}
+
+	if (next != &map->header && next->object.vm_object == NULL &&
+	    next->protection == PROT_NONE &&
+	    end < next->start && next->start - end <=
+	    (((next->eflags & MAP_ENTRY_GROWS_DOWN) != 0) ?
+	    coexecve_cleanup_margin_down : coexecve_cleanup_margin_up)) {
+		end = next->start;
+	}
+
+	rv = vm_map_insert(map, NULL, 0, start, end,
+	    PROT_NONE, PROT_NONE, MAP_NOFAULT | MAP_DISABLE_SYNCER | MAP_DISABLE_COREDUMP);
+	KASSERT(rv == KERN_SUCCESS,
+	    ("%s: vm_map_insert() failed with error %d\n", __func__, rv));
+
+	found = vm_map_lookup_entry(map, start, &entry);
+	KASSERT(found == TRUE,
+	    ("%s: vm_map_insert() returned false\n", __func__));
+
+	KASSERT(entry->protection == PROT_NONE,
+	    ("%s: protection %d\n", __func__, entry->protection));
+	KASSERT(entry->max_protection == PROT_NONE,
+	    ("%s: max_protection %d\n", __func__, entry->max_protection));
+	KASSERT(entry->inheritance == VM_INHERIT_DEFAULT,
+	    ("%s: inheritance %d\n", __func__, entry->inheritance));
+	KASSERT(entry->wired_count == 0,
+	    ("%s: wired_count %d\n", __func__, entry->wired_count));
+	KASSERT(entry->cred == NULL,
+	    ("%s: cred %p\n", __func__, entry->cred));
+
+	/*
+	 * Preserve this particular flag for the purpose of future coalescing
+	 * by another vm_map_entry_abandon() run.
+	 */
+	if (grown_down)
+		entry->eflags |= MAP_ENTRY_GROWS_DOWN;
+
+	vm_map_try_merge_entries(map, prev, entry);
+}
+
 void
 vmspace_exit(struct thread *td)
 {
@@ -941,6 +1035,11 @@ _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
 	map->timestamp = 0;
 	map->busy = 0;
 	map->anon_loc = 0;
+
+#ifdef CHERI_CAPREVOKE
+	map->vm_caprev_st = CAPREVST_NONE;	/* and epoch 0 */
+#endif
+
 #ifdef DIAGNOSTIC
 	map->nupdates = 0;
 #endif
@@ -2261,10 +2360,16 @@ static bool
 vm_map_mergeable_neighbors(vm_map_entry_t prev, vm_map_entry_t entry)
 {
 
+#ifdef notyet
 	KASSERT((prev->eflags & MAP_ENTRY_NOMERGE_MASK) == 0 ||
 	    (entry->eflags & MAP_ENTRY_NOMERGE_MASK) == 0,
 	    ("vm_map_mergeable_neighbors: neither %p nor %p are mergeable",
 	    prev, entry));
+#else
+	if ((prev->eflags & MAP_ENTRY_NOMERGE_MASK) != 0 &&
+	    (entry->eflags & MAP_ENTRY_NOMERGE_MASK) != 0)
+	    return (false);
+#endif
 	return (prev->end == entry->start &&
 	    prev->object.vm_object == entry->object.vm_object &&
 	    (prev->object.vm_object == NULL ||
@@ -3883,8 +3988,8 @@ vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
  *	Deallocates the given address range from the target
  *	map.
  */
-int
-vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
+static int
+_vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end, bool abandon)
 {
 	vm_map_entry_t entry;
 	vm_map_entry_t first_entry;
@@ -3974,12 +4079,28 @@ vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
 		 * will be set in the wrong object!)
 		 */
 		vm_map_log("remove", entry);
-		vm_map_entry_delete(map, entry);
+		if (abandon)
+			vm_map_entry_abandon(map, entry);
+		else
+			vm_map_entry_delete(map, entry);
 		entry = next;
 	}
 	return (KERN_SUCCESS);
 }
 
+int
+vm_map_abandon_and_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
+{
+
+	return (_vm_map_delete(map, start, end, true));
+}
+
+int
+vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
+{
+
+	return (_vm_map_delete(map, start, end, false));
+}
 /*
  *	vm_map_remove:
  *
@@ -4260,6 +4381,13 @@ vmspace_fork(struct vmspace *vm1, vm_ooffset_t *fork_charge)
 	vm2->vm_taddr = vm1->vm_taddr;
 	vm2->vm_daddr = vm1->vm_daddr;
 	vm2->vm_maxsaddr = vm1->vm_maxsaddr;
+
+#ifdef CHERI_CAPREVOKE
+	vm2->vm_map.vm_caprev_st   = vm1->vm_map.vm_caprev_st;
+	vm2->vm_map.vm_caprev_sh   = vm1->vm_map.vm_caprev_sh;
+	vm2->vm_map.vm_caprev_shva = vm1->vm_map.vm_caprev_shva;
+#endif
+
 	vm_map_lock(old_map);
 	if (old_map->busy)
 		vm_map_wait_busy(old_map);
diff --git a/sys/vm/vm_map.h b/sys/vm/vm_map.h
index 915d3e79e8be..e1c072ff19b1 100644
--- a/sys/vm/vm_map.h
+++ b/sys/vm/vm_map.h
@@ -71,6 +71,7 @@
 #include <sys/lock.h>
 #include <sys/sx.h>
 #include <sys/_mutex.h>
+#include <sys/condvar.h>
 
 /*
  *	Types defined:
@@ -200,6 +201,12 @@ struct vm_map {
 	struct vm_map_entry header;	/* List of entries */
 	struct sx lock;			/* Lock for map data */
 	struct mtx system_mtx;
+#ifdef CHERI_CAPREVOKE
+	struct cv vm_caprev_cv;         /* (c) Cap. rev. is single file */
+	uint64_t vm_caprev_st;          /* Capability revocation state */
+	vm_object_t vm_caprev_sh;       /* My caprevoke shadow object */
+	vm_offset_t vm_caprev_shva;     /* caprevoke shadow posn. in map */
+#endif
 	int nentries;			/* Number of entries */
 	vm_size_t size;			/* virtual size */
 	u_int timestamp;		/* Version number */
@@ -446,6 +453,7 @@ vm_map_entry_read_succ(void *token, struct vm_map_entry *const clone,
 #ifdef _KERNEL
 boolean_t vm_map_check_protection (vm_map_t, vm_offset_t, vm_offset_t, vm_prot_t);
 vm_map_t vm_map_create(pmap_t, vm_offset_t, vm_offset_t);
+int vm_map_abandon_and_delete(vm_map_t, vm_offset_t, vm_offset_t);
 int vm_map_delete(vm_map_t, vm_offset_t, vm_offset_t);
 int vm_map_find(vm_map_t, vm_object_t, vm_ooffset_t, vm_offset_t *, vm_size_t,
     vm_offset_t, int, vm_prot_t, vm_prot_t, int);
@@ -506,6 +514,7 @@ int vm_map_wire_locked(vm_map_t map, vm_offset_t start, vm_offset_t end,
     int flags);
 long vmspace_swap_count(struct vmspace *vmspace);
 void vm_map_entry_set_vnode_text(vm_map_entry_t entry, bool add);
+
 #endif				/* _KERNEL */
 #endif				/* _VM_MAP_ */
 // CHERI CHANGES START
diff --git a/sys/vm/vm_mmap.c b/sys/vm/vm_mmap.c
index 75a40f74af54..f45826bbb09a 100644
--- a/sys/vm/vm_mmap.c
+++ b/sys/vm/vm_mmap.c
@@ -128,6 +128,9 @@ SYSCTL_INT(_vm, OID_AUTO, imply_prot_max, CTLFLAG_RWTUN, &imply_prot_max, 0,
 static int log_wxrequests = 0;
 SYSCTL_INT(_vm, OID_AUTO, log_wxrequests, CTLFLAG_RWTUN, &log_wxrequests, 0,
     "Log requests for PROT_WRITE and PROT_EXEC");
+static int abandon_on_munmap = 1;
+SYSCTL_INT(_vm, OID_AUTO, abandon_on_munmap, CTLFLAG_RWTUN, &abandon_on_munmap, 0,
+    "Add abandoned entries on munmap(2)");
 #if __has_feature(capabilities)
 SYSCTL_DECL(_security_cheri);
 SYSCTL_NODE(_security_cheri, OID_AUTO, mmap, CTLFLAG_RW, 0, "mmap");
@@ -1101,7 +1104,10 @@ kern_munmap(struct thread *td, uintptr_t addr0, size_t size)
 		}
 	}
 #endif
-	vm_map_delete(map, addr, addr + size);
+	if (abandon_on_munmap)
+		vm_map_abandon_and_delete(map, addr, addr + size);
+	else
+		vm_map_delete(map, addr, addr + size);
 
 #ifdef HWPMC_HOOKS
 	if (__predict_false(pmc_handled)) {
@@ -1473,6 +1479,21 @@ kern_mincore(struct thread *td, uintptr_t addr0, size_t len,
 				    pmap_is_referenced(m) ||
 				    (m->a.flags & PGA_REFERENCED) != 0)
 					mincoreinfo |= MINCORE_REFERENCED_OTHER;
+#ifdef MINCORE_MAYHAVECAP
+				/*
+				 * The pmap may have told us that this
+				 * particular mapping is already capdirty,
+				 * and if so don't bother with the more
+				 * elaborate probes and especially not with
+				 * the expensive pmap_tc_capdirty.
+				 */
+				if ((mincoreinfo & MINCORE_MAYHAVECAP) != 0 ||
+					((m->a.flags & PGA_CAPSTORED) != 0) ||
+					((m->flags & VPO_PASTCAPSTORE) != 0) ||
+					pmap_tc_capdirty(m) ||
+					((m->a.flags & PGA_CAPSTORED) != 0))
+					mincoreinfo |= MINCORE_MAYHAVECAP;
+#endif
 			}
 			if (object != NULL)
 				VM_OBJECT_WUNLOCK(object);
@@ -2198,3 +2219,19 @@ vm_mmap_to_errno(int rv)
 //   "change_comment": ""
 // }
 // CHERI CHANGES END
+
+/* This is almost surely the wrong place for this */
+int
+sys_caprevoke(struct thread *td, struct caprevoke_args *uap)
+{
+	return ENOSYS;
+}
+int
+sys_caprevoke_shadow(struct thread *td, struct caprevoke_shadow_args *uap)
+{
+	return ENOSYS;
+}
+int sys_caprevoke_entire_shadow_cap(struct thread *td, struct caprevoke_entire_shadow_cap_args *uap)
+{
+	return ENOSYS;
+}
diff --git a/sys/vm/vm_object.c b/sys/vm/vm_object.c
index 1cc1221073ff..1690659b6994 100644
--- a/sys/vm/vm_object.c
+++ b/sys/vm/vm_object.c
@@ -1391,6 +1391,21 @@ vm_object_shadow(vm_object_t *object, vm_ooffset_t *offset, vm_size_t length,
 		VM_OBJECT_WUNLOCK(result);
 	}
 
+#if defined(OBJ_NOSTORETAGS) && defined(OBJ_NOLOADTAGS)
+	/*
+	 * XXX CHERI: This does not feel like the right place to do this,
+	 * and yet here we are.
+	 *
+	 * When shadowing a DEFAULT object type, if that object is marked
+	 * with tag-inhibit bits, then so should the shadow-casting object.
+	 * However, when shadowing non-DEFAULT objects, we often want to
+	 * permit tag stores, so don't inherit the inhibits.
+	 */
+	if (source->type == OBJT_DEFAULT)
+		result->flags |= source->flags
+				& (OBJ_NOLOADTAGS | OBJ_NOSTORETAGS);
+#endif
+
 	/*
 	 * Return the new things
 	 */
diff --git a/sys/vm/vm_page.c b/sys/vm/vm_page.c
index 1c6a1515e047..4f27bdb5a0d3 100644
--- a/sys/vm/vm_page.c
+++ b/sys/vm/vm_page.c
@@ -1796,6 +1796,17 @@ vm_page_replace_hold(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex,
 	 */
 	if (pmap_page_is_write_mapped(mnew))
 		vm_object_set_writeable_dirty(object);
+
+#ifdef PGA_CAPSTORED
+	/*
+	 * Copy across capability tracking flags
+	 */
+	if (mold->a.flags & PGA_CAPSTORED)
+		vm_page_capdirty(mnew);
+	if (mold->oflags & VPO_PASTCAPSTORE)
+		mnew->oflags |= VPO_PASTCAPSTORE;
+#endif
+
 	dropped = vm_page_drop(mold, VPRC_OBJREF) == VPRC_OBJREF;
 	vm_page_xunbusy(mold);
 
diff --git a/sys/vm/vm_page.h b/sys/vm/vm_page.h
index fd1ebc470ca0..04f06dfb5c85 100644
--- a/sys/vm/vm_page.h
+++ b/sys/vm/vm_page.h
@@ -295,6 +295,9 @@ struct vm_page {
 #define	VPO_SWAPSLEEP	0x02		/* waiting for swap to finish */
 #define	VPO_UNMANAGED	0x04		/* no PV management for page */
 #define	VPO_SWAPINPROG	0x08		/* swap I/O in progress on page */
+#if __has_feature(capabilities)
+#define	VPO_PASTCAPSTORE 0x10	/* This page had capabilities in the past */
+#endif
 
 /*
  * Busy page implementation details.
@@ -431,6 +434,13 @@ extern struct mtx_padalign pa_lock[];
  * PGA_SWAP_FREE is used to defer freeing swap space to the pageout daemon
  * when the context that dirties the page does not have the object write lock
  * held.
+ *
+ * PGA_CAPSTORED indicates that a capability was written to this page since
+ * the last time this bit (and the underlying architectural permission) was
+ * cleared.  No locks are required to update this bit; it may be set by the
+ * MD layer arbitrarily and cleared by the MI layer as desired.  The MI
+ * layer must call pmap_sync_capdirty with threads stopped if it expects an
+ * accurate view.
  */
 #define	PGA_WRITEABLE	0x0001		/* page may be mapped writeable */
 #define	PGA_REFERENCED	0x0002		/* page has been referenced */
@@ -442,6 +452,9 @@ extern struct mtx_padalign pa_lock[];
 #define	PGA_NOSYNC	0x0080		/* do not collect for syncer */
 #define	PGA_SWAP_FREE	0x0100		/* page with swap space was dirtied */
 #define	PGA_SWAP_SPACE	0x0200		/* page has allocated swap space */
+#if __has_feature(capabilities)
+#define	PGA_CAPSTORED	0x0400
+#endif
 
 #define	PGA_QUEUE_OP_MASK	(PGA_DEQUEUE | PGA_REQUEUE | PGA_REQUEUE_HEAD)
 #define	PGA_QUEUE_STATE_MASK	(PGA_ENQUEUED | PGA_QUEUE_OP_MASK)
@@ -833,6 +846,30 @@ vm_page_aflag_set(vm_page_t m, uint16_t bits)
 	atomic_set_32(addr, val);
 }
 
+#if 0
+/*
+ * Atomically read and clear some bits in a page's aflags field.  Unlike
+ * vm_page_aflag_clear, this reports the contents of the aflags field before
+ * mutation, allowing for a race-free observation and reset of status.
+ *
+ * This used to be used with capability revocation, but is now unused.
+ *
+ */
+static inline int
+vm_page_aflag_xclear_acq(vm_page_t m, uint16_t bits)
+{
+	uint32_t *addr, n, o;
+
+	addr = (void *)&m->aflags;
+	o = *addr;
+	do {
+		n = o & ~(bits << VM_PAGE_AFLAG_SHIFT);
+	} while (!atomic_fcmpset_acq_32(addr, &o, n));
+
+	return (o >> VM_PAGE_AFLAG_SHIFT) & 0xFFFF;
+}
+#endif
+
 /*
  *	vm_page_dirty:
  *
@@ -855,6 +892,16 @@ vm_page_dirty(vm_page_t m)
 #endif
 }
 
+static __inline void
+vm_page_capdirty(vm_page_t m)
+{
+#ifdef PGA_CAPSTORED
+	vm_page_aflag_set(m, PGA_CAPSTORED);
+#else
+	(void)m;
+#endif
+}
+
 /*
  *	vm_page_undirty:
  *
diff --git a/tools/build/cross-build/include/linux/limits.h b/tools/build/cross-build/include/linux/limits.h
index e31b92c37b81..4af87e5345b7 100644
--- a/tools/build/cross-build/include/linux/limits.h
+++ b/tools/build/cross-build/include/linux/limits.h
@@ -100,10 +100,6 @@
 #warning __USE_POSIX not defined
 #endif
 
-#if defined __GNUC__ && !defined _GCC_LIMITS_H_
-#error "GCC limits not included"
-#endif
-
 #ifndef __OFF_T_MATCHES_OFF64_T
 #error "Expected 64-bit off_t"
 #endif
diff --git a/tools/cheribsdbox/Makefile b/tools/cheribsdbox/Makefile
index 45f86a7cd844..e3e0d3139c75 100644
--- a/tools/cheribsdbox/Makefile
+++ b/tools/cheribsdbox/Makefile
@@ -74,6 +74,7 @@ CRUNCH_SHLIBS+=	-pthread
 
 # ktrace:
 CRUNCH_LIBS+=	-lsysdecode
+CRUNCH_LIBS+= -lprocstat -lelf
 
 # login/su (could theoretically use static_libpam but that will probably not work)
 CRUNCH_SHLIBS+= -lpam -lbsm
@@ -216,6 +217,7 @@ CRUNCH_PROGS_usr.bin+= \
 		basename \
 		bmake \
 		bzip2 \
+		cpuset \
 		diff \
 		dirname \
 		du \
@@ -238,6 +240,7 @@ CRUNCH_PROGS_usr.bin+= \
 		mktemp \
 		nc \
 		passwd \
+		procstat \
 		resizewin \
 		sed \
 		seq \
diff --git a/usr.bin/procstat/procstat_vm.c b/usr.bin/procstat/procstat_vm.c
index aa8bc3a10096..d35a043b3546 100644
--- a/usr.bin/procstat/procstat_vm.c
+++ b/usr.bin/procstat/procstat_vm.c
@@ -53,7 +53,7 @@ procstat_vm(struct procstat *procstat, struct kinfo_proc *kipp)
 
 	ptrwidth = 2*sizeof(void *) + 2;
 	if ((procstat_opts & PS_OPT_NOHEADER) == 0)
-		xo_emit("{T:/%5s %*s %*s %3s %4s %4s %3s %3s %-5s %-2s %-s}\n",
+		xo_emit("{T:/%5s %*s %*s %5s %4s %4s %3s %3s %-5s %-2s %-s}\n",
 		    "PID", ptrwidth, "START", ptrwidth, "END", "PRT", "RES",
 		    "PRES", "REF", "SHD", "FLAG", "TP", "PATH");
 
@@ -77,8 +77,12 @@ procstat_vm(struct procstat *procstat, struct kinfo_proc *kipp)
 		    "r" : "-");
 		xo_emit("{d:write/%s}", kve->kve_protection & KVME_PROT_WRITE ?
 		    "w" : "-");
-		xo_emit("{d:exec/%s} ", kve->kve_protection & KVME_PROT_EXEC ?
+		xo_emit("{d:exec/%s}", kve->kve_protection & KVME_PROT_EXEC ?
 		    "x" : "-");
+		xo_emit("{d:rcap/%s}",
+		    kve->kve_protection & KVME_PROT_READCAPS ? "L" : "-");
+		xo_emit("{d:wcap/%s} ",
+		    kve->kve_protection & KVME_PROT_WRITECAPS ? "S" : "-");
 		xo_open_container("kve_protection");
 		xo_emit("{en:read/%s}", kve->kve_protection & KVME_PROT_READ ?
 		    "true" : "false");
@@ -86,6 +90,10 @@ procstat_vm(struct procstat *procstat, struct kinfo_proc *kipp)
 		    "true" : "false");
 		xo_emit("{en:exec/%s}", kve->kve_protection & KVME_PROT_EXEC ?
 		    "true" : "false");
+		xo_emit("{en:rcap/%s}",
+		    kve->kve_protection & KVME_PROT_READCAPS ? "true" : "false");
+		xo_emit("{en:wcap/%s}",
+		    kve->kve_protection & KVME_PROT_WRITECAPS ? "true" : "false");
 		xo_close_container("kve_protection");
 		xo_emit("{:kve_resident/%4d/%d} ", kve->kve_resident);
 		xo_emit("{:kve_private_resident/%4d/%d} ",
