问题
I have written a kernel module which I'm loading on kernel 4.2.3 . I am trying to read a simple text file in my init_module which basically loads some configuration data by reading the contents of the text file. This same code works on previous versions of kernel but not on 4.2.3 Below is my code snippet for reference :
struct file* pFile = NULL;
pFile = filp_open(fileName, mode, 0);
if(pFile != NULL){
if(IS_ERR(pFile))
{
printk("<1>error %p for %s**\n", pFile, fileName);
pFile = NULL;
}
else if(pFile->f_op->read == NULL || pFile->f_op->write == NULL)
{
filp_close(pFile, 0);
pFile = NULL;
}
In my case I am getting pFile->f_op->read function pointer as NULL. This code works fine for non text files like /proc/kallsyms which I am able to open & read. Please provide me some pointers as to is this a 4.2.3 kernel specific issue, how can i workaround this in my kernel module code ? Any pointers would be very helpful.
回答1:
.read is not the only interface which can implement reading from file. Files also may use .read_iter for that.
For reading a file, instead of direct call to ->read, use
ssize_t vfs_read(struct file *file, char __user *buf, size_t count, loff_t *pos)
which takes into account every possibility.
Similarly, for writing a file
ssize_t vfs_write(struct file *file, const char __user *buf, size_t count, loff_t *pos)
should be used.
UPDATE: Since Linux kernel 4.14 for read/write files in the kernel space functions kernel_read and kernel_write should be used instead. See that my answer for more info.
Reading from file to kernel's buffer (before Linux kernel 4.14)
Because vfs_read expects buffer pointed to user-space memory (__user type attribute denotes that), passing in-kernel buffer will not work: it may cause compiler warning about inconsysency between expected and actual type of second parameter to vfs_read, and, more important, vfs_read will reject (by returning -EFAULT) buffer as pointed not to user space. But one can overcome this behaviour by changing user-space memory segment:
/*
* Assume that `kernel_buf` points to kernel's memory and has type char*.
*/
char __user *user_buf = (__force char __user *)kernel_buf; // Make compiler happy.
mm_segment_t oldfs = get_fs(); // Store current use-space memory segment.
set_fs(KERNEL_DS); // Set user-space memory segment equal to kernel's one.
vfs_read(file, user_buf, count, pos);
set_fs(oldfs); // Restore user-space memory segment after reading.
来源:https://stackoverflow.com/questions/33183923/unable-to-open-read-text-file-from-kernel-module-on-linux-kernel-version-4-2-3