
TITLE.9502 Pagei Thursday,January 27, 2005 12:06 PMLINUXDEVICEDRIVERS
LINUX DEVICE DRIVERS ,TITLE.9502 Page i Thursday, January 27, 2005 12:06 PM

TITLE.9502 Pagei Thursday, January 27, 2005 12:06 PMOtherLinuxresourcesfromO'ReillyRelated titlesUnderstandingtheLinuxLinux Pocket GuideKernelBuilding Embedded LinuxLinux in a NutshellSystemsDesigning EmbeddedRunning LinuxHardwareLinux NetworkAdministrator's GuideLinux Bookslinux.oreilly.com is a complete catalog of O'Reilly's books onResourceCenterLinux and Unix and related technologies, including samplechaptersand code examples.ONLamp.com isthepremiersitefortheopen sourcewebplat-ONLamp.comform:Linux, Apache, MySQL, and either Perl, Python, or PHP.ConferencesO'Reilly brings diverse innovators together to nurture the ideasthat spark revolutionaryindustries.We specialize in documenting thelatest tools and systems, translating the innovator'sknowledge into useful skills for those in the trenches. Visit con-ferences.oreilly.comforourupcomingevents.RELLYNETWORKSafari Bookshelf (safari.oreilly.com) is the premier online refer-Safarience library for programmers and IT professionals. ConductBookshelfsearches across more than 1,ooo books. Subscribers can zero inon answers to time-critical questions in a matter of seconds.Read the books on your Bookshelf from cover to cover or sim-ply flip to the page you need. Try it today with a free trial
Other Linux resources from O’Reilly Related titles Understanding the Linux Kernel Linux in a Nutshell Running Linux Linux Network Administrator’s Guide Linux Pocket Guide Building Embedded Linux Systems Designing Embedded Hardware Linux Books Resource Center linux.oreilly.com is a complete catalog of O’Reilly’s books on Linux and Unix and related technologies, including sample chapters and code examples. ONLamp.com is the premier site for the open source web platform: Linux, Apache, MySQL, and either Perl, Python, or PHP. Conferences O’Reilly brings diverse innovators together to nurture the ideas that spark revolutionary industries. We specialize in documenting the latest tools and systems, translating the innovator’s knowledge into useful skills for those in the trenches. Visit conferences.oreilly.com for our upcoming events. Safari Bookshelf (safari.oreilly.com) is the premier online reference library for programmers and IT professionals. Conduct searches across more than 1,000 books. Subscribers can zero in on answers to time-critical questions in a matter of seconds. Read the books on your Bookshelf from cover to cover or simply flip to the page you need. Try it today with a free trial. ,TITLE.9502 Page ii Thursday, January 27, 2005 12:06 PM

TITLE.9502Page iliThursday,January 27,200512:06PMLINUXDEVICEDRIVERSTHIRDEDITIONJonathan Corbet, AlessandroRubini, and Greg Kroah-HartmanO'REILLYBejing · Cambridge·Farnham Koln - Paris -Sebastopol ·Taipei · Tokyo
LINUX DEVICE DRIVERS THIRD EDITION Jonathan Corbet, Alessandro Rubini, and Greg Kroah-Hartman Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo ,TITLE.9502 Page iii Thursday, January 27, 2005 12:06 PM

COPYRIGHT.10321 Page iv Thursday, January 27, 2005 12:09 PMLinux Device Drivers,Third Editionby Jonathan Corbet, Alessandro Rubini, and Greg Kroah-HartmanCopyright 2005, 2001, 1998 0'Reilly Media, Inc. Allrights reserved.Printed in the United States of America.PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighwayNorth,Sebastopol,CA95472O'Relly books may be purchased for educational, business, or sales promotional use. Online editionsare also availableformost titles (safari.oreilly.com).For more information,contact our corporate/insti-tutional salesdepartment: (800) 998-9938or corporate@orelly.com.Editor:Andy OramProduction Editor:Matt HutchinsonProduction Services:Octal Publishing, Inc.Cover Designer:Edie FreedmanInterior Designer:Melanie WangPrinting History:February 1998:First Edition.June 2001:Second Edition.February 2005:Third Edition.Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks ofO'Reilly Media, Inc.The Linux series designations, Linux Device Drivers, images of the American West,and related trade dress are trademarks of O'Reilly Media, Inc.Many of the designations used by manufacturers and sellers to distinguish their products are claimed astrademarks. Where those designations appear in this book, and O'Reilly Media, Inc. was aware ofatrademark claim, the designations have been printed in caps or initial caps.While every precaution has been taken in the preparation of this book, the publisher and authorsassume no responsibility for errors or omissions, or for damages resulting from the use of theinformation contained herein.This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 2.0License.To view a copyof this license,visithttp:/lcreativecommons.org/licenses/by-sa/2.0/orsendaletter toCreativeCommons,559NathanAbbottWay,Stanford,California94305,USARepKoverThis book uses RepKover, a durable and flexible lay-flat binding.ISBN:0-596-00590-3[M]
Linux Device Drivers, Third Edition by Jonathan Corbet, Alessandro Rubini, and Greg Kroah-Hartman Copyright © 2005, 2001, 1998 O’Reilly Media, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Editor: Andy Oram Production Editor: Matt Hutchinson Production Services: Octal Publishing, Inc. Cover Designer: Edie Freedman Interior Designer: Melanie Wang Printing History: February 1998: First Edition. June 2001: Second Edition. February 2005: Third Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. The Linux series designations, Linux Device Drivers, images of the American West, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 2.0 License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/2.0/ or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. This book uses RepKover™ , a durable and flexible lay-flat binding. ISBN: 0-596-00590-3 [M] ,COPYRIGHT.10321 Page iv Thursday, January 27, 2005 12:09 PM

