5
votes

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.

1
There are many ways to configure devices, such as autoconfiguration, ioctls, or module parameters. What exactly do you want to configure? - CL.
I am developing a driver to interact with UART. Need to set baudrate and firmware file location as configurable parameters to driver module. I wanted to explore if there was a Kernel interface for this purpose. - Anup Warnulkar

1 Answers

4
votes

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.