1

I want to read file from kernel module which contains some parameters

I used the following source code

#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/version.h>
#include <linux/fs.h>      // Needed by filp

#include <linux/rbtree.h>
#include <linux/time.h>
#include <linux/atomic.h>
#include <linux/proc_fs.h>
#include <linux/jiffies.h>

#include <net/net_namespace.h>
#include <net/netns/generic.h>

#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/icmp.h>
#include <linux/inetdevice.h>
#include <linux/if_ether.h>



int init_module(void)
{
    // Create variables
    struct file *f;
    char buf[128];
    mm_segment_t fs;
    int i;
    unsigned long long offset = 0;
    // Init the buffer with 0
    for(i=0;i<128;i++)
        buf[i] = 0;
    // To see in /var/log/messages that the module is operating
    // I am using Fedora and for the test I have chosen following file
    // Obviously it is much smaller than the 128 bytes, but hell with it =)
    f = filp_open("/etc/lsb-release", O_RDONLY, 0);
    if(f == NULL)
        printk(KERN_ALERT "filp_open error!!.\n");
    else{
        // Get current segment descriptor
        fs = get_fs();
        // Set segment descriptor associated to kernel space
        set_fs(get_ds());
        // Read the file

        f->f_op->read(f, buf, 128, &f->f_pos);

        // Restore segment descriptor
        set_fs(fs);

        // See what we read from file
        printk(KERN_INFO "buf:%s\n",buf);
    }

    filp_close(f,NULL);
    return 0;
}

void cleanup_module(void)
{
    printk(KERN_INFO "My module is unloaded\n");
}

But this function crash. I debug it and I found that f->f_op->read is NULL

My kernel version is 4.15 and my ubuntu is 16

What I am missing?

Why f->f_op->read is NULL ?

How to read some parameter from user space in the load of module ? I think better to use file. If so, How to read file in kernel ?

MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • 2
    Does this answer your question? [unable to open / read text file from kernel module on linux kernel version 4.2.3](https://stackoverflow.com/questions/33183923/unable-to-open-read-text-file-from-kernel-module-on-linux-kernel-version-4-2-3) – dragosht Feb 06 '20 at 09:48
  • Maybe this is also helpful: https://stackoverflow.com/questions/1184274/read-write-files-within-a-linux-kernel-module – dragosht Feb 06 '20 at 09:50
  • @dragosht yes in fact I have to use kernel_read() for my kernel version. Thanks ! Please feel free to answer it. And I will upvote – MOHAMED Feb 06 '20 at 10:05
  • You should read that file in user space and pass module parameters to the module if needed. For bigger chunk of data look at how firmware loading work for other modules. – Goswin von Brederlow Feb 06 '20 at 12:13

0 Answers0