Idr3TOC.fm.4587 Page v Thursday,January 20, 2005 9:30 AMTable of ContentsPrefacexi1.AnIntroductiontoDeviceDrivers12TheRole oftheDeviceDriver4Splitting the Kernel5Classes of Devices and Modules8SecurityIssues10Version Numbering11License Terms12Joining the Kernel Development Community12Overview of the Book152.Building and Running Modules15Setting Up Your Test System16The Hello World Module18Kernel Modules Versus Applications22Compiling and Loading28The Kernel Symbol Table30Preliminaries31Initializationand Shutdown35ModuleParameters37Doing It in User Space39QuickReference423.CharDrivers中42TheDesign of scull43Major and Minor Numbers49SomeImportantData Structuresv
v Table of Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi 1. An Introduction to Device Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 The Role of the Device Driver 2 Splitting the Kernel 4 Classes of Devices and Modules 5 Security Issues 8 Version Numbering 10 License Terms 11 Joining the Kernel Development Community 12 Overview of the Book 12 2. Building and Running Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Setting Up Your Test System 15 The Hello World Module 16 Kernel Modules Versus Applications 18 Compiling and Loading 22 The Kernel Symbol Table 28 Preliminaries 30 Initialization and Shutdown 31 Module Parameters 35 Doing It in User Space 37 Quick Reference 39 3. Char Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 The Design of scull 42 Major and Minor Numbers 43 Some Important Data Structures 49 ,ldr3TOC.fm.4587 Page v Thursday, January 20, 2005 9:30 AM

Idr3TOC.fm.4587 Page vi Thursday,January 20, 2005 9:30 AM55Char Device Registration58open and release60scull's MemoryUsage63read and write70Playing with the NewDevices70QuickReference734. Debugging Techniques73Debugging Support in the Kernel75Debuggingby Printing82Debugging by Querying91Debugging by Watching93Debugging System Faults99Debuggers and Related Tools5.106ConcurrencyandRaceConditions107Pitfalls in scull107ConcurrencyandItsManagement109Semaphoresand Mutexes114Completions116Spinlocks121Locking Traps123Alternatives to Locking130QuickReference135Advanced CharDriver Operations6.135ioctl147Blocking I/O163poll and select169Asynchronous Notification171Seeking a Device173Access Control on a Device File179QuickReference7.Time,Delays,andDeferredWork183183Measuring TimeLapses188Knowing the Current Time190Delaying Execution196Kernel Timers202TaskletsviTable ofContents
vi | Table of Contents Char Device Registration 55 open and release 58 scull’s Memory Usage 60 read and write 63 Playing with the New Devices 70 Quick Reference 70 4. Debugging Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 Debugging Support in the Kernel 73 Debugging by Printing 75 Debugging by Querying 82 Debugging by Watching 91 Debugging System Faults 93 Debuggers and Related Tools 99 5. Concurrency and Race Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 Pitfalls in scull 107 Concurrency and Its Management 107 Semaphores and Mutexes 109 Completions 114 Spinlocks 116 Locking Traps 121 Alternatives to Locking 123 Quick Reference 130 6. Advanced Char Driver Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 ioctl 135 Blocking I/O 147 poll and select 163 Asynchronous Notification 169 Seeking a Device 171 Access Control on a Device File 173 Quick Reference 179 7. Time, Delays, and Deferred Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 Measuring Time Lapses 183 Knowing the Current Time 188 Delaying Execution 190 Kernel Timers 196 Tasklets 202 ,ldr3TOC.fm.4587 Page vi Thursday, January 20, 2005 9:30 AM

