Как написать драйвер для linux
Перейти к содержимому

Как написать драйвер для linux

  • автор:

Writing your First Linux driver in the Classroom

This second article, which is part of the series on Linux device drivers, deals with the concept of dynamically loading drivers, first writing a Linux driver, before building and then loading it.

As Shweta and Pugs reached their classroom, they were already late. Their professor was already in there. They looked at each other and Shweta sheepishly asked, “May we come in, sir”. “C’mon. you guys are late again”, called out professor Gopi. “And what is your excuse, today?”. “Sir, we were discussing your topic only. I was explaining her about device drivers in Linux”, was a hurried reply from Pugs. “Good one!! So, then explain me about dynamic loading in Linux. You get it right and you two are excused”, professor emphasized. Pugs was more than happy. And he very well knew, how to make his professor happy – criticize Windows. So, this is what he said.

As we know, a typical driver installation on Windows needs a reboot for it to get activated. That is really not acceptable, if we need to do it, say on a server. That’s where Linux wins the race. In Linux, we can load (/ install) or unload (/ uninstall) a driver on the fly. And it is active for use instantly after load. Also, it is disabled with unload, instantly. This is referred as dynamic loading & unloading of drivers in Linux.

As expected he impressed the professor. “Okay! take your seats. But make sure you are not late again”. With this, the professor continued to the class, “So, as you now already know, what is dynamic loading & unloading of drivers into & out of (Linux) kernel. I shall teach you how to do it. And then, we would get into writing our first Linux driver today”.

Dynamically loading drivers

These dynamically loadable drivers are more commonly referred as modules and built into individual files with .ko (kernel object) extension. Every Linux system has a standard place under the root file system ( / ) for all the pre-built modules. They are organized similar to the kernel source tree structure under /lib/modules/<kernel_version>/kernel , where <kernel_version> would be the output of the command uname -r on the system. Professor demonstrates to the class as shown in Figure 4.

Figure 4

Now, let us take one of the pre-built modules and understand the various operations with it.

Here’s a list of the various (shell) commands relevant to the dynamic operations:

  • lsmod : List the currently loaded modules
  • insmod <module_file> : Insert/Load the module specified by <module_file>
  • modprobe <module> – Insert/Load the <module> along with its dependencies
  • rmmod <module> – Remove/Unload the <module>

These reside under the /sbin directory and are to be executed with root privileges. Let us take the FAT file system related drivers for our experimentation. The various module files would be fat.ko, vfat.ko, etc. under directories fat (& vfat for older kernels) under /lib/modules/ uname -r /kernel/fs. In case, they are in compressed .gz format, they need to be uncompressed using gunzip, for using with insmod. vfat module depends on fat module. So, fat.ko needs to be loaded before vfat.ko. To do all these steps (decompression & dependency loading) automatically, modprobe can be used instead. Observe that there is no .ko for the module name to modprobe. rmmod is used to unload the modules. Figure 5 demonstrates this complete experimentation.

Figure 5

Our first Linux driver

With that understood, now let’s write our first driver. Yes, just before that, some concepts to be set right. A driver never runs by itself. It is similar to a library that gets loaded for its functions to be invoked by the "running" applications. And hence, though written in C, it lacks the main() function. Moreover, it would get loaded / linked with the kernel. Hence, it needs to be compiled in similar ways as the kernel. Even the header files to be used can be picked only from the kernel sources, not from the standard /usr/include.

One interesting fact about the kernel is that it is an object oriented implementation in C. And it is so profound that we would observe the same even with our first driver. Any Linux driver consists of a constructor and a destructor. The constructor of a module gets called whenever insmod succeeds in loading the module into the kernel. And the destructor of the module gets called whenever rmmod succeeds in unloading the module out of the kernel. These two are like normal functions in the driver, except that they are specified as the init & exit functions, respectively by the macros module_init() & module_exit() included through the kernel header module.h

Above is the complete code for our first driver, say ofd.c . Note that there is no stdio.h (a user space header), instead an analogous kernel.h (a kernel space header). printk() being the printf() analogous. Additionally, version.h is included for version compatibility of the module with the kernel into which it is going to get loaded. Also, the MODULE_* macros populate the module related information, which acts like the module’s signature.

Building our first Linux driver

Once we have the C code, it is time to compile it and create the module file ofd.ko. And for that we need to build it in the similar way, as the kernel. So, we shall use the kernel build system to do the same. Here follows our first driver’s Makefile, which would invoke the kernel’s build system from the kernel source. The kernel’s Makefile would in turn invoke our first driver’s Makefile to build our first driver. The kernel source is assumed to be installed at /usr/src/linux . In case of it to be at any other location, the KERNEL_SOURCE variable has to be appropriately updated.

