module field usage in a driver.
------------------------------------

steps:
-------

- A module is made to register with kernel for the file /dev/myown withe major number 254.

- Then open/write function were implemeneted for file_operations structure.

- A character device files was created with the major number 254

  mknod /dev/myown c 254 0

- A application programs was written to open the file /dev/mywon and write a character into the file continuously.

- Run the exe of the compiled application programs, you will get the printk messages from the kernel for the write operation.

- Then rmmod the driver loaded into the kernel. Kernel would go for panic.

- Reboot is required to bring up the machine.

- Now set the owner field of the struct file to THIS_MODULE. Then do all the steps now when u do rmmod <driver> then kernel will not allow you to remove the driver.
# rmmod samplerw.ko
ERROR: Module samplerw is in use


Observation:
------------

You have to tell system that the opened files are managed by your module. if the kernel does not know that, it can't protect you. There is an entry (struct file_operations).owner that can be set to the owning module, or more conveniently (the pointer is only known after the module is loaded) to the special value THIS_MODULE which causes the real value to be inserted there.



Driver code

driver.c
-----------

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include </usr/include/linux/module.h>

static int sample_write(struct file *file,const char* data,int len,loff_t *off);
static int sample_open(struct inode* inode,struct file* filep);

static struct file_operations rwstruct
={
open:sample_open,
write:sample_write,
owner:THIS_MODULE
};

static int major;

int init_module(void)
{
printk(KERN_EMERG "inside init_module");
major = register_chrdev(254,"myown",&rwstruct);
printk(KERN_EMERG "The major umber assigned is %d",major);
return 0;
}

void cleanup_module(void)
{
int cleanup =  unregister_chrdev(major,"myown");
printk(KERN_EMERG "The major umber cleaned up is %d ",cleanup);

}

static int sample_open(struct inode* inode,struct file* file)
{
printk(KERN_EMERG "Inside open %d\n",inode->i_rdev);
return 0;
}


static int sample_write(struct file *file,const char* data,int len,loff_t *off)
{
printk(KERN_EMERG "Inside sample_write lengths is %d \n",len);
return 0;
}
application code

appl.c
---------


#include<stdio.h>
#include<unistd.h>

int main()
{

int fd;
fd = open("/dev/myown",O_WRONLY);

while(1)
{
printf("Writig a myown character");
write(fd,"c",1);
sleep(3);
}

close(fd);

}

Hosted by www.Geocities.ws

1