I think you are now familiar with insmod and rmmod. Now let’s try to make a little complex driver. A driver which can write on memory and read from memory.

For this we need to insmod the driver, then open the driver and read/write. After the operations are finished we need to close the driver. After that, if need you can rmmod the driver.

So when you writing on the memory, you need to be careful with writing memory to the wrong memory region. This may result in damaging your hardware. Let’s say that you have written something in the wrong memory region. The things in that memory region will be replaced with the things that you wrote in that region. So the processors which are happening in that memory region will be lost. Or maybe damage the hardware as we explain in 1st part of Linux device drivers post series.

Ok, let’s see the example code first:

————————————————————————————————————————–

—————————————————————————————————————————-

This is the hello_world.C file (driver file).  in the init function, I have first allocated a memory region. It is done by alloc_chrdev_region() function.

Also, remember to use pointers correctly. If you mess up with them, then you will definitively crash the kernel.

Also, remember to unregister the allocated memory region when exiting the driver. It is done by unregister_chrdev_region() function.

Also, you need to make an open and release function to open and release the drivers before and after using.

In the reading function, it is easy to use the copy_to_user function to copy the data from the driver to the userspace. In writing data, we can use the copy_form_user function to write data from user space to kernel space.

So, this is the basic structure of the Linux device drivers. Now what you need is a make file to make the driver and user application to run the application.

Here is the user application which I made in this case:

—————————————————————————————————————————

———————————————————————————————————————–
You can use any C/C++ or any language to write the user application. But C is recommended. Because you can use basic C functions such as Open, close, etc. You can compile the user application as a normal usual way. (GCC user_app.c) But to build the driver you need to make a Makefile.

I guess with this series of Linux Device driver posts, you have an idea about what is happening with Linux Device Drivers. If you need some more examples, catch my Github repo. Good luck kernel hackers! :

***Please note that all of the content on this post was originally published on champlnx.blogspot.com. We have migrated these posts to www.champlnx.com for your convenience and continued access.

Leave a Reply

Your email address will not be published. Required fields are marked *