*Note 1: Makefiles are very space-sensitive. The lines not starting at the first column have a tab and not spaces.*

*Note 2: For building a Linux driver, you need to have the kernel source (or at the least the kernel headers) installed on your system.*

With the C code (ofd.c) and Makefile ready, all we need to do is put them in a (new) directory of its own, and then invoke make in that directory to build our first driver (ofd.ko).

Summing up

Once we have the ofd.ko file, do the usual steps as root , or with sudo .

lsmod should show you the ofd driver loaded.

While the students were trying their first module, the bell rang, marking the end for this session of the class. And professor Gopi concluded, saying "Currently, you may not be able to observe anything, other than lsmod listing showing our first driver loaded. Where’s the printk output gone? Find that out for yourself in the lab session and update me with your findings. Moreover, today’s first driver would be the template to any driver you write in Linux. Writing any specialized advanced driver is just a matter of what gets filled into its constructor & destructor. So, here onwards, our learnings shall be in enhancing this driver to achieve our specific driver functionalities."



I am writing this guide to lend a hand to everyone who has some curiosity about the device driver programming or like to play a bit with the kernel and write some sample kernel modules.

Coding for the kernel is not the same that developing in user space. It has other implications. The kernel is the chunk of executable program that manages of the available resources of a machine (CPU, memory, file system, I/O, networking…) for all the programs running over it. The access to all of the resources, included the piece of HW for which you are writing the driver, is done by system calls (which is an API for the user programs to access to this resources). Hence the kernel is very structured and when you code in the kernel space you have to meet some special requirements and procedures. Otherwise you could end up in a kernel panic.

But don’t worry In here we will go over it.

There are plenty of others guides out there. I have gone through some of them but, although their content is useful and accurate, the format is a bit old and the explanations usually are very light since it assumes you have a considerable knowledge about how the kernel works.


Before start coding in your favorite editor you will need:

Kernel headers

The kernel headers for your current kernel: normally you won’t have it on your system unless you have compiled your own kernel or you have an insane liking for crashing your system and repairing it. To install them issue as root or with sudo and according to your linux distro:

After a successfully install you can find them in

The $(uname -r) is a bash command that will expand to your current kernel version.


I like Atom with some C plugins for small projects and testing, it is fast to install and the plugins are easily available and installable.

Regarding to the C spelling checker, most of the editors won’t recognize the #include <linux/. > so I recommend to copy the Linux to the development directory just to make happy the C spelling checker of our editor. Assuming you are inside your development directory:

The program

This is the hello world of the device driver programming. Note that the code is not mine, you can find it on internet in several places. So in your development directory create a file called myDriver.c with this content:

Let’s break it down, this module basically does:

  1. Load the libraries init.h and module.h . The first one provide macros for initialized data and the second defines the functions module_init() and module_exit()
  2. MODULE_LICENSE("GPL") it basically tells the kernel that this driver is under GPL license. If the module is licensed under a proprietary license the kernel will complain saying it is tainted. Read more here.
  3. hello_init(void) prints “Hello, world” in the kernel messages log with a log level of KERN_ALERT (this level is set this severe to make it visible in the logs, lesser server level may pass unnoticed)
  4. hello_exit(void) prints “Goodbye, cruel world” when called in the kernel log with same log level.
  5. module_init() tells the kernel which function to call when the module is loaded. Yeap, you guessed it right, it will be hello_init() 😉
  6. module_exit() defines which function to call when the module is removed. It is usually used for clean up all the things (memory reserved and stuff) you did in module_init()


Unfortunately, compiling kernel modules isn’t as easy as gcc -W -Wall myDriver.c -o myDriver . To compile kernel modules, the proper approach is using kbuild. However this may lead into very complicated makefiles, so for the purposes of this guide we will use a very simplified makefile. Create a file called makefile and write on it:

Once you have this you should be able to see in your working directory:

Note that the linux folder is there only so the C spelling checker doesn’t complain. For compiling we just use make . You will be able to see something like this:

You may have guessed that my kernel version (4.12.8–2-ARCH) very likely won’t match yours, and the /path/to/your/working/directory/ will be substituted with your current path (also in the variable $PWD ). Now we are ready for loading our fantastic, great, feature rich module!! 😉

Loading and removing the module

For loading and removing the modules there are different tools: insmod , rmmod and modprobe . We are going to use the first two because are simpler. modprobe is more intelligent and includes many features such as loading an inserted module at next boot and many others, and it is intended more for module management rather than module development. In here we are going to use insmod for loading and rmmod for removing modules.

For loading the module, assuming you are in your working directory:

After issuing this command you will be able to see “Hello, world” at the end of the kernel messages log. For reading the kernel log type:

dmesg shows the kernel log and since it is too big we filter it to show only the last 10 lines with tail . At the end (and if nothing else is generating kernel log messages) you will be able to see your string.

