Dynamic Kernels: Modularized Device Drivers

This is the first in a series of four articles co-authored by Alessandro Rubini and Georg Zezchwitz which present a practical approach to writing Linux device drivers as kernel loadable modules. This installment presents and introduction to thte topic, preparing the reader to understand next month's installment.
Writing Code

Let's look at what kind of code must go inside the module. The simple answer is “whatever you need”. In practice, you must remember that the module is kernel code, and must fit a well-defined interface with the rest of Linux.

Usually, you start with header inclusion. And you begin to have contraints: you must always define the __KERNEL__ symbol before including any header unless it is defined in your makefile, and you must only include files pertaining to the <linux/*> and <asm/*> hierarchies. Sure, you can include your module-specific header, but never, ever, include library specific files, such as <stdio.h> or <sys/time.h>.

The code fragment in Listing 1 represents the first lines of source of a typical character driver. If you are going to write a module, it will be easier to cut and paste these lines from existing source rather than copying them by hand from this article.

#define __KERNEL__         /* kernel code */

#define MODULE             /* always as a module */
#include <linux/module.h>  /* can't do without it */
#include <linux/version.h> /* and this too */

/*
 * Then include whatever header you need.
 * Most likely you need the following:
 */
#include <linux/types.h>   /* ulong and friends */
#include <linux/sched.h>   /* current, task_struct, other goodies */
#include <linux/fcntl.h>   /* O_NONBLOCK etc. */
#include <linux/errno.h>   /* return values */
#include <linux/ioport.h>  /* request_region() */
#include <linux/config.h>  /* system name and global items */
#include <linux/malloc.h>  /* kmalloc, kfree */

#include <asm/io.h>        /* inb() inw() outb() ... */
#include <asm/irq.h>       /* unreadable, but useful */

#include "modulename.h" /* your own material */

After including the headers, there comes actual code. Before talking about specific driver functionality—most of the code—it is worth noting that there exist two module-specific functions, which must be defined in order for the module to be loaded:

int init_module (void);
void cleanup_module (void);

The first is in charge of module initialization (looking for the related hardware and registering the driver in the appropriate kernel tables), while the second is in charge of releasing any resources the module has allocated and deregistering the driver from the kernel tables.

If these functions are not there, insmod will fail to load your module.

The init_module() function returns 0 on success and a negative value on failure. The cleanup_module() function returns void, because it only gets invoked when the module is known to be unloadable. A kernel module keeps a usage count, and cleanup_module() is only called when that counter's value is 0 (more on this later on).

Skeletal code for these two functions will be presented in the next installment. Their design is fundamental for proper loading and unloading of the module, and a few details must dealt with. So here, I'll introduce you to each of the details, so that next month I can present the structure without explaining all the details.

Getting a major number

Both character drivers and block drivers must register themselves in a kernel array; this step is fundamental for the driver to be used. After init_module() returns, the driver's code segment is part of the kernel, and won't ever be called again unless the driver registers its functionality. Linux, like most Unix flavors, keeps an array of device drivers, and each driver is identified by a number, called the major number, which is nothing more than the index in the array of available drivers.

The major number of a device is the first number appearing in the output of ls -l for the device file. The other one is the minor number (you guessed it). All the devices (file nodes) featuring the same major number are serviced by the same driver code.

It is clear that your modularized driver needs its own major number. The problem is that the kernel currently uses a static array to hold driver information, and the array is as small as 64 entries (it used to be 32, but it was increased during the 1.2 kernel development because of lack of major numbers).

Fortunately, the kernel allows dynamic assignment of major numbers. The invocation of the function

int register_chrdev(unsigned int major,
                    const char *name,
                    struct file_operations *fops);

will register your char-driver within the kernel. The first argument is either the number you are requesting or 0, in which case dynamic allocation is performed. The function returns a number less than 0 to signal an error, and 0 or greater to signal successful completion. If you asked for a dynamically assigned number, the positive return value is the major number your driver was assigned. The name argument is the name of your driver, and is what appears within the /proc/devices file. finally, fops is the structure used for calling all the other functions in your driver, and will be described later on.

Using dynamic allocation of major numbers is a winning choice for custom device drivers: you're assured that your device number doesn't conflict with any other device within your system—you're assured that register_chrdev() will succeed, unless you have loaded so many devices that you have run out of free device numbers, which is unlikely.

______________________

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState