Docsity

Linux Kernel Development Third Edition, Apuntes de Ingeniería Infórmatica

Toggle sidebar
bg1
ptg
Linux Kernel
Development
Third Edition
Robert Love
Upper Saddle River, NJ • Boston • Indianapolis • San Francisco
New York • To ront o • Montreal • London • Munich • Pa ris • Madrid
Cape Town • Sydney • Tok yo • Singapore • Mexico City
From the Library of Wow! eBook
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Vista previa parcial del texto

¡Descarga Linux Kernel Development Third Edition y más Apuntes en PDF de Ingeniería Infórmatica solo en Docsity!

Linux Kernel

Development

Third Edition

Robert Love

Upper Saddle River, NJ • Boston • Indianapolis • San Francisco

New York • Toronto • Montreal • London • Munich • Paris • Madrid

Cape Town • Sydney • Tokyo • Singapore • Mexico City

Linux Kernel Development Third Edition

Copyright © 2010 Pearson Education, Inc. All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited repro- duction, storage in a retrieval system, or transmission in any form or by any means, elec- tronic, mechanical, photocopying, recording, or likewise. ISBN-13: 978-0-672-32946- ISBN-10: 0-672-32946- Library of Congress Cataloging-in-Publication Data:

Love, Robert. Linux kernel development / Robert Love. — 3rd ed. p. cm. Includes bibliographical references and index. ISBN 978-0-672-32946-3 (pbk. : alk. paper) 1. Linux. 2. Operating systems (Computers) I. Title.

QA76.76.O63L674 2010 005.4’32—dc 2010018961 Text printed in the United States on recycled paper at RR Donnelley, Crawfordsville, Indiana. First printing June 2010 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 the publish- er was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omis- sions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. The publisher offers excellent discounts on this book when ordered in quantity for bulk pur- chases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact: U.S. Corporate and Government Sales (800) 382- [email protected]

For sales outside the United States please contact: International Sales [email protected] Visit us on the Web: informit.com/aw