You can also check how the module is effectively loaded into the kernel with lsmod or displaying the content of the /proc/modules file:

Finally, and when you are run out of tears of happiness for having been able to load your first module you may remove it 😉

Note that if you press Tab to autocomplete after rmmod it will list all the possibles modules to remove, including yours. Also note that the module is removed by its name myDriver no by is module file name myDriver.ko . Now let’s check the kernel log again:

At the end of the log, we can see how the module printed “Goodbye, cruel world” when it was removed.

Last words

I hope this little superficial tutorial has shed some light into how to get your first linux module loaded and removed.

I think that one of the barriers for starting to program device drivers is the complex set up you have to perform before starting to code/debug. I wish this guide will make the start up process a bit less rough for others.

Как разработать драйвер Linux с нуля


Недавно я занимался изучением IoT и, так как мне не хватало устройств, при попытках симулировать работу прошивки я часто сталкивался с неимением нужного /dev/xxx. Так что я стал задумываться, а могу ли написать драйвер самостоятельно, чтобы заставить прошивку работать. Независимо от того, насколько сложно это будет, и удастся ли воплотить такое намерение, в любом случае вы не пожалеете, если научитесь разрабатывать драйвер Linux с нуля.

❯ Введение

Я написал серию статей, ориентированных в основном на практику, о теории там мало что говорится. Разрабатывать драйверы я научился по книге Linux Device Drivers, а код к примерам, разобранным в этой книге, выложен на GitHub.

Если начать с азов – операционная система Linux делится на пространство ядра и пользовательское пространство. Доступ к аппаратному устройству возможен только через пространство ядра, а драйвер устройства при этом может трактоваться как API, предоставляемый в пространстве ядра и позволяющий коду из пользовательского пространства обращаться к устройству.

Опираясь на эти базовые концепции, я сформулировал для себя несколько проблем, которые и побудили меня изучить разработку драйвера.

  1. В программировании учёба всегда начинается с программы Hello World, так как же в данном случае написать программу Hello World?
  2. Как драйвер генерирует файлы устройств под /dev?
  3. Как именно происходит доступ драйвера к имеющемуся аппаратному обеспечению?
  4. Как написать код, управляемый системой? Или можно извлечь драйвер без кода? Где находятся двоичные файлы, в которых хранятся драйвера? В будущем все это можно было бы опробовать, чтобы изучить, насколько безопасно конкретное устройство.

❯ Всё начинается с Hello World

Вот какой получилась моя программа Hello World:

Драйвер Linux разрабатывается на языке C, причём, на таком, который не слишком мне привычен. При работе я часто пользуюсь библиотекой Libc, которая отсутствует в ядре. Поскольку драйвер – это программа, работающая в ядре, именно в ядре мы используем и библиотечные функции.

Например, printk — это функция вывода, определяемая в ядре, она аналогична printf из Libc. Но мне она в большей степени напоминает логирующую функцию из Python, так как вывод printk идёт разу в лог ядра, а этот лог можно просмотреть командой dmesg .

В коде драйвера есть ровно одна точка входа и одна точка выхода. При загрузке драйвера в ядро выполнится функция, определяемая функцией module_init , которая в вышеприведённом коде называется hello_init . При выгрузке драйвера из ядра вызывается функция, определяемая в функции module_exit , которая в вышеприведённом коде называется hello_exit .

Из показанного выше кода понятно, что, загружаясь, драйвер выводит Hello World, а выгружаясь — Goodbye World .

Кстати: MODULE_LICENSE и MODULE_AUTHOR не так важны. Здесь я не буду подробно их разбирать.

И ещё: для вывода функции printk должен добавляться переход на новую строку, иначе опорожнение буфера происходить не будет.

❯ Компилируем драйвер

Драйвер необходимо скомпилировать командой make , и соответствующий Makefile показан ниже:

Вообще исходный код ядра находится в каталоге /usr/src/linux-headers-$(shell uname -r)/, например:

А нам нужен каталог для скомпилированных исходников, а именно /usr/src/linux-headers-4.4.0-135-generic/ .

Поиск заголовочных файлов для драйверного кода осуществляется именно из этого каталога.

Параметр M=$(PWD) указывает, что вывод от компиляции драйвера попадает именно в текущий каталог.

Наконец, вот команда obj-m := hello.o , предназначенная для загрузки hello.o в hello.ko , а ko – это файл из пространства ядра.

❯ Загружаем драйвер в ядро

Вот некоторые системные команды, которые нам при этом понадобятся:

  • Lsmod : просмотр модуля ядра, загружаемого в настоящий момент.
  • Insmod : загрузка модуля ядра с последующим требованием прав администратора.
  • Rmmod : удаление модуля.

