Kernel panic in nvmap_vma_close() after another process reads NVDEC buffers (Orin NX, R39.2.1)

We hit a reproducible kernel panic in nvmap on R39.2.1 and tracked it down to a regression in nvmap_fault.c. A small change to two functions fixes it on our board. Posting the details, a repro and the patch in case anyone else runs into it, and so NVIDIA can pick it up.

The short version: if any process reads another process’s nvmap mappings (gdb, a crash reporter, anything using /proc/<pid>/mem or process_vm_readv()), the kernel panics later, when the mapping’s owner exits. Because the panic comes later, it’s hard to connect to whatever caused it.

Setup: Orin NX 16GB on a Seeed J401 dev board, L4T R39.2.1 (JetPack 7.2), kernel 6.8.12-l4t-r39.2.1-1021.21, nvmap from the same release. Yocto image on the R39.2.1 BSP. The decoder runs in a Debian 12 container under the NVIDIA container runtime.

What happens

One process decodes H.264 through libnvv4l2 and keeps its buffers mapped (VIDIOC_EXPBUF + NvBufSurfaceMap). A second process reads those mappings through /proc/<pid>/mem, which is what gdb does, and exits. At that point dmesg shows:

BUG: Bad rss-counter state mm:0000000049ad00b6 type:MM_ANONPAGES val:-18260

That’s the reader. Nothing else happens until the decoding process exits, for any reason. Then:

Unable to handle kernel paging request at virtual address ffff3d4085f35000
pc : percpu_counter_add_batch+0x24/0xec
lr : nvmap_vma_close+0x25c/0x27c [nvmap]
Call trace:
 percpu_counter_add_batch+0x24/0xec
 nvmap_vma_close+0x25c/0x27c [nvmap]
 exit_mmap+0x198/0x424
 __mmput+0x38/0x150
 mmput+0x50/0x5c
 nvmap_release+0x2fc/0x3b8 [nvmap]
 __fput+0x7c/0x2c8
 ...
 do_exit+0x300/0x998
Kernel panic - not syncing: Oops: Fatal exception

and the watchdog resets the board. We first hit it in our own application after poking at it with gdb, and it crashed a while later when the app restarted, which made it confusing to chase.

It doesn’t take much. We later hit it again without a debugger: a diagnostic script of ours scans thread stacks through /proc/<pid>/mem, and one of its reads ran into an nvmap mapping next to a stack. That was a single page (MM_ANONPAGES val:-1 when the script exited). Two hours later we rebooted the board normally, the application exited during shutdown, and the reboot turned into the same panic.

Repro

Two small programs and a test stream. nvdec-hold decodes the first second of an H.264 stream through libnvv4l2, keeps its OUTPUT and CAPTURE buffers mapped with NvBufSurfaceMap, and waits. It never touches the CAPTURE mappings itself. memread.py reads every /dmabuf: mapping of a pid through /proc/<pid>/mem and exits.

gcc -O1 -Wall -o nvdec-hold nvdec-hold.c -ldl -I/usr/src/jetson_multimedia_api/include
./nvdec-hold test-640x360.h264 &     # prints "holding pid=..."
P=$!
sudo python3 memread.py $P           # 70 dmabuf/nvmap mappings, 73448 KiB / read ok=70 err=0
dmesg | tail -1                      # BUG: Bad rss-counter state ... MM_ANONPAGES val:-N
kill $P                              # panic

The stream is 2 seconds of ffmpeg’s testsrc2, baseline profile:

ffmpeg -f lavfi -i testsrc2=size=640x360:rate=30 -t 2 -c:v libx264 -profile:v baseline -g 15 test-640x360.h264

Unpatched, this panicked the board every time we ran it, about a minute end to end. Those runs used a longer version of nvdec-hold that also exercises decoder re-init. The trimmed one below sets up the same 70 mappings and moves the RSS counters the same way, but we’ve only run it on the patched module.