Acquisitions Editor Mark Taber Development Editor Michael Thurston Technical Editor Robert P. J. Day Managing Editor Sandra Schroeder Senior Project Editor Tonya Simpson Copy Editor Apostrophe Editing Services Indexer Brad Herriman Proofreader Debbie Williams Publishing Coordinator Vanessa Evans Book Designer Gary Adair Compositor Mark Shirar

  • 1 Introduction to the Linux Kernel
  • 2 Getting Started with the Kernel
  • 3 Process Management
  • 4 Process Scheduling
  • 5 System Calls
  • 6 Kernel Data Structures
  • 7 Interrupts and Interrupt Handlers
  • 8 Bottom Halves and Deferring Work
  • 9 An Introduction to Kernel Synchronization
  • 10 Kernel Synchronization Methods
  • 11 Timers and Time Management
  • 12 Memory Management
  • 13 The Virtual Filesystem
  • 14 The Block I/O Layer
  • 15 The Process Address Space
  • 16 The Page Cache and Page Writeback
  • 17 Devices and Modules
  • 18 Debugging
  • 19 Portability
  • 20 Patches, Hacking, and the Community - Bibliography - Index
  • 1 Introduction to the Linux Kernel Table of Contents
    • History of Unix
    • Along Came Linus: Introduction to Linux
    • Overview of Operating Systems and Kernels
    • Linux Versus Classic Unix Kernels
    • Linux Kernel Versions
    • The Linux Kernel Development Community
    • Before We Begin
  • 2 Getting Started with the Kernel
    • Obtaining the Kernel Source
      • Using Git
      • Installing the Kernel Source
      • Using Patches
    • The Kernel Source Tree
    • Building the Kernel
      • Configuring the Kernel
      • Minimizing Build Noise
      • Spawning Multiple Build Jobs
      • Installing the New Kernel
    • A Beast of a Different Nature
      • No libc or Standard Headers
      • GNU C
        • Inline Functions
        • Inline Assembly
        • Branch Annotation
      • No Memory Protection
      • No (Easy) Use of Floating Point
      • Small, Fixed-Size Stack
      • Synchronization and Concurrency
      • Importance of Portability
      • Conclusion
  • 3 Process Management viii Contents
    • The Process
    • Process Descriptor and the Task Structure
      • Allocating the Process Descriptor
      • Storing the Process Descriptor
      • Process State
      • Manipulating the Current Process State
      • Process Context
      • The Process Family Tree
    • Process Creation
      • Copy-on-Write
      • Forking
      • vfork()
    • The Linux Implementation of Threads
      • Creating Threads
      • Kernel Threads
    • Process Termination
      • Removing the Process Descriptor
      • The Dilemma of the Parentless Task
      • Conclusion
  • 4 Process Scheduling
    • Multitasking
    • Linux’s Process Scheduler
    • Policy
      • I/O-Bound Versus Processor-Bound Processes
      • Process Priority
      • Timeslice
      • The Scheduling Policy in Action
    • The Linux Scheduling Algorithm
      • Scheduler Classes
      • Process Scheduling in Unix Systems
      • Fair Scheduling
    • The Linux Scheduling Implementation
      • Time Accounting
        • The Scheduler Entity Structure
        • The Virtual Runtime
      • Process Selection Contents ix
        • Picking the Next Task
        • Adding Processes to the Tree
        • Removing Processes from the Tree
      • The Scheduler Entry Point
      • Sleeping and Waking Up
        • Wait Queues
        • Waking Up
    • Preemption and Context Switching
      • User Preemption
      • Kernel Preemption
    • Real-Time Scheduling Policies
    • Scheduler-Related System Calls
      • System Calls Scheduling Policy and Priority-Related
      • Processor Affinity System Calls
      • Yielding Processor Time
    • Conclusion
  • 5 System Calls
    • Communicating with the Kernel
    • APIs, POSIX, and the C Library
    • Syscalls
      • System Call Numbers
      • System Call Performance
    • System Call Handler
      • Denoting the Correct System Call
      • Parameter Passing
    • System Call Implementation
      • Implementing System Calls
      • Verifying the Parameters
    • System Call Context
      • Final Steps in Binding a System Call
      • Accessing the System Call from User-Space
      • Why Not to Implement a System Call
    • Conclusion
  • 6 Kernel Data Structures x Contents
    • Linked Lists
      • Singly and Doubly Linked Lists
      • Circular Linked Lists
      • Moving Through a Linked List
      • The Linux Kernel’s Implementation
        • The Linked List Structure
        • Defining a Linked List
        • List Heads
      • Manipulating Linked Lists
        • Adding a Node to a Linked List
        • Deleting a Node from a Linked List
        • Moving and Splicing Linked List Nodes
      • Traversing Linked Lists
        • The Basic Approach
        • The Usable Approach
        • Iterating Through a List Backward
        • Iterating While Removing
        • Other Linked List Methods
    • Queues
      • kfifo
      • Creating a Queue
      • Enqueuing Data
      • Dequeuing Data
      • Obtaining the Size of a Queue
      • Resetting and Destroying the Queue
      • Example Queue Usage
    • Maps
      • Initializing an idr
      • Allocating a New UID
      • Looking Up a UID
      • Removing a UID
      • Destroying an idr
    • Binary Trees
      • Binary Search Trees
      • Self-Balancing Binary Search Trees
        • Red-Black Trees
        • rbtrees
    • What Data Structure to Use, When Contents xi
    • Algorithmic Complexity
      • Algorithms
      • Big-O Notation
      • Big Theta Notation
      • Time Complexity
    • Conclusion
  • 7 Interrupts and Interrupt Handlers
    • Interrupts
    • Interrupt Handlers
    • Top Halves Versus Bottom Halves
    • Registering an Interrupt Handler
      • Interrupt Handler Flags
      • An Interrupt Example
      • Freeing an Interrupt Handler
    • Writing an Interrupt Handler
      • Shared Handlers
      • A Real-Life Interrupt Handler
    • Interrupt Context
    • Implementing Interrupt Handlers
    • /proc/interrupts
    • Interrupt Control
      • Disabling and Enabling Interrupts
      • Disabling a Specific Interrupt Line
      • Status of the Interrupt System
      • Conclusion
  • 8 Bottom Halves and Deferring Work
    • Bottom Halves
      • Why Bottom Halves?
      • A World of Bottom Halves
        • The Original “Bottom Half”
        • Task Queues
        • Softirqs and Tasklets
        • Dispelling the Confusion
    • Softirqs xii Contents
      • Implementing Softirqs
        • The Softirq Handler
        • Executing Softirqs
      • Using Softirqs
        • Assigning an Index
        • Registering Your Handler
        • Raising Your Softirq
    • Tasklets
      • Implementing Tasklets
        • The Tasklet Structure
        • Scheduling Tasklets
      • Using Tasklets
        • Declaring Your Tasklet
        • Writing Your Tasklet Handler
        • Scheduling Your Tasklet
      • ksoftirqd
      • The Old BH Mechanism
    • Work Queues
      • Implementing Work Queues
        • Data Structures Representing the Threads
        • Data Structures Representing the Work
        • Work Queue Implementation Summary
      • Using Work Queues
        • Creating Work
        • Your Work Queue Handler
        • Scheduling Work
        • Flushing Work
        • Creating New Work Queues
      • The Old Task Queue Mechanism
    • Which Bottom Half Should I Use?
    • Locking Between the Bottom Halves
    • Disabling Bottom Halves
    • Conclusion
  • 9 An Introduction to Kernel Synchronization
    • Critical Regions and Race Conditions
      • Why Do We Need Protection?
      • The Single Variable
    • Locking Contents xiii
      • Causes of Concurrency
      • Knowing What to Protect
    • Deadlocks
    • Contention and Scalability
    • Conclusion
  • 10 Kernel Synchronization Methods
    • Atomic Operations
      • Atomic Integer Operations
      • 64-Bit Atomic Operations
      • Atomic Bitwise Operations
    • Spin Locks
      • Spin Lock Methods
      • Other Spin Lock Methods
      • Spin Locks and Bottom Halves
    • Reader-Writer Spin Locks
    • Semaphores
      • Counting and Binary Semaphores
      • Creating and Initializing Semaphores
      • Using Semaphores
    • Reader-Writer Semaphores
    • Mutexes
      • Semaphores Versus Mutexes
      • Spin Locks Versus Mutexes
    • Completion Variables
    • BKL: The Big Kernel Lock
    • Sequential Locks
    • Preemption Disabling
    • Ordering and Barriers
    • Conclusion
  • 11 Timers and Time Management
    • Kernel Notion of Time
    • The Tick Rate: HZ
      • The Ideal HZ Value
      • Advantages with a Larger HZ
      • Disadvantages with a Larger HZ
    • Jiffies xiv Contents
      • Internal Representation of Jiffies
      • Jiffies Wraparound
      • User-Space and HZ
    • Hardware Clocks and Timers
      • Real-Time Clock
      • System Timer
    • The Timer Interrupt Handler
    • The Time of Day
    • Timers
      • Using Timers
      • Timer Race Conditions
      • Timer Implementation
    • Delaying Execution
      • Busy Looping
      • Small Delays
      • schedule_timeout()
        • schedule_timeout() Implementation
        • Sleeping on a Wait Queue, with a Timeout
      • Conclusion
  • 12 Memory Management
    • Pages
    • Zones
    • Getting Pages
      • Getting Zeroed Pages
      • Freeing Pages
    • kmalloc()
      • gfp_mask Flags
        • Action Modifiers
        • Zone Modifiers
        • Type Flags
      • kfree()
    • vmalloc()
    • Slab Layer
      • Design of the Slab Layer
      • Slab Allocator Interface Contents xv
        • Allocating from the Cache
        • Example of Using the Slab Allocator
    • Statically Allocating on the Stack
      • Single-Page Kernel Stacks
      • Playing Fair on the Stack
    • High Memory Mappings
      • Permanent Mappings
      • Temporary Mappings
    • Per-CPU Allocations
    • The New percpu Interface
      • Per-CPU Data at Compile-Time
      • Per-CPU Data at Runtime
    • Reasons for Using Per-CPU Data
    • Picking an Allocation Method
    • Conclusion
  • 13 The Virtual Filesystem
    • Common Filesystem Interface
    • Filesystem Abstraction Layer
    • Unix Filesystems
    • VFS Objects and Their Data Structures
    • The Superblock Object
    • Superblock Operations
    • The Inode Object
    • Inode Operations
    • The Dentry Object
      • Dentry State
      • The Dentry Cache
    • Dentry Operations
    • The File Object
    • File Operations
    • Data Structures Associated with Filesystems
    • Data Structures Associated with a Process
    • Conclusion
  • 14 The Block I/O Layer xvi Contents
    • Anatomy of a Block Device
    • Buffers and Buffer Heads
    • The bio Structure
      • I/O vectors
      • The Old Versus the New
    • Request Queues
    • I/O Schedulers
      • The Job of an I/O Scheduler
      • The Linus Elevator
      • The Deadline I/O Scheduler
      • The Anticipatory I/O Scheduler
      • The Complete Fair Queuing I/O Scheduler
      • The Noop I/O Scheduler
      • I/O Scheduler Selection
      • Conclusion
  • 15 The Process Address Space
    • Address Spaces
    • The Memory Descriptor
      • Allocating a Memory Descriptor
      • Destroying a Memory Descriptor
      • The mm_struct and Kernel Threads
    • Virtual Memory Areas
      • VMA Flags
      • VMA Operations
      • Lists and Trees of Memory Areas
      • Memory Areas in Real Life
    • Manipulating Memory Areas
      • find_vma()
      • find_vma_prev()
      • find_vma_intersection()
    • Address Interval mmap() and do_mmap(): Creating an
    • Address Interval munmap() and do_munmap(): Removing an
    • Page Tables
    • Conclusion
  • 16 The Page Cache and Page Writeback Contents xvii
    • Approaches to Caching
      • Write Caching
      • Cache Eviction
        • Least Recently Used
        • The Two-List Strategy
    • The Linux Page Cache
      • The address_space Object
      • address_space Operations
      • Radix Tree
      • The Old Page Hash Table
    • The Buffer Cache
    • The Flusher Threads
      • Laptop Mode
      • History: bdflush, kupdated, and pdflush
      • Avoiding Congestion with Multiple Threads
    • Conclusion
  • 17 Devices and Modules
    • Device Types
    • Modules
      • Hello, World!
      • Building Modules
        • Living in the Source Tree
        • Living Externally
      • Installing Modules
      • Generating Module Dependencies
      • Loading Modules
      • Managing Configuration Options
      • Module Parameters
      • Exported Symbols
    • The Device Model
      • Kobjects
      • Ktypes
      • Ksets
      • Interrelation of Kobjects, Ktypes, and Ksets
      • Managing and Manipulating Kobjects
      • Reference Counts xviii Contents
        • Reference Counts Incrementing and Decrementing
        • Krefs
    • sysfs
      • Adding and Removing kobjects from sysfs
      • Adding Files to sysfs
        • Default Attributes
        • Creating New Attributes
        • Destroying Attributes
        • sysfs Conventions
      • The Kernel Events Layer
    • Conclusion
  • 18 Debugging
    • Getting Started
    • Bugs in the Kernel
    • Debugging by Printing
      • Robustness
      • Loglevels
      • The Log Buffer
      • syslogd and klogd
      • Transposing printf() and printk()
    • Oops
      • ksymoops
      • kallsyms
    • Kernel Debugging Options
    • Asserting Bugs and Dumping Information
    • Magic SysRq Key
    • The Saga of a Kernel Debugger
      • gdb
      • kgdb
    • Poking and Probing the System
      • Using UID as a Conditional
      • Using Condition Variables
      • Using Statistics
      • Rate and Occurrence Limiting Your Debugging
    • Binary Searching to Find the Culprit Change Contents xix
    • Binary Searching with Git
    • When All Else Fails: The Community
    • Conclusion
  • 19 Portability
    • Portable Operating Systems
    • History of Portability in Linux
    • Word Size and Data Types
      • Opaque Types
      • Special Types
      • Explicitly Sized Types
      • Signedness of Chars
    • Data Alignment
      • Avoiding Alignment Issues
      • Alignment of Nonstandard Types
      • Structure Padding
    • Byte Order
    • Time
    • Page Size
    • Processor Ordering
    • SMP, Kernel Preemption, and High Memory
    • Conclusion
  • 20 Patches, Hacking, and the Community
    • The Community
    • Linux Coding Style
      • Indention
      • Switch Statements
      • Spacing
      • Braces
      • Line Length
      • Naming
      • Functions
      • Comments
      • Typedefs
      • Use Existing Routines
    • Minimize ifdefs in the Source xx Contents
    • Structure Initializers
    • Fixing Up Code Ex Post Facto
  • Chain of Command
  • Submitting Bug Reports
  • Patches
    • Generating Patches
    • Generating Patches with Git
    • Submitting Patches
    • Conclusion
  • Bibliography
  • Index

