I have a kernel module named mymodule and in it I have :
static struct file_operations my_mod_fops = {
.owner = THIS_MODULE
.write = my_write,
.open = my_open,
.unlocked_ioctl = my_ioctl,
.read = my_read,
};
all the function mapped in the previous struct were tested and they are OK.
I want to declare globally (and staticly if available) a char kernel_array[128] and I want to write a userspace application that can do this:
int main(){
char* ptr_to_kernel_arr = get_kernel_array_address();
for (int i=0 ; i<128;++i)
*(ptr_to_kernel_arr+i) = i;
return 0;
}
my difficulties are:
-
how do I get the address of
kernel_array[128]such that I can assign values from a user space application? -
how does the kernel knows to which module from its
lsmodlist holds thekernel_array -
how
mmaprelates all this scenario?
I read chapter 15 and much more material but couldn’t figure out how to do it.
all the examples I found online declare a file and share it with the kernel and user space.
You need to implement the
mmapfunction and point to it fromfile_operations.This will allow the user space to open your device, call
mmapwith the file descriptor, and get the address.Note that mmap works at page resolution. So you can’t map 128 bytes, but only multiples of 4K. You could map the 4K page(s) which contain the static buffer, but then the user process will be able to corrupt memory it shouldn’t touch, which is highly discouraged.