Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading configuration files in linux device driver

How to read configuration files in linux device driver? Experts say that reading and writing file in kernel space is a bad practise. For firmware download we have request_firmware kernel API. Is there a linux kernel API for reading and parsing configuration files for drivers? Eg: Reading baudrate and firmware file path for a particular driver.

like image 877
Anup Warnulkar Avatar asked Oct 02 '22 04:10

Anup Warnulkar


1 Answers

Most of the times doing file i/o from kernel space is discouraged, but if you still want the way to read files from kernel space, kernel provides a good interface to open and read files from kernel. Here is an example module.

 /*
  * read_file.c - A Module to read a file from Kernel Space
  */
 #include <linux/module.h>
 #include <linux/fs.h>

 #define PATH "/home/knare/test.c"
 int mod_init(void)
 {
       struct file *fp;
       char buf[512];
       int offset = 0;
       int ret, i;


       /*open the file in read mode*/
       fp = filp_open(PATH, O_RDONLY, 0);
       if (IS_ERR(fp)) {
            printk("Cannot open the file %ld\n", PTR_ERR(fp));
            return -1;
       }

       printk("Opened the file successfully\n");
       /*Read the data to the end of the file*/
       while (1) {
            ret = kernel_read(fp, offset, buf, 512);
            if (ret > 0) {
                    for (i = 0; i < ret; i++)
                            printk("%c", buf[i]);
                    offset += ret;
            } else
                    break;
        }

       filp_close(fp, NULL);
       return 0;
  }

  void mod_exit(void)
  {

  }

  module_init(mod_init); 
  module_exit(mod_exit);

 MODULE_LICENSE("GPL");
 MODULE_AUTHOR("Knare Technologies (www.knare.org)");
 MODULE_DESCRIPTION("Module to read a file from kernel space");    

I tested this module on linux-3.2 kernel. I used printk() function to print the data, but it will not be your actual case, this is just shown as an example.

like image 168
knare Avatar answered Oct 12 '22 10:10

knare