nvdec-hold.c
// nvdec-hold: decode the start of an H.264 stream with NVDEC through
// libnvv4l2, keep the decoder's buffers mapped, and wait for a signal.
//
// The OUTPUT (bitstream) and CAPTURE (frame) buffers are V4L2 MMAP buffers,
// exported with VIDIOC_EXPBUF and mapped with NvBufSurfaceMap. This process
// never touches the CAPTURE mappings, so their pages are first faulted in by
// whoever reads them from outside (e.g. /proc/<pid>/mem).
//
// Build: gcc -O1 -Wall -o nvdec-hold nvdec-hold.c -ldl
//            -I/usr/src/jetson_multimedia_api/include
// Run:   ./nvdec-hold test-640x360.h264
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/videodev2.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include "nvbufsurface.h"

#define NOUT 16
#define NCAP_MAX 32
#define OUT_SIZE (2 * 1024 * 1024)

static int (*nv_open)(const char *, int, ...);
static int (*nv_ioctl)(int, unsigned long, ...);
static int (*surf_from_fd)(int, void **);
static int (*surf_map)(NvBufSurface *, int, int, NvBufSurfaceMemMapFlags);

static void *must_dlopen(const char *path, const char *name)
{
	void *h = dlopen(path, RTLD_NOW | RTLD_GLOBAL);
	if (!h)
		h = dlopen(name, RTLD_NOW | RTLD_GLOBAL);
	if (!h) {
		fprintf(stderr, "dlopen %s: %s\n", name, dlerror());
		exit(1);
	}
	return h;
}

static int xioctl(int fd, unsigned long req, void *arg, const char *what)
{
	int r = nv_ioctl(fd, req, arg);
	if (r < 0 && errno != EAGAIN)
		fprintf(stderr, "%s: %s\n", what, strerror(errno));
	return r;
}

// Export a V4L2 buffer as a dmabuf fd and map one plane of it.
static void *export_and_map(int fd, enum v4l2_buf_type type, int index, int plane, int *out_fd)
{
	struct v4l2_exportbuffer e = { .type = type, .index = index, .flags = O_CLOEXEC };
	NvBufSurface *s = NULL;

	if (plane == 0) {
		if (xioctl(fd, VIDIOC_EXPBUF, &e, "EXPBUF") < 0)
			return NULL;
		*out_fd = e.fd;
	}
	if (surf_from_fd(*out_fd, (void **)&s) < 0 || !s)
		return NULL;
	if (surf_map(s, 0, plane, NVBUF_MAP_READ_WRITE) != 0)
		return NULL;
	return s->surfaceList[0].mappedAddr.addr[plane];
}

static int capture_on;

static void capture_setup(int fd)
{
	struct v4l2_format f = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE };
	struct v4l2_control c = { .id = V4L2_CID_MIN_BUFFERS_FOR_CAPTURE };
	struct v4l2_requestbuffers rb = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE,
					  .memory = V4L2_MEMORY_MMAP };
	int t = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, n, cap_fd;

	if (xioctl(fd, VIDIOC_G_FMT, &f, "G_FMT(CAPTURE)") < 0)
		return;
	rb.count = (xioctl(fd, VIDIOC_G_CTRL, &c, "G_CTRL") < 0 ? 4 : c.value) + 4;
	if (xioctl(fd, VIDIOC_REQBUFS, &rb, "REQBUFS(CAPTURE)") < 0)
		return;
	n = rb.count > NCAP_MAX ? NCAP_MAX : rb.count;
	for (int i = 0; i < n; i++) {
		struct v4l2_plane pl[VIDEO_MAX_PLANES] = { 0 };
		struct v4l2_buffer b = { .type = t, .memory = V4L2_MEMORY_MMAP, .index = i,
					 .m.planes = pl, .length = f.fmt.pix_mp.num_planes };

		for (int p = 0; p < f.fmt.pix_mp.num_planes; p++)
			export_and_map(fd, t, i, p, &cap_fd);   // mapped, never touched
		xioctl(fd, VIDIOC_QBUF, &b, "QBUF(CAPTURE)");
	}
	xioctl(fd, VIDIOC_STREAMON, &t, "STREAMON(CAPTURE)");
	capture_on = 1;
	printf("capture %ux%u, %d buffers\n", f.fmt.pix_mp.width, f.fmt.pix_mp.height, n);
}

