D1.2168 Page 13 Thursday,January 20, 2005 9:21 AMmemory-based device driver that can be read and written for fun. Using memory asthe hardware base for the device allows anyone to run the sample code without theneed to acquire special hardware.Debugging techniques are vital tools for the programmer and are introduced inChapter 4. Equally important for those who would hack on contemporary kernels isthemanagementofconcurrencyand raceconditions.Chapter5concerns itselfwiththe problems posed by concurrent access to resources and introduces the Linuxmechanismsforcontrolling concurrency.With debugging and concurrency management skills in place, we move to advancedfeatures of char drivers, such as blocking operations,the use of select.and the impor-tant ioctl call; thesetopics are the subject of Chapter 6.Before dealing with hardware management, we dissect a few more of the kernel'ssoftware interfaces:Chapter7 shows how time is managed in the kernel,andChapter8explainsmemoryallocation.Next wefocus on hardware.Chapter 9 describes the management of I/O ports andmemory buffers that live on the device; after that comes interrupt handling, inChapter 10. Unfortunately, not everyone is able to run the sample code for thesechapters, because some hardware support is actually needed to test the softwareinterface interrupts. We've tried our best to keep required hardware support to aminimum,but you still need some simple hardware,such as a standard parallel porttoworkwiththesamplecodeforthesechapters.Chapter l1 covers the use of data types in the kernel and the writing of portablecode.The second half of the book is dedicated to more advanced topics.We start by get-ting deeper into the hardware and, in particular, the functioning of specific periph-eral buses.Chapter12 covers the details of writing drivers for PCI devices, andChapter 13 examines the API for working with USB devices.With an understanding of peripheral buses in place, we can takea detailed look at theLinux devicemodel,which is the abstraction layer used by thekernel to describe thehardware and softwareresources it is managing.Chapter 14 is a bottom-up look atthedevice model infrastructure,starting with the kobject type and working up fromthere. It covers the integration of the device model with real hardware; it then usesthat knowledge to cover topics like hot-pluggable devices and power management.In Chapter 15, we take a diversion into Linux memory management. This chaptershowshowtomapkernel memoryintouser space (themmapsystem call),mapusermemory into kernel space (with get_user_pages), and how to map eitherkind ofmemoryintodevicespace(toperformdirectmemoryaccess[DMA]operations)Overview of the Book13
This is the Title of the Book, eMatter Edition Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved. Overview of the Book | 13 memory-based device driver that can be read and written for fun. Using memory as the hardware base for the device allows anyone to run the sample code without the need to acquire special hardware. Debugging techniques are vital tools for the programmer and are introduced in Chapter 4. Equally important for those who would hack on contemporary kernels is the management of concurrency and race conditions. Chapter 5 concerns itself with the problems posed by concurrent access to resources and introduces the Linux mechanisms for controlling concurrency. With debugging and concurrency management skills in place, we move to advanced features of char drivers, such as blocking operations, the use of select, and the important ioctl call; these topics are the subject of Chapter 6. Before dealing with hardware management, we dissect a few more of the kernel’s software interfaces: Chapter 7 shows how time is managed in the kernel, and Chapter 8 explains memory allocation. Next we focus on hardware. Chapter 9 describes the management of I/O ports and memory buffers that live on the device; after that comes interrupt handling, in Chapter 10. Unfortunately, not everyone is able to run the sample code for these chapters, because some hardware support is actually needed to test the software interface interrupts. We’ve tried our best to keep required hardware support to a minimum, but you still need some simple hardware, such as a standard parallel port, to work with the sample code for these chapters. Chapter 11 covers the use of data types in the kernel and the writing of portable code. The second half of the book is dedicated to more advanced topics. We start by getting deeper into the hardware and, in particular, the functioning of specific peripheral buses. Chapter 12 covers the details of writing drivers for PCI devices, and Chapter 13 examines the API for working with USB devices. With an understanding of peripheral buses in place, we can take a detailed look at the Linux device model, which is the abstraction layer used by the kernel to describe the hardware and software resources it is managing. Chapter 14 is a bottom-up look at the device model infrastructure, starting with the kobject type and working up from there. It covers the integration of the device model with real hardware; it then uses that knowledge to cover topics like hot-pluggable devices and power management. In Chapter 15, we take a diversion into Linux memory management. This chapter shows how to map kernel memory into user space (the mmap system call), map user memory into kernel space (with get_user_pages), and how to map either kind of memory into device space (to perform direct memory access [DMA] operations). ,ch01.2168 Page 13 Thursday, January 20, 2005 9:21 AM
ch01.2168 Page 14 Thursday, January 20, 2005 9:21 AMOur understanding of memory will be useful for thefollowing two chapters, whichcover the other major driver classes.Chapter 16 introduces block drivers and showshow they are different from the char drivers we have worked with so far. ThenChapter 17 gets into the writing of network drivers. We finish up with a discussionof serial drivers (Chapter 18) and a bibliography.14Chapter1: An Introduction to DeviceDrivers
This is the Title of the Book, eMatter Edition Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved. 14 | Chapter 1: An Introduction to Device Drivers Our understanding of memory will be useful for the following two chapters, which cover the other major driver classes. Chapter 16 introduces block drivers and shows how they are different from the char drivers we have worked with so far. Then Chapter 17 gets into the writing of network drivers. We finish up with a discussion of serial drivers (Chapter 18) and a bibliography. ,ch01.2168 Page 14 Thursday, January 20, 2005 9:21 AM
2.6536Page15Friday.January21,200510:32AMCHAPTER 2Building and RunningModulesIt's almost time to begin programming.This chapter introduces all the essential con-cepts about modules and kernel programming. In these few pages, we build and runa complete (if relatively useless) module, and look at some of the basic code sharedby all modules. Developing such expertise is an essential foundation for any kind ofmodularized driver.Toavoidthrowingintoomanyconceptsatonce,thischaptetalks only aboutmodules,without referring to any specific device classAll thekernel items (functions,variables, headerfiles, and macros) that are intro-duced here are described in a reference section at the end of the chapter.SettingUpYourTest SystemStarting with this chapter, we present example modules to demonstrate program-ming concepts.(All of these examples are available on O'Reilly's FTP site,asexplained in Chapter1.)Building,loading,and modifying these examples areagoodwayto improveyour understandingof howdrivers workand interact with thekernelThe example modules should work with almost any 2.6.x kernel, including thoseprovided by distribution vendors. However, we recommend that you obtain a“main-line" kernel directly from the kernel.org mirror network, and install it on your sys-tem. Vendor kernels can be heavily patched and divergent from the mainline; attimes,vendor patches can change the kernel API as seen by device drivers. If you arewriting a driver that must work on a particular distribution, you will certainly wantto build and test against the relevant kernels. But, for the purpose of learning aboutdriver writing, a standard kernel is best.Regardless of the origin of your kernel, building modules for 2.6.x requires that youhave a configured and built kernel tree on your system. This requirement is a changefrom previous versions of the kernel, where a current set of header files was suffi-cient. 2.6 modules are linked against object files found in the kernel source tree; theresult is a more robust module loader, but also the requirement that those object files15
This is the Title of the Book, eMatter Edition Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved. 15 Chapter 2 CHAPTER 2 Building and Running Modules It’s almost time to begin programming. This chapter introduces all the essential concepts about modules and kernel programming. In these few pages, we build and run a complete (if relatively useless)module, and look at some of the basic code shared by all modules. Developing such expertise is an essential foundation for any kind of modularized driver. To avoid throwing in too many concepts at once, this chapter talks only about modules, without referring to any specific device class. All the kernel items (functions, variables, header files, and macros)that are introduced here are described in a reference section at the end of the chapter. Setting Up Your Test System Starting with this chapter, we present example modules to demonstrate programming concepts. (All of these examples are available on O’Reilly’s FTP site, as explained in Chapter 1.)Building, loading, and modifying these examples are a good way to improve your understanding of how drivers work and interact with the kernel. The example modules should work with almost any 2.6.x kernel, including those provided by distribution vendors. However, we recommend that you obtain a “mainline” kernel directly from the kernel.org mirror network, and install it on your system. Vendor kernels can be heavily patched and divergent from the mainline; at times, vendor patches can change the kernel API as seen by device drivers. If you are writing a driver that must work on a particular distribution, you will certainly want to build and test against the relevant kernels. But, for the purpose of learning about driver writing, a standard kernel is best. Regardless of the origin of your kernel, building modules for 2.6.x requires that you have a configured and built kernel tree on your system. This requirement is a change from previous versions of the kernel, where a current set of header files was sufficient. 2.6 modules are linked against object files found in the kernel source tree; the result is a more robust module loader, but also the requirement that those object files ,ch02.6536 Page 15 Friday, January 21, 2005 10:32 AM
h02.6536 Page 16 Friday, January 21, 2005 10:32 AMbe available.So your first order of business is to come up with a kernel source tree(either from the kernel.org network or your distributor's kernel source package),build a new kernel, and install it on your system.For reasons we'll see later, life isgenerally easiest if you are actually running the target kernel when you build yourmodules, though this is not required.You should also give some thought to where you do your moduleexperimentation,development,and testing.Wehave done ourbesttomake our example modules safe and correct, but the possibility ofbugs is always present. Faults in kernel code can bring about thedemise of a user process or,occasionally,the entire system.Theydonotnormallycreatemoreseriousproblems,suchasdiskcorruption.Nonetheless, it is advisable to do your kernel experimentation on asystem that does not contain data that you cannot afford to lose,andthat does not perform essential services. Kernel hackers typically keepa"sacrificial"system around for thepurpose oftesting new code.So, if you do not yet have a suitable system with a configured and builtkernel sourcetree on disk, now would be a good time to set that up.We'll wait.Once that task istaken care of,you'll beready to startplaying withkernel modulesTheHelloWorld ModuleMany programming books begin with a“hello world”example as a way of showingthe simplest possible program.This book deals in kernel modules rather than pro-grams; so, for the impatient reader, the following code is a complete“hello world"module:#include<linux/init.h>#include<linux/module.h>MODULE_LICENSE("DualBSD/GPL");static int hello_init(void)printk(KERN_ALERT "Hello, worldin");return o;1static void hello_exit(void)printk(KERN_ALERT"Goodbye,cruel worldin");1module_init(hello_init);module_exit(hello_exit);This module defines two functions, one to be invoked when the module is loadedinto the kernel (hello_init) and one for when the module is removed (hello_exit).The161 Chapter 2: Building and Running Modules
This is the Title of the Book, eMatter Edition Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved. 16 | Chapter 2: Building and Running Modules be available. So your first order of business is to come up with a kernel source tree (either from the kernel.org network or your distributor’s kernel source package), build a new kernel, and install it on your system. For reasons we’ll see later, life is generally easiest if you are actually running the target kernel when you build your modules, though this is not required. You should also give some thought to where you do your module experimentation, development, and testing. We have done our best to make our example modules safe and correct, but the possibility of bugs is always present. Faults in kernel code can bring about the demise of a user process or, occasionally, the entire system. They do not normally create more serious problems, such as disk corruption. Nonetheless, it is advisable to do your kernel experimentation on a system that does not contain data that you cannot afford to lose, and that does not perform essential services. Kernel hackers typically keep a “sacrificial” system around for the purpose of testing new code. So, if you do not yet have a suitable system with a configured and built kernel source tree on disk, now would be a good time to set that up. We’ll wait. Once that task is taken care of, you’ll be ready to start playing with kernel modules. The Hello World Module Many programming books begin with a “hello world” example as a way of showing the simplest possible program. This book deals in kernel modules rather than programs; so, for the impatient reader, the following code is a complete “hello world” module: #include <linux/init.h> #include <linux/module.h> MODULE_LICENSE("Dual BSD/GPL"); static int hello_init(void) { printk(KERN_ALERT "Hello, world\n"); return 0; } static void hello_exit(void) { printk(KERN_ALERT "Goodbye, cruel world\n"); } module_init(hello_init); module_exit(hello_exit); This module defines two functions, one to be invoked when the module is loaded into the kernel (hello_init)and one for when the module is removed (hello_exit). The ,ch02.6536 Page 16 Friday, January 21, 2005 10:32 AM
h02.6536Page17Friday.January21,200510:32AMmodule_init and module_exit lines use special kernel macros to indicate the role ofthese two functions. Another special macro (MODULE_LICENSE) is used to tell thekernel that this module bears a free license; without such a declaration, the kernelcomplains when the module is loaded.Theprintk function is defined in the Linuxkernel and made available tomodules; itbehaves similarly to the standard C library function printf. The kernel needs its ownprinting function because it runs by itself, without the help of the C library.Themodule can call printk because, after insmod has loaded it, the module is linked tothe kernel and can access the kernel's public symbols (functions and variables, asdetailed in the next section). The string KERN_ALERT is the priority of the message:We've specified a high priority in this module, because a message with the defaultpriority might not show up anywhere useful, depending on the kernel version youare running, the version of the klogd daemon, and your configuration. You canignore this issue for now; we explain it in Chapter 4.You can test the module with the insmod and rmmod utilities,as shown below. Notethat only the superuser can load and unload a module.%makemake[1]:Enteringdirectory/usr/src/linux-2.6.10'CC[M]/home/idd3/src/misc-modules/hello.0Building modules, stage 2.MODPOSTCC/home/1dd3/src/misc-modules/hello.mod.oLD[M]/home/1ldd3/src/misc-modules/hello.komake[1]:Leaving directory~/usr/src/linux-2.6.10'% suroot#insmod./hello.koHello, worldroot#rmmodhelloGoodbye cruel worldroot#Pleasenote onceagain that,fortheabove sequenceof commandsto work,you musthave a properly configured and built kernel tree in a place where the makefile is ableto find it (/usr/src/linux-2.6.10 intheexample shown).Weget intothedetailsof howmodules are built in the section"Compilingand Loading.According to the mechanism your system uses to deliver the message lines, your out-put may be different. In particular, the previous screen dump was taken from a textconsole; if you are running insmod and rmmod from a terminal emulator runningunder the window system, you won't see anything on your screen. The message goestoone of the systemlogfiles,suchas/var/log/messages(thenameof theactual fileThe priority is just a string, such as <i>, which is prepended to the printk format string. Note the lack of acomma after KERN_ALERT; adding a comma there is a common and annoying typo (which, fortunately, iscaughtbythecompiler),The Hello World Module17
This is the Title of the Book, eMatter Edition Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved. The Hello World Module | 17 module_init and module_exit lines use special kernel macros to indicate the role of these two functions. Another special macro (MODULE_LICENSE)is used to tell the kernel that this module bears a free license; without such a declaration, the kernel complains when the module is loaded. The printk function is defined in the Linux kernel and made available to modules; it behaves similarly to the standard C library function printf. The kernel needs its own printing function because it runs by itself, without the help of the C library. The module can call printk because, after insmod has loaded it, the module is linked to the kernel and can access the kernel’s public symbols (functions and variables, as detailed in the next section). The string KERN_ALERT is the priority of the message.* We’ve specified a high priority in this module, because a message with the default priority might not show up anywhere useful, depending on the kernel version you are running, the version of the klogd daemon, and your configuration. You can ignore this issue for now; we explain it in Chapter 4. You can test the module with the insmod and rmmod utilities, as shown below. Note that only the superuser can load and unload a module. % make make[1]: Entering directory `/usr/src/linux-2.6.10' CC [M] /home/ldd3/src/misc-modules/hello.o Building modules, stage 2. MODPOST CC /home/ldd3/src/misc-modules/hello.mod.o LD [M] /home/ldd3/src/misc-modules/hello.ko make[1]: Leaving directory `/usr/src/linux-2.6.10' % su root# insmod ./hello.ko Hello, world root# rmmod hello Goodbye cruel world root# Please note once again that, for the above sequence of commands to work, you must have a properly configured and built kernel tree in a place where the makefile is able to find it (/usr/src/linux-2.6.10 in the example shown). We get into the details of how modules are built in the section “Compiling and Loading.” According to the mechanism your system uses to deliver the message lines, your output may be different. In particular, the previous screen dump was taken from a text console; if you are running insmod and rmmod from a terminal emulator running under the window system, you won’t see anything on your screen. The message goes to one of the system log files, such as /var/log/messages (the name of the actual file * The priority is just a string, such as <1>, which is prepended to the printk format string. Note the lack of a comma after KERN_ALERT; adding a comma there is a common and annoying typo (which, fortunately, is caught by the compiler). ,ch02.6536 Page 17 Friday, January 21, 2005 10:32 AM