bash>/sbin/liloAdded linux*Finally, restart the machine and boot in to your new kernel:bash> rebootThefirstmessageinthebootsequencelaunchesyourcampaignforpolarbears4
bash> /sbin/lilo Added linux * Finally, restart the machine and boot in to your new kernel: bash> reboot The first message in the boot sequence launches your campaign for polar bears
Loadable ModulesBecause Linux runs on a variety of architectures and supports zillions of I/O devices, it's not feasible topermanentlycompilesupportforall possibledevicesintothebasekernel.Distributionsgenerallypackageaminimal kernel image and supplytherest ofthefunctionalities intheform of kernelmodules.Duringruntimethenecessarymodulesaredynamicallyloadedondemand.To generate modules, go to the root of your kernel source tree and build:bash>cd/usr/src/linux-x.Y.z/bash> make modulesTo install the produced modules, do this:bash>make modules installThis creates a kernel source directory structure under /lib/modules/X.Y.Z/kernel/ and populates it with loadablemodule objects. This also invokes the depmod utility that generates module dependencies in the file/lib/modules/X.Y.Z/modules.dep.The following utilities are available to manipulate modules: insmod, rmmod, Ismod, modprobe, modinfo, anddepmod.The first twoare utilities to insert and remove modules,whereas Ismod lists themodules that arecurrently loaded.modprobe is a cleverer version of insmod that also inserts dependent modules after examiningthecontents of/lib/modules/X.Y.Z/modules.dep.Forexample,assumethatyouneedtomountaVirtualFileAllocationTable(VFAT)partitionpresentonaUSBpendrive.UsemodprobetoloadtheVFATfilesystemdriver:[2][2] This exampleassumes that the module is not autoloaded by thekernel. Ifyou enable AutomaticKernel Module Loading (conriG_kmop)during configuration, the kernel automatically runs modprobe with the appropriate arguments when it detects missing subsystems. You'll learnaboutmoduleautoloading in Chapter4,"Laying the Groundwork.'bash>modprobevfatbash>lsmodUsed byModulesize0vfat14208fat490521 vfat97282vfat,fatnls_baseAs yousee in theIsmod output,modprobe inserts threemodules ratherthan one.modprobe first figures outthat ithasto insert/lib/modules/X.Y.Z/kernel/fs/vfat/vfat.ko.Butwhen itpeeks intothedependencyfile/lib/modules/X.Y.Z/modules.dep, it finds thefollowing line and realizes that it has to load two other dependentmodules first:/lib/modules/x.Y.z/kernel/fs/vfat/vfat.ko:/lib/modules/X.Y.z/kernel/fs/fat/fat.ko/iib/modules/x.Y.z/kernel/fs/nls/nls_base.kcIt then proceeds to load fat.ko and nls_base.ko before attempting to insert vfat.ko, thus automatically loadingallthemodulesyouneedtomountyourVFATpartition
Loadable Modules Because Linux runs on a variety of architectures and supports zillions of I/O devices, it's not feasible to permanently compile support for all possible devices into the base kernel. Distributions generally package a minimal kernel image and supply the rest of the functionalities in the form of kernel modules. During runtime, the necessary modules are dynamically loaded on demand. To generate modules, go to the root of your kernel source tree and build: bash> cd /usr/src/linux-X.Y.Z/ bash> make modules To install the produced modules, do this: bash> make modules_install This creates a kernel source directory structure under /lib/modules/X.Y.Z/kernel/ and populates it with loadable module objects. This also invokes the depmod utility that generates module dependencies in the file /lib/modules/X.Y.Z/modules.dep. The following utilities are available to manipulate modules: insmod, rmmod, lsmod, modprobe, modinfo, and depmod. The first two are utilities to insert and remove modules, whereas lsmod lists the modules that are currently loaded. modprobe is a cleverer version of insmod that also inserts dependent modules after examining the contents of /lib/modules/X.Y.Z/modules.dep. For example, assume that you need to mount a Virtual File Allocation Table (VFAT) partition present on a USB pen drive. Use modprobe to load the VFAT filesystem driver:[2] [2] This example assumes that the module is not autoloaded by the kernel. If you enable Automatic Kernel Module Loading (CONFIG_KMOD) during configuration, the kernel automatically runs modprobe with the appropriate arguments when it detects missing subsystems. You'll learn about module autoloading in Chapter 4, "Laying the Groundwork." bash> modprobe vfat bash> lsmod Module Size Used by vfat 14208 0 fat 49052 1 vfat nls_base 9728 2 vfat, fat As you see in the lsmod output, modprobe inserts three modules rather than one. modprobe first figures out that it has to insert /lib/modules/X.Y.Z/kernel/fs/vfat/vfat.ko. But when it peeks into the dependency file /lib/modules/X.Y.Z/modules.dep, it finds the following line and realizes that it has to load two other dependent modules first: /lib/modules/X.Y.Z/kernel/fs/vfat/vfat.ko: /lib/modules/X.Y.Z/kernel/fs/fat/fat.ko /lib/modules/X.Y.Z/kernel/fs/nls/nls_base.ko It then proceeds to load fat.ko and nls_base.ko before attempting to insert vfat.ko, thus automatically loading all the modules you need to mount your VFAT partition
Use the modinfo utility to extract verbose information about the modules you just loaded:bash> modinfo vfatfilename:/lib/modules/x.Y.z/kernel/fs/vfat/vfat.koGPLlicense:description:VFAT filesystem support...depends:fat, nls_baseTo compile a kernel driver as a module, toggle the corresponding menu choice button to<M> while configuringthekernel.Most of the devicedriver examples in this book are implemented as kernel modules.Tobuild amodule mymodule.ko from its source filemymodule.c,createa one-line Makefile and execute itas follows:bash>cd/path/to/module-source/bash> echo "obj-m += mymodule.ko">Makefilebash>make-C/path/to/kernel-sources/M-'pwdmodulesmake:Entering directory/path/to/kernel-sources'Building modules, stage 2.MODPOSTcc/path/to/module-sources/mymodule.mod.oLD[M]/path/to/module-sources/mymodule.komake:Leaving directory/path/to/kernel-sourcesbash>insmod./mymodule.koKernel modules render the kernel footprint smaller and the develop-build-test cycle shorter. You only need torecompile the particular module and reinsert it to effecta change.We look at moduledebuggingtechniques inChapter21,"Debugging DeviceDrivers."There are also some downsides if you choose to design your driver as a kernel module. Unlike built-in drivers,modules cannot reserve resources during boot time, when success is more or less guaranteed.4
Use the modinfo utility to extract verbose information about the modules you just loaded: bash> modinfo vfat filename: /lib/modules/X.Y.Z/kernel/fs/vfat/vfat.ko license: GPL description: VFAT filesystem support . depends: fat, nls_base To compile a kernel driver as a module, toggle the corresponding menu choice button to <M> while configuring the kernel. Most of the device driver examples in this book are implemented as kernel modules. To build a module mymodule.ko from its source file mymodule.c, create a one-line Makefile and execute it as follows: bash> cd /path/to/module-source/ bash> echo "obj-m += mymodule.ko" > Makefile bash> make –C /path/to/kernel-sources/ M=`pwd` modules make: Entering directory '/path/to/kernel-sources' Building modules, stage 2. MODPOST CC /path/to/module-sources/mymodule.mod.o LD [M] /path/to/module-sources/mymodule.ko make: Leaving directory '/path/to/kernel-sources' bash> insmod ./mymodule.ko Kernel modules render the kernel footprint smaller and the develop-build-test cycle shorter. You only need to recompile the particular module and reinsert it to effect a change. We look at module debugging techniques in Chapter 21, "Debugging Device Drivers." There are also some downsides if you choose to design your driver as a kernel module. Unlike built-in drivers, modules cannot reserve resources during boot time, when success is more or less guaranteed
Before StartingLinux has trekked manya terrain and is now state of the art, so you can use itas a vehicle to understandoperatingsystem concepts,processorarchitectures,andevenindustrydomains.Whenyoulearnatechniqueusedbyadevicedriversubsystem,look oneleveldeeperand probetheunderlyingreasonsbehindthatdesignchoice.Wherever not explicitly stated, the text assumes the 32-bit x86 architecture.The book is, however,mindful ofthe fact that you are more likely to write device drivers for embedded devices than for conventional PC-compatiblesystems.Thechapteronserialdrivers,forexample,examinestwodevices:atouchcontrolleronaPC derivative and a UART onacellphone.Or the chapteronI2C devicedrivers looksat an EEPROMon a PCsystemandaReal TimeClockonanembeddeddevice.Thebookalsoteachesyouaboutthecoreinfrastructurethat thekernel providesformost driver classes,whichhides architecturedependencies from device drivers.Device driver debugging techniques are discussed near the end of the book in Chapter 21, so you might find itworthwhile to forward to that chapter as you develop drivers while reading the book.This book is based onthe2.6kernel, whichhassubstantial changesacross theboard from2.4,touchingallmajorsubsystems.Hopefully,youhaveinstalleda2.6-basedLinuxonyoursystembynowandstartedexperimenting with the kernel sources.Each chapter takes the liberty of profusely pointing you to relevantkernelsourcefilesfortwomainreasons:1.Becauseeachdriversubsysteminthekernelistensofthousandsof lineslong,it'sonlypossibletotakearelatively simplistic view in a book. Looking at real drivers in the sources along with the example code inthisbookwill giveyouthebiggerpicture.2.Beforedevelopingadriver,it'sagoodideatozeroinonanexistingdriverinthedrivers/directorythatissimilarto yourrequirementand makethat yourstartingpoint.So,toderivemaximumbenefitfromthisbook,familiarizeyourselfwiththekernel byfrequentlybrowsingthesource tree and staring hard at the code. And in tandem with your code explorations, follow the goings-on in thekernel mailing list
Before Starting Linux has trekked many a terrain and is now state of the art, so you can use it as a vehicle to understand operating system concepts, processor architectures, and even industry domains. When you learn a technique used by a device driver subsystem, look one level deeper and probe the underlying reasons behind that design choice. Wherever not explicitly stated, the text assumes the 32-bit x86 architecture. The book is, however, mindful of the fact that you are more likely to write device drivers for embedded devices than for conventional PCcompatible systems. The chapter on serial drivers, for example, examines two devices: a touch controller on a PC derivative and a UART on a cell phone. Or the chapter on I2C device drivers looks at an EEPROM on a PC system and a Real Time Clock on an embedded device. The book also teaches you about the core infrastructure that the kernel provides for most driver classes, which hides architecture dependencies from device drivers. Device driver debugging techniques are discussed near the end of the book in Chapter 21, so you might find it worthwhile to forward to that chapter as you develop drivers while reading the book. This book is based on the 2.6 kernel, which has substantial changes across the board from 2.4, touching all major subsystems. Hopefully, you have installed a 2.6-based Linux on your system by now and started experimenting with the kernel sources. Each chapter takes the liberty of profusely pointing you to relevant kernel source files for two main reasons: Because each driver subsystem in the kernel is tens of thousands of lines long, it's only possible to take a relatively simplistic view in a book. Looking at real drivers in the sources along with the example code in this book will give you the bigger picture. 1. Before developing a driver, it's a good idea to zero in on an existing driver in the drivers/ directory that is similar to your requirement and make that your starting point. 2. So, to derive maximum benefit from this book, familiarize yourself with the kernel by frequently browsing the source tree and staring hard at the code. And in tandem with your code explorations, follow the goings-on in the kernel mailing list
Chapter2.APeekInsidetheKernelIn This Chapter18·Booting Up30Kernel Modeand UserMode30ProcessContextandInterruptContext31.Kernel Timers39Concurrencyin theKernel49ProcessFilesystem49.AllocatingMemory52Looking atthe SourcesBeforewestart our journey into themystical world of Linuxdevicedrivers,let'sfamiliarizeourselveswithsomebasickernelconceptsbylookingatseveralkernelregionsthroughthelensofadriver developer.Welearn aboutkerneltimers,synchronization mechanisms,and memoryallocation.Butlet'sstartourexpeditionbygettingaviewfromthetop;let'sskimthroughbootmessages emitted by the kernei and hit the breaks whenever something looks interesting.BootingUpFigure 2.1 shows the Linux boot sequence on an x86-based computer. Linux boot on x86-based hardware is setintomotionwhentheBIOSloadstheMasterBootRecord(MBR)fromthebootdevice.Coderesident intheMBRlooksatthepartitiontableandreadsaLinuxbootloadersuchasGRUB,LILO,orSYSLINUXfromtheactive
Chapter 2. A Peek Inside the Kernel In This Chapter Booting Up 18 Kernel Mode and User Mode 30 Process Context and Interrupt Context 30 Kernel Timers 31 Concurrency in the Kernel 39 Process Filesystem 49 Allocating Memory 49 Looking at the Sources 52 Before we start our journey into the mystical world of Linux device drivers, let's familiarize ourselves with some basic kernel concepts by looking at several kernel regions through the lens of a driver developer. We learn about kernel timers, synchronization mechanisms, and memory allocation. But let's start our expedition by getting a view from the top; let's skim through boot messages emitted by the kernel and hit the breaks whenever something looks interesting. Booting Up Figure 2.1 shows the Linux boot sequence on an x86-based computer. Linux boot on x86-based hardware is set into motion when the BIOS loads the Master Boot Record (MBR) from the boot device. Code resident in the MBR looks at the partition table and reads a Linux bootloader such as GRUB, LILO, or SYSLINUX from the active