В старых версиях ядра таким же методом загружалось и удалялось само ядро, но в новых версиях ядра Linux здесь добавляется верификация модуля. Вот в какой ситуации мы сейчас находимся:

С точки зрения безопасности актуальное ядро предполагает, что данный модуль не вызывает доверия. Чтобы этот модуль мог быть загружен, его нужно подписать доверенным сертификатом.

Это можно сделать двумя способами:

  1. Войти в BIOS и отключить безопасную загрузку в UEFI.
  2. Добавить в ядро самоподписываемый сертификат, и именно с его помощью подписать модуль драйвера (подробнее об этом написано тут).

❯ View the Results


❯ Добавляем файлы устройств под /dev

Once again, we firstly provide the code, and then explain the example code.

❯ Классификация драйверов


Драйверы делятся на три категории: символьные устройства, блочные устройства и сетевые интерфейсы. В вышеприведённом коде было разобрано символьное устройство, а обсуждение двух других категорий выходит за рамки этой статьи.

Как было показано выше, brw-rw— — строка о правах доступа для блочных устройств начинается с буквы «b», а для символьных устройств начинается с буквы «c».

❯ О старших и младших числах

Старшее число отличает один драйвер от всех остальных. В принципе, если старшее число у устройств совпадает, это означает, что они управляются одним и тем же драйвером.
В одном каталоге drive может быть создано множество устройств, и отличаться они будут младшими числами. Вместе старшее и младшее число характеризуют устройство, управляемое драйвером (как показано выше).

Старшее число аппаратуры sda и sda1 это 8, а младших чисел здесь два: у одного устройства 0, а у другого 1.


❯ Как драйвер предоставляет API

Я привык считать, что /dev/xxx – это интерфейс, предоставляемый файлом, а в Linux «всё – файл». Поэтому, оперируя драйвером, мы, фактически, оперируем файлом, и именно в драйвере определяется define/open/read/write… что произойдёт с /dev/xxx . Любые мыслимые действия с API драйвера – это операции над файлами.

Какие операции над файлами здесь присутствуют? Все они определяются в структуре file_operations в заголовочном файле ядра <linux/fs.h>.

В коде, приведённом выше в качестве примера:

Я определяю структуру и присваиваю её. Не считая owner, значения всех остальных членов – это указатели функций.

Затем я применяю cdev_add , чтобы зарегистрировать структуру для файловых операций под каждый драйвер, это делается в функции scull_setup_cdev .

Например, совершая операцию “open” (открыть) с устройством под управлением драйвера, я выполняю функцию scull_open, что эквивалентно «перехвату» функции open в системном вызове.

❯ Как сгенерировать нужное нам устройство под /dev

Скомпилировав вышеприведённый код, получим scull.ko , затем подпишем его и, наконец, загрузим в ядро при помощи insmod .

Проверим, удачно ли он загрузился:


Да, драйвер устройства загрузился успешно, но он не создаёт файла устройства в каталоге /dev. Необходимо вручную воспользоваться mknod для связывания устройства:


❯ Итоги

В данном примере мы не совершали никаких операций с конкретным устройством, а просто воспользовались kmalloc , и с его помощью применили блок памяти в пространстве ядра.

Далее не буду вдаваться в детали о коде, все их можно уточнить, погуглив информацию или изучив заголовочные файлы.

В этой статье я хотел поделиться с вами, как самостоятельно научиться разрабатывать драйвера: сначала читать книги, чтобы усвоить базовые концепции, а затем искать информацию по конкретным деталям, когда дойдёт дело до практического применения.

Например, я не знаю, какой API может предоставить драйвер. Всё, что мне нужно знать – что такой API ограничивается файловыми операциями. На данный момент мне понадобятся только операциями open , close , read и write . Как делаются другие операции с файлами – можно уточнить при необходимости.


In order to develop Linux device drivers, it is necessary to have an understanding of the following:

  • C programming. Some in-depth knowledge of C programming is needed, like pointer usage, bit manipulating functions, etc.
  • Microprocessor programming. It is necessary to know how microcomputers work internally: memory addressing, interrupts, etc. All of these concepts should be familiar to an assembler programmer.

There are several different devices in Linux. For simplicity, this brief tutorial will only cover type char devices loaded as modules. Kernel 2.6.x will be used (in particular, kernel 2.6.8 under Debian Sarge, which is now Debian Stable).

User space and kernel space

When you write device drivers, it’s important to make the distinction between “user space” and “kernel space”.

  • Kernel space. Linux (which is a kernel) manages the machine’s hardware in a simple and efficient manner, offering the user a simple and uniform programming interface. In the same way, the kernel, and in particular its device drivers, form a bridge or interface between the end-user/programmer and the hardware. Any subroutines or functions forming part of the kernel (modules and device drivers, for example) are considered to be part of kernel space.
  • User space. End-user programs, like the UNIX shell or other GUI based applications ( kpresenter for example), are part of the user space. Obviously, these applications need to interact with the system’s hardware . However, they don’t do so directly, but through the kernel supported functions.

