2022-06-23

Linux kernel module reference counter is always zero

I am implementing a kernel module that exposes some data to userspase using mmap interface.

I create a file in /proc file system passing struct file_operations with pointers to needed functions:

static struct file_operations module_file_ops = {
    .owner = THIS_MODULE,
    .open = module_open,
    .mmap = module_mmap
};

proc_create(THIS_MODULE->name, 0444, NULL, &module_file_ops);

Userspace application is able to open and read from the file (mmap contents) as expected.

When I do lsof I see the file is opened by the userspace app.

However, lsmod always gives zero as usage counter despite I set .owner to THIS_MODULE, so that I can easily remove the module with rmmod and lead the system to crash.

Please advise.


module.c

#include <linux/fs.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/proc_fs.h>

static struct proc_dir_entry *proc_file;

static const struct file_operations test_file_ops = {
    .owner = THIS_MODULE
};

static int __init initialize(void) {
    int error = 0;

    proc_file = proc_create(THIS_MODULE->name, 0444, NULL, &test_file_ops);
    if (!proc_file) {
        error = -EIO;
    }

    return error;
}

static void __exit teardown(void) {
    proc_remove(proc_file);
}

module_init(initialize);
module_exit(teardown);

Makefile

obj-m += test.o
test-objs := module.o

CC=gcc
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
EXTRA_CFLAGS=-I/usr/include -I/usr/include/x86_64-linux-gnu

all:
        $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules


No comments:

Post a Comment