// Handle the resolution event, recycle decoded frames and free OUTPUT buffers.
static void service(int fd, int *queued)
{
	struct v4l2_event ev;
	struct v4l2_plane pl[VIDEO_MAX_PLANES];
	struct v4l2_buffer b;

	while (nv_ioctl(fd, VIDIOC_DQEVENT, &ev) == 0)
		if (ev.type == V4L2_EVENT_SOURCE_CHANGE && !capture_on)
			capture_setup(fd);
	while (capture_on) {
		memset(pl, 0, sizeof(pl));
		b = (struct v4l2_buffer){ .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE,
					  .memory = V4L2_MEMORY_MMAP, .m.planes = pl,
					  .length = VIDEO_MAX_PLANES };
		if (nv_ioctl(fd, VIDIOC_DQBUF, &b) < 0)
			break;
		nv_ioctl(fd, VIDIOC_QBUF, &b);
	}
	for (;;) {
		memset(pl, 0, sizeof(pl));
		b = (struct v4l2_buffer){ .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE,
					  .memory = V4L2_MEMORY_MMAP, .m.planes = pl, .length = 1 };
		if (nv_ioctl(fd, VIDIOC_DQBUF, &b) < 0)
			break;
		queued[b.index] = 0;
	}
}

int main(int argc, char **argv)
{
	void *out_addr[NOUT];
	int out_fd[NOUT], queued[NOUT] = { 0 };
	int t = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, fd;
	unsigned char *data;
	struct stat st;
	FILE *f;

	if (argc < 2) {
		fprintf(stderr, "usage: %s stream.h264\n", argv[0]);
		return 2;
	}
	f = fopen(argv[1], "rb");
	if (!f || fstat(fileno(f), &st) < 0) {
		perror(argv[1]);
		return 1;
	}
	data = malloc(st.st_size);
	if (fread(data, 1, st.st_size, f) != (size_t)st.st_size) {
		perror("read");
		return 1;
	}
	fclose(f);

	void *v4l2 = must_dlopen("/usr/lib/aarch64-linux-gnu/nvidia/libnvv4l2.so", "libnvv4l2.so");
	void *surf = must_dlopen("/usr/lib/aarch64-linux-gnu/nvidia/libnvbufsurface.so.1.0.0",
				 "libnvbufsurface.so.1.0.0");
	nv_open = dlsym(v4l2, "v4l2_open");
	nv_ioctl = dlsym(v4l2, "v4l2_ioctl");
	surf_from_fd = dlsym(surf, "NvBufSurfaceFromFd");
	surf_map = dlsym(surf, "NvBufSurfaceMap");
	if (!nv_open || !nv_ioctl || !surf_from_fd || !surf_map) {
		fprintf(stderr, "missing symbols\n");
		return 1;
	}

	fd = nv_open("/dev/nvhost-nvdec", O_RDWR | O_NONBLOCK);
	if (fd < 0)
		fd = nv_open("/dev/v4l2-nvdec", O_RDWR | O_NONBLOCK);
	if (fd < 0) {
		perror("v4l2_open");
		return 1;
	}

	struct v4l2_format fmt = { .type = t };
	fmt.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_H264;
	fmt.fmt.pix_mp.num_planes = 1;
	fmt.fmt.pix_mp.plane_fmt[0].sizeimage = OUT_SIZE;
	xioctl(fd, VIDIOC_S_FMT, &fmt, "S_FMT(OUTPUT)");
	struct v4l2_requestbuffers rb = { .count = NOUT, .type = t, .memory = V4L2_MEMORY_MMAP };
	xioctl(fd, VIDIOC_REQBUFS, &rb, "REQBUFS(OUTPUT)");
	for (int i = 0; i < NOUT; i++)
		out_addr[i] = export_and_map(fd, t, i, 0, &out_fd[i]);
	xioctl(fd, VIDIOC_STREAMON, &t, "STREAMON(OUTPUT)");
	struct v4l2_event_subscription sub = { .type = V4L2_EVENT_SOURCE_CHANGE };
	xioctl(fd, VIDIOC_SUBSCRIBE_EVENT, &sub, "SUBSCRIBE_EVENT");

	// Feed the first half of the stream, one Annex-B NAL unit per buffer.
	size_t start = (size_t)-1, nals = 0;
	for (size_t i = 0; i + 3 <= (size_t)st.st_size / 2; i++) {
		int sc = data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1;
		if (!sc && i + 3 < (size_t)st.st_size / 2)
			continue;
		size_t s = sc && i > 0 && data[i - 1] == 0 ? i - 1 : i;
		if (start != (size_t)-1) {
			int idx = -1;
			for (int tries = 0; idx < 0 && tries < 200; tries++) {
				service(fd, queued);
				for (int k = 0; k < NOUT && idx < 0; k++)
					if (!queued[k] && out_addr[k])
						idx = k;
				if (idx < 0)
					usleep(5000);
			}
			if (idx >= 0) {
				struct v4l2_plane pl[1] = { { .bytesused = s - start } };
				struct v4l2_buffer b = { .type = t, .memory = V4L2_MEMORY_MMAP,
							 .index = idx, .m.planes = pl, .length = 1 };
				memcpy(out_addr[idx], data + start, s - start);
				b.timestamp.tv_usec = ++nals;
				if (xioctl(fd, VIDIOC_QBUF, &b, "QBUF(OUTPUT)") == 0)
					queued[idx] = 1;
				usleep(2000);
			}
		}
		start = s;
		i += 2;
	}
	for (int i = 0; i < 50; i++) {
		service(fd, queued);
		usleep(2000);
	}

	printf("holding pid=%d (%zu NAL units fed)\n", getpid(), nals);
	fflush(stdout);
	pause();
	return 0;
}