All of this is shown in figure 1.

Figure 1: User space where applications reside, and kernel space where modules or device drivers reside

Interfacing functions between user space and kernel space

The kernel offers several subroutines or functions in user space, which allow the end-user application programmer to interact with the hardware. Usually, in UNIX or Linux systems, this dialogue is performed through functions or subroutines in order to read and write files. The reason for this is that in Unix devices are seen, from the point of view of the user, as files.

On the other hand, in kernel space Linux also offers several functions or subroutines to perform the low level interactions directly with the hardware, and allow the transfer of information from kernel to user space.

Usually, for each function in user space (allowing the use of devices or files), there exists an equivalent in kernel space (allowing the transfer of information from the kernel to the user and vice-versa). This is shown in Table 1, which is, at this point, empty. It will be filled when the different device drivers concepts are introduced.

Events User functions Kernel functions
Load module
Open device
Read device
Write device
Close device
Remove module

Table 1. Device driver events and their associated interfacing functions in kernel space and user space.

Interfacing functions between kernel space and the hardware device

There are also functions in kernel space which control the device or exchange information between the kernel and the hardware. Table 2 illustrates these concepts. This table will also be filled as the concepts are introduced.

Events Kernel functions
Read data
Write data

Table 2. Device driver events and their associated functions between kernel space and the hardware device.

The first driver: loading and removing the driver in user space

I’ll now show you how to develop your first Linux device driver, which will be introduced in the kernel as a module.

For this purpose I’ll write the following program in a file named nothing.c

Since the release of kernel version 2.6.x, compiling modules has become slightly more complicated. First, you need to have a complete, compiled kernel source-code-tree. If you have a Debian Sarge system, you can follow the steps in Appendix B (towards the end of this article). In the following, I’ll assume that a kernel version 2.6.8 is being used.

Next, you need to generate a makefile. The makefile for this example, which should be named Makefile , will be:

Unlike with previous versions of the kernel, it’s now also necessary to compile the module using the same kernel that you’re going to load and use the module with. To compile it, you can type:

This extremely simple module belongs to kernel space and will form part of it once it’s loaded.

In user space, you can load the module as root by typing the following into the command line:

The insmod command allows the installation of the module in the kernel. However, this particular module isn’t of much use.

It is possible to check that the module has been installed correctly by looking at all installed modules:

Finally, the module can be removed from the kernel using the command:

By issuing the lsmod command again, you can verify that the module is no longer in the kernel.

The summary of all this is shown in Table 3.

Events User functions Kernel functions
Load module insmod
Open device
Read device
Write device
Close device
Remove module rmmod

Table 3. Device driver events and their associated interfacing functions between kernel space and user space.

The “Hello world” driver: loading and removing the driver in kernel space

When a module device driver is loaded into the kernel, some preliminary tasks are usually performed like resetting the device, reserving RAM, reserving interrupts, and reserving input/output ports, etc.

These tasks are performed, in kernel space, by two functions which need to be present (and explicitly declared): module_init and module_exit ; they correspond to the user space commands insmod and rmmod , which are used when installing or removing a module. To sum up, the user commands insmod and rmmod use the kernel space functions module_init and module_exit .

Let’s see a practical example with the classic program Hello world :

The actual functions hello_init and hello_exit can be given any name desired. However, in order for them to be identified as the corresponding loading and removing functions, they have to be passed as parameters to the functions module_init and module_exit .

The printk function has also been introduced. It is very similar to the well known printf apart from the fact that it only works inside the kernel. The <1> symbol shows the high priority of the message (low number). In this way, besides getting the message in the kernel system log files, you should also receive this message in the system console.

This module can be compiled using the same command as before, after adding its name into the Makefile.

In the rest of the article, I have left the Makefiles as an exercise for the reader. A complete Makefile that will compile all of the modules of this tutorial is shown in Appendix A.

When the module is loaded or removed, the messages that were written in the printk statement will be displayed in the system console. If these messages do not appear in the console, you can view them by issuing the dmesg command or by looking at the system log file with cat /var/log/syslog .

Table 4 shows these two new functions.

Events User functions Kernel functions
Load module insmod module_init()
Open device
Read device
Write device
Close device
Remove module rmmod module_exit()

Table 4. Device driver events and their associated interfacing functions between kernel space and user space.

The complete driver “memory”: initial part of the driver

I’ll now show how to build a complete device driver: memory.c . This device will allow a character to be read from or written into it. This device, while normally not very useful, provides a very illustrative example since it is a complete driver; it’s also easy to implement, since it doesn’t interface to a real hardware device (besides the computer itself).