and stay abreast. Robert covers the mechanics and culture of this important part of

kernel life well.

Please enjoy and learn from Robert’s book. And should you decide to take the next

step and become a member of the kernel development community, consider yourself

welcomed in advance.We value and measure people by the usefulness of their contribu-

tions, and when you contribute to Linux, you do so in the knowledge that your work is

of small but immediate benefit to tens or even hundreds of millions of human beings.

This is a most enjoyable privilege and responsibility.

Andrew Morton

Preface

When I was first approached about converting my experiences with the Linux kernel

into a book, I proceeded with trepidation.What would place my book at the top of its

subject? I was not interested unless I could do something special, a best-in-class work.

I realized that I could offer a unique approach to the topic. My job is hacking the kernel.

My hobby is hacking the kernel. My love is hacking the kernel. Over the years, I have accu-

mulated interesting anecdotes and insider tips.With my experiences, I could write a book on

how to hack the kernel and—just as important—how not to hack the kernel. First and fore-

most, this is a book about the design and implementation of the Linux kernel.This book’s

approach differs from would-be competitors, however, in that the information is given with

a slant to learning enough to actually get work done—and getting it done right. I am a

pragmatic engineer and this is a practical book. It should be fun, easy to read, and useful.

I hope that readers can walk away from this work with a better understanding of the