memread.py
# Read every dmabuf/nvmap-backed mapping of <pid> through /proc/<pid>/mem.
import sys
pid = sys.argv[1]
regions = []
for l in open(f"/proc/{pid}/maps"):
    p = l.split()
    name = p[5] if len(p) > 5 else ""
    if "dmabuf" in name or "nvmap" in name or "dma_heap" in name:
        a, b = (int(x, 16) for x in p[0].split("-"))
        regions.append((a, b, p[1], name))
print(f"{len(regions)} dmabuf/nvmap mappings, {sum(b - a for a, b, _, _ in regions) // 1024} KiB")
ok = err = 0
with open(f"/proc/{pid}/mem", "rb", buffering=0) as mem:
    for a, b, perm, name in regions:
        try:
            mem.seek(a); mem.read(b - a); ok += 1
        except OSError as e:
            err += 1
print(f"read ok={ok} err={err}")

One more data point: if the owning process touches its own pages first (we tried an NvBufSurfaceCreate buffer that the holder wrote itself), the read doesn’t trigger anything.

Root cause

In drivers/video/tegra/nvmap/nvmap_fault.c, nvmap_vma_fault() does this (lines 232-235):

if (priv->handle->anon_count != 0 && current->mm != NULL) {
	nvmap_add_mm_counter(current->mm, MM_ANONPAGES, -1);
	priv->map_rss_count++;
	priv->mm = current->mm;
}

and nvmap_vma_close() undoes it later (line 150):

nvmap_add_mm_counter(priv->mm, MM_ANONPAGES, priv->map_rss_count);