To develop this driver, several new #include statements which appear frequently in device drivers need to be added:

After the #include files, the functions that will be defined later are declared. The common functions which are typically used to manipulate files are declared in the definition of the file_operations structure. These will also be explained in detail later. Next, the initialization and exit functions—used when loading and removing the module—are declared to the kernel. Finally, the global variables of the driver are declared: one of them is the major number of the driver, the other is a pointer to a region in memory, memory_buffer , which will be used as storage for the driver data.

The “memory” driver: connection of the device with its files

In UNIX and Linux, devices are accessed from user space in exactly the same way as files are accessed. These device files are normally subdirectories of the /dev directory.

To link normal files with a kernel module two numbers are used: major number and minor number . The major number is the one the kernel uses to link a file with its driver. The minor number is for internal use of the device and for simplicity it won’t be covered in this article.

To achieve this, a file (which will be used to access the device driver) must be created, by typing the following command as root:

# mknod /dev/memory c 60 0

In the above, c means that a char device is to be created, 60 is the major number and 0 is the minor number .

Within the driver, in order to link it with its corresponding /dev file in kernel space, the register_chrdev function is used. It is called with three arguments: major number , a string of characters showing the module name, and a file_operations structure which links the call with the file functions it defines. It is invoked, when installing the module, in this way:

Also, note the use of the kmalloc function. This function is used for memory allocation of the buffer in the device driver which resides in kernel space. Its use is very similar to the well known malloc function. Finally, if registering the major number or allocating the memory fails, the module acts accordingly.

The “memory” driver: removing the driver

In order to remove the module inside the memory_exit function, the function unregsiter_chrdev needs to be present. This will free the major number for the kernel.

The buffer memory is also freed in this function, in order to leave a clean kernel when removing the device driver.

The “memory” driver: opening the device as a file

The kernel space function, which corresponds to opening a file in user space ( fopen ), is the member open: of the file_operations structure in the call to register_chrdev . In this case, it is the memory_open function. It takes as arguments: an inode structure, which sends information to the kernel regarding the major number and minor number ; and a file structure with information relative to the different operations that can be performed on a file. Neither of these functions will be covered in depth within this article.

When a file is opened, it’s normally necessary to initialize driver variables or reset the device. In this simple example, though, these operations are not performed.

The memory_open function can be seen below:

This new function is now shown in Table 5.

Events User functions Kernel functions
Load module insmod module_init()
Open device fopen file_operations: open
Read device
Write device
Close device
Remove module rmmod module_exit()

Table 5. Device driver events and their associated interfacing functions between kernel space and user space.

The “memory” driver: closing the device as a file

The corresponding function for closing a file in user space ( fclose ) is the release: member of the file_operations structure in the call to register_chrdev . In this particular case, it is the function memory_release , which has as arguments an inode structure and a file structure, just like before.

When a file is closed, it’s usually necessary to free the used memory and any variables related to the opening of the device. But, once again, due to the simplicity of this example, none of these operations are performed.

The memory_release function is shown below:

This new function is shown in Table 6.

Events User functions Kernel functions
Load module insmod module_init()
Open device fopen file_operations: open
Read device
Write device
Close device fclose file_operations: release
Remove module rmmod module_exit()

Table 6. Device driver events and their associated interfacing functions between kernel space and user space.

The “memory” driver: reading the device

To read a device with the user function fread or similar, the member read: of the file_operations structure is used in the call to register_chrdev . This time, it is the function memory_read . Its arguments are: a type file structure; a buffer ( buf ), from which the user space function ( fread ) will read; a counter with the number of bytes to transfer ( count ), which has the same value as the usual counter in the user space function ( fread ); and finally, the position of where to start reading the file ( f_pos ).

In this simple case, the memory_read function transfers a single byte from the driver buffer ( memory_buffer ) to user space with the function copy_to_user :

The reading position in the file ( f_pos ) is also changed. If the position is at the beginning of the file, it is increased by one and the number of bytes that have been properly read is given as a return value, 1 . If not at the beginning of the file, an end of file ( 0 ) is returned since the file only stores one byte.

In Table 7 this new function has been added.

Events User functions Kernel functions
Load module insmod module_init()
Open device fopen file_operations: open
Read device fread file_operations: read
Write device
Close device fclose file_operations: release
Remove modules rmmod module_exit()

Table 7. Device driver events and their associated interfacing functions between kernel space and user space.

The “memory” driver: writing to a device

To write to a device with the user function fwrite or similar, the member write: of the file_operations structure is used in the call to register_chrdev . It is the function memory_write , in this particular example, which has the following as arguments: a type file structure; buf , a buffer in which the user space function ( fwrite ) will write; count , a counter with the number of bytes to transfer, which has the same values as the usual counter in the user space function ( fwrite ); and finally, f_pos , the position of where to start writing in the file.