rules (written and unwritten) of the Linux kernel. I intend that you, fresh from reading

this book and the kernel source code, can jump in and start writing useful, correct, clean

kernel code. Of course, you can read this book just for fun, too.

That was the first edition.Time has passed, and now we return once more to the fray.

This third edition offers quite a bit over the first and second: intense polish and revision,

updates, and many fresh sections and all new chapters.This edition incorporates changes in

the kernel since the second edition. More important, however, is the decision made by the

Linux kernel community to not proceed with a 2.7 development kernel in the near to mid-

term.^1 Instead, kernel developers plan to continue developing and stabilizing the 2.6 series.

This decision has many implications, but the item of relevance to this book is that there is

quite a bit of staying power in a contemporary book on the 2.6 Linux kernel.As the Linux

kernel matures, there is a greater chance of a snapshot of the kernel remaining representative

long into the future.This book functions as the canonical documentation for the kernel,

documenting it with both an understanding of its history and an eye to the future.

Using This Book

Developing code in the kernel does not require genius, magic, or a bushy Unix-hacker

beard.The kernel, although having some interesting rules of its own, is not much differ-

ent from any other large software endeavor.You need to master many details—as with

any big project—but the differences are quantitative, not qualitative.

(^1) This decision was made in the summer of 2004 at the annual Linux Kernel Developers Summit in Ottawa, Canada. Your author was an invited attendee.