User Tools

Site Tools


wiki:kerneldriveranatomy

Start Me Up

First we will create a new, fake, driver. It's “fake” because it does nothing!

  1. Pick a directory to put our “fake” driver in
  2. Add module initialization and de-initialization
  3. Put some “printk” calls in there so we can tell it is working
  4. Run this up under emulator
  5. Pat ourselves on the back and make a cup of tea
  6. Add a file system mount point
  7. Handle open and close

Pick a Directory

Pick a folder to put our fake driver in *TODO: pick a folder*

In here we'll add “fake_driver.c”. This will be our working file.

We also need to modify the “Makefile” (makefiles provide the instructions for building our kernel)

Add Module Init and Deinit

Modern Linux defines 2 macros for us called “module_init” and “module_exit”. Both of these take the address of a function to be called in the relevant situation.

This code uses the “printk” function. This lets your driver write out text as it operates. It can sometimes be hard to figure out where this is going but the simple answer is that the kernel keeps a log which can be accessed with the “dmesg” command.

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
 
static int __init fake_driver_init(void)
{
	printk("fake_driver_init");
	return 0;
}
 
static void __exit hello_2_exit(void)
{
	printk("fake_driver_exit");
}
 
module_init(fake_driver_init);
module_exit(fake_driver_exit);

A quick overview. Yes! We need some include files!

The fake_driver_init driver prints some information and then returns 0.

It is important that it returns 0. If it does NOT return zero then the return value is assumed to be an error code (there's a big old list of these). If this happens, for example your hardware could not be found, then no more calls to you module will be made INCLUDING module_exit. That is if you fail init and exit is not invoked.

wiki/kerneldriveranatomy.txt · Last modified: 2018/03/15 05:38 by xylene