0.11770 Page xvi Thursday,January27,2005 12:11PMPayspecial attentiontonotes setapartfromthetextwiththefollowingicons5This is a tip.It contains useful supplementary information about thetopic at hand.This isa warning.It helps you solveand avoid annoyingproblemsUsing CodeExamplesThis book is here to help you get your job done. In general, you may use the code inthisbook inyourprogramsanddocumentation.ThecodesamplesarecoveredbyadualBSD/GPLlicense.We appreciate, but do not require, attribution. An attribution usually includes thetitle, author, publisher, and ISBN. For example: “Linux Device Drivers, Third Edi-tion, by Jonathan Corbet, Alessandro Rubini, and GregKroah-Hartman.Copyright2005O'Reilly Media, Inc.,0-596-00590-3."We'd LiketoHearfromYouPlease address comments and questions concerning thisbook to the publisherO'Reilly Media, Inc.1005Gravenstein HighwayNorthSebastopol,CA 95472(800)998-9938(intheUnitedStatesorCanada)(707) 829-0515 (international or local)(707)829-0104 (fax)We have a web page for this book, where we list errata, examples, and any addi-tional information.You can access this page at:http://www.oreilly.com/catalog/linuxdrive3To comment or ask technical questions about this book, send email to:bookquestions@oreilly.comFor more information about our books,conferences,Resource Centers,and theO'Reilly Network, see our web site at:http://www.oreilly.comxvi1Preface
This is the Title of the Book, eMatter Edition Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved. xvi | Preface Pay special attention to notes set apart from the text with the following icons: This is a tip. It contains useful supplementary information about the topic at hand. This is a warning. It helps you solve and avoid annoying problems. Using Code Examples This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. The code samples are covered by a dual BSD/GPL license. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Linux Device Drivers, Third Edition, by Jonathan Corbet, Alessandro Rubini, and Greg Kroah-Hartman. Copyright 2005 O’Reilly Media, Inc., 0-596-00590-3.” We’d Like to Hear from You Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 (800) 998-9938 (in the United States or Canada) (707) 829-0515 (international or local) (707) 829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at: http://www.oreilly.com/catalog/linuxdrive3 To comment or ask technical questions about this book, send email to: bookquestions@oreilly.com For more information about our books, conferences, Resource Centers, and the O’Reilly Network, see our web site at: http://www.oreilly.com ,ch00.11770 Page xvi Thursday, January 27, 2005 12:11 PM
0.11770 Page xvii Thursday,January 27,2005 12:11PMSafari EnabledWhen you see a Safari? Enabled icon on the cover of your favorite tech-Safarinology book, that means the book is available online through theO'ReillyNetwork Safari Bookshelf.Safari offers a solution that's better than e-books. It's a virtual library that lets youeasily search thousands of top tech books,cut and paste code samples,downloadchapters, and find quick answers when you need the most accurate, current information.Try it forfreeathttp://safari.oreilly.com.AcknowledgmentsThis book, of course, was not written in a vacuum; we would like to thank the manypeople who have helped to make it possible.Thanks to our editor, Andy Oram; this book is a vastly better product as a result ofhis efforts.And obviously weowe a lot to the smartpeople who have laid thephilo-sophical and practical foundations of the current free software renaissance.The first edition was technically reviewed by Alan Cox, Greg Hankins, Hans Ler-men, Heiko Eissfeldt, and Miguel de Icaza (in alphabetic order by first name). Thetechnical reviewers for the second edition were Allan B.Cruse, Christian Morgner,Jake Edge, Jeff Garzik, Jens Axboe, Jerry Cooperstein, Jerome Peter Lynch, MichaelKerrisk, Paul Kinzelman, and Raph Levien. Reviewers for the third edition wereAllanB.Cruse,ChristianMorgner,JamesBottomley,JerryCooperstein,PatrickMochel, Paul Kinzelman, and Robert Love. Together, these people have put a vastamount of effort into finding problems and pointing out possible improvements toourwritingLast but certainly not least, we thank the Linux developers for their relentless work.This includes both the kernel programmers and the user-space people, who often getforgotten.In thisbook, we chosenever to call themby namein order to avoid beingunfair to someone we might forget. We sometimes made an exception to this ruleand called Linus by name; we hopehe doesn't mind.JonI must begin by thanking my wife Laura and my children Michele and Giulia for fill-ingmylifewith joy and patientlyputting upwithmydistraction whileworkingonthis edition. The subscribers of LWN.net have, through their generosity, enabledmuch of this work to happen.The Linuxkernel developers have done me a great ser-vice by letting me be a part of their community, answering my questions, and settingme straight when I got confused. Thanks are due to readers of the second edition ofthis book whose comments, offered at Linux gatherings over much of the worldPrefacexvii
This is the Title of the Book, eMatter Edition Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved. Preface | xvii Safari Enabled When you see a Safari® Enabled icon on the cover of your favorite technology book, that means the book is available online through the O’Reilly Network Safari Bookshelf. Safari offers a solution that’s better than e-books. It’s a virtual library that lets you easily search thousands of top tech books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information. Try it for free at http://safari.oreilly.com. Acknowledgments This book, of course, was not written in a vacuum; we would like to thank the many people who have helped to make it possible. Thanks to our editor, Andy Oram; this book is a vastly better product as a result of his efforts. And obviously we owe a lot to the smart people who have laid the philosophical and practical foundations of the current free software renaissance. The first edition was technically reviewed by Alan Cox, Greg Hankins, Hans Lermen, Heiko Eissfeldt, and Miguel de Icaza (in alphabetic order by first name). The technical reviewers for the second edition were Allan B. Cruse, Christian Morgner, Jake Edge, Jeff Garzik, Jens Axboe, Jerry Cooperstein, Jerome Peter Lynch, Michael Kerrisk, Paul Kinzelman, and Raph Levien. Reviewers for the third edition were Allan B. Cruse, Christian Morgner, James Bottomley, Jerry Cooperstein, Patrick Mochel, Paul Kinzelman, and Robert Love. Together, these people have put a vast amount of effort into finding problems and pointing out possible improvements to our writing. Last but certainly not least, we thank the Linux developers for their relentless work. This includes both the kernel programmers and the user-space people, who often get forgotten. In this book, we chose never to call them by name in order to avoid being unfair to someone we might forget. We sometimes made an exception to this rule and called Linus by name; we hope he doesn’t mind. Jon I must begin by thanking my wife Laura and my children Michele and Giulia for filling my life with joy and patiently putting up with my distraction while working on this edition. The subscribers of LWN.net have, through their generosity, enabled much of this work to happen. The Linux kernel developers have done me a great service by letting me be a part of their community, answering my questions, and setting me straight when I got confused. Thanks are due to readers of the second edition of this book whose comments, offered at Linux gatherings over much of the world, ,ch00.11770 Page xvii Thursday, January 27, 2005 12:11 PM
0.11770 Page xvili Thursday, January 27, 2005 12:11 PMhave been gratifying and inspiring.And I would especially like to thank AlessandroRubini for starting this whole exercise with the first edition (and staying with itthrough the current edition); and Greg Kroah-Hartman, who has brought his consid-erableskillstobearon several chapters,withgreatresults.AlessandroI would like to thank the people that made this work possible. First of all, the incred-ible patience of Federica, whowent as far as letting me review thefirst edition dur-ing our honeymoon, with a laptop in the tent.I want to thank Giorgio and Giulia,who have been involved in later editions of the book and happily accepted to be sonsof "a gnu" who often works late in the night. I owe a lot to all the free-softwareauthors who actually taught me how to program by making their work available foranyone to study.But for this edition, I'm mostlygrateful to Jon and Greg,who havebeen great mates in this work; it couldn't have existed without each and both ofthem, as the code base is bigger and tougher, while my time is a scarcer resource,always contended forby clients,free software issues,and expired deadlines.Jonhasbeen a great leader for this edition; both have been very productive and technicallyinvaluable in supplementing my small-scale and embedded view toward program-ming with their expertise about SMP and number crunchers.GregI would liketo thankmywifeShannon and my children Madeline and Griffin fortheir understanding and patience while I took the time to work on this book. If itwere not for their support of my original Linux development efforts,I would not beable to do this book at all.Thanks also to Alessandro and Jon for offering tolet mework on this book; I am honored that they let me participate in it. Much gratitude isgiven to all of the Linux kernel programmers, who were unselfish enough to writecodein thepublicview,sothatIand others could learn somuchfrom justreading itAlso,for everyone who has ever sent me bug reports, critiqued my code, and flamedme fordoing stupid things,youhave all taught me somuchabout howtobea betterprogrammer and, throughout it all, made mefeel very welcometo be part of thiscommunity.Thankyou.xiliIPreface
This is the Title of the Book, eMatter Edition Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved. xviii | Preface have been gratifying and inspiring. And I would especially like to thank Alessandro Rubini for starting this whole exercise with the first edition (and staying with it through the current edition); and Greg Kroah-Hartman, who has brought his considerable skills to bear on several chapters, with great results. Alessandro I would like to thank the people that made this work possible. First of all, the incredible patience of Federica, who went as far as letting me review the first edition during our honeymoon, with a laptop in the tent. I want to thank Giorgio and Giulia, who have been involved in later editions of the book and happily accepted to be sons of “a gnu” who often works late in the night. I owe a lot to all the free-software authors who actually taught me how to program by making their work available for anyone to study. But for this edition, I’m mostly grateful to Jon and Greg, who have been great mates in this work; it couldn’t have existed without each and both of them, as the code base is bigger and tougher, while my time is a scarcer resource, always contended for by clients, free software issues, and expired deadlines. Jon has been a great leader for this edition; both have been very productive and technically invaluable in supplementing my small-scale and embedded view toward programming with their expertise about SMP and number crunchers. Greg I would like to thank my wife Shannon and my children Madeline and Griffin for their understanding and patience while I took the time to work on this book. If it were not for their support of my original Linux development efforts, I would not be able to do this book at all. Thanks also to Alessandro and Jon for offering to let me work on this book; I am honored that they let me participate in it. Much gratitude is given to all of the Linux kernel programmers, who were unselfish enough to write code in the public view, so that I and others could learn so much from just reading it. Also, for everyone who has ever sent me bug reports, critiqued my code, and flamed me for doing stupid things, you have all taught me so much about how to be a better programmer and, throughout it all, made me feel very welcome to be part of this community. Thank you. ,ch00.11770 Page xviii Thursday, January 27, 2005 12:11 PM
D1.2168Page 1Thursday,January20,20059:21AMCHAPTER 1An Introduction toDeviceDriversOne of the many advantages of free operating systems,as typified by Linux, is thattheir internals are open for all toview.The operating system, once a dark and myste-rious area whose code was restricted to a small number of programmers, can now bereadily examined, understood, and modified by anybody with the requisite skills.Linux has helped to democratize operating systems. The Linux kernel remains alarge and complex body of code, however, and would-be kernel hackers need anentry point where they can approach the code without being overwhelmed by com-plexity. Often, device drivers provide that gateway.Device drivers take on a special role in the Linux kernel. They are distinct "blackboxes" that make a particular piece of hardware respond to a well-defined internalprogramming interface;theyhide completely the details of how the device worksUseractivitiesareperformedbymeansofasetofstandardizedcallsthatareindependent ofthespecificdriver;mappingthose calls to device-specific operations thatacton real hardware is then the role of the devicedriver.This programming interface issuch that drivers can be built separately from the rest of the kernel and “plugged in"at runtime when needed. This modularity makes Linux drivers easy to write, to thepoint thatthere arenow hundreds of them available.There are a number of reasons to be interested in the writing of Linux device driversTherateatwhichnewhardwarebecomes available(andobsoletel)aloneguaranteesthat driver writers will be busy for the foreseeable future. Individuals may need toknow about drivers in order to gain access to a particular device that is of interest tothem. Hardware vendors, by making a Linux driver available for their products, canadd the large and growing Linux user base to their potential markets. And the opensource nature of the Linux system means that if the driver writer wishes, the sourceto a driver can be quickly disseminated to millions of users.This book teaches you howtowriteyour owndrivers and howtohack around inrelated parts of the kernel. We have taken a device-independent approach; the pro-gramming techniques and interfaces are presented, whenever possible, without beingtied to any specific device.Each driver is different; as a driver writer,you need to?
This is the Title of the Book, eMatter Edition Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved. 1 Chapter 1 CHAPTER 1 An Introduction to Device Drivers One of the many advantages of free operating systems, as typified by Linux, is that their internals are open for all to view. The operating system, once a dark and mysterious area whose code was restricted to a small number of programmers, can now be readily examined, understood, and modified by anybody with the requisite skills. Linux has helped to democratize operating systems. The Linux kernel remains a large and complex body of code, however, and would-be kernel hackers need an entry point where they can approach the code without being overwhelmed by complexity. Often, device drivers provide that gateway. Device drivers take on a special role in the Linux kernel. They are distinct “black boxes” that make a particular piece of hardware respond to a well-defined internal programming interface; they hide completely the details of how the device works. User activities are performed by means of a set of standardized calls that are independent of the specific driver; mapping those calls to device-specific operations that act on real hardware is then the role of the device driver. This programming interface is such that drivers can be built separately from the rest of the kernel and “plugged in” at runtime when needed. This modularity makes Linux drivers easy 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 device drivers. The rate at which new hardware becomes available (and obsolete!) alone guarantees that driver writers will be busy for the foreseeable future. Individuals may need to know about drivers in order to gain access to a particular device that is of interest to them. Hardware vendors, by making a Linux driver available for their products, can add the large and growing Linux user base to their potential markets. And the open source nature of the Linux system means that if the driver writer wishes, the source to a driver can be quickly disseminated to millions of users. This book teaches you how to write your own drivers and how to hack around in related parts of the kernel. We have taken a device-independent approach; the programming techniques and interfaces are presented, whenever possible, without being tied to any specific device. Each driver is different; as a driver writer, you need to ,ch01.2168 Page 1 Thursday, January 20, 2005 9:21 AM
D1.2168Page 2Thursday,January20,20059:21AMunderstand your specific device well. But most of the principles and basic tech-niques are the same for all drivers. This book cannot teach you about your device,but it gives you a handle on the background you need to make your device work.As you learn to write drivers, you find out a lot about the Linux kernel in generalthis may help you understand how your machine works and why things aren'talways as fast as you expect or don't do quite what you want. We introduce newideas gradually,starting off with very simpledrivers andbuilding onthem; every newconcept is accompanied by sample code that doesn't need special hardwareto betested.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 wedolaunchintoprogramming.TheRoleoftheDeviceDriverAs a programmer, you are able to make your own choices about your driver, andchoose an acceptable trade-off between the programming time required and the flexi-bility of the result. Though it may appear strange to say that a driver is “flexible,” welikethis word because it emphasizes that the role of a device driver is providingmechanism,notpolicy.The distinction between mechanism and policy is one of the best ideas behind theUnixdesign.Most programmingproblems can indeed be split intotwo parts:"whatcapabilities are to be provided"(themechanism)and"how those capabilities can beused" (the policy). If the two issues are addressed by different parts of the program,or even by different programs altogether, the software package is much easier todevelopand toadapttoparticularneeds.For example, Unix management of the graphic display is split between the X server,which knows the hardware and offers a unified interface to user programs, and thewindow and session managers,which implement a particular policywithout knowing anything about the hardware.People can use the same window manager on dif-ferent hardware, and different users can run different configurations on the sameworkstation.Even completely different desktop environments, such as KDE andGNOME,can coexist onthe same system.Another example is thelayered structureof TCP/IP networking:the operating system offers the socket abstraction, whichimplements no policy regarding thedata to be transferred,while different serversarein charge of the services (and their associated policies). Moreover, a server like ftpdprovides the file transfer mechanism, while users can use whatever client they prefer;both command-line and graphic clients exist, and anyone can write a new user inter-facetotransferfiles.Where drivers are concerned, the same separation of mechanism and policy appliesThefloppydriver ispolicyfreeits roleis only toshow the diskette as a continuous2 ↓Chapter 1: An Introduction to Device Drivers
This is the Title of the Book, eMatter Edition Copyright © 2005 O’Reilly & Associates, Inc. All rights reserved. 2 | Chapter 1: An Introduction to Device Drivers understand your specific device well. But most of the principles and basic techniques are the same for all drivers. This book cannot teach you about your device, but it gives you a handle on the background you need to make your device work. As you learn to write drivers, you find out a lot about the Linux kernel in general; this may help you understand how your machine works and why things aren’t always as fast as you expect or don’t do quite what you want. We introduce new ideas gradually, starting off with very simple drivers and building on them; every new concept is accompanied by sample code that doesn’t need special hardware to be tested. This chapter doesn’t actually get into writing code. However, we introduce some background concepts about the Linux kernel that you’ll be glad you know later, when we do launch into programming. The Role of the Device Driver As a programmer, you are able to make your own choices about your driver, and choose an acceptable trade-off between the programming time required and the flexibility 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 is providing mechanism, not policy. The distinction between mechanism and policy is one of the best ideas behind the Unix 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 of the program, or even by different programs altogether, the software package is much easier to develop and to adapt to particular needs. For example, Unix management of the graphic display is split between the X server, 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 on the same workstation. Even completely different desktop environments, such as KDE and GNOME, can coexist on the same system. Another example is the layered structure of TCP/IP networking: the operating system offers the socket abstraction, which implements no policy regarding the data to be transferred, while different servers are in charge of the services (and their associated policies). Moreover, a server like ftpd provides the file transfer mechanism, while users can use whatever client they prefer; both command-line and graphic clients exist, and anyone can write a new user interface to transfer files. Where drivers are concerned, the same separation of mechanism and policy applies. The floppy driver is policy free—its role is only to show the diskette as a continuous ,ch01.2168 Page 2 Thursday, January 20, 2005 9:21 AM