This assumes that whoever faults a page in is the process that owns the mapping. That’s normally true, but not when someone else reads the memory. With /proc/<pid>/mem, ptrace or process_vm_readv(), the fault runs in the reader’s context, so current->mm is the reader’s mm, not vma->vm_mm. So:

  1. The -1 lands on the reader. The kernel meanwhile charges the page to the owner as a file page, as it should. That’s why the reader dies with exactly -18260 and the owner’s RssFile grows by the same amount.
  2. priv->mm now points at the reader’s mm, and nvmap holds no reference on it.
  3. The reader exits and its mm is freed. percpu_counter_destroy_many() sets the counter’s per-CPU pointer to NULL.
  4. The owner exits, nvmap_vma_close() adds to the counter through the stale pointer, and the kernel panics.

The oops registers confirm it. The faulting instruction in percpu_counter_add_batch is the per-CPU load, x4 (the counters pointer) is 0, and the fault address is exactly x5 (this CPU’s per-CPU offset).

What broke it

This code isn’t in R36.4.4 or R38.2.1. It showed up in R36.5.0 and R39.x with two commits for Bug 5222690:

  • “video: tegra: nvmap: Account NvMap memory for OOM Decisions” (Change-Id I3fa9b76ec9fc8d7f805111cb96e11e2ab1db42ce): charges nvmap allocations to the allocator’s MM_ANONPAGES so the OOM killer can see them. That’s a reasonable goal.
  • “video: tegra: nvmap: Avoid double updation of RSS counter” (Change-Id I77972185f20d9d710571cc07ae1c5188060bfa1f): adds the per-fault -1 so a mapped page isn’t counted twice (anon from the allocation plus file from the mapping). It uses current->mm and caches it in priv->mm. This is the one that introduced the bug.

We couldn’t find any later change to this code in the public sources up to R39.2.

The fix

Charge the mapping’s own mm instead of whoever happened to fault. vma->vm_mm is always valid in ->fault and ->close, and it’s the mm the kernel actually charged the page to, so the offset lands where it’s supposed to. Then nothing needs to be cached at all. These buffers are mapped VM_DONTCOPY (nvmap_dmabuf.c:419), so every VMA sharing a priv has the same vm_mm.

--- a/drivers/video/tegra/nvmap/nvmap_fault.c
+++ b/drivers/video/tegra/nvmap/nvmap_fault.c
@@ static void nvmap_vma_close(struct vm_area_struct *vma)
 	mutex_lock(&priv->vma_lock);
-	if (priv->mm != NULL && h->anon_count != 0) {
-		nvmap_add_mm_counter(priv->mm, MM_ANONPAGES, priv->map_rss_count);
+	if (priv->map_rss_count != 0 && h->anon_count != 0) {
+		nvmap_add_mm_counter(vma->vm_mm, MM_ANONPAGES, priv->map_rss_count);
 		priv->map_rss_count = 0;
-		priv->mm = NULL;
 	}
 	mutex_unlock(&priv->vma_lock);
@@ static vm_fault_t nvmap_vma_fault(struct vm_fault *vmf)
 		mutex_lock(&priv->vma_lock);
-		if (priv->handle->anon_count != 0 && current->mm != NULL) {
-			nvmap_add_mm_counter(current->mm, MM_ANONPAGES, -1);
+		if (priv->handle->anon_count != 0) {
+			nvmap_add_mm_counter(vma->vm_mm, MM_ANONPAGES, -1);
 			priv->map_rss_count++;
-			priv->mm = current->mm;
 		}
 		mutex_unlock(&priv->vma_lock);

priv->mm is then dropped from the struct, since nothing else uses it.

We built the patched nvmap into our image (the same R39.2.1 sources plus this diff) and installed it on the board:

Unpatched Patched
Reader exits Bad rss-counter ... MM_ANONPAGES val:-18260 nothing logged
Holder exits oops in nvmap_vma_close, panic, watchdog reset exits cleanly, nothing logged
Runs panicked every time 5 of 5 clean (4 with the original repro, 1 with nvdec-hold), same boot throughout

In both cases the read itself behaves the same: all 70 mappings come back, and the holder’s RssFile goes from about 10.7 MB to 83.7 MB as the pages get mapped in.

thanks for reporting this issue, let me arrange sources for checking, and having code-review internally.