Idr3TOC.fm.4587 Page vii Thursday, January 20, 2005 9:30 AMWorkqueues205208Quick Reference2138.Allocating Memory213TheReal Storyofkmalloc217Lookaside Caches221get_free_page and Friends224vmalloc and Friends228Per-CPUVariables230Obtaining Large Buffers231Quick Reference2359.CommunicatingwithHardware235VO Ports and I/O Memory239Using I/O Ports245An I/O Port Example248Using I/O Memory255QuickReference25810.Interrupt Handling259Preparing theParallel Port259Installing an Interrupt Handler269Implementing a Handler275Top and Bottom Halves278Interrupt Sharing281Interrupt-Driven I/O286Quick Reference11. Data Types in the Kernel288288Use of Standard CTypes290AssigninganExplicitSizetoDataItems291Interface-Specific Types292OtherPortabilityIssues295Linked Lists299QuickReference30212.PCIDrivers302ThePCIInterface319A Look Back: ISA322PC/104andPC/104+Table of Contents Ivii
Table of Contents | vii Workqueues 205 Quick Reference 208 8. Allocating Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213 The Real Story of kmalloc 213 Lookaside Caches 217 get_free_page and Friends 221 vmalloc and Friends 224 Per-CPU Variables 228 Obtaining Large Buffers 230 Quick Reference 231 9. Communicating with Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 I/O Ports and I/O Memory 235 Using I/O Ports 239 An I/O Port Example 245 Using I/O Memory 248 Quick Reference 255 10. Interrupt Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258 Preparing the Parallel Port 259 Installing an Interrupt Handler 259 Implementing a Handler 269 Top and Bottom Halves 275 Interrupt Sharing 278 Interrupt-Driven I/O 281 Quick Reference 286 11. Data Types in the Kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288 Use of Standard C Types 288 Assigning an Explicit Size to Data Items 290 Interface-Specific Types 291 Other Portability Issues 292 Linked Lists 295 Quick Reference 299 12. PCI Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 The PCI Interface 302 A Look Back: ISA 319 PC/104 and PC/104+ 322 ,ldr3TOC.fm.4587 Page vii Thursday, January 20, 2005 9:30 AM

Idr3TOC.fm.4587 Page vili Thursday, January 20, 2005 9:30 AM322OtherPCBusesSBus323324NuBus325External Buses325QuickReference32713.USBDrivers328USBDevice Basics333USB and Sysfs335USBUrbsWritingaUSBDriver346356USBTransfers Without Urbs360QuickReference36214.TheLinuxDeviceModelKobjects, Ksets, and Subsystems364371Low-Level Sysfs Operations375Hotplug EventGeneration377Buses, Devices, and Drivers387Classes391 Putting It All Together397Hotplug405Dealing with Firmware407QuickReference41215.MemoryMapping andDMA412MemoryManagement inLinux422The mmap Device Operation435Performing Direct I/O440Direct MemoryAccess459Quick ReferenceBlock Drivers46416.465Registration471The Block Device Operations474Request ProcessingSome Other Details491494QuickReferenceviliTable of Contents
viii | Table of Contents Other PC Buses 322 SBus 323 NuBus 324 External Buses 325 Quick Reference 325 13. USB Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 USB Device Basics 328 USB and Sysfs 333 USB Urbs 335 Writing a USB Driver 346 USB Transfers Without Urbs 356 Quick Reference 360 14. The Linux Device Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362 Kobjects, Ksets, and Subsystems 364 Low-Level Sysfs Operations 371 Hotplug Event Generation 375 Buses, Devices, and Drivers 377 Classes 387 Putting It All Together 391 Hotplug 397 Dealing with Firmware 405 Quick Reference 407 15. Memory Mapping and DMA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412 Memory Management in Linux 412 The mmap Device Operation 422 Performing Direct I/O 435 Direct Memory Access 440 Quick Reference 459 16. Block Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464 Registration 465 The Block Device Operations 471 Request Processing 474 Some Other Details 491 Quick Reference 494 ,ldr3TOC.fm.4587 Page viii Thursday, January 20, 2005 9:30 AM

Idr3TOC.fm.4587 Page ix Thursday,January 20, 2005 9:30 AM49717.Network Drivers498How snull Is Designed502Connecting to the Kernel506Thenet_deviceStructureinDetail515Opening and Closing516Packet Transmission521Packet Reception523The Interrupt Handler525Receive Interrupt Mitigation528Changes in Link State528The Socket BuffersMAC Address Resolution532535Custom ioctl Commands536Statistical Information537Multicast540AFewOtherDetails542QuickReference18.TTYDrivers546548A Small TTY Driver553tty_driver Function Pointers560TTY Line Settings564ioctls566 proc and sysfs Handling of TTY Devices567The tty_driver Structure in Detail569The tty_operations Structure in Detail571The tty_struct Structure in Detail573QuickReference575Bibliography579IndexTable of Contentsix
Table of Contents | ix 17. Network Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497 How snull Is Designed 498 Connecting to the Kernel 502 The net_device Structure in Detail 506 Opening and Closing 515 Packet Transmission 516 Packet Reception 521 The Interrupt Handler 523 Receive Interrupt Mitigation 525 Changes in Link State 528 The Socket Buffers 528 MAC Address Resolution 532 Custom ioctl Commands 535 Statistical Information 536 Multicast 537 A Few Other Details 540 Quick Reference 542 18. TTY Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546 A Small TTY Driver 548 tty_driver Function Pointers 553 TTY Line Settings 560 ioctls 564 proc and sysfs Handling of TTY Devices 566 The tty_driver Structure in Detail 567 The tty_operations Structure in Detail 569 The tty_struct Structure in Detail 571 Quick Reference 573 Bibliography. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579 ,ldr3TOC.fm.4587 Page ix Thursday, January 20, 2005 9:30 AM

Jdr3TOC.fm.4587 Page x Thursday, January 20, 2005 9:30 AM
,ldr3TOC.fm.4587 Page x Thursday, January 20, 2005 9:30 AM