Linux Device Drivers 2nd Edition (779877), страница 3
Текст из файла (страница 3)
This modularity makes Linux driverseasy to write, to the point that there are now hundreds of them available.There are a number of reasons to be interested in the writing of Linux devicedrivers. The rate at which new hardware becomes available (and obsolete!) aloneguarantees that driver writers will be busy for the foreseeable future. Individualsmay need to know about drivers in order to gain access to a particular device thatis of interest to them.
Hardware vendors, by making a Linux driver available fortheir products, can add the large and growing Linux user base to their potentialmarkets. And the open source nature of the Linux system means that if the driverwriter wishes, the source to a driver can be quickly disseminated to millions ofusers.122 June 2001 16:32http://openlib.org.uaChapter 1: An Introduction to Device DriversThis book will teach you how to write your own drivers and how to hack aroundin related parts of the kernel. We have taken a device-independent approach; theprogramming techniques and interfaces are presented, whenever possible, withoutbeing tied to any specific device. Each driver is different; as a driver writer, youwill need to understand your specific device well.
But most of the principles andbasic techniques are the same for all drivers. This book cannot teach you aboutyour device, but it will give you a handle on the background you need to makeyour device work.As you learn to write drivers, you will find out a lot about the Linux kernel in general; this may help you understand how your machine works and why thingsaren’t always as fast as you expect or don’t do quite what you want. We’ll introduce new ideas gradually, starting off with very simple drivers and building uponthem; every new concept will be accompanied by sample code that doesn’t needspecial hardware to be tested.This chapter doesn’t actually get into writing code. However, we introduce somebackground concepts about the Linux kernel that you’ll be glad you know later,when we do launch into programming.The Role of the Device DriverAs a programmer, you will be able to make your own choices about your driver,choosing an acceptable trade-off between the programming time required and theflexibility of the result.
Though it may appear strange to say that a driver is “flexible,” we like this word because it emphasizes that the role of a device driver isproviding mechanism, not policy.The distinction between mechanism and policy is one of the best ideas behind theUnix design. Most programming problems can indeed be split into two parts:“what capabilities are to be provided” (the mechanism) and “how those capabilities can be used” (the policy). If the two issues are addressed by different parts ofthe program, or even by different programs altogether, the software package ismuch easier to develop and to adapt to particular needs.For example, Unix management of the graphic display is split between the Xserver, which knows the hardware and offers a unified interface to user programs,and the window and session managers, which implement a particular policy without knowing anything about the hardware.
People can use the same window manager on different hardware, and different users can run different configurations onthe same workstation. Even completely different desktop environments, such asKDE and GNOME, can coexist on the same system. Another example is the layered structure of TCP/IP networking: the operating system offers the socketabstraction, which implements no policy regarding the data to be transferred,while different servers are in charge of the services (and their associated policies).222 June 2001 16:32http://openlib.org.uaThe Role of the Device DriverMoreover, a server like ftpd provides the file transfer mechanism, while users canuse whatever client they prefer; both command-line and graphic clients exist, andanyone can write a new user interface to transfer files.Where drivers are concerned, the same separation of mechanism and policyapplies.
The floppy driver is policy free — its role is only to show the diskette as acontinuous array of data blocks. Higher levels of the system provide policies, suchas who may access the floppy drive, whether the drive is accessed directly or via afilesystem, and whether users may mount filesystems on the drive. Since differentenvironments usually need to use hardware in different ways, it’s important to beas policy free as possible.When writing drivers, a programmer should pay particular attention to this fundamental concept: write kernel code to access the hardware, but don’t force particular policies on the user, since different users have different needs.
The drivershould deal with making the hardware available, leaving all the issues about howto use the hardware to the applications. A driver, then, is flexible if it offers accessto the hardware capabilities without adding constraints. Sometimes, however,some policy decisions must be made.
For example, a digital I/O driver may onlyoffer byte-wide access to the hardware in order to avoid the extra code needed tohandle individual bits.You can also look at your driver from a different perspective: it is a software layerthat lies between the applications and the actual device. This privileged role of thedriver allows the driver programmer to choose exactly how the device shouldappear: different drivers can offer different capabilities, even for the same device.The actual driver design should be a balance between many different considerations. For instance, a single device may be used concurrently by different programs, and the driver programmer has complete freedom to determine how tohandle concurrency.
You could implement memory mapping on the device independently of its hardware capabilities, or you could provide a user library to helpapplication programmers implement new policies on top of the available primitives, and so forth. One major consideration is the trade-off between the desire topresent the user with as many options as possible and the time in which you haveto do the writing as well as the need to keep things simple so that errors don’tcreep in.Policy-free drivers have a number of typical characteristics. These include supportfor both synchronous and asynchronous operation, the ability to be opened multiple times, the ability to exploit the full capabilities of the hardware, and the lack ofsoftware layers to “simplify things” or provide policy-related operations. Drivers ofthis sort not only work better for their end users, but also turn out to be easier towrite and maintain as well.
Being policy free is actually a common target for software designers.322 June 2001 16:32http://openlib.org.uaChapter 1: An Introduction to Device DriversMany device drivers, indeed, are released together with user programs to helpwith configuration and access to the target device. Those programs can range fromsimple utilities to complete graphical applications. Examples include the tunelpprogram, which adjusts how the parallel port printer driver operates, and thegraphical cardctl utility that is part of the PCMCIA driver package.
Often a clientlibrary is provided as well, which provides capabilities that do not need to beimplemented as part of the driver itself.The scope of this book is the kernel, so we’ll try not to deal with policy issues, orwith application programs or support libraries. Sometimes we’ll talk about differentpolicies and how to support them, but we won’t go into much detail about programs using the device or the policies they enforce. You should understand, however, that user programs are an integral part of a software package and that evenpolicy-free packages are distributed with configuration files that apply a defaultbehavior to the underlying mechanisms.Splitting the KernelIn a Unix system, several concurrent pr ocesses attend to different tasks. Each process asks for system resources, be it computing power, memory, network connectivity, or some other resource.
The ker nel is the big chunk of executable code incharge of handling all such requests. Though the distinction between the differentkernel tasks isn’t always clearly marked, the kernel’s role can be split, as shown inFigure 1-1, into the following parts:Pr ocess managementThe kernel is in charge of creating and destroying processes and handlingtheir connection to the outside world (input and output). Communicationamong different processes (through signals, pipes, or interprocess communication primitives) is basic to the overall system functionality and is also handledby the kernel.
In addition, the scheduler, which controls how processes sharethe CPU, is part of process management. More generally, the kernel’s processmanagement activity implements the abstraction of several processes on top ofa single CPU or a few of them.Memory managementThe computer’s memory is a major resource, and the policy used to deal withit is a critical one for system performance.
The kernel builds up a virtualaddressing space for any and all processes on top of the limited availableresources. The different parts of the kernel interact with the memory-management subsystem through a set of function calls, ranging from the simple malloc/fr ee pair to much more exotic functionalities.FilesystemsUnix is heavily based on the filesystem concept; almost everything in Unix canbe treated as a file. The kernel builds a structured filesystem on top ofunstructured hardware, and the resulting file abstraction is heavily used422 June 2001 16:32http://openlib.org.uaSplitting the KernelThe System Call InterfaceProcessmanagementMemorymanagementFilesystemsDevicecontrolNetworkingConcurrency,multitaskingVirtualmemoryFiles and dirs:the VFSTtys &device accessConnectivityArchdependentCodeMemorymanagerFile systemtypesCharacterdevicesNetworksubsystemKernelsubsystemsFeaturesimplementedSoftwaresupportBlock devicesIF driversHardwareCPUMemoryDisks & CDsConsoles,etc.Networkinterfacesfeatures implemented as modulesFigur e 1-1.
A split view of the kernelthroughout the whole system. In addition, Linux supports multiple filesystemtypes, that is, different ways of organizing data on the physical medium. Forexample, diskettes may be formatted with either the Linux-standard ext2filesystem or with the commonly used FAT filesystem.Device controlAlmost every system operation eventually maps to a physical device. With theexception of the processor, memory, and a very few other entities, any and alldevice control operations are performed by code that is specific to the devicebeing addressed. That code is called a device driver.
The kernel must haveembedded in it a device driver for every peripheral present on a system, fromthe hard drive to the keyboard and the tape streamer. This aspect of the kernel’s functions is our primary interest in this book.522 June 2001 16:32http://openlib.org.uaChapter 1: An Introduction to Device DriversNetworkingNetworking must be managed by the operating system because most networkoperations are not specific to a process: incoming packets are asynchronousevents.
The packets must be collected, identified, and dispatched before aprocess takes care of them. The system is in charge of delivering data packetsacross program and network interfaces, and it must control the execution ofprograms according to their network activity.