I want to use serial port in kernel space, I have found some code which was in user space, I tried to convert the codes to work in kernel space...
This is my code
#include <linux/termios.h>
#include <linux/unistd.h>
#include <linux/signal.h>
#include <linux/fcntl.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
struct file * fp;
...
struct termios termAttr;
struct sigaction saio;
oldfs = get_fs();
set_fs(KERNEL_DS);
fp = filp_open("/dev/ttymxc0", O_RDWR | O_NOCTTY | O_NDELAY,0);
if(fp == NULL)
printk(KERN_ALERT "Serial openning error!!.\n");
else{
saio.sa_handler = signal_handler_IO;
saio.sa_flags = 0;
saio.sa_restorer = NULL;
sigaction(SIGIO,&saio,NULL);
fcntl(fp, F_SETFL, O_NDELAY|FASYNC);
fcntl(fp, F_SETOWN, THIS_MODULE);
tcgetattr(fp,&termAttr);
cfsetispeed(&termAttr,B115200);
cfsetospeed(&termAttr,B115200);
termAttr.c_cflag &= ~PARENB;
termAttr.c_cflag &= ~CSTOPB;
termAttr.c_cflag &= ~CSIZE;
termAttr.c_cflag |= CS8;
termAttr.c_cflag |= (CLOCAL | CREAD);
termAttr.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
termAttr.c_iflag &= ~(IXON | IXOFF | IXANY);
termAttr.c_oflag &= ~OPOST;
tcsetattr(fp,TCSANOW,&termAttr);
printk(KERN_ALERT "Serial configured....\n");
vfs_write(fp, "HI",2, NULL);
filp_close(fp, NULL);
set_fs(oldfs);
}
while compiling, I got following errors:
note: each undeclared identifier is reported only once for each function it appears in
error: implicit declaration of function 'sigaction' [-Werror=implicit-function-declaration]
sigaction(SIGIO,&saio,NULL);
^
error: implicit declaration of function 'fcntl' [-Werror=implicit-function-declaration]
fcntl(fp, F_SETFL, O_NDELAY|FASYNC);
^
error: implicit declaration of function 'tcgetattr' [-Werror=implicit-function-declaration]
tcgetattr(fp,&termAttr);
^
error: implicit declaration of function 'cfsetispeed' [-Werror=implicit-function-declaration]
cfsetispeed(&termAttr,B115200);
^
error: implicit declaration of function 'cfsetospeed' [-Werror=implicit-function-declaration]
cfsetospeed(&termAttr,B115200);
^
error: implicit declaration of function 'tcsetattr' [-Werror=implicit-function-declaration]
I am cross compiling this driver and I already compiled Linux source, I have searched for this functions in my Linux source code but I did not find any of this functions! what should I use instead of this functions?
Edit 1:
I have changed my code into this:
//serial
struct ktermios termAttr;
struct sigaction saio;
loff_t pos =0;
struct tty_struct *tty;
serialfp = file_open("/dev/ttyS1", O_RDWR | O_NOCTTY | O_NDELAY,0);
if(serialfp == NULL)
printk(KERN_ALERT "ARIO RMG Serial openning error!!.\n");
else{
tty = (struct tty_struct *)serialfp->private_data;
tty_termios_encode_baud_rate(&tty->termios,B115200,B115200 );
printk(KERN_ALERT "ARIO RMG Serial configured....\n");
pos = serialfp->f_pos;
file_write(serialfp, "\n\n\n\n\nThis is first test of sending serial data from kernel module\n\n\n\n\n",70,&pos);
serialfp->f_pos=pos;
serial_thread_condition = 1;
mutex_init(&serial_mutex);
task1 = kthread_create(&thread_function, (void *)&pid1, "pradeep");
wake_up_process(task1);
printk(KERN_ALERT "data received:%s\n\n\n\n\n\n\n\n",rmg_drvstruct[0].RxSerial);
}
I am able to send data into serial port now, I also created a thread to read data from serial port. with following code:
static int thread_function(void *data){
loff_t pos;
while(serial_thread_condition){
mutex_lock(&serial_mutex);
if (IS_ERR(serialfp)) {
mutex_unlock(&serial_mutex);
serial_thread_condition=0;
return 0;
}
pos = serialfp->f_pos;
printk(KERN_INFO "try to read from serial\r\n");
if(file_read(serialfp, rmg_drvstruct[0].RxSerial, 100, &pos)>0)
{
printk(KERN_INFO "Data: %s\r\n", rmg_drvstruct[0].RxSerial);
serialfp->f_pos = pos;
serial_thread_condition = 0;
mutex_unlock(&serial_mutex);
break;
}
mutex_unlock(&serial_mutex);
}
}
int file_read(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size)
{
mm_segment_t oldfs;
int ret;
oldfs = get_fs();
set_fs(get_ds());
ret = vfs_read(file, data, size, &offset);
set_fs(oldfs);
return ret;
}
But I got nothing in serial port in my thread, I wanted to use interrupts for new received bytes, but irq_request() function makes kernel panic and computer freezes out, so what should I do to properly receive data with interrupt or a thread?
So after a while searching and testing I used this code to communicate with serial port, But I have changed a bit of it.
Please read my edit before using this code
I used a thread to read from serial port, cause using interrupts (request_irq) makes my kernel to shoot himself in the head!
So this is my code for anyone who might want to use serial port in kernel module.
#include <linux/tty.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include<linux/mutex.h>
MODULE_LICENSE("GPL");
struct file * serialfp;
struct task_struct *task1;
int pid1 = 1;
....
static struct file *file_open(const char *path, int flags, int rights)
{
struct file *filp = NULL;
mm_segment_t oldfs;
int err = 0;
oldfs = get_fs();
set_fs(get_ds());
filp = filp_open(path, flags, rights);
set_fs(oldfs);
if (IS_ERR(filp)) {
err = PTR_ERR(filp);
return NULL;
}
return filp;
}
static void file_close(struct file *file)
{
filp_close(file, NULL);
}
static int file_read(struct file *file, unsigned long long *offset, unsigned char *data, unsigned int size)
{
mm_segment_t oldfs;
int ret;
oldfs = get_fs();
set_fs(get_ds());
ret = vfs_read(file, data, size, offset);
set_fs(oldfs);
return ret;
}
static int file_write(struct file *file, unsigned long long *offset, unsigned char *data, unsigned int size)
{
mm_segment_t oldfs;
int ret;
oldfs = get_fs();
set_fs(get_ds());
ret = vfs_write(file, data, size, offset);
set_fs(oldfs);
return ret;
}
int file_sync(struct file *file)
{
vfs_fsync(file, 0);
return 0;
}
static int thread_function(void *data){
loff_t pos;
int len;
while(serial_thread_condition){
mutex_lock(&serial_mutex);
if (IS_ERR(serialfp)|| serial_thread_condition==0) {
printk(KERN_INFO "serial reading thread has been terminated.\r\n");
mutex_unlock(&serial_mutex);
serial_thread_condition=0;
return 0;
}
pos = serialfp->f_pos;
if((len=file_read(serialfp,&pos, rmg_drvstruct[0].RxSerial, 100))>0){
printk(KERN_INFO "Received data : %s\r\n", rmg_drvstruct[0].RxSerial);
serialfp->f_pos = pos;
file_write(serialfp,&pos,"I have received:",16);
file_write(serialfp,&pos, rmg_drvstruct[0].RxSerial,len);
serialfp->f_pos = pos;
}
file_sync(serialfp);
mutex_unlock(&serial_mutex);
mdelay(5);
}
}
so my device opening function is like:
static int device_open(struct inode *inode, struct file *file){
loff_t pos =0;
struct tty_struct *tty;
...
serialfp = file_open("/dev/ttyS1", O_RDWR | O_NOCTTY | O_NDELAY ,0);
if(serialfp == NULL)
printk(KERN_ALERT "ARIO RMG Serial openning error!!.\n");
else{
tty = (struct tty_struct *)serialfp->private_data;
tty_termios_encode_baud_rate(&tty->termios,B115200,B115200 );
printk(KERN_ALERT "Serial configured....\n");
pos = serialfp->f_pos;
file_write(serialfp,&pos,"\n\n\n\n\nThis is first test of sending serial data from kernel module\n\n\n\n\n",70);
serialfp->f_pos=pos;
file_sync(serialfp);
serial_thread_condition = 1;
mutex_init(&serial_mutex);
task1 = kthread_create(&thread_function, (void *)&pid1, "pradeep");
wake_up_process(task1);
}
...
}
and closing module function:
static int device_release(struct inode *inode, struct file *file){
...
if (!IS_ERR(serialfp)) {
mutex_lock(&serial_mutex);
printk(KERN_INFO " Trying to realease serail thread");
if(serial_thread_condition==1){
int i=0;
while(i++<256)serial_thread_condition =0;
}
printk(KERN_INFO " serial thread released.");
file_close(serialfp);
mutex_unlock(&serial_mutex);
}
....
}
Thanks to 0andriy for helping and dmeister for his answer in that link.
EDIT:
So I did what I wanted in kernel, opening a file in kernel space regardless of any suggestions not to do so.
But I needed to open a file in kernel module...
So why every body said don't open user space files in kernel?
In these two articles there are some reasons to not using files in kernel , this link and this link.
there are some reasons like:
1- kernel module may lose CPU at any time and the file which is opened by kernel may close.
2- I am not sure really about this, But they said files needs to have a process to stay opened but kernel module itself is not a process(maybe I am wrong!).
3- If any error happens while working with files(open/close/read/write), kernel module can not handle it and causes kernel panic...
I have experienced a lot of kernel panics only while opening and closing the file I wanted to work with. These are some of reasons why you should not use files in kernel modules, So as every body said before "If you need to use files in kernel module you probably did something wrong in your code!"
Related
I am trying to implement simple debugfs interface module. Code attached for reference. To write data I'm using echo 'string' > /sys/kernel/debug/debugexercise/text and its working as expected data being copied into kernel buffer.
But when I try to retrieve data back using cat command i.e. cat /sys/kernel/debug/debugexercise/text , its not printing any data on terminal.
I have also tried using simple_read_from_buffer instead of copy_to_user but got the same result.
Anybody have idea what is the problem with this code. 4.13.0-45-generic is the kernel version on my system.
#include <linux/module.h>
#include <linux/debugfs.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#define LEN 512
static struct dentry *test_dir;
static struct dentry *test_file;
static char ker_buf[LEN] ;
/* read file operation */
static ssize_t test_read(struct file *fp, char __user *user_buffer, size_t count, loff_t *position){
printk(KERN_NOTICE "debugfs_read called, count %d\n", count);
return copy_to_user(user_buffer, ker_buf, LEN);
}
static ssize_t test_write(struct file *fp, const char __user *user_buffer, size_t count, loff_t *position){
printk(KERN_NOTICE "debugfs_write called, count %d\n",count);
if(count > LEN )
return -EINVAL;
copy_from_user(ker_buf, user_buffer, count);
printk(KERN_NOTICE "write buffer complete: %s\n",ker_buf);
return count;
}
static struct file_operations fops_debug = {
.read = test_read,
.write = test_write,
};
static int __init init_debug(void)
{
test_dir = debugfs_create_dir("debugexercise", NULL);
if(NULL == test_dir){
printk(KERN_ERR "debugfs_create_dir() Failed\n");
return -1;
}
else
printk(KERN_NOTICE "debugexercise created\n");
test_file = debugfs_create_file("text", 0644, test_dir, NULL, &fops_debug);
if(NULL == test_file){
printk(KERN_ERR "debugfs_create_file() Failed\n");
debugfs_remove(test_dir);
return -1;
}
else
printk(KERN_NOTICE "text under debugexercise created\n");
return 0;
}
static void __exit exit_debug(void)
{
printk(KERN_NOTICE "removing module\n");
debugfs_remove(test_file);
debugfs_remove(test_dir);
}
module_init(init_debug)
module_exit(exit_debug)
MODULE_LICENSE("GPL");
copy_to_user returns the number of bytes that could not be copied. On success, this will be zero. Hence, the cat displays 0 characters. I believe you should do:
if (copy_to_user(user_buffer, ker_buf, LEN)){
printk(KERN_INFO "copy to user failed.\n");
return -EINVAL; /* For instance ... */
}
return LEN;
I am trying to implement a system call interception for sys_open() call via kernel module and for that I have defined a miscellaneous device driver MyDevice which can be inserted as kernel module. Below is the code for my kernel module:
#include <linux/version.h>
#include <linux/module.h>
#include <linux/miscdevice.h>
#include <linux/fs.h>
#include <linux/highmem.h>
#include <asm/unistd.h>
MODULE_LICENSE("GPL");
// IOCTL commands
#define IOCTL_PATCH_TABLE 0x00000001
#define IOCTL_FIX_TABLE 0x00000004
//Global variables
int in_use = 0; //set to 1 in open handler and reset to zero in release handler
int is_set = 0; // flag to detect system call interception
unsigned long *sys_call_table = (unsigned long*)0xffffffff81801400; //hard coded address of sys_call_table from /boot/System.map
//function pointer to original sys_open
asmlinkage int (*real_open)(const char* __user, int, int);
//Replacement of original call with modified system call
asmlinkage int custom_open(const char* __user file_name, int flags, int mode)
{
printk("interceptor: open(\"%s\", %X, %X)\n", file_name,flags,mode);
return real_open(file_name,flags,mode);
}
/*
Make the memory page writable
This is little risky as directly arch level protection bit is changed
*/
int make_rw(unsigned long address)
{
unsigned int level;
pte_t *pte = lookup_address(address, &level);
if(pte->pte &~ _PAGE_RW)
pte->pte |= _PAGE_RW;
return 0;
}
/* Make the page write protected */
int make_ro(unsigned long address)
{
unsigned int level;
pte_t *pte = lookup_address(address, &level);
pte->pte = pte->pte &~ _PAGE_RW;
return 0;
}
/* This function will be invoked each time a user process attempts
to open my device. You should keep in mind that the prototype
of this function may change along different kernel versions. */
static int my_open(struct inode *inode, struct file *file)
{
/*Do not allow multiple processes to open this device*/
if(in_use)
return -EBUSY;
in_use++;
printk("MyDevice opened\n");
return 0;
}
/* This function, in turn, will be called when a process closes our device */
static int my_release(struct inode *inode, struct file *file)
{
in_use--;
printk("MyDevice closed\n");
return 0;
}
/*This static function handles ioctl calls performed on MyDevice*/
static int my_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
int retval = 0;
switch(cmd)
{
case IOCTL_PATCH_TABLE:
make_rw((unsigned long)sys_call_table);
real_open = (void*)*(sys_call_table + __NR_open);
*(sys_call_table + __NR_open) = (unsigned long)custom_open;
make_ro((unsigned long)sys_call_table);
is_set=1;
break;
case IOCTL_FIX_TABLE:
make_rw((unsigned long)sys_call_table);
*(sys_call_table + __NR_open) = (unsigned long)real_open;
make_ro((unsigned long)sys_call_table);
is_set=0;
break;
default:
printk("sys_open not executed\n");
break;
}
return retval;
}
//populate data struct for file operations
static const struct file_operations my_fops = {
.owner = THIS_MODULE,
.open = &my_open,
.release = &my_release,
.unlocked_ioctl = (void*)&my_ioctl,
.compat_ioctl = (void*)&my_ioctl
};
//populate miscdevice data structure
static struct miscdevice my_device = {
MISC_DYNAMIC_MINOR,
"MyDevice",
&my_fops
};
static int __init init_my_module(void)
{
int retval;
printk(KERN_INFO "Inside kernel space\n");
retval = misc_register(&my_device);
return retval;
}
static void __exit cleanup_my_module(void)
{
if (is_set)
{
make_rw((unsigned long)sys_call_table);
*(sys_call_table + __NR_open) = (unsigned long)real_open;
make_ro((unsigned long)sys_call_table);
}
misc_deregister(&my_device);
printk(KERN_INFO "Exiting kernel space\n");
return;
}
module_init(init_my_module);
module_exit(cleanup_my_module);
The code for my test file is as follows:
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
/* Define ioctl commands */
#define IOCTL_PATCH_TABLE 0x00000001
#define IOCTL_FIX_TABLE 0x00000004
int main(void)
{
int device = open("/dev/MyDevice", O_RDWR);
printf("%d\n",device);
ioctl(device, IOCTL_PATCH_TABLE);
sleep(2);
ioctl(device, IOCTL_FIX_TABLE);
close(device);
return 0;
}
The problem is that in my test file open("/dev/MyDevice", O_RDWR); is always returning -1, why is it so ? Where am I going wrong ? I checked with ls -l /dev/MyDevice, MyDevice has been successfully registered with following details: crw------- 1 root root 10, 56 Dec 9 19:33 /dev/MyDevice
Sorry, seriously stupid mistake, that's what happens when rookies do things. I just needed to grant the read and write permissions for my miscellaneous char device driver.
sudo chmod a+r+w /dev/MyDevice
Today I am getting started with developing Linux modules. It was rather hard to write, compile and work with Helloworld, but I've done it.
My second module with open, write, read functions is ready, but I really dont know how to test it. Write method just makes printk(). My module is loaded, its name is iamnoob. How to test this write(...) function and to find smth in var/log/syslog?
cat > iamnoob just writes a file to the dir. Same with cp and other.
Sorry for noob question, i've googled, but no answer has been found. Sorry for poor English.
A basic kernel module would normally include registering a character device.
Simple imlementation requires:
Register chrdev region with specific major & minor.
Allocate file operations structure and implement the basic read / write APIs.
Initialize and register character device with the file operations structure to the major / minor region.
See the following code snippet as a template of a module (only read / write APIs are imlemented):
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <asm-generic/uaccess.h>
#define MY_BUFFER_SIZE (1024 * 10)
#define MY_CHRDEV_MAJOR 217
#define MY_CHRDEV_MINOR 0
static struct cdev my_cdev;
static unsigned char *my_buf;
static dev_t my_dev = MKDEV(MY_CHRDEV_MAJOR, MY_CHRDEV_MINOR);
ssize_t my_read(struct file *file, char __user * buf, size_t count, loff_t * ppos)
{
int size;
size = MY_BUFFER_SIZE - 100 - (int)*ppos;
if (size > count)
size = count;
if (copy_to_user(buf, my_buf + *ppos, count))
return -EFAULT;
*ppos += size;
return size;
}
ssize_t my_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)
{
int size;
size = MY_BUFFER_SIZE - 100 - (int)*ppos;
if (size > count)
size = count;
if (copy_from_user(my_buf + *ppos, buf, count))
return -EFAULT;
*ppos += size;
return size;
}
long my_unlocked_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
printk ("%s!\n", __FUNCTION__);
return 0;
}
int my_mmap(struct file *f, struct vm_area_struct *vma)
{
printk ("%s!\n", __FUNCTION__);
return 0;
}
int my_open(struct inode *i, struct file *f)
{
printk ("%s!\n", __FUNCTION__);
return 0;
}
int my_release(struct inode *i, struct file *f)
{
printk ("%s!\n", __FUNCTION__);
return 0;
}
struct file_operations my_fops =
{
.owner = THIS_MODULE,
.read = &my_read,
.write = &my_write,
.unlocked_ioctl = &my_unlocked_ioctl,
.mmap = &my_mmap,
.open = &my_open,
.release = &my_release,
};
static int __init my_module_init(void)
{
int line = 0;
unsigned char *pos;
printk ("%s!\n", __FUNCTION__);
my_buf = (unsigned char *)kzalloc(MY_BUFFER_SIZE, 0);
if (my_buf == NULL) {
printk("%s - failed to kzallocate buf!\n", __FUNCTION__);
return -1;
}
pos = my_buf;
while (pos - my_buf < MY_BUFFER_SIZE - 100) {
sprintf(pos, "Line #%d\n", line++);
pos += strlen(pos);
}
cdev_init(&my_cdev, &my_fops);
if (register_chrdev_region(my_dev, 1, "my_dev")) {
pr_err("Failed to allocate device number\n");
}
cdev_add(&my_cdev, my_dev, 1);
printk ("%s - registered chrdev\n", __FUNCTION__);
return 0;
}
static void __exit my_module_exit(void)
{
printk ("my_module_exit.\n");
unregister_chrdev_region(my_dev, 1);
return;
}
module_init(my_module_init);
module_exit(my_module_exit);
MODULE_LICENSE("GPL");
This module uses a buffer for file operations, therefore can be tested on any machine, regardless of its HW. Make sure you avoid unnecessary printk's as loops may harm your kernel stability.
Once this is done, in user-space shell you should create a /dev node to represent your character device:
sudo mknod /dev/[dev_name] c [major] [minor]
for example:
sudo mknod /dev/my_dev c 217 0
Then you can test your read / write APIs with:
sudo insmod my_modult.ko
cat /dev/my_dev
less -f /dev/my_dev
sudo su
root> echo "This is a test" > /dev/my_dev
root> exit
cat /dev/my_dev
The shell commands listed above perform read, then login as root (to allow writing to device), write to the char dev, then exit and read again to see the changes.
Now you'd normally implement ioctl and mmap if needed.
I am trying to learn device drivers and I started with char device driver. I implemented a small program which is able to read/write from/to kernel buffer. Further, I tried to implement memory mapping and this is not working properly. When I am trying to read through a simple process by mapping my kernel module, it is giving me garbage value. Can any one help with this?
#include<linux/init.h>
#include<linux/module.h>
#include<linux/kernel.h> //printk()
#include<linux/errno.h>
#include<linux/types.h>
#include<linux/proc_fs.h>
#include<asm/uaccess.h> //copy_from,to_user
#include<linux/mm.h> //remap_pfn_range
//#include<linux/mman.h> //private_mapping_ok
#define BUFF_SIZE 128
#define DEV_NAME "MyDevice"
MODULE_LICENSE("GPL");
//Method declarations
int mod_open(struct inode *,struct file *);
int mod_release(struct inode *,struct file *);
ssize_t mod_read(struct file *,char *,size_t ,loff_t *);
ssize_t mod_write(struct file *,char *,size_t ,loff_t *);
int mod_mmap(struct file *, struct vm_area_struct *);
void mod_exit(void);
int mod_init(void);
//Structure that declares the usual file access functions
struct file_operations mod_fops = {
read: mod_read,
write: mod_write,
open: mod_open,
release: mod_release,
mmap: mod_mmap
};
static const struct vm_operations_struct mod_mem_ops = {
};
module_init(mod_init);
module_exit(mod_exit);
char *read_buf;
char *write_buf;
static int Major;
//static int Device_Open = 0;
int buffsize = 0;
int mod_init(void)
{
Major = register_chrdev(0,DEV_NAME,&mod_fops);
if(Major < 0)
{
printk(KERN_ALERT "Can not register %s. No major number alloted",DEV_NAME);
return Major;
}
//allocate memory to buffers
read_buf = kmalloc(BUFF_SIZE, GFP_KERNEL);
write_buf = kmalloc(BUFF_SIZE, GFP_KERNEL);
if(!read_buf || !write_buf)
{
mod_exit();
return -ENOMEM;
}
//reset buffers
memset(read_buf,0, BUFF_SIZE);
memset(write_buf,0, BUFF_SIZE);
printk(KERN_INFO "I was assigned major number %d. To talk to\n", Major);
printk(KERN_INFO "the driver, create a dev file with\n");
printk(KERN_INFO "'mknod /dev/%s c %d 0'.\n",DEV_NAME, Major);
printk(KERN_INFO "Try various minor numbers. Try to cat and echo to\n");
printk(KERN_INFO "the device file.\n");
printk(KERN_INFO "Remove the device file and module when done.\n");
return 0;
}
void mod_exit(void)
{
unregister_chrdev(Major,"memory");
if(read_buf) kfree(read_buf);
if(write_buf) kfree(write_buf);
printk(KERN_INFO "removing module\n");
}
int mod_mmap(struct file *filp, struct vm_area_struct *vma)
{
size_t size = vma->vm_end - vma->vm_start;
vma->vm_ops = &mod_mem_ops;
/* Remap-pfn-range will mark the range VM_IO */
if (remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff, size, vma->vm_page_prot)) {
return -EAGAIN;
}
printk(KERN_INFO "VMA Open. Virt_addr: %lx, phy_addr: %lx\n",vma->vm_start, vma->vm_pgoff<<PAGE_SHIFT);
return 0;
}
ssize_t mod_read(struct file *filp, char *buf, size_t len, loff_t *f_pos)
{
ssize_t bytes;
if(buffsize < len)
bytes = buffsize;
else
bytes = len;
printk(KERN_INFO "Buffer size availabe: %d\n", buffsize);
printk(KERN_INFO "VMA Open. read buffer initial: %lx\n",read_buf);
if(bytes == 0)
return 0;
int retval = copy_to_user(buf,read_buf,bytes);
if(retval)
{
printk(KERN_INFO "copy_to_user fail");
return -EFAULT;
}
else
{
printk(KERN_INFO "copy_to_user succeeded\n");
buffsize -= bytes;
return bytes;
}
}
ssize_t mod_write( struct file *filp,char *buf, size_t len, loff_t *f_pos)
{
memset(read_buf,0,BUFF_SIZE);
memset(write_buf,0,BUFF_SIZE);
if(len > BUFF_SIZE)
{
printk(KERN_ALERT "Buffer not available. Writing only %d bytes.\n",BUFF_SIZE);
len = BUFF_SIZE;
}
printk(KERN_INFO "User space msg size: %d\n",len);
int retval = copy_from_user(read_buf,buf,len);
printk(KERN_INFO "read %d bytes as: %s\n", retval,read_buf);
// memcpy(write_buf,read_buf,len);
// printk(KERN_INFO "written: %s\n", write_buf);
buffsize = len;
return len;
}
int mod_open(struct inode *inode, struct file *filp){return 0;}
int mod_release(struct inode *inode, struct file *filp) {return 0;}
The program which is trying to access this device driver:
#include<stdio.h>
#include<sys/fcntl.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<sys/mman.h>
int main(int argc,char *argv[])
{
int fd,n,len;
char *buff;
if(argc != 3)
{
printf("Too few arguments.\n");
exit(EXIT_FAILURE);
}
buff = (char *)malloc(128);
if(strcmp(argv[1],"read")==0)
{
if(-1 == (fd = open("/dev/MyDevice",O_RDONLY)))
{
printf("Device open fail. Error: %s",strerror(errno));
exit(EXIT_FAILURE);
}
memset(buff,0,128);
if(-1 == (buff = mmap(0,128,PROT_READ,MAP_SHARED | MAP_NORESERVE,fd,0)))
{
printf("Mapping failed. Error: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
/* if(-1 == (n = read(fd,buff,128)))
{
printf("Device read fail. Error: %s",strerror(errno));
exit(EXIT_FAILURE);
}
*/
printf("Read from device:\n%s\n",buff);
close(fd);
}
else if(strcmp(argv[1],"write")==0)
{
len = strlen(argv[2]);
if(-1 == (fd = open("/dev/MyDevice",O_WRONLY)))
{
printf("Device open fail. Error: %s",strerror(errno));
exit(EXIT_FAILURE);
}
if(-1 == (n = write(fd,argv[2],len)))
{
printf("Device write fail. Error: %s",strerror(errno));
exit(EXIT_FAILURE);
}
printf("Written %d bytes successfully.\n",n);
close(fd);
}
else
{
printf("Invalid argument..\n");
exit(EXIT_FAILURE);
}
return 0;
}
I got the error in my code. I was not mapping my buffer to vma->vm_pgoff. Just add following code before calling rmap_pfn_range, then this code will work fine
vma->vm_pgoff = virt_to_phys(read_buff)>>PAGE_SHIFT;
There are still several potential issues in your code although you found the root cause.
"vma->vm_pgoff = virt_to_phys(read_buff)>>PAGE_SHIFT"
It is not very good practice to program in this example, as basically you are overwriting a user file offset (in PAGE size unit). If your driver need to support mmap a memory offset, then obvious there is a issue. In this case, you can just pass virt_to_phys(read_buff)>>PAGE_SHIFT in place.
It is not recommended to use kmalloc to allocate the memory for remap purpose, as it is required to be page aligned, you can just use the kernel page APIs, like get_free_page to allocate the memory, further more, it is better to remap the memory in units of PAGE size, rather than 128 bytes here.
I want to write a virtual sound card driver that shall be used by the linux system for audio playback and capture. The driver shall use a buffer for audio data read/write. I have written the following basic driver:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sound.h>
#include <linux/sysctl.h>
#include <linux/device.h>
#include <linux/slab.h> /* kmalloc() */
#include <linux/gfp.h>
#include <asm/uaccess.h> /* copy_from/to_user */
#include <linux/major.h>
#include <linux/fs.h>
#include <linux/pci.h>
#include <linux/err.h>
#include <sound/core.h>
static char* mod_name = "prosip";
MODULE_LICENSE("GPL");
MODULE_VERSION("0.0.1111");
MODULE_AUTHOR("DD-DDD");
MODULE_DESCRIPTION("proSip Virtual Sound Card");
//
static int ver_major = 133;
static int ver_minor = 3;
//
static int buffer_size = 0;
static char* buffer;
static int read_count = 0;
/* Declaration of memory.c functions */
int prosip_open(struct inode *inode, struct file *filp);
int prosip_release(struct inode *inode, struct file *filp);
//
ssize_t prosip_read(struct file *filp, char *buf, size_t count, loff_t *f_pos);
ssize_t prosip_write(struct file *filp, const char *buf, size_t count, loff_t *f_pos);
//
int prosip_ioctl(struct inode *inode,struct file *file,unsigned int ioctl_num,unsigned long ioctl_param);
//
static int __init prosip_init(void);
static void __exit prosip_exit(void);
/* Structure that declares the usual file access functions */
struct file_operations sound_fops =
{
owner:
THIS_MODULE,
read:
prosip_read,
write:
prosip_write,
open:
prosip_open,
release:
prosip_release,
ioctl:
prosip_ioctl
};
/* Declaration of the init and exit functions */
module_init(prosip_init);
module_exit(prosip_exit);
static int __init prosip_init(void)
{
int ret = -1;
buffer_size = 0;
printk("<1>[prosip] Init...!\n");
ret = register_sound_dsp(&sound_fops, ver_minor);
if(ret < 0)
{
printk("<1> [prosip] Registration failure\n");
//
return ret;
}
else
{
ver_minor = ret;
//
printk("<1> [prosip] DSP Registered succesfully with id %d\n", ret);
}
buffer = kmalloc(101, GFP_KERNEL);
if(buffer == 0)
{
printk("<1>[prosip] Failed to allocate buffer !!!\n");
//
return -ENOMEM;
}
//
return 0;
}
static void __exit prosip_exit(void)
{
printk("<1> [prosip] Sound Exit...\n");
unregister_sound_special(ver_minor);
if(buffer)
{
kfree(buffer);
}
}
/* Declaration of memory.c functions */
int prosip_open(struct inode *inode, struct file *filp)
{
printk("<1> [prosip] Sound Open... \n");
try_module_get(THIS_MODULE);
return 0;
}
//
int prosip_release(struct inode *inode, struct file *filp)
{
printk("<1> [MySound] Sound Release... \n");
module_put(THIS_MODULE);
return 0;
}
//
ssize_t prosip_read(struct file *filp, char *buf, size_t count, loff_t *f_pos)
{
printk("<1> [prosip] Sound read...\n");
printk("<1> [prosip] Writing Count: %d\n", count);
if(buffer == 0)
{
printk("<1> NULL buffer!!! Unable to read");
return 0;
}
//
count = buffer_size;
if(read_count == 0)
{
read_count = buffer_size;
}
else
{
read_count = 0;
}
copy_to_user(buf, buffer, buffer_size);
printk("<1> [prosip] Buffer: %s, buf: %s, Count: %d\n", buffer, buf, count);
return read_count;
}
//
ssize_t prosip_write(struct file *filp, const char *buf, size_t count, loff_t *f_pos)
{
printk("<1> [prosip] Sound write...!\n");
printk("<1> [prosip] Writing Count: %d\n", count);
//
if(buffer == 0)
{
printk("<1> NULL buffer!!! Unable to write");
return 0;
}
copy_from_user(buffer, buf, count);
buffer[count] = 0;
buffer_size = count;
printk("<1> [MySound] Writing Buffer: %s, Count: %d\n", buffer, count);
return count;
}
/*
* This function is called whenever a process tries to do an ioctl on our
* device file.
*
*/
int prosip_ioctl(struct inode *inode,
struct file *file,
unsigned int ioctl_num,
unsigned long ioctl_param)
{
//
return 0;
}
insmoding this module creates a driver at /dev/dsp. Also it is found in /sys/devices/virtual/sound/dsp/, so it is recognised by the system as a virtual audio driver.
I am not yet able to choose this device for playback and capture from applications. What else do I need to do to make this driver enumerated by audio applications?
Well /dev/dsp was the device node used for a sound card under the old OSS sound system in linux but these days pretty much everything will default to looking for devices based on the newer ALSA sound system.
Some software still supports OSS but you may well need to give it special options, or change the configuration, to tell it to use OSS instead of ALSA.
ALSA devices are found under /dev/snd and aren't normally accessed directly, as they are more complicated than the old OSS devices. Instead libasound is normally used to interact with them.