In this case, the function copy_from_user transfers the data from user space to kernel space.

In Table 8 this new function is shown.

Events User functions Kernel functions
Load module insmod module_init()
Open device fopen file_operations: open
Close device fread file_operations: read
Write device fwrite file_operations: write
Close device fclose file_operations: release
Remove module rmmod module_exit()

Device driver events and their associated interfacing functions between kernel space and user space.

The complete “memory” driver

By joining all of the previously shown code, the complete driver is achieved:

Before this module can be used, you will need to compile it in the same way as with previous modules. The module can then be loaded with:

It’s also convenient to unprotect the device:

# chmod 666 /dev/memory

If everything went well, you will have a device /dev/memory to which you can write a string of characters and it will store the last one of them. You can perform the operation like this:

$ echo -n abcdef >/dev/memory

To check the content of the device you can use a simple cat :

The stored character will not change until it is overwritten or the module is removed.

The real “parlelport” driver: description of the parallel port

I’ll now proceed by modifying the driver that I just created to develop one that does a real task on a real device. I’ll use the simple and ubiquitous computer parallel port and the driver will be called parlelport .

The parallel port is effectively a device that allows the input and output of digital information. More specifically it has a female D-25 connector with twenty-five pins. Internally, from the point of view of the CPU, it uses three bytes of memory. In a PC, the base address (the one from the first byte of the device) is usually 0x378 . In this basic example, I’ll use just the first byte, which consists entirely of digital outputs.

The connection of the above-mentioned byte with the external connector pins is shown in figure 2.

Figure 2: The first byte of the parallel port and its pin connections with the external female D-25 connector

The “parlelport” driver: initializing the module

The previous memory_init function needs modification—changing the RAM memory allocation for the reservation of the memory address of the parallel port ( 0x378 ). To achieve this, use the function for checking the availability of a memory region ( check_region ), and the function to reserve the memory region for this device ( request_region ). Both have as arguments the base address of the memory region and its length. The request_region function also accepts a string which defines the module.

The “parlelport” driver: removing the module

It will be very similar to the memory module but substituting the freeing of memory with the removal of the reserved memory of the parallel port. This is done by the release_region function, which has the same arguments as check_region .

The “parlelport” driver: reading the device

In this case, a real device reading action needs to be added to allow the transfer of this information to user space. The inb function achieves this; its arguments are the address of the parallel port and it returns the content of the port.

Table 9 (the equivalent of Table 2) shows this new function.

Events Kernel functions
Read data inb
Write data

Device driver events and their associated functions between kernel space and the hardware device.

The “parlelport” driver: writing to the device

Again, you have to add the “writing to the device” function to be able to transfer later this data to user space. The function outb accomplishes this; it takes as arguments the content to write in the port and its address.

Table 10 summarizes this new function.

Events Kernel functions
Read data inb
Write data outb

Device driver events and their associated functions between kernel space and the hardware device.

The complete “parlelport” driver

I’ll proceed by looking at the whole code of the parlelport module. You have to replace the word memory for the word parlelport throughout the code for the memory module. The final result is shown below:

Initial section

In the initial section of the driver a different major number is used ( 61 ). Also, the global variable memory_buffer is changed to port and two more #include lines are added: ioport.h and io.h .

Module init

In this module-initializing-routine I’ll introduce the memory reserve of the parallel port as was described before.

Removing the module

This routine will include the modifications previously mentioned.

Opening the device as a file

This routine is identical to the memory driver.

Closing the device as a file

Again, the match is perfect.

Reading the device

The reading function is similar to the memory one with the corresponding modifications to read from the port of a device.

Writing to the device

It is analogous to the memory one except for writing to a device.

LEDs to test the use of the parallel port

In this section I’ll detail the construction of a piece of hardware that can be used to visualize the state of the parallel port with some simple LEDs.

WARNING: Connecting devices to the parallel port can harm your computer. Make sure that you are properly earthed and your computer is turned off when connecting the device. Any problems that arise due to undertaking these experiments is your sole responsibility.

The circuit to build is shown in figure 3 You can also read “PC & Electronics: Connecting Your PC to the Outside World” by Zoller as reference.

In order to use it, you must first ensure that all hardware is correctly connected. Next, switch off the PC and connect the device to the parallel port. The PC can then be turned on and all device drivers related to the parallel port should be removed (for example, lp , parport , parport_pc , etc.). The hotplug module of the Debian Sarge distribution is particularly annoying and should be removed. If the file /dev/parlelport does not exist, it must be created as root with the command:

# mknod /dev/parlelport c 61 0

Then it needs to be made readable and writable by anybody with:

# chmod 666 /dev/parlelport

The module can now be installed, parlelport . You can check that it is effectively reserving the input/output port addresses 0x378 with the command:

To turn on the LEDs and check that the system is working, execute the command:

$ echo -n A >/dev/parlelport

This should turn on LED zero and six, leaving all of the others off.

You can check the state of the parallel port issuing the command:

Figure 3: Electronic diagram of the LED matrix to monitor the parallel port

Final application: flashing lights

Finally, I’ll develop a pretty application which will make the LEDs flash in succession. To achieve this, a program in user space needs to be written with which only one bit at a time will be written to the /dev/parlelport device.

It can be compiled in the usual way:

$ gcc -o lights lights.c

and can be executed with the command:

The lights will flash successively one after the other! The flashing LEDs and the Linux computer running this program are shown in figure 4.


Having followed this brief tutorial you should now be capable of writing your own complete device driver for simple hardware like a relay board (see Appendix C), or a minimal device driver for complex hardware. Learning to understand some of these simple concepts behind the Linux kernel allows you, in a quick and easy way, to get up to speed with respect to writing device drivers. And, this will bring you another step closer to becoming a true Linux kernel developer.

Figure 4: Flashing LEDs mounted on the circuit board and the computer running Linux. Two terminals are shown: one where the “parlelport” module is loaded and another one where the “lights” program is run. Tux is closely following what is going on


A. Rubini, J. Corbert. 2001. Linux device drivers (second edition). Ed. O’Reilly. This book is available for free on the internet.

Jonathan Corbet. 2003/2004. Porting device drivers to the 2.6 kernel. This is a very valuable resource for porting drivers to the new 2.6 Linux kernel and also for learning about Linux device drivers.

B. Zoller. 1998. PC & Electronics: Connecting Your PC to the Outside World (Productivity Series). Nowadays it is probably easier to surf the web for hardware projects like this one.

M. Waite, S. Prata. 1990. C Programming. Any other good book on C programming would suffice.

Appendix A. Complete Makefile

Appendix B. Compiling the kernel on a Debian Sarge system

To compile a 2.6.x kernel on a Debian Sarge system you need to perform the following steps, which should be run as root:

  1. Install the “kernel-image-2.6.x” package.
  2. Reboot the machine to make this the running kernel image. This is done semi-automatically by Debian. You may need to tweak the lilo configuration file /etc/lilo.conf and then run lilo to achieve this.
  3. Install the “kernel-source-2.6.x” package.
  4. Change to the source code directory, cd /usr/src and unzip and untar the source code with bunzip2 kernel-source-2.6.x.tar.bz2 and tar xvf kernel-source-2.6.x.tar . Change to the kernel source directory with cd /usr/src/kernel-source-2.6.x
  5. Copy the default Debian kernel configuration file to your local kernel source directory cp /boot/config-2.6.x .config .
  6. Make the kernel and the modules with make and then make modules .

Appendix C. Exercises

If you would like to take on some bigger challenges, here are a couple of exercises you can do:

  1. I once wrote two device drivers for two ISA Meilhaus boards, an analog to digital converter (ME26) and a relay control board (ME53). The software is available from the ADQ project. Get the newer PCI versions of these Meilhaus boards and update the software.
  2. Take any device that doesn’t work on Linux, but has a very similar chipset to another device which does have a proven device driver for Linux. Try to modify the working device driver to make it work for the new device. If you achieve this, submit your code to the kernel and become a kernel developer yourself!

Comments and acknowledgements

Three years have elapsed since the first version of this document was written. It was originally written in Spanish and intended for version 2.2 of the kernel, but kernel 2.4 was already making its first steps at that time. The reason for this choice is that good documentation for writing device drivers, the Linux device drivers book (see bibliography), lagged the release of the kernel in some months. This new version is also coming out soon after the release of the new 2.6 kernel, but up to date documentation is now readily available in Linux Weekly News making it possible to have this document synchronized with the newest kernel.

Fortunately enough, PCs still come with a built-in parallel port, despite the actual trend of changing everything inside a PC to render it obsolete in no time. Let us hope that PCs still continue to have built-in parallel ports for some time in the future, or that at least, parallel port PCI cards are still being sold.

This tutorial has been originally typed using a text editor (i.e. emacs ) in noweb format. This text is then processed with the noweb tool to create a LaTeX file ( .tex ) and the source code files ( .c ). All this can be done using the supplied makefile.document with the command make -f makefile.document .

I would like to thank the “Instituto Politécnico de Bragança”, the “Núcleo Estudantil de Linux del Instituto Politécnico de Bragança (NUX)”, the “Asociación de Software Libre de León (SLeón)” and the “Núcleo de Estudantes de Engenharia Informática da Universidade de Évora” for making this update possible.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *